jasonfan commited on
Commit
8243ed8
·
verified ·
1 Parent(s): c7ba0e0

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. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/INSTALLER +1 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/LICENSE.txt +971 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/METADATA +1092 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/RECORD +0 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/WHEEL +6 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/entry_points.txt +10 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/__init__.py +180 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/__init__.pyi +2 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs.py +0 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs.pyi +3 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.py +389 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.pyi +16 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_asarray.py +135 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_asarray.pyi +41 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype.py +374 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype.pyi +58 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.py +120 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.pyi +83 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_exceptions.py +172 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_exceptions.pyi +73 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_internal.py +963 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_internal.pyi +72 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_machar.py +356 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_machar.pyi +73 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_methods.py +256 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_methods.pyi +24 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so +0 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so +0 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_simd.pyi +25 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_string_helpers.py +100 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_string_helpers.pyi +12 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so +0 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_type_aliases.py +119 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_type_aliases.pyi +96 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_ufunc_config.py +483 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_ufunc_config.pyi +39 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so +0 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/arrayprint.py +1756 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/arrayprint.pyi +229 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/cversions.py +13 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/defchararray.py +1414 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/defchararray.pyi +1096 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/einsumfunc.py +1499 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/einsumfunc.pyi +185 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/fromnumeric.py +0 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/fromnumeric.pyi +1733 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/function_base.py +546 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/function_base.pyi +235 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/getlimits.py +747 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/getlimits.pyi +3 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2005-2024, NumPy Developers.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are
6
+ met:
7
+
8
+ * Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ * Redistributions in binary form must reproduce the above
12
+ copyright notice, this list of conditions and the following
13
+ disclaimer in the documentation and/or other materials provided
14
+ with the distribution.
15
+
16
+ * Neither the name of the NumPy Developers nor the names of any
17
+ contributors may be used to endorse or promote products derived
18
+ from this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+
32
+ ----
33
+
34
+ The NumPy repository and source distributions bundle several libraries that are
35
+ compatibly licensed. We list these here.
36
+
37
+ Name: lapack-lite
38
+ Files: numpy/linalg/lapack_lite/*
39
+ License: BSD-3-Clause
40
+ For details, see numpy/linalg/lapack_lite/LICENSE.txt
41
+
42
+ Name: dragon4
43
+ Files: numpy/_core/src/multiarray/dragon4.c
44
+ License: MIT
45
+ For license text, see numpy/_core/src/multiarray/dragon4.c
46
+
47
+ Name: libdivide
48
+ Files: numpy/_core/include/numpy/libdivide/*
49
+ License: Zlib
50
+ For license text, see numpy/_core/include/numpy/libdivide/LICENSE.txt
51
+
52
+
53
+ Note that the following files are vendored in the repository and sdist but not
54
+ installed in built numpy packages:
55
+
56
+ Name: Meson
57
+ Files: vendored-meson/meson/*
58
+ License: Apache 2.0
59
+ For license text, see vendored-meson/meson/COPYING
60
+
61
+ Name: spin
62
+ Files: .spin/cmds.py
63
+ License: BSD-3
64
+ For license text, see .spin/LICENSE
65
+
66
+ Name: tempita
67
+ Files: numpy/_build_utils/tempita/*
68
+ License: MIT
69
+ For details, see numpy/_build_utils/tempita/LICENCE.txt
70
+
71
+ ----
72
+
73
+ This binary distribution of NumPy also bundles the following software:
74
+
75
+
76
+ Name: OpenBLAS
77
+ Files: numpy.libs/libscipy_openblas*.so
78
+ Description: bundled as a dynamically linked library
79
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
80
+ License: BSD-3-Clause
81
+ Copyright (c) 2011-2014, The OpenBLAS Project
82
+ All rights reserved.
83
+
84
+ Redistribution and use in source and binary forms, with or without
85
+ modification, are permitted provided that the following conditions are
86
+ met:
87
+
88
+ 1. Redistributions of source code must retain the above copyright
89
+ notice, this list of conditions and the following disclaimer.
90
+
91
+ 2. Redistributions in binary form must reproduce the above copyright
92
+ notice, this list of conditions and the following disclaimer in
93
+ the documentation and/or other materials provided with the
94
+ distribution.
95
+ 3. Neither the name of the OpenBLAS project nor the names of
96
+ its contributors may be used to endorse or promote products
97
+ derived from this software without specific prior written
98
+ permission.
99
+
100
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
101
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
102
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
103
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
104
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
105
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
106
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
107
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
108
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
109
+ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
110
+
111
+
112
+ Name: LAPACK
113
+ Files: numpy.libs/libscipy_openblas*.so
114
+ Description: bundled in OpenBLAS
115
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
116
+ License: BSD-3-Clause-Attribution
117
+ Copyright (c) 1992-2013 The University of Tennessee and The University
118
+ of Tennessee Research Foundation. All rights
119
+ reserved.
120
+ Copyright (c) 2000-2013 The University of California Berkeley. All
121
+ rights reserved.
122
+ Copyright (c) 2006-2013 The University of Colorado Denver. All rights
123
+ reserved.
124
+
125
+ $COPYRIGHT$
126
+
127
+ Additional copyrights may follow
128
+
129
+ $HEADER$
130
+
131
+ Redistribution and use in source and binary forms, with or without
132
+ modification, are permitted provided that the following conditions are
133
+ met:
134
+
135
+ - Redistributions of source code must retain the above copyright
136
+ notice, this list of conditions and the following disclaimer.
137
+
138
+ - Redistributions in binary form must reproduce the above copyright
139
+ notice, this list of conditions and the following disclaimer listed
140
+ in this license in the documentation and/or other materials
141
+ provided with the distribution.
142
+
143
+ - Neither the name of the copyright holders nor the names of its
144
+ contributors may be used to endorse or promote products derived from
145
+ this software without specific prior written permission.
146
+
147
+ The copyright holders provide no reassurances that the source code
148
+ provided does not infringe any patent, copyright, or any other
149
+ intellectual property rights of third parties. The copyright holders
150
+ disclaim any liability to any recipient for claims brought against
151
+ recipient by any third party for infringement of that parties
152
+ intellectual property rights.
153
+
154
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
155
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
156
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
157
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
158
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
159
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
160
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
161
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
162
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
163
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
164
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
165
+
166
+
167
+ Name: GCC runtime library
168
+ Files: numpy.libs/libgfortran*.so
169
+ Description: dynamically linked to files compiled with gcc
170
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran
171
+ License: GPL-3.0-with-GCC-exception
172
+ Copyright (C) 2002-2017 Free Software Foundation, Inc.
173
+
174
+ Libgfortran is free software; you can redistribute it and/or modify
175
+ it under the terms of the GNU General Public License as published by
176
+ the Free Software Foundation; either version 3, or (at your option)
177
+ any later version.
178
+
179
+ Libgfortran is distributed in the hope that it will be useful,
180
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
181
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
182
+ GNU General Public License for more details.
183
+
184
+ Under Section 7 of GPL version 3, you are granted additional
185
+ permissions described in the GCC Runtime Library Exception, version
186
+ 3.1, as published by the Free Software Foundation.
187
+
188
+ You should have received a copy of the GNU General Public License and
189
+ a copy of the GCC Runtime Library Exception along with this program;
190
+ see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
191
+ <http://www.gnu.org/licenses/>.
192
+
193
+ ----
194
+
195
+ Full text of license texts referred to above follows (that they are
196
+ listed below does not necessarily imply the conditions apply to the
197
+ present binary release):
198
+
199
+ ----
200
+
201
+ GCC RUNTIME LIBRARY EXCEPTION
202
+
203
+ Version 3.1, 31 March 2009
204
+
205
+ Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
206
+
207
+ Everyone is permitted to copy and distribute verbatim copies of this
208
+ license document, but changing it is not allowed.
209
+
210
+ This GCC Runtime Library Exception ("Exception") is an additional
211
+ permission under section 7 of the GNU General Public License, version
212
+ 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that
213
+ bears a notice placed by the copyright holder of the file stating that
214
+ the file is governed by GPLv3 along with this Exception.
215
+
216
+ When you use GCC to compile a program, GCC may combine portions of
217
+ certain GCC header files and runtime libraries with the compiled
218
+ program. The purpose of this Exception is to allow compilation of
219
+ non-GPL (including proprietary) programs to use, in this way, the
220
+ header files and runtime libraries covered by this Exception.
221
+
222
+ 0. Definitions.
223
+
224
+ A file is an "Independent Module" if it either requires the Runtime
225
+ Library for execution after a Compilation Process, or makes use of an
226
+ interface provided by the Runtime Library, but is not otherwise based
227
+ on the Runtime Library.
228
+
229
+ "GCC" means a version of the GNU Compiler Collection, with or without
230
+ modifications, governed by version 3 (or a specified later version) of
231
+ the GNU General Public License (GPL) with the option of using any
232
+ subsequent versions published by the FSF.
233
+
234
+ "GPL-compatible Software" is software whose conditions of propagation,
235
+ modification and use would permit combination with GCC in accord with
236
+ the license of GCC.
237
+
238
+ "Target Code" refers to output from any compiler for a real or virtual
239
+ target processor architecture, in executable form or suitable for
240
+ input to an assembler, loader, linker and/or execution
241
+ phase. Notwithstanding that, Target Code does not include data in any
242
+ format that is used as a compiler intermediate representation, or used
243
+ for producing a compiler intermediate representation.
244
+
245
+ The "Compilation Process" transforms code entirely represented in
246
+ non-intermediate languages designed for human-written code, and/or in
247
+ Java Virtual Machine byte code, into Target Code. Thus, for example,
248
+ use of source code generators and preprocessors need not be considered
249
+ part of the Compilation Process, since the Compilation Process can be
250
+ understood as starting with the output of the generators or
251
+ preprocessors.
252
+
253
+ A Compilation Process is "Eligible" if it is done using GCC, alone or
254
+ with other GPL-compatible software, or if it is done without using any
255
+ work based on GCC. For example, using non-GPL-compatible Software to
256
+ optimize any GCC intermediate representations would not qualify as an
257
+ Eligible Compilation Process.
258
+
259
+ 1. Grant of Additional Permission.
260
+
261
+ You have permission to propagate a work of Target Code formed by
262
+ combining the Runtime Library with Independent Modules, even if such
263
+ propagation would otherwise violate the terms of GPLv3, provided that
264
+ all Target Code was generated by Eligible Compilation Processes. You
265
+ may then convey such a combination under terms of your choice,
266
+ consistent with the licensing of the Independent Modules.
267
+
268
+ 2. No Weakening of GCC Copyleft.
269
+
270
+ The availability of this Exception does not imply any general
271
+ presumption that third-party software is unaffected by the copyleft
272
+ requirements of the license of GCC.
273
+
274
+ ----
275
+
276
+ GNU GENERAL PUBLIC LICENSE
277
+ Version 3, 29 June 2007
278
+
279
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
280
+ Everyone is permitted to copy and distribute verbatim copies
281
+ of this license document, but changing it is not allowed.
282
+
283
+ Preamble
284
+
285
+ The GNU General Public License is a free, copyleft license for
286
+ software and other kinds of works.
287
+
288
+ The licenses for most software and other practical works are designed
289
+ to take away your freedom to share and change the works. By contrast,
290
+ the GNU General Public License is intended to guarantee your freedom to
291
+ share and change all versions of a program--to make sure it remains free
292
+ software for all its users. We, the Free Software Foundation, use the
293
+ GNU General Public License for most of our software; it applies also to
294
+ any other work released this way by its authors. You can apply it to
295
+ your programs, too.
296
+
297
+ When we speak of free software, we are referring to freedom, not
298
+ price. Our General Public Licenses are designed to make sure that you
299
+ have the freedom to distribute copies of free software (and charge for
300
+ them if you wish), that you receive source code or can get it if you
301
+ want it, that you can change the software or use pieces of it in new
302
+ free programs, and that you know you can do these things.
303
+
304
+ To protect your rights, we need to prevent others from denying you
305
+ these rights or asking you to surrender the rights. Therefore, you have
306
+ certain responsibilities if you distribute copies of the software, or if
307
+ you modify it: responsibilities to respect the freedom of others.
308
+
309
+ For example, if you distribute copies of such a program, whether
310
+ gratis or for a fee, you must pass on to the recipients the same
311
+ freedoms that you received. You must make sure that they, too, receive
312
+ or can get the source code. And you must show them these terms so they
313
+ know their rights.
314
+
315
+ Developers that use the GNU GPL protect your rights with two steps:
316
+ (1) assert copyright on the software, and (2) offer you this License
317
+ giving you legal permission to copy, distribute and/or modify it.
318
+
319
+ For the developers' and authors' protection, the GPL clearly explains
320
+ that there is no warranty for this free software. For both users' and
321
+ authors' sake, the GPL requires that modified versions be marked as
322
+ changed, so that their problems will not be attributed erroneously to
323
+ authors of previous versions.
324
+
325
+ Some devices are designed to deny users access to install or run
326
+ modified versions of the software inside them, although the manufacturer
327
+ can do so. This is fundamentally incompatible with the aim of
328
+ protecting users' freedom to change the software. The systematic
329
+ pattern of such abuse occurs in the area of products for individuals to
330
+ use, which is precisely where it is most unacceptable. Therefore, we
331
+ have designed this version of the GPL to prohibit the practice for those
332
+ products. If such problems arise substantially in other domains, we
333
+ stand ready to extend this provision to those domains in future versions
334
+ of the GPL, as needed to protect the freedom of users.
335
+
336
+ Finally, every program is threatened constantly by software patents.
337
+ States should not allow patents to restrict development and use of
338
+ software on general-purpose computers, but in those that do, we wish to
339
+ avoid the special danger that patents applied to a free program could
340
+ make it effectively proprietary. To prevent this, the GPL assures that
341
+ patents cannot be used to render the program non-free.
342
+
343
+ The precise terms and conditions for copying, distribution and
344
+ modification follow.
345
+
346
+ TERMS AND CONDITIONS
347
+
348
+ 0. Definitions.
349
+
350
+ "This License" refers to version 3 of the GNU General Public License.
351
+
352
+ "Copyright" also means copyright-like laws that apply to other kinds of
353
+ works, such as semiconductor masks.
354
+
355
+ "The Program" refers to any copyrightable work licensed under this
356
+ License. Each licensee is addressed as "you". "Licensees" and
357
+ "recipients" may be individuals or organizations.
358
+
359
+ To "modify" a work means to copy from or adapt all or part of the work
360
+ in a fashion requiring copyright permission, other than the making of an
361
+ exact copy. The resulting work is called a "modified version" of the
362
+ earlier work or a work "based on" the earlier work.
363
+
364
+ A "covered work" means either the unmodified Program or a work based
365
+ on the Program.
366
+
367
+ To "propagate" a work means to do anything with it that, without
368
+ permission, would make you directly or secondarily liable for
369
+ infringement under applicable copyright law, except executing it on a
370
+ computer or modifying a private copy. Propagation includes copying,
371
+ distribution (with or without modification), making available to the
372
+ public, and in some countries other activities as well.
373
+
374
+ To "convey" a work means any kind of propagation that enables other
375
+ parties to make or receive copies. Mere interaction with a user through
376
+ a computer network, with no transfer of a copy, is not conveying.
377
+
378
+ An interactive user interface displays "Appropriate Legal Notices"
379
+ to the extent that it includes a convenient and prominently visible
380
+ feature that (1) displays an appropriate copyright notice, and (2)
381
+ tells the user that there is no warranty for the work (except to the
382
+ extent that warranties are provided), that licensees may convey the
383
+ work under this License, and how to view a copy of this License. If
384
+ the interface presents a list of user commands or options, such as a
385
+ menu, a prominent item in the list meets this criterion.
386
+
387
+ 1. Source Code.
388
+
389
+ The "source code" for a work means the preferred form of the work
390
+ for making modifications to it. "Object code" means any non-source
391
+ form of a work.
392
+
393
+ A "Standard Interface" means an interface that either is an official
394
+ standard defined by a recognized standards body, or, in the case of
395
+ interfaces specified for a particular programming language, one that
396
+ is widely used among developers working in that language.
397
+
398
+ The "System Libraries" of an executable work include anything, other
399
+ than the work as a whole, that (a) is included in the normal form of
400
+ packaging a Major Component, but which is not part of that Major
401
+ Component, and (b) serves only to enable use of the work with that
402
+ Major Component, or to implement a Standard Interface for which an
403
+ implementation is available to the public in source code form. A
404
+ "Major Component", in this context, means a major essential component
405
+ (kernel, window system, and so on) of the specific operating system
406
+ (if any) on which the executable work runs, or a compiler used to
407
+ produce the work, or an object code interpreter used to run it.
408
+
409
+ The "Corresponding Source" for a work in object code form means all
410
+ the source code needed to generate, install, and (for an executable
411
+ work) run the object code and to modify the work, including scripts to
412
+ control those activities. However, it does not include the work's
413
+ System Libraries, or general-purpose tools or generally available free
414
+ programs which are used unmodified in performing those activities but
415
+ which are not part of the work. For example, Corresponding Source
416
+ includes interface definition files associated with source files for
417
+ the work, and the source code for shared libraries and dynamically
418
+ linked subprograms that the work is specifically designed to require,
419
+ such as by intimate data communication or control flow between those
420
+ subprograms and other parts of the work.
421
+
422
+ The Corresponding Source need not include anything that users
423
+ can regenerate automatically from other parts of the Corresponding
424
+ Source.
425
+
426
+ The Corresponding Source for a work in source code form is that
427
+ same work.
428
+
429
+ 2. Basic Permissions.
430
+
431
+ All rights granted under this License are granted for the term of
432
+ copyright on the Program, and are irrevocable provided the stated
433
+ conditions are met. This License explicitly affirms your unlimited
434
+ permission to run the unmodified Program. The output from running a
435
+ covered work is covered by this License only if the output, given its
436
+ content, constitutes a covered work. This License acknowledges your
437
+ rights of fair use or other equivalent, as provided by copyright law.
438
+
439
+ You may make, run and propagate covered works that you do not
440
+ convey, without conditions so long as your license otherwise remains
441
+ in force. You may convey covered works to others for the sole purpose
442
+ of having them make modifications exclusively for you, or provide you
443
+ with facilities for running those works, provided that you comply with
444
+ the terms of this License in conveying all material for which you do
445
+ not control copyright. Those thus making or running the covered works
446
+ for you must do so exclusively on your behalf, under your direction
447
+ and control, on terms that prohibit them from making any copies of
448
+ your copyrighted material outside their relationship with you.
449
+
450
+ Conveying under any other circumstances is permitted solely under
451
+ the conditions stated below. Sublicensing is not allowed; section 10
452
+ makes it unnecessary.
453
+
454
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
455
+
456
+ No covered work shall be deemed part of an effective technological
457
+ measure under any applicable law fulfilling obligations under article
458
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
459
+ similar laws prohibiting or restricting circumvention of such
460
+ measures.
461
+
462
+ When you convey a covered work, you waive any legal power to forbid
463
+ circumvention of technological measures to the extent such circumvention
464
+ is effected by exercising rights under this License with respect to
465
+ the covered work, and you disclaim any intention to limit operation or
466
+ modification of the work as a means of enforcing, against the work's
467
+ users, your or third parties' legal rights to forbid circumvention of
468
+ technological measures.
469
+
470
+ 4. Conveying Verbatim Copies.
471
+
472
+ You may convey verbatim copies of the Program's source code as you
473
+ receive it, in any medium, provided that you conspicuously and
474
+ appropriately publish on each copy an appropriate copyright notice;
475
+ keep intact all notices stating that this License and any
476
+ non-permissive terms added in accord with section 7 apply to the code;
477
+ keep intact all notices of the absence of any warranty; and give all
478
+ recipients a copy of this License along with the Program.
479
+
480
+ You may charge any price or no price for each copy that you convey,
481
+ and you may offer support or warranty protection for a fee.
482
+
483
+ 5. Conveying Modified Source Versions.
484
+
485
+ You may convey a work based on the Program, or the modifications to
486
+ produce it from the Program, in the form of source code under the
487
+ terms of section 4, provided that you also meet all of these conditions:
488
+
489
+ a) The work must carry prominent notices stating that you modified
490
+ it, and giving a relevant date.
491
+
492
+ b) The work must carry prominent notices stating that it is
493
+ released under this License and any conditions added under section
494
+ 7. This requirement modifies the requirement in section 4 to
495
+ "keep intact all notices".
496
+
497
+ c) You must license the entire work, as a whole, under this
498
+ License to anyone who comes into possession of a copy. This
499
+ License will therefore apply, along with any applicable section 7
500
+ additional terms, to the whole of the work, and all its parts,
501
+ regardless of how they are packaged. This License gives no
502
+ permission to license the work in any other way, but it does not
503
+ invalidate such permission if you have separately received it.
504
+
505
+ d) If the work has interactive user interfaces, each must display
506
+ Appropriate Legal Notices; however, if the Program has interactive
507
+ interfaces that do not display Appropriate Legal Notices, your
508
+ work need not make them do so.
509
+
510
+ A compilation of a covered work with other separate and independent
511
+ works, which are not by their nature extensions of the covered work,
512
+ and which are not combined with it such as to form a larger program,
513
+ in or on a volume of a storage or distribution medium, is called an
514
+ "aggregate" if the compilation and its resulting copyright are not
515
+ used to limit the access or legal rights of the compilation's users
516
+ beyond what the individual works permit. Inclusion of a covered work
517
+ in an aggregate does not cause this License to apply to the other
518
+ parts of the aggregate.
519
+
520
+ 6. Conveying Non-Source Forms.
521
+
522
+ You may convey a covered work in object code form under the terms
523
+ of sections 4 and 5, provided that you also convey the
524
+ machine-readable Corresponding Source under the terms of this License,
525
+ in one of these ways:
526
+
527
+ a) Convey the object code in, or embodied in, a physical product
528
+ (including a physical distribution medium), accompanied by the
529
+ Corresponding Source fixed on a durable physical medium
530
+ customarily used for software interchange.
531
+
532
+ b) Convey the object code in, or embodied in, a physical product
533
+ (including a physical distribution medium), accompanied by a
534
+ written offer, valid for at least three years and valid for as
535
+ long as you offer spare parts or customer support for that product
536
+ model, to give anyone who possesses the object code either (1) a
537
+ copy of the Corresponding Source for all the software in the
538
+ product that is covered by this License, on a durable physical
539
+ medium customarily used for software interchange, for a price no
540
+ more than your reasonable cost of physically performing this
541
+ conveying of source, or (2) access to copy the
542
+ Corresponding Source from a network server at no charge.
543
+
544
+ c) Convey individual copies of the object code with a copy of the
545
+ written offer to provide the Corresponding Source. This
546
+ alternative is allowed only occasionally and noncommercially, and
547
+ only if you received the object code with such an offer, in accord
548
+ with subsection 6b.
549
+
550
+ d) Convey the object code by offering access from a designated
551
+ place (gratis or for a charge), and offer equivalent access to the
552
+ Corresponding Source in the same way through the same place at no
553
+ further charge. You need not require recipients to copy the
554
+ Corresponding Source along with the object code. If the place to
555
+ copy the object code is a network server, the Corresponding Source
556
+ may be on a different server (operated by you or a third party)
557
+ that supports equivalent copying facilities, provided you maintain
558
+ clear directions next to the object code saying where to find the
559
+ Corresponding Source. Regardless of what server hosts the
560
+ Corresponding Source, you remain obligated to ensure that it is
561
+ available for as long as needed to satisfy these requirements.
562
+
563
+ e) Convey the object code using peer-to-peer transmission, provided
564
+ you inform other peers where the object code and Corresponding
565
+ Source of the work are being offered to the general public at no
566
+ charge under subsection 6d.
567
+
568
+ A separable portion of the object code, whose source code is excluded
569
+ from the Corresponding Source as a System Library, need not be
570
+ included in conveying the object code work.
571
+
572
+ A "User Product" is either (1) a "consumer product", which means any
573
+ tangible personal property which is normally used for personal, family,
574
+ or household purposes, or (2) anything designed or sold for incorporation
575
+ into a dwelling. In determining whether a product is a consumer product,
576
+ doubtful cases shall be resolved in favor of coverage. For a particular
577
+ product received by a particular user, "normally used" refers to a
578
+ typical or common use of that class of product, regardless of the status
579
+ of the particular user or of the way in which the particular user
580
+ actually uses, or expects or is expected to use, the product. A product
581
+ is a consumer product regardless of whether the product has substantial
582
+ commercial, industrial or non-consumer uses, unless such uses represent
583
+ the only significant mode of use of the product.
584
+
585
+ "Installation Information" for a User Product means any methods,
586
+ procedures, authorization keys, or other information required to install
587
+ and execute modified versions of a covered work in that User Product from
588
+ a modified version of its Corresponding Source. The information must
589
+ suffice to ensure that the continued functioning of the modified object
590
+ code is in no case prevented or interfered with solely because
591
+ modification has been made.
592
+
593
+ If you convey an object code work under this section in, or with, or
594
+ specifically for use in, a User Product, and the conveying occurs as
595
+ part of a transaction in which the right of possession and use of the
596
+ User Product is transferred to the recipient in perpetuity or for a
597
+ fixed term (regardless of how the transaction is characterized), the
598
+ Corresponding Source conveyed under this section must be accompanied
599
+ by the Installation Information. But this requirement does not apply
600
+ if neither you nor any third party retains the ability to install
601
+ modified object code on the User Product (for example, the work has
602
+ been installed in ROM).
603
+
604
+ The requirement to provide Installation Information does not include a
605
+ requirement to continue to provide support service, warranty, or updates
606
+ for a work that has been modified or installed by the recipient, or for
607
+ the User Product in which it has been modified or installed. Access to a
608
+ network may be denied when the modification itself materially and
609
+ adversely affects the operation of the network or violates the rules and
610
+ protocols for communication across the network.
611
+
612
+ Corresponding Source conveyed, and Installation Information provided,
613
+ in accord with this section must be in a format that is publicly
614
+ documented (and with an implementation available to the public in
615
+ source code form), and must require no special password or key for
616
+ unpacking, reading or copying.
617
+
618
+ 7. Additional Terms.
619
+
620
+ "Additional permissions" are terms that supplement the terms of this
621
+ License by making exceptions from one or more of its conditions.
622
+ Additional permissions that are applicable to the entire Program shall
623
+ be treated as though they were included in this License, to the extent
624
+ that they are valid under applicable law. If additional permissions
625
+ apply only to part of the Program, that part may be used separately
626
+ under those permissions, but the entire Program remains governed by
627
+ this License without regard to the additional permissions.
628
+
629
+ When you convey a copy of a covered work, you may at your option
630
+ remove any additional permissions from that copy, or from any part of
631
+ it. (Additional permissions may be written to require their own
632
+ removal in certain cases when you modify the work.) You may place
633
+ additional permissions on material, added by you to a covered work,
634
+ for which you have or can give appropriate copyright permission.
635
+
636
+ Notwithstanding any other provision of this License, for material you
637
+ add to a covered work, you may (if authorized by the copyright holders of
638
+ that material) supplement the terms of this License with terms:
639
+
640
+ a) Disclaiming warranty or limiting liability differently from the
641
+ terms of sections 15 and 16 of this License; or
642
+
643
+ b) Requiring preservation of specified reasonable legal notices or
644
+ author attributions in that material or in the Appropriate Legal
645
+ Notices displayed by works containing it; or
646
+
647
+ c) Prohibiting misrepresentation of the origin of that material, or
648
+ requiring that modified versions of such material be marked in
649
+ reasonable ways as different from the original version; or
650
+
651
+ d) Limiting the use for publicity purposes of names of licensors or
652
+ authors of the material; or
653
+
654
+ e) Declining to grant rights under trademark law for use of some
655
+ trade names, trademarks, or service marks; or
656
+
657
+ f) Requiring indemnification of licensors and authors of that
658
+ material by anyone who conveys the material (or modified versions of
659
+ it) with contractual assumptions of liability to the recipient, for
660
+ any liability that these contractual assumptions directly impose on
661
+ those licensors and authors.
662
+
663
+ All other non-permissive additional terms are considered "further
664
+ restrictions" within the meaning of section 10. If the Program as you
665
+ received it, or any part of it, contains a notice stating that it is
666
+ governed by this License along with a term that is a further
667
+ restriction, you may remove that term. If a license document contains
668
+ a further restriction but permits relicensing or conveying under this
669
+ License, you may add to a covered work material governed by the terms
670
+ of that license document, provided that the further restriction does
671
+ not survive such relicensing or conveying.
672
+
673
+ If you add terms to a covered work in accord with this section, you
674
+ must place, in the relevant source files, a statement of the
675
+ additional terms that apply to those files, or a notice indicating
676
+ where to find the applicable terms.
677
+
678
+ Additional terms, permissive or non-permissive, may be stated in the
679
+ form of a separately written license, or stated as exceptions;
680
+ the above requirements apply either way.
681
+
682
+ 8. Termination.
683
+
684
+ You may not propagate or modify a covered work except as expressly
685
+ provided under this License. Any attempt otherwise to propagate or
686
+ modify it is void, and will automatically terminate your rights under
687
+ this License (including any patent licenses granted under the third
688
+ paragraph of section 11).
689
+
690
+ However, if you cease all violation of this License, then your
691
+ license from a particular copyright holder is reinstated (a)
692
+ provisionally, unless and until the copyright holder explicitly and
693
+ finally terminates your license, and (b) permanently, if the copyright
694
+ holder fails to notify you of the violation by some reasonable means
695
+ prior to 60 days after the cessation.
696
+
697
+ Moreover, your license from a particular copyright holder is
698
+ reinstated permanently if the copyright holder notifies you of the
699
+ violation by some reasonable means, this is the first time you have
700
+ received notice of violation of this License (for any work) from that
701
+ copyright holder, and you cure the violation prior to 30 days after
702
+ your receipt of the notice.
703
+
704
+ Termination of your rights under this section does not terminate the
705
+ licenses of parties who have received copies or rights from you under
706
+ this License. If your rights have been terminated and not permanently
707
+ reinstated, you do not qualify to receive new licenses for the same
708
+ material under section 10.
709
+
710
+ 9. Acceptance Not Required for Having Copies.
711
+
712
+ You are not required to accept this License in order to receive or
713
+ run a copy of the Program. Ancillary propagation of a covered work
714
+ occurring solely as a consequence of using peer-to-peer transmission
715
+ to receive a copy likewise does not require acceptance. However,
716
+ nothing other than this License grants you permission to propagate or
717
+ modify any covered work. These actions infringe copyright if you do
718
+ not accept this License. Therefore, by modifying or propagating a
719
+ covered work, you indicate your acceptance of this License to do so.
720
+
721
+ 10. Automatic Licensing of Downstream Recipients.
722
+
723
+ Each time you convey a covered work, the recipient automatically
724
+ receives a license from the original licensors, to run, modify and
725
+ propagate that work, subject to this License. You are not responsible
726
+ for enforcing compliance by third parties with this License.
727
+
728
+ An "entity transaction" is a transaction transferring control of an
729
+ organization, or substantially all assets of one, or subdividing an
730
+ organization, or merging organizations. If propagation of a covered
731
+ work results from an entity transaction, each party to that
732
+ transaction who receives a copy of the work also receives whatever
733
+ licenses to the work the party's predecessor in interest had or could
734
+ give under the previous paragraph, plus a right to possession of the
735
+ Corresponding Source of the work from the predecessor in interest, if
736
+ the predecessor has it or can get it with reasonable efforts.
737
+
738
+ You may not impose any further restrictions on the exercise of the
739
+ rights granted or affirmed under this License. For example, you may
740
+ not impose a license fee, royalty, or other charge for exercise of
741
+ rights granted under this License, and you may not initiate litigation
742
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
743
+ any patent claim is infringed by making, using, selling, offering for
744
+ sale, or importing the Program or any portion of it.
745
+
746
+ 11. Patents.
747
+
748
+ A "contributor" is a copyright holder who authorizes use under this
749
+ License of the Program or a work on which the Program is based. The
750
+ work thus licensed is called the contributor's "contributor version".
751
+
752
+ A contributor's "essential patent claims" are all patent claims
753
+ owned or controlled by the contributor, whether already acquired or
754
+ hereafter acquired, that would be infringed by some manner, permitted
755
+ by this License, of making, using, or selling its contributor version,
756
+ but do not include claims that would be infringed only as a
757
+ consequence of further modification of the contributor version. For
758
+ purposes of this definition, "control" includes the right to grant
759
+ patent sublicenses in a manner consistent with the requirements of
760
+ this License.
761
+
762
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
763
+ patent license under the contributor's essential patent claims, to
764
+ make, use, sell, offer for sale, import and otherwise run, modify and
765
+ propagate the contents of its contributor version.
766
+
767
+ In the following three paragraphs, a "patent license" is any express
768
+ agreement or commitment, however denominated, not to enforce a patent
769
+ (such as an express permission to practice a patent or covenant not to
770
+ sue for patent infringement). To "grant" such a patent license to a
771
+ party means to make such an agreement or commitment not to enforce a
772
+ patent against the party.
773
+
774
+ If you convey a covered work, knowingly relying on a patent license,
775
+ and the Corresponding Source of the work is not available for anyone
776
+ to copy, free of charge and under the terms of this License, through a
777
+ publicly available network server or other readily accessible means,
778
+ then you must either (1) cause the Corresponding Source to be so
779
+ available, or (2) arrange to deprive yourself of the benefit of the
780
+ patent license for this particular work, or (3) arrange, in a manner
781
+ consistent with the requirements of this License, to extend the patent
782
+ license to downstream recipients. "Knowingly relying" means you have
783
+ actual knowledge that, but for the patent license, your conveying the
784
+ covered work in a country, or your recipient's use of the covered work
785
+ in a country, would infringe one or more identifiable patents in that
786
+ country that you have reason to believe are valid.
787
+
788
+ If, pursuant to or in connection with a single transaction or
789
+ arrangement, you convey, or propagate by procuring conveyance of, a
790
+ covered work, and grant a patent license to some of the parties
791
+ receiving the covered work authorizing them to use, propagate, modify
792
+ or convey a specific copy of the covered work, then the patent license
793
+ you grant is automatically extended to all recipients of the covered
794
+ work and works based on it.
795
+
796
+ A patent license is "discriminatory" if it does not include within
797
+ the scope of its coverage, prohibits the exercise of, or is
798
+ conditioned on the non-exercise of one or more of the rights that are
799
+ specifically granted under this License. You may not convey a covered
800
+ work if you are a party to an arrangement with a third party that is
801
+ in the business of distributing software, under which you make payment
802
+ to the third party based on the extent of your activity of conveying
803
+ the work, and under which the third party grants, to any of the
804
+ parties who would receive the covered work from you, a discriminatory
805
+ patent license (a) in connection with copies of the covered work
806
+ conveyed by you (or copies made from those copies), or (b) primarily
807
+ for and in connection with specific products or compilations that
808
+ contain the covered work, unless you entered into that arrangement,
809
+ or that patent license was granted, prior to 28 March 2007.
810
+
811
+ Nothing in this License shall be construed as excluding or limiting
812
+ any implied license or other defenses to infringement that may
813
+ otherwise be available to you under applicable patent law.
814
+
815
+ 12. No Surrender of Others' Freedom.
816
+
817
+ If conditions are imposed on you (whether by court order, agreement or
818
+ otherwise) that contradict the conditions of this License, they do not
819
+ excuse you from the conditions of this License. If you cannot convey a
820
+ covered work so as to satisfy simultaneously your obligations under this
821
+ License and any other pertinent obligations, then as a consequence you may
822
+ not convey it at all. For example, if you agree to terms that obligate you
823
+ to collect a royalty for further conveying from those to whom you convey
824
+ the Program, the only way you could satisfy both those terms and this
825
+ License would be to refrain entirely from conveying the Program.
826
+
827
+ 13. Use with the GNU Affero General Public License.
828
+
829
+ Notwithstanding any other provision of this License, you have
830
+ permission to link or combine any covered work with a work licensed
831
+ under version 3 of the GNU Affero General Public License into a single
832
+ combined work, and to convey the resulting work. The terms of this
833
+ License will continue to apply to the part which is the covered work,
834
+ but the special requirements of the GNU Affero General Public License,
835
+ section 13, concerning interaction through a network will apply to the
836
+ combination as such.
837
+
838
+ 14. Revised Versions of this License.
839
+
840
+ The Free Software Foundation may publish revised and/or new versions of
841
+ the GNU General Public License from time to time. Such new versions will
842
+ be similar in spirit to the present version, but may differ in detail to
843
+ address new problems or concerns.
844
+
845
+ Each version is given a distinguishing version number. If the
846
+ Program specifies that a certain numbered version of the GNU General
847
+ Public License "or any later version" applies to it, you have the
848
+ option of following the terms and conditions either of that numbered
849
+ version or of any later version published by the Free Software
850
+ Foundation. If the Program does not specify a version number of the
851
+ GNU General Public License, you may choose any version ever published
852
+ by the Free Software Foundation.
853
+
854
+ If the Program specifies that a proxy can decide which future
855
+ versions of the GNU General Public License can be used, that proxy's
856
+ public statement of acceptance of a version permanently authorizes you
857
+ to choose that version for the Program.
858
+
859
+ Later license versions may give you additional or different
860
+ permissions. However, no additional obligations are imposed on any
861
+ author or copyright holder as a result of your choosing to follow a
862
+ later version.
863
+
864
+ 15. Disclaimer of Warranty.
865
+
866
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
867
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
868
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
869
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
870
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
871
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
872
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
873
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
874
+
875
+ 16. Limitation of Liability.
876
+
877
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
878
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
879
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
880
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
881
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
882
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
883
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
884
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
885
+ SUCH DAMAGES.
886
+
887
+ 17. Interpretation of Sections 15 and 16.
888
+
889
+ If the disclaimer of warranty and limitation of liability provided
890
+ above cannot be given local legal effect according to their terms,
891
+ reviewing courts shall apply local law that most closely approximates
892
+ an absolute waiver of all civil liability in connection with the
893
+ Program, unless a warranty or assumption of liability accompanies a
894
+ copy of the Program in return for a fee.
895
+
896
+ END OF TERMS AND CONDITIONS
897
+
898
+ How to Apply These Terms to Your New Programs
899
+
900
+ If you develop a new program, and you want it to be of the greatest
901
+ possible use to the public, the best way to achieve this is to make it
902
+ free software which everyone can redistribute and change under these terms.
903
+
904
+ To do so, attach the following notices to the program. It is safest
905
+ to attach them to the start of each source file to most effectively
906
+ state the exclusion of warranty; and each file should have at least
907
+ the "copyright" line and a pointer to where the full notice is found.
908
+
909
+ <one line to give the program's name and a brief idea of what it does.>
910
+ Copyright (C) <year> <name of author>
911
+
912
+ This program is free software: you can redistribute it and/or modify
913
+ it under the terms of the GNU General Public License as published by
914
+ the Free Software Foundation, either version 3 of the License, or
915
+ (at your option) any later version.
916
+
917
+ This program is distributed in the hope that it will be useful,
918
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
919
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
920
+ GNU General Public License for more details.
921
+
922
+ You should have received a copy of the GNU General Public License
923
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
924
+
925
+ Also add information on how to contact you by electronic and paper mail.
926
+
927
+ If the program does terminal interaction, make it output a short
928
+ notice like this when it starts in an interactive mode:
929
+
930
+ <program> Copyright (C) <year> <name of author>
931
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
932
+ This is free software, and you are welcome to redistribute it
933
+ under certain conditions; type `show c' for details.
934
+
935
+ The hypothetical commands `show w' and `show c' should show the appropriate
936
+ parts of the General Public License. Of course, your program's commands
937
+ might be different; for a GUI interface, you would use an "about box".
938
+
939
+ You should also get your employer (if you work as a programmer) or school,
940
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
941
+ For more information on this, and how to apply and follow the GNU GPL, see
942
+ <http://www.gnu.org/licenses/>.
943
+
944
+ The GNU General Public License does not permit incorporating your program
945
+ into proprietary programs. If your program is a subroutine library, you
946
+ may consider it more useful to permit linking proprietary applications with
947
+ the library. If this is what you want to do, use the GNU Lesser General
948
+ Public License instead of this License. But first, please read
949
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
950
+
951
+ Name: libquadmath
952
+ Files: numpy.libs/libquadmath*.so
953
+ Description: dynamically linked to files compiled with gcc
954
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath
955
+ License: LGPL-2.1-or-later
956
+
957
+ GCC Quad-Precision Math Library
958
+ Copyright (C) 2010-2019 Free Software Foundation, Inc.
959
+ Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org>
960
+
961
+ This file is part of the libquadmath library.
962
+ Libquadmath is free software; you can redistribute it and/or
963
+ modify it under the terms of the GNU Library General Public
964
+ License as published by the Free Software Foundation; either
965
+ version 2.1 of the License, or (at your option) any later version.
966
+
967
+ Libquadmath is distributed in the hope that it will be useful,
968
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
969
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
970
+ Lesser General Public License for more details.
971
+ https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/METADATA ADDED
@@ -0,0 +1,1092 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: numpy
3
+ Version: 2.2.6
4
+ Summary: Fundamental package for array computing in Python
5
+ Author: Travis E. Oliphant et al.
6
+ Maintainer-Email: NumPy Developers <numpy-discussion@python.org>
7
+ License: Copyright (c) 2005-2024, NumPy Developers.
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
12
+ met:
13
+
14
+ * Redistributions of source code must retain the above copyright
15
+ notice, this list of conditions and the following disclaimer.
16
+
17
+ * Redistributions in binary form must reproduce the above
18
+ copyright notice, this list of conditions and the following
19
+ disclaimer in the documentation and/or other materials provided
20
+ with the distribution.
21
+
22
+ * Neither the name of the NumPy Developers nor the names of any
23
+ contributors may be used to endorse or promote products derived
24
+ from this software without specific prior written permission.
25
+
26
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+
38
+ ----
39
+
40
+ The NumPy repository and source distributions bundle several libraries that are
41
+ compatibly licensed. We list these here.
42
+
43
+ Name: lapack-lite
44
+ Files: numpy/linalg/lapack_lite/*
45
+ License: BSD-3-Clause
46
+ For details, see numpy/linalg/lapack_lite/LICENSE.txt
47
+
48
+ Name: dragon4
49
+ Files: numpy/_core/src/multiarray/dragon4.c
50
+ License: MIT
51
+ For license text, see numpy/_core/src/multiarray/dragon4.c
52
+
53
+ Name: libdivide
54
+ Files: numpy/_core/include/numpy/libdivide/*
55
+ License: Zlib
56
+ For license text, see numpy/_core/include/numpy/libdivide/LICENSE.txt
57
+
58
+
59
+ Note that the following files are vendored in the repository and sdist but not
60
+ installed in built numpy packages:
61
+
62
+ Name: Meson
63
+ Files: vendored-meson/meson/*
64
+ License: Apache 2.0
65
+ For license text, see vendored-meson/meson/COPYING
66
+
67
+ Name: spin
68
+ Files: .spin/cmds.py
69
+ License: BSD-3
70
+ For license text, see .spin/LICENSE
71
+
72
+ Name: tempita
73
+ Files: numpy/_build_utils/tempita/*
74
+ License: MIT
75
+ For details, see numpy/_build_utils/tempita/LICENCE.txt
76
+
77
+ ----
78
+
79
+ This binary distribution of NumPy also bundles the following software:
80
+
81
+
82
+ Name: OpenBLAS
83
+ Files: numpy.libs/libscipy_openblas*.so
84
+ Description: bundled as a dynamically linked library
85
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
86
+ License: BSD-3-Clause
87
+ Copyright (c) 2011-2014, The OpenBLAS Project
88
+ All rights reserved.
89
+
90
+ Redistribution and use in source and binary forms, with or without
91
+ modification, are permitted provided that the following conditions are
92
+ met:
93
+
94
+ 1. Redistributions of source code must retain the above copyright
95
+ notice, this list of conditions and the following disclaimer.
96
+
97
+ 2. Redistributions in binary form must reproduce the above copyright
98
+ notice, this list of conditions and the following disclaimer in
99
+ the documentation and/or other materials provided with the
100
+ distribution.
101
+ 3. Neither the name of the OpenBLAS project nor the names of
102
+ its contributors may be used to endorse or promote products
103
+ derived from this software without specific prior written
104
+ permission.
105
+
106
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
107
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
108
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
109
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
110
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
111
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
112
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
113
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
114
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
115
+ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
116
+
117
+
118
+ Name: LAPACK
119
+ Files: numpy.libs/libscipy_openblas*.so
120
+ Description: bundled in OpenBLAS
121
+ Availability: https://github.com/OpenMathLib/OpenBLAS/
122
+ License: BSD-3-Clause-Attribution
123
+ Copyright (c) 1992-2013 The University of Tennessee and The University
124
+ of Tennessee Research Foundation. All rights
125
+ reserved.
126
+ Copyright (c) 2000-2013 The University of California Berkeley. All
127
+ rights reserved.
128
+ Copyright (c) 2006-2013 The University of Colorado Denver. All rights
129
+ reserved.
130
+
131
+ $COPYRIGHT$
132
+
133
+ Additional copyrights may follow
134
+
135
+ $HEADER$
136
+
137
+ Redistribution and use in source and binary forms, with or without
138
+ modification, are permitted provided that the following conditions are
139
+ met:
140
+
141
+ - Redistributions of source code must retain the above copyright
142
+ notice, this list of conditions and the following disclaimer.
143
+
144
+ - Redistributions in binary form must reproduce the above copyright
145
+ notice, this list of conditions and the following disclaimer listed
146
+ in this license in the documentation and/or other materials
147
+ provided with the distribution.
148
+
149
+ - Neither the name of the copyright holders nor the names of its
150
+ contributors may be used to endorse or promote products derived from
151
+ this software without specific prior written permission.
152
+
153
+ The copyright holders provide no reassurances that the source code
154
+ provided does not infringe any patent, copyright, or any other
155
+ intellectual property rights of third parties. The copyright holders
156
+ disclaim any liability to any recipient for claims brought against
157
+ recipient by any third party for infringement of that parties
158
+ intellectual property rights.
159
+
160
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
161
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
162
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
163
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
164
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
165
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
166
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
167
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
168
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
169
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
170
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
171
+
172
+
173
+ Name: GCC runtime library
174
+ Files: numpy.libs/libgfortran*.so
175
+ Description: dynamically linked to files compiled with gcc
176
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran
177
+ License: GPL-3.0-with-GCC-exception
178
+ Copyright (C) 2002-2017 Free Software Foundation, Inc.
179
+
180
+ Libgfortran is free software; you can redistribute it and/or modify
181
+ it under the terms of the GNU General Public License as published by
182
+ the Free Software Foundation; either version 3, or (at your option)
183
+ any later version.
184
+
185
+ Libgfortran is distributed in the hope that it will be useful,
186
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
187
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
188
+ GNU General Public License for more details.
189
+
190
+ Under Section 7 of GPL version 3, you are granted additional
191
+ permissions described in the GCC Runtime Library Exception, version
192
+ 3.1, as published by the Free Software Foundation.
193
+
194
+ You should have received a copy of the GNU General Public License and
195
+ a copy of the GCC Runtime Library Exception along with this program;
196
+ see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
197
+ <http://www.gnu.org/licenses/>.
198
+
199
+ ----
200
+
201
+ Full text of license texts referred to above follows (that they are
202
+ listed below does not necessarily imply the conditions apply to the
203
+ present binary release):
204
+
205
+ ----
206
+
207
+ GCC RUNTIME LIBRARY EXCEPTION
208
+
209
+ Version 3.1, 31 March 2009
210
+
211
+ Copyright (C) 2009 Free Software Foundation, Inc. <http://fsf.org/>
212
+
213
+ Everyone is permitted to copy and distribute verbatim copies of this
214
+ license document, but changing it is not allowed.
215
+
216
+ This GCC Runtime Library Exception ("Exception") is an additional
217
+ permission under section 7 of the GNU General Public License, version
218
+ 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that
219
+ bears a notice placed by the copyright holder of the file stating that
220
+ the file is governed by GPLv3 along with this Exception.
221
+
222
+ When you use GCC to compile a program, GCC may combine portions of
223
+ certain GCC header files and runtime libraries with the compiled
224
+ program. The purpose of this Exception is to allow compilation of
225
+ non-GPL (including proprietary) programs to use, in this way, the
226
+ header files and runtime libraries covered by this Exception.
227
+
228
+ 0. Definitions.
229
+
230
+ A file is an "Independent Module" if it either requires the Runtime
231
+ Library for execution after a Compilation Process, or makes use of an
232
+ interface provided by the Runtime Library, but is not otherwise based
233
+ on the Runtime Library.
234
+
235
+ "GCC" means a version of the GNU Compiler Collection, with or without
236
+ modifications, governed by version 3 (or a specified later version) of
237
+ the GNU General Public License (GPL) with the option of using any
238
+ subsequent versions published by the FSF.
239
+
240
+ "GPL-compatible Software" is software whose conditions of propagation,
241
+ modification and use would permit combination with GCC in accord with
242
+ the license of GCC.
243
+
244
+ "Target Code" refers to output from any compiler for a real or virtual
245
+ target processor architecture, in executable form or suitable for
246
+ input to an assembler, loader, linker and/or execution
247
+ phase. Notwithstanding that, Target Code does not include data in any
248
+ format that is used as a compiler intermediate representation, or used
249
+ for producing a compiler intermediate representation.
250
+
251
+ The "Compilation Process" transforms code entirely represented in
252
+ non-intermediate languages designed for human-written code, and/or in
253
+ Java Virtual Machine byte code, into Target Code. Thus, for example,
254
+ use of source code generators and preprocessors need not be considered
255
+ part of the Compilation Process, since the Compilation Process can be
256
+ understood as starting with the output of the generators or
257
+ preprocessors.
258
+
259
+ A Compilation Process is "Eligible" if it is done using GCC, alone or
260
+ with other GPL-compatible software, or if it is done without using any
261
+ work based on GCC. For example, using non-GPL-compatible Software to
262
+ optimize any GCC intermediate representations would not qualify as an
263
+ Eligible Compilation Process.
264
+
265
+ 1. Grant of Additional Permission.
266
+
267
+ You have permission to propagate a work of Target Code formed by
268
+ combining the Runtime Library with Independent Modules, even if such
269
+ propagation would otherwise violate the terms of GPLv3, provided that
270
+ all Target Code was generated by Eligible Compilation Processes. You
271
+ may then convey such a combination under terms of your choice,
272
+ consistent with the licensing of the Independent Modules.
273
+
274
+ 2. No Weakening of GCC Copyleft.
275
+
276
+ The availability of this Exception does not imply any general
277
+ presumption that third-party software is unaffected by the copyleft
278
+ requirements of the license of GCC.
279
+
280
+ ----
281
+
282
+ GNU GENERAL PUBLIC LICENSE
283
+ Version 3, 29 June 2007
284
+
285
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
286
+ Everyone is permitted to copy and distribute verbatim copies
287
+ of this license document, but changing it is not allowed.
288
+
289
+ Preamble
290
+
291
+ The GNU General Public License is a free, copyleft license for
292
+ software and other kinds of works.
293
+
294
+ The licenses for most software and other practical works are designed
295
+ to take away your freedom to share and change the works. By contrast,
296
+ the GNU General Public License is intended to guarantee your freedom to
297
+ share and change all versions of a program--to make sure it remains free
298
+ software for all its users. We, the Free Software Foundation, use the
299
+ GNU General Public License for most of our software; it applies also to
300
+ any other work released this way by its authors. You can apply it to
301
+ your programs, too.
302
+
303
+ When we speak of free software, we are referring to freedom, not
304
+ price. Our General Public Licenses are designed to make sure that you
305
+ have the freedom to distribute copies of free software (and charge for
306
+ them if you wish), that you receive source code or can get it if you
307
+ want it, that you can change the software or use pieces of it in new
308
+ free programs, and that you know you can do these things.
309
+
310
+ To protect your rights, we need to prevent others from denying you
311
+ these rights or asking you to surrender the rights. Therefore, you have
312
+ certain responsibilities if you distribute copies of the software, or if
313
+ you modify it: responsibilities to respect the freedom of others.
314
+
315
+ For example, if you distribute copies of such a program, whether
316
+ gratis or for a fee, you must pass on to the recipients the same
317
+ freedoms that you received. You must make sure that they, too, receive
318
+ or can get the source code. And you must show them these terms so they
319
+ know their rights.
320
+
321
+ Developers that use the GNU GPL protect your rights with two steps:
322
+ (1) assert copyright on the software, and (2) offer you this License
323
+ giving you legal permission to copy, distribute and/or modify it.
324
+
325
+ For the developers' and authors' protection, the GPL clearly explains
326
+ that there is no warranty for this free software. For both users' and
327
+ authors' sake, the GPL requires that modified versions be marked as
328
+ changed, so that their problems will not be attributed erroneously to
329
+ authors of previous versions.
330
+
331
+ Some devices are designed to deny users access to install or run
332
+ modified versions of the software inside them, although the manufacturer
333
+ can do so. This is fundamentally incompatible with the aim of
334
+ protecting users' freedom to change the software. The systematic
335
+ pattern of such abuse occurs in the area of products for individuals to
336
+ use, which is precisely where it is most unacceptable. Therefore, we
337
+ have designed this version of the GPL to prohibit the practice for those
338
+ products. If such problems arise substantially in other domains, we
339
+ stand ready to extend this provision to those domains in future versions
340
+ of the GPL, as needed to protect the freedom of users.
341
+
342
+ Finally, every program is threatened constantly by software patents.
343
+ States should not allow patents to restrict development and use of
344
+ software on general-purpose computers, but in those that do, we wish to
345
+ avoid the special danger that patents applied to a free program could
346
+ make it effectively proprietary. To prevent this, the GPL assures that
347
+ patents cannot be used to render the program non-free.
348
+
349
+ The precise terms and conditions for copying, distribution and
350
+ modification follow.
351
+
352
+ TERMS AND CONDITIONS
353
+
354
+ 0. Definitions.
355
+
356
+ "This License" refers to version 3 of the GNU General Public License.
357
+
358
+ "Copyright" also means copyright-like laws that apply to other kinds of
359
+ works, such as semiconductor masks.
360
+
361
+ "The Program" refers to any copyrightable work licensed under this
362
+ License. Each licensee is addressed as "you". "Licensees" and
363
+ "recipients" may be individuals or organizations.
364
+
365
+ To "modify" a work means to copy from or adapt all or part of the work
366
+ in a fashion requiring copyright permission, other than the making of an
367
+ exact copy. The resulting work is called a "modified version" of the
368
+ earlier work or a work "based on" the earlier work.
369
+
370
+ A "covered work" means either the unmodified Program or a work based
371
+ on the Program.
372
+
373
+ To "propagate" a work means to do anything with it that, without
374
+ permission, would make you directly or secondarily liable for
375
+ infringement under applicable copyright law, except executing it on a
376
+ computer or modifying a private copy. Propagation includes copying,
377
+ distribution (with or without modification), making available to the
378
+ public, and in some countries other activities as well.
379
+
380
+ To "convey" a work means any kind of propagation that enables other
381
+ parties to make or receive copies. Mere interaction with a user through
382
+ a computer network, with no transfer of a copy, is not conveying.
383
+
384
+ An interactive user interface displays "Appropriate Legal Notices"
385
+ to the extent that it includes a convenient and prominently visible
386
+ feature that (1) displays an appropriate copyright notice, and (2)
387
+ tells the user that there is no warranty for the work (except to the
388
+ extent that warranties are provided), that licensees may convey the
389
+ work under this License, and how to view a copy of this License. If
390
+ the interface presents a list of user commands or options, such as a
391
+ menu, a prominent item in the list meets this criterion.
392
+
393
+ 1. Source Code.
394
+
395
+ The "source code" for a work means the preferred form of the work
396
+ for making modifications to it. "Object code" means any non-source
397
+ form of a work.
398
+
399
+ A "Standard Interface" means an interface that either is an official
400
+ standard defined by a recognized standards body, or, in the case of
401
+ interfaces specified for a particular programming language, one that
402
+ is widely used among developers working in that language.
403
+
404
+ The "System Libraries" of an executable work include anything, other
405
+ than the work as a whole, that (a) is included in the normal form of
406
+ packaging a Major Component, but which is not part of that Major
407
+ Component, and (b) serves only to enable use of the work with that
408
+ Major Component, or to implement a Standard Interface for which an
409
+ implementation is available to the public in source code form. A
410
+ "Major Component", in this context, means a major essential component
411
+ (kernel, window system, and so on) of the specific operating system
412
+ (if any) on which the executable work runs, or a compiler used to
413
+ produce the work, or an object code interpreter used to run it.
414
+
415
+ The "Corresponding Source" for a work in object code form means all
416
+ the source code needed to generate, install, and (for an executable
417
+ work) run the object code and to modify the work, including scripts to
418
+ control those activities. However, it does not include the work's
419
+ System Libraries, or general-purpose tools or generally available free
420
+ programs which are used unmodified in performing those activities but
421
+ which are not part of the work. For example, Corresponding Source
422
+ includes interface definition files associated with source files for
423
+ the work, and the source code for shared libraries and dynamically
424
+ linked subprograms that the work is specifically designed to require,
425
+ such as by intimate data communication or control flow between those
426
+ subprograms and other parts of the work.
427
+
428
+ The Corresponding Source need not include anything that users
429
+ can regenerate automatically from other parts of the Corresponding
430
+ Source.
431
+
432
+ The Corresponding Source for a work in source code form is that
433
+ same work.
434
+
435
+ 2. Basic Permissions.
436
+
437
+ All rights granted under this License are granted for the term of
438
+ copyright on the Program, and are irrevocable provided the stated
439
+ conditions are met. This License explicitly affirms your unlimited
440
+ permission to run the unmodified Program. The output from running a
441
+ covered work is covered by this License only if the output, given its
442
+ content, constitutes a covered work. This License acknowledges your
443
+ rights of fair use or other equivalent, as provided by copyright law.
444
+
445
+ You may make, run and propagate covered works that you do not
446
+ convey, without conditions so long as your license otherwise remains
447
+ in force. You may convey covered works to others for the sole purpose
448
+ of having them make modifications exclusively for you, or provide you
449
+ with facilities for running those works, provided that you comply with
450
+ the terms of this License in conveying all material for which you do
451
+ not control copyright. Those thus making or running the covered works
452
+ for you must do so exclusively on your behalf, under your direction
453
+ and control, on terms that prohibit them from making any copies of
454
+ your copyrighted material outside their relationship with you.
455
+
456
+ Conveying under any other circumstances is permitted solely under
457
+ the conditions stated below. Sublicensing is not allowed; section 10
458
+ makes it unnecessary.
459
+
460
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
461
+
462
+ No covered work shall be deemed part of an effective technological
463
+ measure under any applicable law fulfilling obligations under article
464
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
465
+ similar laws prohibiting or restricting circumvention of such
466
+ measures.
467
+
468
+ When you convey a covered work, you waive any legal power to forbid
469
+ circumvention of technological measures to the extent such circumvention
470
+ is effected by exercising rights under this License with respect to
471
+ the covered work, and you disclaim any intention to limit operation or
472
+ modification of the work as a means of enforcing, against the work's
473
+ users, your or third parties' legal rights to forbid circumvention of
474
+ technological measures.
475
+
476
+ 4. Conveying Verbatim Copies.
477
+
478
+ You may convey verbatim copies of the Program's source code as you
479
+ receive it, in any medium, provided that you conspicuously and
480
+ appropriately publish on each copy an appropriate copyright notice;
481
+ keep intact all notices stating that this License and any
482
+ non-permissive terms added in accord with section 7 apply to the code;
483
+ keep intact all notices of the absence of any warranty; and give all
484
+ recipients a copy of this License along with the Program.
485
+
486
+ You may charge any price or no price for each copy that you convey,
487
+ and you may offer support or warranty protection for a fee.
488
+
489
+ 5. Conveying Modified Source Versions.
490
+
491
+ You may convey a work based on the Program, or the modifications to
492
+ produce it from the Program, in the form of source code under the
493
+ terms of section 4, provided that you also meet all of these conditions:
494
+
495
+ a) The work must carry prominent notices stating that you modified
496
+ it, and giving a relevant date.
497
+
498
+ b) The work must carry prominent notices stating that it is
499
+ released under this License and any conditions added under section
500
+ 7. This requirement modifies the requirement in section 4 to
501
+ "keep intact all notices".
502
+
503
+ c) You must license the entire work, as a whole, under this
504
+ License to anyone who comes into possession of a copy. This
505
+ License will therefore apply, along with any applicable section 7
506
+ additional terms, to the whole of the work, and all its parts,
507
+ regardless of how they are packaged. This License gives no
508
+ permission to license the work in any other way, but it does not
509
+ invalidate such permission if you have separately received it.
510
+
511
+ d) If the work has interactive user interfaces, each must display
512
+ Appropriate Legal Notices; however, if the Program has interactive
513
+ interfaces that do not display Appropriate Legal Notices, your
514
+ work need not make them do so.
515
+
516
+ A compilation of a covered work with other separate and independent
517
+ works, which are not by their nature extensions of the covered work,
518
+ and which are not combined with it such as to form a larger program,
519
+ in or on a volume of a storage or distribution medium, is called an
520
+ "aggregate" if the compilation and its resulting copyright are not
521
+ used to limit the access or legal rights of the compilation's users
522
+ beyond what the individual works permit. Inclusion of a covered work
523
+ in an aggregate does not cause this License to apply to the other
524
+ parts of the aggregate.
525
+
526
+ 6. Conveying Non-Source Forms.
527
+
528
+ You may convey a covered work in object code form under the terms
529
+ of sections 4 and 5, provided that you also convey the
530
+ machine-readable Corresponding Source under the terms of this License,
531
+ in one of these ways:
532
+
533
+ a) Convey the object code in, or embodied in, a physical product
534
+ (including a physical distribution medium), accompanied by the
535
+ Corresponding Source fixed on a durable physical medium
536
+ customarily used for software interchange.
537
+
538
+ b) Convey the object code in, or embodied in, a physical product
539
+ (including a physical distribution medium), accompanied by a
540
+ written offer, valid for at least three years and valid for as
541
+ long as you offer spare parts or customer support for that product
542
+ model, to give anyone who possesses the object code either (1) a
543
+ copy of the Corresponding Source for all the software in the
544
+ product that is covered by this License, on a durable physical
545
+ medium customarily used for software interchange, for a price no
546
+ more than your reasonable cost of physically performing this
547
+ conveying of source, or (2) access to copy the
548
+ Corresponding Source from a network server at no charge.
549
+
550
+ c) Convey individual copies of the object code with a copy of the
551
+ written offer to provide the Corresponding Source. This
552
+ alternative is allowed only occasionally and noncommercially, and
553
+ only if you received the object code with such an offer, in accord
554
+ with subsection 6b.
555
+
556
+ d) Convey the object code by offering access from a designated
557
+ place (gratis or for a charge), and offer equivalent access to the
558
+ Corresponding Source in the same way through the same place at no
559
+ further charge. You need not require recipients to copy the
560
+ Corresponding Source along with the object code. If the place to
561
+ copy the object code is a network server, the Corresponding Source
562
+ may be on a different server (operated by you or a third party)
563
+ that supports equivalent copying facilities, provided you maintain
564
+ clear directions next to the object code saying where to find the
565
+ Corresponding Source. Regardless of what server hosts the
566
+ Corresponding Source, you remain obligated to ensure that it is
567
+ available for as long as needed to satisfy these requirements.
568
+
569
+ e) Convey the object code using peer-to-peer transmission, provided
570
+ you inform other peers where the object code and Corresponding
571
+ Source of the work are being offered to the general public at no
572
+ charge under subsection 6d.
573
+
574
+ A separable portion of the object code, whose source code is excluded
575
+ from the Corresponding Source as a System Library, need not be
576
+ included in conveying the object code work.
577
+
578
+ A "User Product" is either (1) a "consumer product", which means any
579
+ tangible personal property which is normally used for personal, family,
580
+ or household purposes, or (2) anything designed or sold for incorporation
581
+ into a dwelling. In determining whether a product is a consumer product,
582
+ doubtful cases shall be resolved in favor of coverage. For a particular
583
+ product received by a particular user, "normally used" refers to a
584
+ typical or common use of that class of product, regardless of the status
585
+ of the particular user or of the way in which the particular user
586
+ actually uses, or expects or is expected to use, the product. A product
587
+ is a consumer product regardless of whether the product has substantial
588
+ commercial, industrial or non-consumer uses, unless such uses represent
589
+ the only significant mode of use of the product.
590
+
591
+ "Installation Information" for a User Product means any methods,
592
+ procedures, authorization keys, or other information required to install
593
+ and execute modified versions of a covered work in that User Product from
594
+ a modified version of its Corresponding Source. The information must
595
+ suffice to ensure that the continued functioning of the modified object
596
+ code is in no case prevented or interfered with solely because
597
+ modification has been made.
598
+
599
+ If you convey an object code work under this section in, or with, or
600
+ specifically for use in, a User Product, and the conveying occurs as
601
+ part of a transaction in which the right of possession and use of the
602
+ User Product is transferred to the recipient in perpetuity or for a
603
+ fixed term (regardless of how the transaction is characterized), the
604
+ Corresponding Source conveyed under this section must be accompanied
605
+ by the Installation Information. But this requirement does not apply
606
+ if neither you nor any third party retains the ability to install
607
+ modified object code on the User Product (for example, the work has
608
+ been installed in ROM).
609
+
610
+ The requirement to provide Installation Information does not include a
611
+ requirement to continue to provide support service, warranty, or updates
612
+ for a work that has been modified or installed by the recipient, or for
613
+ the User Product in which it has been modified or installed. Access to a
614
+ network may be denied when the modification itself materially and
615
+ adversely affects the operation of the network or violates the rules and
616
+ protocols for communication across the network.
617
+
618
+ Corresponding Source conveyed, and Installation Information provided,
619
+ in accord with this section must be in a format that is publicly
620
+ documented (and with an implementation available to the public in
621
+ source code form), and must require no special password or key for
622
+ unpacking, reading or copying.
623
+
624
+ 7. Additional Terms.
625
+
626
+ "Additional permissions" are terms that supplement the terms of this
627
+ License by making exceptions from one or more of its conditions.
628
+ Additional permissions that are applicable to the entire Program shall
629
+ be treated as though they were included in this License, to the extent
630
+ that they are valid under applicable law. If additional permissions
631
+ apply only to part of the Program, that part may be used separately
632
+ under those permissions, but the entire Program remains governed by
633
+ this License without regard to the additional permissions.
634
+
635
+ When you convey a copy of a covered work, you may at your option
636
+ remove any additional permissions from that copy, or from any part of
637
+ it. (Additional permissions may be written to require their own
638
+ removal in certain cases when you modify the work.) You may place
639
+ additional permissions on material, added by you to a covered work,
640
+ for which you have or can give appropriate copyright permission.
641
+
642
+ Notwithstanding any other provision of this License, for material you
643
+ add to a covered work, you may (if authorized by the copyright holders of
644
+ that material) supplement the terms of this License with terms:
645
+
646
+ a) Disclaiming warranty or limiting liability differently from the
647
+ terms of sections 15 and 16 of this License; or
648
+
649
+ b) Requiring preservation of specified reasonable legal notices or
650
+ author attributions in that material or in the Appropriate Legal
651
+ Notices displayed by works containing it; or
652
+
653
+ c) Prohibiting misrepresentation of the origin of that material, or
654
+ requiring that modified versions of such material be marked in
655
+ reasonable ways as different from the original version; or
656
+
657
+ d) Limiting the use for publicity purposes of names of licensors or
658
+ authors of the material; or
659
+
660
+ e) Declining to grant rights under trademark law for use of some
661
+ trade names, trademarks, or service marks; or
662
+
663
+ f) Requiring indemnification of licensors and authors of that
664
+ material by anyone who conveys the material (or modified versions of
665
+ it) with contractual assumptions of liability to the recipient, for
666
+ any liability that these contractual assumptions directly impose on
667
+ those licensors and authors.
668
+
669
+ All other non-permissive additional terms are considered "further
670
+ restrictions" within the meaning of section 10. If the Program as you
671
+ received it, or any part of it, contains a notice stating that it is
672
+ governed by this License along with a term that is a further
673
+ restriction, you may remove that term. If a license document contains
674
+ a further restriction but permits relicensing or conveying under this
675
+ License, you may add to a covered work material governed by the terms
676
+ of that license document, provided that the further restriction does
677
+ not survive such relicensing or conveying.
678
+
679
+ If you add terms to a covered work in accord with this section, you
680
+ must place, in the relevant source files, a statement of the
681
+ additional terms that apply to those files, or a notice indicating
682
+ where to find the applicable terms.
683
+
684
+ Additional terms, permissive or non-permissive, may be stated in the
685
+ form of a separately written license, or stated as exceptions;
686
+ the above requirements apply either way.
687
+
688
+ 8. Termination.
689
+
690
+ You may not propagate or modify a covered work except as expressly
691
+ provided under this License. Any attempt otherwise to propagate or
692
+ modify it is void, and will automatically terminate your rights under
693
+ this License (including any patent licenses granted under the third
694
+ paragraph of section 11).
695
+
696
+ However, if you cease all violation of this License, then your
697
+ license from a particular copyright holder is reinstated (a)
698
+ provisionally, unless and until the copyright holder explicitly and
699
+ finally terminates your license, and (b) permanently, if the copyright
700
+ holder fails to notify you of the violation by some reasonable means
701
+ prior to 60 days after the cessation.
702
+
703
+ Moreover, your license from a particular copyright holder is
704
+ reinstated permanently if the copyright holder notifies you of the
705
+ violation by some reasonable means, this is the first time you have
706
+ received notice of violation of this License (for any work) from that
707
+ copyright holder, and you cure the violation prior to 30 days after
708
+ your receipt of the notice.
709
+
710
+ Termination of your rights under this section does not terminate the
711
+ licenses of parties who have received copies or rights from you under
712
+ this License. If your rights have been terminated and not permanently
713
+ reinstated, you do not qualify to receive new licenses for the same
714
+ material under section 10.
715
+
716
+ 9. Acceptance Not Required for Having Copies.
717
+
718
+ You are not required to accept this License in order to receive or
719
+ run a copy of the Program. Ancillary propagation of a covered work
720
+ occurring solely as a consequence of using peer-to-peer transmission
721
+ to receive a copy likewise does not require acceptance. However,
722
+ nothing other than this License grants you permission to propagate or
723
+ modify any covered work. These actions infringe copyright if you do
724
+ not accept this License. Therefore, by modifying or propagating a
725
+ covered work, you indicate your acceptance of this License to do so.
726
+
727
+ 10. Automatic Licensing of Downstream Recipients.
728
+
729
+ Each time you convey a covered work, the recipient automatically
730
+ receives a license from the original licensors, to run, modify and
731
+ propagate that work, subject to this License. You are not responsible
732
+ for enforcing compliance by third parties with this License.
733
+
734
+ An "entity transaction" is a transaction transferring control of an
735
+ organization, or substantially all assets of one, or subdividing an
736
+ organization, or merging organizations. If propagation of a covered
737
+ work results from an entity transaction, each party to that
738
+ transaction who receives a copy of the work also receives whatever
739
+ licenses to the work the party's predecessor in interest had or could
740
+ give under the previous paragraph, plus a right to possession of the
741
+ Corresponding Source of the work from the predecessor in interest, if
742
+ the predecessor has it or can get it with reasonable efforts.
743
+
744
+ You may not impose any further restrictions on the exercise of the
745
+ rights granted or affirmed under this License. For example, you may
746
+ not impose a license fee, royalty, or other charge for exercise of
747
+ rights granted under this License, and you may not initiate litigation
748
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
749
+ any patent claim is infringed by making, using, selling, offering for
750
+ sale, or importing the Program or any portion of it.
751
+
752
+ 11. Patents.
753
+
754
+ A "contributor" is a copyright holder who authorizes use under this
755
+ License of the Program or a work on which the Program is based. The
756
+ work thus licensed is called the contributor's "contributor version".
757
+
758
+ A contributor's "essential patent claims" are all patent claims
759
+ owned or controlled by the contributor, whether already acquired or
760
+ hereafter acquired, that would be infringed by some manner, permitted
761
+ by this License, of making, using, or selling its contributor version,
762
+ but do not include claims that would be infringed only as a
763
+ consequence of further modification of the contributor version. For
764
+ purposes of this definition, "control" includes the right to grant
765
+ patent sublicenses in a manner consistent with the requirements of
766
+ this License.
767
+
768
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
769
+ patent license under the contributor's essential patent claims, to
770
+ make, use, sell, offer for sale, import and otherwise run, modify and
771
+ propagate the contents of its contributor version.
772
+
773
+ In the following three paragraphs, a "patent license" is any express
774
+ agreement or commitment, however denominated, not to enforce a patent
775
+ (such as an express permission to practice a patent or covenant not to
776
+ sue for patent infringement). To "grant" such a patent license to a
777
+ party means to make such an agreement or commitment not to enforce a
778
+ patent against the party.
779
+
780
+ If you convey a covered work, knowingly relying on a patent license,
781
+ and the Corresponding Source of the work is not available for anyone
782
+ to copy, free of charge and under the terms of this License, through a
783
+ publicly available network server or other readily accessible means,
784
+ then you must either (1) cause the Corresponding Source to be so
785
+ available, or (2) arrange to deprive yourself of the benefit of the
786
+ patent license for this particular work, or (3) arrange, in a manner
787
+ consistent with the requirements of this License, to extend the patent
788
+ license to downstream recipients. "Knowingly relying" means you have
789
+ actual knowledge that, but for the patent license, your conveying the
790
+ covered work in a country, or your recipient's use of the covered work
791
+ in a country, would infringe one or more identifiable patents in that
792
+ country that you have reason to believe are valid.
793
+
794
+ If, pursuant to or in connection with a single transaction or
795
+ arrangement, you convey, or propagate by procuring conveyance of, a
796
+ covered work, and grant a patent license to some of the parties
797
+ receiving the covered work authorizing them to use, propagate, modify
798
+ or convey a specific copy of the covered work, then the patent license
799
+ you grant is automatically extended to all recipients of the covered
800
+ work and works based on it.
801
+
802
+ A patent license is "discriminatory" if it does not include within
803
+ the scope of its coverage, prohibits the exercise of, or is
804
+ conditioned on the non-exercise of one or more of the rights that are
805
+ specifically granted under this License. You may not convey a covered
806
+ work if you are a party to an arrangement with a third party that is
807
+ in the business of distributing software, under which you make payment
808
+ to the third party based on the extent of your activity of conveying
809
+ the work, and under which the third party grants, to any of the
810
+ parties who would receive the covered work from you, a discriminatory
811
+ patent license (a) in connection with copies of the covered work
812
+ conveyed by you (or copies made from those copies), or (b) primarily
813
+ for and in connection with specific products or compilations that
814
+ contain the covered work, unless you entered into that arrangement,
815
+ or that patent license was granted, prior to 28 March 2007.
816
+
817
+ Nothing in this License shall be construed as excluding or limiting
818
+ any implied license or other defenses to infringement that may
819
+ otherwise be available to you under applicable patent law.
820
+
821
+ 12. No Surrender of Others' Freedom.
822
+
823
+ If conditions are imposed on you (whether by court order, agreement or
824
+ otherwise) that contradict the conditions of this License, they do not
825
+ excuse you from the conditions of this License. If you cannot convey a
826
+ covered work so as to satisfy simultaneously your obligations under this
827
+ License and any other pertinent obligations, then as a consequence you may
828
+ not convey it at all. For example, if you agree to terms that obligate you
829
+ to collect a royalty for further conveying from those to whom you convey
830
+ the Program, the only way you could satisfy both those terms and this
831
+ License would be to refrain entirely from conveying the Program.
832
+
833
+ 13. Use with the GNU Affero General Public License.
834
+
835
+ Notwithstanding any other provision of this License, you have
836
+ permission to link or combine any covered work with a work licensed
837
+ under version 3 of the GNU Affero General Public License into a single
838
+ combined work, and to convey the resulting work. The terms of this
839
+ License will continue to apply to the part which is the covered work,
840
+ but the special requirements of the GNU Affero General Public License,
841
+ section 13, concerning interaction through a network will apply to the
842
+ combination as such.
843
+
844
+ 14. Revised Versions of this License.
845
+
846
+ The Free Software Foundation may publish revised and/or new versions of
847
+ the GNU General Public License from time to time. Such new versions will
848
+ be similar in spirit to the present version, but may differ in detail to
849
+ address new problems or concerns.
850
+
851
+ Each version is given a distinguishing version number. If the
852
+ Program specifies that a certain numbered version of the GNU General
853
+ Public License "or any later version" applies to it, you have the
854
+ option of following the terms and conditions either of that numbered
855
+ version or of any later version published by the Free Software
856
+ Foundation. If the Program does not specify a version number of the
857
+ GNU General Public License, you may choose any version ever published
858
+ by the Free Software Foundation.
859
+
860
+ If the Program specifies that a proxy can decide which future
861
+ versions of the GNU General Public License can be used, that proxy's
862
+ public statement of acceptance of a version permanently authorizes you
863
+ to choose that version for the Program.
864
+
865
+ Later license versions may give you additional or different
866
+ permissions. However, no additional obligations are imposed on any
867
+ author or copyright holder as a result of your choosing to follow a
868
+ later version.
869
+
870
+ 15. Disclaimer of Warranty.
871
+
872
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
873
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
874
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
875
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
876
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
877
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
878
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
879
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
880
+
881
+ 16. Limitation of Liability.
882
+
883
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
884
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
885
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
886
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
887
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
888
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
889
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
890
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
891
+ SUCH DAMAGES.
892
+
893
+ 17. Interpretation of Sections 15 and 16.
894
+
895
+ If the disclaimer of warranty and limitation of liability provided
896
+ above cannot be given local legal effect according to their terms,
897
+ reviewing courts shall apply local law that most closely approximates
898
+ an absolute waiver of all civil liability in connection with the
899
+ Program, unless a warranty or assumption of liability accompanies a
900
+ copy of the Program in return for a fee.
901
+
902
+ END OF TERMS AND CONDITIONS
903
+
904
+ How to Apply These Terms to Your New Programs
905
+
906
+ If you develop a new program, and you want it to be of the greatest
907
+ possible use to the public, the best way to achieve this is to make it
908
+ free software which everyone can redistribute and change under these terms.
909
+
910
+ To do so, attach the following notices to the program. It is safest
911
+ to attach them to the start of each source file to most effectively
912
+ state the exclusion of warranty; and each file should have at least
913
+ the "copyright" line and a pointer to where the full notice is found.
914
+
915
+ <one line to give the program's name and a brief idea of what it does.>
916
+ Copyright (C) <year> <name of author>
917
+
918
+ This program is free software: you can redistribute it and/or modify
919
+ it under the terms of the GNU General Public License as published by
920
+ the Free Software Foundation, either version 3 of the License, or
921
+ (at your option) any later version.
922
+
923
+ This program is distributed in the hope that it will be useful,
924
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
925
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
926
+ GNU General Public License for more details.
927
+
928
+ You should have received a copy of the GNU General Public License
929
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
930
+
931
+ Also add information on how to contact you by electronic and paper mail.
932
+
933
+ If the program does terminal interaction, make it output a short
934
+ notice like this when it starts in an interactive mode:
935
+
936
+ <program> Copyright (C) <year> <name of author>
937
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
938
+ This is free software, and you are welcome to redistribute it
939
+ under certain conditions; type `show c' for details.
940
+
941
+ The hypothetical commands `show w' and `show c' should show the appropriate
942
+ parts of the General Public License. Of course, your program's commands
943
+ might be different; for a GUI interface, you would use an "about box".
944
+
945
+ You should also get your employer (if you work as a programmer) or school,
946
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
947
+ For more information on this, and how to apply and follow the GNU GPL, see
948
+ <http://www.gnu.org/licenses/>.
949
+
950
+ The GNU General Public License does not permit incorporating your program
951
+ into proprietary programs. If your program is a subroutine library, you
952
+ may consider it more useful to permit linking proprietary applications with
953
+ the library. If this is what you want to do, use the GNU Lesser General
954
+ Public License instead of this License. But first, please read
955
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
956
+
957
+ Name: libquadmath
958
+ Files: numpy.libs/libquadmath*.so
959
+ Description: dynamically linked to files compiled with gcc
960
+ Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath
961
+ License: LGPL-2.1-or-later
962
+
963
+ GCC Quad-Precision Math Library
964
+ Copyright (C) 2010-2019 Free Software Foundation, Inc.
965
+ Written by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org>
966
+
967
+ This file is part of the libquadmath library.
968
+ Libquadmath is free software; you can redistribute it and/or
969
+ modify it under the terms of the GNU Library General Public
970
+ License as published by the Free Software Foundation; either
971
+ version 2.1 of the License, or (at your option) any later version.
972
+
973
+ Libquadmath is distributed in the hope that it will be useful,
974
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
975
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
976
+ Lesser General Public License for more details.
977
+ https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
978
+
979
+ Classifier: Development Status :: 5 - Production/Stable
980
+ Classifier: Intended Audience :: Science/Research
981
+ Classifier: Intended Audience :: Developers
982
+ Classifier: License :: OSI Approved :: BSD License
983
+ Classifier: Programming Language :: C
984
+ Classifier: Programming Language :: Python
985
+ Classifier: Programming Language :: Python :: 3
986
+ Classifier: Programming Language :: Python :: 3.10
987
+ Classifier: Programming Language :: Python :: 3.11
988
+ Classifier: Programming Language :: Python :: 3.12
989
+ Classifier: Programming Language :: Python :: 3.13
990
+ Classifier: Programming Language :: Python :: 3 :: Only
991
+ Classifier: Programming Language :: Python :: Implementation :: CPython
992
+ Classifier: Topic :: Software Development
993
+ Classifier: Topic :: Scientific/Engineering
994
+ Classifier: Typing :: Typed
995
+ Classifier: Operating System :: Microsoft :: Windows
996
+ Classifier: Operating System :: POSIX
997
+ Classifier: Operating System :: Unix
998
+ Classifier: Operating System :: MacOS
999
+ Project-URL: homepage, https://numpy.org
1000
+ Project-URL: documentation, https://numpy.org/doc/
1001
+ Project-URL: source, https://github.com/numpy/numpy
1002
+ Project-URL: download, https://pypi.org/project/numpy/#files
1003
+ Project-URL: tracker, https://github.com/numpy/numpy/issues
1004
+ Project-URL: release notes, https://numpy.org/doc/stable/release
1005
+ Requires-Python: >=3.10
1006
+ Description-Content-Type: text/markdown
1007
+
1008
+ <h1 align="center">
1009
+ <img src="https://raw.githubusercontent.com/numpy/numpy/main/branding/logo/primary/numpylogo.svg" width="300">
1010
+ </h1><br>
1011
+
1012
+
1013
+ [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](
1014
+ https://numfocus.org)
1015
+ [![PyPI Downloads](https://img.shields.io/pypi/dm/numpy.svg?label=PyPI%20downloads)](
1016
+ https://pypi.org/project/numpy/)
1017
+ [![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/numpy.svg?label=Conda%20downloads)](
1018
+ https://anaconda.org/conda-forge/numpy)
1019
+ [![Stack Overflow](https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg)](
1020
+ https://stackoverflow.com/questions/tagged/numpy)
1021
+ [![Nature Paper](https://img.shields.io/badge/DOI-10.1038%2Fs41586--020--2649--2-blue)](
1022
+ https://doi.org/10.1038/s41586-020-2649-2)
1023
+ [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/numpy/numpy/badge)](https://securityscorecards.dev/viewer/?uri=github.com/numpy/numpy)
1024
+
1025
+
1026
+ NumPy is the fundamental package for scientific computing with Python.
1027
+
1028
+ - **Website:** https://www.numpy.org
1029
+ - **Documentation:** https://numpy.org/doc
1030
+ - **Mailing list:** https://mail.python.org/mailman/listinfo/numpy-discussion
1031
+ - **Source code:** https://github.com/numpy/numpy
1032
+ - **Contributing:** https://www.numpy.org/devdocs/dev/index.html
1033
+ - **Bug reports:** https://github.com/numpy/numpy/issues
1034
+ - **Report a security vulnerability:** https://tidelift.com/docs/security
1035
+
1036
+ It provides:
1037
+
1038
+ - a powerful N-dimensional array object
1039
+ - sophisticated (broadcasting) functions
1040
+ - tools for integrating C/C++ and Fortran code
1041
+ - useful linear algebra, Fourier transform, and random number capabilities
1042
+
1043
+ Testing:
1044
+
1045
+ NumPy requires `pytest` and `hypothesis`. Tests can then be run after installation with:
1046
+
1047
+ python -c "import numpy, sys; sys.exit(numpy.test() is False)"
1048
+
1049
+ Code of Conduct
1050
+ ----------------------
1051
+
1052
+ NumPy is a community-driven open source project developed by a diverse group of
1053
+ [contributors](https://numpy.org/teams/). The NumPy leadership has made a strong
1054
+ commitment to creating an open, inclusive, and positive community. Please read the
1055
+ [NumPy Code of Conduct](https://numpy.org/code-of-conduct/) for guidance on how to interact
1056
+ with others in a way that makes our community thrive.
1057
+
1058
+ Call for Contributions
1059
+ ----------------------
1060
+
1061
+ The NumPy project welcomes your expertise and enthusiasm!
1062
+
1063
+ Small improvements or fixes are always appreciated. If you are considering larger contributions
1064
+ to the source code, please contact us through the [mailing
1065
+ list](https://mail.python.org/mailman/listinfo/numpy-discussion) first.
1066
+
1067
+ Writing code isn’t the only way to contribute to NumPy. You can also:
1068
+ - review pull requests
1069
+ - help us stay on top of new and old issues
1070
+ - develop tutorials, presentations, and other educational materials
1071
+ - maintain and improve [our website](https://github.com/numpy/numpy.org)
1072
+ - develop graphic design for our brand assets and promotional materials
1073
+ - translate website content
1074
+ - help with outreach and onboard new contributors
1075
+ - write grant proposals and help with other fundraising efforts
1076
+
1077
+ For more information about the ways you can contribute to NumPy, visit [our website](https://numpy.org/contribute/).
1078
+ If you’re unsure where to start or how your skills fit in, reach out! You can
1079
+ ask on the mailing list or here, on GitHub, by opening a new issue or leaving a
1080
+ comment on a relevant issue that is already open.
1081
+
1082
+ Our preferred channels of communication are all public, but if you’d like to
1083
+ speak to us in private first, contact our community coordinators at
1084
+ numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for
1085
+ an invitation).
1086
+
1087
+ We also have a biweekly community call, details of which are announced on the
1088
+ mailing list. You are very welcome to join.
1089
+
1090
+ If you are new to contributing to open source, [this
1091
+ guide](https://opensource.guide/how-to-contribute/) helps explain why, what,
1092
+ and how to successfully get involved.
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: meson
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_17_x86_64
5
+ Tag: cp310-cp310-manylinux2014_x86_64
6
+
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy-2.2.6.dist-info/entry_points.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [array_api]
2
+ numpy = numpy
3
+
4
+ [pyinstaller40]
5
+ hook-dirs = numpy:_pyinstaller_hooks_dir
6
+
7
+ [console_scripts]
8
+ f2py = numpy.f2py.f2py2e:main
9
+ numpy-config = numpy._configtool:main
10
+
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/__init__.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
3
+
4
+ Please note that this module is private. All functions and objects
5
+ are available in the main ``numpy`` namespace - use that instead.
6
+
7
+ """
8
+
9
+ import os
10
+
11
+ from numpy.version import version as __version__
12
+
13
+
14
+ # disables OpenBLAS affinity setting of the main thread that limits
15
+ # python threads or processes to one core
16
+ env_added = []
17
+ for envkey in ['OPENBLAS_MAIN_FREE', 'GOTOBLAS_MAIN_FREE']:
18
+ if envkey not in os.environ:
19
+ os.environ[envkey] = '1'
20
+ env_added.append(envkey)
21
+
22
+ try:
23
+ from . import multiarray
24
+ except ImportError as exc:
25
+ import sys
26
+ msg = """
27
+
28
+ IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
29
+
30
+ Importing the numpy C-extensions failed. This error can happen for
31
+ many reasons, often due to issues with your setup or how NumPy was
32
+ installed.
33
+
34
+ We have compiled some common reasons and troubleshooting tips at:
35
+
36
+ https://numpy.org/devdocs/user/troubleshooting-importerror.html
37
+
38
+ Please note and check the following:
39
+
40
+ * The Python version is: Python%d.%d from "%s"
41
+ * The NumPy version is: "%s"
42
+
43
+ and make sure that they are the versions you expect.
44
+ Please carefully study the documentation linked above for further help.
45
+
46
+ Original error was: %s
47
+ """ % (sys.version_info[0], sys.version_info[1], sys.executable,
48
+ __version__, exc)
49
+ raise ImportError(msg)
50
+ finally:
51
+ for envkey in env_added:
52
+ del os.environ[envkey]
53
+ del envkey
54
+ del env_added
55
+ del os
56
+
57
+ from . import umath
58
+
59
+ # Check that multiarray,umath are pure python modules wrapping
60
+ # _multiarray_umath and not either of the old c-extension modules
61
+ if not (hasattr(multiarray, '_multiarray_umath') and
62
+ hasattr(umath, '_multiarray_umath')):
63
+ import sys
64
+ path = sys.modules['numpy'].__path__
65
+ msg = ("Something is wrong with the numpy installation. "
66
+ "While importing we detected an older version of "
67
+ "numpy in {}. One method of fixing this is to repeatedly uninstall "
68
+ "numpy until none is found, then reinstall this version.")
69
+ raise ImportError(msg.format(path))
70
+
71
+ from . import numerictypes as nt
72
+ from .numerictypes import sctypes, sctypeDict
73
+ multiarray.set_typeDict(nt.sctypeDict)
74
+ from . import numeric
75
+ from .numeric import *
76
+ from . import fromnumeric
77
+ from .fromnumeric import *
78
+ from .records import record, recarray
79
+ # Note: module name memmap is overwritten by a class with same name
80
+ from .memmap import *
81
+ from . import function_base
82
+ from .function_base import *
83
+ from . import _machar
84
+ from . import getlimits
85
+ from .getlimits import *
86
+ from . import shape_base
87
+ from .shape_base import *
88
+ from . import einsumfunc
89
+ from .einsumfunc import *
90
+ del nt
91
+
92
+ from .numeric import absolute as abs
93
+
94
+ # do this after everything else, to minimize the chance of this misleadingly
95
+ # appearing in an import-time traceback
96
+ from . import _add_newdocs
97
+ from . import _add_newdocs_scalars
98
+ # add these for module-freeze analysis (like PyInstaller)
99
+ from . import _dtype_ctypes
100
+ from . import _internal
101
+ from . import _dtype
102
+ from . import _methods
103
+
104
+ acos = numeric.arccos
105
+ acosh = numeric.arccosh
106
+ asin = numeric.arcsin
107
+ asinh = numeric.arcsinh
108
+ atan = numeric.arctan
109
+ atanh = numeric.arctanh
110
+ atan2 = numeric.arctan2
111
+ concat = numeric.concatenate
112
+ bitwise_left_shift = numeric.left_shift
113
+ bitwise_invert = numeric.invert
114
+ bitwise_right_shift = numeric.right_shift
115
+ permute_dims = numeric.transpose
116
+ pow = numeric.power
117
+
118
+ __all__ = [
119
+ "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2",
120
+ "bitwise_invert", "bitwise_left_shift", "bitwise_right_shift", "concat",
121
+ "pow", "permute_dims", "memmap", "sctypeDict", "record", "recarray"
122
+ ]
123
+ __all__ += numeric.__all__
124
+ __all__ += function_base.__all__
125
+ __all__ += getlimits.__all__
126
+ __all__ += shape_base.__all__
127
+ __all__ += einsumfunc.__all__
128
+
129
+
130
+ def _ufunc_reduce(func):
131
+ # Report the `__name__`. pickle will try to find the module. Note that
132
+ # pickle supports for this `__name__` to be a `__qualname__`. It may
133
+ # make sense to add a `__qualname__` to ufuncs, to allow this more
134
+ # explicitly (Numba has ufuncs as attributes).
135
+ # See also: https://github.com/dask/distributed/issues/3450
136
+ return func.__name__
137
+
138
+
139
+ def _DType_reconstruct(scalar_type):
140
+ # This is a work-around to pickle type(np.dtype(np.float64)), etc.
141
+ # and it should eventually be replaced with a better solution, e.g. when
142
+ # DTypes become HeapTypes.
143
+ return type(dtype(scalar_type))
144
+
145
+
146
+ def _DType_reduce(DType):
147
+ # As types/classes, most DTypes can simply be pickled by their name:
148
+ if not DType._legacy or DType.__module__ == "numpy.dtypes":
149
+ return DType.__name__
150
+
151
+ # However, user defined legacy dtypes (like rational) do not end up in
152
+ # `numpy.dtypes` as module and do not have a public class at all.
153
+ # For these, we pickle them by reconstructing them from the scalar type:
154
+ scalar_type = DType.type
155
+ return _DType_reconstruct, (scalar_type,)
156
+
157
+
158
+ def __getattr__(name):
159
+ # Deprecated 2022-11-22, NumPy 1.25.
160
+ if name == "MachAr":
161
+ import warnings
162
+ warnings.warn(
163
+ "The `np._core.MachAr` is considered private API (NumPy 1.24)",
164
+ DeprecationWarning, stacklevel=2,
165
+ )
166
+ return _machar.MachAr
167
+ raise AttributeError(f"Module {__name__!r} has no attribute {name!r}")
168
+
169
+
170
+ import copyreg
171
+
172
+ copyreg.pickle(ufunc, _ufunc_reduce)
173
+ copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
174
+
175
+ # Unclutter namespace (must keep _*_reconstruct for unpickling)
176
+ del copyreg, _ufunc_reduce, _DType_reduce
177
+
178
+ from numpy._pytesttester import PytestTester
179
+ test = PytestTester(__name__)
180
+ del PytestTester
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/__init__.pyi ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # NOTE: The `np._core` namespace is deliberately kept empty due to it
2
+ # being private
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .overrides import get_array_function_like_doc as get_array_function_like_doc
2
+
3
+ def refer_to_array_attribute(attr: str, method: bool = True) -> tuple[str, str]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is separate from ``_add_newdocs.py`` so that it can be mocked out by
3
+ our sphinx ``conf.py`` during doc builds, where we want to avoid showing
4
+ platform-dependent information.
5
+ """
6
+ import sys
7
+ import os
8
+ from numpy._core import dtype
9
+ from numpy._core import numerictypes as _numerictypes
10
+ from numpy._core.function_base import add_newdoc
11
+
12
+ ##############################################################################
13
+ #
14
+ # Documentation for concrete scalar classes
15
+ #
16
+ ##############################################################################
17
+
18
+ def numeric_type_aliases(aliases):
19
+ def type_aliases_gen():
20
+ for alias, doc in aliases:
21
+ try:
22
+ alias_type = getattr(_numerictypes, alias)
23
+ except AttributeError:
24
+ # The set of aliases that actually exist varies between platforms
25
+ pass
26
+ else:
27
+ yield (alias_type, alias, doc)
28
+ return list(type_aliases_gen())
29
+
30
+
31
+ possible_aliases = numeric_type_aliases([
32
+ ('int8', '8-bit signed integer (``-128`` to ``127``)'),
33
+ ('int16', '16-bit signed integer (``-32_768`` to ``32_767``)'),
34
+ ('int32', '32-bit signed integer (``-2_147_483_648`` to ``2_147_483_647``)'),
35
+ ('int64', '64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``)'),
36
+ ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'),
37
+ ('uint8', '8-bit unsigned integer (``0`` to ``255``)'),
38
+ ('uint16', '16-bit unsigned integer (``0`` to ``65_535``)'),
39
+ ('uint32', '32-bit unsigned integer (``0`` to ``4_294_967_295``)'),
40
+ ('uint64', '64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``)'),
41
+ ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'),
42
+ ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'),
43
+ ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'),
44
+ ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'),
45
+ ('float96', '96-bit extended-precision floating-point number type'),
46
+ ('float128', '128-bit extended-precision floating-point number type'),
47
+ ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'),
48
+ ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'),
49
+ ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'),
50
+ ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers'),
51
+ ])
52
+
53
+
54
+ def _get_platform_and_machine():
55
+ try:
56
+ system, _, _, _, machine = os.uname()
57
+ except AttributeError:
58
+ system = sys.platform
59
+ if system == 'win32':
60
+ machine = os.environ.get('PROCESSOR_ARCHITEW6432', '') \
61
+ or os.environ.get('PROCESSOR_ARCHITECTURE', '')
62
+ else:
63
+ machine = 'unknown'
64
+ return system, machine
65
+
66
+
67
+ _system, _machine = _get_platform_and_machine()
68
+ _doc_alias_string = f":Alias on this platform ({_system} {_machine}):"
69
+
70
+
71
+ def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
72
+ # note: `:field: value` is rST syntax which renders as field lists.
73
+ o = getattr(_numerictypes, obj)
74
+
75
+ character_code = dtype(o).char
76
+ canonical_name_doc = "" if obj == o.__name__ else \
77
+ f":Canonical name: `numpy.{obj}`\n "
78
+ if fixed_aliases:
79
+ alias_doc = ''.join(f":Alias: `numpy.{alias}`\n "
80
+ for alias in fixed_aliases)
81
+ else:
82
+ alias_doc = ''
83
+ alias_doc += ''.join(f"{_doc_alias_string} `numpy.{alias}`: {doc}.\n "
84
+ for (alias_type, alias, doc) in possible_aliases if alias_type is o)
85
+
86
+ docstring = f"""
87
+ {doc.strip()}
88
+
89
+ :Character code: ``'{character_code}'``
90
+ {canonical_name_doc}{alias_doc}
91
+ """
92
+
93
+ add_newdoc('numpy._core.numerictypes', obj, docstring)
94
+
95
+
96
+ _bool_docstring = (
97
+ """
98
+ Boolean type (True or False), stored as a byte.
99
+
100
+ .. warning::
101
+
102
+ The :class:`bool` type is not a subclass of the :class:`int_` type
103
+ (the :class:`bool` is not even a number type). This is different
104
+ than Python's default implementation of :class:`bool` as a
105
+ sub-class of :class:`int`.
106
+ """
107
+ )
108
+
109
+ add_newdoc_for_scalar_type('bool', [], _bool_docstring)
110
+
111
+ add_newdoc_for_scalar_type('bool_', [], _bool_docstring)
112
+
113
+ add_newdoc_for_scalar_type('byte', [],
114
+ """
115
+ Signed integer type, compatible with C ``char``.
116
+ """)
117
+
118
+ add_newdoc_for_scalar_type('short', [],
119
+ """
120
+ Signed integer type, compatible with C ``short``.
121
+ """)
122
+
123
+ add_newdoc_for_scalar_type('intc', [],
124
+ """
125
+ Signed integer type, compatible with C ``int``.
126
+ """)
127
+
128
+ # TODO: These docs probably need an if to highlight the default rather than
129
+ # the C-types (and be correct).
130
+ add_newdoc_for_scalar_type('int_', [],
131
+ """
132
+ Default signed integer type, 64bit on 64bit systems and 32bit on 32bit
133
+ systems.
134
+ """)
135
+
136
+ add_newdoc_for_scalar_type('longlong', [],
137
+ """
138
+ Signed integer type, compatible with C ``long long``.
139
+ """)
140
+
141
+ add_newdoc_for_scalar_type('ubyte', [],
142
+ """
143
+ Unsigned integer type, compatible with C ``unsigned char``.
144
+ """)
145
+
146
+ add_newdoc_for_scalar_type('ushort', [],
147
+ """
148
+ Unsigned integer type, compatible with C ``unsigned short``.
149
+ """)
150
+
151
+ add_newdoc_for_scalar_type('uintc', [],
152
+ """
153
+ Unsigned integer type, compatible with C ``unsigned int``.
154
+ """)
155
+
156
+ add_newdoc_for_scalar_type('uint', [],
157
+ """
158
+ Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit
159
+ systems.
160
+ """)
161
+
162
+ add_newdoc_for_scalar_type('ulonglong', [],
163
+ """
164
+ Signed integer type, compatible with C ``unsigned long long``.
165
+ """)
166
+
167
+ add_newdoc_for_scalar_type('half', [],
168
+ """
169
+ Half-precision floating-point number type.
170
+ """)
171
+
172
+ add_newdoc_for_scalar_type('single', [],
173
+ """
174
+ Single-precision floating-point number type, compatible with C ``float``.
175
+ """)
176
+
177
+ add_newdoc_for_scalar_type('double', [],
178
+ """
179
+ Double-precision floating-point number type, compatible with Python
180
+ :class:`float` and C ``double``.
181
+ """)
182
+
183
+ add_newdoc_for_scalar_type('longdouble', [],
184
+ """
185
+ Extended-precision floating-point number type, compatible with C
186
+ ``long double`` but not necessarily with IEEE 754 quadruple-precision.
187
+ """)
188
+
189
+ add_newdoc_for_scalar_type('csingle', [],
190
+ """
191
+ Complex number type composed of two single-precision floating-point
192
+ numbers.
193
+ """)
194
+
195
+ add_newdoc_for_scalar_type('cdouble', [],
196
+ """
197
+ Complex number type composed of two double-precision floating-point
198
+ numbers, compatible with Python :class:`complex`.
199
+ """)
200
+
201
+ add_newdoc_for_scalar_type('clongdouble', [],
202
+ """
203
+ Complex number type composed of two extended-precision floating-point
204
+ numbers.
205
+ """)
206
+
207
+ add_newdoc_for_scalar_type('object_', [],
208
+ """
209
+ Any Python object.
210
+ """)
211
+
212
+ add_newdoc_for_scalar_type('str_', [],
213
+ r"""
214
+ A unicode string.
215
+
216
+ This type strips trailing null codepoints.
217
+
218
+ >>> s = np.str_("abc\x00")
219
+ >>> s
220
+ 'abc'
221
+
222
+ Unlike the builtin :class:`str`, this supports the
223
+ :ref:`python:bufferobjects`, exposing its contents as UCS4:
224
+
225
+ >>> m = memoryview(np.str_("abc"))
226
+ >>> m.format
227
+ '3w'
228
+ >>> m.tobytes()
229
+ b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
230
+ """)
231
+
232
+ add_newdoc_for_scalar_type('bytes_', [],
233
+ r"""
234
+ A byte string.
235
+
236
+ When used in arrays, this type strips trailing null bytes.
237
+ """)
238
+
239
+ add_newdoc_for_scalar_type('void', [],
240
+ r"""
241
+ np.void(length_or_data, /, dtype=None)
242
+
243
+ Create a new structured or unstructured void scalar.
244
+
245
+ Parameters
246
+ ----------
247
+ length_or_data : int, array-like, bytes-like, object
248
+ One of multiple meanings (see notes). The length or
249
+ bytes data of an unstructured void. Or alternatively,
250
+ the data to be stored in the new scalar when `dtype`
251
+ is provided.
252
+ This can be an array-like, in which case an array may
253
+ be returned.
254
+ dtype : dtype, optional
255
+ If provided the dtype of the new scalar. This dtype must
256
+ be "void" dtype (i.e. a structured or unstructured void,
257
+ see also :ref:`defining-structured-types`).
258
+
259
+ .. versionadded:: 1.24
260
+
261
+ Notes
262
+ -----
263
+ For historical reasons and because void scalars can represent both
264
+ arbitrary byte data and structured dtypes, the void constructor
265
+ has three calling conventions:
266
+
267
+ 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
268
+ ``\0`` bytes. The 5 can be a Python or NumPy integer.
269
+ 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
270
+ The dtype itemsize will match the byte string length, here ``"V10"``.
271
+ 3. When a ``dtype=`` is passed the call is roughly the same as an
272
+ array creation. However, a void scalar rather than array is returned.
273
+
274
+ Please see the examples which show all three different conventions.
275
+
276
+ Examples
277
+ --------
278
+ >>> np.void(5)
279
+ np.void(b'\x00\x00\x00\x00\x00')
280
+ >>> np.void(b'abcd')
281
+ np.void(b'\x61\x62\x63\x64')
282
+ >>> np.void((3.2, b'eggs'), dtype="d,S5")
283
+ np.void((3.2, b'eggs'), dtype=[('f0', '<f8'), ('f1', 'S5')])
284
+ >>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
285
+ np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
286
+
287
+ """)
288
+
289
+ add_newdoc_for_scalar_type('datetime64', [],
290
+ """
291
+ If created from a 64-bit integer, it represents an offset from
292
+ ``1970-01-01T00:00:00``.
293
+ If created from string, the string can be in ISO 8601 date
294
+ or datetime format.
295
+
296
+ When parsing a string to create a datetime object, if the string contains
297
+ a trailing timezone (A 'Z' or a timezone offset), the timezone will be
298
+ dropped and a User Warning is given.
299
+
300
+ Datetime64 objects should be considered to be UTC and therefore have an
301
+ offset of +0000.
302
+
303
+ >>> np.datetime64(10, 'Y')
304
+ np.datetime64('1980')
305
+ >>> np.datetime64('1980', 'Y')
306
+ np.datetime64('1980')
307
+ >>> np.datetime64(10, 'D')
308
+ np.datetime64('1970-01-11')
309
+
310
+ See :ref:`arrays.datetime` for more information.
311
+ """)
312
+
313
+ add_newdoc_for_scalar_type('timedelta64', [],
314
+ """
315
+ A timedelta stored as a 64-bit integer.
316
+
317
+ See :ref:`arrays.datetime` for more information.
318
+ """)
319
+
320
+ add_newdoc('numpy._core.numerictypes', "integer", ('is_integer',
321
+ """
322
+ integer.is_integer() -> bool
323
+
324
+ Return ``True`` if the number is finite with integral value.
325
+
326
+ .. versionadded:: 1.22
327
+
328
+ Examples
329
+ --------
330
+ >>> import numpy as np
331
+ >>> np.int64(-2).is_integer()
332
+ True
333
+ >>> np.uint32(5).is_integer()
334
+ True
335
+ """))
336
+
337
+ # TODO: work out how to put this on the base class, np.floating
338
+ for float_name in ('half', 'single', 'double', 'longdouble'):
339
+ add_newdoc('numpy._core.numerictypes', float_name, ('as_integer_ratio',
340
+ """
341
+ {ftype}.as_integer_ratio() -> (int, int)
342
+
343
+ Return a pair of integers, whose ratio is exactly equal to the original
344
+ floating point number, and with a positive denominator.
345
+ Raise `OverflowError` on infinities and a `ValueError` on NaNs.
346
+
347
+ >>> np.{ftype}(10.0).as_integer_ratio()
348
+ (10, 1)
349
+ >>> np.{ftype}(0.0).as_integer_ratio()
350
+ (0, 1)
351
+ >>> np.{ftype}(-.25).as_integer_ratio()
352
+ (-1, 4)
353
+ """.format(ftype=float_name)))
354
+
355
+ add_newdoc('numpy._core.numerictypes', float_name, ('is_integer',
356
+ f"""
357
+ {float_name}.is_integer() -> bool
358
+
359
+ Return ``True`` if the floating point number is finite with integral
360
+ value, and ``False`` otherwise.
361
+
362
+ .. versionadded:: 1.22
363
+
364
+ Examples
365
+ --------
366
+ >>> np.{float_name}(-2.0).is_integer()
367
+ True
368
+ >>> np.{float_name}(3.2).is_integer()
369
+ False
370
+ """))
371
+
372
+ for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
373
+ 'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64'):
374
+ # Add negative examples for signed cases by checking typecode
375
+ add_newdoc('numpy._core.numerictypes', int_name, ('bit_count',
376
+ f"""
377
+ {int_name}.bit_count() -> int
378
+
379
+ Computes the number of 1-bits in the absolute value of the input.
380
+ Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
381
+
382
+ Examples
383
+ --------
384
+ >>> np.{int_name}(127).bit_count()
385
+ 7""" +
386
+ (f"""
387
+ >>> np.{int_name}(-127).bit_count()
388
+ 7
389
+ """ if dtype(int_name).char.islower() else "")))
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_add_newdocs_scalars.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Final
3
+
4
+ import numpy as np
5
+
6
+ possible_aliases: Final[list[tuple[type[np.number], str, str]]] = ...
7
+ _system: Final[str] = ...
8
+ _machine: Final[str] = ...
9
+ _doc_alias_string: Final[str] = ...
10
+ _bool_docstring: Final[str] = ...
11
+ int_name: str = ...
12
+ float_name: str = ...
13
+
14
+ def numeric_type_aliases(aliases: list[tuple[str, str]]) -> list[tuple[type[np.number], str, str]]: ...
15
+ def add_newdoc_for_scalar_type(obj: str, fixed_aliases: Iterable[str], doc: str) -> None: ...
16
+ def _get_platform_and_machine() -> tuple[str, str]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_asarray.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions in the ``as*array`` family that promote array-likes into arrays.
3
+
4
+ `require` fits this category despite its name not matching this pattern.
5
+ """
6
+ from .overrides import (
7
+ array_function_dispatch,
8
+ finalize_array_function_like,
9
+ set_module,
10
+ )
11
+ from .multiarray import array, asanyarray
12
+
13
+
14
+ __all__ = ["require"]
15
+
16
+
17
+ POSSIBLE_FLAGS = {
18
+ 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
19
+ 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
20
+ 'A': 'A', 'ALIGNED': 'A',
21
+ 'W': 'W', 'WRITEABLE': 'W',
22
+ 'O': 'O', 'OWNDATA': 'O',
23
+ 'E': 'E', 'ENSUREARRAY': 'E'
24
+ }
25
+
26
+
27
+ @finalize_array_function_like
28
+ @set_module('numpy')
29
+ def require(a, dtype=None, requirements=None, *, like=None):
30
+ """
31
+ Return an ndarray of the provided type that satisfies requirements.
32
+
33
+ This function is useful to be sure that an array with the correct flags
34
+ is returned for passing to compiled code (perhaps through ctypes).
35
+
36
+ Parameters
37
+ ----------
38
+ a : array_like
39
+ The object to be converted to a type-and-requirement-satisfying array.
40
+ dtype : data-type
41
+ The required data-type. If None preserve the current dtype. If your
42
+ application requires the data to be in native byteorder, include
43
+ a byteorder specification as a part of the dtype specification.
44
+ requirements : str or sequence of str
45
+ The requirements list can be any of the following
46
+
47
+ * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
48
+ * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
49
+ * 'ALIGNED' ('A') - ensure a data-type aligned array
50
+ * 'WRITEABLE' ('W') - ensure a writable array
51
+ * 'OWNDATA' ('O') - ensure an array that owns its own data
52
+ * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
53
+ ${ARRAY_FUNCTION_LIKE}
54
+
55
+ .. versionadded:: 1.20.0
56
+
57
+ Returns
58
+ -------
59
+ out : ndarray
60
+ Array with specified requirements and type if given.
61
+
62
+ See Also
63
+ --------
64
+ asarray : Convert input to an ndarray.
65
+ asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
66
+ ascontiguousarray : Convert input to a contiguous array.
67
+ asfortranarray : Convert input to an ndarray with column-major
68
+ memory order.
69
+ ndarray.flags : Information about the memory layout of the array.
70
+
71
+ Notes
72
+ -----
73
+ The returned array will be guaranteed to have the listed requirements
74
+ by making a copy if needed.
75
+
76
+ Examples
77
+ --------
78
+ >>> import numpy as np
79
+ >>> x = np.arange(6).reshape(2,3)
80
+ >>> x.flags
81
+ C_CONTIGUOUS : True
82
+ F_CONTIGUOUS : False
83
+ OWNDATA : False
84
+ WRITEABLE : True
85
+ ALIGNED : True
86
+ WRITEBACKIFCOPY : False
87
+
88
+ >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
89
+ >>> y.flags
90
+ C_CONTIGUOUS : False
91
+ F_CONTIGUOUS : True
92
+ OWNDATA : True
93
+ WRITEABLE : True
94
+ ALIGNED : True
95
+ WRITEBACKIFCOPY : False
96
+
97
+ """
98
+ if like is not None:
99
+ return _require_with_like(
100
+ like,
101
+ a,
102
+ dtype=dtype,
103
+ requirements=requirements,
104
+ )
105
+
106
+ if not requirements:
107
+ return asanyarray(a, dtype=dtype)
108
+
109
+ requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
110
+
111
+ if 'E' in requirements:
112
+ requirements.remove('E')
113
+ subok = False
114
+ else:
115
+ subok = True
116
+
117
+ order = 'A'
118
+ if requirements >= {'C', 'F'}:
119
+ raise ValueError('Cannot specify both "C" and "F" order')
120
+ elif 'F' in requirements:
121
+ order = 'F'
122
+ requirements.remove('F')
123
+ elif 'C' in requirements:
124
+ order = 'C'
125
+ requirements.remove('C')
126
+
127
+ arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
128
+
129
+ for prop in requirements:
130
+ if not arr.flags[prop]:
131
+ return arr.copy(order)
132
+ return arr
133
+
134
+
135
+ _require_with_like = array_function_dispatch()(require)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_asarray.pyi ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, TypeAlias, TypeVar, overload, Literal
3
+
4
+ from numpy._typing import NDArray, DTypeLike, _SupportsArrayFunc
5
+
6
+ _ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
7
+
8
+ _Requirements: TypeAlias = Literal[
9
+ "C", "C_CONTIGUOUS", "CONTIGUOUS",
10
+ "F", "F_CONTIGUOUS", "FORTRAN",
11
+ "A", "ALIGNED",
12
+ "W", "WRITEABLE",
13
+ "O", "OWNDATA"
14
+ ]
15
+ _E: TypeAlias = Literal["E", "ENSUREARRAY"]
16
+ _RequirementsWithE: TypeAlias = _Requirements | _E
17
+
18
+ @overload
19
+ def require(
20
+ a: _ArrayType,
21
+ dtype: None = ...,
22
+ requirements: None | _Requirements | Iterable[_Requirements] = ...,
23
+ *,
24
+ like: _SupportsArrayFunc = ...
25
+ ) -> _ArrayType: ...
26
+ @overload
27
+ def require(
28
+ a: object,
29
+ dtype: DTypeLike = ...,
30
+ requirements: _E | Iterable[_RequirementsWithE] = ...,
31
+ *,
32
+ like: _SupportsArrayFunc = ...
33
+ ) -> NDArray[Any]: ...
34
+ @overload
35
+ def require(
36
+ a: object,
37
+ dtype: DTypeLike = ...,
38
+ requirements: None | _Requirements | Iterable[_Requirements] = ...,
39
+ *,
40
+ like: _SupportsArrayFunc = ...
41
+ ) -> NDArray[Any]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A place for code to be called from the implementation of np.dtype
3
+
4
+ String handling is much easier to do correctly in python.
5
+ """
6
+ import numpy as np
7
+
8
+
9
+ _kind_to_stem = {
10
+ 'u': 'uint',
11
+ 'i': 'int',
12
+ 'c': 'complex',
13
+ 'f': 'float',
14
+ 'b': 'bool',
15
+ 'V': 'void',
16
+ 'O': 'object',
17
+ 'M': 'datetime',
18
+ 'm': 'timedelta',
19
+ 'S': 'bytes',
20
+ 'U': 'str',
21
+ }
22
+
23
+
24
+ def _kind_name(dtype):
25
+ try:
26
+ return _kind_to_stem[dtype.kind]
27
+ except KeyError as e:
28
+ raise RuntimeError(
29
+ "internal dtype error, unknown kind {!r}"
30
+ .format(dtype.kind)
31
+ ) from None
32
+
33
+
34
+ def __str__(dtype):
35
+ if dtype.fields is not None:
36
+ return _struct_str(dtype, include_align=True)
37
+ elif dtype.subdtype:
38
+ return _subarray_str(dtype)
39
+ elif issubclass(dtype.type, np.flexible) or not dtype.isnative:
40
+ return dtype.str
41
+ else:
42
+ return dtype.name
43
+
44
+
45
+ def __repr__(dtype):
46
+ arg_str = _construction_repr(dtype, include_align=False)
47
+ if dtype.isalignedstruct:
48
+ arg_str = arg_str + ", align=True"
49
+ return "dtype({})".format(arg_str)
50
+
51
+
52
+ def _unpack_field(dtype, offset, title=None):
53
+ """
54
+ Helper function to normalize the items in dtype.fields.
55
+
56
+ Call as:
57
+
58
+ dtype, offset, title = _unpack_field(*dtype.fields[name])
59
+ """
60
+ return dtype, offset, title
61
+
62
+
63
+ def _isunsized(dtype):
64
+ # PyDataType_ISUNSIZED
65
+ return dtype.itemsize == 0
66
+
67
+
68
+ def _construction_repr(dtype, include_align=False, short=False):
69
+ """
70
+ Creates a string repr of the dtype, excluding the 'dtype()' part
71
+ surrounding the object. This object may be a string, a list, or
72
+ a dict depending on the nature of the dtype. This
73
+ is the object passed as the first parameter to the dtype
74
+ constructor, and if no additional constructor parameters are
75
+ given, will reproduce the exact memory layout.
76
+
77
+ Parameters
78
+ ----------
79
+ short : bool
80
+ If true, this creates a shorter repr using 'kind' and 'itemsize',
81
+ instead of the longer type name.
82
+
83
+ include_align : bool
84
+ If true, this includes the 'align=True' parameter
85
+ inside the struct dtype construction dict when needed. Use this flag
86
+ if you want a proper repr string without the 'dtype()' part around it.
87
+
88
+ If false, this does not preserve the
89
+ 'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for
90
+ struct arrays like the regular repr does, because the 'align'
91
+ flag is not part of first dtype constructor parameter. This
92
+ mode is intended for a full 'repr', where the 'align=True' is
93
+ provided as the second parameter.
94
+ """
95
+ if dtype.fields is not None:
96
+ return _struct_str(dtype, include_align=include_align)
97
+ elif dtype.subdtype:
98
+ return _subarray_str(dtype)
99
+ else:
100
+ return _scalar_str(dtype, short=short)
101
+
102
+
103
+ def _scalar_str(dtype, short):
104
+ byteorder = _byte_order_str(dtype)
105
+
106
+ if dtype.type == np.bool:
107
+ if short:
108
+ return "'?'"
109
+ else:
110
+ return "'bool'"
111
+
112
+ elif dtype.type == np.object_:
113
+ # The object reference may be different sizes on different
114
+ # platforms, so it should never include the itemsize here.
115
+ return "'O'"
116
+
117
+ elif dtype.type == np.bytes_:
118
+ if _isunsized(dtype):
119
+ return "'S'"
120
+ else:
121
+ return "'S%d'" % dtype.itemsize
122
+
123
+ elif dtype.type == np.str_:
124
+ if _isunsized(dtype):
125
+ return "'%sU'" % byteorder
126
+ else:
127
+ return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
128
+
129
+ elif dtype.type == str:
130
+ return "'T'"
131
+
132
+ elif not type(dtype)._legacy:
133
+ return f"'{byteorder}{type(dtype).__name__}{dtype.itemsize * 8}'"
134
+
135
+ # unlike the other types, subclasses of void are preserved - but
136
+ # historically the repr does not actually reveal the subclass
137
+ elif issubclass(dtype.type, np.void):
138
+ if _isunsized(dtype):
139
+ return "'V'"
140
+ else:
141
+ return "'V%d'" % dtype.itemsize
142
+
143
+ elif dtype.type == np.datetime64:
144
+ return "'%sM8%s'" % (byteorder, _datetime_metadata_str(dtype))
145
+
146
+ elif dtype.type == np.timedelta64:
147
+ return "'%sm8%s'" % (byteorder, _datetime_metadata_str(dtype))
148
+
149
+ elif np.issubdtype(dtype, np.number):
150
+ # Short repr with endianness, like '<f8'
151
+ if short or dtype.byteorder not in ('=', '|'):
152
+ return "'%s%c%d'" % (byteorder, dtype.kind, dtype.itemsize)
153
+
154
+ # Longer repr, like 'float64'
155
+ else:
156
+ return "'%s%d'" % (_kind_name(dtype), 8*dtype.itemsize)
157
+
158
+ elif dtype.isbuiltin == 2:
159
+ return dtype.type.__name__
160
+
161
+ else:
162
+ raise RuntimeError(
163
+ "Internal error: NumPy dtype unrecognized type number")
164
+
165
+
166
+ def _byte_order_str(dtype):
167
+ """ Normalize byteorder to '<' or '>' """
168
+ # hack to obtain the native and swapped byte order characters
169
+ swapped = np.dtype(int).newbyteorder('S')
170
+ native = swapped.newbyteorder('S')
171
+
172
+ byteorder = dtype.byteorder
173
+ if byteorder == '=':
174
+ return native.byteorder
175
+ if byteorder == 'S':
176
+ # TODO: this path can never be reached
177
+ return swapped.byteorder
178
+ elif byteorder == '|':
179
+ return ''
180
+ else:
181
+ return byteorder
182
+
183
+
184
+ def _datetime_metadata_str(dtype):
185
+ # TODO: this duplicates the C metastr_to_unicode functionality
186
+ unit, count = np.datetime_data(dtype)
187
+ if unit == 'generic':
188
+ return ''
189
+ elif count == 1:
190
+ return '[{}]'.format(unit)
191
+ else:
192
+ return '[{}{}]'.format(count, unit)
193
+
194
+
195
+ def _struct_dict_str(dtype, includealignedflag):
196
+ # unpack the fields dictionary into ls
197
+ names = dtype.names
198
+ fld_dtypes = []
199
+ offsets = []
200
+ titles = []
201
+ for name in names:
202
+ fld_dtype, offset, title = _unpack_field(*dtype.fields[name])
203
+ fld_dtypes.append(fld_dtype)
204
+ offsets.append(offset)
205
+ titles.append(title)
206
+
207
+ # Build up a string to make the dictionary
208
+
209
+ if np._core.arrayprint._get_legacy_print_mode() <= 121:
210
+ colon = ":"
211
+ fieldsep = ","
212
+ else:
213
+ colon = ": "
214
+ fieldsep = ", "
215
+
216
+ # First, the names
217
+ ret = "{'names'%s[" % colon
218
+ ret += fieldsep.join(repr(name) for name in names)
219
+
220
+ # Second, the formats
221
+ ret += "], 'formats'%s[" % colon
222
+ ret += fieldsep.join(
223
+ _construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
224
+
225
+ # Third, the offsets
226
+ ret += "], 'offsets'%s[" % colon
227
+ ret += fieldsep.join("%d" % offset for offset in offsets)
228
+
229
+ # Fourth, the titles
230
+ if any(title is not None for title in titles):
231
+ ret += "], 'titles'%s[" % colon
232
+ ret += fieldsep.join(repr(title) for title in titles)
233
+
234
+ # Fifth, the itemsize
235
+ ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize)
236
+
237
+ if (includealignedflag and dtype.isalignedstruct):
238
+ # Finally, the aligned flag
239
+ ret += ", 'aligned'%sTrue}" % colon
240
+ else:
241
+ ret += "}"
242
+
243
+ return ret
244
+
245
+
246
+ def _aligned_offset(offset, alignment):
247
+ # round up offset:
248
+ return - (-offset // alignment) * alignment
249
+
250
+
251
+ def _is_packed(dtype):
252
+ """
253
+ Checks whether the structured data type in 'dtype'
254
+ has a simple layout, where all the fields are in order,
255
+ and follow each other with no alignment padding.
256
+
257
+ When this returns true, the dtype can be reconstructed
258
+ from a list of the field names and dtypes with no additional
259
+ dtype parameters.
260
+
261
+ Duplicates the C `is_dtype_struct_simple_unaligned_layout` function.
262
+ """
263
+ align = dtype.isalignedstruct
264
+ max_alignment = 1
265
+ total_offset = 0
266
+ for name in dtype.names:
267
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
268
+
269
+ if align:
270
+ total_offset = _aligned_offset(total_offset, fld_dtype.alignment)
271
+ max_alignment = max(max_alignment, fld_dtype.alignment)
272
+
273
+ if fld_offset != total_offset:
274
+ return False
275
+ total_offset += fld_dtype.itemsize
276
+
277
+ if align:
278
+ total_offset = _aligned_offset(total_offset, max_alignment)
279
+
280
+ return total_offset == dtype.itemsize
281
+
282
+
283
+ def _struct_list_str(dtype):
284
+ items = []
285
+ for name in dtype.names:
286
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
287
+
288
+ item = "("
289
+ if title is not None:
290
+ item += "({!r}, {!r}), ".format(title, name)
291
+ else:
292
+ item += "{!r}, ".format(name)
293
+ # Special case subarray handling here
294
+ if fld_dtype.subdtype is not None:
295
+ base, shape = fld_dtype.subdtype
296
+ item += "{}, {}".format(
297
+ _construction_repr(base, short=True),
298
+ shape
299
+ )
300
+ else:
301
+ item += _construction_repr(fld_dtype, short=True)
302
+
303
+ item += ")"
304
+ items.append(item)
305
+
306
+ return "[" + ", ".join(items) + "]"
307
+
308
+
309
+ def _struct_str(dtype, include_align):
310
+ # The list str representation can't include the 'align=' flag,
311
+ # so if it is requested and the struct has the aligned flag set,
312
+ # we must use the dict str instead.
313
+ if not (include_align and dtype.isalignedstruct) and _is_packed(dtype):
314
+ sub = _struct_list_str(dtype)
315
+
316
+ else:
317
+ sub = _struct_dict_str(dtype, include_align)
318
+
319
+ # If the data type isn't the default, void, show it
320
+ if dtype.type != np.void:
321
+ return "({t.__module__}.{t.__name__}, {f})".format(t=dtype.type, f=sub)
322
+ else:
323
+ return sub
324
+
325
+
326
+ def _subarray_str(dtype):
327
+ base, shape = dtype.subdtype
328
+ return "({}, {})".format(
329
+ _construction_repr(base, short=True),
330
+ shape
331
+ )
332
+
333
+
334
+ def _name_includes_bit_suffix(dtype):
335
+ if dtype.type == np.object_:
336
+ # pointer size varies by system, best to omit it
337
+ return False
338
+ elif dtype.type == np.bool:
339
+ # implied
340
+ return False
341
+ elif dtype.type is None:
342
+ return True
343
+ elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
344
+ # unspecified
345
+ return False
346
+ else:
347
+ return True
348
+
349
+
350
+ def _name_get(dtype):
351
+ # provides dtype.name.__get__, documented as returning a "bit name"
352
+
353
+ if dtype.isbuiltin == 2:
354
+ # user dtypes don't promise to do anything special
355
+ return dtype.type.__name__
356
+
357
+ if not type(dtype)._legacy:
358
+ name = type(dtype).__name__
359
+
360
+ elif issubclass(dtype.type, np.void):
361
+ # historically, void subclasses preserve their name, eg `record64`
362
+ name = dtype.type.__name__
363
+ else:
364
+ name = _kind_name(dtype)
365
+
366
+ # append bit counts
367
+ if _name_includes_bit_suffix(dtype):
368
+ name += "{}".format(dtype.itemsize * 8)
369
+
370
+ # append metadata to datetimes
371
+ if dtype.type in (np.datetime64, np.timedelta64):
372
+ name += _datetime_metadata_str(dtype)
373
+
374
+ return name
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype.pyi ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Final, TypeAlias, TypedDict, overload, type_check_only
2
+ from typing import Literal as L
3
+
4
+ from typing_extensions import ReadOnly, TypeVar
5
+
6
+ import numpy as np
7
+
8
+ ###
9
+
10
+ _T = TypeVar("_T")
11
+
12
+ _Name: TypeAlias = L["uint", "int", "complex", "float", "bool", "void", "object", "datetime", "timedelta", "bytes", "str"]
13
+
14
+ @type_check_only
15
+ class _KindToStemType(TypedDict):
16
+ u: ReadOnly[L["uint"]]
17
+ i: ReadOnly[L["int"]]
18
+ c: ReadOnly[L["complex"]]
19
+ f: ReadOnly[L["float"]]
20
+ b: ReadOnly[L["bool"]]
21
+ V: ReadOnly[L["void"]]
22
+ O: ReadOnly[L["object"]]
23
+ M: ReadOnly[L["datetime"]]
24
+ m: ReadOnly[L["timedelta"]]
25
+ S: ReadOnly[L["bytes"]]
26
+ U: ReadOnly[L["str"]]
27
+
28
+ ###
29
+
30
+ _kind_to_stem: Final[_KindToStemType] = ...
31
+
32
+ #
33
+ def _kind_name(dtype: np.dtype[Any]) -> _Name: ...
34
+ def __str__(dtype: np.dtype[Any]) -> str: ...
35
+ def __repr__(dtype: np.dtype[Any]) -> str: ...
36
+
37
+ #
38
+ def _isunsized(dtype: np.dtype[Any]) -> bool: ...
39
+ def _is_packed(dtype: np.dtype[Any]) -> bool: ...
40
+ def _name_includes_bit_suffix(dtype: np.dtype[Any]) -> bool: ...
41
+
42
+ #
43
+ def _construction_repr(dtype: np.dtype[Any], include_align: bool = False, short: bool = False) -> str: ...
44
+ def _scalar_str(dtype: np.dtype[Any], short: bool) -> str: ...
45
+ def _byte_order_str(dtype: np.dtype[Any]) -> str: ...
46
+ def _datetime_metadata_str(dtype: np.dtype[Any]) -> str: ...
47
+ def _struct_dict_str(dtype: np.dtype[Any], includealignedflag: bool) -> str: ...
48
+ def _struct_list_str(dtype: np.dtype[Any]) -> str: ...
49
+ def _struct_str(dtype: np.dtype[Any], include_align: bool) -> str: ...
50
+ def _subarray_str(dtype: np.dtype[Any]) -> str: ...
51
+ def _name_get(dtype: np.dtype[Any]) -> str: ...
52
+
53
+ #
54
+ @overload
55
+ def _unpack_field(dtype: np.dtype[Any], offset: int, title: _T) -> tuple[np.dtype[Any], int, _T]: ...
56
+ @overload
57
+ def _unpack_field(dtype: np.dtype[Any], offset: int, title: None = None) -> tuple[np.dtype[Any], int, None]: ...
58
+ def _aligned_offset(offset: int, alignment: int) -> int: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversion from ctypes to dtype.
3
+
4
+ In an ideal world, we could achieve this through the PEP3118 buffer protocol,
5
+ something like::
6
+
7
+ def dtype_from_ctypes_type(t):
8
+ # needed to ensure that the shape of `t` is within memoryview.format
9
+ class DummyStruct(ctypes.Structure):
10
+ _fields_ = [('a', t)]
11
+
12
+ # empty to avoid memory allocation
13
+ ctype_0 = (DummyStruct * 0)()
14
+ mv = memoryview(ctype_0)
15
+
16
+ # convert the struct, and slice back out the field
17
+ return _dtype_from_pep3118(mv.format)['a']
18
+
19
+ Unfortunately, this fails because:
20
+
21
+ * ctypes cannot handle length-0 arrays with PEP3118 (bpo-32782)
22
+ * PEP3118 cannot represent unions, but both numpy and ctypes can
23
+ * ctypes cannot handle big-endian structs with PEP3118 (bpo-32780)
24
+ """
25
+
26
+ # We delay-import ctypes for distributions that do not include it.
27
+ # While this module is not used unless the user passes in ctypes
28
+ # members, it is eagerly imported from numpy/_core/__init__.py.
29
+ import numpy as np
30
+
31
+
32
+ def _from_ctypes_array(t):
33
+ return np.dtype((dtype_from_ctypes_type(t._type_), (t._length_,)))
34
+
35
+
36
+ def _from_ctypes_structure(t):
37
+ for item in t._fields_:
38
+ if len(item) > 2:
39
+ raise TypeError(
40
+ "ctypes bitfields have no dtype equivalent")
41
+
42
+ if hasattr(t, "_pack_"):
43
+ import ctypes
44
+ formats = []
45
+ offsets = []
46
+ names = []
47
+ current_offset = 0
48
+ for fname, ftyp in t._fields_:
49
+ names.append(fname)
50
+ formats.append(dtype_from_ctypes_type(ftyp))
51
+ # Each type has a default offset, this is platform dependent
52
+ # for some types.
53
+ effective_pack = min(t._pack_, ctypes.alignment(ftyp))
54
+ current_offset = (
55
+ (current_offset + effective_pack - 1) // effective_pack
56
+ ) * effective_pack
57
+ offsets.append(current_offset)
58
+ current_offset += ctypes.sizeof(ftyp)
59
+
60
+ return np.dtype(dict(
61
+ formats=formats,
62
+ offsets=offsets,
63
+ names=names,
64
+ itemsize=ctypes.sizeof(t)))
65
+ else:
66
+ fields = []
67
+ for fname, ftyp in t._fields_:
68
+ fields.append((fname, dtype_from_ctypes_type(ftyp)))
69
+
70
+ # by default, ctypes structs are aligned
71
+ return np.dtype(fields, align=True)
72
+
73
+
74
+ def _from_ctypes_scalar(t):
75
+ """
76
+ Return the dtype type with endianness included if it's the case
77
+ """
78
+ if getattr(t, '__ctype_be__', None) is t:
79
+ return np.dtype('>' + t._type_)
80
+ elif getattr(t, '__ctype_le__', None) is t:
81
+ return np.dtype('<' + t._type_)
82
+ else:
83
+ return np.dtype(t._type_)
84
+
85
+
86
+ def _from_ctypes_union(t):
87
+ import ctypes
88
+ formats = []
89
+ offsets = []
90
+ names = []
91
+ for fname, ftyp in t._fields_:
92
+ names.append(fname)
93
+ formats.append(dtype_from_ctypes_type(ftyp))
94
+ offsets.append(0) # Union fields are offset to 0
95
+
96
+ return np.dtype(dict(
97
+ formats=formats,
98
+ offsets=offsets,
99
+ names=names,
100
+ itemsize=ctypes.sizeof(t)))
101
+
102
+
103
+ def dtype_from_ctypes_type(t):
104
+ """
105
+ Construct a dtype object from a ctypes type
106
+ """
107
+ import _ctypes
108
+ if issubclass(t, _ctypes.Array):
109
+ return _from_ctypes_array(t)
110
+ elif issubclass(t, _ctypes._Pointer):
111
+ raise TypeError("ctypes pointers have no dtype equivalent")
112
+ elif issubclass(t, _ctypes.Structure):
113
+ return _from_ctypes_structure(t)
114
+ elif issubclass(t, _ctypes.Union):
115
+ return _from_ctypes_union(t)
116
+ elif isinstance(getattr(t, '_type_', None), str):
117
+ return _from_ctypes_scalar(t)
118
+ else:
119
+ raise NotImplementedError(
120
+ "Unknown ctypes type {}".format(t.__name__))
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_dtype_ctypes.pyi ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ctypes
2
+ import ctypes as ct
3
+ from typing import Any, overload
4
+
5
+ import numpy as np
6
+
7
+ #
8
+ @overload
9
+ def dtype_from_ctypes_type(t: type[_ctypes.Array[Any] | _ctypes.Structure]) -> np.dtype[np.void]: ...
10
+ @overload
11
+ def dtype_from_ctypes_type(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
12
+ @overload
13
+ def dtype_from_ctypes_type(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
14
+ @overload
15
+ def dtype_from_ctypes_type(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
16
+ @overload
17
+ def dtype_from_ctypes_type(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
18
+ @overload
19
+ def dtype_from_ctypes_type(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
20
+ @overload
21
+ def dtype_from_ctypes_type(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
22
+ @overload
23
+ def dtype_from_ctypes_type(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
24
+ @overload
25
+ def dtype_from_ctypes_type(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
26
+ @overload
27
+ def dtype_from_ctypes_type(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
28
+ @overload
29
+ def dtype_from_ctypes_type(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
30
+ @overload
31
+ def dtype_from_ctypes_type(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
32
+ @overload
33
+ def dtype_from_ctypes_type(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
34
+ @overload
35
+ def dtype_from_ctypes_type(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
36
+ @overload
37
+ def dtype_from_ctypes_type(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
38
+ @overload
39
+ def dtype_from_ctypes_type(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
40
+ @overload
41
+ def dtype_from_ctypes_type(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
42
+
43
+ # NOTE: the complex ctypes on python>=3.14 are not yet supported at runtim, see
44
+ # https://github.com/numpy/numpy/issues/28360
45
+
46
+ #
47
+ def _from_ctypes_array(t: type[_ctypes.Array[Any]]) -> np.dtype[np.void]: ...
48
+ def _from_ctypes_structure(t: type[_ctypes.Structure]) -> np.dtype[np.void]: ...
49
+ def _from_ctypes_union(t: type[_ctypes.Union]) -> np.dtype[np.void]: ...
50
+
51
+ # keep in sync with `dtype_from_ctypes_type` (minus the first overload)
52
+ @overload
53
+ def _from_ctypes_scalar(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
54
+ @overload
55
+ def _from_ctypes_scalar(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
56
+ @overload
57
+ def _from_ctypes_scalar(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
58
+ @overload
59
+ def _from_ctypes_scalar(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
60
+ @overload
61
+ def _from_ctypes_scalar(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
62
+ @overload
63
+ def _from_ctypes_scalar(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
64
+ @overload
65
+ def _from_ctypes_scalar(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
66
+ @overload
67
+ def _from_ctypes_scalar(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
68
+ @overload
69
+ def _from_ctypes_scalar(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
70
+ @overload
71
+ def _from_ctypes_scalar(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
72
+ @overload
73
+ def _from_ctypes_scalar(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
74
+ @overload
75
+ def _from_ctypes_scalar(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
76
+ @overload
77
+ def _from_ctypes_scalar(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
78
+ @overload
79
+ def _from_ctypes_scalar(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
80
+ @overload
81
+ def _from_ctypes_scalar(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
82
+ @overload
83
+ def _from_ctypes_scalar(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_exceptions.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various richly-typed exceptions, that also help us deal with string formatting
3
+ in python where it's easier.
4
+
5
+ By putting the formatting in `__str__`, we also avoid paying the cost for
6
+ users who silence the exceptions.
7
+ """
8
+ from .._utils import set_module
9
+
10
+ def _unpack_tuple(tup):
11
+ if len(tup) == 1:
12
+ return tup[0]
13
+ else:
14
+ return tup
15
+
16
+
17
+ def _display_as_base(cls):
18
+ """
19
+ A decorator that makes an exception class look like its base.
20
+
21
+ We use this to hide subclasses that are implementation details - the user
22
+ should catch the base type, which is what the traceback will show them.
23
+
24
+ Classes decorated with this decorator are subject to removal without a
25
+ deprecation warning.
26
+ """
27
+ assert issubclass(cls, Exception)
28
+ cls.__name__ = cls.__base__.__name__
29
+ return cls
30
+
31
+
32
+ class UFuncTypeError(TypeError):
33
+ """ Base class for all ufunc exceptions """
34
+ def __init__(self, ufunc):
35
+ self.ufunc = ufunc
36
+
37
+
38
+ @_display_as_base
39
+ class _UFuncNoLoopError(UFuncTypeError):
40
+ """ Thrown when a ufunc loop cannot be found """
41
+ def __init__(self, ufunc, dtypes):
42
+ super().__init__(ufunc)
43
+ self.dtypes = tuple(dtypes)
44
+
45
+ def __str__(self):
46
+ return (
47
+ "ufunc {!r} did not contain a loop with signature matching types "
48
+ "{!r} -> {!r}"
49
+ ).format(
50
+ self.ufunc.__name__,
51
+ _unpack_tuple(self.dtypes[:self.ufunc.nin]),
52
+ _unpack_tuple(self.dtypes[self.ufunc.nin:])
53
+ )
54
+
55
+
56
+ @_display_as_base
57
+ class _UFuncBinaryResolutionError(_UFuncNoLoopError):
58
+ """ Thrown when a binary resolution fails """
59
+ def __init__(self, ufunc, dtypes):
60
+ super().__init__(ufunc, dtypes)
61
+ assert len(self.dtypes) == 2
62
+
63
+ def __str__(self):
64
+ return (
65
+ "ufunc {!r} cannot use operands with types {!r} and {!r}"
66
+ ).format(
67
+ self.ufunc.__name__, *self.dtypes
68
+ )
69
+
70
+
71
+ @_display_as_base
72
+ class _UFuncCastingError(UFuncTypeError):
73
+ def __init__(self, ufunc, casting, from_, to):
74
+ super().__init__(ufunc)
75
+ self.casting = casting
76
+ self.from_ = from_
77
+ self.to = to
78
+
79
+
80
+ @_display_as_base
81
+ class _UFuncInputCastingError(_UFuncCastingError):
82
+ """ Thrown when a ufunc input cannot be casted """
83
+ def __init__(self, ufunc, casting, from_, to, i):
84
+ super().__init__(ufunc, casting, from_, to)
85
+ self.in_i = i
86
+
87
+ def __str__(self):
88
+ # only show the number if more than one input exists
89
+ i_str = "{} ".format(self.in_i) if self.ufunc.nin != 1 else ""
90
+ return (
91
+ "Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting "
92
+ "rule {!r}"
93
+ ).format(
94
+ self.ufunc.__name__, i_str, self.from_, self.to, self.casting
95
+ )
96
+
97
+
98
+ @_display_as_base
99
+ class _UFuncOutputCastingError(_UFuncCastingError):
100
+ """ Thrown when a ufunc output cannot be casted """
101
+ def __init__(self, ufunc, casting, from_, to, i):
102
+ super().__init__(ufunc, casting, from_, to)
103
+ self.out_i = i
104
+
105
+ def __str__(self):
106
+ # only show the number if more than one output exists
107
+ i_str = "{} ".format(self.out_i) if self.ufunc.nout != 1 else ""
108
+ return (
109
+ "Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting "
110
+ "rule {!r}"
111
+ ).format(
112
+ self.ufunc.__name__, i_str, self.from_, self.to, self.casting
113
+ )
114
+
115
+
116
+ @_display_as_base
117
+ class _ArrayMemoryError(MemoryError):
118
+ """ Thrown when an array cannot be allocated"""
119
+ def __init__(self, shape, dtype):
120
+ self.shape = shape
121
+ self.dtype = dtype
122
+
123
+ @property
124
+ def _total_size(self):
125
+ num_bytes = self.dtype.itemsize
126
+ for dim in self.shape:
127
+ num_bytes *= dim
128
+ return num_bytes
129
+
130
+ @staticmethod
131
+ def _size_to_string(num_bytes):
132
+ """ Convert a number of bytes into a binary size string """
133
+
134
+ # https://en.wikipedia.org/wiki/Binary_prefix
135
+ LOG2_STEP = 10
136
+ STEP = 1024
137
+ units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
138
+
139
+ unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP
140
+ unit_val = 1 << (unit_i * LOG2_STEP)
141
+ n_units = num_bytes / unit_val
142
+ del unit_val
143
+
144
+ # ensure we pick a unit that is correct after rounding
145
+ if round(n_units) == STEP:
146
+ unit_i += 1
147
+ n_units /= STEP
148
+
149
+ # deal with sizes so large that we don't have units for them
150
+ if unit_i >= len(units):
151
+ new_unit_i = len(units) - 1
152
+ n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP)
153
+ unit_i = new_unit_i
154
+
155
+ unit_name = units[unit_i]
156
+ # format with a sensible number of digits
157
+ if unit_i == 0:
158
+ # no decimal point on bytes
159
+ return '{:.0f} {}'.format(n_units, unit_name)
160
+ elif round(n_units) < 1000:
161
+ # 3 significant figures, if none are dropped to the left of the .
162
+ return '{:#.3g} {}'.format(n_units, unit_name)
163
+ else:
164
+ # just give all the digits otherwise
165
+ return '{:#.0f} {}'.format(n_units, unit_name)
166
+
167
+ def __str__(self):
168
+ size_str = self._size_to_string(self._total_size)
169
+ return (
170
+ "Unable to allocate {} for an array with shape {} and data type {}"
171
+ .format(size_str, self.shape, self.dtype)
172
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_exceptions.pyi ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, Final, overload
3
+
4
+ from typing_extensions import TypeVar, Unpack
5
+
6
+ import numpy as np
7
+ from numpy import _CastingKind
8
+ from numpy._utils import set_module as set_module
9
+
10
+ ###
11
+
12
+ _T = TypeVar("_T")
13
+ _TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]])
14
+ _ExceptionT = TypeVar("_ExceptionT", bound=Exception)
15
+
16
+ ###
17
+
18
+ class UFuncTypeError(TypeError):
19
+ ufunc: Final[np.ufunc]
20
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
21
+
22
+ class _UFuncNoLoopError(UFuncTypeError):
23
+ dtypes: tuple[np.dtype[Any], ...]
24
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
25
+
26
+ class _UFuncBinaryResolutionError(_UFuncNoLoopError):
27
+ dtypes: tuple[np.dtype[Any], np.dtype[Any]]
28
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
29
+
30
+ class _UFuncCastingError(UFuncTypeError):
31
+ casting: Final[_CastingKind]
32
+ from_: Final[np.dtype[Any]]
33
+ to: Final[np.dtype[Any]]
34
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
35
+
36
+ class _UFuncInputCastingError(_UFuncCastingError):
37
+ in_i: Final[int]
38
+ def __init__(
39
+ self,
40
+ /,
41
+ ufunc: np.ufunc,
42
+ casting: _CastingKind,
43
+ from_: np.dtype[Any],
44
+ to: np.dtype[Any],
45
+ i: int,
46
+ ) -> None: ...
47
+
48
+ class _UFuncOutputCastingError(_UFuncCastingError):
49
+ out_i: Final[int]
50
+ def __init__(
51
+ self,
52
+ /,
53
+ ufunc: np.ufunc,
54
+ casting: _CastingKind,
55
+ from_: np.dtype[Any],
56
+ to: np.dtype[Any],
57
+ i: int,
58
+ ) -> None: ...
59
+
60
+ class _ArrayMemoryError(MemoryError):
61
+ shape: tuple[int, ...]
62
+ dtype: np.dtype[Any]
63
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
64
+ @property
65
+ def _total_size(self) -> int: ...
66
+ @staticmethod
67
+ def _size_to_string(num_bytes: int) -> str: ...
68
+
69
+ @overload
70
+ def _unpack_tuple(tup: tuple[_T]) -> _T: ...
71
+ @overload
72
+ def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
73
+ def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_internal.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A place for internal code
3
+
4
+ Some things are more easily handled Python.
5
+
6
+ """
7
+ import ast
8
+ import math
9
+ import re
10
+ import sys
11
+ import warnings
12
+
13
+ from ..exceptions import DTypePromotionError
14
+ from .multiarray import dtype, array, ndarray, promote_types, StringDType
15
+ from numpy import _NoValue
16
+ try:
17
+ import ctypes
18
+ except ImportError:
19
+ ctypes = None
20
+
21
+ IS_PYPY = sys.implementation.name == 'pypy'
22
+
23
+ if sys.byteorder == 'little':
24
+ _nbo = '<'
25
+ else:
26
+ _nbo = '>'
27
+
28
+ def _makenames_list(adict, align):
29
+ allfields = []
30
+
31
+ for fname, obj in adict.items():
32
+ n = len(obj)
33
+ if not isinstance(obj, tuple) or n not in (2, 3):
34
+ raise ValueError("entry not a 2- or 3- tuple")
35
+ if n > 2 and obj[2] == fname:
36
+ continue
37
+ num = int(obj[1])
38
+ if num < 0:
39
+ raise ValueError("invalid offset.")
40
+ format = dtype(obj[0], align=align)
41
+ if n > 2:
42
+ title = obj[2]
43
+ else:
44
+ title = None
45
+ allfields.append((fname, format, num, title))
46
+ # sort by offsets
47
+ allfields.sort(key=lambda x: x[2])
48
+ names = [x[0] for x in allfields]
49
+ formats = [x[1] for x in allfields]
50
+ offsets = [x[2] for x in allfields]
51
+ titles = [x[3] for x in allfields]
52
+
53
+ return names, formats, offsets, titles
54
+
55
+ # Called in PyArray_DescrConverter function when
56
+ # a dictionary without "names" and "formats"
57
+ # fields is used as a data-type descriptor.
58
+ def _usefields(adict, align):
59
+ try:
60
+ names = adict[-1]
61
+ except KeyError:
62
+ names = None
63
+ if names is None:
64
+ names, formats, offsets, titles = _makenames_list(adict, align)
65
+ else:
66
+ formats = []
67
+ offsets = []
68
+ titles = []
69
+ for name in names:
70
+ res = adict[name]
71
+ formats.append(res[0])
72
+ offsets.append(res[1])
73
+ if len(res) > 2:
74
+ titles.append(res[2])
75
+ else:
76
+ titles.append(None)
77
+
78
+ return dtype({"names": names,
79
+ "formats": formats,
80
+ "offsets": offsets,
81
+ "titles": titles}, align)
82
+
83
+
84
+ # construct an array_protocol descriptor list
85
+ # from the fields attribute of a descriptor
86
+ # This calls itself recursively but should eventually hit
87
+ # a descriptor that has no fields and then return
88
+ # a simple typestring
89
+
90
+ def _array_descr(descriptor):
91
+ fields = descriptor.fields
92
+ if fields is None:
93
+ subdtype = descriptor.subdtype
94
+ if subdtype is None:
95
+ if descriptor.metadata is None:
96
+ return descriptor.str
97
+ else:
98
+ new = descriptor.metadata.copy()
99
+ if new:
100
+ return (descriptor.str, new)
101
+ else:
102
+ return descriptor.str
103
+ else:
104
+ return (_array_descr(subdtype[0]), subdtype[1])
105
+
106
+ names = descriptor.names
107
+ ordered_fields = [fields[x] + (x,) for x in names]
108
+ result = []
109
+ offset = 0
110
+ for field in ordered_fields:
111
+ if field[1] > offset:
112
+ num = field[1] - offset
113
+ result.append(('', f'|V{num}'))
114
+ offset += num
115
+ elif field[1] < offset:
116
+ raise ValueError(
117
+ "dtype.descr is not defined for types with overlapping or "
118
+ "out-of-order fields")
119
+ if len(field) > 3:
120
+ name = (field[2], field[3])
121
+ else:
122
+ name = field[2]
123
+ if field[0].subdtype:
124
+ tup = (name, _array_descr(field[0].subdtype[0]),
125
+ field[0].subdtype[1])
126
+ else:
127
+ tup = (name, _array_descr(field[0]))
128
+ offset += field[0].itemsize
129
+ result.append(tup)
130
+
131
+ if descriptor.itemsize > offset:
132
+ num = descriptor.itemsize - offset
133
+ result.append(('', f'|V{num}'))
134
+
135
+ return result
136
+
137
+
138
+ # format_re was originally from numarray by J. Todd Miller
139
+
140
+ format_re = re.compile(r'(?P<order1>[<>|=]?)'
141
+ r'(?P<repeats> *[(]?[ ,0-9]*[)]? *)'
142
+ r'(?P<order2>[<>|=]?)'
143
+ r'(?P<dtype>[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)')
144
+ sep_re = re.compile(r'\s*,\s*')
145
+ space_re = re.compile(r'\s+$')
146
+
147
+ # astr is a string (perhaps comma separated)
148
+
149
+ _convorder = {'=': _nbo}
150
+
151
+ def _commastring(astr):
152
+ startindex = 0
153
+ result = []
154
+ islist = False
155
+ while startindex < len(astr):
156
+ mo = format_re.match(astr, pos=startindex)
157
+ try:
158
+ (order1, repeats, order2, dtype) = mo.groups()
159
+ except (TypeError, AttributeError):
160
+ raise ValueError(
161
+ f'format number {len(result)+1} of "{astr}" is not recognized'
162
+ ) from None
163
+ startindex = mo.end()
164
+ # Separator or ending padding
165
+ if startindex < len(astr):
166
+ if space_re.match(astr, pos=startindex):
167
+ startindex = len(astr)
168
+ else:
169
+ mo = sep_re.match(astr, pos=startindex)
170
+ if not mo:
171
+ raise ValueError(
172
+ 'format number %d of "%s" is not recognized' %
173
+ (len(result)+1, astr))
174
+ startindex = mo.end()
175
+ islist = True
176
+
177
+ if order2 == '':
178
+ order = order1
179
+ elif order1 == '':
180
+ order = order2
181
+ else:
182
+ order1 = _convorder.get(order1, order1)
183
+ order2 = _convorder.get(order2, order2)
184
+ if (order1 != order2):
185
+ raise ValueError(
186
+ 'inconsistent byte-order specification %s and %s' %
187
+ (order1, order2))
188
+ order = order1
189
+
190
+ if order in ('|', '=', _nbo):
191
+ order = ''
192
+ dtype = order + dtype
193
+ if repeats == '':
194
+ newitem = dtype
195
+ else:
196
+ if (repeats[0] == "(" and repeats[-1] == ")"
197
+ and repeats[1:-1].strip() != ""
198
+ and "," not in repeats):
199
+ warnings.warn(
200
+ 'Passing in a parenthesized single number for repeats '
201
+ 'is deprecated; pass either a single number or indicate '
202
+ 'a tuple with a comma, like "(2,)".', DeprecationWarning,
203
+ stacklevel=2)
204
+ newitem = (dtype, ast.literal_eval(repeats))
205
+
206
+ result.append(newitem)
207
+
208
+ return result if islist else result[0]
209
+
210
+ class dummy_ctype:
211
+
212
+ def __init__(self, cls):
213
+ self._cls = cls
214
+
215
+ def __mul__(self, other):
216
+ return self
217
+
218
+ def __call__(self, *other):
219
+ return self._cls(other)
220
+
221
+ def __eq__(self, other):
222
+ return self._cls == other._cls
223
+
224
+ def __ne__(self, other):
225
+ return self._cls != other._cls
226
+
227
+ def _getintp_ctype():
228
+ val = _getintp_ctype.cache
229
+ if val is not None:
230
+ return val
231
+ if ctypes is None:
232
+ import numpy as np
233
+ val = dummy_ctype(np.intp)
234
+ else:
235
+ char = dtype('n').char
236
+ if char == 'i':
237
+ val = ctypes.c_int
238
+ elif char == 'l':
239
+ val = ctypes.c_long
240
+ elif char == 'q':
241
+ val = ctypes.c_longlong
242
+ else:
243
+ val = ctypes.c_long
244
+ _getintp_ctype.cache = val
245
+ return val
246
+
247
+
248
+ _getintp_ctype.cache = None
249
+
250
+ # Used for .ctypes attribute of ndarray
251
+
252
+ class _missing_ctypes:
253
+ def cast(self, num, obj):
254
+ return num.value
255
+
256
+ class c_void_p:
257
+ def __init__(self, ptr):
258
+ self.value = ptr
259
+
260
+
261
+ class _ctypes:
262
+ def __init__(self, array, ptr=None):
263
+ self._arr = array
264
+
265
+ if ctypes:
266
+ self._ctypes = ctypes
267
+ self._data = self._ctypes.c_void_p(ptr)
268
+ else:
269
+ # fake a pointer-like object that holds onto the reference
270
+ self._ctypes = _missing_ctypes()
271
+ self._data = self._ctypes.c_void_p(ptr)
272
+ self._data._objects = array
273
+
274
+ if self._arr.ndim == 0:
275
+ self._zerod = True
276
+ else:
277
+ self._zerod = False
278
+
279
+ def data_as(self, obj):
280
+ """
281
+ Return the data pointer cast to a particular c-types object.
282
+ For example, calling ``self._as_parameter_`` is equivalent to
283
+ ``self.data_as(ctypes.c_void_p)``. Perhaps you want to use
284
+ the data as a pointer to a ctypes array of floating-point data:
285
+ ``self.data_as(ctypes.POINTER(ctypes.c_double))``.
286
+
287
+ The returned pointer will keep a reference to the array.
288
+ """
289
+ # _ctypes.cast function causes a circular reference of self._data in
290
+ # self._data._objects. Attributes of self._data cannot be released
291
+ # until gc.collect is called. Make a copy of the pointer first then
292
+ # let it hold the array reference. This is a workaround to circumvent
293
+ # the CPython bug https://bugs.python.org/issue12836.
294
+ ptr = self._ctypes.cast(self._data, obj)
295
+ ptr._arr = self._arr
296
+ return ptr
297
+
298
+ def shape_as(self, obj):
299
+ """
300
+ Return the shape tuple as an array of some other c-types
301
+ type. For example: ``self.shape_as(ctypes.c_short)``.
302
+ """
303
+ if self._zerod:
304
+ return None
305
+ return (obj*self._arr.ndim)(*self._arr.shape)
306
+
307
+ def strides_as(self, obj):
308
+ """
309
+ Return the strides tuple as an array of some other
310
+ c-types type. For example: ``self.strides_as(ctypes.c_longlong)``.
311
+ """
312
+ if self._zerod:
313
+ return None
314
+ return (obj*self._arr.ndim)(*self._arr.strides)
315
+
316
+ @property
317
+ def data(self):
318
+ """
319
+ A pointer to the memory area of the array as a Python integer.
320
+ This memory area may contain data that is not aligned, or not in
321
+ correct byte-order. The memory area may not even be writeable.
322
+ The array flags and data-type of this array should be respected
323
+ when passing this attribute to arbitrary C-code to avoid trouble
324
+ that can include Python crashing. User Beware! The value of this
325
+ attribute is exactly the same as:
326
+ ``self._array_interface_['data'][0]``.
327
+
328
+ Note that unlike ``data_as``, a reference won't be kept to the array:
329
+ code like ``ctypes.c_void_p((a + b).ctypes.data)`` will result in a
330
+ pointer to a deallocated array, and should be spelt
331
+ ``(a + b).ctypes.data_as(ctypes.c_void_p)``
332
+ """
333
+ return self._data.value
334
+
335
+ @property
336
+ def shape(self):
337
+ """
338
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
339
+ the basetype is the C-integer corresponding to ``dtype('p')`` on this
340
+ platform (see `~numpy.ctypeslib.c_intp`). This base-type could be
341
+ `ctypes.c_int`, `ctypes.c_long`, or `ctypes.c_longlong` depending on
342
+ the platform. The ctypes array contains the shape of
343
+ the underlying array.
344
+ """
345
+ return self.shape_as(_getintp_ctype())
346
+
347
+ @property
348
+ def strides(self):
349
+ """
350
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
351
+ the basetype is the same as for the shape attribute. This ctypes
352
+ array contains the strides information from the underlying array.
353
+ This strides information is important for showing how many bytes
354
+ must be jumped to get to the next element in the array.
355
+ """
356
+ return self.strides_as(_getintp_ctype())
357
+
358
+ @property
359
+ def _as_parameter_(self):
360
+ """
361
+ Overrides the ctypes semi-magic method
362
+
363
+ Enables `c_func(some_array.ctypes)`
364
+ """
365
+ return self.data_as(ctypes.c_void_p)
366
+
367
+ # Numpy 1.21.0, 2021-05-18
368
+
369
+ def get_data(self):
370
+ """Deprecated getter for the `_ctypes.data` property.
371
+
372
+ .. deprecated:: 1.21
373
+ """
374
+ warnings.warn('"get_data" is deprecated. Use "data" instead',
375
+ DeprecationWarning, stacklevel=2)
376
+ return self.data
377
+
378
+ def get_shape(self):
379
+ """Deprecated getter for the `_ctypes.shape` property.
380
+
381
+ .. deprecated:: 1.21
382
+ """
383
+ warnings.warn('"get_shape" is deprecated. Use "shape" instead',
384
+ DeprecationWarning, stacklevel=2)
385
+ return self.shape
386
+
387
+ def get_strides(self):
388
+ """Deprecated getter for the `_ctypes.strides` property.
389
+
390
+ .. deprecated:: 1.21
391
+ """
392
+ warnings.warn('"get_strides" is deprecated. Use "strides" instead',
393
+ DeprecationWarning, stacklevel=2)
394
+ return self.strides
395
+
396
+ def get_as_parameter(self):
397
+ """Deprecated getter for the `_ctypes._as_parameter_` property.
398
+
399
+ .. deprecated:: 1.21
400
+ """
401
+ warnings.warn(
402
+ '"get_as_parameter" is deprecated. Use "_as_parameter_" instead',
403
+ DeprecationWarning, stacklevel=2,
404
+ )
405
+ return self._as_parameter_
406
+
407
+
408
+ def _newnames(datatype, order):
409
+ """
410
+ Given a datatype and an order object, return a new names tuple, with the
411
+ order indicated
412
+ """
413
+ oldnames = datatype.names
414
+ nameslist = list(oldnames)
415
+ if isinstance(order, str):
416
+ order = [order]
417
+ seen = set()
418
+ if isinstance(order, (list, tuple)):
419
+ for name in order:
420
+ try:
421
+ nameslist.remove(name)
422
+ except ValueError:
423
+ if name in seen:
424
+ raise ValueError(f"duplicate field name: {name}") from None
425
+ else:
426
+ raise ValueError(f"unknown field name: {name}") from None
427
+ seen.add(name)
428
+ return tuple(list(order) + nameslist)
429
+ raise ValueError(f"unsupported order value: {order}")
430
+
431
+ def _copy_fields(ary):
432
+ """Return copy of structured array with padding between fields removed.
433
+
434
+ Parameters
435
+ ----------
436
+ ary : ndarray
437
+ Structured array from which to remove padding bytes
438
+
439
+ Returns
440
+ -------
441
+ ary_copy : ndarray
442
+ Copy of ary with padding bytes removed
443
+ """
444
+ dt = ary.dtype
445
+ copy_dtype = {'names': dt.names,
446
+ 'formats': [dt.fields[name][0] for name in dt.names]}
447
+ return array(ary, dtype=copy_dtype, copy=True)
448
+
449
+ def _promote_fields(dt1, dt2):
450
+ """ Perform type promotion for two structured dtypes.
451
+
452
+ Parameters
453
+ ----------
454
+ dt1 : structured dtype
455
+ First dtype.
456
+ dt2 : structured dtype
457
+ Second dtype.
458
+
459
+ Returns
460
+ -------
461
+ out : dtype
462
+ The promoted dtype
463
+
464
+ Notes
465
+ -----
466
+ If one of the inputs is aligned, the result will be. The titles of
467
+ both descriptors must match (point to the same field).
468
+ """
469
+ # Both must be structured and have the same names in the same order
470
+ if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names:
471
+ raise DTypePromotionError(
472
+ f"field names `{dt1.names}` and `{dt2.names}` mismatch.")
473
+
474
+ # if both are identical, we can (maybe!) just return the same dtype.
475
+ identical = dt1 is dt2
476
+ new_fields = []
477
+ for name in dt1.names:
478
+ field1 = dt1.fields[name]
479
+ field2 = dt2.fields[name]
480
+ new_descr = promote_types(field1[0], field2[0])
481
+ identical = identical and new_descr is field1[0]
482
+
483
+ # Check that the titles match (if given):
484
+ if field1[2:] != field2[2:]:
485
+ raise DTypePromotionError(
486
+ f"field titles of field '{name}' mismatch")
487
+ if len(field1) == 2:
488
+ new_fields.append((name, new_descr))
489
+ else:
490
+ new_fields.append(((field1[2], name), new_descr))
491
+
492
+ res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct)
493
+
494
+ # Might as well preserve identity (and metadata) if the dtype is identical
495
+ # and the itemsize, offsets are also unmodified. This could probably be
496
+ # sped up, but also probably just be removed entirely.
497
+ if identical and res.itemsize == dt1.itemsize:
498
+ for name in dt1.names:
499
+ if dt1.fields[name][1] != res.fields[name][1]:
500
+ return res # the dtype changed.
501
+ return dt1
502
+
503
+ return res
504
+
505
+
506
+ def _getfield_is_safe(oldtype, newtype, offset):
507
+ """ Checks safety of getfield for object arrays.
508
+
509
+ As in _view_is_safe, we need to check that memory containing objects is not
510
+ reinterpreted as a non-object datatype and vice versa.
511
+
512
+ Parameters
513
+ ----------
514
+ oldtype : data-type
515
+ Data type of the original ndarray.
516
+ newtype : data-type
517
+ Data type of the field being accessed by ndarray.getfield
518
+ offset : int
519
+ Offset of the field being accessed by ndarray.getfield
520
+
521
+ Raises
522
+ ------
523
+ TypeError
524
+ If the field access is invalid
525
+
526
+ """
527
+ if newtype.hasobject or oldtype.hasobject:
528
+ if offset == 0 and newtype == oldtype:
529
+ return
530
+ if oldtype.names is not None:
531
+ for name in oldtype.names:
532
+ if (oldtype.fields[name][1] == offset and
533
+ oldtype.fields[name][0] == newtype):
534
+ return
535
+ raise TypeError("Cannot get/set field of an object array")
536
+ return
537
+
538
+ def _view_is_safe(oldtype, newtype):
539
+ """ Checks safety of a view involving object arrays, for example when
540
+ doing::
541
+
542
+ np.zeros(10, dtype=oldtype).view(newtype)
543
+
544
+ Parameters
545
+ ----------
546
+ oldtype : data-type
547
+ Data type of original ndarray
548
+ newtype : data-type
549
+ Data type of the view
550
+
551
+ Raises
552
+ ------
553
+ TypeError
554
+ If the new type is incompatible with the old type.
555
+
556
+ """
557
+
558
+ # if the types are equivalent, there is no problem.
559
+ # for example: dtype((np.record, 'i4,i4')) == dtype((np.void, 'i4,i4'))
560
+ if oldtype == newtype:
561
+ return
562
+
563
+ if newtype.hasobject or oldtype.hasobject:
564
+ raise TypeError("Cannot change data-type for array of references.")
565
+ return
566
+
567
+
568
+ # Given a string containing a PEP 3118 format specifier,
569
+ # construct a NumPy dtype
570
+
571
+ _pep3118_native_map = {
572
+ '?': '?',
573
+ 'c': 'S1',
574
+ 'b': 'b',
575
+ 'B': 'B',
576
+ 'h': 'h',
577
+ 'H': 'H',
578
+ 'i': 'i',
579
+ 'I': 'I',
580
+ 'l': 'l',
581
+ 'L': 'L',
582
+ 'q': 'q',
583
+ 'Q': 'Q',
584
+ 'e': 'e',
585
+ 'f': 'f',
586
+ 'd': 'd',
587
+ 'g': 'g',
588
+ 'Zf': 'F',
589
+ 'Zd': 'D',
590
+ 'Zg': 'G',
591
+ 's': 'S',
592
+ 'w': 'U',
593
+ 'O': 'O',
594
+ 'x': 'V', # padding
595
+ }
596
+ _pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
597
+
598
+ _pep3118_standard_map = {
599
+ '?': '?',
600
+ 'c': 'S1',
601
+ 'b': 'b',
602
+ 'B': 'B',
603
+ 'h': 'i2',
604
+ 'H': 'u2',
605
+ 'i': 'i4',
606
+ 'I': 'u4',
607
+ 'l': 'i4',
608
+ 'L': 'u4',
609
+ 'q': 'i8',
610
+ 'Q': 'u8',
611
+ 'e': 'f2',
612
+ 'f': 'f',
613
+ 'd': 'd',
614
+ 'Zf': 'F',
615
+ 'Zd': 'D',
616
+ 's': 'S',
617
+ 'w': 'U',
618
+ 'O': 'O',
619
+ 'x': 'V', # padding
620
+ }
621
+ _pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
622
+
623
+ _pep3118_unsupported_map = {
624
+ 'u': 'UCS-2 strings',
625
+ '&': 'pointers',
626
+ 't': 'bitfields',
627
+ 'X': 'function pointers',
628
+ }
629
+
630
+ class _Stream:
631
+ def __init__(self, s):
632
+ self.s = s
633
+ self.byteorder = '@'
634
+
635
+ def advance(self, n):
636
+ res = self.s[:n]
637
+ self.s = self.s[n:]
638
+ return res
639
+
640
+ def consume(self, c):
641
+ if self.s[:len(c)] == c:
642
+ self.advance(len(c))
643
+ return True
644
+ return False
645
+
646
+ def consume_until(self, c):
647
+ if callable(c):
648
+ i = 0
649
+ while i < len(self.s) and not c(self.s[i]):
650
+ i = i + 1
651
+ return self.advance(i)
652
+ else:
653
+ i = self.s.index(c)
654
+ res = self.advance(i)
655
+ self.advance(len(c))
656
+ return res
657
+
658
+ @property
659
+ def next(self):
660
+ return self.s[0]
661
+
662
+ def __bool__(self):
663
+ return bool(self.s)
664
+
665
+
666
+ def _dtype_from_pep3118(spec):
667
+ stream = _Stream(spec)
668
+ dtype, align = __dtype_from_pep3118(stream, is_subdtype=False)
669
+ return dtype
670
+
671
+ def __dtype_from_pep3118(stream, is_subdtype):
672
+ field_spec = dict(
673
+ names=[],
674
+ formats=[],
675
+ offsets=[],
676
+ itemsize=0
677
+ )
678
+ offset = 0
679
+ common_alignment = 1
680
+ is_padding = False
681
+
682
+ # Parse spec
683
+ while stream:
684
+ value = None
685
+
686
+ # End of structure, bail out to upper level
687
+ if stream.consume('}'):
688
+ break
689
+
690
+ # Sub-arrays (1)
691
+ shape = None
692
+ if stream.consume('('):
693
+ shape = stream.consume_until(')')
694
+ shape = tuple(map(int, shape.split(',')))
695
+
696
+ # Byte order
697
+ if stream.next in ('@', '=', '<', '>', '^', '!'):
698
+ byteorder = stream.advance(1)
699
+ if byteorder == '!':
700
+ byteorder = '>'
701
+ stream.byteorder = byteorder
702
+
703
+ # Byte order characters also control native vs. standard type sizes
704
+ if stream.byteorder in ('@', '^'):
705
+ type_map = _pep3118_native_map
706
+ type_map_chars = _pep3118_native_typechars
707
+ else:
708
+ type_map = _pep3118_standard_map
709
+ type_map_chars = _pep3118_standard_typechars
710
+
711
+ # Item sizes
712
+ itemsize_str = stream.consume_until(lambda c: not c.isdigit())
713
+ if itemsize_str:
714
+ itemsize = int(itemsize_str)
715
+ else:
716
+ itemsize = 1
717
+
718
+ # Data types
719
+ is_padding = False
720
+
721
+ if stream.consume('T{'):
722
+ value, align = __dtype_from_pep3118(
723
+ stream, is_subdtype=True)
724
+ elif stream.next in type_map_chars:
725
+ if stream.next == 'Z':
726
+ typechar = stream.advance(2)
727
+ else:
728
+ typechar = stream.advance(1)
729
+
730
+ is_padding = (typechar == 'x')
731
+ dtypechar = type_map[typechar]
732
+ if dtypechar in 'USV':
733
+ dtypechar += '%d' % itemsize
734
+ itemsize = 1
735
+ numpy_byteorder = {'@': '=', '^': '='}.get(
736
+ stream.byteorder, stream.byteorder)
737
+ value = dtype(numpy_byteorder + dtypechar)
738
+ align = value.alignment
739
+ elif stream.next in _pep3118_unsupported_map:
740
+ desc = _pep3118_unsupported_map[stream.next]
741
+ raise NotImplementedError(
742
+ "Unrepresentable PEP 3118 data type {!r} ({})"
743
+ .format(stream.next, desc))
744
+ else:
745
+ raise ValueError(
746
+ "Unknown PEP 3118 data type specifier %r" % stream.s
747
+ )
748
+
749
+ #
750
+ # Native alignment may require padding
751
+ #
752
+ # Here we assume that the presence of a '@' character implicitly
753
+ # implies that the start of the array is *already* aligned.
754
+ #
755
+ extra_offset = 0
756
+ if stream.byteorder == '@':
757
+ start_padding = (-offset) % align
758
+ intra_padding = (-value.itemsize) % align
759
+
760
+ offset += start_padding
761
+
762
+ if intra_padding != 0:
763
+ if itemsize > 1 or (shape is not None and _prod(shape) > 1):
764
+ # Inject internal padding to the end of the sub-item
765
+ value = _add_trailing_padding(value, intra_padding)
766
+ else:
767
+ # We can postpone the injection of internal padding,
768
+ # as the item appears at most once
769
+ extra_offset += intra_padding
770
+
771
+ # Update common alignment
772
+ common_alignment = _lcm(align, common_alignment)
773
+
774
+ # Convert itemsize to sub-array
775
+ if itemsize != 1:
776
+ value = dtype((value, (itemsize,)))
777
+
778
+ # Sub-arrays (2)
779
+ if shape is not None:
780
+ value = dtype((value, shape))
781
+
782
+ # Field name
783
+ if stream.consume(':'):
784
+ name = stream.consume_until(':')
785
+ else:
786
+ name = None
787
+
788
+ if not (is_padding and name is None):
789
+ if name is not None and name in field_spec['names']:
790
+ raise RuntimeError(
791
+ f"Duplicate field name '{name}' in PEP3118 format"
792
+ )
793
+ field_spec['names'].append(name)
794
+ field_spec['formats'].append(value)
795
+ field_spec['offsets'].append(offset)
796
+
797
+ offset += value.itemsize
798
+ offset += extra_offset
799
+
800
+ field_spec['itemsize'] = offset
801
+
802
+ # extra final padding for aligned types
803
+ if stream.byteorder == '@':
804
+ field_spec['itemsize'] += (-offset) % common_alignment
805
+
806
+ # Check if this was a simple 1-item type, and unwrap it
807
+ if (field_spec['names'] == [None]
808
+ and field_spec['offsets'][0] == 0
809
+ and field_spec['itemsize'] == field_spec['formats'][0].itemsize
810
+ and not is_subdtype):
811
+ ret = field_spec['formats'][0]
812
+ else:
813
+ _fix_names(field_spec)
814
+ ret = dtype(field_spec)
815
+
816
+ # Finished
817
+ return ret, common_alignment
818
+
819
+ def _fix_names(field_spec):
820
+ """ Replace names which are None with the next unused f%d name """
821
+ names = field_spec['names']
822
+ for i, name in enumerate(names):
823
+ if name is not None:
824
+ continue
825
+
826
+ j = 0
827
+ while True:
828
+ name = f'f{j}'
829
+ if name not in names:
830
+ break
831
+ j = j + 1
832
+ names[i] = name
833
+
834
+ def _add_trailing_padding(value, padding):
835
+ """Inject the specified number of padding bytes at the end of a dtype"""
836
+ if value.fields is None:
837
+ field_spec = dict(
838
+ names=['f0'],
839
+ formats=[value],
840
+ offsets=[0],
841
+ itemsize=value.itemsize
842
+ )
843
+ else:
844
+ fields = value.fields
845
+ names = value.names
846
+ field_spec = dict(
847
+ names=names,
848
+ formats=[fields[name][0] for name in names],
849
+ offsets=[fields[name][1] for name in names],
850
+ itemsize=value.itemsize
851
+ )
852
+
853
+ field_spec['itemsize'] += padding
854
+ return dtype(field_spec)
855
+
856
+ def _prod(a):
857
+ p = 1
858
+ for x in a:
859
+ p *= x
860
+ return p
861
+
862
+ def _gcd(a, b):
863
+ """Calculate the greatest common divisor of a and b"""
864
+ if not (math.isfinite(a) and math.isfinite(b)):
865
+ raise ValueError('Can only find greatest common divisor of '
866
+ f'finite arguments, found "{a}" and "{b}"')
867
+ while b:
868
+ a, b = b, a % b
869
+ return a
870
+
871
+ def _lcm(a, b):
872
+ return a // _gcd(a, b) * b
873
+
874
+ def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
875
+ """ Format the error message for when __array_ufunc__ gives up. """
876
+ args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] +
877
+ ['{}={!r}'.format(k, v)
878
+ for k, v in kwargs.items()])
879
+ args = inputs + kwargs.get('out', ())
880
+ types_string = ', '.join(repr(type(arg).__name__) for arg in args)
881
+ return ('operand type(s) all returned NotImplemented from '
882
+ '__array_ufunc__({!r}, {!r}, {}): {}'
883
+ .format(ufunc, method, args_string, types_string))
884
+
885
+
886
+ def array_function_errmsg_formatter(public_api, types):
887
+ """ Format the error message for when __array_ufunc__ gives up. """
888
+ func_name = '{}.{}'.format(public_api.__module__, public_api.__name__)
889
+ return ("no implementation found for '{}' on types that implement "
890
+ '__array_function__: {}'.format(func_name, list(types)))
891
+
892
+
893
+ def _ufunc_doc_signature_formatter(ufunc):
894
+ """
895
+ Builds a signature string which resembles PEP 457
896
+
897
+ This is used to construct the first line of the docstring
898
+ """
899
+
900
+ # input arguments are simple
901
+ if ufunc.nin == 1:
902
+ in_args = 'x'
903
+ else:
904
+ in_args = ', '.join(f'x{i+1}' for i in range(ufunc.nin))
905
+
906
+ # output arguments are both keyword or positional
907
+ if ufunc.nout == 0:
908
+ out_args = ', /, out=()'
909
+ elif ufunc.nout == 1:
910
+ out_args = ', /, out=None'
911
+ else:
912
+ out_args = '[, {positional}], / [, out={default}]'.format(
913
+ positional=', '.join(
914
+ 'out{}'.format(i+1) for i in range(ufunc.nout)),
915
+ default=repr((None,)*ufunc.nout)
916
+ )
917
+
918
+ # keyword only args depend on whether this is a gufunc
919
+ kwargs = (
920
+ ", casting='same_kind'"
921
+ ", order='K'"
922
+ ", dtype=None"
923
+ ", subok=True"
924
+ )
925
+
926
+ # NOTE: gufuncs may or may not support the `axis` parameter
927
+ if ufunc.signature is None:
928
+ kwargs = f", where=True{kwargs}[, signature]"
929
+ else:
930
+ kwargs += "[, signature, axes, axis]"
931
+
932
+ # join all the parts together
933
+ return '{name}({in_args}{out_args}, *{kwargs})'.format(
934
+ name=ufunc.__name__,
935
+ in_args=in_args,
936
+ out_args=out_args,
937
+ kwargs=kwargs
938
+ )
939
+
940
+
941
+ def npy_ctypes_check(cls):
942
+ # determine if a class comes from ctypes, in order to work around
943
+ # a bug in the buffer protocol for those objects, bpo-10746
944
+ try:
945
+ # ctypes class are new-style, so have an __mro__. This probably fails
946
+ # for ctypes classes with multiple inheritance.
947
+ if IS_PYPY:
948
+ # (..., _ctypes.basics._CData, Bufferable, object)
949
+ ctype_base = cls.__mro__[-3]
950
+ else:
951
+ # # (..., _ctypes._CData, object)
952
+ ctype_base = cls.__mro__[-2]
953
+ # right now, they're part of the _ctypes module
954
+ return '_ctypes' in ctype_base.__module__
955
+ except Exception:
956
+ return False
957
+
958
+ # used to handle the _NoValue default argument for na_object
959
+ # in the C implementation of the __reduce__ method for stringdtype
960
+ def _convert_to_stringdtype_kwargs(coerce, na_object=_NoValue):
961
+ if na_object is _NoValue:
962
+ return StringDType(coerce=coerce)
963
+ return StringDType(coerce=coerce, na_object=na_object)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_internal.pyi ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes as ct
2
+ import re
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any, Final, Generic, overload
5
+
6
+ from typing_extensions import Self, TypeVar, deprecated
7
+
8
+ import numpy as np
9
+ import numpy.typing as npt
10
+ from numpy.ctypeslib import c_intp
11
+
12
+ _CastT = TypeVar("_CastT", bound=ct._CanCastTo)
13
+ _T_co = TypeVar("_T_co", covariant=True)
14
+ _CT = TypeVar("_CT", bound=ct._CData)
15
+ _PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)
16
+
17
+ ###
18
+
19
+ IS_PYPY: Final[bool] = ...
20
+
21
+ format_re: Final[re.Pattern[str]] = ...
22
+ sep_re: Final[re.Pattern[str]] = ...
23
+ space_re: Final[re.Pattern[str]] = ...
24
+
25
+ ###
26
+
27
+ # TODO: Let the likes of `shape_as` and `strides_as` return `None`
28
+ # for 0D arrays once we've got shape-support
29
+
30
+ class _ctypes(Generic[_PT_co]):
31
+ @overload
32
+ def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
33
+ @overload
34
+ def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...
35
+
36
+ #
37
+ @property
38
+ def data(self) -> _PT_co: ...
39
+ @property
40
+ def shape(self) -> ct.Array[c_intp]: ...
41
+ @property
42
+ def strides(self) -> ct.Array[c_intp]: ...
43
+ @property
44
+ def _as_parameter_(self) -> ct.c_void_p: ...
45
+
46
+ #
47
+ def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
48
+ def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
49
+ def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
50
+
51
+ #
52
+ @deprecated('"get_data" is deprecated. Use "data" instead')
53
+ def get_data(self, /) -> _PT_co: ...
54
+ @deprecated('"get_shape" is deprecated. Use "shape" instead')
55
+ def get_shape(self, /) -> ct.Array[c_intp]: ...
56
+ @deprecated('"get_strides" is deprecated. Use "strides" instead')
57
+ def get_strides(self, /) -> ct.Array[c_intp]: ...
58
+ @deprecated('"get_as_parameter" is deprecated. Use "_as_parameter_" instead')
59
+ def get_as_parameter(self, /) -> ct.c_void_p: ...
60
+
61
+ class dummy_ctype(Generic[_T_co]):
62
+ _cls: type[_T_co]
63
+
64
+ def __init__(self, /, cls: type[_T_co]) -> None: ...
65
+ def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
66
+ def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
67
+ def __mul__(self, other: object, /) -> Self: ...
68
+ def __call__(self, /, *other: object) -> _T_co: ...
69
+
70
+ def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
71
+ def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
72
+ def npy_ctypes_check(cls: type) -> bool: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_machar.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Machine arithmetic - determine the parameters of the
3
+ floating-point arithmetic system
4
+
5
+ Author: Pearu Peterson, September 2003
6
+
7
+ """
8
+ __all__ = ['MachAr']
9
+
10
+ from .fromnumeric import any
11
+ from ._ufunc_config import errstate
12
+ from .._utils import set_module
13
+
14
+ # Need to speed this up...especially for longdouble
15
+
16
+ # Deprecated 2021-10-20, NumPy 1.22
17
+ class MachAr:
18
+ """
19
+ Diagnosing machine parameters.
20
+
21
+ Attributes
22
+ ----------
23
+ ibeta : int
24
+ Radix in which numbers are represented.
25
+ it : int
26
+ Number of base-`ibeta` digits in the floating point mantissa M.
27
+ machep : int
28
+ Exponent of the smallest (most negative) power of `ibeta` that,
29
+ added to 1.0, gives something different from 1.0
30
+ eps : float
31
+ Floating-point number ``beta**machep`` (floating point precision)
32
+ negep : int
33
+ Exponent of the smallest power of `ibeta` that, subtracted
34
+ from 1.0, gives something different from 1.0.
35
+ epsneg : float
36
+ Floating-point number ``beta**negep``.
37
+ iexp : int
38
+ Number of bits in the exponent (including its sign and bias).
39
+ minexp : int
40
+ Smallest (most negative) power of `ibeta` consistent with there
41
+ being no leading zeros in the mantissa.
42
+ xmin : float
43
+ Floating-point number ``beta**minexp`` (the smallest [in
44
+ magnitude] positive floating point number with full precision).
45
+ maxexp : int
46
+ Smallest (positive) power of `ibeta` that causes overflow.
47
+ xmax : float
48
+ ``(1-epsneg) * beta**maxexp`` (the largest [in magnitude]
49
+ usable floating value).
50
+ irnd : int
51
+ In ``range(6)``, information on what kind of rounding is done
52
+ in addition, and on how underflow is handled.
53
+ ngrd : int
54
+ Number of 'guard digits' used when truncating the product
55
+ of two mantissas to fit the representation.
56
+ epsilon : float
57
+ Same as `eps`.
58
+ tiny : float
59
+ An alias for `smallest_normal`, kept for backwards compatibility.
60
+ huge : float
61
+ Same as `xmax`.
62
+ precision : float
63
+ ``- int(-log10(eps))``
64
+ resolution : float
65
+ ``- 10**(-precision)``
66
+ smallest_normal : float
67
+ The smallest positive floating point number with 1 as leading bit in
68
+ the mantissa following IEEE-754. Same as `xmin`.
69
+ smallest_subnormal : float
70
+ The smallest positive floating point number with 0 as leading bit in
71
+ the mantissa following IEEE-754.
72
+
73
+ Parameters
74
+ ----------
75
+ float_conv : function, optional
76
+ Function that converts an integer or integer array to a float
77
+ or float array. Default is `float`.
78
+ int_conv : function, optional
79
+ Function that converts a float or float array to an integer or
80
+ integer array. Default is `int`.
81
+ float_to_float : function, optional
82
+ Function that converts a float array to float. Default is `float`.
83
+ Note that this does not seem to do anything useful in the current
84
+ implementation.
85
+ float_to_str : function, optional
86
+ Function that converts a single float to a string. Default is
87
+ ``lambda v:'%24.16e' %v``.
88
+ title : str, optional
89
+ Title that is printed in the string representation of `MachAr`.
90
+
91
+ See Also
92
+ --------
93
+ finfo : Machine limits for floating point types.
94
+ iinfo : Machine limits for integer types.
95
+
96
+ References
97
+ ----------
98
+ .. [1] Press, Teukolsky, Vetterling and Flannery,
99
+ "Numerical Recipes in C++," 2nd ed,
100
+ Cambridge University Press, 2002, p. 31.
101
+
102
+ """
103
+
104
+ def __init__(self, float_conv=float,int_conv=int,
105
+ float_to_float=float,
106
+ float_to_str=lambda v:'%24.16e' % v,
107
+ title='Python floating point number'):
108
+ """
109
+
110
+ float_conv - convert integer to float (array)
111
+ int_conv - convert float (array) to integer
112
+ float_to_float - convert float array to float
113
+ float_to_str - convert array float to str
114
+ title - description of used floating point numbers
115
+
116
+ """
117
+ # We ignore all errors here because we are purposely triggering
118
+ # underflow to detect the properties of the running arch.
119
+ with errstate(under='ignore'):
120
+ self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)
121
+
122
+ def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title):
123
+ max_iterN = 10000
124
+ msg = "Did not converge after %d tries with %s"
125
+ one = float_conv(1)
126
+ two = one + one
127
+ zero = one - one
128
+
129
+ # Do we really need to do this? Aren't they 2 and 2.0?
130
+ # Determine ibeta and beta
131
+ a = one
132
+ for _ in range(max_iterN):
133
+ a = a + a
134
+ temp = a + one
135
+ temp1 = temp - a
136
+ if any(temp1 - one != zero):
137
+ break
138
+ else:
139
+ raise RuntimeError(msg % (_, one.dtype))
140
+ b = one
141
+ for _ in range(max_iterN):
142
+ b = b + b
143
+ temp = a + b
144
+ itemp = int_conv(temp-a)
145
+ if any(itemp != 0):
146
+ break
147
+ else:
148
+ raise RuntimeError(msg % (_, one.dtype))
149
+ ibeta = itemp
150
+ beta = float_conv(ibeta)
151
+
152
+ # Determine it and irnd
153
+ it = -1
154
+ b = one
155
+ for _ in range(max_iterN):
156
+ it = it + 1
157
+ b = b * beta
158
+ temp = b + one
159
+ temp1 = temp - b
160
+ if any(temp1 - one != zero):
161
+ break
162
+ else:
163
+ raise RuntimeError(msg % (_, one.dtype))
164
+
165
+ betah = beta / two
166
+ a = one
167
+ for _ in range(max_iterN):
168
+ a = a + a
169
+ temp = a + one
170
+ temp1 = temp - a
171
+ if any(temp1 - one != zero):
172
+ break
173
+ else:
174
+ raise RuntimeError(msg % (_, one.dtype))
175
+ temp = a + betah
176
+ irnd = 0
177
+ if any(temp-a != zero):
178
+ irnd = 1
179
+ tempa = a + beta
180
+ temp = tempa + betah
181
+ if irnd == 0 and any(temp-tempa != zero):
182
+ irnd = 2
183
+
184
+ # Determine negep and epsneg
185
+ negep = it + 3
186
+ betain = one / beta
187
+ a = one
188
+ for i in range(negep):
189
+ a = a * betain
190
+ b = a
191
+ for _ in range(max_iterN):
192
+ temp = one - a
193
+ if any(temp-one != zero):
194
+ break
195
+ a = a * beta
196
+ negep = negep - 1
197
+ # Prevent infinite loop on PPC with gcc 4.0:
198
+ if negep < 0:
199
+ raise RuntimeError("could not determine machine tolerance "
200
+ "for 'negep', locals() -> %s" % (locals()))
201
+ else:
202
+ raise RuntimeError(msg % (_, one.dtype))
203
+ negep = -negep
204
+ epsneg = a
205
+
206
+ # Determine machep and eps
207
+ machep = - it - 3
208
+ a = b
209
+
210
+ for _ in range(max_iterN):
211
+ temp = one + a
212
+ if any(temp-one != zero):
213
+ break
214
+ a = a * beta
215
+ machep = machep + 1
216
+ else:
217
+ raise RuntimeError(msg % (_, one.dtype))
218
+ eps = a
219
+
220
+ # Determine ngrd
221
+ ngrd = 0
222
+ temp = one + eps
223
+ if irnd == 0 and any(temp*one - one != zero):
224
+ ngrd = 1
225
+
226
+ # Determine iexp
227
+ i = 0
228
+ k = 1
229
+ z = betain
230
+ t = one + eps
231
+ nxres = 0
232
+ for _ in range(max_iterN):
233
+ y = z
234
+ z = y*y
235
+ a = z*one # Check here for underflow
236
+ temp = z*t
237
+ if any(a+a == zero) or any(abs(z) >= y):
238
+ break
239
+ temp1 = temp * betain
240
+ if any(temp1*beta == z):
241
+ break
242
+ i = i + 1
243
+ k = k + k
244
+ else:
245
+ raise RuntimeError(msg % (_, one.dtype))
246
+ if ibeta != 10:
247
+ iexp = i + 1
248
+ mx = k + k
249
+ else:
250
+ iexp = 2
251
+ iz = ibeta
252
+ while k >= iz:
253
+ iz = iz * ibeta
254
+ iexp = iexp + 1
255
+ mx = iz + iz - 1
256
+
257
+ # Determine minexp and xmin
258
+ for _ in range(max_iterN):
259
+ xmin = y
260
+ y = y * betain
261
+ a = y * one
262
+ temp = y * t
263
+ if any((a + a) != zero) and any(abs(y) < xmin):
264
+ k = k + 1
265
+ temp1 = temp * betain
266
+ if any(temp1*beta == y) and any(temp != y):
267
+ nxres = 3
268
+ xmin = y
269
+ break
270
+ else:
271
+ break
272
+ else:
273
+ raise RuntimeError(msg % (_, one.dtype))
274
+ minexp = -k
275
+
276
+ # Determine maxexp, xmax
277
+ if mx <= k + k - 3 and ibeta != 10:
278
+ mx = mx + mx
279
+ iexp = iexp + 1
280
+ maxexp = mx + minexp
281
+ irnd = irnd + nxres
282
+ if irnd >= 2:
283
+ maxexp = maxexp - 2
284
+ i = maxexp + minexp
285
+ if ibeta == 2 and not i:
286
+ maxexp = maxexp - 1
287
+ if i > 20:
288
+ maxexp = maxexp - 1
289
+ if any(a != y):
290
+ maxexp = maxexp - 2
291
+ xmax = one - epsneg
292
+ if any(xmax*one != xmax):
293
+ xmax = one - beta*epsneg
294
+ xmax = xmax / (xmin*beta*beta*beta)
295
+ i = maxexp + minexp + 3
296
+ for j in range(i):
297
+ if ibeta == 2:
298
+ xmax = xmax + xmax
299
+ else:
300
+ xmax = xmax * beta
301
+
302
+ smallest_subnormal = abs(xmin / beta ** (it))
303
+
304
+ self.ibeta = ibeta
305
+ self.it = it
306
+ self.negep = negep
307
+ self.epsneg = float_to_float(epsneg)
308
+ self._str_epsneg = float_to_str(epsneg)
309
+ self.machep = machep
310
+ self.eps = float_to_float(eps)
311
+ self._str_eps = float_to_str(eps)
312
+ self.ngrd = ngrd
313
+ self.iexp = iexp
314
+ self.minexp = minexp
315
+ self.xmin = float_to_float(xmin)
316
+ self._str_xmin = float_to_str(xmin)
317
+ self.maxexp = maxexp
318
+ self.xmax = float_to_float(xmax)
319
+ self._str_xmax = float_to_str(xmax)
320
+ self.irnd = irnd
321
+
322
+ self.title = title
323
+ # Commonly used parameters
324
+ self.epsilon = self.eps
325
+ self.tiny = self.xmin
326
+ self.huge = self.xmax
327
+ self.smallest_normal = self.xmin
328
+ self._str_smallest_normal = float_to_str(self.xmin)
329
+ self.smallest_subnormal = float_to_float(smallest_subnormal)
330
+ self._str_smallest_subnormal = float_to_str(smallest_subnormal)
331
+
332
+ import math
333
+ self.precision = int(-math.log10(float_to_float(self.eps)))
334
+ ten = two + two + two + two + two
335
+ resolution = ten ** (-self.precision)
336
+ self.resolution = float_to_float(resolution)
337
+ self._str_resolution = float_to_str(resolution)
338
+
339
+ def __str__(self):
340
+ fmt = (
341
+ 'Machine parameters for %(title)s\n'
342
+ '---------------------------------------------------------------------\n'
343
+ 'ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s\n'
344
+ 'machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon)\n'
345
+ 'negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg)\n'
346
+ 'minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny)\n'
347
+ 'maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge)\n'
348
+ 'smallest_normal=%(smallest_normal)s '
349
+ 'smallest_subnormal=%(smallest_subnormal)s\n'
350
+ '---------------------------------------------------------------------\n'
351
+ )
352
+ return fmt % self.__dict__
353
+
354
+
355
+ if __name__ == '__main__':
356
+ print(MachAr())
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_machar.pyi ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, Final, overload
3
+
4
+ from typing_extensions import TypeVar, Unpack
5
+
6
+ import numpy as np
7
+ from numpy import _CastingKind
8
+ from numpy._utils import set_module as set_module
9
+
10
+ ###
11
+
12
+ _T = TypeVar("_T")
13
+ _TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]])
14
+ _ExceptionT = TypeVar("_ExceptionT", bound=Exception)
15
+
16
+ ###
17
+
18
+ class UFuncTypeError(TypeError):
19
+ ufunc: Final[np.ufunc]
20
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
21
+
22
+ class _UFuncNoLoopError(UFuncTypeError):
23
+ dtypes: tuple[np.dtype[Any], ...]
24
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
25
+
26
+ class _UFuncBinaryResolutionError(_UFuncNoLoopError):
27
+ dtypes: tuple[np.dtype[Any], np.dtype[Any]]
28
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
29
+
30
+ class _UFuncCastingError(UFuncTypeError):
31
+ casting: Final[_CastingKind]
32
+ from_: Final[np.dtype[Any]]
33
+ to: Final[np.dtype[Any]]
34
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
35
+
36
+ class _UFuncInputCastingError(_UFuncCastingError):
37
+ in_i: Final[int]
38
+ def __init__(
39
+ self,
40
+ /,
41
+ ufunc: np.ufunc,
42
+ casting: _CastingKind,
43
+ from_: np.dtype[Any],
44
+ to: np.dtype[Any],
45
+ i: int,
46
+ ) -> None: ...
47
+
48
+ class _UFuncOutputCastingError(_UFuncCastingError):
49
+ out_i: Final[int]
50
+ def __init__(
51
+ self,
52
+ /,
53
+ ufunc: np.ufunc,
54
+ casting: _CastingKind,
55
+ from_: np.dtype[Any],
56
+ to: np.dtype[Any],
57
+ i: int,
58
+ ) -> None: ...
59
+
60
+ class _ArrayMemoryError(MemoryError):
61
+ shape: tuple[int, ...]
62
+ dtype: np.dtype[Any]
63
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
64
+ @property
65
+ def _total_size(self) -> int: ...
66
+ @staticmethod
67
+ def _size_to_string(num_bytes: int) -> str: ...
68
+
69
+ @overload
70
+ def _unpack_tuple(tup: tuple[_T]) -> _T: ...
71
+ @overload
72
+ def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
73
+ def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_methods.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Array methods which are called by both the C-code for the method
3
+ and the Python code for the NumPy-namespace function
4
+
5
+ """
6
+ import os
7
+ import pickle
8
+ import warnings
9
+ from contextlib import nullcontext
10
+
11
+ import numpy as np
12
+ from numpy._core import multiarray as mu
13
+ from numpy._core import umath as um
14
+ from numpy._core.multiarray import asanyarray
15
+ from numpy._core import numerictypes as nt
16
+ from numpy._core import _exceptions
17
+ from numpy._globals import _NoValue
18
+
19
+ # save those O(100) nanoseconds!
20
+ bool_dt = mu.dtype("bool")
21
+ umr_maximum = um.maximum.reduce
22
+ umr_minimum = um.minimum.reduce
23
+ umr_sum = um.add.reduce
24
+ umr_prod = um.multiply.reduce
25
+ umr_bitwise_count = um.bitwise_count
26
+ umr_any = um.logical_or.reduce
27
+ umr_all = um.logical_and.reduce
28
+
29
+ # Complex types to -> (2,)float view for fast-path computation in _var()
30
+ _complex_to_float = {
31
+ nt.dtype(nt.csingle) : nt.dtype(nt.single),
32
+ nt.dtype(nt.cdouble) : nt.dtype(nt.double),
33
+ }
34
+ # Special case for windows: ensure double takes precedence
35
+ if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
36
+ _complex_to_float.update({
37
+ nt.dtype(nt.clongdouble) : nt.dtype(nt.longdouble),
38
+ })
39
+
40
+ # avoid keyword arguments to speed up parsing, saves about 15%-20% for very
41
+ # small reductions
42
+ def _amax(a, axis=None, out=None, keepdims=False,
43
+ initial=_NoValue, where=True):
44
+ return umr_maximum(a, axis, None, out, keepdims, initial, where)
45
+
46
+ def _amin(a, axis=None, out=None, keepdims=False,
47
+ initial=_NoValue, where=True):
48
+ return umr_minimum(a, axis, None, out, keepdims, initial, where)
49
+
50
+ def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
51
+ initial=_NoValue, where=True):
52
+ return umr_sum(a, axis, dtype, out, keepdims, initial, where)
53
+
54
+ def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
55
+ initial=_NoValue, where=True):
56
+ return umr_prod(a, axis, dtype, out, keepdims, initial, where)
57
+
58
+ def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
59
+ # By default, return a boolean for any and all
60
+ if dtype is None:
61
+ dtype = bool_dt
62
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
63
+ if where is True:
64
+ return umr_any(a, axis, dtype, out, keepdims)
65
+ return umr_any(a, axis, dtype, out, keepdims, where=where)
66
+
67
+ def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
68
+ # By default, return a boolean for any and all
69
+ if dtype is None:
70
+ dtype = bool_dt
71
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
72
+ if where is True:
73
+ return umr_all(a, axis, dtype, out, keepdims)
74
+ return umr_all(a, axis, dtype, out, keepdims, where=where)
75
+
76
+ def _count_reduce_items(arr, axis, keepdims=False, where=True):
77
+ # fast-path for the default case
78
+ if where is True:
79
+ # no boolean mask given, calculate items according to axis
80
+ if axis is None:
81
+ axis = tuple(range(arr.ndim))
82
+ elif not isinstance(axis, tuple):
83
+ axis = (axis,)
84
+ items = 1
85
+ for ax in axis:
86
+ items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
87
+ items = nt.intp(items)
88
+ else:
89
+ # TODO: Optimize case when `where` is broadcast along a non-reduction
90
+ # axis and full sum is more excessive than needed.
91
+
92
+ # guarded to protect circular imports
93
+ from numpy.lib._stride_tricks_impl import broadcast_to
94
+ # count True values in (potentially broadcasted) boolean mask
95
+ items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
96
+ keepdims)
97
+ return items
98
+
99
+ def _clip(a, min=None, max=None, out=None, **kwargs):
100
+ if a.dtype.kind in "iu":
101
+ # If min/max is a Python integer, deal with out-of-bound values here.
102
+ # (This enforces NEP 50 rules as no value based promotion is done.)
103
+ if type(min) is int and min <= np.iinfo(a.dtype).min:
104
+ min = None
105
+ if type(max) is int and max >= np.iinfo(a.dtype).max:
106
+ max = None
107
+
108
+ if min is None and max is None:
109
+ # return identity
110
+ return um.positive(a, out=out, **kwargs)
111
+ elif min is None:
112
+ return um.minimum(a, max, out=out, **kwargs)
113
+ elif max is None:
114
+ return um.maximum(a, min, out=out, **kwargs)
115
+ else:
116
+ return um.clip(a, min, max, out=out, **kwargs)
117
+
118
+ def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
119
+ arr = asanyarray(a)
120
+
121
+ is_float16_result = False
122
+
123
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
124
+ if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
125
+ warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
126
+
127
+ # Cast bool, unsigned int, and int to float64 by default
128
+ if dtype is None:
129
+ if issubclass(arr.dtype.type, (nt.integer, nt.bool)):
130
+ dtype = mu.dtype('f8')
131
+ elif issubclass(arr.dtype.type, nt.float16):
132
+ dtype = mu.dtype('f4')
133
+ is_float16_result = True
134
+
135
+ ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
136
+ if isinstance(ret, mu.ndarray):
137
+ ret = um.true_divide(
138
+ ret, rcount, out=ret, casting='unsafe', subok=False)
139
+ if is_float16_result and out is None:
140
+ ret = arr.dtype.type(ret)
141
+ elif hasattr(ret, 'dtype'):
142
+ if is_float16_result:
143
+ ret = arr.dtype.type(ret / rcount)
144
+ else:
145
+ ret = ret.dtype.type(ret / rcount)
146
+ else:
147
+ ret = ret / rcount
148
+
149
+ return ret
150
+
151
+ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
152
+ where=True, mean=None):
153
+ arr = asanyarray(a)
154
+
155
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
156
+ # Make this warning show up on top.
157
+ if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
158
+ warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
159
+ stacklevel=2)
160
+
161
+ # Cast bool, unsigned int, and int to float64 by default
162
+ if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool)):
163
+ dtype = mu.dtype('f8')
164
+
165
+ if mean is not None:
166
+ arrmean = mean
167
+ else:
168
+ # Compute the mean.
169
+ # Note that if dtype is not of inexact type then arraymean will
170
+ # not be either.
171
+ arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
172
+ # The shape of rcount has to match arrmean to not change the shape of
173
+ # out in broadcasting. Otherwise, it cannot be stored back to arrmean.
174
+ if rcount.ndim == 0:
175
+ # fast-path for default case when where is True
176
+ div = rcount
177
+ else:
178
+ # matching rcount to arrmean when where is specified as array
179
+ div = rcount.reshape(arrmean.shape)
180
+ if isinstance(arrmean, mu.ndarray):
181
+ arrmean = um.true_divide(arrmean, div, out=arrmean,
182
+ casting='unsafe', subok=False)
183
+ elif hasattr(arrmean, "dtype"):
184
+ arrmean = arrmean.dtype.type(arrmean / rcount)
185
+ else:
186
+ arrmean = arrmean / rcount
187
+
188
+ # Compute sum of squared deviations from mean
189
+ # Note that x may not be inexact and that we need it to be an array,
190
+ # not a scalar.
191
+ x = asanyarray(arr - arrmean)
192
+
193
+ if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
194
+ x = um.multiply(x, x, out=x)
195
+ # Fast-paths for built-in complex types
196
+ elif x.dtype in _complex_to_float:
197
+ xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
198
+ um.multiply(xv, xv, out=xv)
199
+ x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
200
+ # Most general case; includes handling object arrays containing imaginary
201
+ # numbers and complex types with non-native byteorder
202
+ else:
203
+ x = um.multiply(x, um.conjugate(x), out=x).real
204
+
205
+ ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
206
+
207
+ # Compute degrees of freedom and make sure it is not negative.
208
+ rcount = um.maximum(rcount - ddof, 0)
209
+
210
+ # divide by degrees of freedom
211
+ if isinstance(ret, mu.ndarray):
212
+ ret = um.true_divide(
213
+ ret, rcount, out=ret, casting='unsafe', subok=False)
214
+ elif hasattr(ret, 'dtype'):
215
+ ret = ret.dtype.type(ret / rcount)
216
+ else:
217
+ ret = ret / rcount
218
+
219
+ return ret
220
+
221
+ def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
222
+ where=True, mean=None):
223
+ ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
224
+ keepdims=keepdims, where=where, mean=mean)
225
+
226
+ if isinstance(ret, mu.ndarray):
227
+ ret = um.sqrt(ret, out=ret)
228
+ elif hasattr(ret, 'dtype'):
229
+ ret = ret.dtype.type(um.sqrt(ret))
230
+ else:
231
+ ret = um.sqrt(ret)
232
+
233
+ return ret
234
+
235
+ def _ptp(a, axis=None, out=None, keepdims=False):
236
+ return um.subtract(
237
+ umr_maximum(a, axis, None, out, keepdims),
238
+ umr_minimum(a, axis, None, None, keepdims),
239
+ out
240
+ )
241
+
242
+ def _dump(self, file, protocol=2):
243
+ if hasattr(file, 'write'):
244
+ ctx = nullcontext(file)
245
+ else:
246
+ ctx = open(os.fspath(file), "wb")
247
+ with ctx as f:
248
+ pickle.dump(self, f, protocol=protocol)
249
+
250
+ def _dumps(self, protocol=2):
251
+ return pickle.dumps(self, protocol=protocol)
252
+
253
+ def _bitwise_count(a, out=None, *, where=True, casting='same_kind',
254
+ order='K', dtype=None, subok=True):
255
+ return umr_bitwise_count(a, out, where=where, casting=casting,
256
+ order=order, dtype=dtype, subok=subok)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_methods.pyi ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, TypeAlias
3
+
4
+ from typing_extensions import Concatenate
5
+
6
+ import numpy as np
7
+
8
+ from . import _exceptions as _exceptions
9
+
10
+ ###
11
+
12
+ _Reduce2: TypeAlias = Callable[Concatenate[object, ...], Any]
13
+
14
+ ###
15
+
16
+ bool_dt: np.dtype[np.bool] = ...
17
+ umr_maximum: _Reduce2 = ...
18
+ umr_minimum: _Reduce2 = ...
19
+ umr_sum: _Reduce2 = ...
20
+ umr_prod: _Reduce2 = ...
21
+ umr_bitwise_count = np.bitwise_count
22
+ umr_any: _Reduce2 = ...
23
+ umr_all: _Reduce2 = ...
24
+ _complex_to_float: dict[np.dtype[np.complexfloating], np.dtype[np.floating]] = ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (17 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (59.8 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_simd.pyi ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import TypedDict, type_check_only
3
+
4
+ # NOTE: these 5 are only defined on systems with an intel processor
5
+ SSE42: ModuleType | None = ...
6
+ FMA3: ModuleType | None = ...
7
+ AVX2: ModuleType | None = ...
8
+ AVX512F: ModuleType | None = ...
9
+ AVX512_SKX: ModuleType | None = ...
10
+
11
+ baseline: ModuleType | None = ...
12
+
13
+ @type_check_only
14
+ class SimdTargets(TypedDict):
15
+ SSE42: ModuleType | None
16
+ AVX2: ModuleType | None
17
+ FMA3: ModuleType | None
18
+ AVX512F: ModuleType | None
19
+ AVX512_SKX: ModuleType | None
20
+ baseline: ModuleType | None
21
+
22
+ targets: SimdTargets = ...
23
+
24
+ def clear_floatstatus() -> None: ...
25
+ def get_floatstatus() -> int: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_string_helpers.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ String-handling utilities to avoid locale-dependence.
3
+
4
+ Used primarily to generate type name aliases.
5
+ """
6
+ # "import string" is costly to import!
7
+ # Construct the translation tables directly
8
+ # "A" = chr(65), "a" = chr(97)
9
+ _all_chars = tuple(map(chr, range(256)))
10
+ _ascii_upper = _all_chars[65:65+26]
11
+ _ascii_lower = _all_chars[97:97+26]
12
+ LOWER_TABLE = _all_chars[:65] + _ascii_lower + _all_chars[65+26:]
13
+ UPPER_TABLE = _all_chars[:97] + _ascii_upper + _all_chars[97+26:]
14
+
15
+
16
+ def english_lower(s):
17
+ """ Apply English case rules to convert ASCII strings to all lower case.
18
+
19
+ This is an internal utility function to replace calls to str.lower() such
20
+ that we can avoid changing behavior with changing locales. In particular,
21
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
22
+ both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale.
23
+
24
+ Parameters
25
+ ----------
26
+ s : str
27
+
28
+ Returns
29
+ -------
30
+ lowered : str
31
+
32
+ Examples
33
+ --------
34
+ >>> from numpy._core.numerictypes import english_lower
35
+ >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
36
+ 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'
37
+ >>> english_lower('')
38
+ ''
39
+ """
40
+ lowered = s.translate(LOWER_TABLE)
41
+ return lowered
42
+
43
+
44
+ def english_upper(s):
45
+ """ Apply English case rules to convert ASCII strings to all upper case.
46
+
47
+ This is an internal utility function to replace calls to str.upper() such
48
+ that we can avoid changing behavior with changing locales. In particular,
49
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
50
+ both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale.
51
+
52
+ Parameters
53
+ ----------
54
+ s : str
55
+
56
+ Returns
57
+ -------
58
+ uppered : str
59
+
60
+ Examples
61
+ --------
62
+ >>> from numpy._core.numerictypes import english_upper
63
+ >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
64
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
65
+ >>> english_upper('')
66
+ ''
67
+ """
68
+ uppered = s.translate(UPPER_TABLE)
69
+ return uppered
70
+
71
+
72
+ def english_capitalize(s):
73
+ """ Apply English case rules to convert the first character of an ASCII
74
+ string to upper case.
75
+
76
+ This is an internal utility function to replace calls to str.capitalize()
77
+ such that we can avoid changing behavior with changing locales.
78
+
79
+ Parameters
80
+ ----------
81
+ s : str
82
+
83
+ Returns
84
+ -------
85
+ capitalized : str
86
+
87
+ Examples
88
+ --------
89
+ >>> from numpy._core.numerictypes import english_capitalize
90
+ >>> english_capitalize('int8')
91
+ 'Int8'
92
+ >>> english_capitalize('Int8')
93
+ 'Int8'
94
+ >>> english_capitalize('')
95
+ ''
96
+ """
97
+ if s:
98
+ return english_upper(s[0]) + s[1:]
99
+ else:
100
+ return s
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_string_helpers.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Final
2
+
3
+ _all_chars: Final[tuple[str, ...]] = ...
4
+ _ascii_upper: Final[tuple[str, ...]] = ...
5
+ _ascii_lower: Final[tuple[str, ...]] = ...
6
+
7
+ LOWER_TABLE: Final[tuple[str, ...]] = ...
8
+ UPPER_TABLE: Final[tuple[str, ...]] = ...
9
+
10
+ def english_lower(s: str) -> str: ...
11
+ def english_upper(s: str) -> str: ...
12
+ def english_capitalize(s: str) -> str: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (17.1 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_type_aliases.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Due to compatibility, numpy has a very large number of different naming
3
+ conventions for the scalar types (those subclassing from `numpy.generic`).
4
+ This file produces a convoluted set of dictionaries mapping names to types,
5
+ and sometimes other mappings too.
6
+
7
+ .. data:: allTypes
8
+ A dictionary of names to types that will be exposed as attributes through
9
+ ``np._core.numerictypes.*``
10
+
11
+ .. data:: sctypeDict
12
+ Similar to `allTypes`, but maps a broader set of aliases to their types.
13
+
14
+ .. data:: sctypes
15
+ A dictionary keyed by a "type group" string, providing a list of types
16
+ under that group.
17
+
18
+ """
19
+
20
+ import numpy._core.multiarray as ma
21
+ from numpy._core.multiarray import typeinfo, dtype
22
+
23
+ ######################################
24
+ # Building `sctypeDict` and `allTypes`
25
+ ######################################
26
+
27
+ sctypeDict = {}
28
+ allTypes = {}
29
+ c_names_dict = {}
30
+
31
+ _abstract_type_names = {
32
+ "generic", "integer", "inexact", "floating", "number",
33
+ "flexible", "character", "complexfloating", "unsignedinteger",
34
+ "signedinteger"
35
+ }
36
+
37
+ for _abstract_type_name in _abstract_type_names:
38
+ allTypes[_abstract_type_name] = getattr(ma, _abstract_type_name)
39
+
40
+ for k, v in typeinfo.items():
41
+ if k.startswith("NPY_") and v not in c_names_dict:
42
+ c_names_dict[k[4:]] = v
43
+ else:
44
+ concrete_type = v.type
45
+ allTypes[k] = concrete_type
46
+ sctypeDict[k] = concrete_type
47
+
48
+ _aliases = {
49
+ "double": "float64",
50
+ "cdouble": "complex128",
51
+ "single": "float32",
52
+ "csingle": "complex64",
53
+ "half": "float16",
54
+ "bool_": "bool",
55
+ # Default integer:
56
+ "int_": "intp",
57
+ "uint": "uintp",
58
+ }
59
+
60
+ for k, v in _aliases.items():
61
+ sctypeDict[k] = allTypes[v]
62
+ allTypes[k] = allTypes[v]
63
+
64
+ # extra aliases are added only to `sctypeDict`
65
+ # to support dtype name access, such as`np.dtype("float")`
66
+ _extra_aliases = {
67
+ "float": "float64",
68
+ "complex": "complex128",
69
+ "object": "object_",
70
+ "bytes": "bytes_",
71
+ "a": "bytes_",
72
+ "int": "int_",
73
+ "str": "str_",
74
+ "unicode": "str_",
75
+ }
76
+
77
+ for k, v in _extra_aliases.items():
78
+ sctypeDict[k] = allTypes[v]
79
+
80
+ # include extended precision sized aliases
81
+ for is_complex, full_name in [(False, "longdouble"), (True, "clongdouble")]:
82
+ longdouble_type: type = allTypes[full_name]
83
+
84
+ bits: int = dtype(longdouble_type).itemsize * 8
85
+ base_name: str = "complex" if is_complex else "float"
86
+ extended_prec_name: str = f"{base_name}{bits}"
87
+ if extended_prec_name not in allTypes:
88
+ sctypeDict[extended_prec_name] = longdouble_type
89
+ allTypes[extended_prec_name] = longdouble_type
90
+
91
+
92
+ ####################
93
+ # Building `sctypes`
94
+ ####################
95
+
96
+ sctypes = {"int": set(), "uint": set(), "float": set(),
97
+ "complex": set(), "others": set()}
98
+
99
+ for type_info in typeinfo.values():
100
+ if type_info.kind in ["M", "m"]: # exclude timedelta and datetime
101
+ continue
102
+
103
+ concrete_type = type_info.type
104
+
105
+ # find proper group for each concrete type
106
+ for type_group, abstract_type in [
107
+ ("int", ma.signedinteger), ("uint", ma.unsignedinteger),
108
+ ("float", ma.floating), ("complex", ma.complexfloating),
109
+ ("others", ma.generic)
110
+ ]:
111
+ if issubclass(concrete_type, abstract_type):
112
+ sctypes[type_group].add(concrete_type)
113
+ break
114
+
115
+ # sort sctype groups by bitsize
116
+ for sctype_key in sctypes.keys():
117
+ sctype_list = list(sctypes[sctype_key])
118
+ sctype_list.sort(key=lambda x: dtype(x).itemsize)
119
+ sctypes[sctype_key] = sctype_list
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_type_aliases.pyi ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Collection
2
+ from typing import Any, Final, Literal as L, TypeAlias, TypedDict, type_check_only
3
+
4
+ import numpy as np
5
+
6
+ __all__ = (
7
+ "_abstract_type_names",
8
+ "_aliases",
9
+ "_extra_aliases",
10
+ "allTypes",
11
+ "c_names_dict",
12
+ "sctypeDict",
13
+ "sctypes",
14
+ )
15
+
16
+ sctypeDict: Final[dict[str, type[np.generic]]]
17
+ allTypes: Final[dict[str, type[np.generic]]]
18
+
19
+ @type_check_only
20
+ class _CNamesDict(TypedDict):
21
+ BOOL: np.dtype[np.bool]
22
+ HALF: np.dtype[np.half]
23
+ FLOAT: np.dtype[np.single]
24
+ DOUBLE: np.dtype[np.double]
25
+ LONGDOUBLE: np.dtype[np.longdouble]
26
+ CFLOAT: np.dtype[np.csingle]
27
+ CDOUBLE: np.dtype[np.cdouble]
28
+ CLONGDOUBLE: np.dtype[np.clongdouble]
29
+ STRING: np.dtype[np.bytes_]
30
+ UNICODE: np.dtype[np.str_]
31
+ VOID: np.dtype[np.void]
32
+ OBJECT: np.dtype[np.object_]
33
+ DATETIME: np.dtype[np.datetime64]
34
+ TIMEDELTA: np.dtype[np.timedelta64]
35
+ BYTE: np.dtype[np.byte]
36
+ UBYTE: np.dtype[np.ubyte]
37
+ SHORT: np.dtype[np.short]
38
+ USHORT: np.dtype[np.ushort]
39
+ INT: np.dtype[np.intc]
40
+ UINT: np.dtype[np.uintc]
41
+ LONG: np.dtype[np.long]
42
+ ULONG: np.dtype[np.ulong]
43
+ LONGLONG: np.dtype[np.longlong]
44
+ ULONGLONG: np.dtype[np.ulonglong]
45
+
46
+ c_names_dict: Final[_CNamesDict]
47
+
48
+ _AbstractTypeName: TypeAlias = L[
49
+ "generic",
50
+ "flexible",
51
+ "character",
52
+ "number",
53
+ "integer",
54
+ "inexact",
55
+ "unsignedinteger",
56
+ "signedinteger",
57
+ "floating",
58
+ "complexfloating",
59
+ ]
60
+ _abstract_type_names: Final[set[_AbstractTypeName]]
61
+
62
+ @type_check_only
63
+ class _AliasesType(TypedDict):
64
+ double: L["float64"]
65
+ cdouble: L["complex128"]
66
+ single: L["float32"]
67
+ csingle: L["complex64"]
68
+ half: L["float16"]
69
+ bool_: L["bool"]
70
+ int_: L["intp"]
71
+ uint: L["intp"]
72
+
73
+ _aliases: Final[_AliasesType]
74
+
75
+ @type_check_only
76
+ class _ExtraAliasesType(TypedDict):
77
+ float: L["float64"]
78
+ complex: L["complex128"]
79
+ object: L["object_"]
80
+ bytes: L["bytes_"]
81
+ a: L["bytes_"]
82
+ int: L["int_"]
83
+ str: L["str_"]
84
+ unicode: L["str_"]
85
+
86
+ _extra_aliases: Final[_ExtraAliasesType]
87
+
88
+ @type_check_only
89
+ class _SCTypes(TypedDict):
90
+ int: Collection[type[np.signedinteger[Any]]]
91
+ uint: Collection[type[np.unsignedinteger[Any]]]
92
+ float: Collection[type[np.floating[Any]]]
93
+ complex: Collection[type[np.complexfloating[Any, Any]]]
94
+ others: Collection[type[np.flexible | np.bool | np.object_]]
95
+
96
+ sctypes: Final[_SCTypes]
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_ufunc_config.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions for changing global ufunc configuration
3
+
4
+ This provides helpers which wrap `_get_extobj_dict` and `_make_extobj`, and
5
+ `_extobj_contextvar` from umath.
6
+ """
7
+ import contextlib
8
+ import contextvars
9
+ import functools
10
+
11
+ from .._utils import set_module
12
+ from .umath import _make_extobj, _get_extobj_dict, _extobj_contextvar
13
+
14
+ __all__ = [
15
+ "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
16
+ "errstate"
17
+ ]
18
+
19
+
20
+ @set_module('numpy')
21
+ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
22
+ """
23
+ Set how floating-point errors are handled.
24
+
25
+ Note that operations on integer scalar types (such as `int16`) are
26
+ handled like floating point, and are affected by these settings.
27
+
28
+ Parameters
29
+ ----------
30
+ all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
31
+ Set treatment for all types of floating-point errors at once:
32
+
33
+ - ignore: Take no action when the exception occurs.
34
+ - warn: Print a :exc:`RuntimeWarning` (via the Python `warnings`
35
+ module).
36
+ - raise: Raise a :exc:`FloatingPointError`.
37
+ - call: Call a function specified using the `seterrcall` function.
38
+ - print: Print a warning directly to ``stdout``.
39
+ - log: Record error in a Log object specified by `seterrcall`.
40
+
41
+ The default is not to change the current behavior.
42
+ divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
43
+ Treatment for division by zero.
44
+ over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
45
+ Treatment for floating-point overflow.
46
+ under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
47
+ Treatment for floating-point underflow.
48
+ invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
49
+ Treatment for invalid floating-point operation.
50
+
51
+ Returns
52
+ -------
53
+ old_settings : dict
54
+ Dictionary containing the old settings.
55
+
56
+ See also
57
+ --------
58
+ seterrcall : Set a callback function for the 'call' mode.
59
+ geterr, geterrcall, errstate
60
+
61
+ Notes
62
+ -----
63
+ The floating-point exceptions are defined in the IEEE 754 standard [1]_:
64
+
65
+ - Division by zero: infinite result obtained from finite numbers.
66
+ - Overflow: result too large to be expressed.
67
+ - Underflow: result so close to zero that some precision
68
+ was lost.
69
+ - Invalid operation: result is not an expressible number, typically
70
+ indicates that a NaN was produced.
71
+
72
+ .. [1] https://en.wikipedia.org/wiki/IEEE_754
73
+
74
+ Examples
75
+ --------
76
+ >>> import numpy as np
77
+ >>> orig_settings = np.seterr(all='ignore') # seterr to known value
78
+ >>> np.int16(32000) * np.int16(3)
79
+ np.int16(30464)
80
+ >>> np.seterr(over='raise')
81
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
82
+ >>> old_settings = np.seterr(all='warn', over='raise')
83
+ >>> np.int16(32000) * np.int16(3)
84
+ Traceback (most recent call last):
85
+ File "<stdin>", line 1, in <module>
86
+ FloatingPointError: overflow encountered in scalar multiply
87
+
88
+ >>> old_settings = np.seterr(all='print')
89
+ >>> np.geterr()
90
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
91
+ >>> np.int16(32000) * np.int16(3)
92
+ np.int16(30464)
93
+ >>> np.seterr(**orig_settings) # restore original
94
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
95
+
96
+ """
97
+
98
+ old = _get_extobj_dict()
99
+ # The errstate doesn't include call and bufsize, so pop them:
100
+ old.pop("call", None)
101
+ old.pop("bufsize", None)
102
+
103
+ extobj = _make_extobj(
104
+ all=all, divide=divide, over=over, under=under, invalid=invalid)
105
+ _extobj_contextvar.set(extobj)
106
+ return old
107
+
108
+
109
+ @set_module('numpy')
110
+ def geterr():
111
+ """
112
+ Get the current way of handling floating-point errors.
113
+
114
+ Returns
115
+ -------
116
+ res : dict
117
+ A dictionary with keys "divide", "over", "under", and "invalid",
118
+ whose values are from the strings "ignore", "print", "log", "warn",
119
+ "raise", and "call". The keys represent possible floating-point
120
+ exceptions, and the values define how these exceptions are handled.
121
+
122
+ See Also
123
+ --------
124
+ geterrcall, seterr, seterrcall
125
+
126
+ Notes
127
+ -----
128
+ For complete documentation of the types of floating-point exceptions and
129
+ treatment options, see `seterr`.
130
+
131
+ Examples
132
+ --------
133
+ >>> import numpy as np
134
+ >>> np.geterr()
135
+ {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
136
+ >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP
137
+ array([nan, 1., 1.])
138
+ RuntimeWarning: invalid value encountered in divide
139
+
140
+ >>> oldsettings = np.seterr(all='warn', invalid='raise')
141
+ >>> np.geterr()
142
+ {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'}
143
+ >>> np.arange(3.) / np.arange(3.)
144
+ Traceback (most recent call last):
145
+ ...
146
+ FloatingPointError: invalid value encountered in divide
147
+ >>> oldsettings = np.seterr(**oldsettings) # restore original
148
+
149
+ """
150
+ res = _get_extobj_dict()
151
+ # The "geterr" doesn't include call and bufsize,:
152
+ res.pop("call", None)
153
+ res.pop("bufsize", None)
154
+ return res
155
+
156
+
157
+ @set_module('numpy')
158
+ def setbufsize(size):
159
+ """
160
+ Set the size of the buffer used in ufuncs.
161
+
162
+ .. versionchanged:: 2.0
163
+ The scope of setting the buffer is tied to the `numpy.errstate`
164
+ context. Exiting a ``with errstate():`` will also restore the bufsize.
165
+
166
+ Parameters
167
+ ----------
168
+ size : int
169
+ Size of buffer.
170
+
171
+ Returns
172
+ -------
173
+ bufsize : int
174
+ Previous size of ufunc buffer in bytes.
175
+
176
+ Examples
177
+ --------
178
+ When exiting a `numpy.errstate` context manager the bufsize is restored:
179
+
180
+ >>> import numpy as np
181
+ >>> with np.errstate():
182
+ ... np.setbufsize(4096)
183
+ ... print(np.getbufsize())
184
+ ...
185
+ 8192
186
+ 4096
187
+ >>> np.getbufsize()
188
+ 8192
189
+
190
+ """
191
+ old = _get_extobj_dict()["bufsize"]
192
+ extobj = _make_extobj(bufsize=size)
193
+ _extobj_contextvar.set(extobj)
194
+ return old
195
+
196
+
197
+ @set_module('numpy')
198
+ def getbufsize():
199
+ """
200
+ Return the size of the buffer used in ufuncs.
201
+
202
+ Returns
203
+ -------
204
+ getbufsize : int
205
+ Size of ufunc buffer in bytes.
206
+
207
+ Examples
208
+ --------
209
+ >>> import numpy as np
210
+ >>> np.getbufsize()
211
+ 8192
212
+
213
+ """
214
+ return _get_extobj_dict()["bufsize"]
215
+
216
+
217
+ @set_module('numpy')
218
+ def seterrcall(func):
219
+ """
220
+ Set the floating-point error callback function or log object.
221
+
222
+ There are two ways to capture floating-point error messages. The first
223
+ is to set the error-handler to 'call', using `seterr`. Then, set
224
+ the function to call using this function.
225
+
226
+ The second is to set the error-handler to 'log', using `seterr`.
227
+ Floating-point errors then trigger a call to the 'write' method of
228
+ the provided object.
229
+
230
+ Parameters
231
+ ----------
232
+ func : callable f(err, flag) or object with write method
233
+ Function to call upon floating-point errors ('call'-mode) or
234
+ object whose 'write' method is used to log such message ('log'-mode).
235
+
236
+ The call function takes two arguments. The first is a string describing
237
+ the type of error (such as "divide by zero", "overflow", "underflow",
238
+ or "invalid value"), and the second is the status flag. The flag is a
239
+ byte, whose four least-significant bits indicate the type of error, one
240
+ of "divide", "over", "under", "invalid"::
241
+
242
+ [0 0 0 0 divide over under invalid]
243
+
244
+ In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
245
+
246
+ If an object is provided, its write method should take one argument,
247
+ a string.
248
+
249
+ Returns
250
+ -------
251
+ h : callable, log instance or None
252
+ The old error handler.
253
+
254
+ See Also
255
+ --------
256
+ seterr, geterr, geterrcall
257
+
258
+ Examples
259
+ --------
260
+ Callback upon error:
261
+
262
+ >>> def err_handler(type, flag):
263
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
264
+ ...
265
+
266
+ >>> import numpy as np
267
+
268
+ >>> orig_handler = np.seterrcall(err_handler)
269
+ >>> orig_err = np.seterr(all='call')
270
+
271
+ >>> np.array([1, 2, 3]) / 0.0
272
+ Floating point error (divide by zero), with flag 1
273
+ array([inf, inf, inf])
274
+
275
+ >>> np.seterrcall(orig_handler)
276
+ <function err_handler at 0x...>
277
+ >>> np.seterr(**orig_err)
278
+ {'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
279
+
280
+ Log error message:
281
+
282
+ >>> class Log:
283
+ ... def write(self, msg):
284
+ ... print("LOG: %s" % msg)
285
+ ...
286
+
287
+ >>> log = Log()
288
+ >>> saved_handler = np.seterrcall(log)
289
+ >>> save_err = np.seterr(all='log')
290
+
291
+ >>> np.array([1, 2, 3]) / 0.0
292
+ LOG: Warning: divide by zero encountered in divide
293
+ array([inf, inf, inf])
294
+
295
+ >>> np.seterrcall(orig_handler)
296
+ <numpy.Log object at 0x...>
297
+ >>> np.seterr(**orig_err)
298
+ {'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
299
+
300
+ """
301
+ old = _get_extobj_dict()["call"]
302
+ extobj = _make_extobj(call=func)
303
+ _extobj_contextvar.set(extobj)
304
+ return old
305
+
306
+
307
+ @set_module('numpy')
308
+ def geterrcall():
309
+ """
310
+ Return the current callback function used on floating-point errors.
311
+
312
+ When the error handling for a floating-point error (one of "divide",
313
+ "over", "under", or "invalid") is set to 'call' or 'log', the function
314
+ that is called or the log instance that is written to is returned by
315
+ `geterrcall`. This function or log instance has been set with
316
+ `seterrcall`.
317
+
318
+ Returns
319
+ -------
320
+ errobj : callable, log instance or None
321
+ The current error handler. If no handler was set through `seterrcall`,
322
+ ``None`` is returned.
323
+
324
+ See Also
325
+ --------
326
+ seterrcall, seterr, geterr
327
+
328
+ Notes
329
+ -----
330
+ For complete documentation of the types of floating-point exceptions and
331
+ treatment options, see `seterr`.
332
+
333
+ Examples
334
+ --------
335
+ >>> import numpy as np
336
+ >>> np.geterrcall() # we did not yet set a handler, returns None
337
+
338
+ >>> orig_settings = np.seterr(all='call')
339
+ >>> def err_handler(type, flag):
340
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
341
+ >>> old_handler = np.seterrcall(err_handler)
342
+ >>> np.array([1, 2, 3]) / 0.0
343
+ Floating point error (divide by zero), with flag 1
344
+ array([inf, inf, inf])
345
+
346
+ >>> cur_handler = np.geterrcall()
347
+ >>> cur_handler is err_handler
348
+ True
349
+ >>> old_settings = np.seterr(**orig_settings) # restore original
350
+ >>> old_handler = np.seterrcall(None) # restore original
351
+
352
+ """
353
+ return _get_extobj_dict()["call"]
354
+
355
+
356
+ class _unspecified:
357
+ pass
358
+
359
+
360
+ _Unspecified = _unspecified()
361
+
362
+
363
+ @set_module('numpy')
364
+ class errstate:
365
+ """
366
+ errstate(**kwargs)
367
+
368
+ Context manager for floating-point error handling.
369
+
370
+ Using an instance of `errstate` as a context manager allows statements in
371
+ that context to execute with a known error handling behavior. Upon entering
372
+ the context the error handling is set with `seterr` and `seterrcall`, and
373
+ upon exiting it is reset to what it was before.
374
+
375
+ .. versionchanged:: 1.17.0
376
+ `errstate` is also usable as a function decorator, saving
377
+ a level of indentation if an entire function is wrapped.
378
+
379
+ .. versionchanged:: 2.0
380
+ `errstate` is now fully thread and asyncio safe, but may not be
381
+ entered more than once.
382
+ It is not safe to decorate async functions using ``errstate``.
383
+
384
+ Parameters
385
+ ----------
386
+ kwargs : {divide, over, under, invalid}
387
+ Keyword arguments. The valid keywords are the possible floating-point
388
+ exceptions. Each keyword should have a string value that defines the
389
+ treatment for the particular error. Possible values are
390
+ {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
391
+
392
+ See Also
393
+ --------
394
+ seterr, geterr, seterrcall, geterrcall
395
+
396
+ Notes
397
+ -----
398
+ For complete documentation of the types of floating-point exceptions and
399
+ treatment options, see `seterr`.
400
+
401
+ Examples
402
+ --------
403
+ >>> import numpy as np
404
+ >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
405
+
406
+ >>> np.arange(3) / 0.
407
+ array([nan, inf, inf])
408
+ >>> with np.errstate(divide='ignore'):
409
+ ... np.arange(3) / 0.
410
+ array([nan, inf, inf])
411
+
412
+ >>> np.sqrt(-1)
413
+ np.float64(nan)
414
+ >>> with np.errstate(invalid='raise'):
415
+ ... np.sqrt(-1)
416
+ Traceback (most recent call last):
417
+ File "<stdin>", line 2, in <module>
418
+ FloatingPointError: invalid value encountered in sqrt
419
+
420
+ Outside the context the error handling behavior has not changed:
421
+
422
+ >>> np.geterr()
423
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
424
+ >>> olderr = np.seterr(**olderr) # restore original state
425
+
426
+ """
427
+ __slots__ = (
428
+ "_call", "_all", "_divide", "_over", "_under", "_invalid", "_token")
429
+
430
+ def __init__(self, *, call=_Unspecified,
431
+ all=None, divide=None, over=None, under=None, invalid=None):
432
+ self._token = None
433
+ self._call = call
434
+ self._all = all
435
+ self._divide = divide
436
+ self._over = over
437
+ self._under = under
438
+ self._invalid = invalid
439
+
440
+ def __enter__(self):
441
+ # Note that __call__ duplicates much of this logic
442
+ if self._token is not None:
443
+ raise TypeError("Cannot enter `np.errstate` twice.")
444
+ if self._call is _Unspecified:
445
+ extobj = _make_extobj(
446
+ all=self._all, divide=self._divide, over=self._over,
447
+ under=self._under, invalid=self._invalid)
448
+ else:
449
+ extobj = _make_extobj(
450
+ call=self._call,
451
+ all=self._all, divide=self._divide, over=self._over,
452
+ under=self._under, invalid=self._invalid)
453
+
454
+ self._token = _extobj_contextvar.set(extobj)
455
+
456
+ def __exit__(self, *exc_info):
457
+ _extobj_contextvar.reset(self._token)
458
+
459
+ def __call__(self, func):
460
+ # We need to customize `__call__` compared to `ContextDecorator`
461
+ # because we must store the token per-thread so cannot store it on
462
+ # the instance (we could create a new instance for this).
463
+ # This duplicates the code from `__enter__`.
464
+ @functools.wraps(func)
465
+ def inner(*args, **kwargs):
466
+ if self._call is _Unspecified:
467
+ extobj = _make_extobj(
468
+ all=self._all, divide=self._divide, over=self._over,
469
+ under=self._under, invalid=self._invalid)
470
+ else:
471
+ extobj = _make_extobj(
472
+ call=self._call,
473
+ all=self._all, divide=self._divide, over=self._over,
474
+ under=self._under, invalid=self._invalid)
475
+
476
+ _token = _extobj_contextvar.set(extobj)
477
+ try:
478
+ # Call the original, decorated, function:
479
+ return func(*args, **kwargs)
480
+ finally:
481
+ _extobj_contextvar.reset(_token)
482
+
483
+ return inner
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_ufunc_config.pyi ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import SupportsWrite
2
+ from collections.abc import Callable
3
+ from typing import Any, Literal, TypeAlias, TypedDict, type_check_only
4
+
5
+ from numpy import errstate as errstate
6
+
7
+ _ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
8
+ _ErrFunc: TypeAlias = Callable[[str, int], Any]
9
+ _ErrCall: TypeAlias = _ErrFunc | SupportsWrite[str]
10
+
11
+ @type_check_only
12
+ class _ErrDict(TypedDict):
13
+ divide: _ErrKind
14
+ over: _ErrKind
15
+ under: _ErrKind
16
+ invalid: _ErrKind
17
+
18
+ @type_check_only
19
+ class _ErrDictOptional(TypedDict, total=False):
20
+ all: None | _ErrKind
21
+ divide: None | _ErrKind
22
+ over: None | _ErrKind
23
+ under: None | _ErrKind
24
+ invalid: None | _ErrKind
25
+
26
+ def seterr(
27
+ all: None | _ErrKind = ...,
28
+ divide: None | _ErrKind = ...,
29
+ over: None | _ErrKind = ...,
30
+ under: None | _ErrKind = ...,
31
+ invalid: None | _ErrKind = ...,
32
+ ) -> _ErrDict: ...
33
+ def geterr() -> _ErrDict: ...
34
+ def setbufsize(size: int) -> int: ...
35
+ def getbufsize() -> int: ...
36
+ def seterrcall(func: _ErrCall | None) -> _ErrCall | None: ...
37
+ def geterrcall() -> _ErrCall | None: ...
38
+
39
+ # See `numpy/__init__.pyi` for the `errstate` class and `no_nep5_warnings`
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (46.4 kB). View file
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/arrayprint.py ADDED
@@ -0,0 +1,1756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Array printing function
2
+
3
+ $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
4
+
5
+ """
6
+ __all__ = ["array2string", "array_str", "array_repr",
7
+ "set_printoptions", "get_printoptions", "printoptions",
8
+ "format_float_positional", "format_float_scientific"]
9
+ __docformat__ = 'restructuredtext'
10
+
11
+ #
12
+ # Written by Konrad Hinsen <hinsenk@ere.umontreal.ca>
13
+ # last revision: 1996-3-13
14
+ # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
15
+ # and by Perry Greenfield 2000-4-1 for numarray
16
+ # and by Travis Oliphant 2005-8-22 for numpy
17
+
18
+
19
+ # Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy
20
+ # scalars but for different purposes. scalartypes.c.src has str/reprs for when
21
+ # the scalar is printed on its own, while arrayprint.py has strs for when
22
+ # scalars are printed inside an ndarray. Only the latter strs are currently
23
+ # user-customizable.
24
+
25
+ import functools
26
+ import numbers
27
+ import sys
28
+ try:
29
+ from _thread import get_ident
30
+ except ImportError:
31
+ from _dummy_thread import get_ident
32
+
33
+ import numpy as np
34
+ from . import numerictypes as _nt
35
+ from .umath import absolute, isinf, isfinite, isnat
36
+ from . import multiarray
37
+ from .multiarray import (array, dragon4_positional, dragon4_scientific,
38
+ datetime_as_string, datetime_data, ndarray)
39
+ from .fromnumeric import any
40
+ from .numeric import concatenate, asarray, errstate
41
+ from .numerictypes import (longlong, intc, int_, float64, complex128,
42
+ flexible)
43
+ from .overrides import array_function_dispatch, set_module
44
+ from .printoptions import format_options
45
+ import operator
46
+ import warnings
47
+ import contextlib
48
+
49
+
50
+ def _make_options_dict(precision=None, threshold=None, edgeitems=None,
51
+ linewidth=None, suppress=None, nanstr=None, infstr=None,
52
+ sign=None, formatter=None, floatmode=None, legacy=None,
53
+ override_repr=None):
54
+ """
55
+ Make a dictionary out of the non-None arguments, plus conversion of
56
+ *legacy* and sanity checks.
57
+ """
58
+
59
+ options = {k: v for k, v in list(locals().items()) if v is not None}
60
+
61
+ if suppress is not None:
62
+ options['suppress'] = bool(suppress)
63
+
64
+ modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
65
+ if floatmode not in modes + [None]:
66
+ raise ValueError("floatmode option must be one of " +
67
+ ", ".join('"{}"'.format(m) for m in modes))
68
+
69
+ if sign not in [None, '-', '+', ' ']:
70
+ raise ValueError("sign option must be one of ' ', '+', or '-'")
71
+
72
+ if legacy is False:
73
+ options['legacy'] = sys.maxsize
74
+ elif legacy == False: # noqa: E712
75
+ warnings.warn(
76
+ f"Passing `legacy={legacy!r}` is deprecated.",
77
+ FutureWarning, stacklevel=3
78
+ )
79
+ options['legacy'] = sys.maxsize
80
+ elif legacy == '1.13':
81
+ options['legacy'] = 113
82
+ elif legacy == '1.21':
83
+ options['legacy'] = 121
84
+ elif legacy == '1.25':
85
+ options['legacy'] = 125
86
+ elif legacy == '2.1':
87
+ options['legacy'] = 201
88
+ elif legacy is None:
89
+ pass # OK, do nothing.
90
+ else:
91
+ warnings.warn(
92
+ "legacy printing option can currently only be '1.13', '1.21', "
93
+ "'1.25', '2.1, or `False`", stacklevel=3)
94
+
95
+ if threshold is not None:
96
+ # forbid the bad threshold arg suggested by stack overflow, gh-12351
97
+ if not isinstance(threshold, numbers.Number):
98
+ raise TypeError("threshold must be numeric")
99
+ if np.isnan(threshold):
100
+ raise ValueError("threshold must be non-NAN, try "
101
+ "sys.maxsize for untruncated representation")
102
+
103
+ if precision is not None:
104
+ # forbid the bad precision arg as suggested by issue #18254
105
+ try:
106
+ options['precision'] = operator.index(precision)
107
+ except TypeError as e:
108
+ raise TypeError('precision must be an integer') from e
109
+
110
+ return options
111
+
112
+
113
+ @set_module('numpy')
114
+ def set_printoptions(precision=None, threshold=None, edgeitems=None,
115
+ linewidth=None, suppress=None, nanstr=None,
116
+ infstr=None, formatter=None, sign=None, floatmode=None,
117
+ *, legacy=None, override_repr=None):
118
+ """
119
+ Set printing options.
120
+
121
+ These options determine the way floating point numbers, arrays and
122
+ other NumPy objects are displayed.
123
+
124
+ Parameters
125
+ ----------
126
+ precision : int or None, optional
127
+ Number of digits of precision for floating point output (default 8).
128
+ May be None if `floatmode` is not `fixed`, to print as many digits as
129
+ necessary to uniquely specify the value.
130
+ threshold : int, optional
131
+ Total number of array elements which trigger summarization
132
+ rather than full repr (default 1000).
133
+ To always use the full repr without summarization, pass `sys.maxsize`.
134
+ edgeitems : int, optional
135
+ Number of array items in summary at beginning and end of
136
+ each dimension (default 3).
137
+ linewidth : int, optional
138
+ The number of characters per line for the purpose of inserting
139
+ line breaks (default 75).
140
+ suppress : bool, optional
141
+ If True, always print floating point numbers using fixed point
142
+ notation, in which case numbers equal to zero in the current precision
143
+ will print as zero. If False, then scientific notation is used when
144
+ absolute value of the smallest number is < 1e-4 or the ratio of the
145
+ maximum absolute value to the minimum is > 1e3. The default is False.
146
+ nanstr : str, optional
147
+ String representation of floating point not-a-number (default nan).
148
+ infstr : str, optional
149
+ String representation of floating point infinity (default inf).
150
+ sign : string, either '-', '+', or ' ', optional
151
+ Controls printing of the sign of floating-point types. If '+', always
152
+ print the sign of positive values. If ' ', always prints a space
153
+ (whitespace character) in the sign position of positive values. If
154
+ '-', omit the sign character of positive values. (default '-')
155
+
156
+ .. versionchanged:: 2.0
157
+ The sign parameter can now be an integer type, previously
158
+ types were floating-point types.
159
+
160
+ formatter : dict of callables, optional
161
+ If not None, the keys should indicate the type(s) that the respective
162
+ formatting function applies to. Callables should return a string.
163
+ Types that are not specified (by their corresponding keys) are handled
164
+ by the default formatters. Individual types for which a formatter
165
+ can be set are:
166
+
167
+ - 'bool'
168
+ - 'int'
169
+ - 'timedelta' : a `numpy.timedelta64`
170
+ - 'datetime' : a `numpy.datetime64`
171
+ - 'float'
172
+ - 'longfloat' : 128-bit floats
173
+ - 'complexfloat'
174
+ - 'longcomplexfloat' : composed of two 128-bit floats
175
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
176
+ - 'object' : `np.object_` arrays
177
+
178
+ Other keys that can be used to set a group of types at once are:
179
+
180
+ - 'all' : sets all types
181
+ - 'int_kind' : sets 'int'
182
+ - 'float_kind' : sets 'float' and 'longfloat'
183
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
184
+ - 'str_kind' : sets 'numpystr'
185
+ floatmode : str, optional
186
+ Controls the interpretation of the `precision` option for
187
+ floating-point types. Can take the following values
188
+ (default maxprec_equal):
189
+
190
+ * 'fixed': Always print exactly `precision` fractional digits,
191
+ even if this would print more or fewer digits than
192
+ necessary to specify the value uniquely.
193
+ * 'unique': Print the minimum number of fractional digits necessary
194
+ to represent each value uniquely. Different elements may
195
+ have a different number of digits. The value of the
196
+ `precision` option is ignored.
197
+ * 'maxprec': Print at most `precision` fractional digits, but if
198
+ an element can be uniquely represented with fewer digits
199
+ only print it with that many.
200
+ * 'maxprec_equal': Print at most `precision` fractional digits,
201
+ but if every element in the array can be uniquely
202
+ represented with an equal number of fewer digits, use that
203
+ many digits for all elements.
204
+ legacy : string or `False`, optional
205
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
206
+ approximates numpy 1.13 print output by including a space in the sign
207
+ position of floats and different behavior for 0d arrays. This also
208
+ enables 1.21 legacy printing mode (described below).
209
+
210
+ If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
211
+ approximates numpy 1.21 print output of complex structured dtypes
212
+ by not inserting spaces after commas that separate fields and after
213
+ colons.
214
+
215
+ If set to ``'1.25'`` approximates printing of 1.25 which mainly means
216
+ that numeric scalars are printed without their type information, e.g.
217
+ as ``3.0`` rather than ``np.float64(3.0)``.
218
+
219
+ If set to ``'2.1'``, shape information is not given when arrays are
220
+ summarized (i.e., multiple elements replaced with ``...``).
221
+
222
+ If set to `False`, disables legacy mode.
223
+
224
+ Unrecognized strings will be ignored with a warning for forward
225
+ compatibility.
226
+
227
+ .. versionchanged:: 1.22.0
228
+ .. versionchanged:: 2.2
229
+
230
+ override_repr: callable, optional
231
+ If set a passed function will be used for generating arrays' repr.
232
+ Other options will be ignored.
233
+
234
+ See Also
235
+ --------
236
+ get_printoptions, printoptions, array2string
237
+
238
+ Notes
239
+ -----
240
+ `formatter` is always reset with a call to `set_printoptions`.
241
+
242
+ Use `printoptions` as a context manager to set the values temporarily.
243
+
244
+ Examples
245
+ --------
246
+ Floating point precision can be set:
247
+
248
+ >>> import numpy as np
249
+ >>> np.set_printoptions(precision=4)
250
+ >>> np.array([1.123456789])
251
+ [1.1235]
252
+
253
+ Long arrays can be summarised:
254
+
255
+ >>> np.set_printoptions(threshold=5)
256
+ >>> np.arange(10)
257
+ array([0, 1, 2, ..., 7, 8, 9], shape=(10,))
258
+
259
+ Small results can be suppressed:
260
+
261
+ >>> eps = np.finfo(float).eps
262
+ >>> x = np.arange(4.)
263
+ >>> x**2 - (x + eps)**2
264
+ array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
265
+ >>> np.set_printoptions(suppress=True)
266
+ >>> x**2 - (x + eps)**2
267
+ array([-0., -0., 0., 0.])
268
+
269
+ A custom formatter can be used to display array elements as desired:
270
+
271
+ >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
272
+ >>> x = np.arange(3)
273
+ >>> x
274
+ array([int: 0, int: -1, int: -2])
275
+ >>> np.set_printoptions() # formatter gets reset
276
+ >>> x
277
+ array([0, 1, 2])
278
+
279
+ To put back the default options, you can use:
280
+
281
+ >>> np.set_printoptions(edgeitems=3, infstr='inf',
282
+ ... linewidth=75, nanstr='nan', precision=8,
283
+ ... suppress=False, threshold=1000, formatter=None)
284
+
285
+ Also to temporarily override options, use `printoptions`
286
+ as a context manager:
287
+
288
+ >>> with np.printoptions(precision=2, suppress=True, threshold=5):
289
+ ... np.linspace(0, 10, 10)
290
+ array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ], shape=(10,))
291
+
292
+ """
293
+ _set_printoptions(precision, threshold, edgeitems, linewidth, suppress,
294
+ nanstr, infstr, formatter, sign, floatmode,
295
+ legacy=legacy, override_repr=override_repr)
296
+
297
+
298
+ def _set_printoptions(precision=None, threshold=None, edgeitems=None,
299
+ linewidth=None, suppress=None, nanstr=None,
300
+ infstr=None, formatter=None, sign=None, floatmode=None,
301
+ *, legacy=None, override_repr=None):
302
+ new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth,
303
+ suppress, nanstr, infstr, sign, formatter,
304
+ floatmode, legacy)
305
+ # formatter and override_repr are always reset
306
+ new_opt['formatter'] = formatter
307
+ new_opt['override_repr'] = override_repr
308
+
309
+ updated_opt = format_options.get() | new_opt
310
+ updated_opt.update(new_opt)
311
+
312
+ if updated_opt['legacy'] == 113:
313
+ updated_opt['sign'] = '-'
314
+
315
+ return format_options.set(updated_opt)
316
+
317
+
318
+ @set_module('numpy')
319
+ def get_printoptions():
320
+ """
321
+ Return the current print options.
322
+
323
+ Returns
324
+ -------
325
+ print_opts : dict
326
+ Dictionary of current print options with keys
327
+
328
+ - precision : int
329
+ - threshold : int
330
+ - edgeitems : int
331
+ - linewidth : int
332
+ - suppress : bool
333
+ - nanstr : str
334
+ - infstr : str
335
+ - sign : str
336
+ - formatter : dict of callables
337
+ - floatmode : str
338
+ - legacy : str or False
339
+
340
+ For a full description of these options, see `set_printoptions`.
341
+
342
+ See Also
343
+ --------
344
+ set_printoptions, printoptions
345
+
346
+ Examples
347
+ --------
348
+ >>> import numpy as np
349
+
350
+ >>> np.get_printoptions()
351
+ {'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
352
+
353
+ >>> np.get_printoptions()['linewidth']
354
+ 75
355
+ >>> np.set_printoptions(linewidth=100)
356
+ >>> np.get_printoptions()['linewidth']
357
+ 100
358
+
359
+ """
360
+ opts = format_options.get().copy()
361
+ opts['legacy'] = {
362
+ 113: '1.13', 121: '1.21', 125: '1.25', sys.maxsize: False,
363
+ }[opts['legacy']]
364
+ return opts
365
+
366
+
367
+ def _get_legacy_print_mode():
368
+ """Return the legacy print mode as an int."""
369
+ return format_options.get()['legacy']
370
+
371
+
372
+ @set_module('numpy')
373
+ @contextlib.contextmanager
374
+ def printoptions(*args, **kwargs):
375
+ """Context manager for setting print options.
376
+
377
+ Set print options for the scope of the `with` block, and restore the old
378
+ options at the end. See `set_printoptions` for the full description of
379
+ available options.
380
+
381
+ Examples
382
+ --------
383
+ >>> import numpy as np
384
+
385
+ >>> from numpy.testing import assert_equal
386
+ >>> with np.printoptions(precision=2):
387
+ ... np.array([2.0]) / 3
388
+ array([0.67])
389
+
390
+ The `as`-clause of the `with`-statement gives the current print options:
391
+
392
+ >>> with np.printoptions(precision=2) as opts:
393
+ ... assert_equal(opts, np.get_printoptions())
394
+
395
+ See Also
396
+ --------
397
+ set_printoptions, get_printoptions
398
+
399
+ """
400
+ token = _set_printoptions(*args, **kwargs)
401
+
402
+ try:
403
+ yield get_printoptions()
404
+ finally:
405
+ format_options.reset(token)
406
+
407
+
408
+ def _leading_trailing(a, edgeitems, index=()):
409
+ """
410
+ Keep only the N-D corners (leading and trailing edges) of an array.
411
+
412
+ Should be passed a base-class ndarray, since it makes no guarantees about
413
+ preserving subclasses.
414
+ """
415
+ axis = len(index)
416
+ if axis == a.ndim:
417
+ return a[index]
418
+
419
+ if a.shape[axis] > 2*edgeitems:
420
+ return concatenate((
421
+ _leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]),
422
+ _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])
423
+ ), axis=axis)
424
+ else:
425
+ return _leading_trailing(a, edgeitems, index + np.index_exp[:])
426
+
427
+
428
+ def _object_format(o):
429
+ """ Object arrays containing lists should be printed unambiguously """
430
+ if type(o) is list:
431
+ fmt = 'list({!r})'
432
+ else:
433
+ fmt = '{!r}'
434
+ return fmt.format(o)
435
+
436
+ def repr_format(x):
437
+ if isinstance(x, (np.str_, np.bytes_)):
438
+ return repr(x.item())
439
+ return repr(x)
440
+
441
+ def str_format(x):
442
+ if isinstance(x, (np.str_, np.bytes_)):
443
+ return str(x.item())
444
+ return str(x)
445
+
446
+ def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy,
447
+ formatter, **kwargs):
448
+ # note: extra arguments in kwargs are ignored
449
+
450
+ # wrapped in lambdas to avoid taking a code path
451
+ # with the wrong type of data
452
+ formatdict = {
453
+ 'bool': lambda: BoolFormat(data),
454
+ 'int': lambda: IntegerFormat(data, sign),
455
+ 'float': lambda: FloatingFormat(
456
+ data, precision, floatmode, suppress, sign, legacy=legacy),
457
+ 'longfloat': lambda: FloatingFormat(
458
+ data, precision, floatmode, suppress, sign, legacy=legacy),
459
+ 'complexfloat': lambda: ComplexFloatingFormat(
460
+ data, precision, floatmode, suppress, sign, legacy=legacy),
461
+ 'longcomplexfloat': lambda: ComplexFloatingFormat(
462
+ data, precision, floatmode, suppress, sign, legacy=legacy),
463
+ 'datetime': lambda: DatetimeFormat(data, legacy=legacy),
464
+ 'timedelta': lambda: TimedeltaFormat(data),
465
+ 'object': lambda: _object_format,
466
+ 'void': lambda: str_format,
467
+ 'numpystr': lambda: repr_format}
468
+
469
+ # we need to wrap values in `formatter` in a lambda, so that the interface
470
+ # is the same as the above values.
471
+ def indirect(x):
472
+ return lambda: x
473
+
474
+ if formatter is not None:
475
+ fkeys = [k for k in formatter.keys() if formatter[k] is not None]
476
+ if 'all' in fkeys:
477
+ for key in formatdict.keys():
478
+ formatdict[key] = indirect(formatter['all'])
479
+ if 'int_kind' in fkeys:
480
+ for key in ['int']:
481
+ formatdict[key] = indirect(formatter['int_kind'])
482
+ if 'float_kind' in fkeys:
483
+ for key in ['float', 'longfloat']:
484
+ formatdict[key] = indirect(formatter['float_kind'])
485
+ if 'complex_kind' in fkeys:
486
+ for key in ['complexfloat', 'longcomplexfloat']:
487
+ formatdict[key] = indirect(formatter['complex_kind'])
488
+ if 'str_kind' in fkeys:
489
+ formatdict['numpystr'] = indirect(formatter['str_kind'])
490
+ for key in formatdict.keys():
491
+ if key in fkeys:
492
+ formatdict[key] = indirect(formatter[key])
493
+
494
+ return formatdict
495
+
496
+ def _get_format_function(data, **options):
497
+ """
498
+ find the right formatting function for the dtype_
499
+ """
500
+ dtype_ = data.dtype
501
+ dtypeobj = dtype_.type
502
+ formatdict = _get_formatdict(data, **options)
503
+ if dtypeobj is None:
504
+ return formatdict["numpystr"]()
505
+ elif issubclass(dtypeobj, _nt.bool):
506
+ return formatdict['bool']()
507
+ elif issubclass(dtypeobj, _nt.integer):
508
+ if issubclass(dtypeobj, _nt.timedelta64):
509
+ return formatdict['timedelta']()
510
+ else:
511
+ return formatdict['int']()
512
+ elif issubclass(dtypeobj, _nt.floating):
513
+ if issubclass(dtypeobj, _nt.longdouble):
514
+ return formatdict['longfloat']()
515
+ else:
516
+ return formatdict['float']()
517
+ elif issubclass(dtypeobj, _nt.complexfloating):
518
+ if issubclass(dtypeobj, _nt.clongdouble):
519
+ return formatdict['longcomplexfloat']()
520
+ else:
521
+ return formatdict['complexfloat']()
522
+ elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)):
523
+ return formatdict['numpystr']()
524
+ elif issubclass(dtypeobj, _nt.datetime64):
525
+ return formatdict['datetime']()
526
+ elif issubclass(dtypeobj, _nt.object_):
527
+ return formatdict['object']()
528
+ elif issubclass(dtypeobj, _nt.void):
529
+ if dtype_.names is not None:
530
+ return StructuredVoidFormat.from_data(data, **options)
531
+ else:
532
+ return formatdict['void']()
533
+ else:
534
+ return formatdict['numpystr']()
535
+
536
+
537
+ def _recursive_guard(fillvalue='...'):
538
+ """
539
+ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
540
+
541
+ Decorates a function such that if it calls itself with the same first
542
+ argument, it returns `fillvalue` instead of recursing.
543
+
544
+ Largely copied from reprlib.recursive_repr
545
+ """
546
+
547
+ def decorating_function(f):
548
+ repr_running = set()
549
+
550
+ @functools.wraps(f)
551
+ def wrapper(self, *args, **kwargs):
552
+ key = id(self), get_ident()
553
+ if key in repr_running:
554
+ return fillvalue
555
+ repr_running.add(key)
556
+ try:
557
+ return f(self, *args, **kwargs)
558
+ finally:
559
+ repr_running.discard(key)
560
+
561
+ return wrapper
562
+
563
+ return decorating_function
564
+
565
+
566
+ # gracefully handle recursive calls, when object arrays contain themselves
567
+ @_recursive_guard()
568
+ def _array2string(a, options, separator=' ', prefix=""):
569
+ # The formatter __init__s in _get_format_function cannot deal with
570
+ # subclasses yet, and we also need to avoid recursion issues in
571
+ # _formatArray with subclasses which return 0d arrays in place of scalars
572
+ data = asarray(a)
573
+ if a.shape == ():
574
+ a = data
575
+
576
+ if a.size > options['threshold']:
577
+ summary_insert = "..."
578
+ data = _leading_trailing(data, options['edgeitems'])
579
+ else:
580
+ summary_insert = ""
581
+
582
+ # find the right formatting function for the array
583
+ format_function = _get_format_function(data, **options)
584
+
585
+ # skip over "["
586
+ next_line_prefix = " "
587
+ # skip over array(
588
+ next_line_prefix += " "*len(prefix)
589
+
590
+ lst = _formatArray(a, format_function, options['linewidth'],
591
+ next_line_prefix, separator, options['edgeitems'],
592
+ summary_insert, options['legacy'])
593
+ return lst
594
+
595
+
596
+ def _array2string_dispatcher(
597
+ a, max_line_width=None, precision=None,
598
+ suppress_small=None, separator=None, prefix=None,
599
+ style=None, formatter=None, threshold=None,
600
+ edgeitems=None, sign=None, floatmode=None, suffix=None,
601
+ *, legacy=None):
602
+ return (a,)
603
+
604
+
605
+ @array_function_dispatch(_array2string_dispatcher, module='numpy')
606
+ def array2string(a, max_line_width=None, precision=None,
607
+ suppress_small=None, separator=' ', prefix="",
608
+ style=np._NoValue, formatter=None, threshold=None,
609
+ edgeitems=None, sign=None, floatmode=None, suffix="",
610
+ *, legacy=None):
611
+ """
612
+ Return a string representation of an array.
613
+
614
+ Parameters
615
+ ----------
616
+ a : ndarray
617
+ Input array.
618
+ max_line_width : int, optional
619
+ Inserts newlines if text is longer than `max_line_width`.
620
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
621
+ precision : int or None, optional
622
+ Floating point precision.
623
+ Defaults to ``numpy.get_printoptions()['precision']``.
624
+ suppress_small : bool, optional
625
+ Represent numbers "very close" to zero as zero; default is False.
626
+ Very close is defined by precision: if the precision is 8, e.g.,
627
+ numbers smaller (in absolute value) than 5e-9 are represented as
628
+ zero.
629
+ Defaults to ``numpy.get_printoptions()['suppress']``.
630
+ separator : str, optional
631
+ Inserted between elements.
632
+ prefix : str, optional
633
+ suffix : str, optional
634
+ The length of the prefix and suffix strings are used to respectively
635
+ align and wrap the output. An array is typically printed as::
636
+
637
+ prefix + array2string(a) + suffix
638
+
639
+ The output is left-padded by the length of the prefix string, and
640
+ wrapping is forced at the column ``max_line_width - len(suffix)``.
641
+ It should be noted that the content of prefix and suffix strings are
642
+ not included in the output.
643
+ style : _NoValue, optional
644
+ Has no effect, do not use.
645
+
646
+ .. deprecated:: 1.14.0
647
+ formatter : dict of callables, optional
648
+ If not None, the keys should indicate the type(s) that the respective
649
+ formatting function applies to. Callables should return a string.
650
+ Types that are not specified (by their corresponding keys) are handled
651
+ by the default formatters. Individual types for which a formatter
652
+ can be set are:
653
+
654
+ - 'bool'
655
+ - 'int'
656
+ - 'timedelta' : a `numpy.timedelta64`
657
+ - 'datetime' : a `numpy.datetime64`
658
+ - 'float'
659
+ - 'longfloat' : 128-bit floats
660
+ - 'complexfloat'
661
+ - 'longcomplexfloat' : composed of two 128-bit floats
662
+ - 'void' : type `numpy.void`
663
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
664
+
665
+ Other keys that can be used to set a group of types at once are:
666
+
667
+ - 'all' : sets all types
668
+ - 'int_kind' : sets 'int'
669
+ - 'float_kind' : sets 'float' and 'longfloat'
670
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
671
+ - 'str_kind' : sets 'numpystr'
672
+ threshold : int, optional
673
+ Total number of array elements which trigger summarization
674
+ rather than full repr.
675
+ Defaults to ``numpy.get_printoptions()['threshold']``.
676
+ edgeitems : int, optional
677
+ Number of array items in summary at beginning and end of
678
+ each dimension.
679
+ Defaults to ``numpy.get_printoptions()['edgeitems']``.
680
+ sign : string, either '-', '+', or ' ', optional
681
+ Controls printing of the sign of floating-point types. If '+', always
682
+ print the sign of positive values. If ' ', always prints a space
683
+ (whitespace character) in the sign position of positive values. If
684
+ '-', omit the sign character of positive values.
685
+ Defaults to ``numpy.get_printoptions()['sign']``.
686
+
687
+ .. versionchanged:: 2.0
688
+ The sign parameter can now be an integer type, previously
689
+ types were floating-point types.
690
+
691
+ floatmode : str, optional
692
+ Controls the interpretation of the `precision` option for
693
+ floating-point types.
694
+ Defaults to ``numpy.get_printoptions()['floatmode']``.
695
+ Can take the following values:
696
+
697
+ - 'fixed': Always print exactly `precision` fractional digits,
698
+ even if this would print more or fewer digits than
699
+ necessary to specify the value uniquely.
700
+ - 'unique': Print the minimum number of fractional digits necessary
701
+ to represent each value uniquely. Different elements may
702
+ have a different number of digits. The value of the
703
+ `precision` option is ignored.
704
+ - 'maxprec': Print at most `precision` fractional digits, but if
705
+ an element can be uniquely represented with fewer digits
706
+ only print it with that many.
707
+ - 'maxprec_equal': Print at most `precision` fractional digits,
708
+ but if every element in the array can be uniquely
709
+ represented with an equal number of fewer digits, use that
710
+ many digits for all elements.
711
+ legacy : string or `False`, optional
712
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
713
+ approximates numpy 1.13 print output by including a space in the sign
714
+ position of floats and different behavior for 0d arrays. If set to
715
+ `False`, disables legacy mode. Unrecognized strings will be ignored
716
+ with a warning for forward compatibility.
717
+
718
+ Returns
719
+ -------
720
+ array_str : str
721
+ String representation of the array.
722
+
723
+ Raises
724
+ ------
725
+ TypeError
726
+ if a callable in `formatter` does not return a string.
727
+
728
+ See Also
729
+ --------
730
+ array_str, array_repr, set_printoptions, get_printoptions
731
+
732
+ Notes
733
+ -----
734
+ If a formatter is specified for a certain type, the `precision` keyword is
735
+ ignored for that type.
736
+
737
+ This is a very flexible function; `array_repr` and `array_str` are using
738
+ `array2string` internally so keywords with the same name should work
739
+ identically in all three functions.
740
+
741
+ Examples
742
+ --------
743
+ >>> import numpy as np
744
+ >>> x = np.array([1e-16,1,2,3])
745
+ >>> np.array2string(x, precision=2, separator=',',
746
+ ... suppress_small=True)
747
+ '[0.,1.,2.,3.]'
748
+
749
+ >>> x = np.arange(3.)
750
+ >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
751
+ '[0.00 1.00 2.00]'
752
+
753
+ >>> x = np.arange(3)
754
+ >>> np.array2string(x, formatter={'int':lambda x: hex(x)})
755
+ '[0x0 0x1 0x2]'
756
+
757
+ """
758
+
759
+ overrides = _make_options_dict(precision, threshold, edgeitems,
760
+ max_line_width, suppress_small, None, None,
761
+ sign, formatter, floatmode, legacy)
762
+ options = format_options.get().copy()
763
+ options.update(overrides)
764
+
765
+ if options['legacy'] <= 113:
766
+ if style is np._NoValue:
767
+ style = repr
768
+
769
+ if a.shape == () and a.dtype.names is None:
770
+ return style(a.item())
771
+ elif style is not np._NoValue:
772
+ # Deprecation 11-9-2017 v1.14
773
+ warnings.warn("'style' argument is deprecated and no longer functional"
774
+ " except in 1.13 'legacy' mode",
775
+ DeprecationWarning, stacklevel=2)
776
+
777
+ if options['legacy'] > 113:
778
+ options['linewidth'] -= len(suffix)
779
+
780
+ # treat as a null array if any of shape elements == 0
781
+ if a.size == 0:
782
+ return "[]"
783
+
784
+ return _array2string(a, options, separator, prefix)
785
+
786
+
787
+ def _extendLine(s, line, word, line_width, next_line_prefix, legacy):
788
+ needs_wrap = len(line) + len(word) > line_width
789
+ if legacy > 113:
790
+ # don't wrap lines if it won't help
791
+ if len(line) <= len(next_line_prefix):
792
+ needs_wrap = False
793
+
794
+ if needs_wrap:
795
+ s += line.rstrip() + "\n"
796
+ line = next_line_prefix
797
+ line += word
798
+ return s, line
799
+
800
+
801
+ def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
802
+ """
803
+ Extends line with nicely formatted (possibly multi-line) string ``word``.
804
+ """
805
+ words = word.splitlines()
806
+ if len(words) == 1 or legacy <= 113:
807
+ return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
808
+
809
+ max_word_length = max(len(word) for word in words)
810
+ if (len(line) + max_word_length > line_width and
811
+ len(line) > len(next_line_prefix)):
812
+ s += line.rstrip() + '\n'
813
+ line = next_line_prefix + words[0]
814
+ indent = next_line_prefix
815
+ else:
816
+ indent = len(line)*' '
817
+ line += words[0]
818
+
819
+ for word in words[1::]:
820
+ s += line.rstrip() + '\n'
821
+ line = indent + word
822
+
823
+ suffix_length = max_word_length - len(words[-1])
824
+ line += suffix_length*' '
825
+
826
+ return s, line
827
+
828
+ def _formatArray(a, format_function, line_width, next_line_prefix,
829
+ separator, edge_items, summary_insert, legacy):
830
+ """formatArray is designed for two modes of operation:
831
+
832
+ 1. Full output
833
+
834
+ 2. Summarized output
835
+
836
+ """
837
+ def recurser(index, hanging_indent, curr_width):
838
+ """
839
+ By using this local function, we don't need to recurse with all the
840
+ arguments. Since this function is not created recursively, the cost is
841
+ not significant
842
+ """
843
+ axis = len(index)
844
+ axes_left = a.ndim - axis
845
+
846
+ if axes_left == 0:
847
+ return format_function(a[index])
848
+
849
+ # when recursing, add a space to align with the [ added, and reduce the
850
+ # length of the line by 1
851
+ next_hanging_indent = hanging_indent + ' '
852
+ if legacy <= 113:
853
+ next_width = curr_width
854
+ else:
855
+ next_width = curr_width - len(']')
856
+
857
+ a_len = a.shape[axis]
858
+ show_summary = summary_insert and 2*edge_items < a_len
859
+ if show_summary:
860
+ leading_items = edge_items
861
+ trailing_items = edge_items
862
+ else:
863
+ leading_items = 0
864
+ trailing_items = a_len
865
+
866
+ # stringify the array with the hanging indent on the first line too
867
+ s = ''
868
+
869
+ # last axis (rows) - wrap elements if they would not fit on one line
870
+ if axes_left == 1:
871
+ # the length up until the beginning of the separator / bracket
872
+ if legacy <= 113:
873
+ elem_width = curr_width - len(separator.rstrip())
874
+ else:
875
+ elem_width = curr_width - max(
876
+ len(separator.rstrip()), len(']')
877
+ )
878
+
879
+ line = hanging_indent
880
+ for i in range(leading_items):
881
+ word = recurser(index + (i,), next_hanging_indent, next_width)
882
+ s, line = _extendLine_pretty(
883
+ s, line, word, elem_width, hanging_indent, legacy)
884
+ line += separator
885
+
886
+ if show_summary:
887
+ s, line = _extendLine(
888
+ s, line, summary_insert, elem_width, hanging_indent, legacy
889
+ )
890
+ if legacy <= 113:
891
+ line += ", "
892
+ else:
893
+ line += separator
894
+
895
+ for i in range(trailing_items, 1, -1):
896
+ word = recurser(index + (-i,), next_hanging_indent, next_width)
897
+ s, line = _extendLine_pretty(
898
+ s, line, word, elem_width, hanging_indent, legacy)
899
+ line += separator
900
+
901
+ if legacy <= 113:
902
+ # width of the separator is not considered on 1.13
903
+ elem_width = curr_width
904
+ word = recurser(index + (-1,), next_hanging_indent, next_width)
905
+ s, line = _extendLine_pretty(
906
+ s, line, word, elem_width, hanging_indent, legacy)
907
+
908
+ s += line
909
+
910
+ # other axes - insert newlines between rows
911
+ else:
912
+ s = ''
913
+ line_sep = separator.rstrip() + '\n'*(axes_left - 1)
914
+
915
+ for i in range(leading_items):
916
+ nested = recurser(
917
+ index + (i,), next_hanging_indent, next_width
918
+ )
919
+ s += hanging_indent + nested + line_sep
920
+
921
+ if show_summary:
922
+ if legacy <= 113:
923
+ # trailing space, fixed nbr of newlines,
924
+ # and fixed separator
925
+ s += hanging_indent + summary_insert + ", \n"
926
+ else:
927
+ s += hanging_indent + summary_insert + line_sep
928
+
929
+ for i in range(trailing_items, 1, -1):
930
+ nested = recurser(index + (-i,), next_hanging_indent,
931
+ next_width)
932
+ s += hanging_indent + nested + line_sep
933
+
934
+ nested = recurser(index + (-1,), next_hanging_indent, next_width)
935
+ s += hanging_indent + nested
936
+
937
+ # remove the hanging indent, and wrap in []
938
+ s = '[' + s[len(hanging_indent):] + ']'
939
+ return s
940
+
941
+ try:
942
+ # invoke the recursive part with an initial index and prefix
943
+ return recurser(index=(),
944
+ hanging_indent=next_line_prefix,
945
+ curr_width=line_width)
946
+ finally:
947
+ # recursive closures have a cyclic reference to themselves, which
948
+ # requires gc to collect (gh-10620). To avoid this problem, for
949
+ # performance and PyPy friendliness, we break the cycle:
950
+ recurser = None
951
+
952
+ def _none_or_positive_arg(x, name):
953
+ if x is None:
954
+ return -1
955
+ if x < 0:
956
+ raise ValueError("{} must be >= 0".format(name))
957
+ return x
958
+
959
+ class FloatingFormat:
960
+ """ Formatter for subtypes of np.floating """
961
+ def __init__(self, data, precision, floatmode, suppress_small, sign=False,
962
+ *, legacy=None):
963
+ # for backcompatibility, accept bools
964
+ if isinstance(sign, bool):
965
+ sign = '+' if sign else '-'
966
+
967
+ self._legacy = legacy
968
+ if self._legacy <= 113:
969
+ # when not 0d, legacy does not support '-'
970
+ if data.shape != () and sign == '-':
971
+ sign = ' '
972
+
973
+ self.floatmode = floatmode
974
+ if floatmode == 'unique':
975
+ self.precision = None
976
+ else:
977
+ self.precision = precision
978
+
979
+ self.precision = _none_or_positive_arg(self.precision, 'precision')
980
+
981
+ self.suppress_small = suppress_small
982
+ self.sign = sign
983
+ self.exp_format = False
984
+ self.large_exponent = False
985
+ self.fillFormat(data)
986
+
987
+ def fillFormat(self, data):
988
+ # only the finite values are used to compute the number of digits
989
+ finite_vals = data[isfinite(data)]
990
+
991
+ # choose exponential mode based on the non-zero finite values:
992
+ abs_non_zero = absolute(finite_vals[finite_vals != 0])
993
+ if len(abs_non_zero) != 0:
994
+ max_val = np.max(abs_non_zero)
995
+ min_val = np.min(abs_non_zero)
996
+ with errstate(over='ignore'): # division can overflow
997
+ if max_val >= 1.e8 or (not self.suppress_small and
998
+ (min_val < 0.0001 or max_val/min_val > 1000.)):
999
+ self.exp_format = True
1000
+
1001
+ # do a first pass of printing all the numbers, to determine sizes
1002
+ if len(finite_vals) == 0:
1003
+ self.pad_left = 0
1004
+ self.pad_right = 0
1005
+ self.trim = '.'
1006
+ self.exp_size = -1
1007
+ self.unique = True
1008
+ self.min_digits = None
1009
+ elif self.exp_format:
1010
+ trim, unique = '.', True
1011
+ if self.floatmode == 'fixed' or self._legacy <= 113:
1012
+ trim, unique = 'k', False
1013
+ strs = (dragon4_scientific(x, precision=self.precision,
1014
+ unique=unique, trim=trim, sign=self.sign == '+')
1015
+ for x in finite_vals)
1016
+ frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
1017
+ int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
1018
+ self.exp_size = max(len(s) for s in exp_strs) - 1
1019
+
1020
+ self.trim = 'k'
1021
+ self.precision = max(len(s) for s in frac_part)
1022
+ self.min_digits = self.precision
1023
+ self.unique = unique
1024
+
1025
+ # for back-compat with np 1.13, use 2 spaces & sign and full prec
1026
+ if self._legacy <= 113:
1027
+ self.pad_left = 3
1028
+ else:
1029
+ # this should be only 1 or 2. Can be calculated from sign.
1030
+ self.pad_left = max(len(s) for s in int_part)
1031
+ # pad_right is only needed for nan length calculation
1032
+ self.pad_right = self.exp_size + 2 + self.precision
1033
+ else:
1034
+ trim, unique = '.', True
1035
+ if self.floatmode == 'fixed':
1036
+ trim, unique = 'k', False
1037
+ strs = (dragon4_positional(x, precision=self.precision,
1038
+ fractional=True,
1039
+ unique=unique, trim=trim,
1040
+ sign=self.sign == '+')
1041
+ for x in finite_vals)
1042
+ int_part, frac_part = zip(*(s.split('.') for s in strs))
1043
+ if self._legacy <= 113:
1044
+ self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
1045
+ else:
1046
+ self.pad_left = max(len(s) for s in int_part)
1047
+ self.pad_right = max(len(s) for s in frac_part)
1048
+ self.exp_size = -1
1049
+ self.unique = unique
1050
+
1051
+ if self.floatmode in ['fixed', 'maxprec_equal']:
1052
+ self.precision = self.min_digits = self.pad_right
1053
+ self.trim = 'k'
1054
+ else:
1055
+ self.trim = '.'
1056
+ self.min_digits = 0
1057
+
1058
+ if self._legacy > 113:
1059
+ # account for sign = ' ' by adding one to pad_left
1060
+ if self.sign == ' ' and not any(np.signbit(finite_vals)):
1061
+ self.pad_left += 1
1062
+
1063
+ # if there are non-finite values, may need to increase pad_left
1064
+ if data.size != finite_vals.size:
1065
+ neginf = self.sign != '-' or any(data[isinf(data)] < 0)
1066
+ offset = self.pad_right + 1 # +1 for decimal pt
1067
+ current_options = format_options.get()
1068
+ self.pad_left = max(
1069
+ self.pad_left, len(current_options['nanstr']) - offset,
1070
+ len(current_options['infstr']) + neginf - offset
1071
+ )
1072
+
1073
+ def __call__(self, x):
1074
+ if not np.isfinite(x):
1075
+ with errstate(invalid='ignore'):
1076
+ current_options = format_options.get()
1077
+ if np.isnan(x):
1078
+ sign = '+' if self.sign == '+' else ''
1079
+ ret = sign + current_options['nanstr']
1080
+ else: # isinf
1081
+ sign = '-' if x < 0 else '+' if self.sign == '+' else ''
1082
+ ret = sign + current_options['infstr']
1083
+ return ' '*(
1084
+ self.pad_left + self.pad_right + 1 - len(ret)
1085
+ ) + ret
1086
+
1087
+ if self.exp_format:
1088
+ return dragon4_scientific(x,
1089
+ precision=self.precision,
1090
+ min_digits=self.min_digits,
1091
+ unique=self.unique,
1092
+ trim=self.trim,
1093
+ sign=self.sign == '+',
1094
+ pad_left=self.pad_left,
1095
+ exp_digits=self.exp_size)
1096
+ else:
1097
+ return dragon4_positional(x,
1098
+ precision=self.precision,
1099
+ min_digits=self.min_digits,
1100
+ unique=self.unique,
1101
+ fractional=True,
1102
+ trim=self.trim,
1103
+ sign=self.sign == '+',
1104
+ pad_left=self.pad_left,
1105
+ pad_right=self.pad_right)
1106
+
1107
+
1108
+ @set_module('numpy')
1109
+ def format_float_scientific(x, precision=None, unique=True, trim='k',
1110
+ sign=False, pad_left=None, exp_digits=None,
1111
+ min_digits=None):
1112
+ """
1113
+ Format a floating-point scalar as a decimal string in scientific notation.
1114
+
1115
+ Provides control over rounding, trimming and padding. Uses and assumes
1116
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
1117
+
1118
+ Parameters
1119
+ ----------
1120
+ x : python float or numpy floating scalar
1121
+ Value to format.
1122
+ precision : non-negative integer or None, optional
1123
+ Maximum number of digits to print. May be None if `unique` is
1124
+ `True`, but must be an integer if unique is `False`.
1125
+ unique : boolean, optional
1126
+ If `True`, use a digit-generation strategy which gives the shortest
1127
+ representation which uniquely identifies the floating-point number from
1128
+ other values of the same type, by judicious rounding. If `precision`
1129
+ is given fewer digits than necessary can be printed. If `min_digits`
1130
+ is given more can be printed, in which cases the last digit is rounded
1131
+ with unbiased rounding.
1132
+ If `False`, digits are generated as if printing an infinite-precision
1133
+ value and stopping after `precision` digits, rounding the remaining
1134
+ value with unbiased rounding
1135
+ trim : one of 'k', '.', '0', '-', optional
1136
+ Controls post-processing trimming of trailing digits, as follows:
1137
+
1138
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
1139
+ * '.' : trim all trailing zeros, leave decimal point
1140
+ * '0' : trim all but the zero before the decimal point. Insert the
1141
+ zero if it is missing.
1142
+ * '-' : trim trailing zeros and any trailing decimal point
1143
+ sign : boolean, optional
1144
+ Whether to show the sign for positive values.
1145
+ pad_left : non-negative integer, optional
1146
+ Pad the left side of the string with whitespace until at least that
1147
+ many characters are to the left of the decimal point.
1148
+ exp_digits : non-negative integer, optional
1149
+ Pad the exponent with zeros until it contains at least this
1150
+ many digits. If omitted, the exponent will be at least 2 digits.
1151
+ min_digits : non-negative integer or None, optional
1152
+ Minimum number of digits to print. This only has an effect for
1153
+ `unique=True`. In that case more digits than necessary to uniquely
1154
+ identify the value may be printed and rounded unbiased.
1155
+
1156
+ .. versionadded:: 1.21.0
1157
+
1158
+ Returns
1159
+ -------
1160
+ rep : string
1161
+ The string representation of the floating point value
1162
+
1163
+ See Also
1164
+ --------
1165
+ format_float_positional
1166
+
1167
+ Examples
1168
+ --------
1169
+ >>> import numpy as np
1170
+ >>> np.format_float_scientific(np.float32(np.pi))
1171
+ '3.1415927e+00'
1172
+ >>> s = np.float32(1.23e24)
1173
+ >>> np.format_float_scientific(s, unique=False, precision=15)
1174
+ '1.230000071797338e+24'
1175
+ >>> np.format_float_scientific(s, exp_digits=4)
1176
+ '1.23e+0024'
1177
+ """
1178
+ precision = _none_or_positive_arg(precision, 'precision')
1179
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
1180
+ exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
1181
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
1182
+ if min_digits > 0 and precision > 0 and min_digits > precision:
1183
+ raise ValueError("min_digits must be less than or equal to precision")
1184
+ return dragon4_scientific(x, precision=precision, unique=unique,
1185
+ trim=trim, sign=sign, pad_left=pad_left,
1186
+ exp_digits=exp_digits, min_digits=min_digits)
1187
+
1188
+
1189
+ @set_module('numpy')
1190
+ def format_float_positional(x, precision=None, unique=True,
1191
+ fractional=True, trim='k', sign=False,
1192
+ pad_left=None, pad_right=None, min_digits=None):
1193
+ """
1194
+ Format a floating-point scalar as a decimal string in positional notation.
1195
+
1196
+ Provides control over rounding, trimming and padding. Uses and assumes
1197
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
1198
+
1199
+ Parameters
1200
+ ----------
1201
+ x : python float or numpy floating scalar
1202
+ Value to format.
1203
+ precision : non-negative integer or None, optional
1204
+ Maximum number of digits to print. May be None if `unique` is
1205
+ `True`, but must be an integer if unique is `False`.
1206
+ unique : boolean, optional
1207
+ If `True`, use a digit-generation strategy which gives the shortest
1208
+ representation which uniquely identifies the floating-point number from
1209
+ other values of the same type, by judicious rounding. If `precision`
1210
+ is given fewer digits than necessary can be printed, or if `min_digits`
1211
+ is given more can be printed, in which cases the last digit is rounded
1212
+ with unbiased rounding.
1213
+ If `False`, digits are generated as if printing an infinite-precision
1214
+ value and stopping after `precision` digits, rounding the remaining
1215
+ value with unbiased rounding
1216
+ fractional : boolean, optional
1217
+ If `True`, the cutoffs of `precision` and `min_digits` refer to the
1218
+ total number of digits after the decimal point, including leading
1219
+ zeros.
1220
+ If `False`, `precision` and `min_digits` refer to the total number of
1221
+ significant digits, before or after the decimal point, ignoring leading
1222
+ zeros.
1223
+ trim : one of 'k', '.', '0', '-', optional
1224
+ Controls post-processing trimming of trailing digits, as follows:
1225
+
1226
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
1227
+ * '.' : trim all trailing zeros, leave decimal point
1228
+ * '0' : trim all but the zero before the decimal point. Insert the
1229
+ zero if it is missing.
1230
+ * '-' : trim trailing zeros and any trailing decimal point
1231
+ sign : boolean, optional
1232
+ Whether to show the sign for positive values.
1233
+ pad_left : non-negative integer, optional
1234
+ Pad the left side of the string with whitespace until at least that
1235
+ many characters are to the left of the decimal point.
1236
+ pad_right : non-negative integer, optional
1237
+ Pad the right side of the string with whitespace until at least that
1238
+ many characters are to the right of the decimal point.
1239
+ min_digits : non-negative integer or None, optional
1240
+ Minimum number of digits to print. Only has an effect if `unique=True`
1241
+ in which case additional digits past those necessary to uniquely
1242
+ identify the value may be printed, rounding the last additional digit.
1243
+
1244
+ .. versionadded:: 1.21.0
1245
+
1246
+ Returns
1247
+ -------
1248
+ rep : string
1249
+ The string representation of the floating point value
1250
+
1251
+ See Also
1252
+ --------
1253
+ format_float_scientific
1254
+
1255
+ Examples
1256
+ --------
1257
+ >>> import numpy as np
1258
+ >>> np.format_float_positional(np.float32(np.pi))
1259
+ '3.1415927'
1260
+ >>> np.format_float_positional(np.float16(np.pi))
1261
+ '3.14'
1262
+ >>> np.format_float_positional(np.float16(0.3))
1263
+ '0.3'
1264
+ >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
1265
+ '0.3000488281'
1266
+ """
1267
+ precision = _none_or_positive_arg(precision, 'precision')
1268
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
1269
+ pad_right = _none_or_positive_arg(pad_right, 'pad_right')
1270
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
1271
+ if not fractional and precision == 0:
1272
+ raise ValueError("precision must be greater than 0 if "
1273
+ "fractional=False")
1274
+ if min_digits > 0 and precision > 0 and min_digits > precision:
1275
+ raise ValueError("min_digits must be less than or equal to precision")
1276
+ return dragon4_positional(x, precision=precision, unique=unique,
1277
+ fractional=fractional, trim=trim,
1278
+ sign=sign, pad_left=pad_left,
1279
+ pad_right=pad_right, min_digits=min_digits)
1280
+
1281
+ class IntegerFormat:
1282
+ def __init__(self, data, sign='-'):
1283
+ if data.size > 0:
1284
+ data_max = np.max(data)
1285
+ data_min = np.min(data)
1286
+ data_max_str_len = len(str(data_max))
1287
+ if sign == ' ' and data_min < 0:
1288
+ sign = '-'
1289
+ if data_max >= 0 and sign in "+ ":
1290
+ data_max_str_len += 1
1291
+ max_str_len = max(data_max_str_len,
1292
+ len(str(data_min)))
1293
+ else:
1294
+ max_str_len = 0
1295
+ self.format = f'{{:{sign}{max_str_len}d}}'
1296
+
1297
+ def __call__(self, x):
1298
+ return self.format.format(x)
1299
+
1300
+ class BoolFormat:
1301
+ def __init__(self, data, **kwargs):
1302
+ # add an extra space so " True" and "False" have the same length and
1303
+ # array elements align nicely when printed, except in 0d arrays
1304
+ self.truestr = ' True' if data.shape != () else 'True'
1305
+
1306
+ def __call__(self, x):
1307
+ return self.truestr if x else "False"
1308
+
1309
+
1310
+ class ComplexFloatingFormat:
1311
+ """ Formatter for subtypes of np.complexfloating """
1312
+ def __init__(self, x, precision, floatmode, suppress_small,
1313
+ sign=False, *, legacy=None):
1314
+ # for backcompatibility, accept bools
1315
+ if isinstance(sign, bool):
1316
+ sign = '+' if sign else '-'
1317
+
1318
+ floatmode_real = floatmode_imag = floatmode
1319
+ if legacy <= 113:
1320
+ floatmode_real = 'maxprec_equal'
1321
+ floatmode_imag = 'maxprec'
1322
+
1323
+ self.real_format = FloatingFormat(
1324
+ x.real, precision, floatmode_real, suppress_small,
1325
+ sign=sign, legacy=legacy
1326
+ )
1327
+ self.imag_format = FloatingFormat(
1328
+ x.imag, precision, floatmode_imag, suppress_small,
1329
+ sign='+', legacy=legacy
1330
+ )
1331
+
1332
+ def __call__(self, x):
1333
+ r = self.real_format(x.real)
1334
+ i = self.imag_format(x.imag)
1335
+
1336
+ # add the 'j' before the terminal whitespace in i
1337
+ sp = len(i.rstrip())
1338
+ i = i[:sp] + 'j' + i[sp:]
1339
+
1340
+ return r + i
1341
+
1342
+
1343
+ class _TimelikeFormat:
1344
+ def __init__(self, data):
1345
+ non_nat = data[~isnat(data)]
1346
+ if len(non_nat) > 0:
1347
+ # Max str length of non-NaT elements
1348
+ max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
1349
+ len(self._format_non_nat(np.min(non_nat))))
1350
+ else:
1351
+ max_str_len = 0
1352
+ if len(non_nat) < data.size:
1353
+ # data contains a NaT
1354
+ max_str_len = max(max_str_len, 5)
1355
+ self._format = '%{}s'.format(max_str_len)
1356
+ self._nat = "'NaT'".rjust(max_str_len)
1357
+
1358
+ def _format_non_nat(self, x):
1359
+ # override in subclass
1360
+ raise NotImplementedError
1361
+
1362
+ def __call__(self, x):
1363
+ if isnat(x):
1364
+ return self._nat
1365
+ else:
1366
+ return self._format % self._format_non_nat(x)
1367
+
1368
+
1369
+ class DatetimeFormat(_TimelikeFormat):
1370
+ def __init__(self, x, unit=None, timezone=None, casting='same_kind',
1371
+ legacy=False):
1372
+ # Get the unit from the dtype
1373
+ if unit is None:
1374
+ if x.dtype.kind == 'M':
1375
+ unit = datetime_data(x.dtype)[0]
1376
+ else:
1377
+ unit = 's'
1378
+
1379
+ if timezone is None:
1380
+ timezone = 'naive'
1381
+ self.timezone = timezone
1382
+ self.unit = unit
1383
+ self.casting = casting
1384
+ self.legacy = legacy
1385
+
1386
+ # must be called after the above are configured
1387
+ super().__init__(x)
1388
+
1389
+ def __call__(self, x):
1390
+ if self.legacy <= 113:
1391
+ return self._format_non_nat(x)
1392
+ return super().__call__(x)
1393
+
1394
+ def _format_non_nat(self, x):
1395
+ return "'%s'" % datetime_as_string(x,
1396
+ unit=self.unit,
1397
+ timezone=self.timezone,
1398
+ casting=self.casting)
1399
+
1400
+
1401
+ class TimedeltaFormat(_TimelikeFormat):
1402
+ def _format_non_nat(self, x):
1403
+ return str(x.astype('i8'))
1404
+
1405
+
1406
+ class SubArrayFormat:
1407
+ def __init__(self, format_function, **options):
1408
+ self.format_function = format_function
1409
+ self.threshold = options['threshold']
1410
+ self.edge_items = options['edgeitems']
1411
+
1412
+ def __call__(self, a):
1413
+ self.summary_insert = "..." if a.size > self.threshold else ""
1414
+ return self.format_array(a)
1415
+
1416
+ def format_array(self, a):
1417
+ if np.ndim(a) == 0:
1418
+ return self.format_function(a)
1419
+
1420
+ if self.summary_insert and a.shape[0] > 2*self.edge_items:
1421
+ formatted = (
1422
+ [self.format_array(a_) for a_ in a[:self.edge_items]]
1423
+ + [self.summary_insert]
1424
+ + [self.format_array(a_) for a_ in a[-self.edge_items:]]
1425
+ )
1426
+ else:
1427
+ formatted = [self.format_array(a_) for a_ in a]
1428
+
1429
+ return "[" + ", ".join(formatted) + "]"
1430
+
1431
+
1432
+ class StructuredVoidFormat:
1433
+ """
1434
+ Formatter for structured np.void objects.
1435
+
1436
+ This does not work on structured alias types like
1437
+ np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information,
1438
+ and the implementation relies upon np.void.__getitem__.
1439
+ """
1440
+ def __init__(self, format_functions):
1441
+ self.format_functions = format_functions
1442
+
1443
+ @classmethod
1444
+ def from_data(cls, data, **options):
1445
+ """
1446
+ This is a second way to initialize StructuredVoidFormat,
1447
+ using the raw data as input. Added to avoid changing
1448
+ the signature of __init__.
1449
+ """
1450
+ format_functions = []
1451
+ for field_name in data.dtype.names:
1452
+ format_function = _get_format_function(data[field_name], **options)
1453
+ if data.dtype[field_name].shape != ():
1454
+ format_function = SubArrayFormat(format_function, **options)
1455
+ format_functions.append(format_function)
1456
+ return cls(format_functions)
1457
+
1458
+ def __call__(self, x):
1459
+ str_fields = [
1460
+ format_function(field)
1461
+ for field, format_function in zip(x, self.format_functions)
1462
+ ]
1463
+ if len(str_fields) == 1:
1464
+ return "({},)".format(str_fields[0])
1465
+ else:
1466
+ return "({})".format(", ".join(str_fields))
1467
+
1468
+
1469
+ def _void_scalar_to_string(x, is_repr=True):
1470
+ """
1471
+ Implements the repr for structured-void scalars. It is called from the
1472
+ scalartypes.c.src code, and is placed here because it uses the elementwise
1473
+ formatters defined above.
1474
+ """
1475
+ options = format_options.get().copy()
1476
+
1477
+ if options["legacy"] <= 125:
1478
+ return StructuredVoidFormat.from_data(array(x), **options)(x)
1479
+
1480
+ if options.get('formatter') is None:
1481
+ options['formatter'] = {}
1482
+ options['formatter'].setdefault('float_kind', str)
1483
+ val_repr = StructuredVoidFormat.from_data(array(x), **options)(x)
1484
+ if not is_repr:
1485
+ return val_repr
1486
+ cls = type(x)
1487
+ cls_fqn = cls.__module__.replace("numpy", "np") + "." + cls.__name__
1488
+ void_dtype = np.dtype((np.void, x.dtype))
1489
+ return f"{cls_fqn}({val_repr}, dtype={void_dtype!s})"
1490
+
1491
+
1492
+ _typelessdata = [int_, float64, complex128, _nt.bool]
1493
+
1494
+
1495
+ def dtype_is_implied(dtype):
1496
+ """
1497
+ Determine if the given dtype is implied by the representation
1498
+ of its values.
1499
+
1500
+ Parameters
1501
+ ----------
1502
+ dtype : dtype
1503
+ Data type
1504
+
1505
+ Returns
1506
+ -------
1507
+ implied : bool
1508
+ True if the dtype is implied by the representation of its values.
1509
+
1510
+ Examples
1511
+ --------
1512
+ >>> import numpy as np
1513
+ >>> np._core.arrayprint.dtype_is_implied(int)
1514
+ True
1515
+ >>> np.array([1, 2, 3], int)
1516
+ array([1, 2, 3])
1517
+ >>> np._core.arrayprint.dtype_is_implied(np.int8)
1518
+ False
1519
+ >>> np.array([1, 2, 3], np.int8)
1520
+ array([1, 2, 3], dtype=int8)
1521
+ """
1522
+ dtype = np.dtype(dtype)
1523
+ if format_options.get()['legacy'] <= 113 and dtype.type == np.bool:
1524
+ return False
1525
+
1526
+ # not just void types can be structured, and names are not part of the repr
1527
+ if dtype.names is not None:
1528
+ return False
1529
+
1530
+ # should care about endianness *unless size is 1* (e.g., int8, bool)
1531
+ if not dtype.isnative:
1532
+ return False
1533
+
1534
+ return dtype.type in _typelessdata
1535
+
1536
+
1537
+ def dtype_short_repr(dtype):
1538
+ """
1539
+ Convert a dtype to a short form which evaluates to the same dtype.
1540
+
1541
+ The intent is roughly that the following holds
1542
+
1543
+ >>> from numpy import *
1544
+ >>> dt = np.int64([1, 2]).dtype
1545
+ >>> assert eval(dtype_short_repr(dt)) == dt
1546
+ """
1547
+ if type(dtype).__repr__ != np.dtype.__repr__:
1548
+ # TODO: Custom repr for user DTypes, logic should likely move.
1549
+ return repr(dtype)
1550
+ if dtype.names is not None:
1551
+ # structured dtypes give a list or tuple repr
1552
+ return str(dtype)
1553
+ elif issubclass(dtype.type, flexible):
1554
+ # handle these separately so they don't give garbage like str256
1555
+ return "'%s'" % str(dtype)
1556
+
1557
+ typename = dtype.name
1558
+ if not dtype.isnative:
1559
+ # deal with cases like dtype('<u2') that are identical to an
1560
+ # established dtype (in this case uint16)
1561
+ # except that they have a different endianness.
1562
+ return "'%s'" % str(dtype)
1563
+ # quote typenames which can't be represented as python variable names
1564
+ if typename and not (typename[0].isalpha() and typename.isalnum()):
1565
+ typename = repr(typename)
1566
+ return typename
1567
+
1568
+
1569
+ def _array_repr_implementation(
1570
+ arr, max_line_width=None, precision=None, suppress_small=None,
1571
+ array2string=array2string):
1572
+ """Internal version of array_repr() that allows overriding array2string."""
1573
+ current_options = format_options.get()
1574
+ override_repr = current_options["override_repr"]
1575
+ if override_repr is not None:
1576
+ return override_repr(arr)
1577
+
1578
+ if max_line_width is None:
1579
+ max_line_width = current_options['linewidth']
1580
+
1581
+ if type(arr) is not ndarray:
1582
+ class_name = type(arr).__name__
1583
+ else:
1584
+ class_name = "array"
1585
+
1586
+ prefix = class_name + "("
1587
+ if (current_options['legacy'] <= 113 and
1588
+ arr.shape == () and not arr.dtype.names):
1589
+ lst = repr(arr.item())
1590
+ else:
1591
+ lst = array2string(arr, max_line_width, precision, suppress_small,
1592
+ ', ', prefix, suffix=")")
1593
+
1594
+ # Add dtype and shape information if these cannot be inferred from
1595
+ # the array string.
1596
+ extras = []
1597
+ if (arr.size == 0 and arr.shape != (0,)
1598
+ or current_options['legacy'] > 210
1599
+ and arr.size > current_options['threshold']):
1600
+ extras.append(f"shape={arr.shape}")
1601
+ if not dtype_is_implied(arr.dtype) or arr.size == 0:
1602
+ extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
1603
+
1604
+ if not extras:
1605
+ return prefix + lst + ")"
1606
+
1607
+ arr_str = prefix + lst + ","
1608
+ extra_str = ", ".join(extras) + ")"
1609
+ # compute whether we should put extras on a new line: Do so if adding the
1610
+ # extras would extend the last line past max_line_width.
1611
+ # Note: This line gives the correct result even when rfind returns -1.
1612
+ last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
1613
+ spacer = " "
1614
+ if current_options['legacy'] <= 113:
1615
+ if issubclass(arr.dtype.type, flexible):
1616
+ spacer = '\n' + ' '*len(prefix)
1617
+ elif last_line_len + len(extra_str) + 1 > max_line_width:
1618
+ spacer = '\n' + ' '*len(prefix)
1619
+
1620
+ return arr_str + spacer + extra_str
1621
+
1622
+
1623
+ def _array_repr_dispatcher(
1624
+ arr, max_line_width=None, precision=None, suppress_small=None):
1625
+ return (arr,)
1626
+
1627
+
1628
+ @array_function_dispatch(_array_repr_dispatcher, module='numpy')
1629
+ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
1630
+ """
1631
+ Return the string representation of an array.
1632
+
1633
+ Parameters
1634
+ ----------
1635
+ arr : ndarray
1636
+ Input array.
1637
+ max_line_width : int, optional
1638
+ Inserts newlines if text is longer than `max_line_width`.
1639
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
1640
+ precision : int, optional
1641
+ Floating point precision.
1642
+ Defaults to ``numpy.get_printoptions()['precision']``.
1643
+ suppress_small : bool, optional
1644
+ Represent numbers "very close" to zero as zero; default is False.
1645
+ Very close is defined by precision: if the precision is 8, e.g.,
1646
+ numbers smaller (in absolute value) than 5e-9 are represented as
1647
+ zero.
1648
+ Defaults to ``numpy.get_printoptions()['suppress']``.
1649
+
1650
+ Returns
1651
+ -------
1652
+ string : str
1653
+ The string representation of an array.
1654
+
1655
+ See Also
1656
+ --------
1657
+ array_str, array2string, set_printoptions
1658
+
1659
+ Examples
1660
+ --------
1661
+ >>> import numpy as np
1662
+ >>> np.array_repr(np.array([1,2]))
1663
+ 'array([1, 2])'
1664
+ >>> np.array_repr(np.ma.array([0.]))
1665
+ 'MaskedArray([0.])'
1666
+ >>> np.array_repr(np.array([], np.int32))
1667
+ 'array([], dtype=int32)'
1668
+
1669
+ >>> x = np.array([1e-6, 4e-7, 2, 3])
1670
+ >>> np.array_repr(x, precision=6, suppress_small=True)
1671
+ 'array([0.000001, 0. , 2. , 3. ])'
1672
+
1673
+ """
1674
+ return _array_repr_implementation(
1675
+ arr, max_line_width, precision, suppress_small)
1676
+
1677
+
1678
+ @_recursive_guard()
1679
+ def _guarded_repr_or_str(v):
1680
+ if isinstance(v, bytes):
1681
+ return repr(v)
1682
+ return str(v)
1683
+
1684
+
1685
+ def _array_str_implementation(
1686
+ a, max_line_width=None, precision=None, suppress_small=None,
1687
+ array2string=array2string):
1688
+ """Internal version of array_str() that allows overriding array2string."""
1689
+ if (format_options.get()['legacy'] <= 113 and
1690
+ a.shape == () and not a.dtype.names):
1691
+ return str(a.item())
1692
+
1693
+ # the str of 0d arrays is a special case: It should appear like a scalar,
1694
+ # so floats are not truncated by `precision`, and strings are not wrapped
1695
+ # in quotes. So we return the str of the scalar value.
1696
+ if a.shape == ():
1697
+ # obtain a scalar and call str on it, avoiding problems for subclasses
1698
+ # for which indexing with () returns a 0d instead of a scalar by using
1699
+ # ndarray's getindex. Also guard against recursive 0d object arrays.
1700
+ return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
1701
+
1702
+ return array2string(a, max_line_width, precision, suppress_small, ' ', "")
1703
+
1704
+
1705
+ def _array_str_dispatcher(
1706
+ a, max_line_width=None, precision=None, suppress_small=None):
1707
+ return (a,)
1708
+
1709
+
1710
+ @array_function_dispatch(_array_str_dispatcher, module='numpy')
1711
+ def array_str(a, max_line_width=None, precision=None, suppress_small=None):
1712
+ """
1713
+ Return a string representation of the data in an array.
1714
+
1715
+ The data in the array is returned as a single string. This function is
1716
+ similar to `array_repr`, the difference being that `array_repr` also
1717
+ returns information on the kind of array and its data type.
1718
+
1719
+ Parameters
1720
+ ----------
1721
+ a : ndarray
1722
+ Input array.
1723
+ max_line_width : int, optional
1724
+ Inserts newlines if text is longer than `max_line_width`.
1725
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
1726
+ precision : int, optional
1727
+ Floating point precision.
1728
+ Defaults to ``numpy.get_printoptions()['precision']``.
1729
+ suppress_small : bool, optional
1730
+ Represent numbers "very close" to zero as zero; default is False.
1731
+ Very close is defined by precision: if the precision is 8, e.g.,
1732
+ numbers smaller (in absolute value) than 5e-9 are represented as
1733
+ zero.
1734
+ Defaults to ``numpy.get_printoptions()['suppress']``.
1735
+
1736
+ See Also
1737
+ --------
1738
+ array2string, array_repr, set_printoptions
1739
+
1740
+ Examples
1741
+ --------
1742
+ >>> import numpy as np
1743
+ >>> np.array_str(np.arange(3))
1744
+ '[0 1 2]'
1745
+
1746
+ """
1747
+ return _array_str_implementation(
1748
+ a, max_line_width, precision, suppress_small)
1749
+
1750
+
1751
+ # needed if __array_function__ is disabled
1752
+ _array2string_impl = getattr(array2string, '__wrapped__', array2string)
1753
+ _default_array_str = functools.partial(_array_str_implementation,
1754
+ array2string=_array2string_impl)
1755
+ _default_array_repr = functools.partial(_array_repr_implementation,
1756
+ array2string=_array2string_impl)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/arrayprint.pyi ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+
3
+ # Using a private class is by no means ideal, but it is simply a consequence
4
+ # of a `contextlib.context` returning an instance of aforementioned class
5
+ from contextlib import _GeneratorContextManager
6
+ from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, overload, type_check_only
7
+
8
+ from typing_extensions import deprecated
9
+
10
+ import numpy as np
11
+ from numpy._globals import _NoValueType
12
+ from numpy._typing import NDArray, _CharLike_co, _FloatLike_co
13
+
14
+ __all__ = [
15
+ "array2string",
16
+ "array_repr",
17
+ "array_str",
18
+ "format_float_positional",
19
+ "format_float_scientific",
20
+ "get_printoptions",
21
+ "printoptions",
22
+ "set_printoptions",
23
+ ]
24
+
25
+ ###
26
+
27
+ _FloatMode: TypeAlias = Literal["fixed", "unique", "maxprec", "maxprec_equal"]
28
+ _LegacyNoStyle: TypeAlias = Literal["1.21", "1.25", "2.1", False]
29
+ _Legacy: TypeAlias = Literal["1.13", _LegacyNoStyle]
30
+ _Sign: TypeAlias = Literal["-", "+", " "]
31
+ _Trim: TypeAlias = Literal["k", ".", "0", "-"]
32
+ _ReprFunc: TypeAlias = Callable[[NDArray[Any]], str]
33
+
34
+ @type_check_only
35
+ class _FormatDict(TypedDict, total=False):
36
+ bool: Callable[[np.bool], str]
37
+ int: Callable[[np.integer], str]
38
+ timedelta: Callable[[np.timedelta64], str]
39
+ datetime: Callable[[np.datetime64], str]
40
+ float: Callable[[np.floating], str]
41
+ longfloat: Callable[[np.longdouble], str]
42
+ complexfloat: Callable[[np.complexfloating], str]
43
+ longcomplexfloat: Callable[[np.clongdouble], str]
44
+ void: Callable[[np.void], str]
45
+ numpystr: Callable[[_CharLike_co], str]
46
+ object: Callable[[object], str]
47
+ all: Callable[[object], str]
48
+ int_kind: Callable[[np.integer], str]
49
+ float_kind: Callable[[np.floating], str]
50
+ complex_kind: Callable[[np.complexfloating], str]
51
+ str_kind: Callable[[_CharLike_co], str]
52
+
53
+ @type_check_only
54
+ class _FormatOptions(TypedDict):
55
+ precision: int
56
+ threshold: int
57
+ edgeitems: int
58
+ linewidth: int
59
+ suppress: bool
60
+ nanstr: str
61
+ infstr: str
62
+ formatter: _FormatDict | None
63
+ sign: _Sign
64
+ floatmode: _FloatMode
65
+ legacy: _Legacy
66
+
67
+ ###
68
+
69
+ __docformat__: Final = "restructuredtext" # undocumented
70
+
71
+ def set_printoptions(
72
+ precision: None | SupportsIndex = ...,
73
+ threshold: None | int = ...,
74
+ edgeitems: None | int = ...,
75
+ linewidth: None | int = ...,
76
+ suppress: None | bool = ...,
77
+ nanstr: None | str = ...,
78
+ infstr: None | str = ...,
79
+ formatter: None | _FormatDict = ...,
80
+ sign: _Sign | None = None,
81
+ floatmode: _FloatMode | None = None,
82
+ *,
83
+ legacy: _Legacy | None = None,
84
+ override_repr: _ReprFunc | None = None,
85
+ ) -> None: ...
86
+ def get_printoptions() -> _FormatOptions: ...
87
+
88
+ # public numpy export
89
+ @overload # no style
90
+ def array2string(
91
+ a: NDArray[Any],
92
+ max_line_width: int | None = None,
93
+ precision: SupportsIndex | None = None,
94
+ suppress_small: bool | None = None,
95
+ separator: str = " ",
96
+ prefix: str = "",
97
+ style: _NoValueType = ...,
98
+ formatter: _FormatDict | None = None,
99
+ threshold: int | None = None,
100
+ edgeitems: int | None = None,
101
+ sign: _Sign | None = None,
102
+ floatmode: _FloatMode | None = None,
103
+ suffix: str = "",
104
+ *,
105
+ legacy: _Legacy | None = None,
106
+ ) -> str: ...
107
+ @overload # style=<given> (positional), legacy="1.13"
108
+ def array2string(
109
+ a: NDArray[Any],
110
+ max_line_width: int | None,
111
+ precision: SupportsIndex | None,
112
+ suppress_small: bool | None,
113
+ separator: str,
114
+ prefix: str,
115
+ style: _ReprFunc,
116
+ formatter: _FormatDict | None = None,
117
+ threshold: int | None = None,
118
+ edgeitems: int | None = None,
119
+ sign: _Sign | None = None,
120
+ floatmode: _FloatMode | None = None,
121
+ suffix: str = "",
122
+ *,
123
+ legacy: Literal["1.13"],
124
+ ) -> str: ...
125
+ @overload # style=<given> (keyword), legacy="1.13"
126
+ def array2string(
127
+ a: NDArray[Any],
128
+ max_line_width: int | None = None,
129
+ precision: SupportsIndex | None = None,
130
+ suppress_small: bool | None = None,
131
+ separator: str = " ",
132
+ prefix: str = "",
133
+ *,
134
+ style: _ReprFunc,
135
+ formatter: _FormatDict | None = None,
136
+ threshold: int | None = None,
137
+ edgeitems: int | None = None,
138
+ sign: _Sign | None = None,
139
+ floatmode: _FloatMode | None = None,
140
+ suffix: str = "",
141
+ legacy: Literal["1.13"],
142
+ ) -> str: ...
143
+ @overload # style=<given> (positional), legacy!="1.13"
144
+ @deprecated("'style' argument is deprecated and no longer functional except in 1.13 'legacy' mode")
145
+ def array2string(
146
+ a: NDArray[Any],
147
+ max_line_width: int | None,
148
+ precision: SupportsIndex | None,
149
+ suppress_small: bool | None,
150
+ separator: str,
151
+ prefix: str,
152
+ style: _ReprFunc,
153
+ formatter: _FormatDict | None = None,
154
+ threshold: int | None = None,
155
+ edgeitems: int | None = None,
156
+ sign: _Sign | None = None,
157
+ floatmode: _FloatMode | None = None,
158
+ suffix: str = "",
159
+ *,
160
+ legacy: _LegacyNoStyle | None = None,
161
+ ) -> str: ...
162
+ @overload # style=<given> (keyword), legacy="1.13"
163
+ @deprecated("'style' argument is deprecated and no longer functional except in 1.13 'legacy' mode")
164
+ def array2string(
165
+ a: NDArray[Any],
166
+ max_line_width: int | None = None,
167
+ precision: SupportsIndex | None = None,
168
+ suppress_small: bool | None = None,
169
+ separator: str = " ",
170
+ prefix: str = "",
171
+ *,
172
+ style: _ReprFunc,
173
+ formatter: _FormatDict | None = None,
174
+ threshold: int | None = None,
175
+ edgeitems: int | None = None,
176
+ sign: _Sign | None = None,
177
+ floatmode: _FloatMode | None = None,
178
+ suffix: str = "",
179
+ legacy: _LegacyNoStyle | None = None,
180
+ ) -> str: ...
181
+
182
+ def format_float_scientific(
183
+ x: _FloatLike_co,
184
+ precision: None | int = ...,
185
+ unique: bool = ...,
186
+ trim: _Trim = "k",
187
+ sign: bool = ...,
188
+ pad_left: None | int = ...,
189
+ exp_digits: None | int = ...,
190
+ min_digits: None | int = ...,
191
+ ) -> str: ...
192
+ def format_float_positional(
193
+ x: _FloatLike_co,
194
+ precision: None | int = ...,
195
+ unique: bool = ...,
196
+ fractional: bool = ...,
197
+ trim: _Trim = "k",
198
+ sign: bool = ...,
199
+ pad_left: None | int = ...,
200
+ pad_right: None | int = ...,
201
+ min_digits: None | int = ...,
202
+ ) -> str: ...
203
+ def array_repr(
204
+ arr: NDArray[Any],
205
+ max_line_width: None | int = ...,
206
+ precision: None | SupportsIndex = ...,
207
+ suppress_small: None | bool = ...,
208
+ ) -> str: ...
209
+ def array_str(
210
+ a: NDArray[Any],
211
+ max_line_width: None | int = ...,
212
+ precision: None | SupportsIndex = ...,
213
+ suppress_small: None | bool = ...,
214
+ ) -> str: ...
215
+ def printoptions(
216
+ precision: None | SupportsIndex = ...,
217
+ threshold: None | int = ...,
218
+ edgeitems: None | int = ...,
219
+ linewidth: None | int = ...,
220
+ suppress: None | bool = ...,
221
+ nanstr: None | str = ...,
222
+ infstr: None | str = ...,
223
+ formatter: None | _FormatDict = ...,
224
+ sign: None | _Sign = None,
225
+ floatmode: _FloatMode | None = None,
226
+ *,
227
+ legacy: _Legacy | None = None,
228
+ override_repr: _ReprFunc | None = None,
229
+ ) -> _GeneratorContextManager[_FormatOptions]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/cversions.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple script to compute the api hash of the current API.
2
+
3
+ The API has is defined by numpy_api_order and ufunc_api_order.
4
+
5
+ """
6
+ from os.path import dirname
7
+
8
+ from code_generators.genapi import fullapi_hash
9
+ from code_generators.numpy_api import full_api
10
+
11
+ if __name__ == '__main__':
12
+ curdir = dirname(__file__)
13
+ print(fullapi_hash(full_api))
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/defchararray.py ADDED
@@ -0,0 +1,1414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains a set of functions for vectorized string
3
+ operations and methods.
4
+
5
+ .. note::
6
+ The `chararray` class exists for backwards compatibility with
7
+ Numarray, it is not recommended for new development. Starting from numpy
8
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
9
+ `dtype` `object_`, `bytes_` or `str_`, and use the free functions
10
+ in the `numpy.char` module for fast vectorized string operations.
11
+
12
+ Some methods will only be available if the corresponding string method is
13
+ available in your version of Python.
14
+
15
+ The preferred alias for `defchararray` is `numpy.char`.
16
+
17
+ """
18
+ import functools
19
+
20
+ import numpy as np
21
+ from .._utils import set_module
22
+ from .numerictypes import bytes_, str_, character
23
+ from .numeric import ndarray, array as narray, asarray as asnarray
24
+ from numpy._core.multiarray import compare_chararrays
25
+ from numpy._core import overrides
26
+ from numpy.strings import *
27
+ from numpy.strings import (
28
+ multiply as strings_multiply,
29
+ partition as strings_partition,
30
+ rpartition as strings_rpartition,
31
+ )
32
+ from numpy._core.strings import (
33
+ _split as split,
34
+ _rsplit as rsplit,
35
+ _splitlines as splitlines,
36
+ _join as join,
37
+ )
38
+
39
+ __all__ = [
40
+ 'equal', 'not_equal', 'greater_equal', 'less_equal',
41
+ 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
42
+ 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
43
+ 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
44
+ 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
45
+ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
46
+ 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
47
+ 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
48
+ 'array', 'asarray', 'compare_chararrays', 'chararray'
49
+ ]
50
+
51
+
52
+ array_function_dispatch = functools.partial(
53
+ overrides.array_function_dispatch, module='numpy.char')
54
+
55
+
56
+ def _binary_op_dispatcher(x1, x2):
57
+ return (x1, x2)
58
+
59
+
60
+ @array_function_dispatch(_binary_op_dispatcher)
61
+ def equal(x1, x2):
62
+ """
63
+ Return (x1 == x2) element-wise.
64
+
65
+ Unlike `numpy.equal`, this comparison is performed by first
66
+ stripping whitespace characters from the end of the string. This
67
+ behavior is provided for backward-compatibility with numarray.
68
+
69
+ Parameters
70
+ ----------
71
+ x1, x2 : array_like of str or unicode
72
+ Input arrays of the same shape.
73
+
74
+ Returns
75
+ -------
76
+ out : ndarray
77
+ Output array of bools.
78
+
79
+ Examples
80
+ --------
81
+ >>> import numpy as np
82
+ >>> y = "aa "
83
+ >>> x = "aa"
84
+ >>> np.char.equal(x, y)
85
+ array(True)
86
+
87
+ See Also
88
+ --------
89
+ not_equal, greater_equal, less_equal, greater, less
90
+ """
91
+ return compare_chararrays(x1, x2, '==', True)
92
+
93
+
94
+ @array_function_dispatch(_binary_op_dispatcher)
95
+ def not_equal(x1, x2):
96
+ """
97
+ Return (x1 != x2) element-wise.
98
+
99
+ Unlike `numpy.not_equal`, this comparison is performed by first
100
+ stripping whitespace characters from the end of the string. This
101
+ behavior is provided for backward-compatibility with numarray.
102
+
103
+ Parameters
104
+ ----------
105
+ x1, x2 : array_like of str or unicode
106
+ Input arrays of the same shape.
107
+
108
+ Returns
109
+ -------
110
+ out : ndarray
111
+ Output array of bools.
112
+
113
+ See Also
114
+ --------
115
+ equal, greater_equal, less_equal, greater, less
116
+
117
+ Examples
118
+ --------
119
+ >>> import numpy as np
120
+ >>> x1 = np.array(['a', 'b', 'c'])
121
+ >>> np.char.not_equal(x1, 'b')
122
+ array([ True, False, True])
123
+
124
+ """
125
+ return compare_chararrays(x1, x2, '!=', True)
126
+
127
+
128
+ @array_function_dispatch(_binary_op_dispatcher)
129
+ def greater_equal(x1, x2):
130
+ """
131
+ Return (x1 >= x2) element-wise.
132
+
133
+ Unlike `numpy.greater_equal`, this comparison is performed by
134
+ first stripping whitespace characters from the end of the string.
135
+ This behavior is provided for backward-compatibility with
136
+ numarray.
137
+
138
+ Parameters
139
+ ----------
140
+ x1, x2 : array_like of str or unicode
141
+ Input arrays of the same shape.
142
+
143
+ Returns
144
+ -------
145
+ out : ndarray
146
+ Output array of bools.
147
+
148
+ See Also
149
+ --------
150
+ equal, not_equal, less_equal, greater, less
151
+
152
+ Examples
153
+ --------
154
+ >>> import numpy as np
155
+ >>> x1 = np.array(['a', 'b', 'c'])
156
+ >>> np.char.greater_equal(x1, 'b')
157
+ array([False, True, True])
158
+
159
+ """
160
+ return compare_chararrays(x1, x2, '>=', True)
161
+
162
+
163
+ @array_function_dispatch(_binary_op_dispatcher)
164
+ def less_equal(x1, x2):
165
+ """
166
+ Return (x1 <= x2) element-wise.
167
+
168
+ Unlike `numpy.less_equal`, this comparison is performed by first
169
+ stripping whitespace characters from the end of the string. This
170
+ behavior is provided for backward-compatibility with numarray.
171
+
172
+ Parameters
173
+ ----------
174
+ x1, x2 : array_like of str or unicode
175
+ Input arrays of the same shape.
176
+
177
+ Returns
178
+ -------
179
+ out : ndarray
180
+ Output array of bools.
181
+
182
+ See Also
183
+ --------
184
+ equal, not_equal, greater_equal, greater, less
185
+
186
+ Examples
187
+ --------
188
+ >>> import numpy as np
189
+ >>> x1 = np.array(['a', 'b', 'c'])
190
+ >>> np.char.less_equal(x1, 'b')
191
+ array([ True, True, False])
192
+
193
+ """
194
+ return compare_chararrays(x1, x2, '<=', True)
195
+
196
+
197
+ @array_function_dispatch(_binary_op_dispatcher)
198
+ def greater(x1, x2):
199
+ """
200
+ Return (x1 > x2) element-wise.
201
+
202
+ Unlike `numpy.greater`, this comparison is performed by first
203
+ stripping whitespace characters from the end of the string. This
204
+ behavior is provided for backward-compatibility with numarray.
205
+
206
+ Parameters
207
+ ----------
208
+ x1, x2 : array_like of str or unicode
209
+ Input arrays of the same shape.
210
+
211
+ Returns
212
+ -------
213
+ out : ndarray
214
+ Output array of bools.
215
+
216
+ See Also
217
+ --------
218
+ equal, not_equal, greater_equal, less_equal, less
219
+
220
+ Examples
221
+ --------
222
+ >>> import numpy as np
223
+ >>> x1 = np.array(['a', 'b', 'c'])
224
+ >>> np.char.greater(x1, 'b')
225
+ array([False, False, True])
226
+
227
+ """
228
+ return compare_chararrays(x1, x2, '>', True)
229
+
230
+
231
+ @array_function_dispatch(_binary_op_dispatcher)
232
+ def less(x1, x2):
233
+ """
234
+ Return (x1 < x2) element-wise.
235
+
236
+ Unlike `numpy.greater`, this comparison is performed by first
237
+ stripping whitespace characters from the end of the string. This
238
+ behavior is provided for backward-compatibility with numarray.
239
+
240
+ Parameters
241
+ ----------
242
+ x1, x2 : array_like of str or unicode
243
+ Input arrays of the same shape.
244
+
245
+ Returns
246
+ -------
247
+ out : ndarray
248
+ Output array of bools.
249
+
250
+ See Also
251
+ --------
252
+ equal, not_equal, greater_equal, less_equal, greater
253
+
254
+ Examples
255
+ --------
256
+ >>> import numpy as np
257
+ >>> x1 = np.array(['a', 'b', 'c'])
258
+ >>> np.char.less(x1, 'b')
259
+ array([True, False, False])
260
+
261
+ """
262
+ return compare_chararrays(x1, x2, '<', True)
263
+
264
+
265
+ @set_module("numpy.char")
266
+ def multiply(a, i):
267
+ """
268
+ Return (a * i), that is string multiple concatenation,
269
+ element-wise.
270
+
271
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
272
+ empty string).
273
+
274
+ Parameters
275
+ ----------
276
+ a : array_like, with `np.bytes_` or `np.str_` dtype
277
+
278
+ i : array_like, with any integer dtype
279
+
280
+ Returns
281
+ -------
282
+ out : ndarray
283
+ Output array of str or unicode, depending on input types
284
+
285
+ Notes
286
+ -----
287
+ This is a thin wrapper around np.strings.multiply that raises
288
+ `ValueError` when ``i`` is not an integer. It only
289
+ exists for backwards-compatibility.
290
+
291
+ Examples
292
+ --------
293
+ >>> import numpy as np
294
+ >>> a = np.array(["a", "b", "c"])
295
+ >>> np.strings.multiply(a, 3)
296
+ array(['aaa', 'bbb', 'ccc'], dtype='<U3')
297
+ >>> i = np.array([1, 2, 3])
298
+ >>> np.strings.multiply(a, i)
299
+ array(['a', 'bb', 'ccc'], dtype='<U3')
300
+ >>> np.strings.multiply(np.array(['a']), i)
301
+ array(['a', 'aa', 'aaa'], dtype='<U3')
302
+ >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
303
+ >>> np.strings.multiply(a, 3)
304
+ array([['aaa', 'bbb', 'ccc'],
305
+ ['ddd', 'eee', 'fff']], dtype='<U3')
306
+ >>> np.strings.multiply(a, i)
307
+ array([['a', 'bb', 'ccc'],
308
+ ['d', 'ee', 'fff']], dtype='<U3')
309
+
310
+ """
311
+ try:
312
+ return strings_multiply(a, i)
313
+ except TypeError:
314
+ raise ValueError("Can only multiply by integers")
315
+
316
+
317
+ @set_module("numpy.char")
318
+ def partition(a, sep):
319
+ """
320
+ Partition each element in `a` around `sep`.
321
+
322
+ Calls :meth:`str.partition` element-wise.
323
+
324
+ For each element in `a`, split the element as the first
325
+ occurrence of `sep`, and return 3 strings containing the part
326
+ before the separator, the separator itself, and the part after
327
+ the separator. If the separator is not found, return 3 strings
328
+ containing the string itself, followed by two empty strings.
329
+
330
+ Parameters
331
+ ----------
332
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
333
+ Input array
334
+ sep : {str, unicode}
335
+ Separator to split each string element in `a`.
336
+
337
+ Returns
338
+ -------
339
+ out : ndarray
340
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
341
+ depending on input types. The output array will have an extra
342
+ dimension with 3 elements per input element.
343
+
344
+ Examples
345
+ --------
346
+ >>> import numpy as np
347
+ >>> x = np.array(["Numpy is nice!"])
348
+ >>> np.char.partition(x, " ")
349
+ array([['Numpy', ' ', 'is nice!']], dtype='<U8')
350
+
351
+ See Also
352
+ --------
353
+ str.partition
354
+
355
+ """
356
+ return np.stack(strings_partition(a, sep), axis=-1)
357
+
358
+
359
+ @set_module("numpy.char")
360
+ def rpartition(a, sep):
361
+ """
362
+ Partition (split) each element around the right-most separator.
363
+
364
+ Calls :meth:`str.rpartition` element-wise.
365
+
366
+ For each element in `a`, split the element as the last
367
+ occurrence of `sep`, and return 3 strings containing the part
368
+ before the separator, the separator itself, and the part after
369
+ the separator. If the separator is not found, return 3 strings
370
+ containing the string itself, followed by two empty strings.
371
+
372
+ Parameters
373
+ ----------
374
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
375
+ Input array
376
+ sep : str or unicode
377
+ Right-most separator to split each element in array.
378
+
379
+ Returns
380
+ -------
381
+ out : ndarray
382
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
383
+ depending on input types. The output array will have an extra
384
+ dimension with 3 elements per input element.
385
+
386
+ See Also
387
+ --------
388
+ str.rpartition
389
+
390
+ Examples
391
+ --------
392
+ >>> import numpy as np
393
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
394
+ >>> np.char.rpartition(a, 'A')
395
+ array([['aAaAa', 'A', ''],
396
+ [' a', 'A', ' '],
397
+ ['abB', 'A', 'Bba']], dtype='<U5')
398
+
399
+ """
400
+ return np.stack(strings_rpartition(a, sep), axis=-1)
401
+
402
+
403
+ @set_module("numpy.char")
404
+ class chararray(ndarray):
405
+ """
406
+ chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
407
+ strides=None, order=None)
408
+
409
+ Provides a convenient view on arrays of string and unicode values.
410
+
411
+ .. note::
412
+ The `chararray` class exists for backwards compatibility with
413
+ Numarray, it is not recommended for new development. Starting from numpy
414
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
415
+ `dtype` `~numpy.object_`, `~numpy.bytes_` or `~numpy.str_`, and use
416
+ the free functions in the `numpy.char` module for fast vectorized
417
+ string operations.
418
+
419
+ Versus a NumPy array of dtype `~numpy.bytes_` or `~numpy.str_`, this
420
+ class adds the following functionality:
421
+
422
+ 1) values automatically have whitespace removed from the end
423
+ when indexed
424
+
425
+ 2) comparison operators automatically remove whitespace from the
426
+ end when comparing values
427
+
428
+ 3) vectorized string operations are provided as methods
429
+ (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
430
+
431
+ chararrays should be created using `numpy.char.array` or
432
+ `numpy.char.asarray`, rather than this constructor directly.
433
+
434
+ This constructor creates the array, using `buffer` (with `offset`
435
+ and `strides`) if it is not ``None``. If `buffer` is ``None``, then
436
+ constructs a new array with `strides` in "C order", unless both
437
+ ``len(shape) >= 2`` and ``order='F'``, in which case `strides`
438
+ is in "Fortran order".
439
+
440
+ Methods
441
+ -------
442
+ astype
443
+ argsort
444
+ copy
445
+ count
446
+ decode
447
+ dump
448
+ dumps
449
+ encode
450
+ endswith
451
+ expandtabs
452
+ fill
453
+ find
454
+ flatten
455
+ getfield
456
+ index
457
+ isalnum
458
+ isalpha
459
+ isdecimal
460
+ isdigit
461
+ islower
462
+ isnumeric
463
+ isspace
464
+ istitle
465
+ isupper
466
+ item
467
+ join
468
+ ljust
469
+ lower
470
+ lstrip
471
+ nonzero
472
+ put
473
+ ravel
474
+ repeat
475
+ replace
476
+ reshape
477
+ resize
478
+ rfind
479
+ rindex
480
+ rjust
481
+ rsplit
482
+ rstrip
483
+ searchsorted
484
+ setfield
485
+ setflags
486
+ sort
487
+ split
488
+ splitlines
489
+ squeeze
490
+ startswith
491
+ strip
492
+ swapaxes
493
+ swapcase
494
+ take
495
+ title
496
+ tofile
497
+ tolist
498
+ tostring
499
+ translate
500
+ transpose
501
+ upper
502
+ view
503
+ zfill
504
+
505
+ Parameters
506
+ ----------
507
+ shape : tuple
508
+ Shape of the array.
509
+ itemsize : int, optional
510
+ Length of each array element, in number of characters. Default is 1.
511
+ unicode : bool, optional
512
+ Are the array elements of type unicode (True) or string (False).
513
+ Default is False.
514
+ buffer : object exposing the buffer interface or str, optional
515
+ Memory address of the start of the array data. Default is None,
516
+ in which case a new array is created.
517
+ offset : int, optional
518
+ Fixed stride displacement from the beginning of an axis?
519
+ Default is 0. Needs to be >=0.
520
+ strides : array_like of ints, optional
521
+ Strides for the array (see `~numpy.ndarray.strides` for
522
+ full description). Default is None.
523
+ order : {'C', 'F'}, optional
524
+ The order in which the array data is stored in memory: 'C' ->
525
+ "row major" order (the default), 'F' -> "column major"
526
+ (Fortran) order.
527
+
528
+ Examples
529
+ --------
530
+ >>> import numpy as np
531
+ >>> charar = np.char.chararray((3, 3))
532
+ >>> charar[:] = 'a'
533
+ >>> charar
534
+ chararray([[b'a', b'a', b'a'],
535
+ [b'a', b'a', b'a'],
536
+ [b'a', b'a', b'a']], dtype='|S1')
537
+
538
+ >>> charar = np.char.chararray(charar.shape, itemsize=5)
539
+ >>> charar[:] = 'abc'
540
+ >>> charar
541
+ chararray([[b'abc', b'abc', b'abc'],
542
+ [b'abc', b'abc', b'abc'],
543
+ [b'abc', b'abc', b'abc']], dtype='|S5')
544
+
545
+ """
546
+ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
547
+ offset=0, strides=None, order='C'):
548
+ if unicode:
549
+ dtype = str_
550
+ else:
551
+ dtype = bytes_
552
+
553
+ # force itemsize to be a Python int, since using NumPy integer
554
+ # types results in itemsize.itemsize being used as the size of
555
+ # strings in the new array.
556
+ itemsize = int(itemsize)
557
+
558
+ if isinstance(buffer, str):
559
+ # unicode objects do not have the buffer interface
560
+ filler = buffer
561
+ buffer = None
562
+ else:
563
+ filler = None
564
+
565
+ if buffer is None:
566
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
567
+ order=order)
568
+ else:
569
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
570
+ buffer=buffer,
571
+ offset=offset, strides=strides,
572
+ order=order)
573
+ if filler is not None:
574
+ self[...] = filler
575
+
576
+ return self
577
+
578
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
579
+ # When calling a ufunc (and some other functions), we return a
580
+ # chararray if the ufunc output is a string-like array,
581
+ # or an ndarray otherwise
582
+ if arr.dtype.char in "SUbc":
583
+ return arr.view(type(self))
584
+ return arr
585
+
586
+ def __array_finalize__(self, obj):
587
+ # The b is a special case because it is used for reconstructing.
588
+ if self.dtype.char not in 'VSUbc':
589
+ raise ValueError("Can only create a chararray from string data.")
590
+
591
+ def __getitem__(self, obj):
592
+ val = ndarray.__getitem__(self, obj)
593
+ if isinstance(val, character):
594
+ return val.rstrip()
595
+ return val
596
+
597
+ # IMPLEMENTATION NOTE: Most of the methods of this class are
598
+ # direct delegations to the free functions in this module.
599
+ # However, those that return an array of strings should instead
600
+ # return a chararray, so some extra wrapping is required.
601
+
602
+ def __eq__(self, other):
603
+ """
604
+ Return (self == other) element-wise.
605
+
606
+ See Also
607
+ --------
608
+ equal
609
+ """
610
+ return equal(self, other)
611
+
612
+ def __ne__(self, other):
613
+ """
614
+ Return (self != other) element-wise.
615
+
616
+ See Also
617
+ --------
618
+ not_equal
619
+ """
620
+ return not_equal(self, other)
621
+
622
+ def __ge__(self, other):
623
+ """
624
+ Return (self >= other) element-wise.
625
+
626
+ See Also
627
+ --------
628
+ greater_equal
629
+ """
630
+ return greater_equal(self, other)
631
+
632
+ def __le__(self, other):
633
+ """
634
+ Return (self <= other) element-wise.
635
+
636
+ See Also
637
+ --------
638
+ less_equal
639
+ """
640
+ return less_equal(self, other)
641
+
642
+ def __gt__(self, other):
643
+ """
644
+ Return (self > other) element-wise.
645
+
646
+ See Also
647
+ --------
648
+ greater
649
+ """
650
+ return greater(self, other)
651
+
652
+ def __lt__(self, other):
653
+ """
654
+ Return (self < other) element-wise.
655
+
656
+ See Also
657
+ --------
658
+ less
659
+ """
660
+ return less(self, other)
661
+
662
+ def __add__(self, other):
663
+ """
664
+ Return (self + other), that is string concatenation,
665
+ element-wise for a pair of array_likes of str or unicode.
666
+
667
+ See Also
668
+ --------
669
+ add
670
+ """
671
+ return add(self, other)
672
+
673
+ def __radd__(self, other):
674
+ """
675
+ Return (other + self), that is string concatenation,
676
+ element-wise for a pair of array_likes of `bytes_` or `str_`.
677
+
678
+ See Also
679
+ --------
680
+ add
681
+ """
682
+ return add(other, self)
683
+
684
+ def __mul__(self, i):
685
+ """
686
+ Return (self * i), that is string multiple concatenation,
687
+ element-wise.
688
+
689
+ See Also
690
+ --------
691
+ multiply
692
+ """
693
+ return asarray(multiply(self, i))
694
+
695
+ def __rmul__(self, i):
696
+ """
697
+ Return (self * i), that is string multiple concatenation,
698
+ element-wise.
699
+
700
+ See Also
701
+ --------
702
+ multiply
703
+ """
704
+ return asarray(multiply(self, i))
705
+
706
+ def __mod__(self, i):
707
+ """
708
+ Return (self % i), that is pre-Python 2.6 string formatting
709
+ (interpolation), element-wise for a pair of array_likes of `bytes_`
710
+ or `str_`.
711
+
712
+ See Also
713
+ --------
714
+ mod
715
+ """
716
+ return asarray(mod(self, i))
717
+
718
+ def __rmod__(self, other):
719
+ return NotImplemented
720
+
721
+ def argsort(self, axis=-1, kind=None, order=None):
722
+ """
723
+ Return the indices that sort the array lexicographically.
724
+
725
+ For full documentation see `numpy.argsort`, for which this method is
726
+ in fact merely a "thin wrapper."
727
+
728
+ Examples
729
+ --------
730
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
731
+ >>> c = c.view(np.char.chararray); c
732
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
733
+ dtype='|S5')
734
+ >>> c[c.argsort()]
735
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
736
+ dtype='|S5')
737
+
738
+ """
739
+ return self.__array__().argsort(axis, kind, order)
740
+ argsort.__doc__ = ndarray.argsort.__doc__
741
+
742
+ def capitalize(self):
743
+ """
744
+ Return a copy of `self` with only the first character of each element
745
+ capitalized.
746
+
747
+ See Also
748
+ --------
749
+ char.capitalize
750
+
751
+ """
752
+ return asarray(capitalize(self))
753
+
754
+ def center(self, width, fillchar=' '):
755
+ """
756
+ Return a copy of `self` with its elements centered in a
757
+ string of length `width`.
758
+
759
+ See Also
760
+ --------
761
+ center
762
+ """
763
+ return asarray(center(self, width, fillchar))
764
+
765
+ def count(self, sub, start=0, end=None):
766
+ """
767
+ Returns an array with the number of non-overlapping occurrences of
768
+ substring `sub` in the range [`start`, `end`].
769
+
770
+ See Also
771
+ --------
772
+ char.count
773
+
774
+ """
775
+ return count(self, sub, start, end)
776
+
777
+ def decode(self, encoding=None, errors=None):
778
+ """
779
+ Calls ``bytes.decode`` element-wise.
780
+
781
+ See Also
782
+ --------
783
+ char.decode
784
+
785
+ """
786
+ return decode(self, encoding, errors)
787
+
788
+ def encode(self, encoding=None, errors=None):
789
+ """
790
+ Calls :meth:`str.encode` element-wise.
791
+
792
+ See Also
793
+ --------
794
+ char.encode
795
+
796
+ """
797
+ return encode(self, encoding, errors)
798
+
799
+ def endswith(self, suffix, start=0, end=None):
800
+ """
801
+ Returns a boolean array which is `True` where the string element
802
+ in `self` ends with `suffix`, otherwise `False`.
803
+
804
+ See Also
805
+ --------
806
+ char.endswith
807
+
808
+ """
809
+ return endswith(self, suffix, start, end)
810
+
811
+ def expandtabs(self, tabsize=8):
812
+ """
813
+ Return a copy of each string element where all tab characters are
814
+ replaced by one or more spaces.
815
+
816
+ See Also
817
+ --------
818
+ char.expandtabs
819
+
820
+ """
821
+ return asarray(expandtabs(self, tabsize))
822
+
823
+ def find(self, sub, start=0, end=None):
824
+ """
825
+ For each element, return the lowest index in the string where
826
+ substring `sub` is found.
827
+
828
+ See Also
829
+ --------
830
+ char.find
831
+
832
+ """
833
+ return find(self, sub, start, end)
834
+
835
+ def index(self, sub, start=0, end=None):
836
+ """
837
+ Like `find`, but raises :exc:`ValueError` when the substring is not
838
+ found.
839
+
840
+ See Also
841
+ --------
842
+ char.index
843
+
844
+ """
845
+ return index(self, sub, start, end)
846
+
847
+ def isalnum(self):
848
+ """
849
+ Returns true for each element if all characters in the string
850
+ are alphanumeric and there is at least one character, false
851
+ otherwise.
852
+
853
+ See Also
854
+ --------
855
+ char.isalnum
856
+
857
+ """
858
+ return isalnum(self)
859
+
860
+ def isalpha(self):
861
+ """
862
+ Returns true for each element if all characters in the string
863
+ are alphabetic and there is at least one character, false
864
+ otherwise.
865
+
866
+ See Also
867
+ --------
868
+ char.isalpha
869
+
870
+ """
871
+ return isalpha(self)
872
+
873
+ def isdigit(self):
874
+ """
875
+ Returns true for each element if all characters in the string are
876
+ digits and there is at least one character, false otherwise.
877
+
878
+ See Also
879
+ --------
880
+ char.isdigit
881
+
882
+ """
883
+ return isdigit(self)
884
+
885
+ def islower(self):
886
+ """
887
+ Returns true for each element if all cased characters in the
888
+ string are lowercase and there is at least one cased character,
889
+ false otherwise.
890
+
891
+ See Also
892
+ --------
893
+ char.islower
894
+
895
+ """
896
+ return islower(self)
897
+
898
+ def isspace(self):
899
+ """
900
+ Returns true for each element if there are only whitespace
901
+ characters in the string and there is at least one character,
902
+ false otherwise.
903
+
904
+ See Also
905
+ --------
906
+ char.isspace
907
+
908
+ """
909
+ return isspace(self)
910
+
911
+ def istitle(self):
912
+ """
913
+ Returns true for each element if the element is a titlecased
914
+ string and there is at least one character, false otherwise.
915
+
916
+ See Also
917
+ --------
918
+ char.istitle
919
+
920
+ """
921
+ return istitle(self)
922
+
923
+ def isupper(self):
924
+ """
925
+ Returns true for each element if all cased characters in the
926
+ string are uppercase and there is at least one character, false
927
+ otherwise.
928
+
929
+ See Also
930
+ --------
931
+ char.isupper
932
+
933
+ """
934
+ return isupper(self)
935
+
936
+ def join(self, seq):
937
+ """
938
+ Return a string which is the concatenation of the strings in the
939
+ sequence `seq`.
940
+
941
+ See Also
942
+ --------
943
+ char.join
944
+
945
+ """
946
+ return join(self, seq)
947
+
948
+ def ljust(self, width, fillchar=' '):
949
+ """
950
+ Return an array with the elements of `self` left-justified in a
951
+ string of length `width`.
952
+
953
+ See Also
954
+ --------
955
+ char.ljust
956
+
957
+ """
958
+ return asarray(ljust(self, width, fillchar))
959
+
960
+ def lower(self):
961
+ """
962
+ Return an array with the elements of `self` converted to
963
+ lowercase.
964
+
965
+ See Also
966
+ --------
967
+ char.lower
968
+
969
+ """
970
+ return asarray(lower(self))
971
+
972
+ def lstrip(self, chars=None):
973
+ """
974
+ For each element in `self`, return a copy with the leading characters
975
+ removed.
976
+
977
+ See Also
978
+ --------
979
+ char.lstrip
980
+
981
+ """
982
+ return lstrip(self, chars)
983
+
984
+ def partition(self, sep):
985
+ """
986
+ Partition each element in `self` around `sep`.
987
+
988
+ See Also
989
+ --------
990
+ partition
991
+ """
992
+ return asarray(partition(self, sep))
993
+
994
+ def replace(self, old, new, count=None):
995
+ """
996
+ For each element in `self`, return a copy of the string with all
997
+ occurrences of substring `old` replaced by `new`.
998
+
999
+ See Also
1000
+ --------
1001
+ char.replace
1002
+
1003
+ """
1004
+ return replace(self, old, new, count if count is not None else -1)
1005
+
1006
+ def rfind(self, sub, start=0, end=None):
1007
+ """
1008
+ For each element in `self`, return the highest index in the string
1009
+ where substring `sub` is found, such that `sub` is contained
1010
+ within [`start`, `end`].
1011
+
1012
+ See Also
1013
+ --------
1014
+ char.rfind
1015
+
1016
+ """
1017
+ return rfind(self, sub, start, end)
1018
+
1019
+ def rindex(self, sub, start=0, end=None):
1020
+ """
1021
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
1022
+ not found.
1023
+
1024
+ See Also
1025
+ --------
1026
+ char.rindex
1027
+
1028
+ """
1029
+ return rindex(self, sub, start, end)
1030
+
1031
+ def rjust(self, width, fillchar=' '):
1032
+ """
1033
+ Return an array with the elements of `self`
1034
+ right-justified in a string of length `width`.
1035
+
1036
+ See Also
1037
+ --------
1038
+ char.rjust
1039
+
1040
+ """
1041
+ return asarray(rjust(self, width, fillchar))
1042
+
1043
+ def rpartition(self, sep):
1044
+ """
1045
+ Partition each element in `self` around `sep`.
1046
+
1047
+ See Also
1048
+ --------
1049
+ rpartition
1050
+ """
1051
+ return asarray(rpartition(self, sep))
1052
+
1053
+ def rsplit(self, sep=None, maxsplit=None):
1054
+ """
1055
+ For each element in `self`, return a list of the words in
1056
+ the string, using `sep` as the delimiter string.
1057
+
1058
+ See Also
1059
+ --------
1060
+ char.rsplit
1061
+
1062
+ """
1063
+ return rsplit(self, sep, maxsplit)
1064
+
1065
+ def rstrip(self, chars=None):
1066
+ """
1067
+ For each element in `self`, return a copy with the trailing
1068
+ characters removed.
1069
+
1070
+ See Also
1071
+ --------
1072
+ char.rstrip
1073
+
1074
+ """
1075
+ return rstrip(self, chars)
1076
+
1077
+ def split(self, sep=None, maxsplit=None):
1078
+ """
1079
+ For each element in `self`, return a list of the words in the
1080
+ string, using `sep` as the delimiter string.
1081
+
1082
+ See Also
1083
+ --------
1084
+ char.split
1085
+
1086
+ """
1087
+ return split(self, sep, maxsplit)
1088
+
1089
+ def splitlines(self, keepends=None):
1090
+ """
1091
+ For each element in `self`, return a list of the lines in the
1092
+ element, breaking at line boundaries.
1093
+
1094
+ See Also
1095
+ --------
1096
+ char.splitlines
1097
+
1098
+ """
1099
+ return splitlines(self, keepends)
1100
+
1101
+ def startswith(self, prefix, start=0, end=None):
1102
+ """
1103
+ Returns a boolean array which is `True` where the string element
1104
+ in `self` starts with `prefix`, otherwise `False`.
1105
+
1106
+ See Also
1107
+ --------
1108
+ char.startswith
1109
+
1110
+ """
1111
+ return startswith(self, prefix, start, end)
1112
+
1113
+ def strip(self, chars=None):
1114
+ """
1115
+ For each element in `self`, return a copy with the leading and
1116
+ trailing characters removed.
1117
+
1118
+ See Also
1119
+ --------
1120
+ char.strip
1121
+
1122
+ """
1123
+ return strip(self, chars)
1124
+
1125
+ def swapcase(self):
1126
+ """
1127
+ For each element in `self`, return a copy of the string with
1128
+ uppercase characters converted to lowercase and vice versa.
1129
+
1130
+ See Also
1131
+ --------
1132
+ char.swapcase
1133
+
1134
+ """
1135
+ return asarray(swapcase(self))
1136
+
1137
+ def title(self):
1138
+ """
1139
+ For each element in `self`, return a titlecased version of the
1140
+ string: words start with uppercase characters, all remaining cased
1141
+ characters are lowercase.
1142
+
1143
+ See Also
1144
+ --------
1145
+ char.title
1146
+
1147
+ """
1148
+ return asarray(title(self))
1149
+
1150
+ def translate(self, table, deletechars=None):
1151
+ """
1152
+ For each element in `self`, return a copy of the string where
1153
+ all characters occurring in the optional argument
1154
+ `deletechars` are removed, and the remaining characters have
1155
+ been mapped through the given translation table.
1156
+
1157
+ See Also
1158
+ --------
1159
+ char.translate
1160
+
1161
+ """
1162
+ return asarray(translate(self, table, deletechars))
1163
+
1164
+ def upper(self):
1165
+ """
1166
+ Return an array with the elements of `self` converted to
1167
+ uppercase.
1168
+
1169
+ See Also
1170
+ --------
1171
+ char.upper
1172
+
1173
+ """
1174
+ return asarray(upper(self))
1175
+
1176
+ def zfill(self, width):
1177
+ """
1178
+ Return the numeric string left-filled with zeros in a string of
1179
+ length `width`.
1180
+
1181
+ See Also
1182
+ --------
1183
+ char.zfill
1184
+
1185
+ """
1186
+ return asarray(zfill(self, width))
1187
+
1188
+ def isnumeric(self):
1189
+ """
1190
+ For each element in `self`, return True if there are only
1191
+ numeric characters in the element.
1192
+
1193
+ See Also
1194
+ --------
1195
+ char.isnumeric
1196
+
1197
+ """
1198
+ return isnumeric(self)
1199
+
1200
+ def isdecimal(self):
1201
+ """
1202
+ For each element in `self`, return True if there are only
1203
+ decimal characters in the element.
1204
+
1205
+ See Also
1206
+ --------
1207
+ char.isdecimal
1208
+
1209
+ """
1210
+ return isdecimal(self)
1211
+
1212
+
1213
+ @set_module("numpy.char")
1214
+ def array(obj, itemsize=None, copy=True, unicode=None, order=None):
1215
+ """
1216
+ Create a `~numpy.char.chararray`.
1217
+
1218
+ .. note::
1219
+ This class is provided for numarray backward-compatibility.
1220
+ New code (not concerned with numarray compatibility) should use
1221
+ arrays of type `bytes_` or `str_` and use the free functions
1222
+ in :mod:`numpy.char` for fast vectorized string operations instead.
1223
+
1224
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
1225
+ class adds the following functionality:
1226
+
1227
+ 1) values automatically have whitespace removed from the end
1228
+ when indexed
1229
+
1230
+ 2) comparison operators automatically remove whitespace from the
1231
+ end when comparing values
1232
+
1233
+ 3) vectorized string operations are provided as methods
1234
+ (e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
1235
+ and infix operators (e.g. ``+, *, %``)
1236
+
1237
+ Parameters
1238
+ ----------
1239
+ obj : array of str or unicode-like
1240
+
1241
+ itemsize : int, optional
1242
+ `itemsize` is the number of characters per scalar in the
1243
+ resulting array. If `itemsize` is None, and `obj` is an
1244
+ object array or a Python list, the `itemsize` will be
1245
+ automatically determined. If `itemsize` is provided and `obj`
1246
+ is of type str or unicode, then the `obj` string will be
1247
+ chunked into `itemsize` pieces.
1248
+
1249
+ copy : bool, optional
1250
+ If true (default), then the object is copied. Otherwise, a copy
1251
+ will only be made if ``__array__`` returns a copy, if obj is a
1252
+ nested sequence, or if a copy is needed to satisfy any of the other
1253
+ requirements (`itemsize`, unicode, `order`, etc.).
1254
+
1255
+ unicode : bool, optional
1256
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
1257
+ characters, when false only 8-bit characters. If unicode is
1258
+ None and `obj` is one of the following:
1259
+
1260
+ - a `~numpy.char.chararray`,
1261
+ - an ndarray of type :class:`str_` or :class:`bytes_`
1262
+ - a Python :class:`str` or :class:`bytes` object,
1263
+
1264
+ then the unicode setting of the output array will be
1265
+ automatically determined.
1266
+
1267
+ order : {'C', 'F', 'A'}, optional
1268
+ Specify the order of the array. If order is 'C' (default), then the
1269
+ array will be in C-contiguous order (last-index varies the
1270
+ fastest). If order is 'F', then the returned array
1271
+ will be in Fortran-contiguous order (first-index varies the
1272
+ fastest). If order is 'A', then the returned array may
1273
+ be in any order (either C-, Fortran-contiguous, or even
1274
+ discontiguous).
1275
+
1276
+ Examples
1277
+ --------
1278
+
1279
+ >>> import numpy as np
1280
+ >>> char_array = np.char.array(['hello', 'world', 'numpy','array'])
1281
+ >>> char_array
1282
+ chararray(['hello', 'world', 'numpy', 'array'], dtype='<U5')
1283
+
1284
+ """
1285
+ if isinstance(obj, (bytes, str)):
1286
+ if unicode is None:
1287
+ if isinstance(obj, str):
1288
+ unicode = True
1289
+ else:
1290
+ unicode = False
1291
+
1292
+ if itemsize is None:
1293
+ itemsize = len(obj)
1294
+ shape = len(obj) // itemsize
1295
+
1296
+ return chararray(shape, itemsize=itemsize, unicode=unicode,
1297
+ buffer=obj, order=order)
1298
+
1299
+ if isinstance(obj, (list, tuple)):
1300
+ obj = asnarray(obj)
1301
+
1302
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
1303
+ # If we just have a vanilla chararray, create a chararray
1304
+ # view around it.
1305
+ if not isinstance(obj, chararray):
1306
+ obj = obj.view(chararray)
1307
+
1308
+ if itemsize is None:
1309
+ itemsize = obj.itemsize
1310
+ # itemsize is in 8-bit chars, so for Unicode, we need
1311
+ # to divide by the size of a single Unicode character,
1312
+ # which for NumPy is always 4
1313
+ if issubclass(obj.dtype.type, str_):
1314
+ itemsize //= 4
1315
+
1316
+ if unicode is None:
1317
+ if issubclass(obj.dtype.type, str_):
1318
+ unicode = True
1319
+ else:
1320
+ unicode = False
1321
+
1322
+ if unicode:
1323
+ dtype = str_
1324
+ else:
1325
+ dtype = bytes_
1326
+
1327
+ if order is not None:
1328
+ obj = asnarray(obj, order=order)
1329
+ if (copy or
1330
+ (itemsize != obj.itemsize) or
1331
+ (not unicode and isinstance(obj, str_)) or
1332
+ (unicode and isinstance(obj, bytes_))):
1333
+ obj = obj.astype((dtype, int(itemsize)))
1334
+ return obj
1335
+
1336
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
1337
+ if itemsize is None:
1338
+ # Since no itemsize was specified, convert the input array to
1339
+ # a list so the ndarray constructor will automatically
1340
+ # determine the itemsize for us.
1341
+ obj = obj.tolist()
1342
+ # Fall through to the default case
1343
+
1344
+ if unicode:
1345
+ dtype = str_
1346
+ else:
1347
+ dtype = bytes_
1348
+
1349
+ if itemsize is None:
1350
+ val = narray(obj, dtype=dtype, order=order, subok=True)
1351
+ else:
1352
+ val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
1353
+ return val.view(chararray)
1354
+
1355
+
1356
+ @set_module("numpy.char")
1357
+ def asarray(obj, itemsize=None, unicode=None, order=None):
1358
+ """
1359
+ Convert the input to a `~numpy.char.chararray`, copying the data only if
1360
+ necessary.
1361
+
1362
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
1363
+ class adds the following functionality:
1364
+
1365
+ 1) values automatically have whitespace removed from the end
1366
+ when indexed
1367
+
1368
+ 2) comparison operators automatically remove whitespace from the
1369
+ end when comparing values
1370
+
1371
+ 3) vectorized string operations are provided as methods
1372
+ (e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
1373
+ and infix operators (e.g. ``+``, ``*``, ``%``)
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ obj : array of str or unicode-like
1378
+
1379
+ itemsize : int, optional
1380
+ `itemsize` is the number of characters per scalar in the
1381
+ resulting array. If `itemsize` is None, and `obj` is an
1382
+ object array or a Python list, the `itemsize` will be
1383
+ automatically determined. If `itemsize` is provided and `obj`
1384
+ is of type str or unicode, then the `obj` string will be
1385
+ chunked into `itemsize` pieces.
1386
+
1387
+ unicode : bool, optional
1388
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
1389
+ characters, when false only 8-bit characters. If unicode is
1390
+ None and `obj` is one of the following:
1391
+
1392
+ - a `~numpy.char.chararray`,
1393
+ - an ndarray of type `str_` or `unicode_`
1394
+ - a Python str or unicode object,
1395
+
1396
+ then the unicode setting of the output array will be
1397
+ automatically determined.
1398
+
1399
+ order : {'C', 'F'}, optional
1400
+ Specify the order of the array. If order is 'C' (default), then the
1401
+ array will be in C-contiguous order (last-index varies the
1402
+ fastest). If order is 'F', then the returned array
1403
+ will be in Fortran-contiguous order (first-index varies the
1404
+ fastest).
1405
+
1406
+ Examples
1407
+ --------
1408
+ >>> import numpy as np
1409
+ >>> np.char.asarray(['hello', 'world'])
1410
+ chararray(['hello', 'world'], dtype='<U5')
1411
+
1412
+ """
1413
+ return array(obj, itemsize, copy=False,
1414
+ unicode=unicode, order=order)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/defchararray.pyi ADDED
@@ -0,0 +1,1096 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Literal as L,
3
+ overload,
4
+ TypeAlias,
5
+ TypeVar,
6
+ Any,
7
+ SupportsIndex,
8
+ SupportsInt,
9
+ )
10
+
11
+ import numpy as np
12
+ from numpy import (
13
+ ndarray,
14
+ dtype,
15
+ str_,
16
+ bytes_,
17
+ int_,
18
+ object_,
19
+ _OrderKACF,
20
+ _SupportsBuffer,
21
+ _SupportsArray
22
+ )
23
+ from numpy._typing import (
24
+ NDArray,
25
+ _Shape,
26
+ _ShapeLike,
27
+ _ArrayLikeStr_co as U_co,
28
+ _ArrayLikeBytes_co as S_co,
29
+ _ArrayLikeString_co as T_co,
30
+ _ArrayLikeAnyString_co as UST_co,
31
+ _ArrayLikeInt_co as i_co,
32
+ _ArrayLikeBool_co as b_co,
33
+ )
34
+ from numpy._core.multiarray import compare_chararrays
35
+
36
+ __all__ = [
37
+ "equal",
38
+ "not_equal",
39
+ "greater_equal",
40
+ "less_equal",
41
+ "greater",
42
+ "less",
43
+ "str_len",
44
+ "add",
45
+ "multiply",
46
+ "mod",
47
+ "capitalize",
48
+ "center",
49
+ "count",
50
+ "decode",
51
+ "encode",
52
+ "endswith",
53
+ "expandtabs",
54
+ "find",
55
+ "index",
56
+ "isalnum",
57
+ "isalpha",
58
+ "isdigit",
59
+ "islower",
60
+ "isspace",
61
+ "istitle",
62
+ "isupper",
63
+ "join",
64
+ "ljust",
65
+ "lower",
66
+ "lstrip",
67
+ "partition",
68
+ "replace",
69
+ "rfind",
70
+ "rindex",
71
+ "rjust",
72
+ "rpartition",
73
+ "rsplit",
74
+ "rstrip",
75
+ "split",
76
+ "splitlines",
77
+ "startswith",
78
+ "strip",
79
+ "swapcase",
80
+ "title",
81
+ "translate",
82
+ "upper",
83
+ "zfill",
84
+ "isnumeric",
85
+ "isdecimal",
86
+ "array",
87
+ "asarray",
88
+ "compare_chararrays",
89
+ "chararray",
90
+ ]
91
+
92
+ _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
93
+ _SCT = TypeVar("_SCT", bound=np.character)
94
+ _CharDType_co = TypeVar("_CharDType_co", bound=dtype[np.character], covariant=True)
95
+ _CharArray: TypeAlias = chararray[tuple[int, ...], dtype[_SCT]]
96
+
97
+ _StringDTypeArray: TypeAlias = np.ndarray[_Shape, np.dtypes.StringDType]
98
+ _StringDTypeSupportsArray: TypeAlias = _SupportsArray[np.dtypes.StringDType]
99
+ _StringDTypeOrUnicodeArray: TypeAlias = np.ndarray[_Shape, np.dtype[np.str_]] | np.ndarray[_Shape, np.dtypes.StringDType]
100
+
101
+ class chararray(ndarray[_ShapeT_co, _CharDType_co]):
102
+ @overload
103
+ def __new__(
104
+ subtype,
105
+ shape: _ShapeLike,
106
+ itemsize: SupportsIndex | SupportsInt = ...,
107
+ unicode: L[False] = ...,
108
+ buffer: _SupportsBuffer = ...,
109
+ offset: SupportsIndex = ...,
110
+ strides: _ShapeLike = ...,
111
+ order: _OrderKACF = ...,
112
+ ) -> chararray[_Shape, dtype[bytes_]]: ...
113
+ @overload
114
+ def __new__(
115
+ subtype,
116
+ shape: _ShapeLike,
117
+ itemsize: SupportsIndex | SupportsInt = ...,
118
+ unicode: L[True] = ...,
119
+ buffer: _SupportsBuffer = ...,
120
+ offset: SupportsIndex = ...,
121
+ strides: _ShapeLike = ...,
122
+ order: _OrderKACF = ...,
123
+ ) -> chararray[_Shape, dtype[str_]]: ...
124
+
125
+ def __array_finalize__(self, obj: object) -> None: ...
126
+ def __mul__(self, other: i_co) -> chararray[_Shape, _CharDType_co]: ...
127
+ def __rmul__(self, other: i_co) -> chararray[_Shape, _CharDType_co]: ...
128
+ def __mod__(self, i: Any) -> chararray[_Shape, _CharDType_co]: ...
129
+
130
+ @overload
131
+ def __eq__(
132
+ self: _CharArray[str_],
133
+ other: U_co,
134
+ ) -> NDArray[np.bool]: ...
135
+ @overload
136
+ def __eq__(
137
+ self: _CharArray[bytes_],
138
+ other: S_co,
139
+ ) -> NDArray[np.bool]: ...
140
+
141
+ @overload
142
+ def __ne__(
143
+ self: _CharArray[str_],
144
+ other: U_co,
145
+ ) -> NDArray[np.bool]: ...
146
+ @overload
147
+ def __ne__(
148
+ self: _CharArray[bytes_],
149
+ other: S_co,
150
+ ) -> NDArray[np.bool]: ...
151
+
152
+ @overload
153
+ def __ge__(
154
+ self: _CharArray[str_],
155
+ other: U_co,
156
+ ) -> NDArray[np.bool]: ...
157
+ @overload
158
+ def __ge__(
159
+ self: _CharArray[bytes_],
160
+ other: S_co,
161
+ ) -> NDArray[np.bool]: ...
162
+
163
+ @overload
164
+ def __le__(
165
+ self: _CharArray[str_],
166
+ other: U_co,
167
+ ) -> NDArray[np.bool]: ...
168
+ @overload
169
+ def __le__(
170
+ self: _CharArray[bytes_],
171
+ other: S_co,
172
+ ) -> NDArray[np.bool]: ...
173
+
174
+ @overload
175
+ def __gt__(
176
+ self: _CharArray[str_],
177
+ other: U_co,
178
+ ) -> NDArray[np.bool]: ...
179
+ @overload
180
+ def __gt__(
181
+ self: _CharArray[bytes_],
182
+ other: S_co,
183
+ ) -> NDArray[np.bool]: ...
184
+
185
+ @overload
186
+ def __lt__(
187
+ self: _CharArray[str_],
188
+ other: U_co,
189
+ ) -> NDArray[np.bool]: ...
190
+ @overload
191
+ def __lt__(
192
+ self: _CharArray[bytes_],
193
+ other: S_co,
194
+ ) -> NDArray[np.bool]: ...
195
+
196
+ @overload
197
+ def __add__(
198
+ self: _CharArray[str_],
199
+ other: U_co,
200
+ ) -> _CharArray[str_]: ...
201
+ @overload
202
+ def __add__(
203
+ self: _CharArray[bytes_],
204
+ other: S_co,
205
+ ) -> _CharArray[bytes_]: ...
206
+
207
+ @overload
208
+ def __radd__(
209
+ self: _CharArray[str_],
210
+ other: U_co,
211
+ ) -> _CharArray[str_]: ...
212
+ @overload
213
+ def __radd__(
214
+ self: _CharArray[bytes_],
215
+ other: S_co,
216
+ ) -> _CharArray[bytes_]: ...
217
+
218
+ @overload
219
+ def center(
220
+ self: _CharArray[str_],
221
+ width: i_co,
222
+ fillchar: U_co = ...,
223
+ ) -> _CharArray[str_]: ...
224
+ @overload
225
+ def center(
226
+ self: _CharArray[bytes_],
227
+ width: i_co,
228
+ fillchar: S_co = ...,
229
+ ) -> _CharArray[bytes_]: ...
230
+
231
+ @overload
232
+ def count(
233
+ self: _CharArray[str_],
234
+ sub: U_co,
235
+ start: i_co = ...,
236
+ end: None | i_co = ...,
237
+ ) -> NDArray[int_]: ...
238
+ @overload
239
+ def count(
240
+ self: _CharArray[bytes_],
241
+ sub: S_co,
242
+ start: i_co = ...,
243
+ end: None | i_co = ...,
244
+ ) -> NDArray[int_]: ...
245
+
246
+ def decode(
247
+ self: _CharArray[bytes_],
248
+ encoding: None | str = ...,
249
+ errors: None | str = ...,
250
+ ) -> _CharArray[str_]: ...
251
+
252
+ def encode(
253
+ self: _CharArray[str_],
254
+ encoding: None | str = ...,
255
+ errors: None | str = ...,
256
+ ) -> _CharArray[bytes_]: ...
257
+
258
+ @overload
259
+ def endswith(
260
+ self: _CharArray[str_],
261
+ suffix: U_co,
262
+ start: i_co = ...,
263
+ end: None | i_co = ...,
264
+ ) -> NDArray[np.bool]: ...
265
+ @overload
266
+ def endswith(
267
+ self: _CharArray[bytes_],
268
+ suffix: S_co,
269
+ start: i_co = ...,
270
+ end: None | i_co = ...,
271
+ ) -> NDArray[np.bool]: ...
272
+
273
+ def expandtabs(
274
+ self,
275
+ tabsize: i_co = ...,
276
+ ) -> chararray[_Shape, _CharDType_co]: ...
277
+
278
+ @overload
279
+ def find(
280
+ self: _CharArray[str_],
281
+ sub: U_co,
282
+ start: i_co = ...,
283
+ end: None | i_co = ...,
284
+ ) -> NDArray[int_]: ...
285
+ @overload
286
+ def find(
287
+ self: _CharArray[bytes_],
288
+ sub: S_co,
289
+ start: i_co = ...,
290
+ end: None | i_co = ...,
291
+ ) -> NDArray[int_]: ...
292
+
293
+ @overload
294
+ def index(
295
+ self: _CharArray[str_],
296
+ sub: U_co,
297
+ start: i_co = ...,
298
+ end: None | i_co = ...,
299
+ ) -> NDArray[int_]: ...
300
+ @overload
301
+ def index(
302
+ self: _CharArray[bytes_],
303
+ sub: S_co,
304
+ start: i_co = ...,
305
+ end: None | i_co = ...,
306
+ ) -> NDArray[int_]: ...
307
+
308
+ @overload
309
+ def join(
310
+ self: _CharArray[str_],
311
+ seq: U_co,
312
+ ) -> _CharArray[str_]: ...
313
+ @overload
314
+ def join(
315
+ self: _CharArray[bytes_],
316
+ seq: S_co,
317
+ ) -> _CharArray[bytes_]: ...
318
+
319
+ @overload
320
+ def ljust(
321
+ self: _CharArray[str_],
322
+ width: i_co,
323
+ fillchar: U_co = ...,
324
+ ) -> _CharArray[str_]: ...
325
+ @overload
326
+ def ljust(
327
+ self: _CharArray[bytes_],
328
+ width: i_co,
329
+ fillchar: S_co = ...,
330
+ ) -> _CharArray[bytes_]: ...
331
+
332
+ @overload
333
+ def lstrip(
334
+ self: _CharArray[str_],
335
+ chars: None | U_co = ...,
336
+ ) -> _CharArray[str_]: ...
337
+ @overload
338
+ def lstrip(
339
+ self: _CharArray[bytes_],
340
+ chars: None | S_co = ...,
341
+ ) -> _CharArray[bytes_]: ...
342
+
343
+ @overload
344
+ def partition(
345
+ self: _CharArray[str_],
346
+ sep: U_co,
347
+ ) -> _CharArray[str_]: ...
348
+ @overload
349
+ def partition(
350
+ self: _CharArray[bytes_],
351
+ sep: S_co,
352
+ ) -> _CharArray[bytes_]: ...
353
+
354
+ @overload
355
+ def replace(
356
+ self: _CharArray[str_],
357
+ old: U_co,
358
+ new: U_co,
359
+ count: None | i_co = ...,
360
+ ) -> _CharArray[str_]: ...
361
+ @overload
362
+ def replace(
363
+ self: _CharArray[bytes_],
364
+ old: S_co,
365
+ new: S_co,
366
+ count: None | i_co = ...,
367
+ ) -> _CharArray[bytes_]: ...
368
+
369
+ @overload
370
+ def rfind(
371
+ self: _CharArray[str_],
372
+ sub: U_co,
373
+ start: i_co = ...,
374
+ end: None | i_co = ...,
375
+ ) -> NDArray[int_]: ...
376
+ @overload
377
+ def rfind(
378
+ self: _CharArray[bytes_],
379
+ sub: S_co,
380
+ start: i_co = ...,
381
+ end: None | i_co = ...,
382
+ ) -> NDArray[int_]: ...
383
+
384
+ @overload
385
+ def rindex(
386
+ self: _CharArray[str_],
387
+ sub: U_co,
388
+ start: i_co = ...,
389
+ end: None | i_co = ...,
390
+ ) -> NDArray[int_]: ...
391
+ @overload
392
+ def rindex(
393
+ self: _CharArray[bytes_],
394
+ sub: S_co,
395
+ start: i_co = ...,
396
+ end: None | i_co = ...,
397
+ ) -> NDArray[int_]: ...
398
+
399
+ @overload
400
+ def rjust(
401
+ self: _CharArray[str_],
402
+ width: i_co,
403
+ fillchar: U_co = ...,
404
+ ) -> _CharArray[str_]: ...
405
+ @overload
406
+ def rjust(
407
+ self: _CharArray[bytes_],
408
+ width: i_co,
409
+ fillchar: S_co = ...,
410
+ ) -> _CharArray[bytes_]: ...
411
+
412
+ @overload
413
+ def rpartition(
414
+ self: _CharArray[str_],
415
+ sep: U_co,
416
+ ) -> _CharArray[str_]: ...
417
+ @overload
418
+ def rpartition(
419
+ self: _CharArray[bytes_],
420
+ sep: S_co,
421
+ ) -> _CharArray[bytes_]: ...
422
+
423
+ @overload
424
+ def rsplit(
425
+ self: _CharArray[str_],
426
+ sep: None | U_co = ...,
427
+ maxsplit: None | i_co = ...,
428
+ ) -> NDArray[object_]: ...
429
+ @overload
430
+ def rsplit(
431
+ self: _CharArray[bytes_],
432
+ sep: None | S_co = ...,
433
+ maxsplit: None | i_co = ...,
434
+ ) -> NDArray[object_]: ...
435
+
436
+ @overload
437
+ def rstrip(
438
+ self: _CharArray[str_],
439
+ chars: None | U_co = ...,
440
+ ) -> _CharArray[str_]: ...
441
+ @overload
442
+ def rstrip(
443
+ self: _CharArray[bytes_],
444
+ chars: None | S_co = ...,
445
+ ) -> _CharArray[bytes_]: ...
446
+
447
+ @overload
448
+ def split(
449
+ self: _CharArray[str_],
450
+ sep: None | U_co = ...,
451
+ maxsplit: None | i_co = ...,
452
+ ) -> NDArray[object_]: ...
453
+ @overload
454
+ def split(
455
+ self: _CharArray[bytes_],
456
+ sep: None | S_co = ...,
457
+ maxsplit: None | i_co = ...,
458
+ ) -> NDArray[object_]: ...
459
+
460
+ def splitlines(self, keepends: None | b_co = ...) -> NDArray[object_]: ...
461
+
462
+ @overload
463
+ def startswith(
464
+ self: _CharArray[str_],
465
+ prefix: U_co,
466
+ start: i_co = ...,
467
+ end: None | i_co = ...,
468
+ ) -> NDArray[np.bool]: ...
469
+ @overload
470
+ def startswith(
471
+ self: _CharArray[bytes_],
472
+ prefix: S_co,
473
+ start: i_co = ...,
474
+ end: None | i_co = ...,
475
+ ) -> NDArray[np.bool]: ...
476
+
477
+ @overload
478
+ def strip(
479
+ self: _CharArray[str_],
480
+ chars: None | U_co = ...,
481
+ ) -> _CharArray[str_]: ...
482
+ @overload
483
+ def strip(
484
+ self: _CharArray[bytes_],
485
+ chars: None | S_co = ...,
486
+ ) -> _CharArray[bytes_]: ...
487
+
488
+ @overload
489
+ def translate(
490
+ self: _CharArray[str_],
491
+ table: U_co,
492
+ deletechars: None | U_co = ...,
493
+ ) -> _CharArray[str_]: ...
494
+ @overload
495
+ def translate(
496
+ self: _CharArray[bytes_],
497
+ table: S_co,
498
+ deletechars: None | S_co = ...,
499
+ ) -> _CharArray[bytes_]: ...
500
+
501
+ def zfill(self, width: i_co) -> chararray[_Shape, _CharDType_co]: ...
502
+ def capitalize(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
503
+ def title(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
504
+ def swapcase(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
505
+ def lower(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
506
+ def upper(self) -> chararray[_ShapeT_co, _CharDType_co]: ...
507
+ def isalnum(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
508
+ def isalpha(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
509
+ def isdigit(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
510
+ def islower(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
511
+ def isspace(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
512
+ def istitle(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
513
+ def isupper(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
514
+ def isnumeric(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
515
+ def isdecimal(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
516
+
517
+
518
+ # Comparison
519
+ @overload
520
+ def equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
521
+ @overload
522
+ def equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
523
+ @overload
524
+ def equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
525
+
526
+ @overload
527
+ def not_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
528
+ @overload
529
+ def not_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
530
+ @overload
531
+ def not_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
532
+
533
+ @overload
534
+ def greater_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
535
+ @overload
536
+ def greater_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
537
+ @overload
538
+ def greater_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
539
+
540
+ @overload
541
+ def less_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
542
+ @overload
543
+ def less_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
544
+ @overload
545
+ def less_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
546
+
547
+ @overload
548
+ def greater(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
549
+ @overload
550
+ def greater(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
551
+ @overload
552
+ def greater(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
553
+
554
+ @overload
555
+ def less(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
556
+ @overload
557
+ def less(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
558
+ @overload
559
+ def less(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
560
+
561
+ @overload
562
+ def add(x1: U_co, x2: U_co) -> NDArray[np.str_]: ...
563
+ @overload
564
+ def add(x1: S_co, x2: S_co) -> NDArray[np.bytes_]: ...
565
+ @overload
566
+ def add(x1: _StringDTypeSupportsArray, x2: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
567
+ @overload
568
+ def add(x1: T_co, T_co) -> _StringDTypeOrUnicodeArray: ...
569
+
570
+ @overload
571
+ def multiply(a: U_co, i: i_co) -> NDArray[np.str_]: ...
572
+ @overload
573
+ def multiply(a: S_co, i: i_co) -> NDArray[np.bytes_]: ...
574
+ @overload
575
+ def multiply(a: _StringDTypeSupportsArray, i: i_co) -> _StringDTypeArray: ...
576
+ @overload
577
+ def multiply(a: T_co, i: i_co) -> _StringDTypeOrUnicodeArray: ...
578
+
579
+
580
+ @overload
581
+ def mod(a: U_co, value: Any) -> NDArray[np.str_]: ...
582
+ @overload
583
+ def mod(a: S_co, value: Any) -> NDArray[np.bytes_]: ...
584
+ @overload
585
+ def mod(a: _StringDTypeSupportsArray, value: Any) -> _StringDTypeArray: ...
586
+ @overload
587
+ def mod(a: T_co, value: Any) -> _StringDTypeOrUnicodeArray: ...
588
+
589
+ @overload
590
+ def capitalize(a: U_co) -> NDArray[str_]: ...
591
+ @overload
592
+ def capitalize(a: S_co) -> NDArray[bytes_]: ...
593
+ @overload
594
+ def capitalize(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
595
+ @overload
596
+ def capitalize(a: T_co) -> _StringDTypeOrUnicodeArray: ...
597
+
598
+ @overload
599
+ def center(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
600
+ @overload
601
+ def center(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
602
+ @overload
603
+ def center(a: _StringDTypeSupportsArray, width: i_co, fillchar: _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
604
+ @overload
605
+ def center(a: T_co, width: i_co, fillchar: T_co = ...) -> _StringDTypeOrUnicodeArray: ...
606
+
607
+ def decode(
608
+ a: S_co,
609
+ encoding: None | str = ...,
610
+ errors: None | str = ...,
611
+ ) -> NDArray[str_]: ...
612
+ def encode(
613
+ a: U_co | T_co,
614
+ encoding: None | str = ...,
615
+ errors: None | str = ...,
616
+ ) -> NDArray[bytes_]: ...
617
+
618
+ @overload
619
+ def expandtabs(a: U_co, tabsize: i_co = ...) -> NDArray[str_]: ...
620
+ @overload
621
+ def expandtabs(a: S_co, tabsize: i_co = ...) -> NDArray[bytes_]: ...
622
+ @overload
623
+ def expandtabs(a: _StringDTypeSupportsArray, tabsize: i_co = ...) -> _StringDTypeArray: ...
624
+ @overload
625
+ def expandtabs(a: T_co, tabsize: i_co = ...) -> _StringDTypeOrUnicodeArray: ...
626
+
627
+ @overload
628
+ def join(sep: U_co, seq: U_co) -> NDArray[str_]: ...
629
+ @overload
630
+ def join(sep: S_co, seq: S_co) -> NDArray[bytes_]: ...
631
+ @overload
632
+ def join(sep: _StringDTypeSupportsArray, seq: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
633
+ @overload
634
+ def join(sep: T_co, seq: T_co) -> _StringDTypeOrUnicodeArray: ...
635
+
636
+ @overload
637
+ def ljust(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
638
+ @overload
639
+ def ljust(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
640
+ @overload
641
+ def ljust(a: _StringDTypeSupportsArray, width: i_co, fillchar: _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
642
+ @overload
643
+ def ljust(a: T_co, width: i_co, fillchar: T_co = ...) -> _StringDTypeOrUnicodeArray: ...
644
+
645
+ @overload
646
+ def lower(a: U_co) -> NDArray[str_]: ...
647
+ @overload
648
+ def lower(a: S_co) -> NDArray[bytes_]: ...
649
+ @overload
650
+ def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
651
+ @overload
652
+ def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
653
+
654
+ @overload
655
+ def lstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
656
+ @overload
657
+ def lstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
658
+ @overload
659
+ def lstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
660
+ @overload
661
+ def lstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
662
+
663
+ @overload
664
+ def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
665
+ @overload
666
+ def partition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
667
+ @overload
668
+ def partition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
669
+ @overload
670
+ def partition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
671
+
672
+ @overload
673
+ def replace(
674
+ a: U_co,
675
+ old: U_co,
676
+ new: U_co,
677
+ count: None | i_co = ...,
678
+ ) -> NDArray[str_]: ...
679
+ @overload
680
+ def replace(
681
+ a: S_co,
682
+ old: S_co,
683
+ new: S_co,
684
+ count: None | i_co = ...,
685
+ ) -> NDArray[bytes_]: ...
686
+ @overload
687
+ def replace(
688
+ a: _StringDTypeSupportsArray,
689
+ old: _StringDTypeSupportsArray,
690
+ new: _StringDTypeSupportsArray,
691
+ count: i_co = ...,
692
+ ) -> _StringDTypeArray: ...
693
+ @overload
694
+ def replace(
695
+ a: T_co,
696
+ old: T_co,
697
+ new: T_co,
698
+ count: i_co = ...,
699
+ ) -> _StringDTypeOrUnicodeArray: ...
700
+
701
+ @overload
702
+ def rjust(
703
+ a: U_co,
704
+ width: i_co,
705
+ fillchar: U_co = ...,
706
+ ) -> NDArray[str_]: ...
707
+ @overload
708
+ def rjust(
709
+ a: S_co,
710
+ width: i_co,
711
+ fillchar: S_co = ...,
712
+ ) -> NDArray[bytes_]: ...
713
+ @overload
714
+ def rjust(
715
+ a: _StringDTypeSupportsArray,
716
+ width: i_co,
717
+ fillchar: _StringDTypeSupportsArray = ...,
718
+ ) -> _StringDTypeArray: ...
719
+ @overload
720
+ def rjust(
721
+ a: T_co,
722
+ width: i_co,
723
+ fillchar: T_co = ...,
724
+ ) -> _StringDTypeOrUnicodeArray: ...
725
+
726
+ @overload
727
+ def rpartition(a: U_co, sep: U_co) -> NDArray[str_]: ...
728
+ @overload
729
+ def rpartition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
730
+ @overload
731
+ def rpartition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
732
+ @overload
733
+ def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
734
+
735
+ @overload
736
+ def rsplit(
737
+ a: U_co,
738
+ sep: None | U_co = ...,
739
+ maxsplit: None | i_co = ...,
740
+ ) -> NDArray[object_]: ...
741
+ @overload
742
+ def rsplit(
743
+ a: S_co,
744
+ sep: None | S_co = ...,
745
+ maxsplit: None | i_co = ...,
746
+ ) -> NDArray[object_]: ...
747
+ @overload
748
+ def rsplit(
749
+ a: _StringDTypeSupportsArray,
750
+ sep: None | _StringDTypeSupportsArray = ...,
751
+ maxsplit: None | i_co = ...,
752
+ ) -> NDArray[object_]: ...
753
+ @overload
754
+ def rsplit(
755
+ a: T_co,
756
+ sep: None | T_co = ...,
757
+ maxsplit: None | i_co = ...,
758
+ ) -> NDArray[object_]: ...
759
+
760
+ @overload
761
+ def rstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
762
+ @overload
763
+ def rstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
764
+ @overload
765
+ def rstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
766
+ @overload
767
+ def rstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
768
+
769
+ @overload
770
+ def split(
771
+ a: U_co,
772
+ sep: None | U_co = ...,
773
+ maxsplit: None | i_co = ...,
774
+ ) -> NDArray[object_]: ...
775
+ @overload
776
+ def split(
777
+ a: S_co,
778
+ sep: None | S_co = ...,
779
+ maxsplit: None | i_co = ...,
780
+ ) -> NDArray[object_]: ...
781
+ @overload
782
+ def split(
783
+ a: _StringDTypeSupportsArray,
784
+ sep: None | _StringDTypeSupportsArray = ...,
785
+ maxsplit: None | i_co = ...,
786
+ ) -> NDArray[object_]: ...
787
+ @overload
788
+ def split(
789
+ a: T_co,
790
+ sep: None | T_co = ...,
791
+ maxsplit: None | i_co = ...,
792
+ ) -> NDArray[object_]: ...
793
+
794
+ def splitlines(a: UST_co, keepends: None | b_co = ...) -> NDArray[np.object_]: ...
795
+
796
+ @overload
797
+ def strip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
798
+ @overload
799
+ def strip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
800
+ @overload
801
+ def strip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
802
+ @overload
803
+ def strip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
804
+
805
+ @overload
806
+ def swapcase(a: U_co) -> NDArray[str_]: ...
807
+ @overload
808
+ def swapcase(a: S_co) -> NDArray[bytes_]: ...
809
+ @overload
810
+ def swapcase(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
811
+ @overload
812
+ def swapcase(a: T_co) -> _StringDTypeOrUnicodeArray: ...
813
+
814
+ @overload
815
+ def title(a: U_co) -> NDArray[str_]: ...
816
+ @overload
817
+ def title(a: S_co) -> NDArray[bytes_]: ...
818
+ @overload
819
+ def title(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
820
+ @overload
821
+ def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
822
+
823
+ @overload
824
+ def translate(
825
+ a: U_co,
826
+ table: str,
827
+ deletechars: None | str = ...,
828
+ ) -> NDArray[str_]: ...
829
+ @overload
830
+ def translate(
831
+ a: S_co,
832
+ table: str,
833
+ deletechars: None | str = ...,
834
+ ) -> NDArray[bytes_]: ...
835
+ @overload
836
+ def translate(
837
+ a: _StringDTypeSupportsArray,
838
+ table: str,
839
+ deletechars: None | str = ...,
840
+ ) -> _StringDTypeArray: ...
841
+ @overload
842
+ def translate(
843
+ a: T_co,
844
+ table: str,
845
+ deletechars: None | str = ...,
846
+ ) -> _StringDTypeOrUnicodeArray: ...
847
+
848
+ @overload
849
+ def upper(a: U_co) -> NDArray[str_]: ...
850
+ @overload
851
+ def upper(a: S_co) -> NDArray[bytes_]: ...
852
+ @overload
853
+ def upper(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
854
+ @overload
855
+ def upper(a: T_co) -> _StringDTypeOrUnicodeArray: ...
856
+
857
+ @overload
858
+ def zfill(a: U_co, width: i_co) -> NDArray[str_]: ...
859
+ @overload
860
+ def zfill(a: S_co, width: i_co) -> NDArray[bytes_]: ...
861
+ @overload
862
+ def zfill(a: _StringDTypeSupportsArray, width: i_co) -> _StringDTypeArray: ...
863
+ @overload
864
+ def zfill(a: T_co, width: i_co) -> _StringDTypeOrUnicodeArray: ...
865
+
866
+ # String information
867
+ @overload
868
+ def count(
869
+ a: U_co,
870
+ sub: U_co,
871
+ start: i_co = ...,
872
+ end: None | i_co = ...,
873
+ ) -> NDArray[int_]: ...
874
+ @overload
875
+ def count(
876
+ a: S_co,
877
+ sub: S_co,
878
+ start: i_co = ...,
879
+ end: None | i_co = ...,
880
+ ) -> NDArray[int_]: ...
881
+ @overload
882
+ def count(
883
+ a: T_co,
884
+ sub: T_co,
885
+ start: i_co = ...,
886
+ end: i_co | None = ...,
887
+ ) -> NDArray[np.int_]: ...
888
+
889
+ @overload
890
+ def endswith(
891
+ a: U_co,
892
+ suffix: U_co,
893
+ start: i_co = ...,
894
+ end: None | i_co = ...,
895
+ ) -> NDArray[np.bool]: ...
896
+ @overload
897
+ def endswith(
898
+ a: S_co,
899
+ suffix: S_co,
900
+ start: i_co = ...,
901
+ end: None | i_co = ...,
902
+ ) -> NDArray[np.bool]: ...
903
+ @overload
904
+ def endswith(
905
+ a: T_co,
906
+ suffix: T_co,
907
+ start: i_co = ...,
908
+ end: i_co | None = ...,
909
+ ) -> NDArray[np.bool]: ...
910
+
911
+ @overload
912
+ def find(
913
+ a: U_co,
914
+ sub: U_co,
915
+ start: i_co = ...,
916
+ end: None | i_co = ...,
917
+ ) -> NDArray[int_]: ...
918
+ @overload
919
+ def find(
920
+ a: S_co,
921
+ sub: S_co,
922
+ start: i_co = ...,
923
+ end: None | i_co = ...,
924
+ ) -> NDArray[int_]: ...
925
+ @overload
926
+ def find(
927
+ a: T_co,
928
+ sub: T_co,
929
+ start: i_co = ...,
930
+ end: i_co | None = ...,
931
+ ) -> NDArray[np.int_]: ...
932
+
933
+ @overload
934
+ def index(
935
+ a: U_co,
936
+ sub: U_co,
937
+ start: i_co = ...,
938
+ end: None | i_co = ...,
939
+ ) -> NDArray[int_]: ...
940
+ @overload
941
+ def index(
942
+ a: S_co,
943
+ sub: S_co,
944
+ start: i_co = ...,
945
+ end: None | i_co = ...,
946
+ ) -> NDArray[int_]: ...
947
+ @overload
948
+ def index(
949
+ a: T_co,
950
+ sub: T_co,
951
+ start: i_co = ...,
952
+ end: i_co | None = ...,
953
+ ) -> NDArray[np.int_]: ...
954
+
955
+ def isalpha(a: UST_co) -> NDArray[np.bool]: ...
956
+ def isalnum(a: UST_co) -> NDArray[np.bool]: ...
957
+ def isdecimal(a: U_co | T_co) -> NDArray[np.bool]: ...
958
+ def isdigit(a: UST_co) -> NDArray[np.bool]: ...
959
+ def islower(a: UST_co) -> NDArray[np.bool]: ...
960
+ def isnumeric(a: U_co | T_co) -> NDArray[np.bool]: ...
961
+ def isspace(a: UST_co) -> NDArray[np.bool]: ...
962
+ def istitle(a: UST_co) -> NDArray[np.bool]: ...
963
+ def isupper(a: UST_co) -> NDArray[np.bool]: ...
964
+
965
+ @overload
966
+ def rfind(
967
+ a: U_co,
968
+ sub: U_co,
969
+ start: i_co = ...,
970
+ end: None | i_co = ...,
971
+ ) -> NDArray[int_]: ...
972
+ @overload
973
+ def rfind(
974
+ a: S_co,
975
+ sub: S_co,
976
+ start: i_co = ...,
977
+ end: None | i_co = ...,
978
+ ) -> NDArray[int_]: ...
979
+ @overload
980
+ def rfind(
981
+ a: T_co,
982
+ sub: T_co,
983
+ start: i_co = ...,
984
+ end: i_co | None = ...,
985
+ ) -> NDArray[np.int_]: ...
986
+
987
+ @overload
988
+ def rindex(
989
+ a: U_co,
990
+ sub: U_co,
991
+ start: i_co = ...,
992
+ end: None | i_co = ...,
993
+ ) -> NDArray[int_]: ...
994
+ @overload
995
+ def rindex(
996
+ a: S_co,
997
+ sub: S_co,
998
+ start: i_co = ...,
999
+ end: None | i_co = ...,
1000
+ ) -> NDArray[int_]: ...
1001
+ @overload
1002
+ def rindex(
1003
+ a: T_co,
1004
+ sub: T_co,
1005
+ start: i_co = ...,
1006
+ end: i_co | None = ...,
1007
+ ) -> NDArray[np.int_]: ...
1008
+
1009
+ @overload
1010
+ def startswith(
1011
+ a: U_co,
1012
+ prefix: U_co,
1013
+ start: i_co = ...,
1014
+ end: None | i_co = ...,
1015
+ ) -> NDArray[np.bool]: ...
1016
+ @overload
1017
+ def startswith(
1018
+ a: S_co,
1019
+ prefix: S_co,
1020
+ start: i_co = ...,
1021
+ end: None | i_co = ...,
1022
+ ) -> NDArray[np.bool]: ...
1023
+ @overload
1024
+ def startswith(
1025
+ a: T_co,
1026
+ suffix: T_co,
1027
+ start: i_co = ...,
1028
+ end: i_co | None = ...,
1029
+ ) -> NDArray[np.bool]: ...
1030
+
1031
+ def str_len(A: UST_co) -> NDArray[int_]: ...
1032
+
1033
+ # Overload 1 and 2: str- or bytes-based array-likes
1034
+ # overload 3: arbitrary object with unicode=False (-> bytes_)
1035
+ # overload 4: arbitrary object with unicode=True (-> str_)
1036
+ @overload
1037
+ def array(
1038
+ obj: U_co,
1039
+ itemsize: None | int = ...,
1040
+ copy: bool = ...,
1041
+ unicode: L[False] = ...,
1042
+ order: _OrderKACF = ...,
1043
+ ) -> _CharArray[str_]: ...
1044
+ @overload
1045
+ def array(
1046
+ obj: S_co,
1047
+ itemsize: None | int = ...,
1048
+ copy: bool = ...,
1049
+ unicode: L[False] = ...,
1050
+ order: _OrderKACF = ...,
1051
+ ) -> _CharArray[bytes_]: ...
1052
+ @overload
1053
+ def array(
1054
+ obj: object,
1055
+ itemsize: None | int = ...,
1056
+ copy: bool = ...,
1057
+ unicode: L[False] = ...,
1058
+ order: _OrderKACF = ...,
1059
+ ) -> _CharArray[bytes_]: ...
1060
+ @overload
1061
+ def array(
1062
+ obj: object,
1063
+ itemsize: None | int = ...,
1064
+ copy: bool = ...,
1065
+ unicode: L[True] = ...,
1066
+ order: _OrderKACF = ...,
1067
+ ) -> _CharArray[str_]: ...
1068
+
1069
+ @overload
1070
+ def asarray(
1071
+ obj: U_co,
1072
+ itemsize: None | int = ...,
1073
+ unicode: L[False] = ...,
1074
+ order: _OrderKACF = ...,
1075
+ ) -> _CharArray[str_]: ...
1076
+ @overload
1077
+ def asarray(
1078
+ obj: S_co,
1079
+ itemsize: None | int = ...,
1080
+ unicode: L[False] = ...,
1081
+ order: _OrderKACF = ...,
1082
+ ) -> _CharArray[bytes_]: ...
1083
+ @overload
1084
+ def asarray(
1085
+ obj: object,
1086
+ itemsize: None | int = ...,
1087
+ unicode: L[False] = ...,
1088
+ order: _OrderKACF = ...,
1089
+ ) -> _CharArray[bytes_]: ...
1090
+ @overload
1091
+ def asarray(
1092
+ obj: object,
1093
+ itemsize: None | int = ...,
1094
+ unicode: L[True] = ...,
1095
+ order: _OrderKACF = ...,
1096
+ ) -> _CharArray[str_]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/einsumfunc.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of optimized einsum.
3
+
4
+ """
5
+ import itertools
6
+ import operator
7
+
8
+ from numpy._core.multiarray import c_einsum
9
+ from numpy._core.numeric import asanyarray, tensordot
10
+ from numpy._core.overrides import array_function_dispatch
11
+
12
+ __all__ = ['einsum', 'einsum_path']
13
+
14
+ # importing string for string.ascii_letters would be too slow
15
+ # the first import before caching has been measured to take 800 µs (#23777)
16
+ einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
17
+ einsum_symbols_set = set(einsum_symbols)
18
+
19
+
20
+ def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
21
+ """
22
+ Computes the number of FLOPS in the contraction.
23
+
24
+ Parameters
25
+ ----------
26
+ idx_contraction : iterable
27
+ The indices involved in the contraction
28
+ inner : bool
29
+ Does this contraction require an inner product?
30
+ num_terms : int
31
+ The number of terms in a contraction
32
+ size_dictionary : dict
33
+ The size of each of the indices in idx_contraction
34
+
35
+ Returns
36
+ -------
37
+ flop_count : int
38
+ The total number of FLOPS required for the contraction.
39
+
40
+ Examples
41
+ --------
42
+
43
+ >>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
44
+ 30
45
+
46
+ >>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
47
+ 60
48
+
49
+ """
50
+
51
+ overall_size = _compute_size_by_dict(idx_contraction, size_dictionary)
52
+ op_factor = max(1, num_terms - 1)
53
+ if inner:
54
+ op_factor += 1
55
+
56
+ return overall_size * op_factor
57
+
58
+ def _compute_size_by_dict(indices, idx_dict):
59
+ """
60
+ Computes the product of the elements in indices based on the dictionary
61
+ idx_dict.
62
+
63
+ Parameters
64
+ ----------
65
+ indices : iterable
66
+ Indices to base the product on.
67
+ idx_dict : dictionary
68
+ Dictionary of index sizes
69
+
70
+ Returns
71
+ -------
72
+ ret : int
73
+ The resulting product.
74
+
75
+ Examples
76
+ --------
77
+ >>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
78
+ 90
79
+
80
+ """
81
+ ret = 1
82
+ for i in indices:
83
+ ret *= idx_dict[i]
84
+ return ret
85
+
86
+
87
+ def _find_contraction(positions, input_sets, output_set):
88
+ """
89
+ Finds the contraction for a given set of input and output sets.
90
+
91
+ Parameters
92
+ ----------
93
+ positions : iterable
94
+ Integer positions of terms used in the contraction.
95
+ input_sets : list
96
+ List of sets that represent the lhs side of the einsum subscript
97
+ output_set : set
98
+ Set that represents the rhs side of the overall einsum subscript
99
+
100
+ Returns
101
+ -------
102
+ new_result : set
103
+ The indices of the resulting contraction
104
+ remaining : list
105
+ List of sets that have not been contracted, the new set is appended to
106
+ the end of this list
107
+ idx_removed : set
108
+ Indices removed from the entire contraction
109
+ idx_contraction : set
110
+ The indices used in the current contraction
111
+
112
+ Examples
113
+ --------
114
+
115
+ # A simple dot product test case
116
+ >>> pos = (0, 1)
117
+ >>> isets = [set('ab'), set('bc')]
118
+ >>> oset = set('ac')
119
+ >>> _find_contraction(pos, isets, oset)
120
+ ({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})
121
+
122
+ # A more complex case with additional terms in the contraction
123
+ >>> pos = (0, 2)
124
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
125
+ >>> oset = set('ac')
126
+ >>> _find_contraction(pos, isets, oset)
127
+ ({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
128
+ """
129
+
130
+ idx_contract = set()
131
+ idx_remain = output_set.copy()
132
+ remaining = []
133
+ for ind, value in enumerate(input_sets):
134
+ if ind in positions:
135
+ idx_contract |= value
136
+ else:
137
+ remaining.append(value)
138
+ idx_remain |= value
139
+
140
+ new_result = idx_remain & idx_contract
141
+ idx_removed = (idx_contract - new_result)
142
+ remaining.append(new_result)
143
+
144
+ return (new_result, remaining, idx_removed, idx_contract)
145
+
146
+
147
+ def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
148
+ """
149
+ Computes all possible pair contractions, sieves the results based
150
+ on ``memory_limit`` and returns the lowest cost path. This algorithm
151
+ scales factorial with respect to the elements in the list ``input_sets``.
152
+
153
+ Parameters
154
+ ----------
155
+ input_sets : list
156
+ List of sets that represent the lhs side of the einsum subscript
157
+ output_set : set
158
+ Set that represents the rhs side of the overall einsum subscript
159
+ idx_dict : dictionary
160
+ Dictionary of index sizes
161
+ memory_limit : int
162
+ The maximum number of elements in a temporary array
163
+
164
+ Returns
165
+ -------
166
+ path : list
167
+ The optimal contraction order within the memory limit constraint.
168
+
169
+ Examples
170
+ --------
171
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
172
+ >>> oset = set()
173
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
174
+ >>> _optimal_path(isets, oset, idx_sizes, 5000)
175
+ [(0, 2), (0, 1)]
176
+ """
177
+
178
+ full_results = [(0, [], input_sets)]
179
+ for iteration in range(len(input_sets) - 1):
180
+ iter_results = []
181
+
182
+ # Compute all unique pairs
183
+ for curr in full_results:
184
+ cost, positions, remaining = curr
185
+ for con in itertools.combinations(
186
+ range(len(input_sets) - iteration), 2
187
+ ):
188
+
189
+ # Find the contraction
190
+ cont = _find_contraction(con, remaining, output_set)
191
+ new_result, new_input_sets, idx_removed, idx_contract = cont
192
+
193
+ # Sieve the results based on memory_limit
194
+ new_size = _compute_size_by_dict(new_result, idx_dict)
195
+ if new_size > memory_limit:
196
+ continue
197
+
198
+ # Build (total_cost, positions, indices_remaining)
199
+ total_cost = cost + _flop_count(
200
+ idx_contract, idx_removed, len(con), idx_dict
201
+ )
202
+ new_pos = positions + [con]
203
+ iter_results.append((total_cost, new_pos, new_input_sets))
204
+
205
+ # Update combinatorial list, if we did not find anything return best
206
+ # path + remaining contractions
207
+ if iter_results:
208
+ full_results = iter_results
209
+ else:
210
+ path = min(full_results, key=lambda x: x[0])[1]
211
+ path += [tuple(range(len(input_sets) - iteration))]
212
+ return path
213
+
214
+ # If we have not found anything return single einsum contraction
215
+ if len(full_results) == 0:
216
+ return [tuple(range(len(input_sets)))]
217
+
218
+ path = min(full_results, key=lambda x: x[0])[1]
219
+ return path
220
+
221
+ def _parse_possible_contraction(
222
+ positions, input_sets, output_set, idx_dict,
223
+ memory_limit, path_cost, naive_cost
224
+ ):
225
+ """Compute the cost (removed size + flops) and resultant indices for
226
+ performing the contraction specified by ``positions``.
227
+
228
+ Parameters
229
+ ----------
230
+ positions : tuple of int
231
+ The locations of the proposed tensors to contract.
232
+ input_sets : list of sets
233
+ The indices found on each tensors.
234
+ output_set : set
235
+ The output indices of the expression.
236
+ idx_dict : dict
237
+ Mapping of each index to its size.
238
+ memory_limit : int
239
+ The total allowed size for an intermediary tensor.
240
+ path_cost : int
241
+ The contraction cost so far.
242
+ naive_cost : int
243
+ The cost of the unoptimized expression.
244
+
245
+ Returns
246
+ -------
247
+ cost : (int, int)
248
+ A tuple containing the size of any indices removed, and the flop cost.
249
+ positions : tuple of int
250
+ The locations of the proposed tensors to contract.
251
+ new_input_sets : list of sets
252
+ The resulting new list of indices if this proposed contraction
253
+ is performed.
254
+
255
+ """
256
+
257
+ # Find the contraction
258
+ contract = _find_contraction(positions, input_sets, output_set)
259
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
260
+
261
+ # Sieve the results based on memory_limit
262
+ new_size = _compute_size_by_dict(idx_result, idx_dict)
263
+ if new_size > memory_limit:
264
+ return None
265
+
266
+ # Build sort tuple
267
+ old_sizes = (
268
+ _compute_size_by_dict(input_sets[p], idx_dict) for p in positions
269
+ )
270
+ removed_size = sum(old_sizes) - new_size
271
+
272
+ # NB: removed_size used to be just the size of any removed indices i.e.:
273
+ # helpers.compute_size_by_dict(idx_removed, idx_dict)
274
+ cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict)
275
+ sort = (-removed_size, cost)
276
+
277
+ # Sieve based on total cost as well
278
+ if (path_cost + cost) > naive_cost:
279
+ return None
280
+
281
+ # Add contraction to possible choices
282
+ return [sort, positions, new_input_sets]
283
+
284
+
285
+ def _update_other_results(results, best):
286
+ """Update the positions and provisional input_sets of ``results``
287
+ based on performing the contraction result ``best``. Remove any
288
+ involving the tensors contracted.
289
+
290
+ Parameters
291
+ ----------
292
+ results : list
293
+ List of contraction results produced by
294
+ ``_parse_possible_contraction``.
295
+ best : list
296
+ The best contraction of ``results`` i.e. the one that
297
+ will be performed.
298
+
299
+ Returns
300
+ -------
301
+ mod_results : list
302
+ The list of modified results, updated with outcome of
303
+ ``best`` contraction.
304
+ """
305
+
306
+ best_con = best[1]
307
+ bx, by = best_con
308
+ mod_results = []
309
+
310
+ for cost, (x, y), con_sets in results:
311
+
312
+ # Ignore results involving tensors just contracted
313
+ if x in best_con or y in best_con:
314
+ continue
315
+
316
+ # Update the input_sets
317
+ del con_sets[by - int(by > x) - int(by > y)]
318
+ del con_sets[bx - int(bx > x) - int(bx > y)]
319
+ con_sets.insert(-1, best[2][-1])
320
+
321
+ # Update the position indices
322
+ mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)
323
+ mod_results.append((cost, mod_con, con_sets))
324
+
325
+ return mod_results
326
+
327
+ def _greedy_path(input_sets, output_set, idx_dict, memory_limit):
328
+ """
329
+ Finds the path by contracting the best pair until the input list is
330
+ exhausted. The best pair is found by minimizing the tuple
331
+ ``(-prod(indices_removed), cost)``. What this amounts to is prioritizing
332
+ matrix multiplication or inner product operations, then Hadamard like
333
+ operations, and finally outer operations. Outer products are limited by
334
+ ``memory_limit``. This algorithm scales cubically with respect to the
335
+ number of elements in the list ``input_sets``.
336
+
337
+ Parameters
338
+ ----------
339
+ input_sets : list
340
+ List of sets that represent the lhs side of the einsum subscript
341
+ output_set : set
342
+ Set that represents the rhs side of the overall einsum subscript
343
+ idx_dict : dictionary
344
+ Dictionary of index sizes
345
+ memory_limit : int
346
+ The maximum number of elements in a temporary array
347
+
348
+ Returns
349
+ -------
350
+ path : list
351
+ The greedy contraction order within the memory limit constraint.
352
+
353
+ Examples
354
+ --------
355
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
356
+ >>> oset = set()
357
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
358
+ >>> _greedy_path(isets, oset, idx_sizes, 5000)
359
+ [(0, 2), (0, 1)]
360
+ """
361
+
362
+ # Handle trivial cases that leaked through
363
+ if len(input_sets) == 1:
364
+ return [(0,)]
365
+ elif len(input_sets) == 2:
366
+ return [(0, 1)]
367
+
368
+ # Build up a naive cost
369
+ contract = _find_contraction(
370
+ range(len(input_sets)), input_sets, output_set
371
+ )
372
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
373
+ naive_cost = _flop_count(
374
+ idx_contract, idx_removed, len(input_sets), idx_dict
375
+ )
376
+
377
+ # Initially iterate over all pairs
378
+ comb_iter = itertools.combinations(range(len(input_sets)), 2)
379
+ known_contractions = []
380
+
381
+ path_cost = 0
382
+ path = []
383
+
384
+ for iteration in range(len(input_sets) - 1):
385
+
386
+ # Iterate over all pairs on the first step, only previously
387
+ # found pairs on subsequent steps
388
+ for positions in comb_iter:
389
+
390
+ # Always initially ignore outer products
391
+ if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):
392
+ continue
393
+
394
+ result = _parse_possible_contraction(
395
+ positions, input_sets, output_set, idx_dict,
396
+ memory_limit, path_cost, naive_cost
397
+ )
398
+ if result is not None:
399
+ known_contractions.append(result)
400
+
401
+ # If we do not have a inner contraction, rescan pairs
402
+ # including outer products
403
+ if len(known_contractions) == 0:
404
+
405
+ # Then check the outer products
406
+ for positions in itertools.combinations(
407
+ range(len(input_sets)), 2
408
+ ):
409
+ result = _parse_possible_contraction(
410
+ positions, input_sets, output_set, idx_dict,
411
+ memory_limit, path_cost, naive_cost
412
+ )
413
+ if result is not None:
414
+ known_contractions.append(result)
415
+
416
+ # If we still did not find any remaining contractions,
417
+ # default back to einsum like behavior
418
+ if len(known_contractions) == 0:
419
+ path.append(tuple(range(len(input_sets))))
420
+ break
421
+
422
+ # Sort based on first index
423
+ best = min(known_contractions, key=lambda x: x[0])
424
+
425
+ # Now propagate as many unused contractions as possible
426
+ # to the next iteration
427
+ known_contractions = _update_other_results(known_contractions, best)
428
+
429
+ # Next iteration only compute contractions with the new tensor
430
+ # All other contractions have been accounted for
431
+ input_sets = best[2]
432
+ new_tensor_pos = len(input_sets) - 1
433
+ comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos))
434
+
435
+ # Update path and total cost
436
+ path.append(best[1])
437
+ path_cost += best[0][1]
438
+
439
+ return path
440
+
441
+
442
+ def _can_dot(inputs, result, idx_removed):
443
+ """
444
+ Checks if we can use BLAS (np.tensordot) call and its beneficial to do so.
445
+
446
+ Parameters
447
+ ----------
448
+ inputs : list of str
449
+ Specifies the subscripts for summation.
450
+ result : str
451
+ Resulting summation.
452
+ idx_removed : set
453
+ Indices that are removed in the summation
454
+
455
+
456
+ Returns
457
+ -------
458
+ type : bool
459
+ Returns true if BLAS should and can be used, else False
460
+
461
+ Notes
462
+ -----
463
+ If the operations is BLAS level 1 or 2 and is not already aligned
464
+ we default back to einsum as the memory movement to copy is more
465
+ costly than the operation itself.
466
+
467
+
468
+ Examples
469
+ --------
470
+
471
+ # Standard GEMM operation
472
+ >>> _can_dot(['ij', 'jk'], 'ik', set('j'))
473
+ True
474
+
475
+ # Can use the standard BLAS, but requires odd data movement
476
+ >>> _can_dot(['ijj', 'jk'], 'ik', set('j'))
477
+ False
478
+
479
+ # DDOT where the memory is not aligned
480
+ >>> _can_dot(['ijk', 'ikj'], '', set('ijk'))
481
+ False
482
+
483
+ """
484
+
485
+ # All `dot` calls remove indices
486
+ if len(idx_removed) == 0:
487
+ return False
488
+
489
+ # BLAS can only handle two operands
490
+ if len(inputs) != 2:
491
+ return False
492
+
493
+ input_left, input_right = inputs
494
+
495
+ for c in set(input_left + input_right):
496
+ # can't deal with repeated indices on same input or more than 2 total
497
+ nl, nr = input_left.count(c), input_right.count(c)
498
+ if (nl > 1) or (nr > 1) or (nl + nr > 2):
499
+ return False
500
+
501
+ # can't do implicit summation or dimension collapse e.g.
502
+ # "ab,bc->c" (implicitly sum over 'a')
503
+ # "ab,ca->ca" (take diagonal of 'a')
504
+ if nl + nr - 1 == int(c in result):
505
+ return False
506
+
507
+ # Build a few temporaries
508
+ set_left = set(input_left)
509
+ set_right = set(input_right)
510
+ keep_left = set_left - idx_removed
511
+ keep_right = set_right - idx_removed
512
+ rs = len(idx_removed)
513
+
514
+ # At this point we are a DOT, GEMV, or GEMM operation
515
+
516
+ # Handle inner products
517
+
518
+ # DDOT with aligned data
519
+ if input_left == input_right:
520
+ return True
521
+
522
+ # DDOT without aligned data (better to use einsum)
523
+ if set_left == set_right:
524
+ return False
525
+
526
+ # Handle the 4 possible (aligned) GEMV or GEMM cases
527
+
528
+ # GEMM or GEMV no transpose
529
+ if input_left[-rs:] == input_right[:rs]:
530
+ return True
531
+
532
+ # GEMM or GEMV transpose both
533
+ if input_left[:rs] == input_right[-rs:]:
534
+ return True
535
+
536
+ # GEMM or GEMV transpose right
537
+ if input_left[-rs:] == input_right[-rs:]:
538
+ return True
539
+
540
+ # GEMM or GEMV transpose left
541
+ if input_left[:rs] == input_right[:rs]:
542
+ return True
543
+
544
+ # Einsum is faster than GEMV if we have to copy data
545
+ if not keep_left or not keep_right:
546
+ return False
547
+
548
+ # We are a matrix-matrix product, but we need to copy data
549
+ return True
550
+
551
+
552
+ def _parse_einsum_input(operands):
553
+ """
554
+ A reproduction of einsum c side einsum parsing in python.
555
+
556
+ Returns
557
+ -------
558
+ input_strings : str
559
+ Parsed input strings
560
+ output_string : str
561
+ Parsed output string
562
+ operands : list of array_like
563
+ The operands to use in the numpy contraction
564
+
565
+ Examples
566
+ --------
567
+ The operand list is simplified to reduce printing:
568
+
569
+ >>> np.random.seed(123)
570
+ >>> a = np.random.rand(4, 4)
571
+ >>> b = np.random.rand(4, 4, 4)
572
+ >>> _parse_einsum_input(('...a,...a->...', a, b))
573
+ ('za,xza', 'xz', [a, b]) # may vary
574
+
575
+ >>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
576
+ ('za,xza', 'xz', [a, b]) # may vary
577
+ """
578
+
579
+ if len(operands) == 0:
580
+ raise ValueError("No input operands")
581
+
582
+ if isinstance(operands[0], str):
583
+ subscripts = operands[0].replace(" ", "")
584
+ operands = [asanyarray(v) for v in operands[1:]]
585
+
586
+ # Ensure all characters are valid
587
+ for s in subscripts:
588
+ if s in '.,->':
589
+ continue
590
+ if s not in einsum_symbols:
591
+ raise ValueError("Character %s is not a valid symbol." % s)
592
+
593
+ else:
594
+ tmp_operands = list(operands)
595
+ operand_list = []
596
+ subscript_list = []
597
+ for p in range(len(operands) // 2):
598
+ operand_list.append(tmp_operands.pop(0))
599
+ subscript_list.append(tmp_operands.pop(0))
600
+
601
+ output_list = tmp_operands[-1] if len(tmp_operands) else None
602
+ operands = [asanyarray(v) for v in operand_list]
603
+ subscripts = ""
604
+ last = len(subscript_list) - 1
605
+ for num, sub in enumerate(subscript_list):
606
+ for s in sub:
607
+ if s is Ellipsis:
608
+ subscripts += "..."
609
+ else:
610
+ try:
611
+ s = operator.index(s)
612
+ except TypeError as e:
613
+ raise TypeError(
614
+ "For this input type lists must contain "
615
+ "either int or Ellipsis"
616
+ ) from e
617
+ subscripts += einsum_symbols[s]
618
+ if num != last:
619
+ subscripts += ","
620
+
621
+ if output_list is not None:
622
+ subscripts += "->"
623
+ for s in output_list:
624
+ if s is Ellipsis:
625
+ subscripts += "..."
626
+ else:
627
+ try:
628
+ s = operator.index(s)
629
+ except TypeError as e:
630
+ raise TypeError(
631
+ "For this input type lists must contain "
632
+ "either int or Ellipsis"
633
+ ) from e
634
+ subscripts += einsum_symbols[s]
635
+ # Check for proper "->"
636
+ if ("-" in subscripts) or (">" in subscripts):
637
+ invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
638
+ if invalid or (subscripts.count("->") != 1):
639
+ raise ValueError("Subscripts can only contain one '->'.")
640
+
641
+ # Parse ellipses
642
+ if "." in subscripts:
643
+ used = subscripts.replace(".", "").replace(",", "").replace("->", "")
644
+ unused = list(einsum_symbols_set - set(used))
645
+ ellipse_inds = "".join(unused)
646
+ longest = 0
647
+
648
+ if "->" in subscripts:
649
+ input_tmp, output_sub = subscripts.split("->")
650
+ split_subscripts = input_tmp.split(",")
651
+ out_sub = True
652
+ else:
653
+ split_subscripts = subscripts.split(',')
654
+ out_sub = False
655
+
656
+ for num, sub in enumerate(split_subscripts):
657
+ if "." in sub:
658
+ if (sub.count(".") != 3) or (sub.count("...") != 1):
659
+ raise ValueError("Invalid Ellipses.")
660
+
661
+ # Take into account numerical values
662
+ if operands[num].shape == ():
663
+ ellipse_count = 0
664
+ else:
665
+ ellipse_count = max(operands[num].ndim, 1)
666
+ ellipse_count -= (len(sub) - 3)
667
+
668
+ if ellipse_count > longest:
669
+ longest = ellipse_count
670
+
671
+ if ellipse_count < 0:
672
+ raise ValueError("Ellipses lengths do not match.")
673
+ elif ellipse_count == 0:
674
+ split_subscripts[num] = sub.replace('...', '')
675
+ else:
676
+ rep_inds = ellipse_inds[-ellipse_count:]
677
+ split_subscripts[num] = sub.replace('...', rep_inds)
678
+
679
+ subscripts = ",".join(split_subscripts)
680
+ if longest == 0:
681
+ out_ellipse = ""
682
+ else:
683
+ out_ellipse = ellipse_inds[-longest:]
684
+
685
+ if out_sub:
686
+ subscripts += "->" + output_sub.replace("...", out_ellipse)
687
+ else:
688
+ # Special care for outputless ellipses
689
+ output_subscript = ""
690
+ tmp_subscripts = subscripts.replace(",", "")
691
+ for s in sorted(set(tmp_subscripts)):
692
+ if s not in (einsum_symbols):
693
+ raise ValueError("Character %s is not a valid symbol." % s)
694
+ if tmp_subscripts.count(s) == 1:
695
+ output_subscript += s
696
+ normal_inds = ''.join(sorted(set(output_subscript) -
697
+ set(out_ellipse)))
698
+
699
+ subscripts += "->" + out_ellipse + normal_inds
700
+
701
+ # Build output string if does not exist
702
+ if "->" in subscripts:
703
+ input_subscripts, output_subscript = subscripts.split("->")
704
+ else:
705
+ input_subscripts = subscripts
706
+ # Build output subscripts
707
+ tmp_subscripts = subscripts.replace(",", "")
708
+ output_subscript = ""
709
+ for s in sorted(set(tmp_subscripts)):
710
+ if s not in einsum_symbols:
711
+ raise ValueError("Character %s is not a valid symbol." % s)
712
+ if tmp_subscripts.count(s) == 1:
713
+ output_subscript += s
714
+
715
+ # Make sure output subscripts are in the input
716
+ for char in output_subscript:
717
+ if output_subscript.count(char) != 1:
718
+ raise ValueError("Output character %s appeared more than once in "
719
+ "the output." % char)
720
+ if char not in input_subscripts:
721
+ raise ValueError("Output character %s did not appear in the input"
722
+ % char)
723
+
724
+ # Make sure number operands is equivalent to the number of terms
725
+ if len(input_subscripts.split(',')) != len(operands):
726
+ raise ValueError("Number of einsum subscripts must be equal to the "
727
+ "number of operands.")
728
+
729
+ return (input_subscripts, output_subscript, operands)
730
+
731
+
732
+ def _einsum_path_dispatcher(*operands, optimize=None, einsum_call=None):
733
+ # NOTE: technically, we should only dispatch on array-like arguments, not
734
+ # subscripts (given as strings). But separating operands into
735
+ # arrays/subscripts is a little tricky/slow (given einsum's two supported
736
+ # signatures), so as a practical shortcut we dispatch on everything.
737
+ # Strings will be ignored for dispatching since they don't define
738
+ # __array_function__.
739
+ return operands
740
+
741
+
742
+ @array_function_dispatch(_einsum_path_dispatcher, module='numpy')
743
+ def einsum_path(*operands, optimize='greedy', einsum_call=False):
744
+ """
745
+ einsum_path(subscripts, *operands, optimize='greedy')
746
+
747
+ Evaluates the lowest cost contraction order for an einsum expression by
748
+ considering the creation of intermediate arrays.
749
+
750
+ Parameters
751
+ ----------
752
+ subscripts : str
753
+ Specifies the subscripts for summation.
754
+ *operands : list of array_like
755
+ These are the arrays for the operation.
756
+ optimize : {bool, list, tuple, 'greedy', 'optimal'}
757
+ Choose the type of path. If a tuple is provided, the second argument is
758
+ assumed to be the maximum intermediate size created. If only a single
759
+ argument is provided the largest input or output array size is used
760
+ as a maximum intermediate size.
761
+
762
+ * if a list is given that starts with ``einsum_path``, uses this as the
763
+ contraction path
764
+ * if False no optimization is taken
765
+ * if True defaults to the 'greedy' algorithm
766
+ * 'optimal' An algorithm that combinatorially explores all possible
767
+ ways of contracting the listed tensors and chooses the least costly
768
+ path. Scales exponentially with the number of terms in the
769
+ contraction.
770
+ * 'greedy' An algorithm that chooses the best pair contraction
771
+ at each step. Effectively, this algorithm searches the largest inner,
772
+ Hadamard, and then outer products at each step. Scales cubically with
773
+ the number of terms in the contraction. Equivalent to the 'optimal'
774
+ path for most contractions.
775
+
776
+ Default is 'greedy'.
777
+
778
+ Returns
779
+ -------
780
+ path : list of tuples
781
+ A list representation of the einsum path.
782
+ string_repr : str
783
+ A printable representation of the einsum path.
784
+
785
+ Notes
786
+ -----
787
+ The resulting path indicates which terms of the input contraction should be
788
+ contracted first, the result of this contraction is then appended to the
789
+ end of the contraction list. This list can then be iterated over until all
790
+ intermediate contractions are complete.
791
+
792
+ See Also
793
+ --------
794
+ einsum, linalg.multi_dot
795
+
796
+ Examples
797
+ --------
798
+
799
+ We can begin with a chain dot example. In this case, it is optimal to
800
+ contract the ``b`` and ``c`` tensors first as represented by the first
801
+ element of the path ``(1, 2)``. The resulting tensor is added to the end
802
+ of the contraction and the remaining contraction ``(0, 1)`` is then
803
+ completed.
804
+
805
+ >>> np.random.seed(123)
806
+ >>> a = np.random.rand(2, 2)
807
+ >>> b = np.random.rand(2, 5)
808
+ >>> c = np.random.rand(5, 2)
809
+ >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
810
+ >>> print(path_info[0])
811
+ ['einsum_path', (1, 2), (0, 1)]
812
+ >>> print(path_info[1])
813
+ Complete contraction: ij,jk,kl->il # may vary
814
+ Naive scaling: 4
815
+ Optimized scaling: 3
816
+ Naive FLOP count: 1.600e+02
817
+ Optimized FLOP count: 5.600e+01
818
+ Theoretical speedup: 2.857
819
+ Largest intermediate: 4.000e+00 elements
820
+ -------------------------------------------------------------------------
821
+ scaling current remaining
822
+ -------------------------------------------------------------------------
823
+ 3 kl,jk->jl ij,jl->il
824
+ 3 jl,ij->il il->il
825
+
826
+
827
+ A more complex index transformation example.
828
+
829
+ >>> I = np.random.rand(10, 10, 10, 10)
830
+ >>> C = np.random.rand(10, 10)
831
+ >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
832
+ ... optimize='greedy')
833
+
834
+ >>> print(path_info[0])
835
+ ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
836
+ >>> print(path_info[1])
837
+ Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
838
+ Naive scaling: 8
839
+ Optimized scaling: 5
840
+ Naive FLOP count: 8.000e+08
841
+ Optimized FLOP count: 8.000e+05
842
+ Theoretical speedup: 1000.000
843
+ Largest intermediate: 1.000e+04 elements
844
+ --------------------------------------------------------------------------
845
+ scaling current remaining
846
+ --------------------------------------------------------------------------
847
+ 5 abcd,ea->bcde fb,gc,hd,bcde->efgh
848
+ 5 bcde,fb->cdef gc,hd,cdef->efgh
849
+ 5 cdef,gc->defg hd,defg->efgh
850
+ 5 defg,hd->efgh efgh->efgh
851
+ """
852
+
853
+ # Figure out what the path really is
854
+ path_type = optimize
855
+ if path_type is True:
856
+ path_type = 'greedy'
857
+ if path_type is None:
858
+ path_type = False
859
+
860
+ explicit_einsum_path = False
861
+ memory_limit = None
862
+
863
+ # No optimization or a named path algorithm
864
+ if (path_type is False) or isinstance(path_type, str):
865
+ pass
866
+
867
+ # Given an explicit path
868
+ elif len(path_type) and (path_type[0] == 'einsum_path'):
869
+ explicit_einsum_path = True
870
+
871
+ # Path tuple with memory limit
872
+ elif ((len(path_type) == 2) and isinstance(path_type[0], str) and
873
+ isinstance(path_type[1], (int, float))):
874
+ memory_limit = int(path_type[1])
875
+ path_type = path_type[0]
876
+
877
+ else:
878
+ raise TypeError("Did not understand the path: %s" % str(path_type))
879
+
880
+ # Hidden option, only einsum should call this
881
+ einsum_call_arg = einsum_call
882
+
883
+ # Python side parsing
884
+ input_subscripts, output_subscript, operands = (
885
+ _parse_einsum_input(operands)
886
+ )
887
+
888
+ # Build a few useful list and sets
889
+ input_list = input_subscripts.split(',')
890
+ input_sets = [set(x) for x in input_list]
891
+ output_set = set(output_subscript)
892
+ indices = set(input_subscripts.replace(',', ''))
893
+
894
+ # Get length of each unique dimension and ensure all dimensions are correct
895
+ dimension_dict = {}
896
+ broadcast_indices = [[] for x in range(len(input_list))]
897
+ for tnum, term in enumerate(input_list):
898
+ sh = operands[tnum].shape
899
+ if len(sh) != len(term):
900
+ raise ValueError("Einstein sum subscript %s does not contain the "
901
+ "correct number of indices for operand %d."
902
+ % (input_subscripts[tnum], tnum))
903
+ for cnum, char in enumerate(term):
904
+ dim = sh[cnum]
905
+
906
+ # Build out broadcast indices
907
+ if dim == 1:
908
+ broadcast_indices[tnum].append(char)
909
+
910
+ if char in dimension_dict.keys():
911
+ # For broadcasting cases we always want the largest dim size
912
+ if dimension_dict[char] == 1:
913
+ dimension_dict[char] = dim
914
+ elif dim not in (1, dimension_dict[char]):
915
+ raise ValueError("Size of label '%s' for operand %d (%d) "
916
+ "does not match previous terms (%d)."
917
+ % (char, tnum, dimension_dict[char], dim))
918
+ else:
919
+ dimension_dict[char] = dim
920
+
921
+ # Convert broadcast inds to sets
922
+ broadcast_indices = [set(x) for x in broadcast_indices]
923
+
924
+ # Compute size of each input array plus the output array
925
+ size_list = [_compute_size_by_dict(term, dimension_dict)
926
+ for term in input_list + [output_subscript]]
927
+ max_size = max(size_list)
928
+
929
+ if memory_limit is None:
930
+ memory_arg = max_size
931
+ else:
932
+ memory_arg = memory_limit
933
+
934
+ # Compute naive cost
935
+ # This isn't quite right, need to look into exactly how einsum does this
936
+ inner_product = (sum(len(x) for x in input_sets) - len(indices)) > 0
937
+ naive_cost = _flop_count(
938
+ indices, inner_product, len(input_list), dimension_dict
939
+ )
940
+
941
+ # Compute the path
942
+ if explicit_einsum_path:
943
+ path = path_type[1:]
944
+ elif (
945
+ (path_type is False)
946
+ or (len(input_list) in [1, 2])
947
+ or (indices == output_set)
948
+ ):
949
+ # Nothing to be optimized, leave it to einsum
950
+ path = [tuple(range(len(input_list)))]
951
+ elif path_type == "greedy":
952
+ path = _greedy_path(
953
+ input_sets, output_set, dimension_dict, memory_arg
954
+ )
955
+ elif path_type == "optimal":
956
+ path = _optimal_path(
957
+ input_sets, output_set, dimension_dict, memory_arg
958
+ )
959
+ else:
960
+ raise KeyError("Path name %s not found", path_type)
961
+
962
+ cost_list, scale_list, size_list, contraction_list = [], [], [], []
963
+
964
+ # Build contraction tuple (positions, gemm, einsum_str, remaining)
965
+ for cnum, contract_inds in enumerate(path):
966
+ # Make sure we remove inds from right to left
967
+ contract_inds = tuple(sorted(contract_inds, reverse=True))
968
+
969
+ contract = _find_contraction(contract_inds, input_sets, output_set)
970
+ out_inds, input_sets, idx_removed, idx_contract = contract
971
+
972
+ cost = _flop_count(
973
+ idx_contract, idx_removed, len(contract_inds), dimension_dict
974
+ )
975
+ cost_list.append(cost)
976
+ scale_list.append(len(idx_contract))
977
+ size_list.append(_compute_size_by_dict(out_inds, dimension_dict))
978
+
979
+ bcast = set()
980
+ tmp_inputs = []
981
+ for x in contract_inds:
982
+ tmp_inputs.append(input_list.pop(x))
983
+ bcast |= broadcast_indices.pop(x)
984
+
985
+ new_bcast_inds = bcast - idx_removed
986
+
987
+ # If we're broadcasting, nix blas
988
+ if not len(idx_removed & bcast):
989
+ do_blas = _can_dot(tmp_inputs, out_inds, idx_removed)
990
+ else:
991
+ do_blas = False
992
+
993
+ # Last contraction
994
+ if (cnum - len(path)) == -1:
995
+ idx_result = output_subscript
996
+ else:
997
+ sort_result = [(dimension_dict[ind], ind) for ind in out_inds]
998
+ idx_result = "".join([x[1] for x in sorted(sort_result)])
999
+
1000
+ input_list.append(idx_result)
1001
+ broadcast_indices.append(new_bcast_inds)
1002
+ einsum_str = ",".join(tmp_inputs) + "->" + idx_result
1003
+
1004
+ contraction = (
1005
+ contract_inds, idx_removed, einsum_str, input_list[:], do_blas
1006
+ )
1007
+ contraction_list.append(contraction)
1008
+
1009
+ opt_cost = sum(cost_list) + 1
1010
+
1011
+ if len(input_list) != 1:
1012
+ # Explicit "einsum_path" is usually trusted, but we detect this kind of
1013
+ # mistake in order to prevent from returning an intermediate value.
1014
+ raise RuntimeError(
1015
+ "Invalid einsum_path is specified: {} more operands has to be "
1016
+ "contracted.".format(len(input_list) - 1))
1017
+
1018
+ if einsum_call_arg:
1019
+ return (operands, contraction_list)
1020
+
1021
+ # Return the path along with a nice string representation
1022
+ overall_contraction = input_subscripts + "->" + output_subscript
1023
+ header = ("scaling", "current", "remaining")
1024
+
1025
+ speedup = naive_cost / opt_cost
1026
+ max_i = max(size_list)
1027
+
1028
+ path_print = " Complete contraction: %s\n" % overall_contraction
1029
+ path_print += " Naive scaling: %d\n" % len(indices)
1030
+ path_print += " Optimized scaling: %d\n" % max(scale_list)
1031
+ path_print += " Naive FLOP count: %.3e\n" % naive_cost
1032
+ path_print += " Optimized FLOP count: %.3e\n" % opt_cost
1033
+ path_print += " Theoretical speedup: %3.3f\n" % speedup
1034
+ path_print += " Largest intermediate: %.3e elements\n" % max_i
1035
+ path_print += "-" * 74 + "\n"
1036
+ path_print += "%6s %24s %40s\n" % header
1037
+ path_print += "-" * 74
1038
+
1039
+ for n, contraction in enumerate(contraction_list):
1040
+ inds, idx_rm, einsum_str, remaining, blas = contraction
1041
+ remaining_str = ",".join(remaining) + "->" + output_subscript
1042
+ path_run = (scale_list[n], einsum_str, remaining_str)
1043
+ path_print += "\n%4d %24s %40s" % path_run
1044
+
1045
+ path = ['einsum_path'] + path
1046
+ return (path, path_print)
1047
+
1048
+
1049
+ def _einsum_dispatcher(*operands, out=None, optimize=None, **kwargs):
1050
+ # Arguably we dispatch on more arguments than we really should; see note in
1051
+ # _einsum_path_dispatcher for why.
1052
+ yield from operands
1053
+ yield out
1054
+
1055
+
1056
+ # Rewrite einsum to handle different cases
1057
+ @array_function_dispatch(_einsum_dispatcher, module='numpy')
1058
+ def einsum(*operands, out=None, optimize=False, **kwargs):
1059
+ """
1060
+ einsum(subscripts, *operands, out=None, dtype=None, order='K',
1061
+ casting='safe', optimize=False)
1062
+
1063
+ Evaluates the Einstein summation convention on the operands.
1064
+
1065
+ Using the Einstein summation convention, many common multi-dimensional,
1066
+ linear algebraic array operations can be represented in a simple fashion.
1067
+ In *implicit* mode `einsum` computes these values.
1068
+
1069
+ In *explicit* mode, `einsum` provides further flexibility to compute
1070
+ other array operations that might not be considered classical Einstein
1071
+ summation operations, by disabling, or forcing summation over specified
1072
+ subscript labels.
1073
+
1074
+ See the notes and examples for clarification.
1075
+
1076
+ Parameters
1077
+ ----------
1078
+ subscripts : str
1079
+ Specifies the subscripts for summation as comma separated list of
1080
+ subscript labels. An implicit (classical Einstein summation)
1081
+ calculation is performed unless the explicit indicator '->' is
1082
+ included as well as subscript labels of the precise output form.
1083
+ operands : list of array_like
1084
+ These are the arrays for the operation.
1085
+ out : ndarray, optional
1086
+ If provided, the calculation is done into this array.
1087
+ dtype : {data-type, None}, optional
1088
+ If provided, forces the calculation to use the data type specified.
1089
+ Note that you may have to also give a more liberal `casting`
1090
+ parameter to allow the conversions. Default is None.
1091
+ order : {'C', 'F', 'A', 'K'}, optional
1092
+ Controls the memory layout of the output. 'C' means it should
1093
+ be C contiguous. 'F' means it should be Fortran contiguous,
1094
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
1095
+ 'K' means it should be as close to the layout as the inputs as
1096
+ is possible, including arbitrarily permuted axes.
1097
+ Default is 'K'.
1098
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
1099
+ Controls what kind of data casting may occur. Setting this to
1100
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
1101
+
1102
+ * 'no' means the data types should not be cast at all.
1103
+ * 'equiv' means only byte-order changes are allowed.
1104
+ * 'safe' means only casts which can preserve values are allowed.
1105
+ * 'same_kind' means only safe casts or casts within a kind,
1106
+ like float64 to float32, are allowed.
1107
+ * 'unsafe' means any data conversions may be done.
1108
+
1109
+ Default is 'safe'.
1110
+ optimize : {False, True, 'greedy', 'optimal'}, optional
1111
+ Controls if intermediate optimization should occur. No optimization
1112
+ will occur if False and True will default to the 'greedy' algorithm.
1113
+ Also accepts an explicit contraction list from the ``np.einsum_path``
1114
+ function. See ``np.einsum_path`` for more details. Defaults to False.
1115
+
1116
+ Returns
1117
+ -------
1118
+ output : ndarray
1119
+ The calculation based on the Einstein summation convention.
1120
+
1121
+ See Also
1122
+ --------
1123
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
1124
+ einsum:
1125
+ Similar verbose interface is provided by the
1126
+ `einops <https://github.com/arogozhnikov/einops>`_ package to cover
1127
+ additional operations: transpose, reshape/flatten, repeat/tile,
1128
+ squeeze/unsqueeze and reductions.
1129
+ The `opt_einsum <https://optimized-einsum.readthedocs.io/en/stable/>`_
1130
+ optimizes contraction order for einsum-like expressions
1131
+ in backend-agnostic manner.
1132
+
1133
+ Notes
1134
+ -----
1135
+ The Einstein summation convention can be used to compute
1136
+ many multi-dimensional, linear algebraic array operations. `einsum`
1137
+ provides a succinct way of representing these.
1138
+
1139
+ A non-exhaustive list of these operations,
1140
+ which can be computed by `einsum`, is shown below along with examples:
1141
+
1142
+ * Trace of an array, :py:func:`numpy.trace`.
1143
+ * Return a diagonal, :py:func:`numpy.diag`.
1144
+ * Array axis summations, :py:func:`numpy.sum`.
1145
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
1146
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul`
1147
+ :py:func:`numpy.dot`.
1148
+ * Vector inner and outer products, :py:func:`numpy.inner`
1149
+ :py:func:`numpy.outer`.
1150
+ * Broadcasting, element-wise and scalar multiplication,
1151
+ :py:func:`numpy.multiply`.
1152
+ * Tensor contractions, :py:func:`numpy.tensordot`.
1153
+ * Chained array operations, in efficient calculation order,
1154
+ :py:func:`numpy.einsum_path`.
1155
+
1156
+ The subscripts string is a comma-separated list of subscript labels,
1157
+ where each label refers to a dimension of the corresponding operand.
1158
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
1159
+ is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
1160
+ appears only once, it is not summed, so ``np.einsum('i', a)``
1161
+ produces a view of ``a`` with no changes. A further example
1162
+ ``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
1163
+ and is equivalent to :py:func:`np.matmul(a,b) <numpy.matmul>`.
1164
+ Repeated subscript labels in one operand take the diagonal.
1165
+ For example, ``np.einsum('ii', a)`` is equivalent to
1166
+ :py:func:`np.trace(a) <numpy.trace>`.
1167
+
1168
+ In *implicit mode*, the chosen subscripts are important
1169
+ since the axes of the output are reordered alphabetically. This
1170
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
1171
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
1172
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
1173
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
1174
+ multiplication since subscript 'h' precedes subscript 'i'.
1175
+
1176
+ In *explicit mode* the output can be directly controlled by
1177
+ specifying output subscript labels. This requires the
1178
+ identifier '->' as well as the list of output subscript labels.
1179
+ This feature increases the flexibility of the function since
1180
+ summing can be disabled or forced when required. The call
1181
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
1182
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
1183
+ is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
1184
+ The difference is that `einsum` does not allow broadcasting by default.
1185
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
1186
+ order of the output subscript labels and therefore returns matrix
1187
+ multiplication, unlike the example above in implicit mode.
1188
+
1189
+ To enable and control broadcasting, use an ellipsis. Default
1190
+ NumPy-style broadcasting is done by adding an ellipsis
1191
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
1192
+ ``np.einsum('...i->...', a)`` is like
1193
+ :py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
1194
+ To take the trace along the first and last axes,
1195
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
1196
+ product with the left-most indices instead of rightmost, one can do
1197
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
1198
+
1199
+ When there is only one operand, no axes are summed, and no output
1200
+ parameter is provided, a view into the operand is returned instead
1201
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
1202
+ produces a view (changed in version 1.10.0).
1203
+
1204
+ `einsum` also provides an alternative way to provide the subscripts and
1205
+ operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
1206
+ If the output shape is not provided in this format `einsum` will be
1207
+ calculated in implicit mode, otherwise it will be performed explicitly.
1208
+ The examples below have corresponding `einsum` calls with the two
1209
+ parameter methods.
1210
+
1211
+ Views returned from einsum are now writeable whenever the input array
1212
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
1213
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
1214
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
1215
+ of a 2D array.
1216
+
1217
+ Added the ``optimize`` argument which will optimize the contraction order
1218
+ of an einsum expression. For a contraction with three or more operands
1219
+ this can greatly increase the computational efficiency at the cost of
1220
+ a larger memory footprint during computation.
1221
+
1222
+ Typically a 'greedy' algorithm is applied which empirical tests have shown
1223
+ returns the optimal path in the majority of cases. In some cases 'optimal'
1224
+ will return the superlative path through a more expensive, exhaustive
1225
+ search. For iterative calculations it may be advisable to calculate
1226
+ the optimal path once and reuse that path by supplying it as an argument.
1227
+ An example is given below.
1228
+
1229
+ See :py:func:`numpy.einsum_path` for more details.
1230
+
1231
+ Examples
1232
+ --------
1233
+ >>> a = np.arange(25).reshape(5,5)
1234
+ >>> b = np.arange(5)
1235
+ >>> c = np.arange(6).reshape(2,3)
1236
+
1237
+ Trace of a matrix:
1238
+
1239
+ >>> np.einsum('ii', a)
1240
+ 60
1241
+ >>> np.einsum(a, [0,0])
1242
+ 60
1243
+ >>> np.trace(a)
1244
+ 60
1245
+
1246
+ Extract the diagonal (requires explicit form):
1247
+
1248
+ >>> np.einsum('ii->i', a)
1249
+ array([ 0, 6, 12, 18, 24])
1250
+ >>> np.einsum(a, [0,0], [0])
1251
+ array([ 0, 6, 12, 18, 24])
1252
+ >>> np.diag(a)
1253
+ array([ 0, 6, 12, 18, 24])
1254
+
1255
+ Sum over an axis (requires explicit form):
1256
+
1257
+ >>> np.einsum('ij->i', a)
1258
+ array([ 10, 35, 60, 85, 110])
1259
+ >>> np.einsum(a, [0,1], [0])
1260
+ array([ 10, 35, 60, 85, 110])
1261
+ >>> np.sum(a, axis=1)
1262
+ array([ 10, 35, 60, 85, 110])
1263
+
1264
+ For higher dimensional arrays summing a single axis can be done
1265
+ with ellipsis:
1266
+
1267
+ >>> np.einsum('...j->...', a)
1268
+ array([ 10, 35, 60, 85, 110])
1269
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
1270
+ array([ 10, 35, 60, 85, 110])
1271
+
1272
+ Compute a matrix transpose, or reorder any number of axes:
1273
+
1274
+ >>> np.einsum('ji', c)
1275
+ array([[0, 3],
1276
+ [1, 4],
1277
+ [2, 5]])
1278
+ >>> np.einsum('ij->ji', c)
1279
+ array([[0, 3],
1280
+ [1, 4],
1281
+ [2, 5]])
1282
+ >>> np.einsum(c, [1,0])
1283
+ array([[0, 3],
1284
+ [1, 4],
1285
+ [2, 5]])
1286
+ >>> np.transpose(c)
1287
+ array([[0, 3],
1288
+ [1, 4],
1289
+ [2, 5]])
1290
+
1291
+ Vector inner products:
1292
+
1293
+ >>> np.einsum('i,i', b, b)
1294
+ 30
1295
+ >>> np.einsum(b, [0], b, [0])
1296
+ 30
1297
+ >>> np.inner(b,b)
1298
+ 30
1299
+
1300
+ Matrix vector multiplication:
1301
+
1302
+ >>> np.einsum('ij,j', a, b)
1303
+ array([ 30, 80, 130, 180, 230])
1304
+ >>> np.einsum(a, [0,1], b, [1])
1305
+ array([ 30, 80, 130, 180, 230])
1306
+ >>> np.dot(a, b)
1307
+ array([ 30, 80, 130, 180, 230])
1308
+ >>> np.einsum('...j,j', a, b)
1309
+ array([ 30, 80, 130, 180, 230])
1310
+
1311
+ Broadcasting and scalar multiplication:
1312
+
1313
+ >>> np.einsum('..., ...', 3, c)
1314
+ array([[ 0, 3, 6],
1315
+ [ 9, 12, 15]])
1316
+ >>> np.einsum(',ij', 3, c)
1317
+ array([[ 0, 3, 6],
1318
+ [ 9, 12, 15]])
1319
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
1320
+ array([[ 0, 3, 6],
1321
+ [ 9, 12, 15]])
1322
+ >>> np.multiply(3, c)
1323
+ array([[ 0, 3, 6],
1324
+ [ 9, 12, 15]])
1325
+
1326
+ Vector outer product:
1327
+
1328
+ >>> np.einsum('i,j', np.arange(2)+1, b)
1329
+ array([[0, 1, 2, 3, 4],
1330
+ [0, 2, 4, 6, 8]])
1331
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
1332
+ array([[0, 1, 2, 3, 4],
1333
+ [0, 2, 4, 6, 8]])
1334
+ >>> np.outer(np.arange(2)+1, b)
1335
+ array([[0, 1, 2, 3, 4],
1336
+ [0, 2, 4, 6, 8]])
1337
+
1338
+ Tensor contraction:
1339
+
1340
+ >>> a = np.arange(60.).reshape(3,4,5)
1341
+ >>> b = np.arange(24.).reshape(4,3,2)
1342
+ >>> np.einsum('ijk,jil->kl', a, b)
1343
+ array([[4400., 4730.],
1344
+ [4532., 4874.],
1345
+ [4664., 5018.],
1346
+ [4796., 5162.],
1347
+ [4928., 5306.]])
1348
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
1349
+ array([[4400., 4730.],
1350
+ [4532., 4874.],
1351
+ [4664., 5018.],
1352
+ [4796., 5162.],
1353
+ [4928., 5306.]])
1354
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
1355
+ array([[4400., 4730.],
1356
+ [4532., 4874.],
1357
+ [4664., 5018.],
1358
+ [4796., 5162.],
1359
+ [4928., 5306.]])
1360
+
1361
+ Writeable returned arrays (since version 1.10.0):
1362
+
1363
+ >>> a = np.zeros((3, 3))
1364
+ >>> np.einsum('ii->i', a)[:] = 1
1365
+ >>> a
1366
+ array([[1., 0., 0.],
1367
+ [0., 1., 0.],
1368
+ [0., 0., 1.]])
1369
+
1370
+ Example of ellipsis use:
1371
+
1372
+ >>> a = np.arange(6).reshape((3,2))
1373
+ >>> b = np.arange(12).reshape((4,3))
1374
+ >>> np.einsum('ki,jk->ij', a, b)
1375
+ array([[10, 28, 46, 64],
1376
+ [13, 40, 67, 94]])
1377
+ >>> np.einsum('ki,...k->i...', a, b)
1378
+ array([[10, 28, 46, 64],
1379
+ [13, 40, 67, 94]])
1380
+ >>> np.einsum('k...,jk', a, b)
1381
+ array([[10, 28, 46, 64],
1382
+ [13, 40, 67, 94]])
1383
+
1384
+ Chained array operations. For more complicated contractions, speed ups
1385
+ might be achieved by repeatedly computing a 'greedy' path or pre-computing
1386
+ the 'optimal' path and repeatedly applying it, using an `einsum_path`
1387
+ insertion (since version 1.12.0). Performance improvements can be
1388
+ particularly significant with larger arrays:
1389
+
1390
+ >>> a = np.ones(64).reshape(2,4,8)
1391
+
1392
+ Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.)
1393
+
1394
+ >>> for iteration in range(500):
1395
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
1396
+
1397
+ Sub-optimal `einsum` (due to repeated path calculation time): ~330ms
1398
+
1399
+ >>> for iteration in range(500):
1400
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
1401
+ ... optimize='optimal')
1402
+
1403
+ Greedy `einsum` (faster optimal path approximation): ~160ms
1404
+
1405
+ >>> for iteration in range(500):
1406
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
1407
+
1408
+ Optimal `einsum` (best usage pattern in some use cases): ~110ms
1409
+
1410
+ >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
1411
+ ... optimize='optimal')[0]
1412
+ >>> for iteration in range(500):
1413
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
1414
+
1415
+ """
1416
+ # Special handling if out is specified
1417
+ specified_out = out is not None
1418
+
1419
+ # If no optimization, run pure einsum
1420
+ if optimize is False:
1421
+ if specified_out:
1422
+ kwargs['out'] = out
1423
+ return c_einsum(*operands, **kwargs)
1424
+
1425
+ # Check the kwargs to avoid a more cryptic error later, without having to
1426
+ # repeat default values here
1427
+ valid_einsum_kwargs = ['dtype', 'order', 'casting']
1428
+ unknown_kwargs = [k for (k, v) in kwargs.items() if
1429
+ k not in valid_einsum_kwargs]
1430
+ if len(unknown_kwargs):
1431
+ raise TypeError("Did not understand the following kwargs: %s"
1432
+ % unknown_kwargs)
1433
+
1434
+ # Build the contraction list and operand
1435
+ operands, contraction_list = einsum_path(*operands, optimize=optimize,
1436
+ einsum_call=True)
1437
+
1438
+ # Handle order kwarg for output array, c_einsum allows mixed case
1439
+ output_order = kwargs.pop('order', 'K')
1440
+ if output_order.upper() == 'A':
1441
+ if all(arr.flags.f_contiguous for arr in operands):
1442
+ output_order = 'F'
1443
+ else:
1444
+ output_order = 'C'
1445
+
1446
+ # Start contraction loop
1447
+ for num, contraction in enumerate(contraction_list):
1448
+ inds, idx_rm, einsum_str, remaining, blas = contraction
1449
+ tmp_operands = [operands.pop(x) for x in inds]
1450
+
1451
+ # Do we need to deal with the output?
1452
+ handle_out = specified_out and ((num + 1) == len(contraction_list))
1453
+
1454
+ # Call tensordot if still possible
1455
+ if blas:
1456
+ # Checks have already been handled
1457
+ input_str, results_index = einsum_str.split('->')
1458
+ input_left, input_right = input_str.split(',')
1459
+
1460
+ tensor_result = input_left + input_right
1461
+ for s in idx_rm:
1462
+ tensor_result = tensor_result.replace(s, "")
1463
+
1464
+ # Find indices to contract over
1465
+ left_pos, right_pos = [], []
1466
+ for s in sorted(idx_rm):
1467
+ left_pos.append(input_left.find(s))
1468
+ right_pos.append(input_right.find(s))
1469
+
1470
+ # Contract!
1471
+ new_view = tensordot(
1472
+ *tmp_operands, axes=(tuple(left_pos), tuple(right_pos))
1473
+ )
1474
+
1475
+ # Build a new view if needed
1476
+ if (tensor_result != results_index) or handle_out:
1477
+ if handle_out:
1478
+ kwargs["out"] = out
1479
+ new_view = c_einsum(
1480
+ tensor_result + '->' + results_index, new_view, **kwargs
1481
+ )
1482
+
1483
+ # Call einsum
1484
+ else:
1485
+ # If out was specified
1486
+ if handle_out:
1487
+ kwargs["out"] = out
1488
+
1489
+ # Do the contraction
1490
+ new_view = c_einsum(einsum_str, *tmp_operands, **kwargs)
1491
+
1492
+ # Append new items and dereference what we can
1493
+ operands.append(new_view)
1494
+ del tmp_operands, new_view
1495
+
1496
+ if specified_out:
1497
+ return out
1498
+ else:
1499
+ return asanyarray(operands[0], order=output_order)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/einsumfunc.pyi ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from typing import TypeAlias, TypeVar, Any, overload, Literal
3
+
4
+ import numpy as np
5
+ from numpy import number, _OrderKACF
6
+ from numpy._typing import (
7
+ NDArray,
8
+ _ArrayLikeBool_co,
9
+ _ArrayLikeUInt_co,
10
+ _ArrayLikeInt_co,
11
+ _ArrayLikeFloat_co,
12
+ _ArrayLikeComplex_co,
13
+ _ArrayLikeObject_co,
14
+ _DTypeLikeBool,
15
+ _DTypeLikeUInt,
16
+ _DTypeLikeInt,
17
+ _DTypeLikeFloat,
18
+ _DTypeLikeComplex,
19
+ _DTypeLikeComplex_co,
20
+ _DTypeLikeObject,
21
+ )
22
+
23
+ __all__ = ["einsum", "einsum_path"]
24
+
25
+ _ArrayType = TypeVar(
26
+ "_ArrayType",
27
+ bound=NDArray[np.bool | number[Any]],
28
+ )
29
+
30
+ _OptimizeKind: TypeAlias = bool | Literal["greedy", "optimal"] | Sequence[Any] | None
31
+ _CastingSafe: TypeAlias = Literal["no", "equiv", "safe", "same_kind"]
32
+ _CastingUnsafe: TypeAlias = Literal["unsafe"]
33
+
34
+
35
+ # TODO: Properly handle the `casting`-based combinatorics
36
+ # TODO: We need to evaluate the content `__subscripts` in order
37
+ # to identify whether or an array or scalar is returned. At a cursory
38
+ # glance this seems like something that can quite easily be done with
39
+ # a mypy plugin.
40
+ # Something like `is_scalar = bool(__subscripts.partition("->")[-1])`
41
+ @overload
42
+ def einsum(
43
+ subscripts: str | _ArrayLikeInt_co,
44
+ /,
45
+ *operands: _ArrayLikeBool_co,
46
+ out: None = ...,
47
+ dtype: None | _DTypeLikeBool = ...,
48
+ order: _OrderKACF = ...,
49
+ casting: _CastingSafe = ...,
50
+ optimize: _OptimizeKind = ...,
51
+ ) -> Any: ...
52
+ @overload
53
+ def einsum(
54
+ subscripts: str | _ArrayLikeInt_co,
55
+ /,
56
+ *operands: _ArrayLikeUInt_co,
57
+ out: None = ...,
58
+ dtype: None | _DTypeLikeUInt = ...,
59
+ order: _OrderKACF = ...,
60
+ casting: _CastingSafe = ...,
61
+ optimize: _OptimizeKind = ...,
62
+ ) -> Any: ...
63
+ @overload
64
+ def einsum(
65
+ subscripts: str | _ArrayLikeInt_co,
66
+ /,
67
+ *operands: _ArrayLikeInt_co,
68
+ out: None = ...,
69
+ dtype: None | _DTypeLikeInt = ...,
70
+ order: _OrderKACF = ...,
71
+ casting: _CastingSafe = ...,
72
+ optimize: _OptimizeKind = ...,
73
+ ) -> Any: ...
74
+ @overload
75
+ def einsum(
76
+ subscripts: str | _ArrayLikeInt_co,
77
+ /,
78
+ *operands: _ArrayLikeFloat_co,
79
+ out: None = ...,
80
+ dtype: None | _DTypeLikeFloat = ...,
81
+ order: _OrderKACF = ...,
82
+ casting: _CastingSafe = ...,
83
+ optimize: _OptimizeKind = ...,
84
+ ) -> Any: ...
85
+ @overload
86
+ def einsum(
87
+ subscripts: str | _ArrayLikeInt_co,
88
+ /,
89
+ *operands: _ArrayLikeComplex_co,
90
+ out: None = ...,
91
+ dtype: None | _DTypeLikeComplex = ...,
92
+ order: _OrderKACF = ...,
93
+ casting: _CastingSafe = ...,
94
+ optimize: _OptimizeKind = ...,
95
+ ) -> Any: ...
96
+ @overload
97
+ def einsum(
98
+ subscripts: str | _ArrayLikeInt_co,
99
+ /,
100
+ *operands: Any,
101
+ casting: _CastingUnsafe,
102
+ dtype: None | _DTypeLikeComplex_co = ...,
103
+ out: None = ...,
104
+ order: _OrderKACF = ...,
105
+ optimize: _OptimizeKind = ...,
106
+ ) -> Any: ...
107
+ @overload
108
+ def einsum(
109
+ subscripts: str | _ArrayLikeInt_co,
110
+ /,
111
+ *operands: _ArrayLikeComplex_co,
112
+ out: _ArrayType,
113
+ dtype: None | _DTypeLikeComplex_co = ...,
114
+ order: _OrderKACF = ...,
115
+ casting: _CastingSafe = ...,
116
+ optimize: _OptimizeKind = ...,
117
+ ) -> _ArrayType: ...
118
+ @overload
119
+ def einsum(
120
+ subscripts: str | _ArrayLikeInt_co,
121
+ /,
122
+ *operands: Any,
123
+ out: _ArrayType,
124
+ casting: _CastingUnsafe,
125
+ dtype: None | _DTypeLikeComplex_co = ...,
126
+ order: _OrderKACF = ...,
127
+ optimize: _OptimizeKind = ...,
128
+ ) -> _ArrayType: ...
129
+
130
+ @overload
131
+ def einsum(
132
+ subscripts: str | _ArrayLikeInt_co,
133
+ /,
134
+ *operands: _ArrayLikeObject_co,
135
+ out: None = ...,
136
+ dtype: None | _DTypeLikeObject = ...,
137
+ order: _OrderKACF = ...,
138
+ casting: _CastingSafe = ...,
139
+ optimize: _OptimizeKind = ...,
140
+ ) -> Any: ...
141
+ @overload
142
+ def einsum(
143
+ subscripts: str | _ArrayLikeInt_co,
144
+ /,
145
+ *operands: Any,
146
+ casting: _CastingUnsafe,
147
+ dtype: None | _DTypeLikeObject = ...,
148
+ out: None = ...,
149
+ order: _OrderKACF = ...,
150
+ optimize: _OptimizeKind = ...,
151
+ ) -> Any: ...
152
+ @overload
153
+ def einsum(
154
+ subscripts: str | _ArrayLikeInt_co,
155
+ /,
156
+ *operands: _ArrayLikeObject_co,
157
+ out: _ArrayType,
158
+ dtype: None | _DTypeLikeObject = ...,
159
+ order: _OrderKACF = ...,
160
+ casting: _CastingSafe = ...,
161
+ optimize: _OptimizeKind = ...,
162
+ ) -> _ArrayType: ...
163
+ @overload
164
+ def einsum(
165
+ subscripts: str | _ArrayLikeInt_co,
166
+ /,
167
+ *operands: Any,
168
+ out: _ArrayType,
169
+ casting: _CastingUnsafe,
170
+ dtype: None | _DTypeLikeObject = ...,
171
+ order: _OrderKACF = ...,
172
+ optimize: _OptimizeKind = ...,
173
+ ) -> _ArrayType: ...
174
+
175
+ # NOTE: `einsum_call` is a hidden kwarg unavailable for public use.
176
+ # It is therefore excluded from the signatures below.
177
+ # NOTE: In practice the list consists of a `str` (first element)
178
+ # and a variable number of integer tuples.
179
+ def einsum_path(
180
+ subscripts: str | _ArrayLikeInt_co,
181
+ /,
182
+ *operands: _ArrayLikeComplex_co | _DTypeLikeObject,
183
+ optimize: _OptimizeKind = "greedy",
184
+ einsum_call: Literal[False] = False,
185
+ ) -> tuple[list[Any], str]: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/fromnumeric.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/fromnumeric.pyi ADDED
@@ -0,0 +1,1733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: ANN401
2
+ from collections.abc import Sequence
3
+ from typing import (
4
+ Any,
5
+ Literal,
6
+ Protocol,
7
+ SupportsIndex,
8
+ TypeAlias,
9
+ TypeVar,
10
+ overload,
11
+ type_check_only,
12
+ )
13
+
14
+ from _typeshed import Incomplete
15
+ from typing_extensions import Never, deprecated
16
+
17
+ import numpy as np
18
+ from numpy import (
19
+ number,
20
+ uint64,
21
+ int_,
22
+ int64,
23
+ intp,
24
+ float16,
25
+ floating,
26
+ complexfloating,
27
+ timedelta64,
28
+ object_,
29
+ generic,
30
+ _AnyShapeType,
31
+ _OrderKACF,
32
+ _OrderACF,
33
+ _ModeKind,
34
+ _PartitionKind,
35
+ _SortKind,
36
+ _SortSide,
37
+ _CastingKind,
38
+ )
39
+ from numpy._globals import _NoValueType
40
+ from numpy._typing import (
41
+ DTypeLike,
42
+ _DTypeLike,
43
+ ArrayLike,
44
+ _ArrayLike,
45
+ NDArray,
46
+ _NestedSequence,
47
+ _ShapeLike,
48
+ _ArrayLikeBool_co,
49
+ _ArrayLikeUInt_co,
50
+ _ArrayLikeInt,
51
+ _ArrayLikeInt_co,
52
+ _ArrayLikeFloat_co,
53
+ _ArrayLikeComplex_co,
54
+ _ArrayLikeObject_co,
55
+ _IntLike_co,
56
+ _BoolLike_co,
57
+ _ComplexLike_co,
58
+ _NumberLike_co,
59
+ _ScalarLike_co,
60
+ )
61
+
62
+ __all__ = [
63
+ "all",
64
+ "amax",
65
+ "amin",
66
+ "any",
67
+ "argmax",
68
+ "argmin",
69
+ "argpartition",
70
+ "argsort",
71
+ "around",
72
+ "choose",
73
+ "clip",
74
+ "compress",
75
+ "cumprod",
76
+ "cumsum",
77
+ "cumulative_prod",
78
+ "cumulative_sum",
79
+ "diagonal",
80
+ "mean",
81
+ "max",
82
+ "min",
83
+ "matrix_transpose",
84
+ "ndim",
85
+ "nonzero",
86
+ "partition",
87
+ "prod",
88
+ "ptp",
89
+ "put",
90
+ "ravel",
91
+ "repeat",
92
+ "reshape",
93
+ "resize",
94
+ "round",
95
+ "searchsorted",
96
+ "shape",
97
+ "size",
98
+ "sort",
99
+ "squeeze",
100
+ "std",
101
+ "sum",
102
+ "swapaxes",
103
+ "take",
104
+ "trace",
105
+ "transpose",
106
+ "var",
107
+ ]
108
+
109
+ _SCT = TypeVar("_SCT", bound=generic)
110
+ _SCT_uifcO = TypeVar("_SCT_uifcO", bound=number[Any] | object_)
111
+ _ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
112
+ _ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...])
113
+ _ShapeType_co = TypeVar("_ShapeType_co", bound=tuple[int, ...], covariant=True)
114
+
115
+ @type_check_only
116
+ class _SupportsShape(Protocol[_ShapeType_co]):
117
+ # NOTE: it matters that `self` is positional only
118
+ @property
119
+ def shape(self, /) -> _ShapeType_co: ...
120
+
121
+ # a "sequence" that isn't a string, bytes, bytearray, or memoryview
122
+ _T = TypeVar("_T")
123
+ _PyArray: TypeAlias = list[_T] | tuple[_T, ...]
124
+ # `int` also covers `bool`
125
+ _PyScalar: TypeAlias = float | complex | bytes | str
126
+
127
+ @overload
128
+ def take(
129
+ a: _ArrayLike[_SCT],
130
+ indices: _IntLike_co,
131
+ axis: None = ...,
132
+ out: None = ...,
133
+ mode: _ModeKind = ...,
134
+ ) -> _SCT: ...
135
+ @overload
136
+ def take(
137
+ a: ArrayLike,
138
+ indices: _IntLike_co,
139
+ axis: SupportsIndex | None = ...,
140
+ out: None = ...,
141
+ mode: _ModeKind = ...,
142
+ ) -> Any: ...
143
+ @overload
144
+ def take(
145
+ a: _ArrayLike[_SCT],
146
+ indices: _ArrayLikeInt_co,
147
+ axis: SupportsIndex | None = ...,
148
+ out: None = ...,
149
+ mode: _ModeKind = ...,
150
+ ) -> NDArray[_SCT]: ...
151
+ @overload
152
+ def take(
153
+ a: ArrayLike,
154
+ indices: _ArrayLikeInt_co,
155
+ axis: SupportsIndex | None = ...,
156
+ out: None = ...,
157
+ mode: _ModeKind = ...,
158
+ ) -> NDArray[Any]: ...
159
+ @overload
160
+ def take(
161
+ a: ArrayLike,
162
+ indices: _ArrayLikeInt_co,
163
+ axis: SupportsIndex | None,
164
+ out: _ArrayT,
165
+ mode: _ModeKind = ...,
166
+ ) -> _ArrayT: ...
167
+ @overload
168
+ def take(
169
+ a: ArrayLike,
170
+ indices: _ArrayLikeInt_co,
171
+ axis: SupportsIndex | None = ...,
172
+ *,
173
+ out: _ArrayT,
174
+ mode: _ModeKind = ...,
175
+ ) -> _ArrayT: ...
176
+
177
+ @overload
178
+ def reshape( # shape: index
179
+ a: _ArrayLike[_SCT],
180
+ /,
181
+ shape: SupportsIndex,
182
+ order: _OrderACF = "C",
183
+ *,
184
+ copy: bool | None = None,
185
+ ) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ...
186
+ @overload
187
+ def reshape( # shape: (int, ...) @ _AnyShapeType
188
+ a: _ArrayLike[_SCT],
189
+ /,
190
+ shape: _AnyShapeType,
191
+ order: _OrderACF = "C",
192
+ *,
193
+ copy: bool | None = None,
194
+ ) -> np.ndarray[_AnyShapeType, np.dtype[_SCT]]: ...
195
+ @overload # shape: Sequence[index]
196
+ def reshape(
197
+ a: _ArrayLike[_SCT],
198
+ /,
199
+ shape: Sequence[SupportsIndex],
200
+ order: _OrderACF = "C",
201
+ *,
202
+ copy: bool | None = None,
203
+ ) -> NDArray[_SCT]: ...
204
+ @overload # shape: index
205
+ def reshape(
206
+ a: ArrayLike,
207
+ /,
208
+ shape: SupportsIndex,
209
+ order: _OrderACF = "C",
210
+ *,
211
+ copy: bool | None = None,
212
+ ) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
213
+ @overload
214
+ def reshape( # shape: (int, ...) @ _AnyShapeType
215
+ a: ArrayLike,
216
+ /,
217
+ shape: _AnyShapeType,
218
+ order: _OrderACF = "C",
219
+ *,
220
+ copy: bool | None = None,
221
+ ) -> np.ndarray[_AnyShapeType, np.dtype[Any]]: ...
222
+ @overload # shape: Sequence[index]
223
+ def reshape(
224
+ a: ArrayLike,
225
+ /,
226
+ shape: Sequence[SupportsIndex],
227
+ order: _OrderACF = "C",
228
+ *,
229
+ copy: bool | None = None,
230
+ ) -> NDArray[Any]: ...
231
+ @overload
232
+ @deprecated(
233
+ "`newshape` keyword argument is deprecated, "
234
+ "use `shape=...` or pass shape positionally instead. "
235
+ "(deprecated in NumPy 2.1)",
236
+ )
237
+ def reshape(
238
+ a: ArrayLike,
239
+ /,
240
+ shape: None = None,
241
+ order: _OrderACF = "C",
242
+ *,
243
+ newshape: _ShapeLike,
244
+ copy: bool | None = None,
245
+ ) -> NDArray[Any]: ...
246
+
247
+ @overload
248
+ def choose(
249
+ a: _IntLike_co,
250
+ choices: ArrayLike,
251
+ out: None = ...,
252
+ mode: _ModeKind = ...,
253
+ ) -> Any: ...
254
+ @overload
255
+ def choose(
256
+ a: _ArrayLikeInt_co,
257
+ choices: _ArrayLike[_SCT],
258
+ out: None = ...,
259
+ mode: _ModeKind = ...,
260
+ ) -> NDArray[_SCT]: ...
261
+ @overload
262
+ def choose(
263
+ a: _ArrayLikeInt_co,
264
+ choices: ArrayLike,
265
+ out: None = ...,
266
+ mode: _ModeKind = ...,
267
+ ) -> NDArray[Any]: ...
268
+ @overload
269
+ def choose(
270
+ a: _ArrayLikeInt_co,
271
+ choices: ArrayLike,
272
+ out: _ArrayT,
273
+ mode: _ModeKind = ...,
274
+ ) -> _ArrayT: ...
275
+
276
+ @overload
277
+ def repeat(
278
+ a: _ArrayLike[_SCT],
279
+ repeats: _ArrayLikeInt_co,
280
+ axis: SupportsIndex | None = ...,
281
+ ) -> NDArray[_SCT]: ...
282
+ @overload
283
+ def repeat(
284
+ a: ArrayLike,
285
+ repeats: _ArrayLikeInt_co,
286
+ axis: SupportsIndex | None = ...,
287
+ ) -> NDArray[Any]: ...
288
+
289
+ def put(
290
+ a: NDArray[Any],
291
+ ind: _ArrayLikeInt_co,
292
+ v: ArrayLike,
293
+ mode: _ModeKind = ...,
294
+ ) -> None: ...
295
+
296
+ @overload
297
+ def swapaxes(
298
+ a: _ArrayLike[_SCT],
299
+ axis1: SupportsIndex,
300
+ axis2: SupportsIndex,
301
+ ) -> NDArray[_SCT]: ...
302
+ @overload
303
+ def swapaxes(
304
+ a: ArrayLike,
305
+ axis1: SupportsIndex,
306
+ axis2: SupportsIndex,
307
+ ) -> NDArray[Any]: ...
308
+
309
+ @overload
310
+ def transpose(
311
+ a: _ArrayLike[_SCT],
312
+ axes: _ShapeLike | None = ...
313
+ ) -> NDArray[_SCT]: ...
314
+ @overload
315
+ def transpose(
316
+ a: ArrayLike,
317
+ axes: _ShapeLike | None = ...
318
+ ) -> NDArray[Any]: ...
319
+
320
+ @overload
321
+ def matrix_transpose(x: _ArrayLike[_SCT], /) -> NDArray[_SCT]: ...
322
+ @overload
323
+ def matrix_transpose(x: ArrayLike, /) -> NDArray[Any]: ...
324
+
325
+ #
326
+ @overload
327
+ def partition(
328
+ a: _ArrayLike[_SCT],
329
+ kth: _ArrayLikeInt,
330
+ axis: SupportsIndex | None = -1,
331
+ kind: _PartitionKind = "introselect",
332
+ order: None = None,
333
+ ) -> NDArray[_SCT]: ...
334
+ @overload
335
+ def partition(
336
+ a: _ArrayLike[np.void],
337
+ kth: _ArrayLikeInt,
338
+ axis: SupportsIndex | None = -1,
339
+ kind: _PartitionKind = "introselect",
340
+ order: str | Sequence[str] | None = None,
341
+ ) -> NDArray[np.void]: ...
342
+ @overload
343
+ def partition(
344
+ a: ArrayLike,
345
+ kth: _ArrayLikeInt,
346
+ axis: SupportsIndex | None = -1,
347
+ kind: _PartitionKind = "introselect",
348
+ order: str | Sequence[str] | None = None,
349
+ ) -> NDArray[Any]: ...
350
+
351
+ #
352
+ def argpartition(
353
+ a: ArrayLike,
354
+ kth: _ArrayLikeInt,
355
+ axis: SupportsIndex | None = -1,
356
+ kind: _PartitionKind = "introselect",
357
+ order: str | Sequence[str] | None = None,
358
+ ) -> NDArray[intp]: ...
359
+
360
+ #
361
+ @overload
362
+ def sort(
363
+ a: _ArrayLike[_SCT],
364
+ axis: SupportsIndex | None = ...,
365
+ kind: _SortKind | None = ...,
366
+ order: str | Sequence[str] | None = ...,
367
+ *,
368
+ stable: bool | None = ...,
369
+ ) -> NDArray[_SCT]: ...
370
+ @overload
371
+ def sort(
372
+ a: ArrayLike,
373
+ axis: SupportsIndex | None = ...,
374
+ kind: _SortKind | None = ...,
375
+ order: str | Sequence[str] | None = ...,
376
+ *,
377
+ stable: bool | None = ...,
378
+ ) -> NDArray[Any]: ...
379
+
380
+ def argsort(
381
+ a: ArrayLike,
382
+ axis: SupportsIndex | None = ...,
383
+ kind: _SortKind | None = ...,
384
+ order: str | Sequence[str] | None = ...,
385
+ *,
386
+ stable: bool | None = ...,
387
+ ) -> NDArray[intp]: ...
388
+
389
+ @overload
390
+ def argmax(
391
+ a: ArrayLike,
392
+ axis: None = ...,
393
+ out: None = ...,
394
+ *,
395
+ keepdims: Literal[False] = ...,
396
+ ) -> intp: ...
397
+ @overload
398
+ def argmax(
399
+ a: ArrayLike,
400
+ axis: SupportsIndex | None = ...,
401
+ out: None = ...,
402
+ *,
403
+ keepdims: bool = ...,
404
+ ) -> Any: ...
405
+ @overload
406
+ def argmax(
407
+ a: ArrayLike,
408
+ axis: SupportsIndex | None,
409
+ out: _ArrayT,
410
+ *,
411
+ keepdims: bool = ...,
412
+ ) -> _ArrayT: ...
413
+ @overload
414
+ def argmax(
415
+ a: ArrayLike,
416
+ axis: SupportsIndex | None = ...,
417
+ *,
418
+ out: _ArrayT,
419
+ keepdims: bool = ...,
420
+ ) -> _ArrayT: ...
421
+
422
+ @overload
423
+ def argmin(
424
+ a: ArrayLike,
425
+ axis: None = ...,
426
+ out: None = ...,
427
+ *,
428
+ keepdims: Literal[False] = ...,
429
+ ) -> intp: ...
430
+ @overload
431
+ def argmin(
432
+ a: ArrayLike,
433
+ axis: SupportsIndex | None = ...,
434
+ out: None = ...,
435
+ *,
436
+ keepdims: bool = ...,
437
+ ) -> Any: ...
438
+ @overload
439
+ def argmin(
440
+ a: ArrayLike,
441
+ axis: SupportsIndex | None,
442
+ out: _ArrayT,
443
+ *,
444
+ keepdims: bool = ...,
445
+ ) -> _ArrayT: ...
446
+ @overload
447
+ def argmin(
448
+ a: ArrayLike,
449
+ axis: SupportsIndex | None = ...,
450
+ *,
451
+ out: _ArrayT,
452
+ keepdims: bool = ...,
453
+ ) -> _ArrayT: ...
454
+
455
+ @overload
456
+ def searchsorted(
457
+ a: ArrayLike,
458
+ v: _ScalarLike_co,
459
+ side: _SortSide = ...,
460
+ sorter: _ArrayLikeInt_co | None = ..., # 1D int array
461
+ ) -> intp: ...
462
+ @overload
463
+ def searchsorted(
464
+ a: ArrayLike,
465
+ v: ArrayLike,
466
+ side: _SortSide = ...,
467
+ sorter: _ArrayLikeInt_co | None = ..., # 1D int array
468
+ ) -> NDArray[intp]: ...
469
+
470
+ #
471
+ @overload
472
+ def resize(a: _ArrayLike[_SCT], new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ...
473
+ @overload
474
+ def resize(a: _ArrayLike[_SCT], new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[_SCT]]: ...
475
+ @overload
476
+ def resize(a: _ArrayLike[_SCT], new_shape: _ShapeLike) -> NDArray[_SCT]: ...
477
+ @overload
478
+ def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
479
+ @overload
480
+ def resize(a: ArrayLike, new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[Any]]: ...
481
+ @overload
482
+ def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ...
483
+
484
+ @overload
485
+ def squeeze(
486
+ a: _SCT,
487
+ axis: _ShapeLike | None = ...,
488
+ ) -> _SCT: ...
489
+ @overload
490
+ def squeeze(
491
+ a: _ArrayLike[_SCT],
492
+ axis: _ShapeLike | None = ...,
493
+ ) -> NDArray[_SCT]: ...
494
+ @overload
495
+ def squeeze(
496
+ a: ArrayLike,
497
+ axis: _ShapeLike | None = ...,
498
+ ) -> NDArray[Any]: ...
499
+
500
+ @overload
501
+ def diagonal(
502
+ a: _ArrayLike[_SCT],
503
+ offset: SupportsIndex = ...,
504
+ axis1: SupportsIndex = ...,
505
+ axis2: SupportsIndex = ..., # >= 2D array
506
+ ) -> NDArray[_SCT]: ...
507
+ @overload
508
+ def diagonal(
509
+ a: ArrayLike,
510
+ offset: SupportsIndex = ...,
511
+ axis1: SupportsIndex = ...,
512
+ axis2: SupportsIndex = ..., # >= 2D array
513
+ ) -> NDArray[Any]: ...
514
+
515
+ @overload
516
+ def trace(
517
+ a: ArrayLike, # >= 2D array
518
+ offset: SupportsIndex = ...,
519
+ axis1: SupportsIndex = ...,
520
+ axis2: SupportsIndex = ...,
521
+ dtype: DTypeLike = ...,
522
+ out: None = ...,
523
+ ) -> Any: ...
524
+ @overload
525
+ def trace(
526
+ a: ArrayLike, # >= 2D array
527
+ offset: SupportsIndex,
528
+ axis1: SupportsIndex,
529
+ axis2: SupportsIndex,
530
+ dtype: DTypeLike,
531
+ out: _ArrayT,
532
+ ) -> _ArrayT: ...
533
+ @overload
534
+ def trace(
535
+ a: ArrayLike, # >= 2D array
536
+ offset: SupportsIndex = ...,
537
+ axis1: SupportsIndex = ...,
538
+ axis2: SupportsIndex = ...,
539
+ dtype: DTypeLike = ...,
540
+ *,
541
+ out: _ArrayT,
542
+ ) -> _ArrayT: ...
543
+
544
+ _Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_SCT]]
545
+
546
+ @overload
547
+ def ravel(a: _ArrayLike[_SCT], order: _OrderKACF = "C") -> _Array1D[_SCT]: ...
548
+ @overload
549
+ def ravel(a: bytes | _NestedSequence[bytes], order: _OrderKACF = "C") -> _Array1D[np.bytes_]: ...
550
+ @overload
551
+ def ravel(a: str | _NestedSequence[str], order: _OrderKACF = "C") -> _Array1D[np.str_]: ...
552
+ @overload
553
+ def ravel(a: bool | _NestedSequence[bool], order: _OrderKACF = "C") -> _Array1D[np.bool]: ...
554
+ @overload
555
+ def ravel(a: int | _NestedSequence[int], order: _OrderKACF = "C") -> _Array1D[np.int_ | np.bool]: ...
556
+ @overload
557
+ def ravel(a: float | _NestedSequence[float], order: _OrderKACF = "C") -> _Array1D[np.float64 | np.int_ | np.bool]: ...
558
+ @overload
559
+ def ravel(
560
+ a: complex | _NestedSequence[complex],
561
+ order: _OrderKACF = "C",
562
+ ) -> _Array1D[np.complex128 | np.float64 | np.int_ | np.bool]: ...
563
+ @overload
564
+ def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype[Any]]: ...
565
+
566
+ def nonzero(a: _ArrayLike[Any]) -> tuple[NDArray[intp], ...]: ...
567
+
568
+ # this prevents `Any` from being returned with Pyright
569
+ @overload
570
+ def shape(a: _SupportsShape[Never]) -> tuple[int, ...]: ...
571
+ @overload
572
+ def shape(a: _SupportsShape[_ShapeType]) -> _ShapeType: ...
573
+ @overload
574
+ def shape(a: _PyScalar) -> tuple[()]: ...
575
+ # `collections.abc.Sequence` can't be used hesre, since `bytes` and `str` are
576
+ # subtypes of it, which would make the return types incompatible.
577
+ @overload
578
+ def shape(a: _PyArray[_PyScalar]) -> tuple[int]: ...
579
+ @overload
580
+ def shape(a: _PyArray[_PyArray[_PyScalar]]) -> tuple[int, int]: ...
581
+ # this overload will be skipped by typecheckers that don't support PEP 688
582
+ @overload
583
+ def shape(a: memoryview | bytearray) -> tuple[int]: ...
584
+ @overload
585
+ def shape(a: ArrayLike) -> tuple[int, ...]: ...
586
+
587
+ @overload
588
+ def compress(
589
+ condition: _ArrayLikeBool_co, # 1D bool array
590
+ a: _ArrayLike[_SCT],
591
+ axis: SupportsIndex | None = ...,
592
+ out: None = ...,
593
+ ) -> NDArray[_SCT]: ...
594
+ @overload
595
+ def compress(
596
+ condition: _ArrayLikeBool_co, # 1D bool array
597
+ a: ArrayLike,
598
+ axis: SupportsIndex | None = ...,
599
+ out: None = ...,
600
+ ) -> NDArray[Any]: ...
601
+ @overload
602
+ def compress(
603
+ condition: _ArrayLikeBool_co, # 1D bool array
604
+ a: ArrayLike,
605
+ axis: SupportsIndex | None,
606
+ out: _ArrayT,
607
+ ) -> _ArrayT: ...
608
+ @overload
609
+ def compress(
610
+ condition: _ArrayLikeBool_co, # 1D bool array
611
+ a: ArrayLike,
612
+ axis: SupportsIndex | None = ...,
613
+ *,
614
+ out: _ArrayT,
615
+ ) -> _ArrayT: ...
616
+
617
+ @overload
618
+ def clip(
619
+ a: _SCT,
620
+ a_min: ArrayLike | None,
621
+ a_max: ArrayLike | None,
622
+ out: None = ...,
623
+ *,
624
+ min: ArrayLike | None = ...,
625
+ max: ArrayLike | None = ...,
626
+ dtype: None = ...,
627
+ where: _ArrayLikeBool_co | None = ...,
628
+ order: _OrderKACF = ...,
629
+ subok: bool = ...,
630
+ signature: str | tuple[str | None, ...] = ...,
631
+ casting: _CastingKind = ...,
632
+ ) -> _SCT: ...
633
+ @overload
634
+ def clip(
635
+ a: _ScalarLike_co,
636
+ a_min: ArrayLike | None,
637
+ a_max: ArrayLike | None,
638
+ out: None = ...,
639
+ *,
640
+ min: ArrayLike | None = ...,
641
+ max: ArrayLike | None = ...,
642
+ dtype: None = ...,
643
+ where: _ArrayLikeBool_co | None = ...,
644
+ order: _OrderKACF = ...,
645
+ subok: bool = ...,
646
+ signature: str | tuple[str | None, ...] = ...,
647
+ casting: _CastingKind = ...,
648
+ ) -> Any: ...
649
+ @overload
650
+ def clip(
651
+ a: _ArrayLike[_SCT],
652
+ a_min: ArrayLike | None,
653
+ a_max: ArrayLike | None,
654
+ out: None = ...,
655
+ *,
656
+ min: ArrayLike | None = ...,
657
+ max: ArrayLike | None = ...,
658
+ dtype: None = ...,
659
+ where: _ArrayLikeBool_co | None = ...,
660
+ order: _OrderKACF = ...,
661
+ subok: bool = ...,
662
+ signature: str | tuple[str | None, ...] = ...,
663
+ casting: _CastingKind = ...,
664
+ ) -> NDArray[_SCT]: ...
665
+ @overload
666
+ def clip(
667
+ a: ArrayLike,
668
+ a_min: ArrayLike | None,
669
+ a_max: ArrayLike | None,
670
+ out: None = ...,
671
+ *,
672
+ min: ArrayLike | None = ...,
673
+ max: ArrayLike | None = ...,
674
+ dtype: None = ...,
675
+ where: _ArrayLikeBool_co | None = ...,
676
+ order: _OrderKACF = ...,
677
+ subok: bool = ...,
678
+ signature: str | tuple[str | None, ...] = ...,
679
+ casting: _CastingKind = ...,
680
+ ) -> NDArray[Any]: ...
681
+ @overload
682
+ def clip(
683
+ a: ArrayLike,
684
+ a_min: ArrayLike | None,
685
+ a_max: ArrayLike | None,
686
+ out: _ArrayT,
687
+ *,
688
+ min: ArrayLike | None = ...,
689
+ max: ArrayLike | None = ...,
690
+ dtype: DTypeLike = ...,
691
+ where: _ArrayLikeBool_co | None = ...,
692
+ order: _OrderKACF = ...,
693
+ subok: bool = ...,
694
+ signature: str | tuple[str | None, ...] = ...,
695
+ casting: _CastingKind = ...,
696
+ ) -> _ArrayT: ...
697
+ @overload
698
+ def clip(
699
+ a: ArrayLike,
700
+ a_min: ArrayLike | None,
701
+ a_max: ArrayLike | None,
702
+ out: ArrayLike = ...,
703
+ *,
704
+ min: ArrayLike | None = ...,
705
+ max: ArrayLike | None = ...,
706
+ dtype: DTypeLike,
707
+ where: _ArrayLikeBool_co | None = ...,
708
+ order: _OrderKACF = ...,
709
+ subok: bool = ...,
710
+ signature: str | tuple[str | None, ...] = ...,
711
+ casting: _CastingKind = ...,
712
+ ) -> Any: ...
713
+
714
+ @overload
715
+ def sum(
716
+ a: _ArrayLike[_SCT],
717
+ axis: None = ...,
718
+ dtype: None = ...,
719
+ out: None = ...,
720
+ keepdims: Literal[False] = ...,
721
+ initial: _NumberLike_co = ...,
722
+ where: _ArrayLikeBool_co = ...,
723
+ ) -> _SCT: ...
724
+ @overload
725
+ def sum(
726
+ a: _ArrayLike[_SCT],
727
+ axis: None = ...,
728
+ dtype: None = ...,
729
+ out: None = ...,
730
+ keepdims: bool = ...,
731
+ initial: _NumberLike_co = ...,
732
+ where: _ArrayLikeBool_co = ...,
733
+ ) -> _SCT | NDArray[_SCT]: ...
734
+ @overload
735
+ def sum(
736
+ a: ArrayLike,
737
+ axis: None,
738
+ dtype: _DTypeLike[_SCT],
739
+ out: None = ...,
740
+ keepdims: Literal[False] = ...,
741
+ initial: _NumberLike_co = ...,
742
+ where: _ArrayLikeBool_co = ...,
743
+ ) -> _SCT: ...
744
+ @overload
745
+ def sum(
746
+ a: ArrayLike,
747
+ axis: None = ...,
748
+ *,
749
+ dtype: _DTypeLike[_SCT],
750
+ out: None = ...,
751
+ keepdims: Literal[False] = ...,
752
+ initial: _NumberLike_co = ...,
753
+ where: _ArrayLikeBool_co = ...,
754
+ ) -> _SCT: ...
755
+ @overload
756
+ def sum(
757
+ a: ArrayLike,
758
+ axis: _ShapeLike | None,
759
+ dtype: _DTypeLike[_SCT],
760
+ out: None = ...,
761
+ keepdims: bool = ...,
762
+ initial: _NumberLike_co = ...,
763
+ where: _ArrayLikeBool_co = ...,
764
+ ) -> _SCT | NDArray[_SCT]: ...
765
+ @overload
766
+ def sum(
767
+ a: ArrayLike,
768
+ axis: _ShapeLike | None = ...,
769
+ *,
770
+ dtype: _DTypeLike[_SCT],
771
+ out: None = ...,
772
+ keepdims: bool = ...,
773
+ initial: _NumberLike_co = ...,
774
+ where: _ArrayLikeBool_co = ...,
775
+ ) -> _SCT | NDArray[_SCT]: ...
776
+ @overload
777
+ def sum(
778
+ a: ArrayLike,
779
+ axis: _ShapeLike | None = ...,
780
+ dtype: DTypeLike = ...,
781
+ out: None = ...,
782
+ keepdims: bool = ...,
783
+ initial: _NumberLike_co = ...,
784
+ where: _ArrayLikeBool_co = ...,
785
+ ) -> Any: ...
786
+ @overload
787
+ def sum(
788
+ a: ArrayLike,
789
+ axis: _ShapeLike | None,
790
+ dtype: DTypeLike,
791
+ out: _ArrayT,
792
+ keepdims: bool = ...,
793
+ initial: _NumberLike_co = ...,
794
+ where: _ArrayLikeBool_co = ...,
795
+ ) -> _ArrayT: ...
796
+ @overload
797
+ def sum(
798
+ a: ArrayLike,
799
+ axis: _ShapeLike | None = ...,
800
+ dtype: DTypeLike = ...,
801
+ *,
802
+ out: _ArrayT,
803
+ keepdims: bool = ...,
804
+ initial: _NumberLike_co = ...,
805
+ where: _ArrayLikeBool_co = ...,
806
+ ) -> _ArrayT: ...
807
+
808
+ @overload
809
+ def all(
810
+ a: ArrayLike,
811
+ axis: None = None,
812
+ out: None = None,
813
+ keepdims: Literal[False, 0] | _NoValueType = ...,
814
+ *,
815
+ where: _ArrayLikeBool_co | _NoValueType = ...,
816
+ ) -> np.bool: ...
817
+ @overload
818
+ def all(
819
+ a: ArrayLike,
820
+ axis: int | tuple[int, ...] | None = None,
821
+ out: None = None,
822
+ keepdims: _BoolLike_co | _NoValueType = ...,
823
+ *,
824
+ where: _ArrayLikeBool_co | _NoValueType = ...,
825
+ ) -> Incomplete: ...
826
+ @overload
827
+ def all(
828
+ a: ArrayLike,
829
+ axis: int | tuple[int, ...] | None,
830
+ out: _ArrayT,
831
+ keepdims: _BoolLike_co | _NoValueType = ...,
832
+ *,
833
+ where: _ArrayLikeBool_co | _NoValueType = ...,
834
+ ) -> _ArrayT: ...
835
+ @overload
836
+ def all(
837
+ a: ArrayLike,
838
+ axis: int | tuple[int, ...] | None = None,
839
+ *,
840
+ out: _ArrayT,
841
+ keepdims: _BoolLike_co | _NoValueType = ...,
842
+ where: _ArrayLikeBool_co | _NoValueType = ...,
843
+ ) -> _ArrayT: ...
844
+
845
+ @overload
846
+ def any(
847
+ a: ArrayLike,
848
+ axis: None = None,
849
+ out: None = None,
850
+ keepdims: Literal[False, 0] | _NoValueType = ...,
851
+ *,
852
+ where: _ArrayLikeBool_co | _NoValueType = ...,
853
+ ) -> np.bool: ...
854
+ @overload
855
+ def any(
856
+ a: ArrayLike,
857
+ axis: int | tuple[int, ...] | None = None,
858
+ out: None = None,
859
+ keepdims: _BoolLike_co | _NoValueType = ...,
860
+ *,
861
+ where: _ArrayLikeBool_co | _NoValueType = ...,
862
+ ) -> Incomplete: ...
863
+ @overload
864
+ def any(
865
+ a: ArrayLike,
866
+ axis: int | tuple[int, ...] | None,
867
+ out: _ArrayT,
868
+ keepdims: _BoolLike_co | _NoValueType = ...,
869
+ *,
870
+ where: _ArrayLikeBool_co | _NoValueType = ...,
871
+ ) -> _ArrayT: ...
872
+ @overload
873
+ def any(
874
+ a: ArrayLike,
875
+ axis: int | tuple[int, ...] | None = None,
876
+ *,
877
+ out: _ArrayT,
878
+ keepdims: _BoolLike_co | _NoValueType = ...,
879
+ where: _ArrayLikeBool_co | _NoValueType = ...,
880
+ ) -> _ArrayT: ...
881
+
882
+ @overload
883
+ def cumsum(
884
+ a: _ArrayLike[_SCT],
885
+ axis: SupportsIndex | None = ...,
886
+ dtype: None = ...,
887
+ out: None = ...,
888
+ ) -> NDArray[_SCT]: ...
889
+ @overload
890
+ def cumsum(
891
+ a: ArrayLike,
892
+ axis: SupportsIndex | None = ...,
893
+ dtype: None = ...,
894
+ out: None = ...,
895
+ ) -> NDArray[Any]: ...
896
+ @overload
897
+ def cumsum(
898
+ a: ArrayLike,
899
+ axis: SupportsIndex | None,
900
+ dtype: _DTypeLike[_SCT],
901
+ out: None = ...,
902
+ ) -> NDArray[_SCT]: ...
903
+ @overload
904
+ def cumsum(
905
+ a: ArrayLike,
906
+ axis: SupportsIndex | None = ...,
907
+ *,
908
+ dtype: _DTypeLike[_SCT],
909
+ out: None = ...,
910
+ ) -> NDArray[_SCT]: ...
911
+ @overload
912
+ def cumsum(
913
+ a: ArrayLike,
914
+ axis: SupportsIndex | None = ...,
915
+ dtype: DTypeLike = ...,
916
+ out: None = ...,
917
+ ) -> NDArray[Any]: ...
918
+ @overload
919
+ def cumsum(
920
+ a: ArrayLike,
921
+ axis: SupportsIndex | None,
922
+ dtype: DTypeLike,
923
+ out: _ArrayT,
924
+ ) -> _ArrayT: ...
925
+ @overload
926
+ def cumsum(
927
+ a: ArrayLike,
928
+ axis: SupportsIndex | None = ...,
929
+ dtype: DTypeLike = ...,
930
+ *,
931
+ out: _ArrayT,
932
+ ) -> _ArrayT: ...
933
+
934
+ @overload
935
+ def cumulative_sum(
936
+ x: _ArrayLike[_SCT],
937
+ /,
938
+ *,
939
+ axis: SupportsIndex | None = ...,
940
+ dtype: None = ...,
941
+ out: None = ...,
942
+ include_initial: bool = ...,
943
+ ) -> NDArray[_SCT]: ...
944
+ @overload
945
+ def cumulative_sum(
946
+ x: ArrayLike,
947
+ /,
948
+ *,
949
+ axis: SupportsIndex | None = ...,
950
+ dtype: None = ...,
951
+ out: None = ...,
952
+ include_initial: bool = ...,
953
+ ) -> NDArray[Any]: ...
954
+ @overload
955
+ def cumulative_sum(
956
+ x: ArrayLike,
957
+ /,
958
+ *,
959
+ axis: SupportsIndex | None = ...,
960
+ dtype: _DTypeLike[_SCT],
961
+ out: None = ...,
962
+ include_initial: bool = ...,
963
+ ) -> NDArray[_SCT]: ...
964
+ @overload
965
+ def cumulative_sum(
966
+ x: ArrayLike,
967
+ /,
968
+ *,
969
+ axis: SupportsIndex | None = ...,
970
+ dtype: DTypeLike = ...,
971
+ out: None = ...,
972
+ include_initial: bool = ...,
973
+ ) -> NDArray[Any]: ...
974
+ @overload
975
+ def cumulative_sum(
976
+ x: ArrayLike,
977
+ /,
978
+ *,
979
+ axis: SupportsIndex | None = ...,
980
+ dtype: DTypeLike = ...,
981
+ out: _ArrayT,
982
+ include_initial: bool = ...,
983
+ ) -> _ArrayT: ...
984
+
985
+ @overload
986
+ def ptp(
987
+ a: _ArrayLike[_SCT],
988
+ axis: None = ...,
989
+ out: None = ...,
990
+ keepdims: Literal[False] = ...,
991
+ ) -> _SCT: ...
992
+ @overload
993
+ def ptp(
994
+ a: ArrayLike,
995
+ axis: _ShapeLike | None = ...,
996
+ out: None = ...,
997
+ keepdims: bool = ...,
998
+ ) -> Any: ...
999
+ @overload
1000
+ def ptp(
1001
+ a: ArrayLike,
1002
+ axis: _ShapeLike | None,
1003
+ out: _ArrayT,
1004
+ keepdims: bool = ...,
1005
+ ) -> _ArrayT: ...
1006
+ @overload
1007
+ def ptp(
1008
+ a: ArrayLike,
1009
+ axis: _ShapeLike | None = ...,
1010
+ *,
1011
+ out: _ArrayT,
1012
+ keepdims: bool = ...,
1013
+ ) -> _ArrayT: ...
1014
+
1015
+ @overload
1016
+ def amax(
1017
+ a: _ArrayLike[_SCT],
1018
+ axis: None = ...,
1019
+ out: None = ...,
1020
+ keepdims: Literal[False] = ...,
1021
+ initial: _NumberLike_co = ...,
1022
+ where: _ArrayLikeBool_co = ...,
1023
+ ) -> _SCT: ...
1024
+ @overload
1025
+ def amax(
1026
+ a: ArrayLike,
1027
+ axis: _ShapeLike | None = ...,
1028
+ out: None = ...,
1029
+ keepdims: bool = ...,
1030
+ initial: _NumberLike_co = ...,
1031
+ where: _ArrayLikeBool_co = ...,
1032
+ ) -> Any: ...
1033
+ @overload
1034
+ def amax(
1035
+ a: ArrayLike,
1036
+ axis: _ShapeLike | None,
1037
+ out: _ArrayT,
1038
+ keepdims: bool = ...,
1039
+ initial: _NumberLike_co = ...,
1040
+ where: _ArrayLikeBool_co = ...,
1041
+ ) -> _ArrayT: ...
1042
+ @overload
1043
+ def amax(
1044
+ a: ArrayLike,
1045
+ axis: _ShapeLike | None = ...,
1046
+ *,
1047
+ out: _ArrayT,
1048
+ keepdims: bool = ...,
1049
+ initial: _NumberLike_co = ...,
1050
+ where: _ArrayLikeBool_co = ...,
1051
+ ) -> _ArrayT: ...
1052
+
1053
+ @overload
1054
+ def amin(
1055
+ a: _ArrayLike[_SCT],
1056
+ axis: None = ...,
1057
+ out: None = ...,
1058
+ keepdims: Literal[False] = ...,
1059
+ initial: _NumberLike_co = ...,
1060
+ where: _ArrayLikeBool_co = ...,
1061
+ ) -> _SCT: ...
1062
+ @overload
1063
+ def amin(
1064
+ a: ArrayLike,
1065
+ axis: _ShapeLike | None = ...,
1066
+ out: None = ...,
1067
+ keepdims: bool = ...,
1068
+ initial: _NumberLike_co = ...,
1069
+ where: _ArrayLikeBool_co = ...,
1070
+ ) -> Any: ...
1071
+ @overload
1072
+ def amin(
1073
+ a: ArrayLike,
1074
+ axis: _ShapeLike | None,
1075
+ out: _ArrayT,
1076
+ keepdims: bool = ...,
1077
+ initial: _NumberLike_co = ...,
1078
+ where: _ArrayLikeBool_co = ...,
1079
+ ) -> _ArrayT: ...
1080
+ @overload
1081
+ def amin(
1082
+ a: ArrayLike,
1083
+ axis: _ShapeLike | None = ...,
1084
+ *,
1085
+ out: _ArrayT,
1086
+ keepdims: bool = ...,
1087
+ initial: _NumberLike_co = ...,
1088
+ where: _ArrayLikeBool_co = ...,
1089
+ ) -> _ArrayT: ...
1090
+
1091
+ # TODO: `np.prod()``: For object arrays `initial` does not necessarily
1092
+ # have to be a numerical scalar.
1093
+ # The only requirement is that it is compatible
1094
+ # with the `.__mul__()` method(s) of the passed array's elements.
1095
+
1096
+ # Note that the same situation holds for all wrappers around
1097
+ # `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`).
1098
+ @overload
1099
+ def prod(
1100
+ a: _ArrayLikeBool_co,
1101
+ axis: None = ...,
1102
+ dtype: None = ...,
1103
+ out: None = ...,
1104
+ keepdims: Literal[False] = ...,
1105
+ initial: _NumberLike_co = ...,
1106
+ where: _ArrayLikeBool_co = ...,
1107
+ ) -> int_: ...
1108
+ @overload
1109
+ def prod(
1110
+ a: _ArrayLikeUInt_co,
1111
+ axis: None = ...,
1112
+ dtype: None = ...,
1113
+ out: None = ...,
1114
+ keepdims: Literal[False] = ...,
1115
+ initial: _NumberLike_co = ...,
1116
+ where: _ArrayLikeBool_co = ...,
1117
+ ) -> uint64: ...
1118
+ @overload
1119
+ def prod(
1120
+ a: _ArrayLikeInt_co,
1121
+ axis: None = ...,
1122
+ dtype: None = ...,
1123
+ out: None = ...,
1124
+ keepdims: Literal[False] = ...,
1125
+ initial: _NumberLike_co = ...,
1126
+ where: _ArrayLikeBool_co = ...,
1127
+ ) -> int64: ...
1128
+ @overload
1129
+ def prod(
1130
+ a: _ArrayLikeFloat_co,
1131
+ axis: None = ...,
1132
+ dtype: None = ...,
1133
+ out: None = ...,
1134
+ keepdims: Literal[False] = ...,
1135
+ initial: _NumberLike_co = ...,
1136
+ where: _ArrayLikeBool_co = ...,
1137
+ ) -> floating[Any]: ...
1138
+ @overload
1139
+ def prod(
1140
+ a: _ArrayLikeComplex_co,
1141
+ axis: None = ...,
1142
+ dtype: None = ...,
1143
+ out: None = ...,
1144
+ keepdims: Literal[False] = ...,
1145
+ initial: _NumberLike_co = ...,
1146
+ where: _ArrayLikeBool_co = ...,
1147
+ ) -> complexfloating[Any, Any]: ...
1148
+ @overload
1149
+ def prod(
1150
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1151
+ axis: _ShapeLike | None = ...,
1152
+ dtype: None = ...,
1153
+ out: None = ...,
1154
+ keepdims: bool = ...,
1155
+ initial: _NumberLike_co = ...,
1156
+ where: _ArrayLikeBool_co = ...,
1157
+ ) -> Any: ...
1158
+ @overload
1159
+ def prod(
1160
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1161
+ axis: None,
1162
+ dtype: _DTypeLike[_SCT],
1163
+ out: None = ...,
1164
+ keepdims: Literal[False] = ...,
1165
+ initial: _NumberLike_co = ...,
1166
+ where: _ArrayLikeBool_co = ...,
1167
+ ) -> _SCT: ...
1168
+ @overload
1169
+ def prod(
1170
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1171
+ axis: None = ...,
1172
+ *,
1173
+ dtype: _DTypeLike[_SCT],
1174
+ out: None = ...,
1175
+ keepdims: Literal[False] = ...,
1176
+ initial: _NumberLike_co = ...,
1177
+ where: _ArrayLikeBool_co = ...,
1178
+ ) -> _SCT: ...
1179
+ @overload
1180
+ def prod(
1181
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1182
+ axis: _ShapeLike | None = ...,
1183
+ dtype: DTypeLike | None = ...,
1184
+ out: None = ...,
1185
+ keepdims: bool = ...,
1186
+ initial: _NumberLike_co = ...,
1187
+ where: _ArrayLikeBool_co = ...,
1188
+ ) -> Any: ...
1189
+ @overload
1190
+ def prod(
1191
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1192
+ axis: _ShapeLike | None,
1193
+ dtype: DTypeLike | None,
1194
+ out: _ArrayT,
1195
+ keepdims: bool = ...,
1196
+ initial: _NumberLike_co = ...,
1197
+ where: _ArrayLikeBool_co = ...,
1198
+ ) -> _ArrayT: ...
1199
+ @overload
1200
+ def prod(
1201
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1202
+ axis: _ShapeLike | None = ...,
1203
+ dtype: DTypeLike | None = ...,
1204
+ *,
1205
+ out: _ArrayT,
1206
+ keepdims: bool = ...,
1207
+ initial: _NumberLike_co = ...,
1208
+ where: _ArrayLikeBool_co = ...,
1209
+ ) -> _ArrayT: ...
1210
+
1211
+ @overload
1212
+ def cumprod(
1213
+ a: _ArrayLikeBool_co,
1214
+ axis: SupportsIndex | None = ...,
1215
+ dtype: None = ...,
1216
+ out: None = ...,
1217
+ ) -> NDArray[int_]: ...
1218
+ @overload
1219
+ def cumprod(
1220
+ a: _ArrayLikeUInt_co,
1221
+ axis: SupportsIndex | None = ...,
1222
+ dtype: None = ...,
1223
+ out: None = ...,
1224
+ ) -> NDArray[uint64]: ...
1225
+ @overload
1226
+ def cumprod(
1227
+ a: _ArrayLikeInt_co,
1228
+ axis: SupportsIndex | None = ...,
1229
+ dtype: None = ...,
1230
+ out: None = ...,
1231
+ ) -> NDArray[int64]: ...
1232
+ @overload
1233
+ def cumprod(
1234
+ a: _ArrayLikeFloat_co,
1235
+ axis: SupportsIndex | None = ...,
1236
+ dtype: None = ...,
1237
+ out: None = ...,
1238
+ ) -> NDArray[floating[Any]]: ...
1239
+ @overload
1240
+ def cumprod(
1241
+ a: _ArrayLikeComplex_co,
1242
+ axis: SupportsIndex | None = ...,
1243
+ dtype: None = ...,
1244
+ out: None = ...,
1245
+ ) -> NDArray[complexfloating[Any, Any]]: ...
1246
+ @overload
1247
+ def cumprod(
1248
+ a: _ArrayLikeObject_co,
1249
+ axis: SupportsIndex | None = ...,
1250
+ dtype: None = ...,
1251
+ out: None = ...,
1252
+ ) -> NDArray[object_]: ...
1253
+ @overload
1254
+ def cumprod(
1255
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1256
+ axis: SupportsIndex | None,
1257
+ dtype: _DTypeLike[_SCT],
1258
+ out: None = ...,
1259
+ ) -> NDArray[_SCT]: ...
1260
+ @overload
1261
+ def cumprod(
1262
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1263
+ axis: SupportsIndex | None = ...,
1264
+ *,
1265
+ dtype: _DTypeLike[_SCT],
1266
+ out: None = ...,
1267
+ ) -> NDArray[_SCT]: ...
1268
+ @overload
1269
+ def cumprod(
1270
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1271
+ axis: SupportsIndex | None = ...,
1272
+ dtype: DTypeLike = ...,
1273
+ out: None = ...,
1274
+ ) -> NDArray[Any]: ...
1275
+ @overload
1276
+ def cumprod(
1277
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1278
+ axis: SupportsIndex | None,
1279
+ dtype: DTypeLike,
1280
+ out: _ArrayT,
1281
+ ) -> _ArrayT: ...
1282
+ @overload
1283
+ def cumprod(
1284
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1285
+ axis: SupportsIndex | None = ...,
1286
+ dtype: DTypeLike = ...,
1287
+ *,
1288
+ out: _ArrayT,
1289
+ ) -> _ArrayT: ...
1290
+
1291
+ @overload
1292
+ def cumulative_prod(
1293
+ x: _ArrayLikeBool_co,
1294
+ /,
1295
+ *,
1296
+ axis: SupportsIndex | None = ...,
1297
+ dtype: None = ...,
1298
+ out: None = ...,
1299
+ include_initial: bool = ...,
1300
+ ) -> NDArray[int_]: ...
1301
+ @overload
1302
+ def cumulative_prod(
1303
+ x: _ArrayLikeUInt_co,
1304
+ /,
1305
+ *,
1306
+ axis: SupportsIndex | None = ...,
1307
+ dtype: None = ...,
1308
+ out: None = ...,
1309
+ include_initial: bool = ...,
1310
+ ) -> NDArray[uint64]: ...
1311
+ @overload
1312
+ def cumulative_prod(
1313
+ x: _ArrayLikeInt_co,
1314
+ /,
1315
+ *,
1316
+ axis: SupportsIndex | None = ...,
1317
+ dtype: None = ...,
1318
+ out: None = ...,
1319
+ include_initial: bool = ...,
1320
+ ) -> NDArray[int64]: ...
1321
+ @overload
1322
+ def cumulative_prod(
1323
+ x: _ArrayLikeFloat_co,
1324
+ /,
1325
+ *,
1326
+ axis: SupportsIndex | None = ...,
1327
+ dtype: None = ...,
1328
+ out: None = ...,
1329
+ include_initial: bool = ...,
1330
+ ) -> NDArray[floating[Any]]: ...
1331
+ @overload
1332
+ def cumulative_prod(
1333
+ x: _ArrayLikeComplex_co,
1334
+ /,
1335
+ *,
1336
+ axis: SupportsIndex | None = ...,
1337
+ dtype: None = ...,
1338
+ out: None = ...,
1339
+ include_initial: bool = ...,
1340
+ ) -> NDArray[complexfloating[Any, Any]]: ...
1341
+ @overload
1342
+ def cumulative_prod(
1343
+ x: _ArrayLikeObject_co,
1344
+ /,
1345
+ *,
1346
+ axis: SupportsIndex | None = ...,
1347
+ dtype: None = ...,
1348
+ out: None = ...,
1349
+ include_initial: bool = ...,
1350
+ ) -> NDArray[object_]: ...
1351
+ @overload
1352
+ def cumulative_prod(
1353
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1354
+ /,
1355
+ *,
1356
+ axis: SupportsIndex | None = ...,
1357
+ dtype: _DTypeLike[_SCT],
1358
+ out: None = ...,
1359
+ include_initial: bool = ...,
1360
+ ) -> NDArray[_SCT]: ...
1361
+ @overload
1362
+ def cumulative_prod(
1363
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1364
+ /,
1365
+ *,
1366
+ axis: SupportsIndex | None = ...,
1367
+ dtype: DTypeLike = ...,
1368
+ out: None = ...,
1369
+ include_initial: bool = ...,
1370
+ ) -> NDArray[Any]: ...
1371
+ @overload
1372
+ def cumulative_prod(
1373
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1374
+ /,
1375
+ *,
1376
+ axis: SupportsIndex | None = ...,
1377
+ dtype: DTypeLike = ...,
1378
+ out: _ArrayT,
1379
+ include_initial: bool = ...,
1380
+ ) -> _ArrayT: ...
1381
+
1382
+ def ndim(a: ArrayLike) -> int: ...
1383
+
1384
+ def size(a: ArrayLike, axis: int | None = ...) -> int: ...
1385
+
1386
+ @overload
1387
+ def around(
1388
+ a: _BoolLike_co,
1389
+ decimals: SupportsIndex = ...,
1390
+ out: None = ...,
1391
+ ) -> float16: ...
1392
+ @overload
1393
+ def around(
1394
+ a: _SCT_uifcO,
1395
+ decimals: SupportsIndex = ...,
1396
+ out: None = ...,
1397
+ ) -> _SCT_uifcO: ...
1398
+ @overload
1399
+ def around(
1400
+ a: _ComplexLike_co | object_,
1401
+ decimals: SupportsIndex = ...,
1402
+ out: None = ...,
1403
+ ) -> Any: ...
1404
+ @overload
1405
+ def around(
1406
+ a: _ArrayLikeBool_co,
1407
+ decimals: SupportsIndex = ...,
1408
+ out: None = ...,
1409
+ ) -> NDArray[float16]: ...
1410
+ @overload
1411
+ def around(
1412
+ a: _ArrayLike[_SCT_uifcO],
1413
+ decimals: SupportsIndex = ...,
1414
+ out: None = ...,
1415
+ ) -> NDArray[_SCT_uifcO]: ...
1416
+ @overload
1417
+ def around(
1418
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1419
+ decimals: SupportsIndex = ...,
1420
+ out: None = ...,
1421
+ ) -> NDArray[Any]: ...
1422
+ @overload
1423
+ def around(
1424
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1425
+ decimals: SupportsIndex,
1426
+ out: _ArrayT,
1427
+ ) -> _ArrayT: ...
1428
+ @overload
1429
+ def around(
1430
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1431
+ decimals: SupportsIndex = ...,
1432
+ *,
1433
+ out: _ArrayT,
1434
+ ) -> _ArrayT: ...
1435
+
1436
+ @overload
1437
+ def mean(
1438
+ a: _ArrayLikeFloat_co,
1439
+ axis: None = ...,
1440
+ dtype: None = ...,
1441
+ out: None = ...,
1442
+ keepdims: Literal[False] | _NoValueType = ...,
1443
+ *,
1444
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1445
+ ) -> floating[Any]: ...
1446
+ @overload
1447
+ def mean(
1448
+ a: _ArrayLikeComplex_co,
1449
+ axis: None = ...,
1450
+ dtype: None = ...,
1451
+ out: None = ...,
1452
+ keepdims: Literal[False] | _NoValueType = ...,
1453
+ *,
1454
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1455
+ ) -> complexfloating[Any]: ...
1456
+ @overload
1457
+ def mean(
1458
+ a: _ArrayLike[np.timedelta64],
1459
+ axis: None = ...,
1460
+ dtype: None = ...,
1461
+ out: None = ...,
1462
+ keepdims: Literal[False] | _NoValueType = ...,
1463
+ *,
1464
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1465
+ ) -> timedelta64: ...
1466
+ @overload
1467
+ def mean(
1468
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1469
+ axis: _ShapeLike | None,
1470
+ dtype: DTypeLike,
1471
+ out: _ArrayT,
1472
+ keepdims: bool | _NoValueType = ...,
1473
+ *,
1474
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1475
+ ) -> _ArrayT: ...
1476
+ @overload
1477
+ def mean(
1478
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1479
+ axis: _ShapeLike | None = ...,
1480
+ dtype: DTypeLike | None = ...,
1481
+ *,
1482
+ out: _ArrayT,
1483
+ keepdims: bool | _NoValueType = ...,
1484
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1485
+ ) -> _ArrayT: ...
1486
+ @overload
1487
+ def mean(
1488
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1489
+ axis: None,
1490
+ dtype: _DTypeLike[_SCT],
1491
+ out: None = ...,
1492
+ keepdims: Literal[False] | _NoValueType = ...,
1493
+ *,
1494
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1495
+ ) -> _SCT: ...
1496
+ @overload
1497
+ def mean(
1498
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1499
+ axis: None = ...,
1500
+ *,
1501
+ dtype: _DTypeLike[_SCT],
1502
+ out: None = ...,
1503
+ keepdims: Literal[False] | _NoValueType = ...,
1504
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1505
+ ) -> _SCT: ...
1506
+ @overload
1507
+ def mean(
1508
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1509
+ axis: _ShapeLike | None,
1510
+ dtype: _DTypeLike[_SCT],
1511
+ out: None,
1512
+ keepdims: Literal[True, 1],
1513
+ *,
1514
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1515
+ ) -> NDArray[_SCT]: ...
1516
+ @overload
1517
+ def mean(
1518
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1519
+ axis: _ShapeLike | None,
1520
+ dtype: _DTypeLike[_SCT],
1521
+ out: None = ...,
1522
+ *,
1523
+ keepdims: bool | _NoValueType = ...,
1524
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1525
+ ) -> _SCT | NDArray[_SCT]: ...
1526
+ @overload
1527
+ def mean(
1528
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1529
+ axis: _ShapeLike | None = ...,
1530
+ *,
1531
+ dtype: _DTypeLike[_SCT],
1532
+ out: None = ...,
1533
+ keepdims: bool | _NoValueType = ...,
1534
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1535
+ ) -> _SCT | NDArray[_SCT]: ...
1536
+ @overload
1537
+ def mean(
1538
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1539
+ axis: _ShapeLike | None = ...,
1540
+ dtype: DTypeLike | None = ...,
1541
+ out: None = ...,
1542
+ keepdims: bool | _NoValueType = ...,
1543
+ *,
1544
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1545
+ ) -> Incomplete: ...
1546
+
1547
+ @overload
1548
+ def std(
1549
+ a: _ArrayLikeComplex_co,
1550
+ axis: None = ...,
1551
+ dtype: None = ...,
1552
+ out: None = ...,
1553
+ ddof: float = ...,
1554
+ keepdims: Literal[False] = ...,
1555
+ *,
1556
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1557
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
1558
+ correction: float | _NoValueType = ...,
1559
+ ) -> floating[Any]: ...
1560
+ @overload
1561
+ def std(
1562
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1563
+ axis: _ShapeLike | None = ...,
1564
+ dtype: None = ...,
1565
+ out: None = ...,
1566
+ ddof: float = ...,
1567
+ keepdims: bool = ...,
1568
+ *,
1569
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1570
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1571
+ correction: float | _NoValueType = ...,
1572
+ ) -> Any: ...
1573
+ @overload
1574
+ def std(
1575
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1576
+ axis: None,
1577
+ dtype: _DTypeLike[_SCT],
1578
+ out: None = ...,
1579
+ ddof: float = ...,
1580
+ keepdims: Literal[False] = ...,
1581
+ *,
1582
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1583
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1584
+ correction: float | _NoValueType = ...,
1585
+ ) -> _SCT: ...
1586
+ @overload
1587
+ def std(
1588
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1589
+ axis: None = ...,
1590
+ *,
1591
+ dtype: _DTypeLike[_SCT],
1592
+ out: None = ...,
1593
+ ddof: float = ...,
1594
+ keepdims: Literal[False] = ...,
1595
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1596
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1597
+ correction: float | _NoValueType = ...,
1598
+ ) -> _SCT: ...
1599
+ @overload
1600
+ def std(
1601
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1602
+ axis: _ShapeLike | None = ...,
1603
+ dtype: DTypeLike = ...,
1604
+ out: None = ...,
1605
+ ddof: float = ...,
1606
+ keepdims: bool = ...,
1607
+ *,
1608
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1609
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1610
+ correction: float | _NoValueType = ...,
1611
+ ) -> Any: ...
1612
+ @overload
1613
+ def std(
1614
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1615
+ axis: _ShapeLike | None,
1616
+ dtype: DTypeLike,
1617
+ out: _ArrayT,
1618
+ ddof: float = ...,
1619
+ keepdims: bool = ...,
1620
+ *,
1621
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1622
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1623
+ correction: float | _NoValueType = ...,
1624
+ ) -> _ArrayT: ...
1625
+ @overload
1626
+ def std(
1627
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1628
+ axis: _ShapeLike | None = ...,
1629
+ dtype: DTypeLike = ...,
1630
+ *,
1631
+ out: _ArrayT,
1632
+ ddof: float = ...,
1633
+ keepdims: bool = ...,
1634
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1635
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1636
+ correction: float | _NoValueType = ...,
1637
+ ) -> _ArrayT: ...
1638
+
1639
+ @overload
1640
+ def var(
1641
+ a: _ArrayLikeComplex_co,
1642
+ axis: None = ...,
1643
+ dtype: None = ...,
1644
+ out: None = ...,
1645
+ ddof: float = ...,
1646
+ keepdims: Literal[False] = ...,
1647
+ *,
1648
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1649
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
1650
+ correction: float | _NoValueType = ...,
1651
+ ) -> floating[Any]: ...
1652
+ @overload
1653
+ def var(
1654
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1655
+ axis: _ShapeLike | None = ...,
1656
+ dtype: None = ...,
1657
+ out: None = ...,
1658
+ ddof: float = ...,
1659
+ keepdims: bool = ...,
1660
+ *,
1661
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1662
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1663
+ correction: float | _NoValueType = ...,
1664
+ ) -> Any: ...
1665
+ @overload
1666
+ def var(
1667
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1668
+ axis: None,
1669
+ dtype: _DTypeLike[_SCT],
1670
+ out: None = ...,
1671
+ ddof: float = ...,
1672
+ keepdims: Literal[False] = ...,
1673
+ *,
1674
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1675
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1676
+ correction: float | _NoValueType = ...,
1677
+ ) -> _SCT: ...
1678
+ @overload
1679
+ def var(
1680
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1681
+ axis: None = ...,
1682
+ *,
1683
+ dtype: _DTypeLike[_SCT],
1684
+ out: None = ...,
1685
+ ddof: float = ...,
1686
+ keepdims: Literal[False] = ...,
1687
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1688
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1689
+ correction: float | _NoValueType = ...,
1690
+ ) -> _SCT: ...
1691
+ @overload
1692
+ def var(
1693
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1694
+ axis: _ShapeLike | None = ...,
1695
+ dtype: DTypeLike = ...,
1696
+ out: None = ...,
1697
+ ddof: float = ...,
1698
+ keepdims: bool = ...,
1699
+ *,
1700
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1701
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1702
+ correction: float | _NoValueType = ...,
1703
+ ) -> Any: ...
1704
+ @overload
1705
+ def var(
1706
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1707
+ axis: _ShapeLike | None,
1708
+ dtype: DTypeLike,
1709
+ out: _ArrayT,
1710
+ ddof: float = ...,
1711
+ keepdims: bool = ...,
1712
+ *,
1713
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1714
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1715
+ correction: float | _NoValueType = ...,
1716
+ ) -> _ArrayT: ...
1717
+ @overload
1718
+ def var(
1719
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1720
+ axis: _ShapeLike | None = ...,
1721
+ dtype: DTypeLike = ...,
1722
+ *,
1723
+ out: _ArrayT,
1724
+ ddof: float = ...,
1725
+ keepdims: bool = ...,
1726
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1727
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1728
+ correction: float | _NoValueType = ...,
1729
+ ) -> _ArrayT: ...
1730
+
1731
+ max = amax
1732
+ min = amin
1733
+ round = around
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/function_base.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import warnings
3
+ import operator
4
+ import types
5
+
6
+ import numpy as np
7
+ from . import numeric as _nx
8
+ from .numeric import result_type, nan, asanyarray, ndim
9
+ from numpy._core.multiarray import add_docstring
10
+ from numpy._core._multiarray_umath import _array_converter
11
+ from numpy._core import overrides
12
+
13
+ __all__ = ['logspace', 'linspace', 'geomspace']
14
+
15
+
16
+ array_function_dispatch = functools.partial(
17
+ overrides.array_function_dispatch, module='numpy')
18
+
19
+
20
+ def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None,
21
+ dtype=None, axis=None, *, device=None):
22
+ return (start, stop)
23
+
24
+
25
+ @array_function_dispatch(_linspace_dispatcher)
26
+ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
27
+ axis=0, *, device=None):
28
+ """
29
+ Return evenly spaced numbers over a specified interval.
30
+
31
+ Returns `num` evenly spaced samples, calculated over the
32
+ interval [`start`, `stop`].
33
+
34
+ The endpoint of the interval can optionally be excluded.
35
+
36
+ .. versionchanged:: 1.20.0
37
+ Values are rounded towards ``-inf`` instead of ``0`` when an
38
+ integer ``dtype`` is specified. The old behavior can
39
+ still be obtained with ``np.linspace(start, stop, num).astype(int)``
40
+
41
+ Parameters
42
+ ----------
43
+ start : array_like
44
+ The starting value of the sequence.
45
+ stop : array_like
46
+ The end value of the sequence, unless `endpoint` is set to False.
47
+ In that case, the sequence consists of all but the last of ``num + 1``
48
+ evenly spaced samples, so that `stop` is excluded. Note that the step
49
+ size changes when `endpoint` is False.
50
+ num : int, optional
51
+ Number of samples to generate. Default is 50. Must be non-negative.
52
+ endpoint : bool, optional
53
+ If True, `stop` is the last sample. Otherwise, it is not included.
54
+ Default is True.
55
+ retstep : bool, optional
56
+ If True, return (`samples`, `step`), where `step` is the spacing
57
+ between samples.
58
+ dtype : dtype, optional
59
+ The type of the output array. If `dtype` is not given, the data type
60
+ is inferred from `start` and `stop`. The inferred dtype will never be
61
+ an integer; `float` is chosen even if the arguments would produce an
62
+ array of integers.
63
+ axis : int, optional
64
+ The axis in the result to store the samples. Relevant only if start
65
+ or stop are array-like. By default (0), the samples will be along a
66
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
67
+ device : str, optional
68
+ The device on which to place the created array. Default: None.
69
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
70
+
71
+ .. versionadded:: 2.0.0
72
+
73
+ Returns
74
+ -------
75
+ samples : ndarray
76
+ There are `num` equally spaced samples in the closed interval
77
+ ``[start, stop]`` or the half-open interval ``[start, stop)``
78
+ (depending on whether `endpoint` is True or False).
79
+ step : float, optional
80
+ Only returned if `retstep` is True
81
+
82
+ Size of spacing between samples.
83
+
84
+
85
+ See Also
86
+ --------
87
+ arange : Similar to `linspace`, but uses a step size (instead of the
88
+ number of samples).
89
+ geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
90
+ scale (a geometric progression).
91
+ logspace : Similar to `geomspace`, but with the end points specified as
92
+ logarithms.
93
+ :ref:`how-to-partition`
94
+
95
+ Examples
96
+ --------
97
+ >>> import numpy as np
98
+ >>> np.linspace(2.0, 3.0, num=5)
99
+ array([2. , 2.25, 2.5 , 2.75, 3. ])
100
+ >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
101
+ array([2. , 2.2, 2.4, 2.6, 2.8])
102
+ >>> np.linspace(2.0, 3.0, num=5, retstep=True)
103
+ (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
104
+
105
+ Graphical illustration:
106
+
107
+ >>> import matplotlib.pyplot as plt
108
+ >>> N = 8
109
+ >>> y = np.zeros(N)
110
+ >>> x1 = np.linspace(0, 10, N, endpoint=True)
111
+ >>> x2 = np.linspace(0, 10, N, endpoint=False)
112
+ >>> plt.plot(x1, y, 'o')
113
+ [<matplotlib.lines.Line2D object at 0x...>]
114
+ >>> plt.plot(x2, y + 0.5, 'o')
115
+ [<matplotlib.lines.Line2D object at 0x...>]
116
+ >>> plt.ylim([-0.5, 1])
117
+ (-0.5, 1)
118
+ >>> plt.show()
119
+
120
+ """
121
+ num = operator.index(num)
122
+ if num < 0:
123
+ raise ValueError(
124
+ "Number of samples, %s, must be non-negative." % num
125
+ )
126
+ div = (num - 1) if endpoint else num
127
+
128
+ conv = _array_converter(start, stop)
129
+ start, stop = conv.as_arrays()
130
+ dt = conv.result_type(ensure_inexact=True)
131
+
132
+ if dtype is None:
133
+ dtype = dt
134
+ integer_dtype = False
135
+ else:
136
+ integer_dtype = _nx.issubdtype(dtype, _nx.integer)
137
+
138
+ # Use `dtype=type(dt)` to enforce a floating point evaluation:
139
+ delta = np.subtract(stop, start, dtype=type(dt))
140
+ y = _nx.arange(
141
+ 0, num, dtype=dt, device=device
142
+ ).reshape((-1,) + (1,) * ndim(delta))
143
+
144
+ # In-place multiplication y *= delta/div is faster, but prevents
145
+ # the multiplicant from overriding what class is produced, and thus
146
+ # prevents, e.g. use of Quantities, see gh-7142. Hence, we multiply
147
+ # in place only for standard scalar types.
148
+ if div > 0:
149
+ _mult_inplace = _nx.isscalar(delta)
150
+ step = delta / div
151
+ any_step_zero = (
152
+ step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any())
153
+ if any_step_zero:
154
+ # Special handling for denormal numbers, gh-5437
155
+ y /= div
156
+ if _mult_inplace:
157
+ y *= delta
158
+ else:
159
+ y = y * delta
160
+ else:
161
+ if _mult_inplace:
162
+ y *= step
163
+ else:
164
+ y = y * step
165
+ else:
166
+ # sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
167
+ # have an undefined step
168
+ step = nan
169
+ # Multiply with delta to allow possible override of output class.
170
+ y = y * delta
171
+
172
+ y += start
173
+
174
+ if endpoint and num > 1:
175
+ y[-1, ...] = stop
176
+
177
+ if axis != 0:
178
+ y = _nx.moveaxis(y, 0, axis)
179
+
180
+ if integer_dtype:
181
+ _nx.floor(y, out=y)
182
+
183
+ y = conv.wrap(y.astype(dtype, copy=False))
184
+ if retstep:
185
+ return y, step
186
+ else:
187
+ return y
188
+
189
+
190
+ def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None,
191
+ dtype=None, axis=None):
192
+ return (start, stop, base)
193
+
194
+
195
+ @array_function_dispatch(_logspace_dispatcher)
196
+ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
197
+ axis=0):
198
+ """
199
+ Return numbers spaced evenly on a log scale.
200
+
201
+ In linear space, the sequence starts at ``base ** start``
202
+ (`base` to the power of `start`) and ends with ``base ** stop``
203
+ (see `endpoint` below).
204
+
205
+ .. versionchanged:: 1.25.0
206
+ Non-scalar 'base` is now supported
207
+
208
+ Parameters
209
+ ----------
210
+ start : array_like
211
+ ``base ** start`` is the starting value of the sequence.
212
+ stop : array_like
213
+ ``base ** stop`` is the final value of the sequence, unless `endpoint`
214
+ is False. In that case, ``num + 1`` values are spaced over the
215
+ interval in log-space, of which all but the last (a sequence of
216
+ length `num`) are returned.
217
+ num : integer, optional
218
+ Number of samples to generate. Default is 50.
219
+ endpoint : boolean, optional
220
+ If true, `stop` is the last sample. Otherwise, it is not included.
221
+ Default is True.
222
+ base : array_like, optional
223
+ The base of the log space. The step size between the elements in
224
+ ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
225
+ Default is 10.0.
226
+ dtype : dtype
227
+ The type of the output array. If `dtype` is not given, the data type
228
+ is inferred from `start` and `stop`. The inferred type will never be
229
+ an integer; `float` is chosen even if the arguments would produce an
230
+ array of integers.
231
+ axis : int, optional
232
+ The axis in the result to store the samples. Relevant only if start,
233
+ stop, or base are array-like. By default (0), the samples will be
234
+ along a new axis inserted at the beginning. Use -1 to get an axis at
235
+ the end.
236
+
237
+ Returns
238
+ -------
239
+ samples : ndarray
240
+ `num` samples, equally spaced on a log scale.
241
+
242
+ See Also
243
+ --------
244
+ arange : Similar to linspace, with the step size specified instead of the
245
+ number of samples. Note that, when used with a float endpoint, the
246
+ endpoint may or may not be included.
247
+ linspace : Similar to logspace, but with the samples uniformly distributed
248
+ in linear space, instead of log space.
249
+ geomspace : Similar to logspace, but with endpoints specified directly.
250
+ :ref:`how-to-partition`
251
+
252
+ Notes
253
+ -----
254
+ If base is a scalar, logspace is equivalent to the code
255
+
256
+ >>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
257
+ ... # doctest: +SKIP
258
+ >>> power(base, y).astype(dtype)
259
+ ... # doctest: +SKIP
260
+
261
+ Examples
262
+ --------
263
+ >>> import numpy as np
264
+ >>> np.logspace(2.0, 3.0, num=4)
265
+ array([ 100. , 215.443469 , 464.15888336, 1000. ])
266
+ >>> np.logspace(2.0, 3.0, num=4, endpoint=False)
267
+ array([100. , 177.827941 , 316.22776602, 562.34132519])
268
+ >>> np.logspace(2.0, 3.0, num=4, base=2.0)
269
+ array([4. , 5.0396842 , 6.34960421, 8. ])
270
+ >>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
271
+ array([[ 4. , 5.0396842 , 6.34960421, 8. ],
272
+ [ 9. , 12.98024613, 18.72075441, 27. ]])
273
+
274
+ Graphical illustration:
275
+
276
+ >>> import matplotlib.pyplot as plt
277
+ >>> N = 10
278
+ >>> x1 = np.logspace(0.1, 1, N, endpoint=True)
279
+ >>> x2 = np.logspace(0.1, 1, N, endpoint=False)
280
+ >>> y = np.zeros(N)
281
+ >>> plt.plot(x1, y, 'o')
282
+ [<matplotlib.lines.Line2D object at 0x...>]
283
+ >>> plt.plot(x2, y + 0.5, 'o')
284
+ [<matplotlib.lines.Line2D object at 0x...>]
285
+ >>> plt.ylim([-0.5, 1])
286
+ (-0.5, 1)
287
+ >>> plt.show()
288
+
289
+ """
290
+ if not isinstance(base, (float, int)) and np.ndim(base):
291
+ # If base is non-scalar, broadcast it with the others, since it
292
+ # may influence how axis is interpreted.
293
+ ndmax = np.broadcast(start, stop, base).ndim
294
+ start, stop, base = (
295
+ np.array(a, copy=None, subok=True, ndmin=ndmax)
296
+ for a in (start, stop, base)
297
+ )
298
+ base = np.expand_dims(base, axis=axis)
299
+ y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
300
+ if dtype is None:
301
+ return _nx.power(base, y)
302
+ return _nx.power(base, y).astype(dtype, copy=False)
303
+
304
+
305
+ def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
306
+ axis=None):
307
+ return (start, stop)
308
+
309
+
310
+ @array_function_dispatch(_geomspace_dispatcher)
311
+ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
312
+ """
313
+ Return numbers spaced evenly on a log scale (a geometric progression).
314
+
315
+ This is similar to `logspace`, but with endpoints specified directly.
316
+ Each output sample is a constant multiple of the previous.
317
+
318
+ Parameters
319
+ ----------
320
+ start : array_like
321
+ The starting value of the sequence.
322
+ stop : array_like
323
+ The final value of the sequence, unless `endpoint` is False.
324
+ In that case, ``num + 1`` values are spaced over the
325
+ interval in log-space, of which all but the last (a sequence of
326
+ length `num`) are returned.
327
+ num : integer, optional
328
+ Number of samples to generate. Default is 50.
329
+ endpoint : boolean, optional
330
+ If true, `stop` is the last sample. Otherwise, it is not included.
331
+ Default is True.
332
+ dtype : dtype
333
+ The type of the output array. If `dtype` is not given, the data type
334
+ is inferred from `start` and `stop`. The inferred dtype will never be
335
+ an integer; `float` is chosen even if the arguments would produce an
336
+ array of integers.
337
+ axis : int, optional
338
+ The axis in the result to store the samples. Relevant only if start
339
+ or stop are array-like. By default (0), the samples will be along a
340
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
341
+
342
+ Returns
343
+ -------
344
+ samples : ndarray
345
+ `num` samples, equally spaced on a log scale.
346
+
347
+ See Also
348
+ --------
349
+ logspace : Similar to geomspace, but with endpoints specified using log
350
+ and base.
351
+ linspace : Similar to geomspace, but with arithmetic instead of geometric
352
+ progression.
353
+ arange : Similar to linspace, with the step size specified instead of the
354
+ number of samples.
355
+ :ref:`how-to-partition`
356
+
357
+ Notes
358
+ -----
359
+ If the inputs or dtype are complex, the output will follow a logarithmic
360
+ spiral in the complex plane. (There are an infinite number of spirals
361
+ passing through two points; the output will follow the shortest such path.)
362
+
363
+ Examples
364
+ --------
365
+ >>> import numpy as np
366
+ >>> np.geomspace(1, 1000, num=4)
367
+ array([ 1., 10., 100., 1000.])
368
+ >>> np.geomspace(1, 1000, num=3, endpoint=False)
369
+ array([ 1., 10., 100.])
370
+ >>> np.geomspace(1, 1000, num=4, endpoint=False)
371
+ array([ 1. , 5.62341325, 31.6227766 , 177.827941 ])
372
+ >>> np.geomspace(1, 256, num=9)
373
+ array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.])
374
+
375
+ Note that the above may not produce exact integers:
376
+
377
+ >>> np.geomspace(1, 256, num=9, dtype=int)
378
+ array([ 1, 2, 4, 7, 16, 32, 63, 127, 256])
379
+ >>> np.around(np.geomspace(1, 256, num=9)).astype(int)
380
+ array([ 1, 2, 4, 8, 16, 32, 64, 128, 256])
381
+
382
+ Negative, decreasing, and complex inputs are allowed:
383
+
384
+ >>> np.geomspace(1000, 1, num=4)
385
+ array([1000., 100., 10., 1.])
386
+ >>> np.geomspace(-1000, -1, num=4)
387
+ array([-1000., -100., -10., -1.])
388
+ >>> np.geomspace(1j, 1000j, num=4) # Straight line
389
+ array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j])
390
+ >>> np.geomspace(-1+0j, 1+0j, num=5) # Circle
391
+ array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
392
+ 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,
393
+ 1.00000000e+00+0.00000000e+00j])
394
+
395
+ Graphical illustration of `endpoint` parameter:
396
+
397
+ >>> import matplotlib.pyplot as plt
398
+ >>> N = 10
399
+ >>> y = np.zeros(N)
400
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
401
+ [<matplotlib.lines.Line2D object at 0x...>]
402
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
403
+ [<matplotlib.lines.Line2D object at 0x...>]
404
+ >>> plt.axis([0.5, 2000, 0, 3])
405
+ [0.5, 2000, 0, 3]
406
+ >>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
407
+ >>> plt.show()
408
+
409
+ """
410
+ start = asanyarray(start)
411
+ stop = asanyarray(stop)
412
+ if _nx.any(start == 0) or _nx.any(stop == 0):
413
+ raise ValueError('Geometric sequence cannot include zero')
414
+
415
+ dt = result_type(start, stop, float(num), _nx.zeros((), dtype))
416
+ if dtype is None:
417
+ dtype = dt
418
+ else:
419
+ # complex to dtype('complex128'), for instance
420
+ dtype = _nx.dtype(dtype)
421
+
422
+ # Promote both arguments to the same dtype in case, for instance, one is
423
+ # complex and another is negative and log would produce NaN otherwise.
424
+ # Copy since we may change things in-place further down.
425
+ start = start.astype(dt, copy=True)
426
+ stop = stop.astype(dt, copy=True)
427
+
428
+ # Allow negative real values and ensure a consistent result for complex
429
+ # (including avoiding negligible real or imaginary parts in output) by
430
+ # rotating start to positive real, calculating, then undoing rotation.
431
+ out_sign = _nx.sign(start)
432
+ start /= out_sign
433
+ stop = stop / out_sign
434
+
435
+ log_start = _nx.log10(start)
436
+ log_stop = _nx.log10(stop)
437
+ result = logspace(log_start, log_stop, num=num,
438
+ endpoint=endpoint, base=10.0, dtype=dt)
439
+
440
+ # Make sure the endpoints match the start and stop arguments. This is
441
+ # necessary because np.exp(np.log(x)) is not necessarily equal to x.
442
+ if num > 0:
443
+ result[0] = start
444
+ if num > 1 and endpoint:
445
+ result[-1] = stop
446
+
447
+ result *= out_sign
448
+
449
+ if axis != 0:
450
+ result = _nx.moveaxis(result, 0, axis)
451
+
452
+ return result.astype(dtype, copy=False)
453
+
454
+
455
+ def _needs_add_docstring(obj):
456
+ """
457
+ Returns true if the only way to set the docstring of `obj` from python is
458
+ via add_docstring.
459
+
460
+ This function errs on the side of being overly conservative.
461
+ """
462
+ Py_TPFLAGS_HEAPTYPE = 1 << 9
463
+
464
+ if isinstance(obj, (types.FunctionType, types.MethodType, property)):
465
+ return False
466
+
467
+ if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE:
468
+ return False
469
+
470
+ return True
471
+
472
+
473
+ def _add_docstring(obj, doc, warn_on_python):
474
+ if warn_on_python and not _needs_add_docstring(obj):
475
+ warnings.warn(
476
+ "add_newdoc was used on a pure-python object {}. "
477
+ "Prefer to attach it directly to the source."
478
+ .format(obj),
479
+ UserWarning,
480
+ stacklevel=3)
481
+ try:
482
+ add_docstring(obj, doc)
483
+ except Exception:
484
+ pass
485
+
486
+
487
+ def add_newdoc(place, obj, doc, warn_on_python=True):
488
+ """
489
+ Add documentation to an existing object, typically one defined in C
490
+
491
+ The purpose is to allow easier editing of the docstrings without requiring
492
+ a re-compile. This exists primarily for internal use within numpy itself.
493
+
494
+ Parameters
495
+ ----------
496
+ place : str
497
+ The absolute name of the module to import from
498
+ obj : str or None
499
+ The name of the object to add documentation to, typically a class or
500
+ function name.
501
+ doc : {str, Tuple[str, str], List[Tuple[str, str]]}
502
+ If a string, the documentation to apply to `obj`
503
+
504
+ If a tuple, then the first element is interpreted as an attribute
505
+ of `obj` and the second as the docstring to apply -
506
+ ``(method, docstring)``
507
+
508
+ If a list, then each element of the list should be a tuple of length
509
+ two - ``[(method1, docstring1), (method2, docstring2), ...]``
510
+ warn_on_python : bool
511
+ If True, the default, emit `UserWarning` if this is used to attach
512
+ documentation to a pure-python object.
513
+
514
+ Notes
515
+ -----
516
+ This routine never raises an error if the docstring can't be written, but
517
+ will raise an error if the object being documented does not exist.
518
+
519
+ This routine cannot modify read-only docstrings, as appear
520
+ in new-style classes or built-in functions. Because this
521
+ routine never raises an error the caller must check manually
522
+ that the docstrings were changed.
523
+
524
+ Since this function grabs the ``char *`` from a c-level str object and puts
525
+ it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
526
+ C-API best-practices, by:
527
+
528
+ - modifying a `PyTypeObject` after calling `PyType_Ready`
529
+ - calling `Py_INCREF` on the str and losing the reference, so the str
530
+ will never be released
531
+
532
+ If possible it should be avoided.
533
+ """
534
+ new = getattr(__import__(place, globals(), {}, [obj]), obj)
535
+ if isinstance(doc, str):
536
+ if "${ARRAY_FUNCTION_LIKE}" in doc:
537
+ doc = overrides.get_array_function_like_doc(new, doc)
538
+ _add_docstring(new, doc.strip(), warn_on_python)
539
+ elif isinstance(doc, tuple):
540
+ attr, docstring = doc
541
+ _add_docstring(getattr(new, attr), docstring.strip(), warn_on_python)
542
+ elif isinstance(doc, list):
543
+ for attr, docstring in doc:
544
+ _add_docstring(
545
+ getattr(new, attr), docstring.strip(), warn_on_python
546
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/function_base.pyi ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Literal as L,
3
+ overload,
4
+ Any,
5
+ SupportsIndex,
6
+ TypeVar,
7
+ )
8
+
9
+ from numpy import floating, complexfloating, generic
10
+ from numpy._typing import (
11
+ NDArray,
12
+ DTypeLike,
13
+ _DTypeLike,
14
+ _ArrayLikeFloat_co,
15
+ _ArrayLikeComplex_co,
16
+ )
17
+
18
+ __all__ = ["logspace", "linspace", "geomspace"]
19
+
20
+ _SCT = TypeVar("_SCT", bound=generic)
21
+
22
+ @overload
23
+ def linspace(
24
+ start: _ArrayLikeFloat_co,
25
+ stop: _ArrayLikeFloat_co,
26
+ num: SupportsIndex = ...,
27
+ endpoint: bool = ...,
28
+ retstep: L[False] = ...,
29
+ dtype: None = ...,
30
+ axis: SupportsIndex = ...,
31
+ *,
32
+ device: L["cpu"] | None = ...,
33
+ ) -> NDArray[floating]: ...
34
+ @overload
35
+ def linspace(
36
+ start: _ArrayLikeComplex_co,
37
+ stop: _ArrayLikeComplex_co,
38
+ num: SupportsIndex = ...,
39
+ endpoint: bool = ...,
40
+ retstep: L[False] = ...,
41
+ dtype: None = ...,
42
+ axis: SupportsIndex = ...,
43
+ *,
44
+ device: L["cpu"] | None = ...,
45
+ ) -> NDArray[complexfloating]: ...
46
+ @overload
47
+ def linspace(
48
+ start: _ArrayLikeComplex_co,
49
+ stop: _ArrayLikeComplex_co,
50
+ num: SupportsIndex,
51
+ endpoint: bool,
52
+ retstep: L[False],
53
+ dtype: _DTypeLike[_SCT],
54
+ axis: SupportsIndex = ...,
55
+ *,
56
+ device: L["cpu"] | None = ...,
57
+ ) -> NDArray[_SCT]: ...
58
+ @overload
59
+ def linspace(
60
+ start: _ArrayLikeComplex_co,
61
+ stop: _ArrayLikeComplex_co,
62
+ num: SupportsIndex = ...,
63
+ endpoint: bool = ...,
64
+ retstep: L[False] = ...,
65
+ *,
66
+ dtype: _DTypeLike[_SCT],
67
+ axis: SupportsIndex = ...,
68
+ device: L["cpu"] | None = ...,
69
+ ) -> NDArray[_SCT]: ...
70
+ @overload
71
+ def linspace(
72
+ start: _ArrayLikeComplex_co,
73
+ stop: _ArrayLikeComplex_co,
74
+ num: SupportsIndex = ...,
75
+ endpoint: bool = ...,
76
+ retstep: L[False] = ...,
77
+ dtype: DTypeLike = ...,
78
+ axis: SupportsIndex = ...,
79
+ *,
80
+ device: L["cpu"] | None = ...,
81
+ ) -> NDArray[Any]: ...
82
+ @overload
83
+ def linspace(
84
+ start: _ArrayLikeFloat_co,
85
+ stop: _ArrayLikeFloat_co,
86
+ num: SupportsIndex = ...,
87
+ endpoint: bool = ...,
88
+ *,
89
+ retstep: L[True],
90
+ dtype: None = ...,
91
+ axis: SupportsIndex = ...,
92
+ device: L["cpu"] | None = ...,
93
+ ) -> tuple[NDArray[floating], floating]: ...
94
+ @overload
95
+ def linspace(
96
+ start: _ArrayLikeComplex_co,
97
+ stop: _ArrayLikeComplex_co,
98
+ num: SupportsIndex = ...,
99
+ endpoint: bool = ...,
100
+ *,
101
+ retstep: L[True],
102
+ dtype: None = ...,
103
+ axis: SupportsIndex = ...,
104
+ device: L["cpu"] | None = ...,
105
+ ) -> tuple[NDArray[complexfloating], complexfloating]: ...
106
+ @overload
107
+ def linspace(
108
+ start: _ArrayLikeComplex_co,
109
+ stop: _ArrayLikeComplex_co,
110
+ num: SupportsIndex = ...,
111
+ endpoint: bool = ...,
112
+ *,
113
+ retstep: L[True],
114
+ dtype: _DTypeLike[_SCT],
115
+ axis: SupportsIndex = ...,
116
+ device: L["cpu"] | None = ...,
117
+ ) -> tuple[NDArray[_SCT], _SCT]: ...
118
+ @overload
119
+ def linspace(
120
+ start: _ArrayLikeComplex_co,
121
+ stop: _ArrayLikeComplex_co,
122
+ num: SupportsIndex = ...,
123
+ endpoint: bool = ...,
124
+ *,
125
+ retstep: L[True],
126
+ dtype: DTypeLike = ...,
127
+ axis: SupportsIndex = ...,
128
+ device: L["cpu"] | None = ...,
129
+ ) -> tuple[NDArray[Any], Any]: ...
130
+
131
+ @overload
132
+ def logspace(
133
+ start: _ArrayLikeFloat_co,
134
+ stop: _ArrayLikeFloat_co,
135
+ num: SupportsIndex = ...,
136
+ endpoint: bool = ...,
137
+ base: _ArrayLikeFloat_co = ...,
138
+ dtype: None = ...,
139
+ axis: SupportsIndex = ...,
140
+ ) -> NDArray[floating]: ...
141
+ @overload
142
+ def logspace(
143
+ start: _ArrayLikeComplex_co,
144
+ stop: _ArrayLikeComplex_co,
145
+ num: SupportsIndex = ...,
146
+ endpoint: bool = ...,
147
+ base: _ArrayLikeComplex_co = ...,
148
+ dtype: None = ...,
149
+ axis: SupportsIndex = ...,
150
+ ) -> NDArray[complexfloating]: ...
151
+ @overload
152
+ def logspace(
153
+ start: _ArrayLikeComplex_co,
154
+ stop: _ArrayLikeComplex_co,
155
+ num: SupportsIndex,
156
+ endpoint: bool,
157
+ base: _ArrayLikeComplex_co,
158
+ dtype: _DTypeLike[_SCT],
159
+ axis: SupportsIndex = ...,
160
+ ) -> NDArray[_SCT]: ...
161
+ @overload
162
+ def logspace(
163
+ start: _ArrayLikeComplex_co,
164
+ stop: _ArrayLikeComplex_co,
165
+ num: SupportsIndex = ...,
166
+ endpoint: bool = ...,
167
+ base: _ArrayLikeComplex_co = ...,
168
+ *,
169
+ dtype: _DTypeLike[_SCT],
170
+ axis: SupportsIndex = ...,
171
+ ) -> NDArray[_SCT]: ...
172
+ @overload
173
+ def logspace(
174
+ start: _ArrayLikeComplex_co,
175
+ stop: _ArrayLikeComplex_co,
176
+ num: SupportsIndex = ...,
177
+ endpoint: bool = ...,
178
+ base: _ArrayLikeComplex_co = ...,
179
+ dtype: DTypeLike = ...,
180
+ axis: SupportsIndex = ...,
181
+ ) -> NDArray[Any]: ...
182
+
183
+ @overload
184
+ def geomspace(
185
+ start: _ArrayLikeFloat_co,
186
+ stop: _ArrayLikeFloat_co,
187
+ num: SupportsIndex = ...,
188
+ endpoint: bool = ...,
189
+ dtype: None = ...,
190
+ axis: SupportsIndex = ...,
191
+ ) -> NDArray[floating]: ...
192
+ @overload
193
+ def geomspace(
194
+ start: _ArrayLikeComplex_co,
195
+ stop: _ArrayLikeComplex_co,
196
+ num: SupportsIndex = ...,
197
+ endpoint: bool = ...,
198
+ dtype: None = ...,
199
+ axis: SupportsIndex = ...,
200
+ ) -> NDArray[complexfloating]: ...
201
+ @overload
202
+ def geomspace(
203
+ start: _ArrayLikeComplex_co,
204
+ stop: _ArrayLikeComplex_co,
205
+ num: SupportsIndex,
206
+ endpoint: bool,
207
+ dtype: _DTypeLike[_SCT],
208
+ axis: SupportsIndex = ...,
209
+ ) -> NDArray[_SCT]: ...
210
+ @overload
211
+ def geomspace(
212
+ start: _ArrayLikeComplex_co,
213
+ stop: _ArrayLikeComplex_co,
214
+ num: SupportsIndex = ...,
215
+ endpoint: bool = ...,
216
+ *,
217
+ dtype: _DTypeLike[_SCT],
218
+ axis: SupportsIndex = ...,
219
+ ) -> NDArray[_SCT]: ...
220
+ @overload
221
+ def geomspace(
222
+ start: _ArrayLikeComplex_co,
223
+ stop: _ArrayLikeComplex_co,
224
+ num: SupportsIndex = ...,
225
+ endpoint: bool = ...,
226
+ dtype: DTypeLike = ...,
227
+ axis: SupportsIndex = ...,
228
+ ) -> NDArray[Any]: ...
229
+
230
+ def add_newdoc(
231
+ place: str,
232
+ obj: str,
233
+ doc: str | tuple[str, str] | list[tuple[str, str]],
234
+ warn_on_python: bool = ...,
235
+ ) -> None: ...
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/getlimits.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Machine limits for Float32 and Float64 and (long double) if available...
2
+
3
+ """
4
+ __all__ = ['finfo', 'iinfo']
5
+
6
+ import types
7
+ import warnings
8
+
9
+ from .._utils import set_module
10
+ from ._machar import MachAr
11
+ from . import numeric
12
+ from . import numerictypes as ntypes
13
+ from .numeric import array, inf, nan
14
+ from .umath import log10, exp2, nextafter, isnan
15
+
16
+
17
+ def _fr0(a):
18
+ """fix rank-0 --> rank-1"""
19
+ if a.ndim == 0:
20
+ a = a.copy()
21
+ a.shape = (1,)
22
+ return a
23
+
24
+
25
+ def _fr1(a):
26
+ """fix rank > 0 --> rank-0"""
27
+ if a.size == 1:
28
+ a = a.copy()
29
+ a.shape = ()
30
+ return a
31
+
32
+
33
+ class MachArLike:
34
+ """ Object to simulate MachAr instance """
35
+ def __init__(self, ftype, *, eps, epsneg, huge, tiny,
36
+ ibeta, smallest_subnormal=None, **kwargs):
37
+ self.params = _MACHAR_PARAMS[ftype]
38
+ self.ftype = ftype
39
+ self.title = self.params['title']
40
+ # Parameter types same as for discovered MachAr object.
41
+ if not smallest_subnormal:
42
+ self._smallest_subnormal = nextafter(
43
+ self.ftype(0), self.ftype(1), dtype=self.ftype)
44
+ else:
45
+ self._smallest_subnormal = smallest_subnormal
46
+ self.epsilon = self.eps = self._float_to_float(eps)
47
+ self.epsneg = self._float_to_float(epsneg)
48
+ self.xmax = self.huge = self._float_to_float(huge)
49
+ self.xmin = self._float_to_float(tiny)
50
+ self.smallest_normal = self.tiny = self._float_to_float(tiny)
51
+ self.ibeta = self.params['itype'](ibeta)
52
+ self.__dict__.update(kwargs)
53
+ self.precision = int(-log10(self.eps))
54
+ self.resolution = self._float_to_float(
55
+ self._float_conv(10) ** (-self.precision))
56
+ self._str_eps = self._float_to_str(self.eps)
57
+ self._str_epsneg = self._float_to_str(self.epsneg)
58
+ self._str_xmin = self._float_to_str(self.xmin)
59
+ self._str_xmax = self._float_to_str(self.xmax)
60
+ self._str_resolution = self._float_to_str(self.resolution)
61
+ self._str_smallest_normal = self._float_to_str(self.xmin)
62
+
63
+ @property
64
+ def smallest_subnormal(self):
65
+ """Return the value for the smallest subnormal.
66
+
67
+ Returns
68
+ -------
69
+ smallest_subnormal : float
70
+ value for the smallest subnormal.
71
+
72
+ Warns
73
+ -----
74
+ UserWarning
75
+ If the calculated value for the smallest subnormal is zero.
76
+ """
77
+ # Check that the calculated value is not zero, in case it raises a
78
+ # warning.
79
+ value = self._smallest_subnormal
80
+ if self.ftype(0) == value:
81
+ warnings.warn(
82
+ 'The value of the smallest subnormal for {} type '
83
+ 'is zero.'.format(self.ftype), UserWarning, stacklevel=2)
84
+
85
+ return self._float_to_float(value)
86
+
87
+ @property
88
+ def _str_smallest_subnormal(self):
89
+ """Return the string representation of the smallest subnormal."""
90
+ return self._float_to_str(self.smallest_subnormal)
91
+
92
+ def _float_to_float(self, value):
93
+ """Converts float to float.
94
+
95
+ Parameters
96
+ ----------
97
+ value : float
98
+ value to be converted.
99
+ """
100
+ return _fr1(self._float_conv(value))
101
+
102
+ def _float_conv(self, value):
103
+ """Converts float to conv.
104
+
105
+ Parameters
106
+ ----------
107
+ value : float
108
+ value to be converted.
109
+ """
110
+ return array([value], self.ftype)
111
+
112
+ def _float_to_str(self, value):
113
+ """Converts float to str.
114
+
115
+ Parameters
116
+ ----------
117
+ value : float
118
+ value to be converted.
119
+ """
120
+ return self.params['fmt'] % array(_fr0(value)[0], self.ftype)
121
+
122
+
123
+ _convert_to_float = {
124
+ ntypes.csingle: ntypes.single,
125
+ ntypes.complex128: ntypes.float64,
126
+ ntypes.clongdouble: ntypes.longdouble
127
+ }
128
+
129
+ # Parameters for creating MachAr / MachAr-like objects
130
+ _title_fmt = 'numpy {} precision floating point number'
131
+ _MACHAR_PARAMS = {
132
+ ntypes.double: dict(
133
+ itype = ntypes.int64,
134
+ fmt = '%24.16e',
135
+ title = _title_fmt.format('double')),
136
+ ntypes.single: dict(
137
+ itype = ntypes.int32,
138
+ fmt = '%15.7e',
139
+ title = _title_fmt.format('single')),
140
+ ntypes.longdouble: dict(
141
+ itype = ntypes.longlong,
142
+ fmt = '%s',
143
+ title = _title_fmt.format('long double')),
144
+ ntypes.half: dict(
145
+ itype = ntypes.int16,
146
+ fmt = '%12.5e',
147
+ title = _title_fmt.format('half'))}
148
+
149
+ # Key to identify the floating point type. Key is result of
150
+ #
151
+ # ftype = np.longdouble # or float64, float32, etc.
152
+ # v = (ftype(-1.0) / ftype(10.0))
153
+ # v.view(v.dtype.newbyteorder('<')).tobytes()
154
+ #
155
+ # Uses division to work around deficiencies in strtold on some platforms.
156
+ # See:
157
+ # https://perl5.git.perl.org/perl.git/blob/3118d7d684b56cbeb702af874f4326683c45f045:/Configure
158
+
159
+ _KNOWN_TYPES = {}
160
+ def _register_type(machar, bytepat):
161
+ _KNOWN_TYPES[bytepat] = machar
162
+
163
+
164
+ _float_ma = {}
165
+
166
+
167
+ def _register_known_types():
168
+ # Known parameters for float16
169
+ # See docstring of MachAr class for description of parameters.
170
+ f16 = ntypes.float16
171
+ float16_ma = MachArLike(f16,
172
+ machep=-10,
173
+ negep=-11,
174
+ minexp=-14,
175
+ maxexp=16,
176
+ it=10,
177
+ iexp=5,
178
+ ibeta=2,
179
+ irnd=5,
180
+ ngrd=0,
181
+ eps=exp2(f16(-10)),
182
+ epsneg=exp2(f16(-11)),
183
+ huge=f16(65504),
184
+ tiny=f16(2 ** -14))
185
+ _register_type(float16_ma, b'f\xae')
186
+ _float_ma[16] = float16_ma
187
+
188
+ # Known parameters for float32
189
+ f32 = ntypes.float32
190
+ float32_ma = MachArLike(f32,
191
+ machep=-23,
192
+ negep=-24,
193
+ minexp=-126,
194
+ maxexp=128,
195
+ it=23,
196
+ iexp=8,
197
+ ibeta=2,
198
+ irnd=5,
199
+ ngrd=0,
200
+ eps=exp2(f32(-23)),
201
+ epsneg=exp2(f32(-24)),
202
+ huge=f32((1 - 2 ** -24) * 2**128),
203
+ tiny=exp2(f32(-126)))
204
+ _register_type(float32_ma, b'\xcd\xcc\xcc\xbd')
205
+ _float_ma[32] = float32_ma
206
+
207
+ # Known parameters for float64
208
+ f64 = ntypes.float64
209
+ epsneg_f64 = 2.0 ** -53.0
210
+ tiny_f64 = 2.0 ** -1022.0
211
+ float64_ma = MachArLike(f64,
212
+ machep=-52,
213
+ negep=-53,
214
+ minexp=-1022,
215
+ maxexp=1024,
216
+ it=52,
217
+ iexp=11,
218
+ ibeta=2,
219
+ irnd=5,
220
+ ngrd=0,
221
+ eps=2.0 ** -52.0,
222
+ epsneg=epsneg_f64,
223
+ huge=(1.0 - epsneg_f64) / tiny_f64 * f64(4),
224
+ tiny=tiny_f64)
225
+ _register_type(float64_ma, b'\x9a\x99\x99\x99\x99\x99\xb9\xbf')
226
+ _float_ma[64] = float64_ma
227
+
228
+ # Known parameters for IEEE 754 128-bit binary float
229
+ ld = ntypes.longdouble
230
+ epsneg_f128 = exp2(ld(-113))
231
+ tiny_f128 = exp2(ld(-16382))
232
+ # Ignore runtime error when this is not f128
233
+ with numeric.errstate(all='ignore'):
234
+ huge_f128 = (ld(1) - epsneg_f128) / tiny_f128 * ld(4)
235
+ float128_ma = MachArLike(ld,
236
+ machep=-112,
237
+ negep=-113,
238
+ minexp=-16382,
239
+ maxexp=16384,
240
+ it=112,
241
+ iexp=15,
242
+ ibeta=2,
243
+ irnd=5,
244
+ ngrd=0,
245
+ eps=exp2(ld(-112)),
246
+ epsneg=epsneg_f128,
247
+ huge=huge_f128,
248
+ tiny=tiny_f128)
249
+ # IEEE 754 128-bit binary float
250
+ _register_type(float128_ma,
251
+ b'\x9a\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\xfb\xbf')
252
+ _float_ma[128] = float128_ma
253
+
254
+ # Known parameters for float80 (Intel 80-bit extended precision)
255
+ epsneg_f80 = exp2(ld(-64))
256
+ tiny_f80 = exp2(ld(-16382))
257
+ # Ignore runtime error when this is not f80
258
+ with numeric.errstate(all='ignore'):
259
+ huge_f80 = (ld(1) - epsneg_f80) / tiny_f80 * ld(4)
260
+ float80_ma = MachArLike(ld,
261
+ machep=-63,
262
+ negep=-64,
263
+ minexp=-16382,
264
+ maxexp=16384,
265
+ it=63,
266
+ iexp=15,
267
+ ibeta=2,
268
+ irnd=5,
269
+ ngrd=0,
270
+ eps=exp2(ld(-63)),
271
+ epsneg=epsneg_f80,
272
+ huge=huge_f80,
273
+ tiny=tiny_f80)
274
+ # float80, first 10 bytes containing actual storage
275
+ _register_type(float80_ma, b'\xcd\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xfb\xbf')
276
+ _float_ma[80] = float80_ma
277
+
278
+ # Guessed / known parameters for double double; see:
279
+ # https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#Double-double_arithmetic
280
+ # These numbers have the same exponent range as float64, but extended
281
+ # number of digits in the significand.
282
+ huge_dd = nextafter(ld(inf), ld(0), dtype=ld)
283
+ # As the smallest_normal in double double is so hard to calculate we set
284
+ # it to NaN.
285
+ smallest_normal_dd = nan
286
+ # Leave the same value for the smallest subnormal as double
287
+ smallest_subnormal_dd = ld(nextafter(0., 1.))
288
+ float_dd_ma = MachArLike(ld,
289
+ machep=-105,
290
+ negep=-106,
291
+ minexp=-1022,
292
+ maxexp=1024,
293
+ it=105,
294
+ iexp=11,
295
+ ibeta=2,
296
+ irnd=5,
297
+ ngrd=0,
298
+ eps=exp2(ld(-105)),
299
+ epsneg=exp2(ld(-106)),
300
+ huge=huge_dd,
301
+ tiny=smallest_normal_dd,
302
+ smallest_subnormal=smallest_subnormal_dd)
303
+ # double double; low, high order (e.g. PPC 64)
304
+ _register_type(float_dd_ma,
305
+ b'\x9a\x99\x99\x99\x99\x99Y<\x9a\x99\x99\x99\x99\x99\xb9\xbf')
306
+ # double double; high, low order (e.g. PPC 64 le)
307
+ _register_type(float_dd_ma,
308
+ b'\x9a\x99\x99\x99\x99\x99\xb9\xbf\x9a\x99\x99\x99\x99\x99Y<')
309
+ _float_ma['dd'] = float_dd_ma
310
+
311
+
312
+ def _get_machar(ftype):
313
+ """ Get MachAr instance or MachAr-like instance
314
+
315
+ Get parameters for floating point type, by first trying signatures of
316
+ various known floating point types, then, if none match, attempting to
317
+ identify parameters by analysis.
318
+
319
+ Parameters
320
+ ----------
321
+ ftype : class
322
+ Numpy floating point type class (e.g. ``np.float64``)
323
+
324
+ Returns
325
+ -------
326
+ ma_like : instance of :class:`MachAr` or :class:`MachArLike`
327
+ Object giving floating point parameters for `ftype`.
328
+
329
+ Warns
330
+ -----
331
+ UserWarning
332
+ If the binary signature of the float type is not in the dictionary of
333
+ known float types.
334
+ """
335
+ params = _MACHAR_PARAMS.get(ftype)
336
+ if params is None:
337
+ raise ValueError(repr(ftype))
338
+ # Detect known / suspected types
339
+ # ftype(-1.0) / ftype(10.0) is better than ftype('-0.1') because stold
340
+ # may be deficient
341
+ key = (ftype(-1.0) / ftype(10.))
342
+ key = key.view(key.dtype.newbyteorder("<")).tobytes()
343
+ ma_like = None
344
+ if ftype == ntypes.longdouble:
345
+ # Could be 80 bit == 10 byte extended precision, where last bytes can
346
+ # be random garbage.
347
+ # Comparing first 10 bytes to pattern first to avoid branching on the
348
+ # random garbage.
349
+ ma_like = _KNOWN_TYPES.get(key[:10])
350
+ if ma_like is None:
351
+ # see if the full key is known.
352
+ ma_like = _KNOWN_TYPES.get(key)
353
+ if ma_like is None and len(key) == 16:
354
+ # machine limits could be f80 masquerading as np.float128,
355
+ # find all keys with length 16 and make new dict, but make the keys
356
+ # only 10 bytes long, the last bytes can be random garbage
357
+ _kt = {k[:10]: v for k, v in _KNOWN_TYPES.items() if len(k) == 16}
358
+ ma_like = _kt.get(key[:10])
359
+ if ma_like is not None:
360
+ return ma_like
361
+ # Fall back to parameter discovery
362
+ warnings.warn(
363
+ f'Signature {key} for {ftype} does not match any known type: '
364
+ 'falling back to type probe function.\n'
365
+ 'This warnings indicates broken support for the dtype!',
366
+ UserWarning, stacklevel=2)
367
+ return _discovered_machar(ftype)
368
+
369
+
370
+ def _discovered_machar(ftype):
371
+ """ Create MachAr instance with found information on float types
372
+
373
+ TODO: MachAr should be retired completely ideally. We currently only
374
+ ever use it system with broken longdouble (valgrind, WSL).
375
+ """
376
+ params = _MACHAR_PARAMS[ftype]
377
+ return MachAr(lambda v: array([v], ftype),
378
+ lambda v: _fr0(v.astype(params['itype']))[0],
379
+ lambda v: array(_fr0(v)[0], ftype),
380
+ lambda v: params['fmt'] % array(_fr0(v)[0], ftype),
381
+ params['title'])
382
+
383
+
384
+ @set_module('numpy')
385
+ class finfo:
386
+ """
387
+ finfo(dtype)
388
+
389
+ Machine limits for floating point types.
390
+
391
+ Attributes
392
+ ----------
393
+ bits : int
394
+ The number of bits occupied by the type.
395
+ dtype : dtype
396
+ Returns the dtype for which `finfo` returns information. For complex
397
+ input, the returned dtype is the associated ``float*`` dtype for its
398
+ real and complex components.
399
+ eps : float
400
+ The difference between 1.0 and the next smallest representable float
401
+ larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
402
+ standard, ``eps = 2**-52``, approximately 2.22e-16.
403
+ epsneg : float
404
+ The difference between 1.0 and the next smallest representable float
405
+ less than 1.0. For example, for 64-bit binary floats in the IEEE-754
406
+ standard, ``epsneg = 2**-53``, approximately 1.11e-16.
407
+ iexp : int
408
+ The number of bits in the exponent portion of the floating point
409
+ representation.
410
+ machep : int
411
+ The exponent that yields `eps`.
412
+ max : floating point number of the appropriate type
413
+ The largest representable number.
414
+ maxexp : int
415
+ The smallest positive power of the base (2) that causes overflow.
416
+ min : floating point number of the appropriate type
417
+ The smallest representable number, typically ``-max``.
418
+ minexp : int
419
+ The most negative power of the base (2) consistent with there
420
+ being no leading 0's in the mantissa.
421
+ negep : int
422
+ The exponent that yields `epsneg`.
423
+ nexp : int
424
+ The number of bits in the exponent including its sign and bias.
425
+ nmant : int
426
+ The number of bits in the mantissa.
427
+ precision : int
428
+ The approximate number of decimal digits to which this kind of
429
+ float is precise.
430
+ resolution : floating point number of the appropriate type
431
+ The approximate decimal resolution of this type, i.e.,
432
+ ``10**-precision``.
433
+ tiny : float
434
+ An alias for `smallest_normal`, kept for backwards compatibility.
435
+ smallest_normal : float
436
+ The smallest positive floating point number with 1 as leading bit in
437
+ the mantissa following IEEE-754 (see Notes).
438
+ smallest_subnormal : float
439
+ The smallest positive floating point number with 0 as leading bit in
440
+ the mantissa following IEEE-754.
441
+
442
+ Parameters
443
+ ----------
444
+ dtype : float, dtype, or instance
445
+ Kind of floating point or complex floating point
446
+ data-type about which to get information.
447
+
448
+ See Also
449
+ --------
450
+ iinfo : The equivalent for integer data types.
451
+ spacing : The distance between a value and the nearest adjacent number
452
+ nextafter : The next floating point value after x1 towards x2
453
+
454
+ Notes
455
+ -----
456
+ For developers of NumPy: do not instantiate this at the module level.
457
+ The initial calculation of these parameters is expensive and negatively
458
+ impacts import times. These objects are cached, so calling ``finfo()``
459
+ repeatedly inside your functions is not a problem.
460
+
461
+ Note that ``smallest_normal`` is not actually the smallest positive
462
+ representable value in a NumPy floating point type. As in the IEEE-754
463
+ standard [1]_, NumPy floating point types make use of subnormal numbers to
464
+ fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
465
+ may have significantly reduced precision [2]_.
466
+
467
+ This function can also be used for complex data types as well. If used,
468
+ the output will be the same as the corresponding real float type
469
+ (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
470
+ However, the output is true for the real and imaginary components.
471
+
472
+ References
473
+ ----------
474
+ .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
475
+ pp.1-70, 2008, https://doi.org/10.1109/IEEESTD.2008.4610935
476
+ .. [2] Wikipedia, "Denormal Numbers",
477
+ https://en.wikipedia.org/wiki/Denormal_number
478
+
479
+ Examples
480
+ --------
481
+ >>> import numpy as np
482
+ >>> np.finfo(np.float64).dtype
483
+ dtype('float64')
484
+ >>> np.finfo(np.complex64).dtype
485
+ dtype('float32')
486
+
487
+ """
488
+
489
+ _finfo_cache = {}
490
+
491
+ __class_getitem__ = classmethod(types.GenericAlias)
492
+
493
+ def __new__(cls, dtype):
494
+ try:
495
+ obj = cls._finfo_cache.get(dtype) # most common path
496
+ if obj is not None:
497
+ return obj
498
+ except TypeError:
499
+ pass
500
+
501
+ if dtype is None:
502
+ # Deprecated in NumPy 1.25, 2023-01-16
503
+ warnings.warn(
504
+ "finfo() dtype cannot be None. This behavior will "
505
+ "raise an error in the future. (Deprecated in NumPy 1.25)",
506
+ DeprecationWarning,
507
+ stacklevel=2
508
+ )
509
+
510
+ try:
511
+ dtype = numeric.dtype(dtype)
512
+ except TypeError:
513
+ # In case a float instance was given
514
+ dtype = numeric.dtype(type(dtype))
515
+
516
+ obj = cls._finfo_cache.get(dtype)
517
+ if obj is not None:
518
+ return obj
519
+ dtypes = [dtype]
520
+ newdtype = ntypes.obj2sctype(dtype)
521
+ if newdtype is not dtype:
522
+ dtypes.append(newdtype)
523
+ dtype = newdtype
524
+ if not issubclass(dtype, numeric.inexact):
525
+ raise ValueError("data type %r not inexact" % (dtype))
526
+ obj = cls._finfo_cache.get(dtype)
527
+ if obj is not None:
528
+ return obj
529
+ if not issubclass(dtype, numeric.floating):
530
+ newdtype = _convert_to_float[dtype]
531
+ if newdtype is not dtype:
532
+ # dtype changed, for example from complex128 to float64
533
+ dtypes.append(newdtype)
534
+ dtype = newdtype
535
+
536
+ obj = cls._finfo_cache.get(dtype, None)
537
+ if obj is not None:
538
+ # the original dtype was not in the cache, but the new
539
+ # dtype is in the cache. we add the original dtypes to
540
+ # the cache and return the result
541
+ for dt in dtypes:
542
+ cls._finfo_cache[dt] = obj
543
+ return obj
544
+ obj = object.__new__(cls)._init(dtype)
545
+ for dt in dtypes:
546
+ cls._finfo_cache[dt] = obj
547
+ return obj
548
+
549
+ def _init(self, dtype):
550
+ self.dtype = numeric.dtype(dtype)
551
+ machar = _get_machar(dtype)
552
+
553
+ for word in ['precision', 'iexp',
554
+ 'maxexp', 'minexp', 'negep',
555
+ 'machep']:
556
+ setattr(self, word, getattr(machar, word))
557
+ for word in ['resolution', 'epsneg', 'smallest_subnormal']:
558
+ setattr(self, word, getattr(machar, word).flat[0])
559
+ self.bits = self.dtype.itemsize * 8
560
+ self.max = machar.huge.flat[0]
561
+ self.min = -self.max
562
+ self.eps = machar.eps.flat[0]
563
+ self.nexp = machar.iexp
564
+ self.nmant = machar.it
565
+ self._machar = machar
566
+ self._str_tiny = machar._str_xmin.strip()
567
+ self._str_max = machar._str_xmax.strip()
568
+ self._str_epsneg = machar._str_epsneg.strip()
569
+ self._str_eps = machar._str_eps.strip()
570
+ self._str_resolution = machar._str_resolution.strip()
571
+ self._str_smallest_normal = machar._str_smallest_normal.strip()
572
+ self._str_smallest_subnormal = machar._str_smallest_subnormal.strip()
573
+ return self
574
+
575
+ def __str__(self):
576
+ fmt = (
577
+ 'Machine parameters for %(dtype)s\n'
578
+ '---------------------------------------------------------------\n'
579
+ 'precision = %(precision)3s resolution = %(_str_resolution)s\n'
580
+ 'machep = %(machep)6s eps = %(_str_eps)s\n'
581
+ 'negep = %(negep)6s epsneg = %(_str_epsneg)s\n'
582
+ 'minexp = %(minexp)6s tiny = %(_str_tiny)s\n'
583
+ 'maxexp = %(maxexp)6s max = %(_str_max)s\n'
584
+ 'nexp = %(nexp)6s min = -max\n'
585
+ 'smallest_normal = %(_str_smallest_normal)s '
586
+ 'smallest_subnormal = %(_str_smallest_subnormal)s\n'
587
+ '---------------------------------------------------------------\n'
588
+ )
589
+ return fmt % self.__dict__
590
+
591
+ def __repr__(self):
592
+ c = self.__class__.__name__
593
+ d = self.__dict__.copy()
594
+ d['klass'] = c
595
+ return (("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s,"
596
+ " max=%(_str_max)s, dtype=%(dtype)s)") % d)
597
+
598
+ @property
599
+ def smallest_normal(self):
600
+ """Return the value for the smallest normal.
601
+
602
+ Returns
603
+ -------
604
+ smallest_normal : float
605
+ Value for the smallest normal.
606
+
607
+ Warns
608
+ -----
609
+ UserWarning
610
+ If the calculated value for the smallest normal is requested for
611
+ double-double.
612
+ """
613
+ # This check is necessary because the value for smallest_normal is
614
+ # platform dependent for longdouble types.
615
+ if isnan(self._machar.smallest_normal.flat[0]):
616
+ warnings.warn(
617
+ 'The value of smallest normal is undefined for double double',
618
+ UserWarning, stacklevel=2)
619
+ return self._machar.smallest_normal.flat[0]
620
+
621
+ @property
622
+ def tiny(self):
623
+ """Return the value for tiny, alias of smallest_normal.
624
+
625
+ Returns
626
+ -------
627
+ tiny : float
628
+ Value for the smallest normal, alias of smallest_normal.
629
+
630
+ Warns
631
+ -----
632
+ UserWarning
633
+ If the calculated value for the smallest normal is requested for
634
+ double-double.
635
+ """
636
+ return self.smallest_normal
637
+
638
+
639
+ @set_module('numpy')
640
+ class iinfo:
641
+ """
642
+ iinfo(type)
643
+
644
+ Machine limits for integer types.
645
+
646
+ Attributes
647
+ ----------
648
+ bits : int
649
+ The number of bits occupied by the type.
650
+ dtype : dtype
651
+ Returns the dtype for which `iinfo` returns information.
652
+ min : int
653
+ The smallest integer expressible by the type.
654
+ max : int
655
+ The largest integer expressible by the type.
656
+
657
+ Parameters
658
+ ----------
659
+ int_type : integer type, dtype, or instance
660
+ The kind of integer data type to get information about.
661
+
662
+ See Also
663
+ --------
664
+ finfo : The equivalent for floating point data types.
665
+
666
+ Examples
667
+ --------
668
+ With types:
669
+
670
+ >>> import numpy as np
671
+ >>> ii16 = np.iinfo(np.int16)
672
+ >>> ii16.min
673
+ -32768
674
+ >>> ii16.max
675
+ 32767
676
+ >>> ii32 = np.iinfo(np.int32)
677
+ >>> ii32.min
678
+ -2147483648
679
+ >>> ii32.max
680
+ 2147483647
681
+
682
+ With instances:
683
+
684
+ >>> ii32 = np.iinfo(np.int32(10))
685
+ >>> ii32.min
686
+ -2147483648
687
+ >>> ii32.max
688
+ 2147483647
689
+
690
+ """
691
+
692
+ _min_vals = {}
693
+ _max_vals = {}
694
+
695
+ __class_getitem__ = classmethod(types.GenericAlias)
696
+
697
+ def __init__(self, int_type):
698
+ try:
699
+ self.dtype = numeric.dtype(int_type)
700
+ except TypeError:
701
+ self.dtype = numeric.dtype(type(int_type))
702
+ self.kind = self.dtype.kind
703
+ self.bits = self.dtype.itemsize * 8
704
+ self.key = "%s%d" % (self.kind, self.bits)
705
+ if self.kind not in 'iu':
706
+ raise ValueError("Invalid integer data type %r." % (self.kind,))
707
+
708
+ @property
709
+ def min(self):
710
+ """Minimum value of given dtype."""
711
+ if self.kind == 'u':
712
+ return 0
713
+ else:
714
+ try:
715
+ val = iinfo._min_vals[self.key]
716
+ except KeyError:
717
+ val = int(-(1 << (self.bits-1)))
718
+ iinfo._min_vals[self.key] = val
719
+ return val
720
+
721
+ @property
722
+ def max(self):
723
+ """Maximum value of given dtype."""
724
+ try:
725
+ val = iinfo._max_vals[self.key]
726
+ except KeyError:
727
+ if self.kind == 'u':
728
+ val = int((1 << self.bits) - 1)
729
+ else:
730
+ val = int((1 << (self.bits-1)) - 1)
731
+ iinfo._max_vals[self.key] = val
732
+ return val
733
+
734
+ def __str__(self):
735
+ """String representation."""
736
+ fmt = (
737
+ 'Machine parameters for %(dtype)s\n'
738
+ '---------------------------------------------------------------\n'
739
+ 'min = %(min)s\n'
740
+ 'max = %(max)s\n'
741
+ '---------------------------------------------------------------\n'
742
+ )
743
+ return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
744
+
745
+ def __repr__(self):
746
+ return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
747
+ self.min, self.max, self.dtype)
miniconda3/envs/ladir/lib/python3.10/site-packages/numpy/_core/getlimits.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from numpy import finfo, iinfo
2
+
3
+ __all__ = ["finfo", "iinfo"]