JinghuiLuAstronaut commited on
Commit
955d85e
·
verified ·
1 Parent(s): c494a5d

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/cversions.py +13 -0
  2. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/defchararray.py +2914 -0
  3. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/defchararray.pyi +421 -0
  4. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_argparse.py +62 -0
  5. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_array_coercion.py +898 -0
  6. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_custom_dtypes.py +253 -0
  7. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_function_base.py +446 -0
  8. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_getlimits.py +194 -0
  9. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_hashtable.py +30 -0
  10. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_indexing.py +1417 -0
  11. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_memmap.py +215 -0
  12. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_records.py +520 -0
  13. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalar_methods.py +204 -0
  14. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalarbuffer.py +153 -0
  15. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalarinherit.py +98 -0
  16. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_strings.py +99 -0
  17. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_umath.py +0 -0
  18. LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_umath_accuracy.py +75 -0
  19. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_lm1b_lr3e3_nobottleneck_step97k_decode1024_ema_selfcond_20260613_223847.log +31 -0
  20. LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_lr3e3_not5_nobottleneck_250k_decode64_ema_20260613_225804.log +31 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/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))
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/defchararray.py ADDED
@@ -0,0 +1,2914 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from .._utils import set_module
21
+ from .numerictypes import (
22
+ bytes_, str_, integer, int_, object_, bool_, character)
23
+ from .numeric import ndarray, compare_chararrays
24
+ from .numeric import array as narray
25
+ from numpy.core.multiarray import _vec_string
26
+ from numpy.core import overrides
27
+ from numpy.compat import asbytes
28
+ import numpy
29
+
30
+ __all__ = [
31
+ 'equal', 'not_equal', 'greater_equal', 'less_equal',
32
+ 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
33
+ 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
34
+ 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
35
+ 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
36
+ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
37
+ 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
38
+ 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
39
+ 'array', 'asarray'
40
+ ]
41
+
42
+
43
+ _globalvar = 0
44
+
45
+ array_function_dispatch = functools.partial(
46
+ overrides.array_function_dispatch, module='numpy.char')
47
+
48
+
49
+ def _is_unicode(arr):
50
+ """Returns True if arr is a string or a string array with a dtype that
51
+ represents a unicode string, otherwise returns False.
52
+
53
+ """
54
+ if (isinstance(arr, str) or
55
+ issubclass(numpy.asarray(arr).dtype.type, str)):
56
+ return True
57
+ return False
58
+
59
+
60
+ def _to_bytes_or_str_array(result, output_dtype_like=None):
61
+ """
62
+ Helper function to cast a result back into an array
63
+ with the appropriate dtype if an object array must be used
64
+ as an intermediary.
65
+ """
66
+ ret = numpy.asarray(result.tolist())
67
+ dtype = getattr(output_dtype_like, 'dtype', None)
68
+ if dtype is not None:
69
+ return ret.astype(type(dtype)(_get_num_chars(ret)), copy=False)
70
+ return ret
71
+
72
+
73
+ def _clean_args(*args):
74
+ """
75
+ Helper function for delegating arguments to Python string
76
+ functions.
77
+
78
+ Many of the Python string operations that have optional arguments
79
+ do not use 'None' to indicate a default value. In these cases,
80
+ we need to remove all None arguments, and those following them.
81
+ """
82
+ newargs = []
83
+ for chk in args:
84
+ if chk is None:
85
+ break
86
+ newargs.append(chk)
87
+ return newargs
88
+
89
+ def _get_num_chars(a):
90
+ """
91
+ Helper function that returns the number of characters per field in
92
+ a string or unicode array. This is to abstract out the fact that
93
+ for a unicode array this is itemsize / 4.
94
+ """
95
+ if issubclass(a.dtype.type, str_):
96
+ return a.itemsize // 4
97
+ return a.itemsize
98
+
99
+
100
+ def _binary_op_dispatcher(x1, x2):
101
+ return (x1, x2)
102
+
103
+
104
+ @array_function_dispatch(_binary_op_dispatcher)
105
+ def equal(x1, x2):
106
+ """
107
+ Return (x1 == x2) element-wise.
108
+
109
+ Unlike `numpy.equal`, this comparison is performed by first
110
+ stripping whitespace characters from the end of the string. This
111
+ behavior is provided for backward-compatibility with numarray.
112
+
113
+ Parameters
114
+ ----------
115
+ x1, x2 : array_like of str or unicode
116
+ Input arrays of the same shape.
117
+
118
+ Returns
119
+ -------
120
+ out : ndarray
121
+ Output array of bools.
122
+
123
+ See Also
124
+ --------
125
+ not_equal, greater_equal, less_equal, greater, less
126
+ """
127
+ return compare_chararrays(x1, x2, '==', True)
128
+
129
+
130
+ @array_function_dispatch(_binary_op_dispatcher)
131
+ def not_equal(x1, x2):
132
+ """
133
+ Return (x1 != x2) element-wise.
134
+
135
+ Unlike `numpy.not_equal`, this comparison is performed by first
136
+ stripping whitespace characters from the end of the string. This
137
+ behavior is provided for backward-compatibility with numarray.
138
+
139
+ Parameters
140
+ ----------
141
+ x1, x2 : array_like of str or unicode
142
+ Input arrays of the same shape.
143
+
144
+ Returns
145
+ -------
146
+ out : ndarray
147
+ Output array of bools.
148
+
149
+ See Also
150
+ --------
151
+ equal, greater_equal, less_equal, greater, less
152
+ """
153
+ return compare_chararrays(x1, x2, '!=', True)
154
+
155
+
156
+ @array_function_dispatch(_binary_op_dispatcher)
157
+ def greater_equal(x1, x2):
158
+ """
159
+ Return (x1 >= x2) element-wise.
160
+
161
+ Unlike `numpy.greater_equal`, this comparison is performed by
162
+ first stripping whitespace characters from the end of the string.
163
+ This behavior is provided for backward-compatibility with
164
+ numarray.
165
+
166
+ Parameters
167
+ ----------
168
+ x1, x2 : array_like of str or unicode
169
+ Input arrays of the same shape.
170
+
171
+ Returns
172
+ -------
173
+ out : ndarray
174
+ Output array of bools.
175
+
176
+ See Also
177
+ --------
178
+ equal, not_equal, less_equal, greater, less
179
+ """
180
+ return compare_chararrays(x1, x2, '>=', True)
181
+
182
+
183
+ @array_function_dispatch(_binary_op_dispatcher)
184
+ def less_equal(x1, x2):
185
+ """
186
+ Return (x1 <= x2) element-wise.
187
+
188
+ Unlike `numpy.less_equal`, this comparison is performed by first
189
+ stripping whitespace characters from the end of the string. This
190
+ behavior is provided for backward-compatibility with numarray.
191
+
192
+ Parameters
193
+ ----------
194
+ x1, x2 : array_like of str or unicode
195
+ Input arrays of the same shape.
196
+
197
+ Returns
198
+ -------
199
+ out : ndarray
200
+ Output array of bools.
201
+
202
+ See Also
203
+ --------
204
+ equal, not_equal, greater_equal, greater, less
205
+ """
206
+ return compare_chararrays(x1, x2, '<=', True)
207
+
208
+
209
+ @array_function_dispatch(_binary_op_dispatcher)
210
+ def greater(x1, x2):
211
+ """
212
+ Return (x1 > x2) element-wise.
213
+
214
+ Unlike `numpy.greater`, this comparison is performed by first
215
+ stripping whitespace characters from the end of the string. This
216
+ behavior is provided for backward-compatibility with numarray.
217
+
218
+ Parameters
219
+ ----------
220
+ x1, x2 : array_like of str or unicode
221
+ Input arrays of the same shape.
222
+
223
+ Returns
224
+ -------
225
+ out : ndarray
226
+ Output array of bools.
227
+
228
+ See Also
229
+ --------
230
+ equal, not_equal, greater_equal, less_equal, less
231
+ """
232
+ return compare_chararrays(x1, x2, '>', True)
233
+
234
+
235
+ @array_function_dispatch(_binary_op_dispatcher)
236
+ def less(x1, x2):
237
+ """
238
+ Return (x1 < x2) element-wise.
239
+
240
+ Unlike `numpy.greater`, this comparison is performed by first
241
+ stripping whitespace characters from the end of the string. This
242
+ behavior is provided for backward-compatibility with numarray.
243
+
244
+ Parameters
245
+ ----------
246
+ x1, x2 : array_like of str or unicode
247
+ Input arrays of the same shape.
248
+
249
+ Returns
250
+ -------
251
+ out : ndarray
252
+ Output array of bools.
253
+
254
+ See Also
255
+ --------
256
+ equal, not_equal, greater_equal, less_equal, greater
257
+ """
258
+ return compare_chararrays(x1, x2, '<', True)
259
+
260
+
261
+ def _unary_op_dispatcher(a):
262
+ return (a,)
263
+
264
+
265
+ @array_function_dispatch(_unary_op_dispatcher)
266
+ def str_len(a):
267
+ """
268
+ Return len(a) element-wise.
269
+
270
+ Parameters
271
+ ----------
272
+ a : array_like of str or unicode
273
+
274
+ Returns
275
+ -------
276
+ out : ndarray
277
+ Output array of integers
278
+
279
+ See Also
280
+ --------
281
+ len
282
+
283
+ Examples
284
+ --------
285
+ >>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])
286
+ >>> np.char.str_len(a)
287
+ array([23, 15])
288
+ >>> a = np.array([u'\u0420', u'\u043e'])
289
+ >>> np.char.str_len(a)
290
+ array([1, 1])
291
+ >>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']])
292
+ >>> np.char.str_len(a)
293
+ array([[5, 5], [1, 1]])
294
+ """
295
+ # Note: __len__, etc. currently return ints, which are not C-integers.
296
+ # Generally intp would be expected for lengths, although int is sufficient
297
+ # due to the dtype itemsize limitation.
298
+ return _vec_string(a, int_, '__len__')
299
+
300
+
301
+ @array_function_dispatch(_binary_op_dispatcher)
302
+ def add(x1, x2):
303
+ """
304
+ Return element-wise string concatenation for two arrays of str or unicode.
305
+
306
+ Arrays `x1` and `x2` must have the same shape.
307
+
308
+ Parameters
309
+ ----------
310
+ x1 : array_like of str or unicode
311
+ Input array.
312
+ x2 : array_like of str or unicode
313
+ Input array.
314
+
315
+ Returns
316
+ -------
317
+ add : ndarray
318
+ Output array of `bytes_` or `str_`, depending on input types
319
+ of the same shape as `x1` and `x2`.
320
+
321
+ """
322
+ arr1 = numpy.asarray(x1)
323
+ arr2 = numpy.asarray(x2)
324
+ out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
325
+
326
+ if type(arr1.dtype) != type(arr2.dtype):
327
+ # Enforce this for now. The solution to it will be implement add
328
+ # as a ufunc. It never worked right on Python 3: bytes + unicode gave
329
+ # nonsense unicode + bytes errored, and unicode + object used the
330
+ # object dtype itemsize as num chars (worked on short strings).
331
+ # bytes + void worked but promoting void->bytes is dubious also.
332
+ raise TypeError(
333
+ "np.char.add() requires both arrays of the same dtype kind, but "
334
+ f"got dtypes: '{arr1.dtype}' and '{arr2.dtype}' (the few cases "
335
+ "where this used to work often lead to incorrect results).")
336
+
337
+ return _vec_string(arr1, type(arr1.dtype)(out_size), '__add__', (arr2,))
338
+
339
+ def _multiply_dispatcher(a, i):
340
+ return (a,)
341
+
342
+
343
+ @array_function_dispatch(_multiply_dispatcher)
344
+ def multiply(a, i):
345
+ """
346
+ Return (a * i), that is string multiple concatenation,
347
+ element-wise.
348
+
349
+ Values in `i` of less than 0 are treated as 0 (which yields an
350
+ empty string).
351
+
352
+ Parameters
353
+ ----------
354
+ a : array_like of str or unicode
355
+
356
+ i : array_like of ints
357
+
358
+ Returns
359
+ -------
360
+ out : ndarray
361
+ Output array of str or unicode, depending on input types
362
+
363
+ Examples
364
+ --------
365
+ >>> a = np.array(["a", "b", "c"])
366
+ >>> np.char.multiply(x, 3)
367
+ array(['aaa', 'bbb', 'ccc'], dtype='<U3')
368
+ >>> i = np.array([1, 2, 3])
369
+ >>> np.char.multiply(a, i)
370
+ array(['a', 'bb', 'ccc'], dtype='<U3')
371
+ >>> np.char.multiply(np.array(['a']), i)
372
+ array(['a', 'aa', 'aaa'], dtype='<U3')
373
+ >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
374
+ >>> np.char.multiply(a, 3)
375
+ array([['aaa', 'bbb', 'ccc'],
376
+ ['ddd', 'eee', 'fff']], dtype='<U3')
377
+ >>> np.char.multiply(a, i)
378
+ array([['a', 'bb', 'ccc'],
379
+ ['d', 'ee', 'fff']], dtype='<U3')
380
+ """
381
+ a_arr = numpy.asarray(a)
382
+ i_arr = numpy.asarray(i)
383
+ if not issubclass(i_arr.dtype.type, integer):
384
+ raise ValueError("Can only multiply by integers")
385
+ out_size = _get_num_chars(a_arr) * max(int(i_arr.max()), 0)
386
+ return _vec_string(
387
+ a_arr, type(a_arr.dtype)(out_size), '__mul__', (i_arr,))
388
+
389
+
390
+ def _mod_dispatcher(a, values):
391
+ return (a, values)
392
+
393
+
394
+ @array_function_dispatch(_mod_dispatcher)
395
+ def mod(a, values):
396
+ """
397
+ Return (a % i), that is pre-Python 2.6 string formatting
398
+ (interpolation), element-wise for a pair of array_likes of str
399
+ or unicode.
400
+
401
+ Parameters
402
+ ----------
403
+ a : array_like of str or unicode
404
+
405
+ values : array_like of values
406
+ These values will be element-wise interpolated into the string.
407
+
408
+ Returns
409
+ -------
410
+ out : ndarray
411
+ Output array of str or unicode, depending on input types
412
+
413
+ See Also
414
+ --------
415
+ str.__mod__
416
+
417
+ """
418
+ return _to_bytes_or_str_array(
419
+ _vec_string(a, object_, '__mod__', (values,)), a)
420
+
421
+
422
+ @array_function_dispatch(_unary_op_dispatcher)
423
+ def capitalize(a):
424
+ """
425
+ Return a copy of `a` with only the first character of each element
426
+ capitalized.
427
+
428
+ Calls `str.capitalize` element-wise.
429
+
430
+ For 8-bit strings, this method is locale-dependent.
431
+
432
+ Parameters
433
+ ----------
434
+ a : array_like of str or unicode
435
+ Input array of strings to capitalize.
436
+
437
+ Returns
438
+ -------
439
+ out : ndarray
440
+ Output array of str or unicode, depending on input
441
+ types
442
+
443
+ See Also
444
+ --------
445
+ str.capitalize
446
+
447
+ Examples
448
+ --------
449
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
450
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'],
451
+ dtype='|S4')
452
+ >>> np.char.capitalize(c)
453
+ array(['A1b2', '1b2a', 'B2a1', '2a1b'],
454
+ dtype='|S4')
455
+
456
+ """
457
+ a_arr = numpy.asarray(a)
458
+ return _vec_string(a_arr, a_arr.dtype, 'capitalize')
459
+
460
+
461
+ def _center_dispatcher(a, width, fillchar=None):
462
+ return (a,)
463
+
464
+
465
+ @array_function_dispatch(_center_dispatcher)
466
+ def center(a, width, fillchar=' '):
467
+ """
468
+ Return a copy of `a` with its elements centered in a string of
469
+ length `width`.
470
+
471
+ Calls `str.center` element-wise.
472
+
473
+ Parameters
474
+ ----------
475
+ a : array_like of str or unicode
476
+
477
+ width : int
478
+ The length of the resulting strings
479
+ fillchar : str or unicode, optional
480
+ The padding character to use (default is space).
481
+
482
+ Returns
483
+ -------
484
+ out : ndarray
485
+ Output array of str or unicode, depending on input
486
+ types
487
+
488
+ See Also
489
+ --------
490
+ str.center
491
+
492
+ Notes
493
+ -----
494
+ This function is intended to work with arrays of strings. The
495
+ fill character is not applied to numeric types.
496
+
497
+ Examples
498
+ --------
499
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
500
+ array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
501
+ >>> np.char.center(c, width=9)
502
+ array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
503
+ >>> np.char.center(c, width=9, fillchar='*')
504
+ array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
505
+ >>> np.char.center(c, width=1)
506
+ array(['a', '1', 'b', '2'], dtype='<U1')
507
+
508
+ """
509
+ a_arr = numpy.asarray(a)
510
+ width_arr = numpy.asarray(width)
511
+ size = int(numpy.max(width_arr.flat))
512
+ if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
513
+ fillchar = asbytes(fillchar)
514
+ return _vec_string(
515
+ a_arr, type(a_arr.dtype)(size), 'center', (width_arr, fillchar))
516
+
517
+
518
+ def _count_dispatcher(a, sub, start=None, end=None):
519
+ return (a,)
520
+
521
+
522
+ @array_function_dispatch(_count_dispatcher)
523
+ def count(a, sub, start=0, end=None):
524
+ """
525
+ Returns an array with the number of non-overlapping occurrences of
526
+ substring `sub` in the range [`start`, `end`].
527
+
528
+ Calls `str.count` element-wise.
529
+
530
+ Parameters
531
+ ----------
532
+ a : array_like of str or unicode
533
+
534
+ sub : str or unicode
535
+ The substring to search for.
536
+
537
+ start, end : int, optional
538
+ Optional arguments `start` and `end` are interpreted as slice
539
+ notation to specify the range in which to count.
540
+
541
+ Returns
542
+ -------
543
+ out : ndarray
544
+ Output array of ints.
545
+
546
+ See Also
547
+ --------
548
+ str.count
549
+
550
+ Examples
551
+ --------
552
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
553
+ >>> c
554
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
555
+ >>> np.char.count(c, 'A')
556
+ array([3, 1, 1])
557
+ >>> np.char.count(c, 'aA')
558
+ array([3, 1, 0])
559
+ >>> np.char.count(c, 'A', start=1, end=4)
560
+ array([2, 1, 1])
561
+ >>> np.char.count(c, 'A', start=1, end=3)
562
+ array([1, 0, 0])
563
+
564
+ """
565
+ return _vec_string(a, int_, 'count', [sub, start] + _clean_args(end))
566
+
567
+
568
+ def _code_dispatcher(a, encoding=None, errors=None):
569
+ return (a,)
570
+
571
+
572
+ @array_function_dispatch(_code_dispatcher)
573
+ def decode(a, encoding=None, errors=None):
574
+ r"""
575
+ Calls ``bytes.decode`` element-wise.
576
+
577
+ The set of available codecs comes from the Python standard library,
578
+ and may be extended at runtime. For more information, see the
579
+ :mod:`codecs` module.
580
+
581
+ Parameters
582
+ ----------
583
+ a : array_like of str or unicode
584
+
585
+ encoding : str, optional
586
+ The name of an encoding
587
+
588
+ errors : str, optional
589
+ Specifies how to handle encoding errors
590
+
591
+ Returns
592
+ -------
593
+ out : ndarray
594
+
595
+ See Also
596
+ --------
597
+ :py:meth:`bytes.decode`
598
+
599
+ Notes
600
+ -----
601
+ The type of the result will depend on the encoding specified.
602
+
603
+ Examples
604
+ --------
605
+ >>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
606
+ ... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
607
+ >>> c
608
+ array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
609
+ ... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
610
+ >>> np.char.decode(c, encoding='cp037')
611
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
612
+
613
+ """
614
+ return _to_bytes_or_str_array(
615
+ _vec_string(a, object_, 'decode', _clean_args(encoding, errors)))
616
+
617
+
618
+ @array_function_dispatch(_code_dispatcher)
619
+ def encode(a, encoding=None, errors=None):
620
+ """
621
+ Calls `str.encode` element-wise.
622
+
623
+ The set of available codecs comes from the Python standard library,
624
+ and may be extended at runtime. For more information, see the codecs
625
+ module.
626
+
627
+ Parameters
628
+ ----------
629
+ a : array_like of str or unicode
630
+
631
+ encoding : str, optional
632
+ The name of an encoding
633
+
634
+ errors : str, optional
635
+ Specifies how to handle encoding errors
636
+
637
+ Returns
638
+ -------
639
+ out : ndarray
640
+
641
+ See Also
642
+ --------
643
+ str.encode
644
+
645
+ Notes
646
+ -----
647
+ The type of the result will depend on the encoding specified.
648
+
649
+ """
650
+ return _to_bytes_or_str_array(
651
+ _vec_string(a, object_, 'encode', _clean_args(encoding, errors)))
652
+
653
+
654
+ def _endswith_dispatcher(a, suffix, start=None, end=None):
655
+ return (a,)
656
+
657
+
658
+ @array_function_dispatch(_endswith_dispatcher)
659
+ def endswith(a, suffix, start=0, end=None):
660
+ """
661
+ Returns a boolean array which is `True` where the string element
662
+ in `a` ends with `suffix`, otherwise `False`.
663
+
664
+ Calls `str.endswith` element-wise.
665
+
666
+ Parameters
667
+ ----------
668
+ a : array_like of str or unicode
669
+
670
+ suffix : str
671
+
672
+ start, end : int, optional
673
+ With optional `start`, test beginning at that position. With
674
+ optional `end`, stop comparing at that position.
675
+
676
+ Returns
677
+ -------
678
+ out : ndarray
679
+ Outputs an array of bools.
680
+
681
+ See Also
682
+ --------
683
+ str.endswith
684
+
685
+ Examples
686
+ --------
687
+ >>> s = np.array(['foo', 'bar'])
688
+ >>> s[0] = 'foo'
689
+ >>> s[1] = 'bar'
690
+ >>> s
691
+ array(['foo', 'bar'], dtype='<U3')
692
+ >>> np.char.endswith(s, 'ar')
693
+ array([False, True])
694
+ >>> np.char.endswith(s, 'a', start=1, end=2)
695
+ array([False, True])
696
+
697
+ """
698
+ return _vec_string(
699
+ a, bool_, 'endswith', [suffix, start] + _clean_args(end))
700
+
701
+
702
+ def _expandtabs_dispatcher(a, tabsize=None):
703
+ return (a,)
704
+
705
+
706
+ @array_function_dispatch(_expandtabs_dispatcher)
707
+ def expandtabs(a, tabsize=8):
708
+ """
709
+ Return a copy of each string element where all tab characters are
710
+ replaced by one or more spaces.
711
+
712
+ Calls `str.expandtabs` element-wise.
713
+
714
+ Return a copy of each string element where all tab characters are
715
+ replaced by one or more spaces, depending on the current column
716
+ and the given `tabsize`. The column number is reset to zero after
717
+ each newline occurring in the string. This doesn't understand other
718
+ non-printing characters or escape sequences.
719
+
720
+ Parameters
721
+ ----------
722
+ a : array_like of str or unicode
723
+ Input array
724
+ tabsize : int, optional
725
+ Replace tabs with `tabsize` number of spaces. If not given defaults
726
+ to 8 spaces.
727
+
728
+ Returns
729
+ -------
730
+ out : ndarray
731
+ Output array of str or unicode, depending on input type
732
+
733
+ See Also
734
+ --------
735
+ str.expandtabs
736
+
737
+ """
738
+ return _to_bytes_or_str_array(
739
+ _vec_string(a, object_, 'expandtabs', (tabsize,)), a)
740
+
741
+
742
+ @array_function_dispatch(_count_dispatcher)
743
+ def find(a, sub, start=0, end=None):
744
+ """
745
+ For each element, return the lowest index in the string where
746
+ substring `sub` is found.
747
+
748
+ Calls `str.find` element-wise.
749
+
750
+ For each element, return the lowest index in the string where
751
+ substring `sub` is found, such that `sub` is contained in the
752
+ range [`start`, `end`].
753
+
754
+ Parameters
755
+ ----------
756
+ a : array_like of str or unicode
757
+
758
+ sub : str or unicode
759
+
760
+ start, end : int, optional
761
+ Optional arguments `start` and `end` are interpreted as in
762
+ slice notation.
763
+
764
+ Returns
765
+ -------
766
+ out : ndarray or int
767
+ Output array of ints. Returns -1 if `sub` is not found.
768
+
769
+ See Also
770
+ --------
771
+ str.find
772
+
773
+ Examples
774
+ --------
775
+ >>> a = np.array(["NumPy is a Python library"])
776
+ >>> np.char.find(a, "Python", start=0, end=None)
777
+ array([11])
778
+
779
+ """
780
+ return _vec_string(
781
+ a, int_, 'find', [sub, start] + _clean_args(end))
782
+
783
+
784
+ @array_function_dispatch(_count_dispatcher)
785
+ def index(a, sub, start=0, end=None):
786
+ """
787
+ Like `find`, but raises `ValueError` when the substring is not found.
788
+
789
+ Calls `str.index` element-wise.
790
+
791
+ Parameters
792
+ ----------
793
+ a : array_like of str or unicode
794
+
795
+ sub : str or unicode
796
+
797
+ start, end : int, optional
798
+
799
+ Returns
800
+ -------
801
+ out : ndarray
802
+ Output array of ints. Returns -1 if `sub` is not found.
803
+
804
+ See Also
805
+ --------
806
+ find, str.find
807
+
808
+ Examples
809
+ --------
810
+ >>> a = np.array(["Computer Science"])
811
+ >>> np.char.index(a, "Science", start=0, end=None)
812
+ array([9])
813
+
814
+ """
815
+ return _vec_string(
816
+ a, int_, 'index', [sub, start] + _clean_args(end))
817
+
818
+
819
+ @array_function_dispatch(_unary_op_dispatcher)
820
+ def isalnum(a):
821
+ """
822
+ Returns true for each element if all characters in the string are
823
+ alphanumeric and there is at least one character, false otherwise.
824
+
825
+ Calls `str.isalnum` element-wise.
826
+
827
+ For 8-bit strings, this method is locale-dependent.
828
+
829
+ Parameters
830
+ ----------
831
+ a : array_like of str or unicode
832
+
833
+ Returns
834
+ -------
835
+ out : ndarray
836
+ Output array of str or unicode, depending on input type
837
+
838
+ See Also
839
+ --------
840
+ str.isalnum
841
+ """
842
+ return _vec_string(a, bool_, 'isalnum')
843
+
844
+
845
+ @array_function_dispatch(_unary_op_dispatcher)
846
+ def isalpha(a):
847
+ """
848
+ Returns true for each element if all characters in the string are
849
+ alphabetic and there is at least one character, false otherwise.
850
+
851
+ Calls `str.isalpha` element-wise.
852
+
853
+ For 8-bit strings, this method is locale-dependent.
854
+
855
+ Parameters
856
+ ----------
857
+ a : array_like of str or unicode
858
+
859
+ Returns
860
+ -------
861
+ out : ndarray
862
+ Output array of bools
863
+
864
+ See Also
865
+ --------
866
+ str.isalpha
867
+ """
868
+ return _vec_string(a, bool_, 'isalpha')
869
+
870
+
871
+ @array_function_dispatch(_unary_op_dispatcher)
872
+ def isdigit(a):
873
+ """
874
+ Returns true for each element if all characters in the string are
875
+ digits and there is at least one character, false otherwise.
876
+
877
+ Calls `str.isdigit` element-wise.
878
+
879
+ For 8-bit strings, this method is locale-dependent.
880
+
881
+ Parameters
882
+ ----------
883
+ a : array_like of str or unicode
884
+
885
+ Returns
886
+ -------
887
+ out : ndarray
888
+ Output array of bools
889
+
890
+ See Also
891
+ --------
892
+ str.isdigit
893
+
894
+ Examples
895
+ --------
896
+ >>> a = np.array(['a', 'b', '0'])
897
+ >>> np.char.isdigit(a)
898
+ array([False, False, True])
899
+ >>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
900
+ >>> np.char.isdigit(a)
901
+ array([[False, False, True], [False, True, True]])
902
+ """
903
+ return _vec_string(a, bool_, 'isdigit')
904
+
905
+
906
+ @array_function_dispatch(_unary_op_dispatcher)
907
+ def islower(a):
908
+ """
909
+ Returns true for each element if all cased characters in the
910
+ string are lowercase and there is at least one cased character,
911
+ false otherwise.
912
+
913
+ Calls `str.islower` element-wise.
914
+
915
+ For 8-bit strings, this method is locale-dependent.
916
+
917
+ Parameters
918
+ ----------
919
+ a : array_like of str or unicode
920
+
921
+ Returns
922
+ -------
923
+ out : ndarray
924
+ Output array of bools
925
+
926
+ See Also
927
+ --------
928
+ str.islower
929
+ """
930
+ return _vec_string(a, bool_, 'islower')
931
+
932
+
933
+ @array_function_dispatch(_unary_op_dispatcher)
934
+ def isspace(a):
935
+ """
936
+ Returns true for each element if there are only whitespace
937
+ characters in the string and there is at least one character,
938
+ false otherwise.
939
+
940
+ Calls `str.isspace` element-wise.
941
+
942
+ For 8-bit strings, this method is locale-dependent.
943
+
944
+ Parameters
945
+ ----------
946
+ a : array_like of str or unicode
947
+
948
+ Returns
949
+ -------
950
+ out : ndarray
951
+ Output array of bools
952
+
953
+ See Also
954
+ --------
955
+ str.isspace
956
+ """
957
+ return _vec_string(a, bool_, 'isspace')
958
+
959
+
960
+ @array_function_dispatch(_unary_op_dispatcher)
961
+ def istitle(a):
962
+ """
963
+ Returns true for each element if the element is a titlecased
964
+ string and there is at least one character, false otherwise.
965
+
966
+ Call `str.istitle` element-wise.
967
+
968
+ For 8-bit strings, this method is locale-dependent.
969
+
970
+ Parameters
971
+ ----------
972
+ a : array_like of str or unicode
973
+
974
+ Returns
975
+ -------
976
+ out : ndarray
977
+ Output array of bools
978
+
979
+ See Also
980
+ --------
981
+ str.istitle
982
+ """
983
+ return _vec_string(a, bool_, 'istitle')
984
+
985
+
986
+ @array_function_dispatch(_unary_op_dispatcher)
987
+ def isupper(a):
988
+ """
989
+ Return true for each element if all cased characters in the
990
+ string are uppercase and there is at least one character, false
991
+ otherwise.
992
+
993
+ Call `str.isupper` element-wise.
994
+
995
+ For 8-bit strings, this method is locale-dependent.
996
+
997
+ Parameters
998
+ ----------
999
+ a : array_like of str or unicode
1000
+
1001
+ Returns
1002
+ -------
1003
+ out : ndarray
1004
+ Output array of bools
1005
+
1006
+ See Also
1007
+ --------
1008
+ str.isupper
1009
+
1010
+ Examples
1011
+ --------
1012
+ >>> str = "GHC"
1013
+ >>> np.char.isupper(str)
1014
+ array(True)
1015
+ >>> a = np.array(["hello", "HELLO", "Hello"])
1016
+ >>> np.char.isupper(a)
1017
+ array([False, True, False])
1018
+
1019
+ """
1020
+ return _vec_string(a, bool_, 'isupper')
1021
+
1022
+
1023
+ def _join_dispatcher(sep, seq):
1024
+ return (sep, seq)
1025
+
1026
+
1027
+ @array_function_dispatch(_join_dispatcher)
1028
+ def join(sep, seq):
1029
+ """
1030
+ Return a string which is the concatenation of the strings in the
1031
+ sequence `seq`.
1032
+
1033
+ Calls `str.join` element-wise.
1034
+
1035
+ Parameters
1036
+ ----------
1037
+ sep : array_like of str or unicode
1038
+ seq : array_like of str or unicode
1039
+
1040
+ Returns
1041
+ -------
1042
+ out : ndarray
1043
+ Output array of str or unicode, depending on input types
1044
+
1045
+ See Also
1046
+ --------
1047
+ str.join
1048
+
1049
+ Examples
1050
+ --------
1051
+ >>> np.char.join('-', 'osd')
1052
+ array('o-s-d', dtype='<U5')
1053
+
1054
+ >>> np.char.join(['-', '.'], ['ghc', 'osd'])
1055
+ array(['g-h-c', 'o.s.d'], dtype='<U5')
1056
+
1057
+ """
1058
+ return _to_bytes_or_str_array(
1059
+ _vec_string(sep, object_, 'join', (seq,)), seq)
1060
+
1061
+
1062
+
1063
+ def _just_dispatcher(a, width, fillchar=None):
1064
+ return (a,)
1065
+
1066
+
1067
+ @array_function_dispatch(_just_dispatcher)
1068
+ def ljust(a, width, fillchar=' '):
1069
+ """
1070
+ Return an array with the elements of `a` left-justified in a
1071
+ string of length `width`.
1072
+
1073
+ Calls `str.ljust` element-wise.
1074
+
1075
+ Parameters
1076
+ ----------
1077
+ a : array_like of str or unicode
1078
+
1079
+ width : int
1080
+ The length of the resulting strings
1081
+ fillchar : str or unicode, optional
1082
+ The character to use for padding
1083
+
1084
+ Returns
1085
+ -------
1086
+ out : ndarray
1087
+ Output array of str or unicode, depending on input type
1088
+
1089
+ See Also
1090
+ --------
1091
+ str.ljust
1092
+
1093
+ """
1094
+ a_arr = numpy.asarray(a)
1095
+ width_arr = numpy.asarray(width)
1096
+ size = int(numpy.max(width_arr.flat))
1097
+ if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
1098
+ fillchar = asbytes(fillchar)
1099
+ return _vec_string(
1100
+ a_arr, type(a_arr.dtype)(size), 'ljust', (width_arr, fillchar))
1101
+
1102
+
1103
+ @array_function_dispatch(_unary_op_dispatcher)
1104
+ def lower(a):
1105
+ """
1106
+ Return an array with the elements converted to lowercase.
1107
+
1108
+ Call `str.lower` element-wise.
1109
+
1110
+ For 8-bit strings, this method is locale-dependent.
1111
+
1112
+ Parameters
1113
+ ----------
1114
+ a : array_like, {str, unicode}
1115
+ Input array.
1116
+
1117
+ Returns
1118
+ -------
1119
+ out : ndarray, {str, unicode}
1120
+ Output array of str or unicode, depending on input type
1121
+
1122
+ See Also
1123
+ --------
1124
+ str.lower
1125
+
1126
+ Examples
1127
+ --------
1128
+ >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
1129
+ array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
1130
+ >>> np.char.lower(c)
1131
+ array(['a1b c', '1bca', 'bca1'], dtype='<U5')
1132
+
1133
+ """
1134
+ a_arr = numpy.asarray(a)
1135
+ return _vec_string(a_arr, a_arr.dtype, 'lower')
1136
+
1137
+
1138
+ def _strip_dispatcher(a, chars=None):
1139
+ return (a,)
1140
+
1141
+
1142
+ @array_function_dispatch(_strip_dispatcher)
1143
+ def lstrip(a, chars=None):
1144
+ """
1145
+ For each element in `a`, return a copy with the leading characters
1146
+ removed.
1147
+
1148
+ Calls `str.lstrip` element-wise.
1149
+
1150
+ Parameters
1151
+ ----------
1152
+ a : array-like, {str, unicode}
1153
+ Input array.
1154
+
1155
+ chars : {str, unicode}, optional
1156
+ The `chars` argument is a string specifying the set of
1157
+ characters to be removed. If omitted or None, the `chars`
1158
+ argument defaults to removing whitespace. The `chars` argument
1159
+ is not a prefix; rather, all combinations of its values are
1160
+ stripped.
1161
+
1162
+ Returns
1163
+ -------
1164
+ out : ndarray, {str, unicode}
1165
+ Output array of str or unicode, depending on input type
1166
+
1167
+ See Also
1168
+ --------
1169
+ str.lstrip
1170
+
1171
+ Examples
1172
+ --------
1173
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
1174
+ >>> c
1175
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
1176
+
1177
+ The 'a' variable is unstripped from c[1] because whitespace leading.
1178
+
1179
+ >>> np.char.lstrip(c, 'a')
1180
+ array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
1181
+
1182
+
1183
+ >>> np.char.lstrip(c, 'A') # leaves c unchanged
1184
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
1185
+ >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
1186
+ ... # XXX: is this a regression? This used to return True
1187
+ ... # np.char.lstrip(c,'') does not modify c at all.
1188
+ False
1189
+ >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
1190
+ True
1191
+
1192
+ """
1193
+ a_arr = numpy.asarray(a)
1194
+ return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
1195
+
1196
+
1197
+ def _partition_dispatcher(a, sep):
1198
+ return (a,)
1199
+
1200
+
1201
+ @array_function_dispatch(_partition_dispatcher)
1202
+ def partition(a, sep):
1203
+ """
1204
+ Partition each element in `a` around `sep`.
1205
+
1206
+ Calls `str.partition` element-wise.
1207
+
1208
+ For each element in `a`, split the element as the first
1209
+ occurrence of `sep`, and return 3 strings containing the part
1210
+ before the separator, the separator itself, and the part after
1211
+ the separator. If the separator is not found, return 3 strings
1212
+ containing the string itself, followed by two empty strings.
1213
+
1214
+ Parameters
1215
+ ----------
1216
+ a : array_like, {str, unicode}
1217
+ Input array
1218
+ sep : {str, unicode}
1219
+ Separator to split each string element in `a`.
1220
+
1221
+ Returns
1222
+ -------
1223
+ out : ndarray, {str, unicode}
1224
+ Output array of str or unicode, depending on input type.
1225
+ The output array will have an extra dimension with 3
1226
+ elements per input element.
1227
+
1228
+ See Also
1229
+ --------
1230
+ str.partition
1231
+
1232
+ """
1233
+ return _to_bytes_or_str_array(
1234
+ _vec_string(a, object_, 'partition', (sep,)), a)
1235
+
1236
+
1237
+ def _replace_dispatcher(a, old, new, count=None):
1238
+ return (a,)
1239
+
1240
+
1241
+ @array_function_dispatch(_replace_dispatcher)
1242
+ def replace(a, old, new, count=None):
1243
+ """
1244
+ For each element in `a`, return a copy of the string with all
1245
+ occurrences of substring `old` replaced by `new`.
1246
+
1247
+ Calls `str.replace` element-wise.
1248
+
1249
+ Parameters
1250
+ ----------
1251
+ a : array-like of str or unicode
1252
+
1253
+ old, new : str or unicode
1254
+
1255
+ count : int, optional
1256
+ If the optional argument `count` is given, only the first
1257
+ `count` occurrences are replaced.
1258
+
1259
+ Returns
1260
+ -------
1261
+ out : ndarray
1262
+ Output array of str or unicode, depending on input type
1263
+
1264
+ See Also
1265
+ --------
1266
+ str.replace
1267
+
1268
+ Examples
1269
+ --------
1270
+ >>> a = np.array(["That is a mango", "Monkeys eat mangos"])
1271
+ >>> np.char.replace(a, 'mango', 'banana')
1272
+ array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19')
1273
+
1274
+ >>> a = np.array(["The dish is fresh", "This is it"])
1275
+ >>> np.char.replace(a, 'is', 'was')
1276
+ array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
1277
+ """
1278
+ return _to_bytes_or_str_array(
1279
+ _vec_string(a, object_, 'replace', [old, new] + _clean_args(count)), a)
1280
+
1281
+
1282
+ @array_function_dispatch(_count_dispatcher)
1283
+ def rfind(a, sub, start=0, end=None):
1284
+ """
1285
+ For each element in `a`, return the highest index in the string
1286
+ where substring `sub` is found, such that `sub` is contained
1287
+ within [`start`, `end`].
1288
+
1289
+ Calls `str.rfind` element-wise.
1290
+
1291
+ Parameters
1292
+ ----------
1293
+ a : array-like of str or unicode
1294
+
1295
+ sub : str or unicode
1296
+
1297
+ start, end : int, optional
1298
+ Optional arguments `start` and `end` are interpreted as in
1299
+ slice notation.
1300
+
1301
+ Returns
1302
+ -------
1303
+ out : ndarray
1304
+ Output array of ints. Return -1 on failure.
1305
+
1306
+ See Also
1307
+ --------
1308
+ str.rfind
1309
+
1310
+ """
1311
+ return _vec_string(
1312
+ a, int_, 'rfind', [sub, start] + _clean_args(end))
1313
+
1314
+
1315
+ @array_function_dispatch(_count_dispatcher)
1316
+ def rindex(a, sub, start=0, end=None):
1317
+ """
1318
+ Like `rfind`, but raises `ValueError` when the substring `sub` is
1319
+ not found.
1320
+
1321
+ Calls `str.rindex` element-wise.
1322
+
1323
+ Parameters
1324
+ ----------
1325
+ a : array-like of str or unicode
1326
+
1327
+ sub : str or unicode
1328
+
1329
+ start, end : int, optional
1330
+
1331
+ Returns
1332
+ -------
1333
+ out : ndarray
1334
+ Output array of ints.
1335
+
1336
+ See Also
1337
+ --------
1338
+ rfind, str.rindex
1339
+
1340
+ """
1341
+ return _vec_string(
1342
+ a, int_, 'rindex', [sub, start] + _clean_args(end))
1343
+
1344
+
1345
+ @array_function_dispatch(_just_dispatcher)
1346
+ def rjust(a, width, fillchar=' '):
1347
+ """
1348
+ Return an array with the elements of `a` right-justified in a
1349
+ string of length `width`.
1350
+
1351
+ Calls `str.rjust` element-wise.
1352
+
1353
+ Parameters
1354
+ ----------
1355
+ a : array_like of str or unicode
1356
+
1357
+ width : int
1358
+ The length of the resulting strings
1359
+ fillchar : str or unicode, optional
1360
+ The character to use for padding
1361
+
1362
+ Returns
1363
+ -------
1364
+ out : ndarray
1365
+ Output array of str or unicode, depending on input type
1366
+
1367
+ See Also
1368
+ --------
1369
+ str.rjust
1370
+
1371
+ """
1372
+ a_arr = numpy.asarray(a)
1373
+ width_arr = numpy.asarray(width)
1374
+ size = int(numpy.max(width_arr.flat))
1375
+ if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
1376
+ fillchar = asbytes(fillchar)
1377
+ return _vec_string(
1378
+ a_arr, type(a_arr.dtype)(size), 'rjust', (width_arr, fillchar))
1379
+
1380
+
1381
+ @array_function_dispatch(_partition_dispatcher)
1382
+ def rpartition(a, sep):
1383
+ """
1384
+ Partition (split) each element around the right-most separator.
1385
+
1386
+ Calls `str.rpartition` element-wise.
1387
+
1388
+ For each element in `a`, split the element as the last
1389
+ occurrence of `sep`, and return 3 strings containing the part
1390
+ before the separator, the separator itself, and the part after
1391
+ the separator. If the separator is not found, return 3 strings
1392
+ containing the string itself, followed by two empty strings.
1393
+
1394
+ Parameters
1395
+ ----------
1396
+ a : array_like of str or unicode
1397
+ Input array
1398
+ sep : str or unicode
1399
+ Right-most separator to split each element in array.
1400
+
1401
+ Returns
1402
+ -------
1403
+ out : ndarray
1404
+ Output array of string or unicode, depending on input
1405
+ type. The output array will have an extra dimension with
1406
+ 3 elements per input element.
1407
+
1408
+ See Also
1409
+ --------
1410
+ str.rpartition
1411
+
1412
+ """
1413
+ return _to_bytes_or_str_array(
1414
+ _vec_string(a, object_, 'rpartition', (sep,)), a)
1415
+
1416
+
1417
+ def _split_dispatcher(a, sep=None, maxsplit=None):
1418
+ return (a,)
1419
+
1420
+
1421
+ @array_function_dispatch(_split_dispatcher)
1422
+ def rsplit(a, sep=None, maxsplit=None):
1423
+ """
1424
+ For each element in `a`, return a list of the words in the
1425
+ string, using `sep` as the delimiter string.
1426
+
1427
+ Calls `str.rsplit` element-wise.
1428
+
1429
+ Except for splitting from the right, `rsplit`
1430
+ behaves like `split`.
1431
+
1432
+ Parameters
1433
+ ----------
1434
+ a : array_like of str or unicode
1435
+
1436
+ sep : str or unicode, optional
1437
+ If `sep` is not specified or None, any whitespace string
1438
+ is a separator.
1439
+ maxsplit : int, optional
1440
+ If `maxsplit` is given, at most `maxsplit` splits are done,
1441
+ the rightmost ones.
1442
+
1443
+ Returns
1444
+ -------
1445
+ out : ndarray
1446
+ Array of list objects
1447
+
1448
+ See Also
1449
+ --------
1450
+ str.rsplit, split
1451
+
1452
+ """
1453
+ # This will return an array of lists of different sizes, so we
1454
+ # leave it as an object array
1455
+ return _vec_string(
1456
+ a, object_, 'rsplit', [sep] + _clean_args(maxsplit))
1457
+
1458
+
1459
+ def _strip_dispatcher(a, chars=None):
1460
+ return (a,)
1461
+
1462
+
1463
+ @array_function_dispatch(_strip_dispatcher)
1464
+ def rstrip(a, chars=None):
1465
+ """
1466
+ For each element in `a`, return a copy with the trailing
1467
+ characters removed.
1468
+
1469
+ Calls `str.rstrip` element-wise.
1470
+
1471
+ Parameters
1472
+ ----------
1473
+ a : array-like of str or unicode
1474
+
1475
+ chars : str or unicode, optional
1476
+ The `chars` argument is a string specifying the set of
1477
+ characters to be removed. If omitted or None, the `chars`
1478
+ argument defaults to removing whitespace. The `chars` argument
1479
+ is not a suffix; rather, all combinations of its values are
1480
+ stripped.
1481
+
1482
+ Returns
1483
+ -------
1484
+ out : ndarray
1485
+ Output array of str or unicode, depending on input type
1486
+
1487
+ See Also
1488
+ --------
1489
+ str.rstrip
1490
+
1491
+ Examples
1492
+ --------
1493
+ >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
1494
+ array(['aAaAaA', 'abBABba'],
1495
+ dtype='|S7')
1496
+ >>> np.char.rstrip(c, b'a')
1497
+ array(['aAaAaA', 'abBABb'],
1498
+ dtype='|S7')
1499
+ >>> np.char.rstrip(c, b'A')
1500
+ array(['aAaAa', 'abBABba'],
1501
+ dtype='|S7')
1502
+
1503
+ """
1504
+ a_arr = numpy.asarray(a)
1505
+ return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,))
1506
+
1507
+
1508
+ @array_function_dispatch(_split_dispatcher)
1509
+ def split(a, sep=None, maxsplit=None):
1510
+ """
1511
+ For each element in `a`, return a list of the words in the
1512
+ string, using `sep` as the delimiter string.
1513
+
1514
+ Calls `str.split` element-wise.
1515
+
1516
+ Parameters
1517
+ ----------
1518
+ a : array_like of str or unicode
1519
+
1520
+ sep : str or unicode, optional
1521
+ If `sep` is not specified or None, any whitespace string is a
1522
+ separator.
1523
+
1524
+ maxsplit : int, optional
1525
+ If `maxsplit` is given, at most `maxsplit` splits are done.
1526
+
1527
+ Returns
1528
+ -------
1529
+ out : ndarray
1530
+ Array of list objects
1531
+
1532
+ See Also
1533
+ --------
1534
+ str.split, rsplit
1535
+
1536
+ """
1537
+ # This will return an array of lists of different sizes, so we
1538
+ # leave it as an object array
1539
+ return _vec_string(
1540
+ a, object_, 'split', [sep] + _clean_args(maxsplit))
1541
+
1542
+
1543
+ def _splitlines_dispatcher(a, keepends=None):
1544
+ return (a,)
1545
+
1546
+
1547
+ @array_function_dispatch(_splitlines_dispatcher)
1548
+ def splitlines(a, keepends=None):
1549
+ """
1550
+ For each element in `a`, return a list of the lines in the
1551
+ element, breaking at line boundaries.
1552
+
1553
+ Calls `str.splitlines` element-wise.
1554
+
1555
+ Parameters
1556
+ ----------
1557
+ a : array_like of str or unicode
1558
+
1559
+ keepends : bool, optional
1560
+ Line breaks are not included in the resulting list unless
1561
+ keepends is given and true.
1562
+
1563
+ Returns
1564
+ -------
1565
+ out : ndarray
1566
+ Array of list objects
1567
+
1568
+ See Also
1569
+ --------
1570
+ str.splitlines
1571
+
1572
+ """
1573
+ return _vec_string(
1574
+ a, object_, 'splitlines', _clean_args(keepends))
1575
+
1576
+
1577
+ def _startswith_dispatcher(a, prefix, start=None, end=None):
1578
+ return (a,)
1579
+
1580
+
1581
+ @array_function_dispatch(_startswith_dispatcher)
1582
+ def startswith(a, prefix, start=0, end=None):
1583
+ """
1584
+ Returns a boolean array which is `True` where the string element
1585
+ in `a` starts with `prefix`, otherwise `False`.
1586
+
1587
+ Calls `str.startswith` element-wise.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ a : array_like of str or unicode
1592
+
1593
+ prefix : str
1594
+
1595
+ start, end : int, optional
1596
+ With optional `start`, test beginning at that position. With
1597
+ optional `end`, stop comparing at that position.
1598
+
1599
+ Returns
1600
+ -------
1601
+ out : ndarray
1602
+ Array of booleans
1603
+
1604
+ See Also
1605
+ --------
1606
+ str.startswith
1607
+
1608
+ """
1609
+ return _vec_string(
1610
+ a, bool_, 'startswith', [prefix, start] + _clean_args(end))
1611
+
1612
+
1613
+ @array_function_dispatch(_strip_dispatcher)
1614
+ def strip(a, chars=None):
1615
+ """
1616
+ For each element in `a`, return a copy with the leading and
1617
+ trailing characters removed.
1618
+
1619
+ Calls `str.strip` element-wise.
1620
+
1621
+ Parameters
1622
+ ----------
1623
+ a : array-like of str or unicode
1624
+
1625
+ chars : str or unicode, optional
1626
+ The `chars` argument is a string specifying the set of
1627
+ characters to be removed. If omitted or None, the `chars`
1628
+ argument defaults to removing whitespace. The `chars` argument
1629
+ is not a prefix or suffix; rather, all combinations of its
1630
+ values are stripped.
1631
+
1632
+ Returns
1633
+ -------
1634
+ out : ndarray
1635
+ Output array of str or unicode, depending on input type
1636
+
1637
+ See Also
1638
+ --------
1639
+ str.strip
1640
+
1641
+ Examples
1642
+ --------
1643
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
1644
+ >>> c
1645
+ array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
1646
+ >>> np.char.strip(c)
1647
+ array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
1648
+ >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
1649
+ array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
1650
+ >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
1651
+ array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
1652
+
1653
+ """
1654
+ a_arr = numpy.asarray(a)
1655
+ return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
1656
+
1657
+
1658
+ @array_function_dispatch(_unary_op_dispatcher)
1659
+ def swapcase(a):
1660
+ """
1661
+ Return element-wise a copy of the string with
1662
+ uppercase characters converted to lowercase and vice versa.
1663
+
1664
+ Calls `str.swapcase` element-wise.
1665
+
1666
+ For 8-bit strings, this method is locale-dependent.
1667
+
1668
+ Parameters
1669
+ ----------
1670
+ a : array_like, {str, unicode}
1671
+ Input array.
1672
+
1673
+ Returns
1674
+ -------
1675
+ out : ndarray, {str, unicode}
1676
+ Output array of str or unicode, depending on input type
1677
+
1678
+ See Also
1679
+ --------
1680
+ str.swapcase
1681
+
1682
+ Examples
1683
+ --------
1684
+ >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
1685
+ array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
1686
+ dtype='|S5')
1687
+ >>> np.char.swapcase(c)
1688
+ array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
1689
+ dtype='|S5')
1690
+
1691
+ """
1692
+ a_arr = numpy.asarray(a)
1693
+ return _vec_string(a_arr, a_arr.dtype, 'swapcase')
1694
+
1695
+
1696
+ @array_function_dispatch(_unary_op_dispatcher)
1697
+ def title(a):
1698
+ """
1699
+ Return element-wise title cased version of string or unicode.
1700
+
1701
+ Title case words start with uppercase characters, all remaining cased
1702
+ characters are lowercase.
1703
+
1704
+ Calls `str.title` element-wise.
1705
+
1706
+ For 8-bit strings, this method is locale-dependent.
1707
+
1708
+ Parameters
1709
+ ----------
1710
+ a : array_like, {str, unicode}
1711
+ Input array.
1712
+
1713
+ Returns
1714
+ -------
1715
+ out : ndarray
1716
+ Output array of str or unicode, depending on input type
1717
+
1718
+ See Also
1719
+ --------
1720
+ str.title
1721
+
1722
+ Examples
1723
+ --------
1724
+ >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
1725
+ array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
1726
+ dtype='|S5')
1727
+ >>> np.char.title(c)
1728
+ array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
1729
+ dtype='|S5')
1730
+
1731
+ """
1732
+ a_arr = numpy.asarray(a)
1733
+ return _vec_string(a_arr, a_arr.dtype, 'title')
1734
+
1735
+
1736
+ def _translate_dispatcher(a, table, deletechars=None):
1737
+ return (a,)
1738
+
1739
+
1740
+ @array_function_dispatch(_translate_dispatcher)
1741
+ def translate(a, table, deletechars=None):
1742
+ """
1743
+ For each element in `a`, return a copy of the string where all
1744
+ characters occurring in the optional argument `deletechars` are
1745
+ removed, and the remaining characters have been mapped through the
1746
+ given translation table.
1747
+
1748
+ Calls `str.translate` element-wise.
1749
+
1750
+ Parameters
1751
+ ----------
1752
+ a : array-like of str or unicode
1753
+
1754
+ table : str of length 256
1755
+
1756
+ deletechars : str
1757
+
1758
+ Returns
1759
+ -------
1760
+ out : ndarray
1761
+ Output array of str or unicode, depending on input type
1762
+
1763
+ See Also
1764
+ --------
1765
+ str.translate
1766
+
1767
+ """
1768
+ a_arr = numpy.asarray(a)
1769
+ if issubclass(a_arr.dtype.type, str_):
1770
+ return _vec_string(
1771
+ a_arr, a_arr.dtype, 'translate', (table,))
1772
+ else:
1773
+ return _vec_string(
1774
+ a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars))
1775
+
1776
+
1777
+ @array_function_dispatch(_unary_op_dispatcher)
1778
+ def upper(a):
1779
+ """
1780
+ Return an array with the elements converted to uppercase.
1781
+
1782
+ Calls `str.upper` element-wise.
1783
+
1784
+ For 8-bit strings, this method is locale-dependent.
1785
+
1786
+ Parameters
1787
+ ----------
1788
+ a : array_like, {str, unicode}
1789
+ Input array.
1790
+
1791
+ Returns
1792
+ -------
1793
+ out : ndarray, {str, unicode}
1794
+ Output array of str or unicode, depending on input type
1795
+
1796
+ See Also
1797
+ --------
1798
+ str.upper
1799
+
1800
+ Examples
1801
+ --------
1802
+ >>> c = np.array(['a1b c', '1bca', 'bca1']); c
1803
+ array(['a1b c', '1bca', 'bca1'], dtype='<U5')
1804
+ >>> np.char.upper(c)
1805
+ array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
1806
+
1807
+ """
1808
+ a_arr = numpy.asarray(a)
1809
+ return _vec_string(a_arr, a_arr.dtype, 'upper')
1810
+
1811
+
1812
+ def _zfill_dispatcher(a, width):
1813
+ return (a,)
1814
+
1815
+
1816
+ @array_function_dispatch(_zfill_dispatcher)
1817
+ def zfill(a, width):
1818
+ """
1819
+ Return the numeric string left-filled with zeros
1820
+
1821
+ Calls `str.zfill` element-wise.
1822
+
1823
+ Parameters
1824
+ ----------
1825
+ a : array_like, {str, unicode}
1826
+ Input array.
1827
+ width : int
1828
+ Width of string to left-fill elements in `a`.
1829
+
1830
+ Returns
1831
+ -------
1832
+ out : ndarray, {str, unicode}
1833
+ Output array of str or unicode, depending on input type
1834
+
1835
+ See Also
1836
+ --------
1837
+ str.zfill
1838
+
1839
+ """
1840
+ a_arr = numpy.asarray(a)
1841
+ width_arr = numpy.asarray(width)
1842
+ size = int(numpy.max(width_arr.flat))
1843
+ return _vec_string(
1844
+ a_arr, type(a_arr.dtype)(size), 'zfill', (width_arr,))
1845
+
1846
+
1847
+ @array_function_dispatch(_unary_op_dispatcher)
1848
+ def isnumeric(a):
1849
+ """
1850
+ For each element, return True if there are only numeric
1851
+ characters in the element.
1852
+
1853
+ Calls `str.isnumeric` element-wise.
1854
+
1855
+ Numeric characters include digit characters, and all characters
1856
+ that have the Unicode numeric value property, e.g. ``U+2155,
1857
+ VULGAR FRACTION ONE FIFTH``.
1858
+
1859
+ Parameters
1860
+ ----------
1861
+ a : array_like, unicode
1862
+ Input array.
1863
+
1864
+ Returns
1865
+ -------
1866
+ out : ndarray, bool
1867
+ Array of booleans of same shape as `a`.
1868
+
1869
+ See Also
1870
+ --------
1871
+ str.isnumeric
1872
+
1873
+ Examples
1874
+ --------
1875
+ >>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])
1876
+ array([ True, False, False, False, False])
1877
+
1878
+ """
1879
+ if not _is_unicode(a):
1880
+ raise TypeError("isnumeric is only available for Unicode strings and arrays")
1881
+ return _vec_string(a, bool_, 'isnumeric')
1882
+
1883
+
1884
+ @array_function_dispatch(_unary_op_dispatcher)
1885
+ def isdecimal(a):
1886
+ """
1887
+ For each element, return True if there are only decimal
1888
+ characters in the element.
1889
+
1890
+ Calls `str.isdecimal` element-wise.
1891
+
1892
+ Decimal characters include digit characters, and all characters
1893
+ that can be used to form decimal-radix numbers,
1894
+ e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
1895
+
1896
+ Parameters
1897
+ ----------
1898
+ a : array_like, unicode
1899
+ Input array.
1900
+
1901
+ Returns
1902
+ -------
1903
+ out : ndarray, bool
1904
+ Array of booleans identical in shape to `a`.
1905
+
1906
+ See Also
1907
+ --------
1908
+ str.isdecimal
1909
+
1910
+ Examples
1911
+ --------
1912
+ >>> np.char.isdecimal(['12345', '4.99', '123ABC', ''])
1913
+ array([ True, False, False, False])
1914
+
1915
+ """
1916
+ if not _is_unicode(a):
1917
+ raise TypeError(
1918
+ "isdecimal is only available for Unicode strings and arrays")
1919
+ return _vec_string(a, bool_, 'isdecimal')
1920
+
1921
+
1922
+ @set_module('numpy')
1923
+ class chararray(ndarray):
1924
+ """
1925
+ chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
1926
+ strides=None, order=None)
1927
+
1928
+ Provides a convenient view on arrays of string and unicode values.
1929
+
1930
+ .. note::
1931
+ The `chararray` class exists for backwards compatibility with
1932
+ Numarray, it is not recommended for new development. Starting from numpy
1933
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
1934
+ `dtype` `object_`, `bytes_` or `str_`, and use the free functions
1935
+ in the `numpy.char` module for fast vectorized string operations.
1936
+
1937
+ Versus a regular NumPy array of type `str` or `unicode`, this
1938
+ class adds the following functionality:
1939
+
1940
+ 1) values automatically have whitespace removed from the end
1941
+ when indexed
1942
+
1943
+ 2) comparison operators automatically remove whitespace from the
1944
+ end when comparing values
1945
+
1946
+ 3) vectorized string operations are provided as methods
1947
+ (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
1948
+
1949
+ chararrays should be created using `numpy.char.array` or
1950
+ `numpy.char.asarray`, rather than this constructor directly.
1951
+
1952
+ This constructor creates the array, using `buffer` (with `offset`
1953
+ and `strides`) if it is not ``None``. If `buffer` is ``None``, then
1954
+ constructs a new array with `strides` in "C order", unless both
1955
+ ``len(shape) >= 2`` and ``order='F'``, in which case `strides`
1956
+ is in "Fortran order".
1957
+
1958
+ Methods
1959
+ -------
1960
+ astype
1961
+ argsort
1962
+ copy
1963
+ count
1964
+ decode
1965
+ dump
1966
+ dumps
1967
+ encode
1968
+ endswith
1969
+ expandtabs
1970
+ fill
1971
+ find
1972
+ flatten
1973
+ getfield
1974
+ index
1975
+ isalnum
1976
+ isalpha
1977
+ isdecimal
1978
+ isdigit
1979
+ islower
1980
+ isnumeric
1981
+ isspace
1982
+ istitle
1983
+ isupper
1984
+ item
1985
+ join
1986
+ ljust
1987
+ lower
1988
+ lstrip
1989
+ nonzero
1990
+ put
1991
+ ravel
1992
+ repeat
1993
+ replace
1994
+ reshape
1995
+ resize
1996
+ rfind
1997
+ rindex
1998
+ rjust
1999
+ rsplit
2000
+ rstrip
2001
+ searchsorted
2002
+ setfield
2003
+ setflags
2004
+ sort
2005
+ split
2006
+ splitlines
2007
+ squeeze
2008
+ startswith
2009
+ strip
2010
+ swapaxes
2011
+ swapcase
2012
+ take
2013
+ title
2014
+ tofile
2015
+ tolist
2016
+ tostring
2017
+ translate
2018
+ transpose
2019
+ upper
2020
+ view
2021
+ zfill
2022
+
2023
+ Parameters
2024
+ ----------
2025
+ shape : tuple
2026
+ Shape of the array.
2027
+ itemsize : int, optional
2028
+ Length of each array element, in number of characters. Default is 1.
2029
+ unicode : bool, optional
2030
+ Are the array elements of type unicode (True) or string (False).
2031
+ Default is False.
2032
+ buffer : object exposing the buffer interface or str, optional
2033
+ Memory address of the start of the array data. Default is None,
2034
+ in which case a new array is created.
2035
+ offset : int, optional
2036
+ Fixed stride displacement from the beginning of an axis?
2037
+ Default is 0. Needs to be >=0.
2038
+ strides : array_like of ints, optional
2039
+ Strides for the array (see `ndarray.strides` for full description).
2040
+ Default is None.
2041
+ order : {'C', 'F'}, optional
2042
+ The order in which the array data is stored in memory: 'C' ->
2043
+ "row major" order (the default), 'F' -> "column major"
2044
+ (Fortran) order.
2045
+
2046
+ Examples
2047
+ --------
2048
+ >>> charar = np.chararray((3, 3))
2049
+ >>> charar[:] = 'a'
2050
+ >>> charar
2051
+ chararray([[b'a', b'a', b'a'],
2052
+ [b'a', b'a', b'a'],
2053
+ [b'a', b'a', b'a']], dtype='|S1')
2054
+
2055
+ >>> charar = np.chararray(charar.shape, itemsize=5)
2056
+ >>> charar[:] = 'abc'
2057
+ >>> charar
2058
+ chararray([[b'abc', b'abc', b'abc'],
2059
+ [b'abc', b'abc', b'abc'],
2060
+ [b'abc', b'abc', b'abc']], dtype='|S5')
2061
+
2062
+ """
2063
+ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
2064
+ offset=0, strides=None, order='C'):
2065
+ global _globalvar
2066
+
2067
+ if unicode:
2068
+ dtype = str_
2069
+ else:
2070
+ dtype = bytes_
2071
+
2072
+ # force itemsize to be a Python int, since using NumPy integer
2073
+ # types results in itemsize.itemsize being used as the size of
2074
+ # strings in the new array.
2075
+ itemsize = int(itemsize)
2076
+
2077
+ if isinstance(buffer, str):
2078
+ # unicode objects do not have the buffer interface
2079
+ filler = buffer
2080
+ buffer = None
2081
+ else:
2082
+ filler = None
2083
+
2084
+ _globalvar = 1
2085
+ if buffer is None:
2086
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
2087
+ order=order)
2088
+ else:
2089
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
2090
+ buffer=buffer,
2091
+ offset=offset, strides=strides,
2092
+ order=order)
2093
+ if filler is not None:
2094
+ self[...] = filler
2095
+ _globalvar = 0
2096
+ return self
2097
+
2098
+ def __array_finalize__(self, obj):
2099
+ # The b is a special case because it is used for reconstructing.
2100
+ if not _globalvar and self.dtype.char not in 'SUbc':
2101
+ raise ValueError("Can only create a chararray from string data.")
2102
+
2103
+ def __getitem__(self, obj):
2104
+ val = ndarray.__getitem__(self, obj)
2105
+
2106
+ if isinstance(val, character):
2107
+ temp = val.rstrip()
2108
+ if len(temp) == 0:
2109
+ val = ''
2110
+ else:
2111
+ val = temp
2112
+
2113
+ return val
2114
+
2115
+ # IMPLEMENTATION NOTE: Most of the methods of this class are
2116
+ # direct delegations to the free functions in this module.
2117
+ # However, those that return an array of strings should instead
2118
+ # return a chararray, so some extra wrapping is required.
2119
+
2120
+ def __eq__(self, other):
2121
+ """
2122
+ Return (self == other) element-wise.
2123
+
2124
+ See Also
2125
+ --------
2126
+ equal
2127
+ """
2128
+ return equal(self, other)
2129
+
2130
+ def __ne__(self, other):
2131
+ """
2132
+ Return (self != other) element-wise.
2133
+
2134
+ See Also
2135
+ --------
2136
+ not_equal
2137
+ """
2138
+ return not_equal(self, other)
2139
+
2140
+ def __ge__(self, other):
2141
+ """
2142
+ Return (self >= other) element-wise.
2143
+
2144
+ See Also
2145
+ --------
2146
+ greater_equal
2147
+ """
2148
+ return greater_equal(self, other)
2149
+
2150
+ def __le__(self, other):
2151
+ """
2152
+ Return (self <= other) element-wise.
2153
+
2154
+ See Also
2155
+ --------
2156
+ less_equal
2157
+ """
2158
+ return less_equal(self, other)
2159
+
2160
+ def __gt__(self, other):
2161
+ """
2162
+ Return (self > other) element-wise.
2163
+
2164
+ See Also
2165
+ --------
2166
+ greater
2167
+ """
2168
+ return greater(self, other)
2169
+
2170
+ def __lt__(self, other):
2171
+ """
2172
+ Return (self < other) element-wise.
2173
+
2174
+ See Also
2175
+ --------
2176
+ less
2177
+ """
2178
+ return less(self, other)
2179
+
2180
+ def __add__(self, other):
2181
+ """
2182
+ Return (self + other), that is string concatenation,
2183
+ element-wise for a pair of array_likes of str or unicode.
2184
+
2185
+ See Also
2186
+ --------
2187
+ add
2188
+ """
2189
+ return asarray(add(self, other))
2190
+
2191
+ def __radd__(self, other):
2192
+ """
2193
+ Return (other + self), that is string concatenation,
2194
+ element-wise for a pair of array_likes of `bytes_` or `str_`.
2195
+
2196
+ See Also
2197
+ --------
2198
+ add
2199
+ """
2200
+ return asarray(add(numpy.asarray(other), self))
2201
+
2202
+ def __mul__(self, i):
2203
+ """
2204
+ Return (self * i), that is string multiple concatenation,
2205
+ element-wise.
2206
+
2207
+ See Also
2208
+ --------
2209
+ multiply
2210
+ """
2211
+ return asarray(multiply(self, i))
2212
+
2213
+ def __rmul__(self, i):
2214
+ """
2215
+ Return (self * i), that is string multiple concatenation,
2216
+ element-wise.
2217
+
2218
+ See Also
2219
+ --------
2220
+ multiply
2221
+ """
2222
+ return asarray(multiply(self, i))
2223
+
2224
+ def __mod__(self, i):
2225
+ """
2226
+ Return (self % i), that is pre-Python 2.6 string formatting
2227
+ (interpolation), element-wise for a pair of array_likes of `bytes_`
2228
+ or `str_`.
2229
+
2230
+ See Also
2231
+ --------
2232
+ mod
2233
+ """
2234
+ return asarray(mod(self, i))
2235
+
2236
+ def __rmod__(self, other):
2237
+ return NotImplemented
2238
+
2239
+ def argsort(self, axis=-1, kind=None, order=None):
2240
+ """
2241
+ Return the indices that sort the array lexicographically.
2242
+
2243
+ For full documentation see `numpy.argsort`, for which this method is
2244
+ in fact merely a "thin wrapper."
2245
+
2246
+ Examples
2247
+ --------
2248
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
2249
+ >>> c = c.view(np.chararray); c
2250
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
2251
+ dtype='|S5')
2252
+ >>> c[c.argsort()]
2253
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
2254
+ dtype='|S5')
2255
+
2256
+ """
2257
+ return self.__array__().argsort(axis, kind, order)
2258
+ argsort.__doc__ = ndarray.argsort.__doc__
2259
+
2260
+ def capitalize(self):
2261
+ """
2262
+ Return a copy of `self` with only the first character of each element
2263
+ capitalized.
2264
+
2265
+ See Also
2266
+ --------
2267
+ char.capitalize
2268
+
2269
+ """
2270
+ return asarray(capitalize(self))
2271
+
2272
+ def center(self, width, fillchar=' '):
2273
+ """
2274
+ Return a copy of `self` with its elements centered in a
2275
+ string of length `width`.
2276
+
2277
+ See Also
2278
+ --------
2279
+ center
2280
+ """
2281
+ return asarray(center(self, width, fillchar))
2282
+
2283
+ def count(self, sub, start=0, end=None):
2284
+ """
2285
+ Returns an array with the number of non-overlapping occurrences of
2286
+ substring `sub` in the range [`start`, `end`].
2287
+
2288
+ See Also
2289
+ --------
2290
+ char.count
2291
+
2292
+ """
2293
+ return count(self, sub, start, end)
2294
+
2295
+ def decode(self, encoding=None, errors=None):
2296
+ """
2297
+ Calls ``bytes.decode`` element-wise.
2298
+
2299
+ See Also
2300
+ --------
2301
+ char.decode
2302
+
2303
+ """
2304
+ return decode(self, encoding, errors)
2305
+
2306
+ def encode(self, encoding=None, errors=None):
2307
+ """
2308
+ Calls `str.encode` element-wise.
2309
+
2310
+ See Also
2311
+ --------
2312
+ char.encode
2313
+
2314
+ """
2315
+ return encode(self, encoding, errors)
2316
+
2317
+ def endswith(self, suffix, start=0, end=None):
2318
+ """
2319
+ Returns a boolean array which is `True` where the string element
2320
+ in `self` ends with `suffix`, otherwise `False`.
2321
+
2322
+ See Also
2323
+ --------
2324
+ char.endswith
2325
+
2326
+ """
2327
+ return endswith(self, suffix, start, end)
2328
+
2329
+ def expandtabs(self, tabsize=8):
2330
+ """
2331
+ Return a copy of each string element where all tab characters are
2332
+ replaced by one or more spaces.
2333
+
2334
+ See Also
2335
+ --------
2336
+ char.expandtabs
2337
+
2338
+ """
2339
+ return asarray(expandtabs(self, tabsize))
2340
+
2341
+ def find(self, sub, start=0, end=None):
2342
+ """
2343
+ For each element, return the lowest index in the string where
2344
+ substring `sub` is found.
2345
+
2346
+ See Also
2347
+ --------
2348
+ char.find
2349
+
2350
+ """
2351
+ return find(self, sub, start, end)
2352
+
2353
+ def index(self, sub, start=0, end=None):
2354
+ """
2355
+ Like `find`, but raises `ValueError` when the substring is not found.
2356
+
2357
+ See Also
2358
+ --------
2359
+ char.index
2360
+
2361
+ """
2362
+ return index(self, sub, start, end)
2363
+
2364
+ def isalnum(self):
2365
+ """
2366
+ Returns true for each element if all characters in the string
2367
+ are alphanumeric and there is at least one character, false
2368
+ otherwise.
2369
+
2370
+ See Also
2371
+ --------
2372
+ char.isalnum
2373
+
2374
+ """
2375
+ return isalnum(self)
2376
+
2377
+ def isalpha(self):
2378
+ """
2379
+ Returns true for each element if all characters in the string
2380
+ are alphabetic and there is at least one character, false
2381
+ otherwise.
2382
+
2383
+ See Also
2384
+ --------
2385
+ char.isalpha
2386
+
2387
+ """
2388
+ return isalpha(self)
2389
+
2390
+ def isdigit(self):
2391
+ """
2392
+ Returns true for each element if all characters in the string are
2393
+ digits and there is at least one character, false otherwise.
2394
+
2395
+ See Also
2396
+ --------
2397
+ char.isdigit
2398
+
2399
+ """
2400
+ return isdigit(self)
2401
+
2402
+ def islower(self):
2403
+ """
2404
+ Returns true for each element if all cased characters in the
2405
+ string are lowercase and there is at least one cased character,
2406
+ false otherwise.
2407
+
2408
+ See Also
2409
+ --------
2410
+ char.islower
2411
+
2412
+ """
2413
+ return islower(self)
2414
+
2415
+ def isspace(self):
2416
+ """
2417
+ Returns true for each element if there are only whitespace
2418
+ characters in the string and there is at least one character,
2419
+ false otherwise.
2420
+
2421
+ See Also
2422
+ --------
2423
+ char.isspace
2424
+
2425
+ """
2426
+ return isspace(self)
2427
+
2428
+ def istitle(self):
2429
+ """
2430
+ Returns true for each element if the element is a titlecased
2431
+ string and there is at least one character, false otherwise.
2432
+
2433
+ See Also
2434
+ --------
2435
+ char.istitle
2436
+
2437
+ """
2438
+ return istitle(self)
2439
+
2440
+ def isupper(self):
2441
+ """
2442
+ Returns true for each element if all cased characters in the
2443
+ string are uppercase and there is at least one character, false
2444
+ otherwise.
2445
+
2446
+ See Also
2447
+ --------
2448
+ char.isupper
2449
+
2450
+ """
2451
+ return isupper(self)
2452
+
2453
+ def join(self, seq):
2454
+ """
2455
+ Return a string which is the concatenation of the strings in the
2456
+ sequence `seq`.
2457
+
2458
+ See Also
2459
+ --------
2460
+ char.join
2461
+
2462
+ """
2463
+ return join(self, seq)
2464
+
2465
+ def ljust(self, width, fillchar=' '):
2466
+ """
2467
+ Return an array with the elements of `self` left-justified in a
2468
+ string of length `width`.
2469
+
2470
+ See Also
2471
+ --------
2472
+ char.ljust
2473
+
2474
+ """
2475
+ return asarray(ljust(self, width, fillchar))
2476
+
2477
+ def lower(self):
2478
+ """
2479
+ Return an array with the elements of `self` converted to
2480
+ lowercase.
2481
+
2482
+ See Also
2483
+ --------
2484
+ char.lower
2485
+
2486
+ """
2487
+ return asarray(lower(self))
2488
+
2489
+ def lstrip(self, chars=None):
2490
+ """
2491
+ For each element in `self`, return a copy with the leading characters
2492
+ removed.
2493
+
2494
+ See Also
2495
+ --------
2496
+ char.lstrip
2497
+
2498
+ """
2499
+ return asarray(lstrip(self, chars))
2500
+
2501
+ def partition(self, sep):
2502
+ """
2503
+ Partition each element in `self` around `sep`.
2504
+
2505
+ See Also
2506
+ --------
2507
+ partition
2508
+ """
2509
+ return asarray(partition(self, sep))
2510
+
2511
+ def replace(self, old, new, count=None):
2512
+ """
2513
+ For each element in `self`, return a copy of the string with all
2514
+ occurrences of substring `old` replaced by `new`.
2515
+
2516
+ See Also
2517
+ --------
2518
+ char.replace
2519
+
2520
+ """
2521
+ return asarray(replace(self, old, new, count))
2522
+
2523
+ def rfind(self, sub, start=0, end=None):
2524
+ """
2525
+ For each element in `self`, return the highest index in the string
2526
+ where substring `sub` is found, such that `sub` is contained
2527
+ within [`start`, `end`].
2528
+
2529
+ See Also
2530
+ --------
2531
+ char.rfind
2532
+
2533
+ """
2534
+ return rfind(self, sub, start, end)
2535
+
2536
+ def rindex(self, sub, start=0, end=None):
2537
+ """
2538
+ Like `rfind`, but raises `ValueError` when the substring `sub` is
2539
+ not found.
2540
+
2541
+ See Also
2542
+ --------
2543
+ char.rindex
2544
+
2545
+ """
2546
+ return rindex(self, sub, start, end)
2547
+
2548
+ def rjust(self, width, fillchar=' '):
2549
+ """
2550
+ Return an array with the elements of `self`
2551
+ right-justified in a string of length `width`.
2552
+
2553
+ See Also
2554
+ --------
2555
+ char.rjust
2556
+
2557
+ """
2558
+ return asarray(rjust(self, width, fillchar))
2559
+
2560
+ def rpartition(self, sep):
2561
+ """
2562
+ Partition each element in `self` around `sep`.
2563
+
2564
+ See Also
2565
+ --------
2566
+ rpartition
2567
+ """
2568
+ return asarray(rpartition(self, sep))
2569
+
2570
+ def rsplit(self, sep=None, maxsplit=None):
2571
+ """
2572
+ For each element in `self`, return a list of the words in
2573
+ the string, using `sep` as the delimiter string.
2574
+
2575
+ See Also
2576
+ --------
2577
+ char.rsplit
2578
+
2579
+ """
2580
+ return rsplit(self, sep, maxsplit)
2581
+
2582
+ def rstrip(self, chars=None):
2583
+ """
2584
+ For each element in `self`, return a copy with the trailing
2585
+ characters removed.
2586
+
2587
+ See Also
2588
+ --------
2589
+ char.rstrip
2590
+
2591
+ """
2592
+ return asarray(rstrip(self, chars))
2593
+
2594
+ def split(self, sep=None, maxsplit=None):
2595
+ """
2596
+ For each element in `self`, return a list of the words in the
2597
+ string, using `sep` as the delimiter string.
2598
+
2599
+ See Also
2600
+ --------
2601
+ char.split
2602
+
2603
+ """
2604
+ return split(self, sep, maxsplit)
2605
+
2606
+ def splitlines(self, keepends=None):
2607
+ """
2608
+ For each element in `self`, return a list of the lines in the
2609
+ element, breaking at line boundaries.
2610
+
2611
+ See Also
2612
+ --------
2613
+ char.splitlines
2614
+
2615
+ """
2616
+ return splitlines(self, keepends)
2617
+
2618
+ def startswith(self, prefix, start=0, end=None):
2619
+ """
2620
+ Returns a boolean array which is `True` where the string element
2621
+ in `self` starts with `prefix`, otherwise `False`.
2622
+
2623
+ See Also
2624
+ --------
2625
+ char.startswith
2626
+
2627
+ """
2628
+ return startswith(self, prefix, start, end)
2629
+
2630
+ def strip(self, chars=None):
2631
+ """
2632
+ For each element in `self`, return a copy with the leading and
2633
+ trailing characters removed.
2634
+
2635
+ See Also
2636
+ --------
2637
+ char.strip
2638
+
2639
+ """
2640
+ return asarray(strip(self, chars))
2641
+
2642
+ def swapcase(self):
2643
+ """
2644
+ For each element in `self`, return a copy of the string with
2645
+ uppercase characters converted to lowercase and vice versa.
2646
+
2647
+ See Also
2648
+ --------
2649
+ char.swapcase
2650
+
2651
+ """
2652
+ return asarray(swapcase(self))
2653
+
2654
+ def title(self):
2655
+ """
2656
+ For each element in `self`, return a titlecased version of the
2657
+ string: words start with uppercase characters, all remaining cased
2658
+ characters are lowercase.
2659
+
2660
+ See Also
2661
+ --------
2662
+ char.title
2663
+
2664
+ """
2665
+ return asarray(title(self))
2666
+
2667
+ def translate(self, table, deletechars=None):
2668
+ """
2669
+ For each element in `self`, return a copy of the string where
2670
+ all characters occurring in the optional argument
2671
+ `deletechars` are removed, and the remaining characters have
2672
+ been mapped through the given translation table.
2673
+
2674
+ See Also
2675
+ --------
2676
+ char.translate
2677
+
2678
+ """
2679
+ return asarray(translate(self, table, deletechars))
2680
+
2681
+ def upper(self):
2682
+ """
2683
+ Return an array with the elements of `self` converted to
2684
+ uppercase.
2685
+
2686
+ See Also
2687
+ --------
2688
+ char.upper
2689
+
2690
+ """
2691
+ return asarray(upper(self))
2692
+
2693
+ def zfill(self, width):
2694
+ """
2695
+ Return the numeric string left-filled with zeros in a string of
2696
+ length `width`.
2697
+
2698
+ See Also
2699
+ --------
2700
+ char.zfill
2701
+
2702
+ """
2703
+ return asarray(zfill(self, width))
2704
+
2705
+ def isnumeric(self):
2706
+ """
2707
+ For each element in `self`, return True if there are only
2708
+ numeric characters in the element.
2709
+
2710
+ See Also
2711
+ --------
2712
+ char.isnumeric
2713
+
2714
+ """
2715
+ return isnumeric(self)
2716
+
2717
+ def isdecimal(self):
2718
+ """
2719
+ For each element in `self`, return True if there are only
2720
+ decimal characters in the element.
2721
+
2722
+ See Also
2723
+ --------
2724
+ char.isdecimal
2725
+
2726
+ """
2727
+ return isdecimal(self)
2728
+
2729
+
2730
+ @set_module("numpy.char")
2731
+ def array(obj, itemsize=None, copy=True, unicode=None, order=None):
2732
+ """
2733
+ Create a `chararray`.
2734
+
2735
+ .. note::
2736
+ This class is provided for numarray backward-compatibility.
2737
+ New code (not concerned with numarray compatibility) should use
2738
+ arrays of type `bytes_` or `str_` and use the free functions
2739
+ in :mod:`numpy.char <numpy.core.defchararray>` for fast
2740
+ vectorized string operations instead.
2741
+
2742
+ Versus a regular NumPy array of type `str` or `unicode`, this
2743
+ class adds the following functionality:
2744
+
2745
+ 1) values automatically have whitespace removed from the end
2746
+ when indexed
2747
+
2748
+ 2) comparison operators automatically remove whitespace from the
2749
+ end when comparing values
2750
+
2751
+ 3) vectorized string operations are provided as methods
2752
+ (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``)
2753
+
2754
+ Parameters
2755
+ ----------
2756
+ obj : array of str or unicode-like
2757
+
2758
+ itemsize : int, optional
2759
+ `itemsize` is the number of characters per scalar in the
2760
+ resulting array. If `itemsize` is None, and `obj` is an
2761
+ object array or a Python list, the `itemsize` will be
2762
+ automatically determined. If `itemsize` is provided and `obj`
2763
+ is of type str or unicode, then the `obj` string will be
2764
+ chunked into `itemsize` pieces.
2765
+
2766
+ copy : bool, optional
2767
+ If true (default), then the object is copied. Otherwise, a copy
2768
+ will only be made if __array__ returns a copy, if obj is a
2769
+ nested sequence, or if a copy is needed to satisfy any of the other
2770
+ requirements (`itemsize`, unicode, `order`, etc.).
2771
+
2772
+ unicode : bool, optional
2773
+ When true, the resulting `chararray` can contain Unicode
2774
+ characters, when false only 8-bit characters. If unicode is
2775
+ None and `obj` is one of the following:
2776
+
2777
+ - a `chararray`,
2778
+ - an ndarray of type `str` or `unicode`
2779
+ - a Python str or unicode object,
2780
+
2781
+ then the unicode setting of the output array will be
2782
+ automatically determined.
2783
+
2784
+ order : {'C', 'F', 'A'}, optional
2785
+ Specify the order of the array. If order is 'C' (default), then the
2786
+ array will be in C-contiguous order (last-index varies the
2787
+ fastest). If order is 'F', then the returned array
2788
+ will be in Fortran-contiguous order (first-index varies the
2789
+ fastest). If order is 'A', then the returned array may
2790
+ be in any order (either C-, Fortran-contiguous, or even
2791
+ discontiguous).
2792
+ """
2793
+ if isinstance(obj, (bytes, str)):
2794
+ if unicode is None:
2795
+ if isinstance(obj, str):
2796
+ unicode = True
2797
+ else:
2798
+ unicode = False
2799
+
2800
+ if itemsize is None:
2801
+ itemsize = len(obj)
2802
+ shape = len(obj) // itemsize
2803
+
2804
+ return chararray(shape, itemsize=itemsize, unicode=unicode,
2805
+ buffer=obj, order=order)
2806
+
2807
+ if isinstance(obj, (list, tuple)):
2808
+ obj = numpy.asarray(obj)
2809
+
2810
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
2811
+ # If we just have a vanilla chararray, create a chararray
2812
+ # view around it.
2813
+ if not isinstance(obj, chararray):
2814
+ obj = obj.view(chararray)
2815
+
2816
+ if itemsize is None:
2817
+ itemsize = obj.itemsize
2818
+ # itemsize is in 8-bit chars, so for Unicode, we need
2819
+ # to divide by the size of a single Unicode character,
2820
+ # which for NumPy is always 4
2821
+ if issubclass(obj.dtype.type, str_):
2822
+ itemsize //= 4
2823
+
2824
+ if unicode is None:
2825
+ if issubclass(obj.dtype.type, str_):
2826
+ unicode = True
2827
+ else:
2828
+ unicode = False
2829
+
2830
+ if unicode:
2831
+ dtype = str_
2832
+ else:
2833
+ dtype = bytes_
2834
+
2835
+ if order is not None:
2836
+ obj = numpy.asarray(obj, order=order)
2837
+ if (copy or
2838
+ (itemsize != obj.itemsize) or
2839
+ (not unicode and isinstance(obj, str_)) or
2840
+ (unicode and isinstance(obj, bytes_))):
2841
+ obj = obj.astype((dtype, int(itemsize)))
2842
+ return obj
2843
+
2844
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
2845
+ if itemsize is None:
2846
+ # Since no itemsize was specified, convert the input array to
2847
+ # a list so the ndarray constructor will automatically
2848
+ # determine the itemsize for us.
2849
+ obj = obj.tolist()
2850
+ # Fall through to the default case
2851
+
2852
+ if unicode:
2853
+ dtype = str_
2854
+ else:
2855
+ dtype = bytes_
2856
+
2857
+ if itemsize is None:
2858
+ val = narray(obj, dtype=dtype, order=order, subok=True)
2859
+ else:
2860
+ val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
2861
+ return val.view(chararray)
2862
+
2863
+
2864
+ @set_module("numpy.char")
2865
+ def asarray(obj, itemsize=None, unicode=None, order=None):
2866
+ """
2867
+ Convert the input to a `chararray`, copying the data only if
2868
+ necessary.
2869
+
2870
+ Versus a regular NumPy array of type `str` or `unicode`, this
2871
+ class adds the following functionality:
2872
+
2873
+ 1) values automatically have whitespace removed from the end
2874
+ when indexed
2875
+
2876
+ 2) comparison operators automatically remove whitespace from the
2877
+ end when comparing values
2878
+
2879
+ 3) vectorized string operations are provided as methods
2880
+ (e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``)
2881
+
2882
+ Parameters
2883
+ ----------
2884
+ obj : array of str or unicode-like
2885
+
2886
+ itemsize : int, optional
2887
+ `itemsize` is the number of characters per scalar in the
2888
+ resulting array. If `itemsize` is None, and `obj` is an
2889
+ object array or a Python list, the `itemsize` will be
2890
+ automatically determined. If `itemsize` is provided and `obj`
2891
+ is of type str or unicode, then the `obj` string will be
2892
+ chunked into `itemsize` pieces.
2893
+
2894
+ unicode : bool, optional
2895
+ When true, the resulting `chararray` can contain Unicode
2896
+ characters, when false only 8-bit characters. If unicode is
2897
+ None and `obj` is one of the following:
2898
+
2899
+ - a `chararray`,
2900
+ - an ndarray of type `str` or 'unicode`
2901
+ - a Python str or unicode object,
2902
+
2903
+ then the unicode setting of the output array will be
2904
+ automatically determined.
2905
+
2906
+ order : {'C', 'F'}, optional
2907
+ Specify the order of the array. If order is 'C' (default), then the
2908
+ array will be in C-contiguous order (last-index varies the
2909
+ fastest). If order is 'F', then the returned array
2910
+ will be in Fortran-contiguous order (first-index varies the
2911
+ fastest).
2912
+ """
2913
+ return array(obj, itemsize, copy=False,
2914
+ unicode=unicode, order=order)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/defchararray.pyi ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Literal as L,
3
+ overload,
4
+ TypeVar,
5
+ Any,
6
+ )
7
+
8
+ from numpy import (
9
+ chararray as chararray,
10
+ dtype,
11
+ str_,
12
+ bytes_,
13
+ int_,
14
+ bool_,
15
+ object_,
16
+ _OrderKACF,
17
+ )
18
+
19
+ from numpy._typing import (
20
+ NDArray,
21
+ _ArrayLikeStr_co as U_co,
22
+ _ArrayLikeBytes_co as S_co,
23
+ _ArrayLikeInt_co as i_co,
24
+ _ArrayLikeBool_co as b_co,
25
+ )
26
+
27
+ from numpy.core.multiarray import compare_chararrays as compare_chararrays
28
+
29
+ _SCT = TypeVar("_SCT", str_, bytes_)
30
+ _CharArray = chararray[Any, dtype[_SCT]]
31
+
32
+ __all__: list[str]
33
+
34
+ # Comparison
35
+ @overload
36
+ def equal(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
37
+ @overload
38
+ def equal(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
39
+
40
+ @overload
41
+ def not_equal(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
42
+ @overload
43
+ def not_equal(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
44
+
45
+ @overload
46
+ def greater_equal(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
47
+ @overload
48
+ def greater_equal(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
49
+
50
+ @overload
51
+ def less_equal(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
52
+ @overload
53
+ def less_equal(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
54
+
55
+ @overload
56
+ def greater(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
57
+ @overload
58
+ def greater(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
59
+
60
+ @overload
61
+ def less(x1: U_co, x2: U_co) -> NDArray[bool_]: ...
62
+ @overload
63
+ def less(x1: S_co, x2: S_co) -> NDArray[bool_]: ...
64
+
65
+ # String operations
66
+ @overload
67
+ def add(x1: U_co, x2: U_co) -> NDArray[str_]: ...
68
+ @overload
69
+ def add(x1: S_co, x2: S_co) -> NDArray[bytes_]: ...
70
+
71
+ @overload
72
+ def multiply(a: U_co, i: i_co) -> NDArray[str_]: ...
73
+ @overload
74
+ def multiply(a: S_co, i: i_co) -> NDArray[bytes_]: ...
75
+
76
+ @overload
77
+ def mod(a: U_co, value: Any) -> NDArray[str_]: ...
78
+ @overload
79
+ def mod(a: S_co, value: Any) -> NDArray[bytes_]: ...
80
+
81
+ @overload
82
+ def capitalize(a: U_co) -> NDArray[str_]: ...
83
+ @overload
84
+ def capitalize(a: S_co) -> NDArray[bytes_]: ...
85
+
86
+ @overload
87
+ def center(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
88
+ @overload
89
+ def center(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
90
+
91
+ def decode(
92
+ a: S_co,
93
+ encoding: None | str = ...,
94
+ errors: None | str = ...,
95
+ ) -> NDArray[str_]: ...
96
+
97
+ def encode(
98
+ a: U_co,
99
+ encoding: None | str = ...,
100
+ errors: None | str = ...,
101
+ ) -> NDArray[bytes_]: ...
102
+
103
+ @overload
104
+ def expandtabs(a: U_co, tabsize: i_co = ...) -> NDArray[str_]: ...
105
+ @overload
106
+ def expandtabs(a: S_co, tabsize: i_co = ...) -> NDArray[bytes_]: ...
107
+
108
+ @overload
109
+ def join(sep: U_co, seq: U_co) -> NDArray[str_]: ...
110
+ @overload
111
+ def join(sep: S_co, seq: S_co) -> NDArray[bytes_]: ...
112
+
113
+ @overload
114
+ def ljust(a: U_co, width: i_co, fillchar: U_co = ...) -> NDArray[str_]: ...
115
+ @overload
116
+ def ljust(a: S_co, width: i_co, fillchar: S_co = ...) -> NDArray[bytes_]: ...
117
+
118
+ @overload
119
+ def lower(a: U_co) -> NDArray[str_]: ...
120
+ @overload
121
+ def lower(a: S_co) -> NDArray[bytes_]: ...
122
+
123
+ @overload
124
+ def lstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
125
+ @overload
126
+ def lstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
127
+
128
+ @overload
129
+ def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
130
+ @overload
131
+ def partition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
132
+
133
+ @overload
134
+ def replace(
135
+ a: U_co,
136
+ old: U_co,
137
+ new: U_co,
138
+ count: None | i_co = ...,
139
+ ) -> NDArray[str_]: ...
140
+ @overload
141
+ def replace(
142
+ a: S_co,
143
+ old: S_co,
144
+ new: S_co,
145
+ count: None | i_co = ...,
146
+ ) -> NDArray[bytes_]: ...
147
+
148
+ @overload
149
+ def rjust(
150
+ a: U_co,
151
+ width: i_co,
152
+ fillchar: U_co = ...,
153
+ ) -> NDArray[str_]: ...
154
+ @overload
155
+ def rjust(
156
+ a: S_co,
157
+ width: i_co,
158
+ fillchar: S_co = ...,
159
+ ) -> NDArray[bytes_]: ...
160
+
161
+ @overload
162
+ def rpartition(a: U_co, sep: U_co) -> NDArray[str_]: ...
163
+ @overload
164
+ def rpartition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
165
+
166
+ @overload
167
+ def rsplit(
168
+ a: U_co,
169
+ sep: None | U_co = ...,
170
+ maxsplit: None | i_co = ...,
171
+ ) -> NDArray[object_]: ...
172
+ @overload
173
+ def rsplit(
174
+ a: S_co,
175
+ sep: None | S_co = ...,
176
+ maxsplit: None | i_co = ...,
177
+ ) -> NDArray[object_]: ...
178
+
179
+ @overload
180
+ def rstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
181
+ @overload
182
+ def rstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
183
+
184
+ @overload
185
+ def split(
186
+ a: U_co,
187
+ sep: None | U_co = ...,
188
+ maxsplit: None | i_co = ...,
189
+ ) -> NDArray[object_]: ...
190
+ @overload
191
+ def split(
192
+ a: S_co,
193
+ sep: None | S_co = ...,
194
+ maxsplit: None | i_co = ...,
195
+ ) -> NDArray[object_]: ...
196
+
197
+ @overload
198
+ def splitlines(a: U_co, keepends: None | b_co = ...) -> NDArray[object_]: ...
199
+ @overload
200
+ def splitlines(a: S_co, keepends: None | b_co = ...) -> NDArray[object_]: ...
201
+
202
+ @overload
203
+ def strip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
204
+ @overload
205
+ def strip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
206
+
207
+ @overload
208
+ def swapcase(a: U_co) -> NDArray[str_]: ...
209
+ @overload
210
+ def swapcase(a: S_co) -> NDArray[bytes_]: ...
211
+
212
+ @overload
213
+ def title(a: U_co) -> NDArray[str_]: ...
214
+ @overload
215
+ def title(a: S_co) -> NDArray[bytes_]: ...
216
+
217
+ @overload
218
+ def translate(
219
+ a: U_co,
220
+ table: U_co,
221
+ deletechars: None | U_co = ...,
222
+ ) -> NDArray[str_]: ...
223
+ @overload
224
+ def translate(
225
+ a: S_co,
226
+ table: S_co,
227
+ deletechars: None | S_co = ...,
228
+ ) -> NDArray[bytes_]: ...
229
+
230
+ @overload
231
+ def upper(a: U_co) -> NDArray[str_]: ...
232
+ @overload
233
+ def upper(a: S_co) -> NDArray[bytes_]: ...
234
+
235
+ @overload
236
+ def zfill(a: U_co, width: i_co) -> NDArray[str_]: ...
237
+ @overload
238
+ def zfill(a: S_co, width: i_co) -> NDArray[bytes_]: ...
239
+
240
+ # String information
241
+ @overload
242
+ def count(
243
+ a: U_co,
244
+ sub: U_co,
245
+ start: i_co = ...,
246
+ end: None | i_co = ...,
247
+ ) -> NDArray[int_]: ...
248
+ @overload
249
+ def count(
250
+ a: S_co,
251
+ sub: S_co,
252
+ start: i_co = ...,
253
+ end: None | i_co = ...,
254
+ ) -> NDArray[int_]: ...
255
+
256
+ @overload
257
+ def endswith(
258
+ a: U_co,
259
+ suffix: U_co,
260
+ start: i_co = ...,
261
+ end: None | i_co = ...,
262
+ ) -> NDArray[bool_]: ...
263
+ @overload
264
+ def endswith(
265
+ a: S_co,
266
+ suffix: S_co,
267
+ start: i_co = ...,
268
+ end: None | i_co = ...,
269
+ ) -> NDArray[bool_]: ...
270
+
271
+ @overload
272
+ def find(
273
+ a: U_co,
274
+ sub: U_co,
275
+ start: i_co = ...,
276
+ end: None | i_co = ...,
277
+ ) -> NDArray[int_]: ...
278
+ @overload
279
+ def find(
280
+ a: S_co,
281
+ sub: S_co,
282
+ start: i_co = ...,
283
+ end: None | i_co = ...,
284
+ ) -> NDArray[int_]: ...
285
+
286
+ @overload
287
+ def index(
288
+ a: U_co,
289
+ sub: U_co,
290
+ start: i_co = ...,
291
+ end: None | i_co = ...,
292
+ ) -> NDArray[int_]: ...
293
+ @overload
294
+ def index(
295
+ a: S_co,
296
+ sub: S_co,
297
+ start: i_co = ...,
298
+ end: None | i_co = ...,
299
+ ) -> NDArray[int_]: ...
300
+
301
+ def isalpha(a: U_co | S_co) -> NDArray[bool_]: ...
302
+ def isalnum(a: U_co | S_co) -> NDArray[bool_]: ...
303
+ def isdecimal(a: U_co | S_co) -> NDArray[bool_]: ...
304
+ def isdigit(a: U_co | S_co) -> NDArray[bool_]: ...
305
+ def islower(a: U_co | S_co) -> NDArray[bool_]: ...
306
+ def isnumeric(a: U_co | S_co) -> NDArray[bool_]: ...
307
+ def isspace(a: U_co | S_co) -> NDArray[bool_]: ...
308
+ def istitle(a: U_co | S_co) -> NDArray[bool_]: ...
309
+ def isupper(a: U_co | S_co) -> NDArray[bool_]: ...
310
+
311
+ @overload
312
+ def rfind(
313
+ a: U_co,
314
+ sub: U_co,
315
+ start: i_co = ...,
316
+ end: None | i_co = ...,
317
+ ) -> NDArray[int_]: ...
318
+ @overload
319
+ def rfind(
320
+ a: S_co,
321
+ sub: S_co,
322
+ start: i_co = ...,
323
+ end: None | i_co = ...,
324
+ ) -> NDArray[int_]: ...
325
+
326
+ @overload
327
+ def rindex(
328
+ a: U_co,
329
+ sub: U_co,
330
+ start: i_co = ...,
331
+ end: None | i_co = ...,
332
+ ) -> NDArray[int_]: ...
333
+ @overload
334
+ def rindex(
335
+ a: S_co,
336
+ sub: S_co,
337
+ start: i_co = ...,
338
+ end: None | i_co = ...,
339
+ ) -> NDArray[int_]: ...
340
+
341
+ @overload
342
+ def startswith(
343
+ a: U_co,
344
+ prefix: U_co,
345
+ start: i_co = ...,
346
+ end: None | i_co = ...,
347
+ ) -> NDArray[bool_]: ...
348
+ @overload
349
+ def startswith(
350
+ a: S_co,
351
+ prefix: S_co,
352
+ start: i_co = ...,
353
+ end: None | i_co = ...,
354
+ ) -> NDArray[bool_]: ...
355
+
356
+ def str_len(A: U_co | S_co) -> NDArray[int_]: ...
357
+
358
+ # Overload 1 and 2: str- or bytes-based array-likes
359
+ # overload 3: arbitrary object with unicode=False (-> bytes_)
360
+ # overload 4: arbitrary object with unicode=True (-> str_)
361
+ @overload
362
+ def array(
363
+ obj: U_co,
364
+ itemsize: None | int = ...,
365
+ copy: bool = ...,
366
+ unicode: L[False] = ...,
367
+ order: _OrderKACF = ...,
368
+ ) -> _CharArray[str_]: ...
369
+ @overload
370
+ def array(
371
+ obj: S_co,
372
+ itemsize: None | int = ...,
373
+ copy: bool = ...,
374
+ unicode: L[False] = ...,
375
+ order: _OrderKACF = ...,
376
+ ) -> _CharArray[bytes_]: ...
377
+ @overload
378
+ def array(
379
+ obj: object,
380
+ itemsize: None | int = ...,
381
+ copy: bool = ...,
382
+ unicode: L[False] = ...,
383
+ order: _OrderKACF = ...,
384
+ ) -> _CharArray[bytes_]: ...
385
+ @overload
386
+ def array(
387
+ obj: object,
388
+ itemsize: None | int = ...,
389
+ copy: bool = ...,
390
+ unicode: L[True] = ...,
391
+ order: _OrderKACF = ...,
392
+ ) -> _CharArray[str_]: ...
393
+
394
+ @overload
395
+ def asarray(
396
+ obj: U_co,
397
+ itemsize: None | int = ...,
398
+ unicode: L[False] = ...,
399
+ order: _OrderKACF = ...,
400
+ ) -> _CharArray[str_]: ...
401
+ @overload
402
+ def asarray(
403
+ obj: S_co,
404
+ itemsize: None | int = ...,
405
+ unicode: L[False] = ...,
406
+ order: _OrderKACF = ...,
407
+ ) -> _CharArray[bytes_]: ...
408
+ @overload
409
+ def asarray(
410
+ obj: object,
411
+ itemsize: None | int = ...,
412
+ unicode: L[False] = ...,
413
+ order: _OrderKACF = ...,
414
+ ) -> _CharArray[bytes_]: ...
415
+ @overload
416
+ def asarray(
417
+ obj: object,
418
+ itemsize: None | int = ...,
419
+ unicode: L[True] = ...,
420
+ order: _OrderKACF = ...,
421
+ ) -> _CharArray[str_]: ...
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_argparse.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the private NumPy argument parsing functionality.
3
+ They mainly exists to ensure good test coverage without having to try the
4
+ weirder cases on actual numpy functions but test them in one place.
5
+
6
+ The test function is defined in C to be equivalent to (errors may not always
7
+ match exactly, and could be adjusted):
8
+
9
+ def func(arg1, /, arg2, *, arg3):
10
+ i = integer(arg1) # reproducing the 'i' parsing in Python.
11
+ return None
12
+ """
13
+
14
+ import pytest
15
+
16
+ import numpy as np
17
+ from numpy.core._multiarray_tests import argparse_example_function as func
18
+
19
+
20
+ def test_invalid_integers():
21
+ with pytest.raises(TypeError,
22
+ match="integer argument expected, got float"):
23
+ func(1.)
24
+ with pytest.raises(OverflowError):
25
+ func(2**100)
26
+
27
+
28
+ def test_missing_arguments():
29
+ with pytest.raises(TypeError,
30
+ match="missing required positional argument 0"):
31
+ func()
32
+ with pytest.raises(TypeError,
33
+ match="missing required positional argument 0"):
34
+ func(arg2=1, arg3=4)
35
+ with pytest.raises(TypeError,
36
+ match=r"missing required argument \'arg2\' \(pos 1\)"):
37
+ func(1, arg3=5)
38
+
39
+
40
+ def test_too_many_positional():
41
+ # the second argument is positional but can be passed as keyword.
42
+ with pytest.raises(TypeError,
43
+ match="takes from 2 to 3 positional arguments but 4 were given"):
44
+ func(1, 2, 3, 4)
45
+
46
+
47
+ def test_multiple_values():
48
+ with pytest.raises(TypeError,
49
+ match=r"given by name \('arg2'\) and position \(position 1\)"):
50
+ func(1, 2, arg2=3)
51
+
52
+
53
+ def test_string_fallbacks():
54
+ # We can (currently?) use numpy strings to test the "slow" fallbacks
55
+ # that should normally not be taken due to string interning.
56
+ arg2 = np.str_("arg2")
57
+ missing_arg = np.str_("missing_arg")
58
+ func(1, **{arg2: 3})
59
+ with pytest.raises(TypeError,
60
+ match="got an unexpected keyword argument 'missing_arg'"):
61
+ func(2, **{missing_arg: 3})
62
+
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_array_coercion.py ADDED
@@ -0,0 +1,898 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for array coercion, mainly through testing `np.array` results directly.
3
+ Note that other such tests exist, e.g., in `test_api.py` and many corner-cases
4
+ are tested (sometimes indirectly) elsewhere.
5
+ """
6
+
7
+ from itertools import permutations, product
8
+
9
+ import pytest
10
+ from pytest import param
11
+
12
+ import numpy as np
13
+ from numpy.core._rational_tests import rational
14
+ from numpy.core._multiarray_umath import _discover_array_parameters
15
+
16
+ from numpy.testing import (
17
+ assert_array_equal, assert_warns, IS_PYPY)
18
+
19
+
20
+ def arraylikes():
21
+ """
22
+ Generator for functions converting an array into various array-likes.
23
+ If full is True (default) it includes array-likes not capable of handling
24
+ all dtypes.
25
+ """
26
+ # base array:
27
+ def ndarray(a):
28
+ return a
29
+
30
+ yield param(ndarray, id="ndarray")
31
+
32
+ # subclass:
33
+ class MyArr(np.ndarray):
34
+ pass
35
+
36
+ def subclass(a):
37
+ return a.view(MyArr)
38
+
39
+ yield subclass
40
+
41
+ class _SequenceLike():
42
+ # Older NumPy versions, sometimes cared whether a protocol array was
43
+ # also _SequenceLike. This shouldn't matter, but keep it for now
44
+ # for __array__ and not the others.
45
+ def __len__(self):
46
+ raise TypeError
47
+
48
+ def __getitem__(self):
49
+ raise TypeError
50
+
51
+ # Array-interface
52
+ class ArrayDunder(_SequenceLike):
53
+ def __init__(self, a):
54
+ self.a = a
55
+
56
+ def __array__(self, dtype=None):
57
+ return self.a
58
+
59
+ yield param(ArrayDunder, id="__array__")
60
+
61
+ # memory-view
62
+ yield param(memoryview, id="memoryview")
63
+
64
+ # Array-interface
65
+ class ArrayInterface:
66
+ def __init__(self, a):
67
+ self.a = a # need to hold on to keep interface valid
68
+ self.__array_interface__ = a.__array_interface__
69
+
70
+ yield param(ArrayInterface, id="__array_interface__")
71
+
72
+ # Array-Struct
73
+ class ArrayStruct:
74
+ def __init__(self, a):
75
+ self.a = a # need to hold on to keep struct valid
76
+ self.__array_struct__ = a.__array_struct__
77
+
78
+ yield param(ArrayStruct, id="__array_struct__")
79
+
80
+
81
+ def scalar_instances(times=True, extended_precision=True, user_dtype=True):
82
+ # Hard-coded list of scalar instances.
83
+ # Floats:
84
+ yield param(np.sqrt(np.float16(5)), id="float16")
85
+ yield param(np.sqrt(np.float32(5)), id="float32")
86
+ yield param(np.sqrt(np.float64(5)), id="float64")
87
+ if extended_precision:
88
+ yield param(np.sqrt(np.longdouble(5)), id="longdouble")
89
+
90
+ # Complex:
91
+ yield param(np.sqrt(np.complex64(2+3j)), id="complex64")
92
+ yield param(np.sqrt(np.complex128(2+3j)), id="complex128")
93
+ if extended_precision:
94
+ yield param(np.sqrt(np.longcomplex(2+3j)), id="clongdouble")
95
+
96
+ # Bool:
97
+ # XFAIL: Bool should be added, but has some bad properties when it
98
+ # comes to strings, see also gh-9875
99
+ # yield param(np.bool_(0), id="bool")
100
+
101
+ # Integers:
102
+ yield param(np.int8(2), id="int8")
103
+ yield param(np.int16(2), id="int16")
104
+ yield param(np.int32(2), id="int32")
105
+ yield param(np.int64(2), id="int64")
106
+
107
+ yield param(np.uint8(2), id="uint8")
108
+ yield param(np.uint16(2), id="uint16")
109
+ yield param(np.uint32(2), id="uint32")
110
+ yield param(np.uint64(2), id="uint64")
111
+
112
+ # Rational:
113
+ if user_dtype:
114
+ yield param(rational(1, 2), id="rational")
115
+
116
+ # Cannot create a structured void scalar directly:
117
+ structured = np.array([(1, 3)], "i,i")[0]
118
+ assert isinstance(structured, np.void)
119
+ assert structured.dtype == np.dtype("i,i")
120
+ yield param(structured, id="structured")
121
+
122
+ if times:
123
+ # Datetimes and timedelta
124
+ yield param(np.timedelta64(2), id="timedelta64[generic]")
125
+ yield param(np.timedelta64(23, "s"), id="timedelta64[s]")
126
+ yield param(np.timedelta64("NaT", "s"), id="timedelta64[s](NaT)")
127
+
128
+ yield param(np.datetime64("NaT"), id="datetime64[generic](NaT)")
129
+ yield param(np.datetime64("2020-06-07 12:43", "ms"), id="datetime64[ms]")
130
+
131
+ # Strings and unstructured void:
132
+ yield param(np.bytes_(b"1234"), id="bytes")
133
+ yield param(np.str_("2345"), id="unicode")
134
+ yield param(np.void(b"4321"), id="unstructured_void")
135
+
136
+
137
+ def is_parametric_dtype(dtype):
138
+ """Returns True if the dtype is a parametric legacy dtype (itemsize
139
+ is 0, or a datetime without units)
140
+ """
141
+ if dtype.itemsize == 0:
142
+ return True
143
+ if issubclass(dtype.type, (np.datetime64, np.timedelta64)):
144
+ if dtype.name.endswith("64"):
145
+ # Generic time units
146
+ return True
147
+ return False
148
+
149
+
150
+ class TestStringDiscovery:
151
+ @pytest.mark.parametrize("obj",
152
+ [object(), 1.2, 10**43, None, "string"],
153
+ ids=["object", "1.2", "10**43", "None", "string"])
154
+ def test_basic_stringlength(self, obj):
155
+ length = len(str(obj))
156
+ expected = np.dtype(f"S{length}")
157
+
158
+ assert np.array(obj, dtype="S").dtype == expected
159
+ assert np.array([obj], dtype="S").dtype == expected
160
+
161
+ # A nested array is also discovered correctly
162
+ arr = np.array(obj, dtype="O")
163
+ assert np.array(arr, dtype="S").dtype == expected
164
+ # Also if we use the dtype class
165
+ assert np.array(arr, dtype=type(expected)).dtype == expected
166
+ # Check that .astype() behaves identical
167
+ assert arr.astype("S").dtype == expected
168
+ # The DType class is accepted by `.astype()`
169
+ assert arr.astype(type(np.dtype("S"))).dtype == expected
170
+
171
+ @pytest.mark.parametrize("obj",
172
+ [object(), 1.2, 10**43, None, "string"],
173
+ ids=["object", "1.2", "10**43", "None", "string"])
174
+ def test_nested_arrays_stringlength(self, obj):
175
+ length = len(str(obj))
176
+ expected = np.dtype(f"S{length}")
177
+ arr = np.array(obj, dtype="O")
178
+ assert np.array([arr, arr], dtype="S").dtype == expected
179
+
180
+ @pytest.mark.parametrize("arraylike", arraylikes())
181
+ def test_unpack_first_level(self, arraylike):
182
+ # We unpack exactly one level of array likes
183
+ obj = np.array([None])
184
+ obj[0] = np.array(1.2)
185
+ # the length of the included item, not of the float dtype
186
+ length = len(str(obj[0]))
187
+ expected = np.dtype(f"S{length}")
188
+
189
+ obj = arraylike(obj)
190
+ # casting to string usually calls str(obj)
191
+ arr = np.array([obj], dtype="S")
192
+ assert arr.shape == (1, 1)
193
+ assert arr.dtype == expected
194
+
195
+
196
+ class TestScalarDiscovery:
197
+ def test_void_special_case(self):
198
+ # Void dtypes with structures discover tuples as elements
199
+ arr = np.array((1, 2, 3), dtype="i,i,i")
200
+ assert arr.shape == ()
201
+ arr = np.array([(1, 2, 3)], dtype="i,i,i")
202
+ assert arr.shape == (1,)
203
+
204
+ def test_char_special_case(self):
205
+ arr = np.array("string", dtype="c")
206
+ assert arr.shape == (6,)
207
+ assert arr.dtype.char == "c"
208
+ arr = np.array(["string"], dtype="c")
209
+ assert arr.shape == (1, 6)
210
+ assert arr.dtype.char == "c"
211
+
212
+ def test_char_special_case_deep(self):
213
+ # Check that the character special case errors correctly if the
214
+ # array is too deep:
215
+ nested = ["string"] # 2 dimensions (due to string being sequence)
216
+ for i in range(np.MAXDIMS - 2):
217
+ nested = [nested]
218
+
219
+ arr = np.array(nested, dtype='c')
220
+ assert arr.shape == (1,) * (np.MAXDIMS - 1) + (6,)
221
+ with pytest.raises(ValueError):
222
+ np.array([nested], dtype="c")
223
+
224
+ def test_unknown_object(self):
225
+ arr = np.array(object())
226
+ assert arr.shape == ()
227
+ assert arr.dtype == np.dtype("O")
228
+
229
+ @pytest.mark.parametrize("scalar", scalar_instances())
230
+ def test_scalar(self, scalar):
231
+ arr = np.array(scalar)
232
+ assert arr.shape == ()
233
+ assert arr.dtype == scalar.dtype
234
+
235
+ arr = np.array([[scalar, scalar]])
236
+ assert arr.shape == (1, 2)
237
+ assert arr.dtype == scalar.dtype
238
+
239
+ # Additionally to string this test also runs into a corner case
240
+ # with datetime promotion (the difference is the promotion order).
241
+ @pytest.mark.filterwarnings("ignore:Promotion of numbers:FutureWarning")
242
+ def test_scalar_promotion(self):
243
+ for sc1, sc2 in product(scalar_instances(), scalar_instances()):
244
+ sc1, sc2 = sc1.values[0], sc2.values[0]
245
+ # test all combinations:
246
+ try:
247
+ arr = np.array([sc1, sc2])
248
+ except (TypeError, ValueError):
249
+ # The promotion between two times can fail
250
+ # XFAIL (ValueError): Some object casts are currently undefined
251
+ continue
252
+ assert arr.shape == (2,)
253
+ try:
254
+ dt1, dt2 = sc1.dtype, sc2.dtype
255
+ expected_dtype = np.promote_types(dt1, dt2)
256
+ assert arr.dtype == expected_dtype
257
+ except TypeError as e:
258
+ # Will currently always go to object dtype
259
+ assert arr.dtype == np.dtype("O")
260
+
261
+ @pytest.mark.parametrize("scalar", scalar_instances())
262
+ def test_scalar_coercion(self, scalar):
263
+ # This tests various scalar coercion paths, mainly for the numerical
264
+ # types. It includes some paths not directly related to `np.array`.
265
+ if isinstance(scalar, np.inexact):
266
+ # Ensure we have a full-precision number if available
267
+ scalar = type(scalar)((scalar * 2)**0.5)
268
+
269
+ if type(scalar) is rational:
270
+ # Rational generally fails due to a missing cast. In the future
271
+ # object casts should automatically be defined based on `setitem`.
272
+ pytest.xfail("Rational to object cast is undefined currently.")
273
+
274
+ # Use casting from object:
275
+ arr = np.array(scalar, dtype=object).astype(scalar.dtype)
276
+
277
+ # Test various ways to create an array containing this scalar:
278
+ arr1 = np.array(scalar).reshape(1)
279
+ arr2 = np.array([scalar])
280
+ arr3 = np.empty(1, dtype=scalar.dtype)
281
+ arr3[0] = scalar
282
+ arr4 = np.empty(1, dtype=scalar.dtype)
283
+ arr4[:] = [scalar]
284
+ # All of these methods should yield the same results
285
+ assert_array_equal(arr, arr1)
286
+ assert_array_equal(arr, arr2)
287
+ assert_array_equal(arr, arr3)
288
+ assert_array_equal(arr, arr4)
289
+
290
+ @pytest.mark.xfail(IS_PYPY, reason="`int(np.complex128(3))` fails on PyPy")
291
+ @pytest.mark.filterwarnings("ignore::numpy.ComplexWarning")
292
+ @pytest.mark.parametrize("cast_to", scalar_instances())
293
+ def test_scalar_coercion_same_as_cast_and_assignment(self, cast_to):
294
+ """
295
+ Test that in most cases:
296
+ * `np.array(scalar, dtype=dtype)`
297
+ * `np.empty((), dtype=dtype)[()] = scalar`
298
+ * `np.array(scalar).astype(dtype)`
299
+ should behave the same. The only exceptions are parametric dtypes
300
+ (mainly datetime/timedelta without unit) and void without fields.
301
+ """
302
+ dtype = cast_to.dtype # use to parametrize only the target dtype
303
+
304
+ for scalar in scalar_instances(times=False):
305
+ scalar = scalar.values[0]
306
+
307
+ if dtype.type == np.void:
308
+ if scalar.dtype.fields is not None and dtype.fields is None:
309
+ # Here, coercion to "V6" works, but the cast fails.
310
+ # Since the types are identical, SETITEM takes care of
311
+ # this, but has different rules than the cast.
312
+ with pytest.raises(TypeError):
313
+ np.array(scalar).astype(dtype)
314
+ np.array(scalar, dtype=dtype)
315
+ np.array([scalar], dtype=dtype)
316
+ continue
317
+
318
+ # The main test, we first try to use casting and if it succeeds
319
+ # continue below testing that things are the same, otherwise
320
+ # test that the alternative paths at least also fail.
321
+ try:
322
+ cast = np.array(scalar).astype(dtype)
323
+ except (TypeError, ValueError, RuntimeError):
324
+ # coercion should also raise (error type may change)
325
+ with pytest.raises(Exception):
326
+ np.array(scalar, dtype=dtype)
327
+
328
+ if (isinstance(scalar, rational) and
329
+ np.issubdtype(dtype, np.signedinteger)):
330
+ return
331
+
332
+ with pytest.raises(Exception):
333
+ np.array([scalar], dtype=dtype)
334
+ # assignment should also raise
335
+ res = np.zeros((), dtype=dtype)
336
+ with pytest.raises(Exception):
337
+ res[()] = scalar
338
+
339
+ return
340
+
341
+ # Non error path:
342
+ arr = np.array(scalar, dtype=dtype)
343
+ assert_array_equal(arr, cast)
344
+ # assignment behaves the same
345
+ ass = np.zeros((), dtype=dtype)
346
+ ass[()] = scalar
347
+ assert_array_equal(ass, cast)
348
+
349
+ @pytest.mark.parametrize("pyscalar", [10, 10.32, 10.14j, 10**100])
350
+ def test_pyscalar_subclasses(self, pyscalar):
351
+ """NumPy arrays are read/write which means that anything but invariant
352
+ behaviour is on thin ice. However, we currently are happy to discover
353
+ subclasses of Python float, int, complex the same as the base classes.
354
+ This should potentially be deprecated.
355
+ """
356
+ class MyScalar(type(pyscalar)):
357
+ pass
358
+
359
+ res = np.array(MyScalar(pyscalar))
360
+ expected = np.array(pyscalar)
361
+ assert_array_equal(res, expected)
362
+
363
+ @pytest.mark.parametrize("dtype_char", np.typecodes["All"])
364
+ def test_default_dtype_instance(self, dtype_char):
365
+ if dtype_char in "SU":
366
+ dtype = np.dtype(dtype_char + "1")
367
+ elif dtype_char == "V":
368
+ # Legacy behaviour was to use V8. The reason was float64 being the
369
+ # default dtype and that having 8 bytes.
370
+ dtype = np.dtype("V8")
371
+ else:
372
+ dtype = np.dtype(dtype_char)
373
+
374
+ discovered_dtype, _ = _discover_array_parameters([], type(dtype))
375
+
376
+ assert discovered_dtype == dtype
377
+ assert discovered_dtype.itemsize == dtype.itemsize
378
+
379
+ @pytest.mark.parametrize("dtype", np.typecodes["Integer"])
380
+ @pytest.mark.parametrize(["scalar", "error"],
381
+ [(np.float64(np.nan), ValueError),
382
+ (np.array(-1).astype(np.ulonglong)[()], OverflowError)])
383
+ def test_scalar_to_int_coerce_does_not_cast(self, dtype, scalar, error):
384
+ """
385
+ Signed integers are currently different in that they do not cast other
386
+ NumPy scalar, but instead use scalar.__int__(). The hardcoded
387
+ exception to this rule is `np.array(scalar, dtype=integer)`.
388
+ """
389
+ dtype = np.dtype(dtype)
390
+
391
+ # This is a special case using casting logic. It warns for the NaN
392
+ # but allows the cast (giving undefined behaviour).
393
+ with np.errstate(invalid="ignore"):
394
+ coerced = np.array(scalar, dtype=dtype)
395
+ cast = np.array(scalar).astype(dtype)
396
+ assert_array_equal(coerced, cast)
397
+
398
+ # However these fail:
399
+ with pytest.raises(error):
400
+ np.array([scalar], dtype=dtype)
401
+ with pytest.raises(error):
402
+ cast[()] = scalar
403
+
404
+
405
+ class TestTimeScalars:
406
+ @pytest.mark.parametrize("dtype", [np.int64, np.float32])
407
+ @pytest.mark.parametrize("scalar",
408
+ [param(np.timedelta64("NaT", "s"), id="timedelta64[s](NaT)"),
409
+ param(np.timedelta64(123, "s"), id="timedelta64[s]"),
410
+ param(np.datetime64("NaT", "generic"), id="datetime64[generic](NaT)"),
411
+ param(np.datetime64(1, "D"), id="datetime64[D]")],)
412
+ def test_coercion_basic(self, dtype, scalar):
413
+ # Note the `[scalar]` is there because np.array(scalar) uses stricter
414
+ # `scalar.__int__()` rules for backward compatibility right now.
415
+ arr = np.array(scalar, dtype=dtype)
416
+ cast = np.array(scalar).astype(dtype)
417
+ assert_array_equal(arr, cast)
418
+
419
+ ass = np.ones((), dtype=dtype)
420
+ if issubclass(dtype, np.integer):
421
+ with pytest.raises(TypeError):
422
+ # raises, as would np.array([scalar], dtype=dtype), this is
423
+ # conversion from times, but behaviour of integers.
424
+ ass[()] = scalar
425
+ else:
426
+ ass[()] = scalar
427
+ assert_array_equal(ass, cast)
428
+
429
+ @pytest.mark.parametrize("dtype", [np.int64, np.float32])
430
+ @pytest.mark.parametrize("scalar",
431
+ [param(np.timedelta64(123, "ns"), id="timedelta64[ns]"),
432
+ param(np.timedelta64(12, "generic"), id="timedelta64[generic]")])
433
+ def test_coercion_timedelta_convert_to_number(self, dtype, scalar):
434
+ # Only "ns" and "generic" timedeltas can be converted to numbers
435
+ # so these are slightly special.
436
+ arr = np.array(scalar, dtype=dtype)
437
+ cast = np.array(scalar).astype(dtype)
438
+ ass = np.ones((), dtype=dtype)
439
+ ass[()] = scalar # raises, as would np.array([scalar], dtype=dtype)
440
+
441
+ assert_array_equal(arr, cast)
442
+ assert_array_equal(cast, cast)
443
+
444
+ @pytest.mark.parametrize("dtype", ["S6", "U6"])
445
+ @pytest.mark.parametrize(["val", "unit"],
446
+ [param(123, "s", id="[s]"), param(123, "D", id="[D]")])
447
+ def test_coercion_assignment_datetime(self, val, unit, dtype):
448
+ # String from datetime64 assignment is currently special cased to
449
+ # never use casting. This is because casting will error in this
450
+ # case, and traditionally in most cases the behaviour is maintained
451
+ # like this. (`np.array(scalar, dtype="U6")` would have failed before)
452
+ # TODO: This discrepancy _should_ be resolved, either by relaxing the
453
+ # cast, or by deprecating the first part.
454
+ scalar = np.datetime64(val, unit)
455
+ dtype = np.dtype(dtype)
456
+ cut_string = dtype.type(str(scalar)[:6])
457
+
458
+ arr = np.array(scalar, dtype=dtype)
459
+ assert arr[()] == cut_string
460
+ ass = np.ones((), dtype=dtype)
461
+ ass[()] = scalar
462
+ assert ass[()] == cut_string
463
+
464
+ with pytest.raises(RuntimeError):
465
+ # However, unlike the above assignment using `str(scalar)[:6]`
466
+ # due to being handled by the string DType and not be casting
467
+ # the explicit cast fails:
468
+ np.array(scalar).astype(dtype)
469
+
470
+
471
+ @pytest.mark.parametrize(["val", "unit"],
472
+ [param(123, "s", id="[s]"), param(123, "D", id="[D]")])
473
+ def test_coercion_assignment_timedelta(self, val, unit):
474
+ scalar = np.timedelta64(val, unit)
475
+
476
+ # Unlike datetime64, timedelta allows the unsafe cast:
477
+ np.array(scalar, dtype="S6")
478
+ cast = np.array(scalar).astype("S6")
479
+ ass = np.ones((), dtype="S6")
480
+ ass[()] = scalar
481
+ expected = scalar.astype("S")[:6]
482
+ assert cast[()] == expected
483
+ assert ass[()] == expected
484
+
485
+ class TestNested:
486
+ def test_nested_simple(self):
487
+ initial = [1.2]
488
+ nested = initial
489
+ for i in range(np.MAXDIMS - 1):
490
+ nested = [nested]
491
+
492
+ arr = np.array(nested, dtype="float64")
493
+ assert arr.shape == (1,) * np.MAXDIMS
494
+ with pytest.raises(ValueError):
495
+ np.array([nested], dtype="float64")
496
+
497
+ with pytest.raises(ValueError, match=".*would exceed the maximum"):
498
+ np.array([nested]) # user must ask for `object` explicitly
499
+
500
+ arr = np.array([nested], dtype=object)
501
+ assert arr.dtype == np.dtype("O")
502
+ assert arr.shape == (1,) * np.MAXDIMS
503
+ assert arr.item() is initial
504
+
505
+ def test_pathological_self_containing(self):
506
+ # Test that this also works for two nested sequences
507
+ l = []
508
+ l.append(l)
509
+ arr = np.array([l, l, l], dtype=object)
510
+ assert arr.shape == (3,) + (1,) * (np.MAXDIMS - 1)
511
+
512
+ # Also check a ragged case:
513
+ arr = np.array([l, [None], l], dtype=object)
514
+ assert arr.shape == (3, 1)
515
+
516
+ @pytest.mark.parametrize("arraylike", arraylikes())
517
+ def test_nested_arraylikes(self, arraylike):
518
+ # We try storing an array like into an array, but the array-like
519
+ # will have too many dimensions. This means the shape discovery
520
+ # decides that the array-like must be treated as an object (a special
521
+ # case of ragged discovery). The result will be an array with one
522
+ # dimension less than the maximum dimensions, and the array being
523
+ # assigned to it (which does work for object or if `float(arraylike)`
524
+ # works).
525
+ initial = arraylike(np.ones((1, 1)))
526
+
527
+ nested = initial
528
+ for i in range(np.MAXDIMS - 1):
529
+ nested = [nested]
530
+
531
+ with pytest.raises(ValueError, match=".*would exceed the maximum"):
532
+ # It will refuse to assign the array into
533
+ np.array(nested, dtype="float64")
534
+
535
+ # If this is object, we end up assigning a (1, 1) array into (1,)
536
+ # (due to running out of dimensions), this is currently supported but
537
+ # a special case which is not ideal.
538
+ arr = np.array(nested, dtype=object)
539
+ assert arr.shape == (1,) * np.MAXDIMS
540
+ assert arr.item() == np.array(initial).item()
541
+
542
+ @pytest.mark.parametrize("arraylike", arraylikes())
543
+ def test_uneven_depth_ragged(self, arraylike):
544
+ arr = np.arange(4).reshape((2, 2))
545
+ arr = arraylike(arr)
546
+
547
+ # Array is ragged in the second dimension already:
548
+ out = np.array([arr, [arr]], dtype=object)
549
+ assert out.shape == (2,)
550
+ assert out[0] is arr
551
+ assert type(out[1]) is list
552
+
553
+ # Array is ragged in the third dimension:
554
+ with pytest.raises(ValueError):
555
+ # This is a broadcast error during assignment, because
556
+ # the array shape would be (2, 2, 2) but `arr[0, 0] = arr` fails.
557
+ np.array([arr, [arr, arr]], dtype=object)
558
+
559
+ def test_empty_sequence(self):
560
+ arr = np.array([[], [1], [[1]]], dtype=object)
561
+ assert arr.shape == (3,)
562
+
563
+ # The empty sequence stops further dimension discovery, so the
564
+ # result shape will be (0,) which leads to an error during:
565
+ with pytest.raises(ValueError):
566
+ np.array([[], np.empty((0, 1))], dtype=object)
567
+
568
+ def test_array_of_different_depths(self):
569
+ # When multiple arrays (or array-likes) are included in a
570
+ # sequences and have different depth, we currently discover
571
+ # as many dimensions as they share. (see also gh-17224)
572
+ arr = np.zeros((3, 2))
573
+ mismatch_first_dim = np.zeros((1, 2))
574
+ mismatch_second_dim = np.zeros((3, 3))
575
+
576
+ dtype, shape = _discover_array_parameters(
577
+ [arr, mismatch_second_dim], dtype=np.dtype("O"))
578
+ assert shape == (2, 3)
579
+
580
+ dtype, shape = _discover_array_parameters(
581
+ [arr, mismatch_first_dim], dtype=np.dtype("O"))
582
+ assert shape == (2,)
583
+ # The second case is currently supported because the arrays
584
+ # can be stored as objects:
585
+ res = np.asarray([arr, mismatch_first_dim], dtype=np.dtype("O"))
586
+ assert res[0] is arr
587
+ assert res[1] is mismatch_first_dim
588
+
589
+
590
+ class TestBadSequences:
591
+ # These are tests for bad objects passed into `np.array`, in general
592
+ # these have undefined behaviour. In the old code they partially worked
593
+ # when now they will fail. We could (and maybe should) create a copy
594
+ # of all sequences to be safe against bad-actors.
595
+
596
+ def test_growing_list(self):
597
+ # List to coerce, `mylist` will append to it during coercion
598
+ obj = []
599
+ class mylist(list):
600
+ def __len__(self):
601
+ obj.append([1, 2])
602
+ return super().__len__()
603
+
604
+ obj.append(mylist([1, 2]))
605
+
606
+ with pytest.raises(RuntimeError):
607
+ np.array(obj)
608
+
609
+ # Note: We do not test a shrinking list. These do very evil things
610
+ # and the only way to fix them would be to copy all sequences.
611
+ # (which may be a real option in the future).
612
+
613
+ def test_mutated_list(self):
614
+ # List to coerce, `mylist` will mutate the first element
615
+ obj = []
616
+ class mylist(list):
617
+ def __len__(self):
618
+ obj[0] = [2, 3] # replace with a different list.
619
+ return super().__len__()
620
+
621
+ obj.append([2, 3])
622
+ obj.append(mylist([1, 2]))
623
+ # Does not crash:
624
+ np.array(obj)
625
+
626
+ def test_replace_0d_array(self):
627
+ # List to coerce, `mylist` will mutate the first element
628
+ obj = []
629
+ class baditem:
630
+ def __len__(self):
631
+ obj[0][0] = 2 # replace with a different list.
632
+ raise ValueError("not actually a sequence!")
633
+
634
+ def __getitem__(self):
635
+ pass
636
+
637
+ # Runs into a corner case in the new code, the `array(2)` is cached
638
+ # so replacing it invalidates the cache.
639
+ obj.append([np.array(2), baditem()])
640
+ with pytest.raises(RuntimeError):
641
+ np.array(obj)
642
+
643
+
644
+ class TestArrayLikes:
645
+ @pytest.mark.parametrize("arraylike", arraylikes())
646
+ def test_0d_object_special_case(self, arraylike):
647
+ arr = np.array(0.)
648
+ obj = arraylike(arr)
649
+ # A single array-like is always converted:
650
+ res = np.array(obj, dtype=object)
651
+ assert_array_equal(arr, res)
652
+
653
+ # But a single 0-D nested array-like never:
654
+ res = np.array([obj], dtype=object)
655
+ assert res[0] is obj
656
+
657
+ @pytest.mark.parametrize("arraylike", arraylikes())
658
+ @pytest.mark.parametrize("arr", [np.array(0.), np.arange(4)])
659
+ def test_object_assignment_special_case(self, arraylike, arr):
660
+ obj = arraylike(arr)
661
+ empty = np.arange(1, dtype=object)
662
+ empty[:] = [obj]
663
+ assert empty[0] is obj
664
+
665
+ def test_0d_generic_special_case(self):
666
+ class ArraySubclass(np.ndarray):
667
+ def __float__(self):
668
+ raise TypeError("e.g. quantities raise on this")
669
+
670
+ arr = np.array(0.)
671
+ obj = arr.view(ArraySubclass)
672
+ res = np.array(obj)
673
+ # The subclass is simply cast:
674
+ assert_array_equal(arr, res)
675
+
676
+ # If the 0-D array-like is included, __float__ is currently
677
+ # guaranteed to be used. We may want to change that, quantities
678
+ # and masked arrays half make use of this.
679
+ with pytest.raises(TypeError):
680
+ np.array([obj])
681
+
682
+ # The same holds for memoryview:
683
+ obj = memoryview(arr)
684
+ res = np.array(obj)
685
+ assert_array_equal(arr, res)
686
+ with pytest.raises(ValueError):
687
+ # The error type does not matter much here.
688
+ np.array([obj])
689
+
690
+ def test_arraylike_classes(self):
691
+ # The classes of array-likes should generally be acceptable to be
692
+ # stored inside a numpy (object) array. This tests all of the
693
+ # special attributes (since all are checked during coercion).
694
+ arr = np.array(np.int64)
695
+ assert arr[()] is np.int64
696
+ arr = np.array([np.int64])
697
+ assert arr[0] is np.int64
698
+
699
+ # This also works for properties/unbound methods:
700
+ class ArrayLike:
701
+ @property
702
+ def __array_interface__(self):
703
+ pass
704
+
705
+ @property
706
+ def __array_struct__(self):
707
+ pass
708
+
709
+ def __array__(self):
710
+ pass
711
+
712
+ arr = np.array(ArrayLike)
713
+ assert arr[()] is ArrayLike
714
+ arr = np.array([ArrayLike])
715
+ assert arr[0] is ArrayLike
716
+
717
+ @pytest.mark.skipif(
718
+ np.dtype(np.intp).itemsize < 8, reason="Needs 64bit platform")
719
+ def test_too_large_array_error_paths(self):
720
+ """Test the error paths, including for memory leaks"""
721
+ arr = np.array(0, dtype="uint8")
722
+ # Guarantees that a contiguous copy won't work:
723
+ arr = np.broadcast_to(arr, 2**62)
724
+
725
+ for i in range(5):
726
+ # repeat, to ensure caching cannot have an effect:
727
+ with pytest.raises(MemoryError):
728
+ np.array(arr)
729
+ with pytest.raises(MemoryError):
730
+ np.array([arr])
731
+
732
+ @pytest.mark.parametrize("attribute",
733
+ ["__array_interface__", "__array__", "__array_struct__"])
734
+ @pytest.mark.parametrize("error", [RecursionError, MemoryError])
735
+ def test_bad_array_like_attributes(self, attribute, error):
736
+ # RecursionError and MemoryError are considered fatal. All errors
737
+ # (except AttributeError) should probably be raised in the future,
738
+ # but shapely made use of it, so it will require a deprecation.
739
+
740
+ class BadInterface:
741
+ def __getattr__(self, attr):
742
+ if attr == attribute:
743
+ raise error
744
+ super().__getattr__(attr)
745
+
746
+ with pytest.raises(error):
747
+ np.array(BadInterface())
748
+
749
+ @pytest.mark.parametrize("error", [RecursionError, MemoryError])
750
+ def test_bad_array_like_bad_length(self, error):
751
+ # RecursionError and MemoryError are considered "critical" in
752
+ # sequences. We could expand this more generally though. (NumPy 1.20)
753
+ class BadSequence:
754
+ def __len__(self):
755
+ raise error
756
+ def __getitem__(self):
757
+ # must have getitem to be a Sequence
758
+ return 1
759
+
760
+ with pytest.raises(error):
761
+ np.array(BadSequence())
762
+
763
+
764
+ class TestAsArray:
765
+ """Test expected behaviors of ``asarray``."""
766
+
767
+ def test_dtype_identity(self):
768
+ """Confirm the intended behavior for *dtype* kwarg.
769
+
770
+ The result of ``asarray()`` should have the dtype provided through the
771
+ keyword argument, when used. This forces unique array handles to be
772
+ produced for unique np.dtype objects, but (for equivalent dtypes), the
773
+ underlying data (the base object) is shared with the original array
774
+ object.
775
+
776
+ Ref https://github.com/numpy/numpy/issues/1468
777
+ """
778
+ int_array = np.array([1, 2, 3], dtype='i')
779
+ assert np.asarray(int_array) is int_array
780
+
781
+ # The character code resolves to the singleton dtype object provided
782
+ # by the numpy package.
783
+ assert np.asarray(int_array, dtype='i') is int_array
784
+
785
+ # Derive a dtype from n.dtype('i'), but add a metadata object to force
786
+ # the dtype to be distinct.
787
+ unequal_type = np.dtype('i', metadata={'spam': True})
788
+ annotated_int_array = np.asarray(int_array, dtype=unequal_type)
789
+ assert annotated_int_array is not int_array
790
+ assert annotated_int_array.base is int_array
791
+ # Create an equivalent descriptor with a new and distinct dtype
792
+ # instance.
793
+ equivalent_requirement = np.dtype('i', metadata={'spam': True})
794
+ annotated_int_array_alt = np.asarray(annotated_int_array,
795
+ dtype=equivalent_requirement)
796
+ assert unequal_type == equivalent_requirement
797
+ assert unequal_type is not equivalent_requirement
798
+ assert annotated_int_array_alt is not annotated_int_array
799
+ assert annotated_int_array_alt.dtype is equivalent_requirement
800
+
801
+ # Check the same logic for a pair of C types whose equivalence may vary
802
+ # between computing environments.
803
+ # Find an equivalent pair.
804
+ integer_type_codes = ('i', 'l', 'q')
805
+ integer_dtypes = [np.dtype(code) for code in integer_type_codes]
806
+ typeA = None
807
+ typeB = None
808
+ for typeA, typeB in permutations(integer_dtypes, r=2):
809
+ if typeA == typeB:
810
+ assert typeA is not typeB
811
+ break
812
+ assert isinstance(typeA, np.dtype) and isinstance(typeB, np.dtype)
813
+
814
+ # These ``asarray()`` calls may produce a new view or a copy,
815
+ # but never the same object.
816
+ long_int_array = np.asarray(int_array, dtype='l')
817
+ long_long_int_array = np.asarray(int_array, dtype='q')
818
+ assert long_int_array is not int_array
819
+ assert long_long_int_array is not int_array
820
+ assert np.asarray(long_int_array, dtype='q') is not long_int_array
821
+ array_a = np.asarray(int_array, dtype=typeA)
822
+ assert typeA == typeB
823
+ assert typeA is not typeB
824
+ assert array_a.dtype is typeA
825
+ assert array_a is not np.asarray(array_a, dtype=typeB)
826
+ assert np.asarray(array_a, dtype=typeB).dtype is typeB
827
+ assert array_a is np.asarray(array_a, dtype=typeB).base
828
+
829
+
830
+ class TestSpecialAttributeLookupFailure:
831
+ # An exception was raised while fetching the attribute
832
+
833
+ class WeirdArrayLike:
834
+ @property
835
+ def __array__(self):
836
+ raise RuntimeError("oops!")
837
+
838
+ class WeirdArrayInterface:
839
+ @property
840
+ def __array_interface__(self):
841
+ raise RuntimeError("oops!")
842
+
843
+ def test_deprecated(self):
844
+ with pytest.raises(RuntimeError):
845
+ np.array(self.WeirdArrayLike())
846
+ with pytest.raises(RuntimeError):
847
+ np.array(self.WeirdArrayInterface())
848
+
849
+
850
+ def test_subarray_from_array_construction():
851
+ # Arrays are more complex, since they "broadcast" on success:
852
+ arr = np.array([1, 2])
853
+
854
+ res = arr.astype("(2)i,")
855
+ assert_array_equal(res, [[1, 1], [2, 2]])
856
+
857
+ res = np.array(arr, dtype="(2)i,")
858
+
859
+ assert_array_equal(res, [[1, 1], [2, 2]])
860
+
861
+ res = np.array([[(1,), (2,)], arr], dtype="(2)i,")
862
+ assert_array_equal(res, [[[1, 1], [2, 2]], [[1, 1], [2, 2]]])
863
+
864
+ # Also try a multi-dimensional example:
865
+ arr = np.arange(5 * 2).reshape(5, 2)
866
+ expected = np.broadcast_to(arr[:, :, np.newaxis, np.newaxis], (5, 2, 2, 2))
867
+
868
+ res = arr.astype("(2,2)f")
869
+ assert_array_equal(res, expected)
870
+
871
+ res = np.array(arr, dtype="(2,2)f")
872
+ assert_array_equal(res, expected)
873
+
874
+
875
+ def test_empty_string():
876
+ # Empty strings are unfortunately often converted to S1 and we need to
877
+ # make sure we are filling the S1 and not the (possibly) detected S0
878
+ # result. This should likely just return S0 and if not maybe the decision
879
+ # to return S1 should be moved.
880
+ res = np.array([""] * 10, dtype="S")
881
+ assert_array_equal(res, np.array("\0", "S1"))
882
+ assert res.dtype == "S1"
883
+
884
+ arr = np.array([""] * 10, dtype=object)
885
+
886
+ res = arr.astype("S")
887
+ assert_array_equal(res, b"")
888
+ assert res.dtype == "S1"
889
+
890
+ res = np.array(arr, dtype="S")
891
+ assert_array_equal(res, b"")
892
+ # TODO: This is arguably weird/wrong, but seems old:
893
+ assert res.dtype == f"S{np.dtype('O').itemsize}"
894
+
895
+ res = np.array([[""] * 10, arr], dtype="S")
896
+ assert_array_equal(res, b"")
897
+ assert res.shape == (2, 10)
898
+ assert res.dtype == "S1"
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_custom_dtypes.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_array_equal
5
+ from numpy.core._multiarray_umath import (
6
+ _discover_array_parameters as discover_array_params, _get_sfloat_dtype)
7
+
8
+
9
+ SF = _get_sfloat_dtype()
10
+
11
+
12
+ class TestSFloat:
13
+ def _get_array(self, scaling, aligned=True):
14
+ if not aligned:
15
+ a = np.empty(3*8 + 1, dtype=np.uint8)[1:]
16
+ a = a.view(np.float64)
17
+ a[:] = [1., 2., 3.]
18
+ else:
19
+ a = np.array([1., 2., 3.])
20
+
21
+ a *= 1./scaling # the casting code also uses the reciprocal.
22
+ return a.view(SF(scaling))
23
+
24
+ def test_sfloat_rescaled(self):
25
+ sf = SF(1.)
26
+ sf2 = sf.scaled_by(2.)
27
+ assert sf2.get_scaling() == 2.
28
+ sf6 = sf2.scaled_by(3.)
29
+ assert sf6.get_scaling() == 6.
30
+
31
+ def test_class_discovery(self):
32
+ # This does not test much, since we always discover the scaling as 1.
33
+ # But most of NumPy (when writing) does not understand DType classes
34
+ dt, _ = discover_array_params([1., 2., 3.], dtype=SF)
35
+ assert dt == SF(1.)
36
+
37
+ @pytest.mark.parametrize("scaling", [1., -1., 2.])
38
+ def test_scaled_float_from_floats(self, scaling):
39
+ a = np.array([1., 2., 3.], dtype=SF(scaling))
40
+
41
+ assert a.dtype.get_scaling() == scaling
42
+ assert_array_equal(scaling * a.view(np.float64), [1., 2., 3.])
43
+
44
+ def test_repr(self):
45
+ # Check the repr, mainly to cover the code paths:
46
+ assert repr(SF(scaling=1.)) == "_ScaledFloatTestDType(scaling=1.0)"
47
+
48
+ def test_dtype_name(self):
49
+ assert SF(1.).name == "_ScaledFloatTestDType64"
50
+
51
+ @pytest.mark.parametrize("scaling", [1., -1., 2.])
52
+ def test_sfloat_from_float(self, scaling):
53
+ a = np.array([1., 2., 3.]).astype(dtype=SF(scaling))
54
+
55
+ assert a.dtype.get_scaling() == scaling
56
+ assert_array_equal(scaling * a.view(np.float64), [1., 2., 3.])
57
+
58
+ @pytest.mark.parametrize("aligned", [True, False])
59
+ @pytest.mark.parametrize("scaling", [1., -1., 2.])
60
+ def test_sfloat_getitem(self, aligned, scaling):
61
+ a = self._get_array(1., aligned)
62
+ assert a.tolist() == [1., 2., 3.]
63
+
64
+ @pytest.mark.parametrize("aligned", [True, False])
65
+ def test_sfloat_casts(self, aligned):
66
+ a = self._get_array(1., aligned)
67
+
68
+ assert np.can_cast(a, SF(-1.), casting="equiv")
69
+ assert not np.can_cast(a, SF(-1.), casting="no")
70
+ na = a.astype(SF(-1.))
71
+ assert_array_equal(-1 * na.view(np.float64), a.view(np.float64))
72
+
73
+ assert np.can_cast(a, SF(2.), casting="same_kind")
74
+ assert not np.can_cast(a, SF(2.), casting="safe")
75
+ a2 = a.astype(SF(2.))
76
+ assert_array_equal(2 * a2.view(np.float64), a.view(np.float64))
77
+
78
+ @pytest.mark.parametrize("aligned", [True, False])
79
+ def test_sfloat_cast_internal_errors(self, aligned):
80
+ a = self._get_array(2e300, aligned)
81
+
82
+ with pytest.raises(TypeError,
83
+ match="error raised inside the core-loop: non-finite factor!"):
84
+ a.astype(SF(2e-300))
85
+
86
+ def test_sfloat_promotion(self):
87
+ assert np.result_type(SF(2.), SF(3.)) == SF(3.)
88
+ assert np.result_type(SF(3.), SF(2.)) == SF(3.)
89
+ # Float64 -> SF(1.) and then promotes normally, so both of this work:
90
+ assert np.result_type(SF(3.), np.float64) == SF(3.)
91
+ assert np.result_type(np.float64, SF(0.5)) == SF(1.)
92
+
93
+ # Test an undefined promotion:
94
+ with pytest.raises(TypeError):
95
+ np.result_type(SF(1.), np.int64)
96
+
97
+ def test_basic_multiply(self):
98
+ a = self._get_array(2.)
99
+ b = self._get_array(4.)
100
+
101
+ res = a * b
102
+ # multiplies dtype scaling and content separately:
103
+ assert res.dtype.get_scaling() == 8.
104
+ expected_view = a.view(np.float64) * b.view(np.float64)
105
+ assert_array_equal(res.view(np.float64), expected_view)
106
+
107
+ def test_possible_and_impossible_reduce(self):
108
+ # For reductions to work, the first and last operand must have the
109
+ # same dtype. For this parametric DType that is not necessarily true.
110
+ a = self._get_array(2.)
111
+ # Addition reductin works (as of writing requires to pass initial
112
+ # because setting a scaled-float from the default `0` fails).
113
+ res = np.add.reduce(a, initial=0.)
114
+ assert res == a.astype(np.float64).sum()
115
+
116
+ # But each multiplication changes the factor, so a reduction is not
117
+ # possible (the relaxed version of the old refusal to handle any
118
+ # flexible dtype).
119
+ with pytest.raises(TypeError,
120
+ match="the resolved dtypes are not compatible"):
121
+ np.multiply.reduce(a)
122
+
123
+ def test_basic_ufunc_at(self):
124
+ float_a = np.array([1., 2., 3.])
125
+ b = self._get_array(2.)
126
+
127
+ float_b = b.view(np.float64).copy()
128
+ np.multiply.at(float_b, [1, 1, 1], float_a)
129
+ np.multiply.at(b, [1, 1, 1], float_a)
130
+
131
+ assert_array_equal(b.view(np.float64), float_b)
132
+
133
+ def test_basic_multiply_promotion(self):
134
+ float_a = np.array([1., 2., 3.])
135
+ b = self._get_array(2.)
136
+
137
+ res1 = float_a * b
138
+ res2 = b * float_a
139
+
140
+ # one factor is one, so we get the factor of b:
141
+ assert res1.dtype == res2.dtype == b.dtype
142
+ expected_view = float_a * b.view(np.float64)
143
+ assert_array_equal(res1.view(np.float64), expected_view)
144
+ assert_array_equal(res2.view(np.float64), expected_view)
145
+
146
+ # Check that promotion works when `out` is used:
147
+ np.multiply(b, float_a, out=res2)
148
+ with pytest.raises(TypeError):
149
+ # The promoter accepts this (maybe it should not), but the SFloat
150
+ # result cannot be cast to integer:
151
+ np.multiply(b, float_a, out=np.arange(3))
152
+
153
+ def test_basic_addition(self):
154
+ a = self._get_array(2.)
155
+ b = self._get_array(4.)
156
+
157
+ res = a + b
158
+ # addition uses the type promotion rules for the result:
159
+ assert res.dtype == np.result_type(a.dtype, b.dtype)
160
+ expected_view = (a.astype(res.dtype).view(np.float64) +
161
+ b.astype(res.dtype).view(np.float64))
162
+ assert_array_equal(res.view(np.float64), expected_view)
163
+
164
+ def test_addition_cast_safety(self):
165
+ """The addition method is special for the scaled float, because it
166
+ includes the "cast" between different factors, thus cast-safety
167
+ is influenced by the implementation.
168
+ """
169
+ a = self._get_array(2.)
170
+ b = self._get_array(-2.)
171
+ c = self._get_array(3.)
172
+
173
+ # sign change is "equiv":
174
+ np.add(a, b, casting="equiv")
175
+ with pytest.raises(TypeError):
176
+ np.add(a, b, casting="no")
177
+
178
+ # Different factor is "same_kind" (default) so check that "safe" fails
179
+ with pytest.raises(TypeError):
180
+ np.add(a, c, casting="safe")
181
+
182
+ # Check that casting the output fails also (done by the ufunc here)
183
+ with pytest.raises(TypeError):
184
+ np.add(a, a, out=c, casting="safe")
185
+
186
+ @pytest.mark.parametrize("ufunc",
187
+ [np.logical_and, np.logical_or, np.logical_xor])
188
+ def test_logical_ufuncs_casts_to_bool(self, ufunc):
189
+ a = self._get_array(2.)
190
+ a[0] = 0. # make sure first element is considered False.
191
+
192
+ float_equiv = a.astype(float)
193
+ expected = ufunc(float_equiv, float_equiv)
194
+ res = ufunc(a, a)
195
+ assert_array_equal(res, expected)
196
+
197
+ # also check that the same works for reductions:
198
+ expected = ufunc.reduce(float_equiv)
199
+ res = ufunc.reduce(a)
200
+ assert_array_equal(res, expected)
201
+
202
+ # The output casting does not match the bool, bool -> bool loop:
203
+ with pytest.raises(TypeError):
204
+ ufunc(a, a, out=np.empty(a.shape, dtype=int), casting="equiv")
205
+
206
+ def test_wrapped_and_wrapped_reductions(self):
207
+ a = self._get_array(2.)
208
+ float_equiv = a.astype(float)
209
+
210
+ expected = np.hypot(float_equiv, float_equiv)
211
+ res = np.hypot(a, a)
212
+ assert res.dtype == a.dtype
213
+ res_float = res.view(np.float64) * 2
214
+ assert_array_equal(res_float, expected)
215
+
216
+ # Also check reduction (keepdims, due to incorrect getitem)
217
+ res = np.hypot.reduce(a, keepdims=True)
218
+ assert res.dtype == a.dtype
219
+ expected = np.hypot.reduce(float_equiv, keepdims=True)
220
+ assert res.view(np.float64) * 2 == expected
221
+
222
+ def test_astype_class(self):
223
+ # Very simple test that we accept `.astype()` also on the class.
224
+ # ScaledFloat always returns the default descriptor, but it does
225
+ # check the relevant code paths.
226
+ arr = np.array([1., 2., 3.], dtype=object)
227
+
228
+ res = arr.astype(SF) # passing the class class
229
+ expected = arr.astype(SF(1.)) # above will have discovered 1. scaling
230
+ assert_array_equal(res.view(np.float64), expected.view(np.float64))
231
+
232
+ def test_creation_class(self):
233
+ arr1 = np.array([1., 2., 3.], dtype=SF)
234
+ assert arr1.dtype == SF(1.)
235
+ arr2 = np.array([1., 2., 3.], dtype=SF(1.))
236
+ assert_array_equal(arr1.view(np.float64), arr2.view(np.float64))
237
+
238
+
239
+ def test_type_pickle():
240
+ # can't actually unpickle, but we can pickle (if in namespace)
241
+ import pickle
242
+
243
+ np._ScaledFloatTestDType = SF
244
+
245
+ s = pickle.dumps(SF)
246
+ res = pickle.loads(s)
247
+ assert res is SF
248
+
249
+ del np._ScaledFloatTestDType
250
+
251
+
252
+ def test_is_numeric():
253
+ assert SF._is_numeric
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_function_base.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from numpy import (
3
+ logspace, linspace, geomspace, dtype, array, sctypes, arange, isnan,
4
+ ndarray, sqrt, nextafter, stack, errstate
5
+ )
6
+ from numpy.testing import (
7
+ assert_, assert_equal, assert_raises, assert_array_equal, assert_allclose,
8
+ )
9
+
10
+
11
+ class PhysicalQuantity(float):
12
+ def __new__(cls, value):
13
+ return float.__new__(cls, value)
14
+
15
+ def __add__(self, x):
16
+ assert_(isinstance(x, PhysicalQuantity))
17
+ return PhysicalQuantity(float(x) + float(self))
18
+ __radd__ = __add__
19
+
20
+ def __sub__(self, x):
21
+ assert_(isinstance(x, PhysicalQuantity))
22
+ return PhysicalQuantity(float(self) - float(x))
23
+
24
+ def __rsub__(self, x):
25
+ assert_(isinstance(x, PhysicalQuantity))
26
+ return PhysicalQuantity(float(x) - float(self))
27
+
28
+ def __mul__(self, x):
29
+ return PhysicalQuantity(float(x) * float(self))
30
+ __rmul__ = __mul__
31
+
32
+ def __div__(self, x):
33
+ return PhysicalQuantity(float(self) / float(x))
34
+
35
+ def __rdiv__(self, x):
36
+ return PhysicalQuantity(float(x) / float(self))
37
+
38
+
39
+ class PhysicalQuantity2(ndarray):
40
+ __array_priority__ = 10
41
+
42
+
43
+ class TestLogspace:
44
+
45
+ def test_basic(self):
46
+ y = logspace(0, 6)
47
+ assert_(len(y) == 50)
48
+ y = logspace(0, 6, num=100)
49
+ assert_(y[-1] == 10 ** 6)
50
+ y = logspace(0, 6, endpoint=False)
51
+ assert_(y[-1] < 10 ** 6)
52
+ y = logspace(0, 6, num=7)
53
+ assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6])
54
+
55
+ def test_start_stop_array(self):
56
+ start = array([0., 1.])
57
+ stop = array([6., 7.])
58
+ t1 = logspace(start, stop, 6)
59
+ t2 = stack([logspace(_start, _stop, 6)
60
+ for _start, _stop in zip(start, stop)], axis=1)
61
+ assert_equal(t1, t2)
62
+ t3 = logspace(start, stop[0], 6)
63
+ t4 = stack([logspace(_start, stop[0], 6)
64
+ for _start in start], axis=1)
65
+ assert_equal(t3, t4)
66
+ t5 = logspace(start, stop, 6, axis=-1)
67
+ assert_equal(t5, t2.T)
68
+
69
+ @pytest.mark.parametrize("axis", [0, 1, -1])
70
+ def test_base_array(self, axis: int):
71
+ start = 1
72
+ stop = 2
73
+ num = 6
74
+ base = array([1, 2])
75
+ t1 = logspace(start, stop, num=num, base=base, axis=axis)
76
+ t2 = stack(
77
+ [logspace(start, stop, num=num, base=_base) for _base in base],
78
+ axis=(axis + 1) % t1.ndim,
79
+ )
80
+ assert_equal(t1, t2)
81
+
82
+ @pytest.mark.parametrize("axis", [0, 1, -1])
83
+ def test_stop_base_array(self, axis: int):
84
+ start = 1
85
+ stop = array([2, 3])
86
+ num = 6
87
+ base = array([1, 2])
88
+ t1 = logspace(start, stop, num=num, base=base, axis=axis)
89
+ t2 = stack(
90
+ [logspace(start, _stop, num=num, base=_base)
91
+ for _stop, _base in zip(stop, base)],
92
+ axis=(axis + 1) % t1.ndim,
93
+ )
94
+ assert_equal(t1, t2)
95
+
96
+ def test_dtype(self):
97
+ y = logspace(0, 6, dtype='float32')
98
+ assert_equal(y.dtype, dtype('float32'))
99
+ y = logspace(0, 6, dtype='float64')
100
+ assert_equal(y.dtype, dtype('float64'))
101
+ y = logspace(0, 6, dtype='int32')
102
+ assert_equal(y.dtype, dtype('int32'))
103
+
104
+ def test_physical_quantities(self):
105
+ a = PhysicalQuantity(1.0)
106
+ b = PhysicalQuantity(5.0)
107
+ assert_equal(logspace(a, b), logspace(1.0, 5.0))
108
+
109
+ def test_subclass(self):
110
+ a = array(1).view(PhysicalQuantity2)
111
+ b = array(7).view(PhysicalQuantity2)
112
+ ls = logspace(a, b)
113
+ assert type(ls) is PhysicalQuantity2
114
+ assert_equal(ls, logspace(1.0, 7.0))
115
+ ls = logspace(a, b, 1)
116
+ assert type(ls) is PhysicalQuantity2
117
+ assert_equal(ls, logspace(1.0, 7.0, 1))
118
+
119
+
120
+ class TestGeomspace:
121
+
122
+ def test_basic(self):
123
+ y = geomspace(1, 1e6)
124
+ assert_(len(y) == 50)
125
+ y = geomspace(1, 1e6, num=100)
126
+ assert_(y[-1] == 10 ** 6)
127
+ y = geomspace(1, 1e6, endpoint=False)
128
+ assert_(y[-1] < 10 ** 6)
129
+ y = geomspace(1, 1e6, num=7)
130
+ assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6])
131
+
132
+ y = geomspace(8, 2, num=3)
133
+ assert_allclose(y, [8, 4, 2])
134
+ assert_array_equal(y.imag, 0)
135
+
136
+ y = geomspace(-1, -100, num=3)
137
+ assert_array_equal(y, [-1, -10, -100])
138
+ assert_array_equal(y.imag, 0)
139
+
140
+ y = geomspace(-100, -1, num=3)
141
+ assert_array_equal(y, [-100, -10, -1])
142
+ assert_array_equal(y.imag, 0)
143
+
144
+ def test_boundaries_match_start_and_stop_exactly(self):
145
+ # make sure that the boundaries of the returned array exactly
146
+ # equal 'start' and 'stop' - this isn't obvious because
147
+ # np.exp(np.log(x)) isn't necessarily exactly equal to x
148
+ start = 0.3
149
+ stop = 20.3
150
+
151
+ y = geomspace(start, stop, num=1)
152
+ assert_equal(y[0], start)
153
+
154
+ y = geomspace(start, stop, num=1, endpoint=False)
155
+ assert_equal(y[0], start)
156
+
157
+ y = geomspace(start, stop, num=3)
158
+ assert_equal(y[0], start)
159
+ assert_equal(y[-1], stop)
160
+
161
+ y = geomspace(start, stop, num=3, endpoint=False)
162
+ assert_equal(y[0], start)
163
+
164
+ def test_nan_interior(self):
165
+ with errstate(invalid='ignore'):
166
+ y = geomspace(-3, 3, num=4)
167
+
168
+ assert_equal(y[0], -3.0)
169
+ assert_(isnan(y[1:-1]).all())
170
+ assert_equal(y[3], 3.0)
171
+
172
+ with errstate(invalid='ignore'):
173
+ y = geomspace(-3, 3, num=4, endpoint=False)
174
+
175
+ assert_equal(y[0], -3.0)
176
+ assert_(isnan(y[1:]).all())
177
+
178
+ def test_complex(self):
179
+ # Purely imaginary
180
+ y = geomspace(1j, 16j, num=5)
181
+ assert_allclose(y, [1j, 2j, 4j, 8j, 16j])
182
+ assert_array_equal(y.real, 0)
183
+
184
+ y = geomspace(-4j, -324j, num=5)
185
+ assert_allclose(y, [-4j, -12j, -36j, -108j, -324j])
186
+ assert_array_equal(y.real, 0)
187
+
188
+ y = geomspace(1+1j, 1000+1000j, num=4)
189
+ assert_allclose(y, [1+1j, 10+10j, 100+100j, 1000+1000j])
190
+
191
+ y = geomspace(-1+1j, -1000+1000j, num=4)
192
+ assert_allclose(y, [-1+1j, -10+10j, -100+100j, -1000+1000j])
193
+
194
+ # Logarithmic spirals
195
+ y = geomspace(-1, 1, num=3, dtype=complex)
196
+ assert_allclose(y, [-1, 1j, +1])
197
+
198
+ y = geomspace(0+3j, -3+0j, 3)
199
+ assert_allclose(y, [0+3j, -3/sqrt(2)+3j/sqrt(2), -3+0j])
200
+ y = geomspace(0+3j, 3+0j, 3)
201
+ assert_allclose(y, [0+3j, 3/sqrt(2)+3j/sqrt(2), 3+0j])
202
+ y = geomspace(-3+0j, 0-3j, 3)
203
+ assert_allclose(y, [-3+0j, -3/sqrt(2)-3j/sqrt(2), 0-3j])
204
+ y = geomspace(0+3j, -3+0j, 3)
205
+ assert_allclose(y, [0+3j, -3/sqrt(2)+3j/sqrt(2), -3+0j])
206
+ y = geomspace(-2-3j, 5+7j, 7)
207
+ assert_allclose(y, [-2-3j, -0.29058977-4.15771027j,
208
+ 2.08885354-4.34146838j, 4.58345529-3.16355218j,
209
+ 6.41401745-0.55233457j, 6.75707386+3.11795092j,
210
+ 5+7j])
211
+
212
+ # Type promotion should prevent the -5 from becoming a NaN
213
+ y = geomspace(3j, -5, 2)
214
+ assert_allclose(y, [3j, -5])
215
+ y = geomspace(-5, 3j, 2)
216
+ assert_allclose(y, [-5, 3j])
217
+
218
+ def test_dtype(self):
219
+ y = geomspace(1, 1e6, dtype='float32')
220
+ assert_equal(y.dtype, dtype('float32'))
221
+ y = geomspace(1, 1e6, dtype='float64')
222
+ assert_equal(y.dtype, dtype('float64'))
223
+ y = geomspace(1, 1e6, dtype='int32')
224
+ assert_equal(y.dtype, dtype('int32'))
225
+
226
+ # Native types
227
+ y = geomspace(1, 1e6, dtype=float)
228
+ assert_equal(y.dtype, dtype('float_'))
229
+ y = geomspace(1, 1e6, dtype=complex)
230
+ assert_equal(y.dtype, dtype('complex'))
231
+
232
+ def test_start_stop_array_scalar(self):
233
+ lim1 = array([120, 100], dtype="int8")
234
+ lim2 = array([-120, -100], dtype="int8")
235
+ lim3 = array([1200, 1000], dtype="uint16")
236
+ t1 = geomspace(lim1[0], lim1[1], 5)
237
+ t2 = geomspace(lim2[0], lim2[1], 5)
238
+ t3 = geomspace(lim3[0], lim3[1], 5)
239
+ t4 = geomspace(120.0, 100.0, 5)
240
+ t5 = geomspace(-120.0, -100.0, 5)
241
+ t6 = geomspace(1200.0, 1000.0, 5)
242
+
243
+ # t3 uses float32, t6 uses float64
244
+ assert_allclose(t1, t4, rtol=1e-2)
245
+ assert_allclose(t2, t5, rtol=1e-2)
246
+ assert_allclose(t3, t6, rtol=1e-5)
247
+
248
+ def test_start_stop_array(self):
249
+ # Try to use all special cases.
250
+ start = array([1.e0, 32., 1j, -4j, 1+1j, -1])
251
+ stop = array([1.e4, 2., 16j, -324j, 10000+10000j, 1])
252
+ t1 = geomspace(start, stop, 5)
253
+ t2 = stack([geomspace(_start, _stop, 5)
254
+ for _start, _stop in zip(start, stop)], axis=1)
255
+ assert_equal(t1, t2)
256
+ t3 = geomspace(start, stop[0], 5)
257
+ t4 = stack([geomspace(_start, stop[0], 5)
258
+ for _start in start], axis=1)
259
+ assert_equal(t3, t4)
260
+ t5 = geomspace(start, stop, 5, axis=-1)
261
+ assert_equal(t5, t2.T)
262
+
263
+ def test_physical_quantities(self):
264
+ a = PhysicalQuantity(1.0)
265
+ b = PhysicalQuantity(5.0)
266
+ assert_equal(geomspace(a, b), geomspace(1.0, 5.0))
267
+
268
+ def test_subclass(self):
269
+ a = array(1).view(PhysicalQuantity2)
270
+ b = array(7).view(PhysicalQuantity2)
271
+ gs = geomspace(a, b)
272
+ assert type(gs) is PhysicalQuantity2
273
+ assert_equal(gs, geomspace(1.0, 7.0))
274
+ gs = geomspace(a, b, 1)
275
+ assert type(gs) is PhysicalQuantity2
276
+ assert_equal(gs, geomspace(1.0, 7.0, 1))
277
+
278
+ def test_bounds(self):
279
+ assert_raises(ValueError, geomspace, 0, 10)
280
+ assert_raises(ValueError, geomspace, 10, 0)
281
+ assert_raises(ValueError, geomspace, 0, 0)
282
+
283
+
284
+ class TestLinspace:
285
+
286
+ def test_basic(self):
287
+ y = linspace(0, 10)
288
+ assert_(len(y) == 50)
289
+ y = linspace(2, 10, num=100)
290
+ assert_(y[-1] == 10)
291
+ y = linspace(2, 10, endpoint=False)
292
+ assert_(y[-1] < 10)
293
+ assert_raises(ValueError, linspace, 0, 10, num=-1)
294
+
295
+ def test_corner(self):
296
+ y = list(linspace(0, 1, 1))
297
+ assert_(y == [0.0], y)
298
+ assert_raises(TypeError, linspace, 0, 1, num=2.5)
299
+
300
+ def test_type(self):
301
+ t1 = linspace(0, 1, 0).dtype
302
+ t2 = linspace(0, 1, 1).dtype
303
+ t3 = linspace(0, 1, 2).dtype
304
+ assert_equal(t1, t2)
305
+ assert_equal(t2, t3)
306
+
307
+ def test_dtype(self):
308
+ y = linspace(0, 6, dtype='float32')
309
+ assert_equal(y.dtype, dtype('float32'))
310
+ y = linspace(0, 6, dtype='float64')
311
+ assert_equal(y.dtype, dtype('float64'))
312
+ y = linspace(0, 6, dtype='int32')
313
+ assert_equal(y.dtype, dtype('int32'))
314
+
315
+ def test_start_stop_array_scalar(self):
316
+ lim1 = array([-120, 100], dtype="int8")
317
+ lim2 = array([120, -100], dtype="int8")
318
+ lim3 = array([1200, 1000], dtype="uint16")
319
+ t1 = linspace(lim1[0], lim1[1], 5)
320
+ t2 = linspace(lim2[0], lim2[1], 5)
321
+ t3 = linspace(lim3[0], lim3[1], 5)
322
+ t4 = linspace(-120.0, 100.0, 5)
323
+ t5 = linspace(120.0, -100.0, 5)
324
+ t6 = linspace(1200.0, 1000.0, 5)
325
+ assert_equal(t1, t4)
326
+ assert_equal(t2, t5)
327
+ assert_equal(t3, t6)
328
+
329
+ def test_start_stop_array(self):
330
+ start = array([-120, 120], dtype="int8")
331
+ stop = array([100, -100], dtype="int8")
332
+ t1 = linspace(start, stop, 5)
333
+ t2 = stack([linspace(_start, _stop, 5)
334
+ for _start, _stop in zip(start, stop)], axis=1)
335
+ assert_equal(t1, t2)
336
+ t3 = linspace(start, stop[0], 5)
337
+ t4 = stack([linspace(_start, stop[0], 5)
338
+ for _start in start], axis=1)
339
+ assert_equal(t3, t4)
340
+ t5 = linspace(start, stop, 5, axis=-1)
341
+ assert_equal(t5, t2.T)
342
+
343
+ def test_complex(self):
344
+ lim1 = linspace(1 + 2j, 3 + 4j, 5)
345
+ t1 = array([1.0+2.j, 1.5+2.5j, 2.0+3j, 2.5+3.5j, 3.0+4j])
346
+ lim2 = linspace(1j, 10, 5)
347
+ t2 = array([0.0+1.j, 2.5+0.75j, 5.0+0.5j, 7.5+0.25j, 10.0+0j])
348
+ assert_equal(lim1, t1)
349
+ assert_equal(lim2, t2)
350
+
351
+ def test_physical_quantities(self):
352
+ a = PhysicalQuantity(0.0)
353
+ b = PhysicalQuantity(1.0)
354
+ assert_equal(linspace(a, b), linspace(0.0, 1.0))
355
+
356
+ def test_subclass(self):
357
+ a = array(0).view(PhysicalQuantity2)
358
+ b = array(1).view(PhysicalQuantity2)
359
+ ls = linspace(a, b)
360
+ assert type(ls) is PhysicalQuantity2
361
+ assert_equal(ls, linspace(0.0, 1.0))
362
+ ls = linspace(a, b, 1)
363
+ assert type(ls) is PhysicalQuantity2
364
+ assert_equal(ls, linspace(0.0, 1.0, 1))
365
+
366
+ def test_array_interface(self):
367
+ # Regression test for https://github.com/numpy/numpy/pull/6659
368
+ # Ensure that start/stop can be objects that implement
369
+ # __array_interface__ and are convertible to numeric scalars
370
+
371
+ class Arrayish:
372
+ """
373
+ A generic object that supports the __array_interface__ and hence
374
+ can in principle be converted to a numeric scalar, but is not
375
+ otherwise recognized as numeric, but also happens to support
376
+ multiplication by floats.
377
+
378
+ Data should be an object that implements the buffer interface,
379
+ and contains at least 4 bytes.
380
+ """
381
+
382
+ def __init__(self, data):
383
+ self._data = data
384
+
385
+ @property
386
+ def __array_interface__(self):
387
+ return {'shape': (), 'typestr': '<i4', 'data': self._data,
388
+ 'version': 3}
389
+
390
+ def __mul__(self, other):
391
+ # For the purposes of this test any multiplication is an
392
+ # identity operation :)
393
+ return self
394
+
395
+ one = Arrayish(array(1, dtype='<i4'))
396
+ five = Arrayish(array(5, dtype='<i4'))
397
+
398
+ assert_equal(linspace(one, five), linspace(1, 5))
399
+
400
+ def test_denormal_numbers(self):
401
+ # Regression test for gh-5437. Will probably fail when compiled
402
+ # with ICC, which flushes denormals to zero
403
+ for ftype in sctypes['float']:
404
+ stop = nextafter(ftype(0), ftype(1)) * 5 # A denormal number
405
+ assert_(any(linspace(0, stop, 10, endpoint=False, dtype=ftype)))
406
+
407
+ def test_equivalent_to_arange(self):
408
+ for j in range(1000):
409
+ assert_equal(linspace(0, j, j+1, dtype=int),
410
+ arange(j+1, dtype=int))
411
+
412
+ def test_retstep(self):
413
+ for num in [0, 1, 2]:
414
+ for ept in [False, True]:
415
+ y = linspace(0, 1, num, endpoint=ept, retstep=True)
416
+ assert isinstance(y, tuple) and len(y) == 2
417
+ if num == 2:
418
+ y0_expect = [0.0, 1.0] if ept else [0.0, 0.5]
419
+ assert_array_equal(y[0], y0_expect)
420
+ assert_equal(y[1], y0_expect[1])
421
+ elif num == 1 and not ept:
422
+ assert_array_equal(y[0], [0.0])
423
+ assert_equal(y[1], 1.0)
424
+ else:
425
+ assert_array_equal(y[0], [0.0][:num])
426
+ assert isnan(y[1])
427
+
428
+ def test_object(self):
429
+ start = array(1, dtype='O')
430
+ stop = array(2, dtype='O')
431
+ y = linspace(start, stop, 3)
432
+ assert_array_equal(y, array([1., 1.5, 2.]))
433
+
434
+ def test_round_negative(self):
435
+ y = linspace(-1, 3, num=8, dtype=int)
436
+ t = array([-1, -1, 0, 0, 1, 1, 2, 3], dtype=int)
437
+ assert_array_equal(y, t)
438
+
439
+ def test_any_step_zero_and_not_mult_inplace(self):
440
+ # any_step_zero is True, _mult_inplace is False
441
+ start = array([0.0, 1.0])
442
+ stop = array([2.0, 1.0])
443
+ y = linspace(start, stop, 3)
444
+ assert_array_equal(y, array([[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]))
445
+
446
+
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_getlimits.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test functions for limits module.
2
+
3
+ """
4
+ import warnings
5
+ import numpy as np
6
+ import pytest
7
+ from numpy.core import finfo, iinfo
8
+ from numpy import half, single, double, longdouble
9
+ from numpy.testing import assert_equal, assert_, assert_raises
10
+ from numpy.core.getlimits import _discovered_machar, _float_ma
11
+
12
+ ##################################################
13
+
14
+ class TestPythonFloat:
15
+ def test_singleton(self):
16
+ ftype = finfo(float)
17
+ ftype2 = finfo(float)
18
+ assert_equal(id(ftype), id(ftype2))
19
+
20
+ class TestHalf:
21
+ def test_singleton(self):
22
+ ftype = finfo(half)
23
+ ftype2 = finfo(half)
24
+ assert_equal(id(ftype), id(ftype2))
25
+
26
+ class TestSingle:
27
+ def test_singleton(self):
28
+ ftype = finfo(single)
29
+ ftype2 = finfo(single)
30
+ assert_equal(id(ftype), id(ftype2))
31
+
32
+ class TestDouble:
33
+ def test_singleton(self):
34
+ ftype = finfo(double)
35
+ ftype2 = finfo(double)
36
+ assert_equal(id(ftype), id(ftype2))
37
+
38
+ class TestLongdouble:
39
+ def test_singleton(self):
40
+ ftype = finfo(longdouble)
41
+ ftype2 = finfo(longdouble)
42
+ assert_equal(id(ftype), id(ftype2))
43
+
44
+ def assert_finfo_equal(f1, f2):
45
+ # assert two finfo instances have the same attributes
46
+ for attr in ('bits', 'eps', 'epsneg', 'iexp', 'machep',
47
+ 'max', 'maxexp', 'min', 'minexp', 'negep', 'nexp',
48
+ 'nmant', 'precision', 'resolution', 'tiny',
49
+ 'smallest_normal', 'smallest_subnormal'):
50
+ assert_equal(getattr(f1, attr), getattr(f2, attr),
51
+ f'finfo instances {f1} and {f2} differ on {attr}')
52
+
53
+ def assert_iinfo_equal(i1, i2):
54
+ # assert two iinfo instances have the same attributes
55
+ for attr in ('bits', 'min', 'max'):
56
+ assert_equal(getattr(i1, attr), getattr(i2, attr),
57
+ f'iinfo instances {i1} and {i2} differ on {attr}')
58
+
59
+ class TestFinfo:
60
+ def test_basic(self):
61
+ dts = list(zip(['f2', 'f4', 'f8', 'c8', 'c16'],
62
+ [np.float16, np.float32, np.float64, np.complex64,
63
+ np.complex128]))
64
+ for dt1, dt2 in dts:
65
+ assert_finfo_equal(finfo(dt1), finfo(dt2))
66
+
67
+ assert_raises(ValueError, finfo, 'i4')
68
+
69
+ def test_regression_gh23108(self):
70
+ # np.float32(1.0) and np.float64(1.0) have the same hash and are
71
+ # equal under the == operator
72
+ f1 = np.finfo(np.float32(1.0))
73
+ f2 = np.finfo(np.float64(1.0))
74
+ assert f1 != f2
75
+
76
+ def test_regression_gh23867(self):
77
+ class NonHashableWithDtype:
78
+ __hash__ = None
79
+ dtype = np.dtype('float32')
80
+
81
+ x = NonHashableWithDtype()
82
+ assert np.finfo(x) == np.finfo(x.dtype)
83
+
84
+
85
+ class TestIinfo:
86
+ def test_basic(self):
87
+ dts = list(zip(['i1', 'i2', 'i4', 'i8',
88
+ 'u1', 'u2', 'u4', 'u8'],
89
+ [np.int8, np.int16, np.int32, np.int64,
90
+ np.uint8, np.uint16, np.uint32, np.uint64]))
91
+ for dt1, dt2 in dts:
92
+ assert_iinfo_equal(iinfo(dt1), iinfo(dt2))
93
+
94
+ assert_raises(ValueError, iinfo, 'f4')
95
+
96
+ def test_unsigned_max(self):
97
+ types = np.sctypes['uint']
98
+ for T in types:
99
+ with np.errstate(over="ignore"):
100
+ max_calculated = T(0) - T(1)
101
+ assert_equal(iinfo(T).max, max_calculated)
102
+
103
+ class TestRepr:
104
+ def test_iinfo_repr(self):
105
+ expected = "iinfo(min=-32768, max=32767, dtype=int16)"
106
+ assert_equal(repr(np.iinfo(np.int16)), expected)
107
+
108
+ def test_finfo_repr(self):
109
+ expected = "finfo(resolution=1e-06, min=-3.4028235e+38," + \
110
+ " max=3.4028235e+38, dtype=float32)"
111
+ assert_equal(repr(np.finfo(np.float32)), expected)
112
+
113
+
114
+ def test_instances():
115
+ # Test the finfo and iinfo results on numeric instances agree with
116
+ # the results on the corresponding types
117
+
118
+ for c in [int, np.int16, np.int32, np.int64]:
119
+ class_iinfo = iinfo(c)
120
+ instance_iinfo = iinfo(c(12))
121
+
122
+ assert_iinfo_equal(class_iinfo, instance_iinfo)
123
+
124
+ for c in [float, np.float16, np.float32, np.float64]:
125
+ class_finfo = finfo(c)
126
+ instance_finfo = finfo(c(1.2))
127
+ assert_finfo_equal(class_finfo, instance_finfo)
128
+
129
+ with pytest.raises(ValueError):
130
+ iinfo(10.)
131
+
132
+ with pytest.raises(ValueError):
133
+ iinfo('hi')
134
+
135
+ with pytest.raises(ValueError):
136
+ finfo(np.int64(1))
137
+
138
+
139
+ def assert_ma_equal(discovered, ma_like):
140
+ # Check MachAr-like objects same as calculated MachAr instances
141
+ for key, value in discovered.__dict__.items():
142
+ assert_equal(value, getattr(ma_like, key))
143
+ if hasattr(value, 'shape'):
144
+ assert_equal(value.shape, getattr(ma_like, key).shape)
145
+ assert_equal(value.dtype, getattr(ma_like, key).dtype)
146
+
147
+
148
+ def test_known_types():
149
+ # Test we are correctly compiling parameters for known types
150
+ for ftype, ma_like in ((np.float16, _float_ma[16]),
151
+ (np.float32, _float_ma[32]),
152
+ (np.float64, _float_ma[64])):
153
+ assert_ma_equal(_discovered_machar(ftype), ma_like)
154
+ # Suppress warning for broken discovery of double double on PPC
155
+ with np.errstate(all='ignore'):
156
+ ld_ma = _discovered_machar(np.longdouble)
157
+ bytes = np.dtype(np.longdouble).itemsize
158
+ if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
159
+ # 80-bit extended precision
160
+ assert_ma_equal(ld_ma, _float_ma[80])
161
+ elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
162
+ # IEE 754 128-bit
163
+ assert_ma_equal(ld_ma, _float_ma[128])
164
+
165
+
166
+ def test_subnormal_warning():
167
+ """Test that the subnormal is zero warning is not being raised."""
168
+ with np.errstate(all='ignore'):
169
+ ld_ma = _discovered_machar(np.longdouble)
170
+ bytes = np.dtype(np.longdouble).itemsize
171
+ with warnings.catch_warnings(record=True) as w:
172
+ warnings.simplefilter('always')
173
+ if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
174
+ # 80-bit extended precision
175
+ ld_ma.smallest_subnormal
176
+ assert len(w) == 0
177
+ elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
178
+ # IEE 754 128-bit
179
+ ld_ma.smallest_subnormal
180
+ assert len(w) == 0
181
+ else:
182
+ # Double double
183
+ ld_ma.smallest_subnormal
184
+ # This test may fail on some platforms
185
+ assert len(w) == 0
186
+
187
+
188
+ def test_plausible_finfo():
189
+ # Assert that finfo returns reasonable results for all types
190
+ for ftype in np.sctypes['float'] + np.sctypes['complex']:
191
+ info = np.finfo(ftype)
192
+ assert_(info.nmant > 1)
193
+ assert_(info.minexp < -1)
194
+ assert_(info.maxexp > 1)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_hashtable.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import random
4
+ from numpy.core._multiarray_tests import identityhash_tester
5
+
6
+
7
+ @pytest.mark.parametrize("key_length", [1, 3, 6])
8
+ @pytest.mark.parametrize("length", [1, 16, 2000])
9
+ def test_identity_hashtable(key_length, length):
10
+ # use a 30 object pool for everything (duplicates will happen)
11
+ pool = [object() for i in range(20)]
12
+ keys_vals = []
13
+ for i in range(length):
14
+ keys = tuple(random.choices(pool, k=key_length))
15
+ keys_vals.append((keys, random.choice(pool)))
16
+
17
+ dictionary = dict(keys_vals)
18
+
19
+ # add a random item at the end:
20
+ keys_vals.append(random.choice(keys_vals))
21
+ # the expected one could be different with duplicates:
22
+ expected = dictionary[keys_vals[-1][0]]
23
+
24
+ res = identityhash_tester(key_length, keys_vals, replace=True)
25
+ assert res is expected
26
+
27
+ # check that ensuring one duplicate definitely raises:
28
+ keys_vals.insert(0, keys_vals[-2])
29
+ with pytest.raises(RuntimeError):
30
+ identityhash_tester(key_length, keys_vals)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_indexing.py ADDED
@@ -0,0 +1,1417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import warnings
3
+ import functools
4
+ import operator
5
+
6
+ import pytest
7
+
8
+ import numpy as np
9
+ from numpy.core._multiarray_tests import array_indexing
10
+ from itertools import product
11
+ from numpy.testing import (
12
+ assert_, assert_equal, assert_raises, assert_raises_regex,
13
+ assert_array_equal, assert_warns, HAS_REFCOUNT, IS_WASM
14
+ )
15
+
16
+
17
+ class TestIndexing:
18
+ def test_index_no_floats(self):
19
+ a = np.array([[[5]]])
20
+
21
+ assert_raises(IndexError, lambda: a[0.0])
22
+ assert_raises(IndexError, lambda: a[0, 0.0])
23
+ assert_raises(IndexError, lambda: a[0.0, 0])
24
+ assert_raises(IndexError, lambda: a[0.0,:])
25
+ assert_raises(IndexError, lambda: a[:, 0.0])
26
+ assert_raises(IndexError, lambda: a[:, 0.0,:])
27
+ assert_raises(IndexError, lambda: a[0.0,:,:])
28
+ assert_raises(IndexError, lambda: a[0, 0, 0.0])
29
+ assert_raises(IndexError, lambda: a[0.0, 0, 0])
30
+ assert_raises(IndexError, lambda: a[0, 0.0, 0])
31
+ assert_raises(IndexError, lambda: a[-1.4])
32
+ assert_raises(IndexError, lambda: a[0, -1.4])
33
+ assert_raises(IndexError, lambda: a[-1.4, 0])
34
+ assert_raises(IndexError, lambda: a[-1.4,:])
35
+ assert_raises(IndexError, lambda: a[:, -1.4])
36
+ assert_raises(IndexError, lambda: a[:, -1.4,:])
37
+ assert_raises(IndexError, lambda: a[-1.4,:,:])
38
+ assert_raises(IndexError, lambda: a[0, 0, -1.4])
39
+ assert_raises(IndexError, lambda: a[-1.4, 0, 0])
40
+ assert_raises(IndexError, lambda: a[0, -1.4, 0])
41
+ assert_raises(IndexError, lambda: a[0.0:, 0.0])
42
+ assert_raises(IndexError, lambda: a[0.0:, 0.0,:])
43
+
44
+ def test_slicing_no_floats(self):
45
+ a = np.array([[5]])
46
+
47
+ # start as float.
48
+ assert_raises(TypeError, lambda: a[0.0:])
49
+ assert_raises(TypeError, lambda: a[0:, 0.0:2])
50
+ assert_raises(TypeError, lambda: a[0.0::2, :0])
51
+ assert_raises(TypeError, lambda: a[0.0:1:2,:])
52
+ assert_raises(TypeError, lambda: a[:, 0.0:])
53
+ # stop as float.
54
+ assert_raises(TypeError, lambda: a[:0.0])
55
+ assert_raises(TypeError, lambda: a[:0, 1:2.0])
56
+ assert_raises(TypeError, lambda: a[:0.0:2, :0])
57
+ assert_raises(TypeError, lambda: a[:0.0,:])
58
+ assert_raises(TypeError, lambda: a[:, 0:4.0:2])
59
+ # step as float.
60
+ assert_raises(TypeError, lambda: a[::1.0])
61
+ assert_raises(TypeError, lambda: a[0:, :2:2.0])
62
+ assert_raises(TypeError, lambda: a[1::4.0, :0])
63
+ assert_raises(TypeError, lambda: a[::5.0,:])
64
+ assert_raises(TypeError, lambda: a[:, 0:4:2.0])
65
+ # mixed.
66
+ assert_raises(TypeError, lambda: a[1.0:2:2.0])
67
+ assert_raises(TypeError, lambda: a[1.0::2.0])
68
+ assert_raises(TypeError, lambda: a[0:, :2.0:2.0])
69
+ assert_raises(TypeError, lambda: a[1.0:1:4.0, :0])
70
+ assert_raises(TypeError, lambda: a[1.0:5.0:5.0,:])
71
+ assert_raises(TypeError, lambda: a[:, 0.4:4.0:2.0])
72
+ # should still get the DeprecationWarning if step = 0.
73
+ assert_raises(TypeError, lambda: a[::0.0])
74
+
75
+ def test_index_no_array_to_index(self):
76
+ # No non-scalar arrays.
77
+ a = np.array([[[1]]])
78
+
79
+ assert_raises(TypeError, lambda: a[a:a:a])
80
+
81
+ def test_none_index(self):
82
+ # `None` index adds newaxis
83
+ a = np.array([1, 2, 3])
84
+ assert_equal(a[None], a[np.newaxis])
85
+ assert_equal(a[None].ndim, a.ndim + 1)
86
+
87
+ def test_empty_tuple_index(self):
88
+ # Empty tuple index creates a view
89
+ a = np.array([1, 2, 3])
90
+ assert_equal(a[()], a)
91
+ assert_(a[()].base is a)
92
+ a = np.array(0)
93
+ assert_(isinstance(a[()], np.int_))
94
+
95
+ def test_void_scalar_empty_tuple(self):
96
+ s = np.zeros((), dtype='V4')
97
+ assert_equal(s[()].dtype, s.dtype)
98
+ assert_equal(s[()], s)
99
+ assert_equal(type(s[...]), np.ndarray)
100
+
101
+ def test_same_kind_index_casting(self):
102
+ # Indexes should be cast with same-kind and not safe, even if that
103
+ # is somewhat unsafe. So test various different code paths.
104
+ index = np.arange(5)
105
+ u_index = index.astype(np.uintp)
106
+ arr = np.arange(10)
107
+
108
+ assert_array_equal(arr[index], arr[u_index])
109
+ arr[u_index] = np.arange(5)
110
+ assert_array_equal(arr, np.arange(10))
111
+
112
+ arr = np.arange(10).reshape(5, 2)
113
+ assert_array_equal(arr[index], arr[u_index])
114
+
115
+ arr[u_index] = np.arange(5)[:,None]
116
+ assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1))
117
+
118
+ arr = np.arange(25).reshape(5, 5)
119
+ assert_array_equal(arr[u_index, u_index], arr[index, index])
120
+
121
+ def test_empty_fancy_index(self):
122
+ # Empty list index creates an empty array
123
+ # with the same dtype (but with weird shape)
124
+ a = np.array([1, 2, 3])
125
+ assert_equal(a[[]], [])
126
+ assert_equal(a[[]].dtype, a.dtype)
127
+
128
+ b = np.array([], dtype=np.intp)
129
+ assert_equal(a[[]], [])
130
+ assert_equal(a[[]].dtype, a.dtype)
131
+
132
+ b = np.array([])
133
+ assert_raises(IndexError, a.__getitem__, b)
134
+
135
+ def test_ellipsis_index(self):
136
+ a = np.array([[1, 2, 3],
137
+ [4, 5, 6],
138
+ [7, 8, 9]])
139
+ assert_(a[...] is not a)
140
+ assert_equal(a[...], a)
141
+ # `a[...]` was `a` in numpy <1.9.
142
+ assert_(a[...].base is a)
143
+
144
+ # Slicing with ellipsis can skip an
145
+ # arbitrary number of dimensions
146
+ assert_equal(a[0, ...], a[0])
147
+ assert_equal(a[0, ...], a[0,:])
148
+ assert_equal(a[..., 0], a[:, 0])
149
+
150
+ # Slicing with ellipsis always results
151
+ # in an array, not a scalar
152
+ assert_equal(a[0, ..., 1], np.array(2))
153
+
154
+ # Assignment with `(Ellipsis,)` on 0-d arrays
155
+ b = np.array(1)
156
+ b[(Ellipsis,)] = 2
157
+ assert_equal(b, 2)
158
+
159
+ def test_single_int_index(self):
160
+ # Single integer index selects one row
161
+ a = np.array([[1, 2, 3],
162
+ [4, 5, 6],
163
+ [7, 8, 9]])
164
+
165
+ assert_equal(a[0], [1, 2, 3])
166
+ assert_equal(a[-1], [7, 8, 9])
167
+
168
+ # Index out of bounds produces IndexError
169
+ assert_raises(IndexError, a.__getitem__, 1 << 30)
170
+ # Index overflow produces IndexError
171
+ assert_raises(IndexError, a.__getitem__, 1 << 64)
172
+
173
+ def test_single_bool_index(self):
174
+ # Single boolean index
175
+ a = np.array([[1, 2, 3],
176
+ [4, 5, 6],
177
+ [7, 8, 9]])
178
+
179
+ assert_equal(a[np.array(True)], a[None])
180
+ assert_equal(a[np.array(False)], a[None][0:0])
181
+
182
+ def test_boolean_shape_mismatch(self):
183
+ arr = np.ones((5, 4, 3))
184
+
185
+ index = np.array([True])
186
+ assert_raises(IndexError, arr.__getitem__, index)
187
+
188
+ index = np.array([False] * 6)
189
+ assert_raises(IndexError, arr.__getitem__, index)
190
+
191
+ index = np.zeros((4, 4), dtype=bool)
192
+ assert_raises(IndexError, arr.__getitem__, index)
193
+
194
+ assert_raises(IndexError, arr.__getitem__, (slice(None), index))
195
+
196
+ def test_boolean_indexing_onedim(self):
197
+ # Indexing a 2-dimensional array with
198
+ # boolean array of length one
199
+ a = np.array([[ 0., 0., 0.]])
200
+ b = np.array([ True], dtype=bool)
201
+ assert_equal(a[b], a)
202
+ # boolean assignment
203
+ a[b] = 1.
204
+ assert_equal(a, [[1., 1., 1.]])
205
+
206
+ def test_boolean_assignment_value_mismatch(self):
207
+ # A boolean assignment should fail when the shape of the values
208
+ # cannot be broadcast to the subscription. (see also gh-3458)
209
+ a = np.arange(4)
210
+
211
+ def f(a, v):
212
+ a[a > -1] = v
213
+
214
+ assert_raises(ValueError, f, a, [])
215
+ assert_raises(ValueError, f, a, [1, 2, 3])
216
+ assert_raises(ValueError, f, a[:1], [1, 2, 3])
217
+
218
+ def test_boolean_assignment_needs_api(self):
219
+ # See also gh-7666
220
+ # This caused a segfault on Python 2 due to the GIL not being
221
+ # held when the iterator does not need it, but the transfer function
222
+ # does
223
+ arr = np.zeros(1000)
224
+ indx = np.zeros(1000, dtype=bool)
225
+ indx[:100] = True
226
+ arr[indx] = np.ones(100, dtype=object)
227
+
228
+ expected = np.zeros(1000)
229
+ expected[:100] = 1
230
+ assert_array_equal(arr, expected)
231
+
232
+ def test_boolean_indexing_twodim(self):
233
+ # Indexing a 2-dimensional array with
234
+ # 2-dimensional boolean array
235
+ a = np.array([[1, 2, 3],
236
+ [4, 5, 6],
237
+ [7, 8, 9]])
238
+ b = np.array([[ True, False, True],
239
+ [False, True, False],
240
+ [ True, False, True]])
241
+ assert_equal(a[b], [1, 3, 5, 7, 9])
242
+ assert_equal(a[b[1]], [[4, 5, 6]])
243
+ assert_equal(a[b[0]], a[b[2]])
244
+
245
+ # boolean assignment
246
+ a[b] = 0
247
+ assert_equal(a, [[0, 2, 0],
248
+ [4, 0, 6],
249
+ [0, 8, 0]])
250
+
251
+ def test_boolean_indexing_list(self):
252
+ # Regression test for #13715. It's a use-after-free bug which the
253
+ # test won't directly catch, but it will show up in valgrind.
254
+ a = np.array([1, 2, 3])
255
+ b = [True, False, True]
256
+ # Two variants of the test because the first takes a fast path
257
+ assert_equal(a[b], [1, 3])
258
+ assert_equal(a[None, b], [[1, 3]])
259
+
260
+ def test_reverse_strides_and_subspace_bufferinit(self):
261
+ # This tests that the strides are not reversed for simple and
262
+ # subspace fancy indexing.
263
+ a = np.ones(5)
264
+ b = np.zeros(5, dtype=np.intp)[::-1]
265
+ c = np.arange(5)[::-1]
266
+
267
+ a[b] = c
268
+ # If the strides are not reversed, the 0 in the arange comes last.
269
+ assert_equal(a[0], 0)
270
+
271
+ # This also tests that the subspace buffer is initialized:
272
+ a = np.ones((5, 2))
273
+ c = np.arange(10).reshape(5, 2)[::-1]
274
+ a[b, :] = c
275
+ assert_equal(a[0], [0, 1])
276
+
277
+ def test_reversed_strides_result_allocation(self):
278
+ # Test a bug when calculating the output strides for a result array
279
+ # when the subspace size was 1 (and test other cases as well)
280
+ a = np.arange(10)[:, None]
281
+ i = np.arange(10)[::-1]
282
+ assert_array_equal(a[i], a[i.copy('C')])
283
+
284
+ a = np.arange(20).reshape(-1, 2)
285
+
286
+ def test_uncontiguous_subspace_assignment(self):
287
+ # During development there was a bug activating a skip logic
288
+ # based on ndim instead of size.
289
+ a = np.full((3, 4, 2), -1)
290
+ b = np.full((3, 4, 2), -1)
291
+
292
+ a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T
293
+ b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy()
294
+
295
+ assert_equal(a, b)
296
+
297
+ def test_too_many_fancy_indices_special_case(self):
298
+ # Just documents behaviour, this is a small limitation.
299
+ a = np.ones((1,) * 32) # 32 is NPY_MAXDIMS
300
+ assert_raises(IndexError, a.__getitem__, (np.array([0]),) * 32)
301
+
302
+ def test_scalar_array_bool(self):
303
+ # NumPy bools can be used as boolean index (python ones as of yet not)
304
+ a = np.array(1)
305
+ assert_equal(a[np.bool_(True)], a[np.array(True)])
306
+ assert_equal(a[np.bool_(False)], a[np.array(False)])
307
+
308
+ # After deprecating bools as integers:
309
+ #a = np.array([0,1,2])
310
+ #assert_equal(a[True, :], a[None, :])
311
+ #assert_equal(a[:, True], a[:, None])
312
+ #
313
+ #assert_(not np.may_share_memory(a, a[True, :]))
314
+
315
+ def test_everything_returns_views(self):
316
+ # Before `...` would return a itself.
317
+ a = np.arange(5)
318
+
319
+ assert_(a is not a[()])
320
+ assert_(a is not a[...])
321
+ assert_(a is not a[:])
322
+
323
+ def test_broaderrors_indexing(self):
324
+ a = np.zeros((5, 5))
325
+ assert_raises(IndexError, a.__getitem__, ([0, 1], [0, 1, 2]))
326
+ assert_raises(IndexError, a.__setitem__, ([0, 1], [0, 1, 2]), 0)
327
+
328
+ def test_trivial_fancy_out_of_bounds(self):
329
+ a = np.zeros(5)
330
+ ind = np.ones(20, dtype=np.intp)
331
+ ind[-1] = 10
332
+ assert_raises(IndexError, a.__getitem__, ind)
333
+ assert_raises(IndexError, a.__setitem__, ind, 0)
334
+ ind = np.ones(20, dtype=np.intp)
335
+ ind[0] = 11
336
+ assert_raises(IndexError, a.__getitem__, ind)
337
+ assert_raises(IndexError, a.__setitem__, ind, 0)
338
+
339
+ def test_trivial_fancy_not_possible(self):
340
+ # Test that the fast path for trivial assignment is not incorrectly
341
+ # used when the index is not contiguous or 1D, see also gh-11467.
342
+ a = np.arange(6)
343
+ idx = np.arange(6, dtype=np.intp).reshape(2, 1, 3)[:, :, 0]
344
+ assert_array_equal(a[idx], idx)
345
+
346
+ # this case must not go into the fast path, note that idx is
347
+ # a non-contiuguous none 1D array here.
348
+ a[idx] = -1
349
+ res = np.arange(6)
350
+ res[0] = -1
351
+ res[3] = -1
352
+ assert_array_equal(a, res)
353
+
354
+ def test_nonbaseclass_values(self):
355
+ class SubClass(np.ndarray):
356
+ def __array_finalize__(self, old):
357
+ # Have array finalize do funny things
358
+ self.fill(99)
359
+
360
+ a = np.zeros((5, 5))
361
+ s = a.copy().view(type=SubClass)
362
+ s.fill(1)
363
+
364
+ a[[0, 1, 2, 3, 4], :] = s
365
+ assert_((a == 1).all())
366
+
367
+ # Subspace is last, so transposing might want to finalize
368
+ a[:, [0, 1, 2, 3, 4]] = s
369
+ assert_((a == 1).all())
370
+
371
+ a.fill(0)
372
+ a[...] = s
373
+ assert_((a == 1).all())
374
+
375
+ def test_array_like_values(self):
376
+ # Similar to the above test, but use a memoryview instead
377
+ a = np.zeros((5, 5))
378
+ s = np.arange(25, dtype=np.float64).reshape(5, 5)
379
+
380
+ a[[0, 1, 2, 3, 4], :] = memoryview(s)
381
+ assert_array_equal(a, s)
382
+
383
+ a[:, [0, 1, 2, 3, 4]] = memoryview(s)
384
+ assert_array_equal(a, s)
385
+
386
+ a[...] = memoryview(s)
387
+ assert_array_equal(a, s)
388
+
389
+ def test_subclass_writeable(self):
390
+ d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)],
391
+ dtype=[('target', 'S20'), ('V_mag', '>f4')])
392
+ ind = np.array([False, True, True], dtype=bool)
393
+ assert_(d[ind].flags.writeable)
394
+ ind = np.array([0, 1])
395
+ assert_(d[ind].flags.writeable)
396
+ assert_(d[...].flags.writeable)
397
+ assert_(d[0].flags.writeable)
398
+
399
+ def test_memory_order(self):
400
+ # This is not necessary to preserve. Memory layouts for
401
+ # more complex indices are not as simple.
402
+ a = np.arange(10)
403
+ b = np.arange(10).reshape(5,2).T
404
+ assert_(a[b].flags.f_contiguous)
405
+
406
+ # Takes a different implementation branch:
407
+ a = a.reshape(-1, 1)
408
+ assert_(a[b, 0].flags.f_contiguous)
409
+
410
+ def test_scalar_return_type(self):
411
+ # Full scalar indices should return scalars and object
412
+ # arrays should not call PyArray_Return on their items
413
+ class Zero:
414
+ # The most basic valid indexing
415
+ def __index__(self):
416
+ return 0
417
+
418
+ z = Zero()
419
+
420
+ class ArrayLike:
421
+ # Simple array, should behave like the array
422
+ def __array__(self):
423
+ return np.array(0)
424
+
425
+ a = np.zeros(())
426
+ assert_(isinstance(a[()], np.float_))
427
+ a = np.zeros(1)
428
+ assert_(isinstance(a[z], np.float_))
429
+ a = np.zeros((1, 1))
430
+ assert_(isinstance(a[z, np.array(0)], np.float_))
431
+ assert_(isinstance(a[z, ArrayLike()], np.float_))
432
+
433
+ # And object arrays do not call it too often:
434
+ b = np.array(0)
435
+ a = np.array(0, dtype=object)
436
+ a[()] = b
437
+ assert_(isinstance(a[()], np.ndarray))
438
+ a = np.array([b, None])
439
+ assert_(isinstance(a[z], np.ndarray))
440
+ a = np.array([[b, None]])
441
+ assert_(isinstance(a[z, np.array(0)], np.ndarray))
442
+ assert_(isinstance(a[z, ArrayLike()], np.ndarray))
443
+
444
+ def test_small_regressions(self):
445
+ # Reference count of intp for index checks
446
+ a = np.array([0])
447
+ if HAS_REFCOUNT:
448
+ refcount = sys.getrefcount(np.dtype(np.intp))
449
+ # item setting always checks indices in separate function:
450
+ a[np.array([0], dtype=np.intp)] = 1
451
+ a[np.array([0], dtype=np.uint8)] = 1
452
+ assert_raises(IndexError, a.__setitem__,
453
+ np.array([1], dtype=np.intp), 1)
454
+ assert_raises(IndexError, a.__setitem__,
455
+ np.array([1], dtype=np.uint8), 1)
456
+
457
+ if HAS_REFCOUNT:
458
+ assert_equal(sys.getrefcount(np.dtype(np.intp)), refcount)
459
+
460
+ def test_unaligned(self):
461
+ v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]
462
+ d = v.view(np.dtype("S8"))
463
+ # unaligned source
464
+ x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]
465
+ x = x.view(np.dtype("S8"))
466
+ x[...] = np.array("b" * 8, dtype="S")
467
+ b = np.arange(d.size)
468
+ #trivial
469
+ assert_equal(d[b], d)
470
+ d[b] = x
471
+ # nontrivial
472
+ # unaligned index array
473
+ b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]
474
+ b = b.view(np.intp)[:d.size]
475
+ b[...] = np.arange(d.size)
476
+ assert_equal(d[b.astype(np.int16)], d)
477
+ d[b.astype(np.int16)] = x
478
+ # boolean
479
+ d[b % 2 == 0]
480
+ d[b % 2 == 0] = x[::2]
481
+
482
+ def test_tuple_subclass(self):
483
+ arr = np.ones((5, 5))
484
+
485
+ # A tuple subclass should also be an nd-index
486
+ class TupleSubclass(tuple):
487
+ pass
488
+ index = ([1], [1])
489
+ index = TupleSubclass(index)
490
+ assert_(arr[index].shape == (1,))
491
+ # Unlike the non nd-index:
492
+ assert_(arr[index,].shape != (1,))
493
+
494
+ def test_broken_sequence_not_nd_index(self):
495
+ # See gh-5063:
496
+ # If we have an object which claims to be a sequence, but fails
497
+ # on item getting, this should not be converted to an nd-index (tuple)
498
+ # If this object happens to be a valid index otherwise, it should work
499
+ # This object here is very dubious and probably bad though:
500
+ class SequenceLike:
501
+ def __index__(self):
502
+ return 0
503
+
504
+ def __len__(self):
505
+ return 1
506
+
507
+ def __getitem__(self, item):
508
+ raise IndexError('Not possible')
509
+
510
+ arr = np.arange(10)
511
+ assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
512
+
513
+ # also test that field indexing does not segfault
514
+ # for a similar reason, by indexing a structured array
515
+ arr = np.zeros((1,), dtype=[('f1', 'i8'), ('f2', 'i8')])
516
+ assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
517
+
518
+ def test_indexing_array_weird_strides(self):
519
+ # See also gh-6221
520
+ # the shapes used here come from the issue and create the correct
521
+ # size for the iterator buffering size.
522
+ x = np.ones(10)
523
+ x2 = np.ones((10, 2))
524
+ ind = np.arange(10)[:, None, None, None]
525
+ ind = np.broadcast_to(ind, (10, 55, 4, 4))
526
+
527
+ # single advanced index case
528
+ assert_array_equal(x[ind], x[ind.copy()])
529
+ # higher dimensional advanced index
530
+ zind = np.zeros(4, dtype=np.intp)
531
+ assert_array_equal(x2[ind, zind], x2[ind.copy(), zind])
532
+
533
+ def test_indexing_array_negative_strides(self):
534
+ # From gh-8264,
535
+ # core dumps if negative strides are used in iteration
536
+ arro = np.zeros((4, 4))
537
+ arr = arro[::-1, ::-1]
538
+
539
+ slices = (slice(None), [0, 1, 2, 3])
540
+ arr[slices] = 10
541
+ assert_array_equal(arr, 10.)
542
+
543
+ def test_character_assignment(self):
544
+ # This is an example a function going through CopyObject which
545
+ # used to have an untested special path for scalars
546
+ # (the character special dtype case, should be deprecated probably)
547
+ arr = np.zeros((1, 5), dtype="c")
548
+ arr[0] = np.str_("asdfg") # must assign as a sequence
549
+ assert_array_equal(arr[0], np.array("asdfg", dtype="c"))
550
+ assert arr[0, 1] == b"s" # make sure not all were set to "a" for both
551
+
552
+ @pytest.mark.parametrize("index",
553
+ [True, False, np.array([0])])
554
+ @pytest.mark.parametrize("num", [32, 40])
555
+ @pytest.mark.parametrize("original_ndim", [1, 32])
556
+ def test_too_many_advanced_indices(self, index, num, original_ndim):
557
+ # These are limitations based on the number of arguments we can process.
558
+ # For `num=32` (and all boolean cases), the result is actually define;
559
+ # but the use of NpyIter (NPY_MAXARGS) limits it for technical reasons.
560
+ arr = np.ones((1,) * original_ndim)
561
+ with pytest.raises(IndexError):
562
+ arr[(index,) * num]
563
+ with pytest.raises(IndexError):
564
+ arr[(index,) * num] = 1.
565
+
566
+ @pytest.mark.skipif(IS_WASM, reason="no threading")
567
+ def test_structured_advanced_indexing(self):
568
+ # Test that copyswap(n) used by integer array indexing is threadsafe
569
+ # for structured datatypes, see gh-15387. This test can behave randomly.
570
+ from concurrent.futures import ThreadPoolExecutor
571
+
572
+ # Create a deeply nested dtype to make a failure more likely:
573
+ dt = np.dtype([("", "f8")])
574
+ dt = np.dtype([("", dt)] * 2)
575
+ dt = np.dtype([("", dt)] * 2)
576
+ # The array should be large enough to likely run into threading issues
577
+ arr = np.random.uniform(size=(6000, 8)).view(dt)[:, 0]
578
+
579
+ rng = np.random.default_rng()
580
+ def func(arr):
581
+ indx = rng.integers(0, len(arr), size=6000, dtype=np.intp)
582
+ arr[indx]
583
+
584
+ tpe = ThreadPoolExecutor(max_workers=8)
585
+ futures = [tpe.submit(func, arr) for _ in range(10)]
586
+ for f in futures:
587
+ f.result()
588
+
589
+ assert arr.dtype is dt
590
+
591
+ def test_nontuple_ndindex(self):
592
+ a = np.arange(25).reshape((5, 5))
593
+ assert_equal(a[[0, 1]], np.array([a[0], a[1]]))
594
+ assert_equal(a[[0, 1], [0, 1]], np.array([0, 6]))
595
+ assert_raises(IndexError, a.__getitem__, [slice(None)])
596
+
597
+
598
+ class TestFieldIndexing:
599
+ def test_scalar_return_type(self):
600
+ # Field access on an array should return an array, even if it
601
+ # is 0-d.
602
+ a = np.zeros((), [('a','f8')])
603
+ assert_(isinstance(a['a'], np.ndarray))
604
+ assert_(isinstance(a[['a']], np.ndarray))
605
+
606
+
607
+ class TestBroadcastedAssignments:
608
+ def assign(self, a, ind, val):
609
+ a[ind] = val
610
+ return a
611
+
612
+ def test_prepending_ones(self):
613
+ a = np.zeros((3, 2))
614
+
615
+ a[...] = np.ones((1, 3, 2))
616
+ # Fancy with subspace with and without transpose
617
+ a[[0, 1, 2], :] = np.ones((1, 3, 2))
618
+ a[:, [0, 1]] = np.ones((1, 3, 2))
619
+ # Fancy without subspace (with broadcasting)
620
+ a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2))
621
+
622
+ def test_prepend_not_one(self):
623
+ assign = self.assign
624
+ s_ = np.s_
625
+ a = np.zeros(5)
626
+
627
+ # Too large and not only ones.
628
+ assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1)))
629
+ assert_raises(ValueError, assign, a, s_[[1, 2, 3],], np.ones((2, 1)))
630
+ assert_raises(ValueError, assign, a, s_[[[1], [2]],], np.ones((2,2,1)))
631
+
632
+ def test_simple_broadcasting_errors(self):
633
+ assign = self.assign
634
+ s_ = np.s_
635
+ a = np.zeros((5, 1))
636
+
637
+ assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 2)))
638
+ assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 0)))
639
+ assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 2)))
640
+ assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 0)))
641
+ assert_raises(ValueError, assign, a, s_[[0], :], np.zeros((2, 1)))
642
+
643
+ @pytest.mark.parametrize("index", [
644
+ (..., [1, 2], slice(None)),
645
+ ([0, 1], ..., 0),
646
+ (..., [1, 2], [1, 2])])
647
+ def test_broadcast_error_reports_correct_shape(self, index):
648
+ values = np.zeros((100, 100)) # will never broadcast below
649
+
650
+ arr = np.zeros((3, 4, 5, 6, 7))
651
+ # We currently report without any spaces (could be changed)
652
+ shape_str = str(arr[index].shape).replace(" ", "")
653
+
654
+ with pytest.raises(ValueError) as e:
655
+ arr[index] = values
656
+
657
+ assert str(e.value).endswith(shape_str)
658
+
659
+ def test_index_is_larger(self):
660
+ # Simple case of fancy index broadcasting of the index.
661
+ a = np.zeros((5, 5))
662
+ a[[[0], [1], [2]], [0, 1, 2]] = [2, 3, 4]
663
+
664
+ assert_((a[:3, :3] == [2, 3, 4]).all())
665
+
666
+ def test_broadcast_subspace(self):
667
+ a = np.zeros((100, 100))
668
+ v = np.arange(100)[:,None]
669
+ b = np.arange(100)[::-1]
670
+ a[b] = v
671
+ assert_((a[::-1] == v).all())
672
+
673
+
674
+ class TestSubclasses:
675
+ def test_basic(self):
676
+ # Test that indexing in various ways produces SubClass instances,
677
+ # and that the base is set up correctly: the original subclass
678
+ # instance for views, and a new ndarray for advanced/boolean indexing
679
+ # where a copy was made (latter a regression test for gh-11983).
680
+ class SubClass(np.ndarray):
681
+ pass
682
+
683
+ a = np.arange(5)
684
+ s = a.view(SubClass)
685
+ s_slice = s[:3]
686
+ assert_(type(s_slice) is SubClass)
687
+ assert_(s_slice.base is s)
688
+ assert_array_equal(s_slice, a[:3])
689
+
690
+ s_fancy = s[[0, 1, 2]]
691
+ assert_(type(s_fancy) is SubClass)
692
+ assert_(s_fancy.base is not s)
693
+ assert_(type(s_fancy.base) is np.ndarray)
694
+ assert_array_equal(s_fancy, a[[0, 1, 2]])
695
+ assert_array_equal(s_fancy.base, a[[0, 1, 2]])
696
+
697
+ s_bool = s[s > 0]
698
+ assert_(type(s_bool) is SubClass)
699
+ assert_(s_bool.base is not s)
700
+ assert_(type(s_bool.base) is np.ndarray)
701
+ assert_array_equal(s_bool, a[a > 0])
702
+ assert_array_equal(s_bool.base, a[a > 0])
703
+
704
+ def test_fancy_on_read_only(self):
705
+ # Test that fancy indexing on read-only SubClass does not make a
706
+ # read-only copy (gh-14132)
707
+ class SubClass(np.ndarray):
708
+ pass
709
+
710
+ a = np.arange(5)
711
+ s = a.view(SubClass)
712
+ s.flags.writeable = False
713
+ s_fancy = s[[0, 1, 2]]
714
+ assert_(s_fancy.flags.writeable)
715
+
716
+
717
+ def test_finalize_gets_full_info(self):
718
+ # Array finalize should be called on the filled array.
719
+ class SubClass(np.ndarray):
720
+ def __array_finalize__(self, old):
721
+ self.finalize_status = np.array(self)
722
+ self.old = old
723
+
724
+ s = np.arange(10).view(SubClass)
725
+ new_s = s[:3]
726
+ assert_array_equal(new_s.finalize_status, new_s)
727
+ assert_array_equal(new_s.old, s)
728
+
729
+ new_s = s[[0,1,2,3]]
730
+ assert_array_equal(new_s.finalize_status, new_s)
731
+ assert_array_equal(new_s.old, s)
732
+
733
+ new_s = s[s > 0]
734
+ assert_array_equal(new_s.finalize_status, new_s)
735
+ assert_array_equal(new_s.old, s)
736
+
737
+
738
+ class TestFancyIndexingCast:
739
+ def test_boolean_index_cast_assign(self):
740
+ # Setup the boolean index and float arrays.
741
+ shape = (8, 63)
742
+ bool_index = np.zeros(shape).astype(bool)
743
+ bool_index[0, 1] = True
744
+ zero_array = np.zeros(shape)
745
+
746
+ # Assigning float is fine.
747
+ zero_array[bool_index] = np.array([1])
748
+ assert_equal(zero_array[0, 1], 1)
749
+
750
+ # Fancy indexing works, although we get a cast warning.
751
+ assert_warns(np.ComplexWarning,
752
+ zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
753
+ assert_equal(zero_array[0, 1], 2) # No complex part
754
+
755
+ # Cast complex to float, throwing away the imaginary portion.
756
+ assert_warns(np.ComplexWarning,
757
+ zero_array.__setitem__, bool_index, np.array([1j]))
758
+ assert_equal(zero_array[0, 1], 0)
759
+
760
+ class TestFancyIndexingEquivalence:
761
+ def test_object_assign(self):
762
+ # Check that the field and object special case using copyto is active.
763
+ # The right hand side cannot be converted to an array here.
764
+ a = np.arange(5, dtype=object)
765
+ b = a.copy()
766
+ a[:3] = [1, (1,2), 3]
767
+ b[[0, 1, 2]] = [1, (1,2), 3]
768
+ assert_array_equal(a, b)
769
+
770
+ # test same for subspace fancy indexing
771
+ b = np.arange(5, dtype=object)[None, :]
772
+ b[[0], :3] = [[1, (1,2), 3]]
773
+ assert_array_equal(a, b[0])
774
+
775
+ # Check that swapping of axes works.
776
+ # There was a bug that made the later assignment throw a ValueError
777
+ # do to an incorrectly transposed temporary right hand side (gh-5714)
778
+ b = b.T
779
+ b[:3, [0]] = [[1], [(1,2)], [3]]
780
+ assert_array_equal(a, b[:, 0])
781
+
782
+ # Another test for the memory order of the subspace
783
+ arr = np.ones((3, 4, 5), dtype=object)
784
+ # Equivalent slicing assignment for comparison
785
+ cmp_arr = arr.copy()
786
+ cmp_arr[:1, ...] = [[[1], [2], [3], [4]]]
787
+ arr[[0], ...] = [[[1], [2], [3], [4]]]
788
+ assert_array_equal(arr, cmp_arr)
789
+ arr = arr.copy('F')
790
+ arr[[0], ...] = [[[1], [2], [3], [4]]]
791
+ assert_array_equal(arr, cmp_arr)
792
+
793
+ def test_cast_equivalence(self):
794
+ # Yes, normal slicing uses unsafe casting.
795
+ a = np.arange(5)
796
+ b = a.copy()
797
+
798
+ a[:3] = np.array(['2', '-3', '-1'])
799
+ b[[0, 2, 1]] = np.array(['2', '-1', '-3'])
800
+ assert_array_equal(a, b)
801
+
802
+ # test the same for subspace fancy indexing
803
+ b = np.arange(5)[None, :]
804
+ b[[0], :3] = np.array([['2', '-3', '-1']])
805
+ assert_array_equal(a, b[0])
806
+
807
+
808
+ class TestMultiIndexingAutomated:
809
+ """
810
+ These tests use code to mimic the C-Code indexing for selection.
811
+
812
+ NOTE:
813
+
814
+ * This still lacks tests for complex item setting.
815
+ * If you change behavior of indexing, you might want to modify
816
+ these tests to try more combinations.
817
+ * Behavior was written to match numpy version 1.8. (though a
818
+ first version matched 1.7.)
819
+ * Only tuple indices are supported by the mimicking code.
820
+ (and tested as of writing this)
821
+ * Error types should match most of the time as long as there
822
+ is only one error. For multiple errors, what gets raised
823
+ will usually not be the same one. They are *not* tested.
824
+
825
+ Update 2016-11-30: It is probably not worth maintaining this test
826
+ indefinitely and it can be dropped if maintenance becomes a burden.
827
+
828
+ """
829
+
830
+ def setup_method(self):
831
+ self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)
832
+ self.b = np.empty((3, 0, 5, 6))
833
+ self.complex_indices = ['skip', Ellipsis,
834
+ 0,
835
+ # Boolean indices, up to 3-d for some special cases of eating up
836
+ # dimensions, also need to test all False
837
+ np.array([True, False, False]),
838
+ np.array([[True, False], [False, True]]),
839
+ np.array([[[False, False], [False, False]]]),
840
+ # Some slices:
841
+ slice(-5, 5, 2),
842
+ slice(1, 1, 100),
843
+ slice(4, -1, -2),
844
+ slice(None, None, -3),
845
+ # Some Fancy indexes:
846
+ np.empty((0, 1, 1), dtype=np.intp), # empty and can be broadcast
847
+ np.array([0, 1, -2]),
848
+ np.array([[2], [0], [1]]),
849
+ np.array([[0, -1], [0, 1]], dtype=np.dtype('intp').newbyteorder()),
850
+ np.array([2, -1], dtype=np.int8),
851
+ np.zeros([1]*31, dtype=int), # trigger too large array.
852
+ np.array([0., 1.])] # invalid datatype
853
+ # Some simpler indices that still cover a bit more
854
+ self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]),
855
+ 'skip']
856
+ # Very simple ones to fill the rest:
857
+ self.fill_indices = [slice(None, None), 0]
858
+
859
+ def _get_multi_index(self, arr, indices):
860
+ """Mimic multi dimensional indexing.
861
+
862
+ Parameters
863
+ ----------
864
+ arr : ndarray
865
+ Array to be indexed.
866
+ indices : tuple of index objects
867
+
868
+ Returns
869
+ -------
870
+ out : ndarray
871
+ An array equivalent to the indexing operation (but always a copy).
872
+ `arr[indices]` should be identical.
873
+ no_copy : bool
874
+ Whether the indexing operation requires a copy. If this is `True`,
875
+ `np.may_share_memory(arr, arr[indices])` should be `True` (with
876
+ some exceptions for scalars and possibly 0-d arrays).
877
+
878
+ Notes
879
+ -----
880
+ While the function may mostly match the errors of normal indexing this
881
+ is generally not the case.
882
+ """
883
+ in_indices = list(indices)
884
+ indices = []
885
+ # if False, this is a fancy or boolean index
886
+ no_copy = True
887
+ # number of fancy/scalar indexes that are not consecutive
888
+ num_fancy = 0
889
+ # number of dimensions indexed by a "fancy" index
890
+ fancy_dim = 0
891
+ # NOTE: This is a funny twist (and probably OK to change).
892
+ # The boolean array has illegal indexes, but this is
893
+ # allowed if the broadcast fancy-indices are 0-sized.
894
+ # This variable is to catch that case.
895
+ error_unless_broadcast_to_empty = False
896
+
897
+ # We need to handle Ellipsis and make arrays from indices, also
898
+ # check if this is fancy indexing (set no_copy).
899
+ ndim = 0
900
+ ellipsis_pos = None # define here mostly to replace all but first.
901
+ for i, indx in enumerate(in_indices):
902
+ if indx is None:
903
+ continue
904
+ if isinstance(indx, np.ndarray) and indx.dtype == bool:
905
+ no_copy = False
906
+ if indx.ndim == 0:
907
+ raise IndexError
908
+ # boolean indices can have higher dimensions
909
+ ndim += indx.ndim
910
+ fancy_dim += indx.ndim
911
+ continue
912
+ if indx is Ellipsis:
913
+ if ellipsis_pos is None:
914
+ ellipsis_pos = i
915
+ continue # do not increment ndim counter
916
+ raise IndexError
917
+ if isinstance(indx, slice):
918
+ ndim += 1
919
+ continue
920
+ if not isinstance(indx, np.ndarray):
921
+ # This could be open for changes in numpy.
922
+ # numpy should maybe raise an error if casting to intp
923
+ # is not safe. It rejects np.array([1., 2.]) but not
924
+ # [1., 2.] as index (same for ie. np.take).
925
+ # (Note the importance of empty lists if changing this here)
926
+ try:
927
+ indx = np.array(indx, dtype=np.intp)
928
+ except ValueError:
929
+ raise IndexError
930
+ in_indices[i] = indx
931
+ elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i':
932
+ raise IndexError('arrays used as indices must be of '
933
+ 'integer (or boolean) type')
934
+ if indx.ndim != 0:
935
+ no_copy = False
936
+ ndim += 1
937
+ fancy_dim += 1
938
+
939
+ if arr.ndim - ndim < 0:
940
+ # we can't take more dimensions then we have, not even for 0-d
941
+ # arrays. since a[()] makes sense, but not a[(),]. We will
942
+ # raise an error later on, unless a broadcasting error occurs
943
+ # first.
944
+ raise IndexError
945
+
946
+ if ndim == 0 and None not in in_indices:
947
+ # Well we have no indexes or one Ellipsis. This is legal.
948
+ return arr.copy(), no_copy
949
+
950
+ if ellipsis_pos is not None:
951
+ in_indices[ellipsis_pos:ellipsis_pos+1] = ([slice(None, None)] *
952
+ (arr.ndim - ndim))
953
+
954
+ for ax, indx in enumerate(in_indices):
955
+ if isinstance(indx, slice):
956
+ # convert to an index array
957
+ indx = np.arange(*indx.indices(arr.shape[ax]))
958
+ indices.append(['s', indx])
959
+ continue
960
+ elif indx is None:
961
+ # this is like taking a slice with one element from a new axis:
962
+ indices.append(['n', np.array([0], dtype=np.intp)])
963
+ arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:]))
964
+ continue
965
+ if isinstance(indx, np.ndarray) and indx.dtype == bool:
966
+ if indx.shape != arr.shape[ax:ax+indx.ndim]:
967
+ raise IndexError
968
+
969
+ try:
970
+ flat_indx = np.ravel_multi_index(np.nonzero(indx),
971
+ arr.shape[ax:ax+indx.ndim], mode='raise')
972
+ except Exception:
973
+ error_unless_broadcast_to_empty = True
974
+ # fill with 0s instead, and raise error later
975
+ flat_indx = np.array([0]*indx.sum(), dtype=np.intp)
976
+ # concatenate axis into a single one:
977
+ if indx.ndim != 0:
978
+ arr = arr.reshape((arr.shape[:ax]
979
+ + (np.prod(arr.shape[ax:ax+indx.ndim]),)
980
+ + arr.shape[ax+indx.ndim:]))
981
+ indx = flat_indx
982
+ else:
983
+ # This could be changed, a 0-d boolean index can
984
+ # make sense (even outside the 0-d indexed array case)
985
+ # Note that originally this is could be interpreted as
986
+ # integer in the full integer special case.
987
+ raise IndexError
988
+ else:
989
+ # If the index is a singleton, the bounds check is done
990
+ # before the broadcasting. This used to be different in <1.9
991
+ if indx.ndim == 0:
992
+ if indx >= arr.shape[ax] or indx < -arr.shape[ax]:
993
+ raise IndexError
994
+ if indx.ndim == 0:
995
+ # The index is a scalar. This used to be two fold, but if
996
+ # fancy indexing was active, the check was done later,
997
+ # possibly after broadcasting it away (1.7. or earlier).
998
+ # Now it is always done.
999
+ if indx >= arr.shape[ax] or indx < - arr.shape[ax]:
1000
+ raise IndexError
1001
+ if (len(indices) > 0 and
1002
+ indices[-1][0] == 'f' and
1003
+ ax != ellipsis_pos):
1004
+ # NOTE: There could still have been a 0-sized Ellipsis
1005
+ # between them. Checked that with ellipsis_pos.
1006
+ indices[-1].append(indx)
1007
+ else:
1008
+ # We have a fancy index that is not after an existing one.
1009
+ # NOTE: A 0-d array triggers this as well, while one may
1010
+ # expect it to not trigger it, since a scalar would not be
1011
+ # considered fancy indexing.
1012
+ num_fancy += 1
1013
+ indices.append(['f', indx])
1014
+
1015
+ if num_fancy > 1 and not no_copy:
1016
+ # We have to flush the fancy indexes left
1017
+ new_indices = indices[:]
1018
+ axes = list(range(arr.ndim))
1019
+ fancy_axes = []
1020
+ new_indices.insert(0, ['f'])
1021
+ ni = 0
1022
+ ai = 0
1023
+ for indx in indices:
1024
+ ni += 1
1025
+ if indx[0] == 'f':
1026
+ new_indices[0].extend(indx[1:])
1027
+ del new_indices[ni]
1028
+ ni -= 1
1029
+ for ax in range(ai, ai + len(indx[1:])):
1030
+ fancy_axes.append(ax)
1031
+ axes.remove(ax)
1032
+ ai += len(indx) - 1 # axis we are at
1033
+ indices = new_indices
1034
+ # and now we need to transpose arr:
1035
+ arr = arr.transpose(*(fancy_axes + axes))
1036
+
1037
+ # We only have one 'f' index now and arr is transposed accordingly.
1038
+ # Now handle newaxis by reshaping...
1039
+ ax = 0
1040
+ for indx in indices:
1041
+ if indx[0] == 'f':
1042
+ if len(indx) == 1:
1043
+ continue
1044
+ # First of all, reshape arr to combine fancy axes into one:
1045
+ orig_shape = arr.shape
1046
+ orig_slice = orig_shape[ax:ax + len(indx[1:])]
1047
+ arr = arr.reshape((arr.shape[:ax]
1048
+ + (np.prod(orig_slice).astype(int),)
1049
+ + arr.shape[ax + len(indx[1:]):]))
1050
+
1051
+ # Check if broadcasting works
1052
+ res = np.broadcast(*indx[1:])
1053
+ # unfortunately the indices might be out of bounds. So check
1054
+ # that first, and use mode='wrap' then. However only if
1055
+ # there are any indices...
1056
+ if res.size != 0:
1057
+ if error_unless_broadcast_to_empty:
1058
+ raise IndexError
1059
+ for _indx, _size in zip(indx[1:], orig_slice):
1060
+ if _indx.size == 0:
1061
+ continue
1062
+ if np.any(_indx >= _size) or np.any(_indx < -_size):
1063
+ raise IndexError
1064
+ if len(indx[1:]) == len(orig_slice):
1065
+ if np.prod(orig_slice) == 0:
1066
+ # Work around for a crash or IndexError with 'wrap'
1067
+ # in some 0-sized cases.
1068
+ try:
1069
+ mi = np.ravel_multi_index(indx[1:], orig_slice,
1070
+ mode='raise')
1071
+ except Exception:
1072
+ # This happens with 0-sized orig_slice (sometimes?)
1073
+ # here it is a ValueError, but indexing gives a:
1074
+ raise IndexError('invalid index into 0-sized')
1075
+ else:
1076
+ mi = np.ravel_multi_index(indx[1:], orig_slice,
1077
+ mode='wrap')
1078
+ else:
1079
+ # Maybe never happens...
1080
+ raise ValueError
1081
+ arr = arr.take(mi.ravel(), axis=ax)
1082
+ try:
1083
+ arr = arr.reshape((arr.shape[:ax]
1084
+ + mi.shape
1085
+ + arr.shape[ax+1:]))
1086
+ except ValueError:
1087
+ # too many dimensions, probably
1088
+ raise IndexError
1089
+ ax += mi.ndim
1090
+ continue
1091
+
1092
+ # If we are here, we have a 1D array for take:
1093
+ arr = arr.take(indx[1], axis=ax)
1094
+ ax += 1
1095
+
1096
+ return arr, no_copy
1097
+
1098
+ def _check_multi_index(self, arr, index):
1099
+ """Check a multi index item getting and simple setting.
1100
+
1101
+ Parameters
1102
+ ----------
1103
+ arr : ndarray
1104
+ Array to be indexed, must be a reshaped arange.
1105
+ index : tuple of indexing objects
1106
+ Index being tested.
1107
+ """
1108
+ # Test item getting
1109
+ try:
1110
+ mimic_get, no_copy = self._get_multi_index(arr, index)
1111
+ except Exception as e:
1112
+ if HAS_REFCOUNT:
1113
+ prev_refcount = sys.getrefcount(arr)
1114
+ assert_raises(type(e), arr.__getitem__, index)
1115
+ assert_raises(type(e), arr.__setitem__, index, 0)
1116
+ if HAS_REFCOUNT:
1117
+ assert_equal(prev_refcount, sys.getrefcount(arr))
1118
+ return
1119
+
1120
+ self._compare_index_result(arr, index, mimic_get, no_copy)
1121
+
1122
+ def _check_single_index(self, arr, index):
1123
+ """Check a single index item getting and simple setting.
1124
+
1125
+ Parameters
1126
+ ----------
1127
+ arr : ndarray
1128
+ Array to be indexed, must be an arange.
1129
+ index : indexing object
1130
+ Index being tested. Must be a single index and not a tuple
1131
+ of indexing objects (see also `_check_multi_index`).
1132
+ """
1133
+ try:
1134
+ mimic_get, no_copy = self._get_multi_index(arr, (index,))
1135
+ except Exception as e:
1136
+ if HAS_REFCOUNT:
1137
+ prev_refcount = sys.getrefcount(arr)
1138
+ assert_raises(type(e), arr.__getitem__, index)
1139
+ assert_raises(type(e), arr.__setitem__, index, 0)
1140
+ if HAS_REFCOUNT:
1141
+ assert_equal(prev_refcount, sys.getrefcount(arr))
1142
+ return
1143
+
1144
+ self._compare_index_result(arr, index, mimic_get, no_copy)
1145
+
1146
+ def _compare_index_result(self, arr, index, mimic_get, no_copy):
1147
+ """Compare mimicked result to indexing result.
1148
+ """
1149
+ arr = arr.copy()
1150
+ indexed_arr = arr[index]
1151
+ assert_array_equal(indexed_arr, mimic_get)
1152
+ # Check if we got a view, unless its a 0-sized or 0-d array.
1153
+ # (then its not a view, and that does not matter)
1154
+ if indexed_arr.size != 0 and indexed_arr.ndim != 0:
1155
+ assert_(np.may_share_memory(indexed_arr, arr) == no_copy)
1156
+ # Check reference count of the original array
1157
+ if HAS_REFCOUNT:
1158
+ if no_copy:
1159
+ # refcount increases by one:
1160
+ assert_equal(sys.getrefcount(arr), 3)
1161
+ else:
1162
+ assert_equal(sys.getrefcount(arr), 2)
1163
+
1164
+ # Test non-broadcast setitem:
1165
+ b = arr.copy()
1166
+ b[index] = mimic_get + 1000
1167
+ if b.size == 0:
1168
+ return # nothing to compare here...
1169
+ if no_copy and indexed_arr.ndim != 0:
1170
+ # change indexed_arr in-place to manipulate original:
1171
+ indexed_arr += 1000
1172
+ assert_array_equal(arr, b)
1173
+ return
1174
+ # Use the fact that the array is originally an arange:
1175
+ arr.flat[indexed_arr.ravel()] += 1000
1176
+ assert_array_equal(arr, b)
1177
+
1178
+ def test_boolean(self):
1179
+ a = np.array(5)
1180
+ assert_equal(a[np.array(True)], 5)
1181
+ a[np.array(True)] = 1
1182
+ assert_equal(a, 1)
1183
+ # NOTE: This is different from normal broadcasting, as
1184
+ # arr[boolean_array] works like in a multi index. Which means
1185
+ # it is aligned to the left. This is probably correct for
1186
+ # consistency with arr[boolean_array,] also no broadcasting
1187
+ # is done at all
1188
+ self._check_multi_index(
1189
+ self.a, (np.zeros_like(self.a, dtype=bool),))
1190
+ self._check_multi_index(
1191
+ self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],))
1192
+ self._check_multi_index(
1193
+ self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))
1194
+
1195
+ def test_multidim(self):
1196
+ # Automatically test combinations with complex indexes on 2nd (or 1st)
1197
+ # spot and the simple ones in one other spot.
1198
+ with warnings.catch_warnings():
1199
+ # This is so that np.array(True) is not accepted in a full integer
1200
+ # index, when running the file separately.
1201
+ warnings.filterwarnings('error', '', DeprecationWarning)
1202
+ warnings.filterwarnings('error', '', np.VisibleDeprecationWarning)
1203
+
1204
+ def isskip(idx):
1205
+ return isinstance(idx, str) and idx == "skip"
1206
+
1207
+ for simple_pos in [0, 2, 3]:
1208
+ tocheck = [self.fill_indices, self.complex_indices,
1209
+ self.fill_indices, self.fill_indices]
1210
+ tocheck[simple_pos] = self.simple_indices
1211
+ for index in product(*tocheck):
1212
+ index = tuple(i for i in index if not isskip(i))
1213
+ self._check_multi_index(self.a, index)
1214
+ self._check_multi_index(self.b, index)
1215
+
1216
+ # Check very simple item getting:
1217
+ self._check_multi_index(self.a, (0, 0, 0, 0))
1218
+ self._check_multi_index(self.b, (0, 0, 0, 0))
1219
+ # Also check (simple cases of) too many indices:
1220
+ assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0))
1221
+ assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0)
1222
+ assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0))
1223
+ assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0)
1224
+
1225
+ def test_1d(self):
1226
+ a = np.arange(10)
1227
+ for index in self.complex_indices:
1228
+ self._check_single_index(a, index)
1229
+
1230
+ class TestFloatNonIntegerArgument:
1231
+ """
1232
+ These test that ``TypeError`` is raised when you try to use
1233
+ non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
1234
+ and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.
1235
+
1236
+ """
1237
+ def test_valid_indexing(self):
1238
+ # These should raise no errors.
1239
+ a = np.array([[[5]]])
1240
+
1241
+ a[np.array([0])]
1242
+ a[[0, 0]]
1243
+ a[:, [0, 0]]
1244
+ a[:, 0,:]
1245
+ a[:,:,:]
1246
+
1247
+ def test_valid_slicing(self):
1248
+ # These should raise no errors.
1249
+ a = np.array([[[5]]])
1250
+
1251
+ a[::]
1252
+ a[0:]
1253
+ a[:2]
1254
+ a[0:2]
1255
+ a[::2]
1256
+ a[1::2]
1257
+ a[:2:2]
1258
+ a[1:2:2]
1259
+
1260
+ def test_non_integer_argument_errors(self):
1261
+ a = np.array([[5]])
1262
+
1263
+ assert_raises(TypeError, np.reshape, a, (1., 1., -1))
1264
+ assert_raises(TypeError, np.reshape, a, (np.array(1.), -1))
1265
+ assert_raises(TypeError, np.take, a, [0], 1.)
1266
+ assert_raises(TypeError, np.take, a, [0], np.float64(1.))
1267
+
1268
+ def test_non_integer_sequence_multiplication(self):
1269
+ # NumPy scalar sequence multiply should not work with non-integers
1270
+ def mult(a, b):
1271
+ return a * b
1272
+
1273
+ assert_raises(TypeError, mult, [1], np.float_(3))
1274
+ # following should be OK
1275
+ mult([1], np.int_(3))
1276
+
1277
+ def test_reduce_axis_float_index(self):
1278
+ d = np.zeros((3,3,3))
1279
+ assert_raises(TypeError, np.min, d, 0.5)
1280
+ assert_raises(TypeError, np.min, d, (0.5, 1))
1281
+ assert_raises(TypeError, np.min, d, (1, 2.2))
1282
+ assert_raises(TypeError, np.min, d, (.2, 1.2))
1283
+
1284
+
1285
+ class TestBooleanIndexing:
1286
+ # Using a boolean as integer argument/indexing is an error.
1287
+ def test_bool_as_int_argument_errors(self):
1288
+ a = np.array([[[1]]])
1289
+
1290
+ assert_raises(TypeError, np.reshape, a, (True, -1))
1291
+ assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))
1292
+ # Note that operator.index(np.array(True)) does not work, a boolean
1293
+ # array is thus also deprecated, but not with the same message:
1294
+ assert_raises(TypeError, operator.index, np.array(True))
1295
+ assert_warns(DeprecationWarning, operator.index, np.True_)
1296
+ assert_raises(TypeError, np.take, args=(a, [0], False))
1297
+
1298
+ def test_boolean_indexing_weirdness(self):
1299
+ # Weird boolean indexing things
1300
+ a = np.ones((2, 3, 4))
1301
+ assert a[False, True, ...].shape == (0, 2, 3, 4)
1302
+ assert a[True, [0, 1], True, True, [1], [[2]]].shape == (1, 2)
1303
+ assert_raises(IndexError, lambda: a[False, [0, 1], ...])
1304
+
1305
+ def test_boolean_indexing_fast_path(self):
1306
+ # These used to either give the wrong error, or incorrectly give no
1307
+ # error.
1308
+ a = np.ones((3, 3))
1309
+
1310
+ # This used to incorrectly work (and give an array of shape (0,))
1311
+ idx1 = np.array([[False]*9])
1312
+ assert_raises_regex(IndexError,
1313
+ "boolean index did not match indexed array along dimension 0; "
1314
+ "dimension is 3 but corresponding boolean dimension is 1",
1315
+ lambda: a[idx1])
1316
+
1317
+ # This used to incorrectly give a ValueError: operands could not be broadcast together
1318
+ idx2 = np.array([[False]*8 + [True]])
1319
+ assert_raises_regex(IndexError,
1320
+ "boolean index did not match indexed array along dimension 0; "
1321
+ "dimension is 3 but corresponding boolean dimension is 1",
1322
+ lambda: a[idx2])
1323
+
1324
+ # This is the same as it used to be. The above two should work like this.
1325
+ idx3 = np.array([[False]*10])
1326
+ assert_raises_regex(IndexError,
1327
+ "boolean index did not match indexed array along dimension 0; "
1328
+ "dimension is 3 but corresponding boolean dimension is 1",
1329
+ lambda: a[idx3])
1330
+
1331
+ # This used to give ValueError: non-broadcastable operand
1332
+ a = np.ones((1, 1, 2))
1333
+ idx = np.array([[[True], [False]]])
1334
+ assert_raises_regex(IndexError,
1335
+ "boolean index did not match indexed array along dimension 1; "
1336
+ "dimension is 1 but corresponding boolean dimension is 2",
1337
+ lambda: a[idx])
1338
+
1339
+
1340
+ class TestArrayToIndexDeprecation:
1341
+ """Creating an index from array not 0-D is an error.
1342
+
1343
+ """
1344
+ def test_array_to_index_error(self):
1345
+ # so no exception is expected. The raising is effectively tested above.
1346
+ a = np.array([[[1]]])
1347
+
1348
+ assert_raises(TypeError, operator.index, np.array([1]))
1349
+ assert_raises(TypeError, np.reshape, a, (a, -1))
1350
+ assert_raises(TypeError, np.take, a, [0], a)
1351
+
1352
+
1353
+ class TestNonIntegerArrayLike:
1354
+ """Tests that array_likes only valid if can safely cast to integer.
1355
+
1356
+ For instance, lists give IndexError when they cannot be safely cast to
1357
+ an integer.
1358
+
1359
+ """
1360
+ def test_basic(self):
1361
+ a = np.arange(10)
1362
+
1363
+ assert_raises(IndexError, a.__getitem__, [0.5, 1.5])
1364
+ assert_raises(IndexError, a.__getitem__, (['1', '2'],))
1365
+
1366
+ # The following is valid
1367
+ a.__getitem__([])
1368
+
1369
+
1370
+ class TestMultipleEllipsisError:
1371
+ """An index can only have a single ellipsis.
1372
+
1373
+ """
1374
+ def test_basic(self):
1375
+ a = np.arange(10)
1376
+ assert_raises(IndexError, lambda: a[..., ...])
1377
+ assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 2,))
1378
+ assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))
1379
+
1380
+
1381
+ class TestCApiAccess:
1382
+ def test_getitem(self):
1383
+ subscript = functools.partial(array_indexing, 0)
1384
+
1385
+ # 0-d arrays don't work:
1386
+ assert_raises(IndexError, subscript, np.ones(()), 0)
1387
+ # Out of bound values:
1388
+ assert_raises(IndexError, subscript, np.ones(10), 11)
1389
+ assert_raises(IndexError, subscript, np.ones(10), -11)
1390
+ assert_raises(IndexError, subscript, np.ones((10, 10)), 11)
1391
+ assert_raises(IndexError, subscript, np.ones((10, 10)), -11)
1392
+
1393
+ a = np.arange(10)
1394
+ assert_array_equal(a[4], subscript(a, 4))
1395
+ a = a.reshape(5, 2)
1396
+ assert_array_equal(a[-4], subscript(a, -4))
1397
+
1398
+ def test_setitem(self):
1399
+ assign = functools.partial(array_indexing, 1)
1400
+
1401
+ # Deletion is impossible:
1402
+ assert_raises(ValueError, assign, np.ones(10), 0)
1403
+ # 0-d arrays don't work:
1404
+ assert_raises(IndexError, assign, np.ones(()), 0, 0)
1405
+ # Out of bound values:
1406
+ assert_raises(IndexError, assign, np.ones(10), 11, 0)
1407
+ assert_raises(IndexError, assign, np.ones(10), -11, 0)
1408
+ assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0)
1409
+ assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0)
1410
+
1411
+ a = np.arange(10)
1412
+ assign(a, 4, 10)
1413
+ assert_(a[4] == 10)
1414
+
1415
+ a = a.reshape(5, 2)
1416
+ assign(a, 4, 10)
1417
+ assert_array_equal(a[-1], [10, 10])
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_memmap.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import mmap
4
+ import pytest
5
+ from pathlib import Path
6
+ from tempfile import NamedTemporaryFile, TemporaryFile
7
+
8
+ from numpy import (
9
+ memmap, sum, average, prod, ndarray, isscalar, add, subtract, multiply)
10
+
11
+ from numpy import arange, allclose, asarray
12
+ from numpy.testing import (
13
+ assert_, assert_equal, assert_array_equal, suppress_warnings, IS_PYPY,
14
+ break_cycles
15
+ )
16
+
17
+ class TestMemmap:
18
+ def setup_method(self):
19
+ self.tmpfp = NamedTemporaryFile(prefix='mmap')
20
+ self.shape = (3, 4)
21
+ self.dtype = 'float32'
22
+ self.data = arange(12, dtype=self.dtype)
23
+ self.data.resize(self.shape)
24
+
25
+ def teardown_method(self):
26
+ self.tmpfp.close()
27
+ self.data = None
28
+ if IS_PYPY:
29
+ break_cycles()
30
+ break_cycles()
31
+
32
+ def test_roundtrip(self):
33
+ # Write data to file
34
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
35
+ shape=self.shape)
36
+ fp[:] = self.data[:]
37
+ del fp # Test __del__ machinery, which handles cleanup
38
+
39
+ # Read data back from file
40
+ newfp = memmap(self.tmpfp, dtype=self.dtype, mode='r',
41
+ shape=self.shape)
42
+ assert_(allclose(self.data, newfp))
43
+ assert_array_equal(self.data, newfp)
44
+ assert_equal(newfp.flags.writeable, False)
45
+
46
+ def test_open_with_filename(self, tmp_path):
47
+ tmpname = tmp_path / 'mmap'
48
+ fp = memmap(tmpname, dtype=self.dtype, mode='w+',
49
+ shape=self.shape)
50
+ fp[:] = self.data[:]
51
+ del fp
52
+
53
+ def test_unnamed_file(self):
54
+ with TemporaryFile() as f:
55
+ fp = memmap(f, dtype=self.dtype, shape=self.shape)
56
+ del fp
57
+
58
+ def test_attributes(self):
59
+ offset = 1
60
+ mode = "w+"
61
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode=mode,
62
+ shape=self.shape, offset=offset)
63
+ assert_equal(offset, fp.offset)
64
+ assert_equal(mode, fp.mode)
65
+ del fp
66
+
67
+ def test_filename(self, tmp_path):
68
+ tmpname = tmp_path / "mmap"
69
+ fp = memmap(tmpname, dtype=self.dtype, mode='w+',
70
+ shape=self.shape)
71
+ abspath = Path(os.path.abspath(tmpname))
72
+ fp[:] = self.data[:]
73
+ assert_equal(abspath, fp.filename)
74
+ b = fp[:1]
75
+ assert_equal(abspath, b.filename)
76
+ del b
77
+ del fp
78
+
79
+ def test_path(self, tmp_path):
80
+ tmpname = tmp_path / "mmap"
81
+ fp = memmap(Path(tmpname), dtype=self.dtype, mode='w+',
82
+ shape=self.shape)
83
+ # os.path.realpath does not resolve symlinks on Windows
84
+ # see: https://bugs.python.org/issue9949
85
+ # use Path.resolve, just as memmap class does internally
86
+ abspath = str(Path(tmpname).resolve())
87
+ fp[:] = self.data[:]
88
+ assert_equal(abspath, str(fp.filename.resolve()))
89
+ b = fp[:1]
90
+ assert_equal(abspath, str(b.filename.resolve()))
91
+ del b
92
+ del fp
93
+
94
+ def test_filename_fileobj(self):
95
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+",
96
+ shape=self.shape)
97
+ assert_equal(fp.filename, self.tmpfp.name)
98
+
99
+ @pytest.mark.skipif(sys.platform == 'gnu0',
100
+ reason="Known to fail on hurd")
101
+ def test_flush(self):
102
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
103
+ shape=self.shape)
104
+ fp[:] = self.data[:]
105
+ assert_equal(fp[0], self.data[0])
106
+ fp.flush()
107
+
108
+ def test_del(self):
109
+ # Make sure a view does not delete the underlying mmap
110
+ fp_base = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
111
+ shape=self.shape)
112
+ fp_base[0] = 5
113
+ fp_view = fp_base[0:1]
114
+ assert_equal(fp_view[0], 5)
115
+ del fp_view
116
+ # Should still be able to access and assign values after
117
+ # deleting the view
118
+ assert_equal(fp_base[0], 5)
119
+ fp_base[0] = 6
120
+ assert_equal(fp_base[0], 6)
121
+
122
+ def test_arithmetic_drops_references(self):
123
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
124
+ shape=self.shape)
125
+ tmp = (fp + 10)
126
+ if isinstance(tmp, memmap):
127
+ assert_(tmp._mmap is not fp._mmap)
128
+
129
+ def test_indexing_drops_references(self):
130
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
131
+ shape=self.shape)
132
+ tmp = fp[(1, 2), (2, 3)]
133
+ if isinstance(tmp, memmap):
134
+ assert_(tmp._mmap is not fp._mmap)
135
+
136
+ def test_slicing_keeps_references(self):
137
+ fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+',
138
+ shape=self.shape)
139
+ assert_(fp[:2, :2]._mmap is fp._mmap)
140
+
141
+ def test_view(self):
142
+ fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
143
+ new1 = fp.view()
144
+ new2 = new1.view()
145
+ assert_(new1.base is fp)
146
+ assert_(new2.base is fp)
147
+ new_array = asarray(fp)
148
+ assert_(new_array.base is fp)
149
+
150
+ def test_ufunc_return_ndarray(self):
151
+ fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
152
+ fp[:] = self.data
153
+
154
+ with suppress_warnings() as sup:
155
+ sup.filter(FutureWarning, "np.average currently does not preserve")
156
+ for unary_op in [sum, average, prod]:
157
+ result = unary_op(fp)
158
+ assert_(isscalar(result))
159
+ assert_(result.__class__ is self.data[0, 0].__class__)
160
+
161
+ assert_(unary_op(fp, axis=0).__class__ is ndarray)
162
+ assert_(unary_op(fp, axis=1).__class__ is ndarray)
163
+
164
+ for binary_op in [add, subtract, multiply]:
165
+ assert_(binary_op(fp, self.data).__class__ is ndarray)
166
+ assert_(binary_op(self.data, fp).__class__ is ndarray)
167
+ assert_(binary_op(fp, fp).__class__ is ndarray)
168
+
169
+ fp += 1
170
+ assert(fp.__class__ is memmap)
171
+ add(fp, 1, out=fp)
172
+ assert(fp.__class__ is memmap)
173
+
174
+ def test_getitem(self):
175
+ fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape)
176
+ fp[:] = self.data
177
+
178
+ assert_(fp[1:, :-1].__class__ is memmap)
179
+ # Fancy indexing returns a copy that is not memmapped
180
+ assert_(fp[[0, 1]].__class__ is ndarray)
181
+
182
+ def test_memmap_subclass(self):
183
+ class MemmapSubClass(memmap):
184
+ pass
185
+
186
+ fp = MemmapSubClass(self.tmpfp, dtype=self.dtype, shape=self.shape)
187
+ fp[:] = self.data
188
+
189
+ # We keep previous behavior for subclasses of memmap, i.e. the
190
+ # ufunc and __getitem__ output is never turned into a ndarray
191
+ assert_(sum(fp, axis=0).__class__ is MemmapSubClass)
192
+ assert_(sum(fp).__class__ is MemmapSubClass)
193
+ assert_(fp[1:, :-1].__class__ is MemmapSubClass)
194
+ assert(fp[[0, 1]].__class__ is MemmapSubClass)
195
+
196
+ def test_mmap_offset_greater_than_allocation_granularity(self):
197
+ size = 5 * mmap.ALLOCATIONGRANULARITY
198
+ offset = mmap.ALLOCATIONGRANULARITY + 1
199
+ fp = memmap(self.tmpfp, shape=size, mode='w+', offset=offset)
200
+ assert_(fp.offset == offset)
201
+
202
+ def test_no_shape(self):
203
+ self.tmpfp.write(b'a'*16)
204
+ mm = memmap(self.tmpfp, dtype='float64')
205
+ assert_equal(mm.shape, (2,))
206
+
207
+ def test_empty_array(self):
208
+ # gh-12653
209
+ with pytest.raises(ValueError, match='empty file'):
210
+ memmap(self.tmpfp, shape=(0,4), mode='w+')
211
+
212
+ self.tmpfp.write(b'\0')
213
+
214
+ # ok now the file is not empty
215
+ memmap(self.tmpfp, shape=(0,4), mode='w+')
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_records.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ import textwrap
3
+ from io import BytesIO
4
+ from os import path
5
+ from pathlib import Path
6
+ import pytest
7
+
8
+ import numpy as np
9
+ from numpy.testing import (
10
+ assert_, assert_equal, assert_array_equal, assert_array_almost_equal,
11
+ assert_raises, temppath,
12
+ )
13
+ from numpy.compat import pickle
14
+
15
+
16
+ class TestFromrecords:
17
+ def test_fromrecords(self):
18
+ r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
19
+ names='col1,col2,col3')
20
+ assert_equal(r[0].item(), (456, 'dbe', 1.2))
21
+ assert_equal(r['col1'].dtype.kind, 'i')
22
+ assert_equal(r['col2'].dtype.kind, 'U')
23
+ assert_equal(r['col2'].dtype.itemsize, 12)
24
+ assert_equal(r['col3'].dtype.kind, 'f')
25
+
26
+ def test_fromrecords_0len(self):
27
+ """ Verify fromrecords works with a 0-length input """
28
+ dtype = [('a', float), ('b', float)]
29
+ r = np.rec.fromrecords([], dtype=dtype)
30
+ assert_equal(r.shape, (0,))
31
+
32
+ def test_fromrecords_2d(self):
33
+ data = [
34
+ [(1, 2), (3, 4), (5, 6)],
35
+ [(6, 5), (4, 3), (2, 1)]
36
+ ]
37
+ expected_a = [[1, 3, 5], [6, 4, 2]]
38
+ expected_b = [[2, 4, 6], [5, 3, 1]]
39
+
40
+ # try with dtype
41
+ r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
42
+ assert_equal(r1['a'], expected_a)
43
+ assert_equal(r1['b'], expected_b)
44
+
45
+ # try with names
46
+ r2 = np.rec.fromrecords(data, names=['a', 'b'])
47
+ assert_equal(r2['a'], expected_a)
48
+ assert_equal(r2['b'], expected_b)
49
+
50
+ assert_equal(r1, r2)
51
+
52
+ def test_method_array(self):
53
+ r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big')
54
+ assert_equal(r[1].item(), (25444, b'efg', 1633837924))
55
+
56
+ def test_method_array2(self):
57
+ r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
58
+ (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
59
+ assert_equal(r[1].item(), (2, 22.0, b'b'))
60
+
61
+ def test_recarray_slices(self):
62
+ r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
63
+ (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
64
+ assert_equal(r[1::2][1].item(), (4, 44.0, b'd'))
65
+
66
+ def test_recarray_fromarrays(self):
67
+ x1 = np.array([1, 2, 3, 4])
68
+ x2 = np.array(['a', 'dd', 'xyz', '12'])
69
+ x3 = np.array([1.1, 2, 3, 4])
70
+ r = np.rec.fromarrays([x1, x2, x3], names='a,b,c')
71
+ assert_equal(r[1].item(), (2, 'dd', 2.0))
72
+ x1[1] = 34
73
+ assert_equal(r.a, np.array([1, 2, 3, 4]))
74
+
75
+ def test_recarray_fromfile(self):
76
+ data_dir = path.join(path.dirname(__file__), 'data')
77
+ filename = path.join(data_dir, 'recarray_from_file.fits')
78
+ fd = open(filename, 'rb')
79
+ fd.seek(2880 * 2)
80
+ r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
81
+ fd.seek(2880 * 2)
82
+ r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big')
83
+ fd.seek(2880 * 2)
84
+ bytes_array = BytesIO()
85
+ bytes_array.write(fd.read())
86
+ bytes_array.seek(0)
87
+ r3 = np.rec.fromfile(bytes_array, formats='f8,i4,a5', shape=3, byteorder='big')
88
+ fd.close()
89
+ assert_equal(r1, r2)
90
+ assert_equal(r2, r3)
91
+
92
+ def test_recarray_from_obj(self):
93
+ count = 10
94
+ a = np.zeros(count, dtype='O')
95
+ b = np.zeros(count, dtype='f8')
96
+ c = np.zeros(count, dtype='f8')
97
+ for i in range(len(a)):
98
+ a[i] = list(range(1, 10))
99
+
100
+ mine = np.rec.fromarrays([a, b, c], names='date,data1,data2')
101
+ for i in range(len(a)):
102
+ assert_((mine.date[i] == list(range(1, 10))))
103
+ assert_((mine.data1[i] == 0.0))
104
+ assert_((mine.data2[i] == 0.0))
105
+
106
+ def test_recarray_repr(self):
107
+ a = np.array([(1, 0.1), (2, 0.2)],
108
+ dtype=[('foo', '<i4'), ('bar', '<f8')])
109
+ a = np.rec.array(a)
110
+ assert_equal(
111
+ repr(a),
112
+ textwrap.dedent("""\
113
+ rec.array([(1, 0.1), (2, 0.2)],
114
+ dtype=[('foo', '<i4'), ('bar', '<f8')])""")
115
+ )
116
+
117
+ # make sure non-structured dtypes also show up as rec.array
118
+ a = np.array(np.ones(4, dtype='f8'))
119
+ assert_(repr(np.rec.array(a)).startswith('rec.array'))
120
+
121
+ # check that the 'np.record' part of the dtype isn't shown
122
+ a = np.rec.array(np.ones(3, dtype='i4,i4'))
123
+ assert_equal(repr(a).find('numpy.record'), -1)
124
+ a = np.rec.array(np.ones(3, dtype='i4'))
125
+ assert_(repr(a).find('dtype=int32') != -1)
126
+
127
+ def test_0d_recarray_repr(self):
128
+ arr_0d = np.rec.array((1, 2.0, '2003'), dtype='<i4,<f8,<M8[Y]')
129
+ assert_equal(repr(arr_0d), textwrap.dedent("""\
130
+ rec.array((1, 2., '2003'),
131
+ dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '<M8[Y]')])"""))
132
+
133
+ record = arr_0d[()]
134
+ assert_equal(repr(record), "(1, 2., '2003')")
135
+ # 1.13 converted to python scalars before the repr
136
+ try:
137
+ np.set_printoptions(legacy='1.13')
138
+ assert_equal(repr(record), '(1, 2.0, datetime.date(2003, 1, 1))')
139
+ finally:
140
+ np.set_printoptions(legacy=False)
141
+
142
+ def test_recarray_from_repr(self):
143
+ a = np.array([(1,'ABC'), (2, "DEF")],
144
+ dtype=[('foo', int), ('bar', 'S4')])
145
+ recordarr = np.rec.array(a)
146
+ recarr = a.view(np.recarray)
147
+ recordview = a.view(np.dtype((np.record, a.dtype)))
148
+
149
+ recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np})
150
+ recarr_r = eval("numpy." + repr(recarr), {'numpy': np})
151
+ recordview_r = eval("numpy." + repr(recordview), {'numpy': np})
152
+
153
+ assert_equal(type(recordarr_r), np.recarray)
154
+ assert_equal(recordarr_r.dtype.type, np.record)
155
+ assert_equal(recordarr, recordarr_r)
156
+
157
+ assert_equal(type(recarr_r), np.recarray)
158
+ assert_equal(recarr_r.dtype.type, np.record)
159
+ assert_equal(recarr, recarr_r)
160
+
161
+ assert_equal(type(recordview_r), np.ndarray)
162
+ assert_equal(recordview.dtype.type, np.record)
163
+ assert_equal(recordview, recordview_r)
164
+
165
+ def test_recarray_views(self):
166
+ a = np.array([(1,'ABC'), (2, "DEF")],
167
+ dtype=[('foo', int), ('bar', 'S4')])
168
+ b = np.array([1,2,3,4,5], dtype=np.int64)
169
+
170
+ #check that np.rec.array gives right dtypes
171
+ assert_equal(np.rec.array(a).dtype.type, np.record)
172
+ assert_equal(type(np.rec.array(a)), np.recarray)
173
+ assert_equal(np.rec.array(b).dtype.type, np.int64)
174
+ assert_equal(type(np.rec.array(b)), np.recarray)
175
+
176
+ #check that viewing as recarray does the same
177
+ assert_equal(a.view(np.recarray).dtype.type, np.record)
178
+ assert_equal(type(a.view(np.recarray)), np.recarray)
179
+ assert_equal(b.view(np.recarray).dtype.type, np.int64)
180
+ assert_equal(type(b.view(np.recarray)), np.recarray)
181
+
182
+ #check that view to non-structured dtype preserves type=np.recarray
183
+ r = np.rec.array(np.ones(4, dtype="f4,i4"))
184
+ rv = r.view('f8').view('f4,i4')
185
+ assert_equal(type(rv), np.recarray)
186
+ assert_equal(rv.dtype.type, np.record)
187
+
188
+ #check that getitem also preserves np.recarray and np.record
189
+ r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
190
+ ('c', 'i4,i4')]))
191
+ assert_equal(r['c'].dtype.type, np.record)
192
+ assert_equal(type(r['c']), np.recarray)
193
+
194
+ #and that it preserves subclasses (gh-6949)
195
+ class C(np.recarray):
196
+ pass
197
+
198
+ c = r.view(C)
199
+ assert_equal(type(c['c']), C)
200
+
201
+ # check that accessing nested structures keep record type, but
202
+ # not for subarrays, non-void structures, non-structured voids
203
+ test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)),
204
+ ('d', ('i8', 'i4,i4'))]
205
+ r = np.rec.array([((1,1), b'11111111', [1,1], 1),
206
+ ((1,1), b'11111111', [1,1], 1)], dtype=test_dtype)
207
+ assert_equal(r.a.dtype.type, np.record)
208
+ assert_equal(r.b.dtype.type, np.void)
209
+ assert_equal(r.c.dtype.type, np.float32)
210
+ assert_equal(r.d.dtype.type, np.int64)
211
+ # check the same, but for views
212
+ r = np.rec.array(np.ones(4, dtype='i4,i4'))
213
+ assert_equal(r.view('f4,f4').dtype.type, np.record)
214
+ assert_equal(r.view(('i4',2)).dtype.type, np.int32)
215
+ assert_equal(r.view('V8').dtype.type, np.void)
216
+ assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
217
+
218
+ #check that we can undo the view
219
+ arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
220
+ for arr in arrs:
221
+ rec = np.rec.array(arr)
222
+ # recommended way to view as an ndarray:
223
+ arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray)
224
+ assert_equal(arr2.dtype.type, arr.dtype.type)
225
+ assert_equal(type(arr2), type(arr))
226
+
227
+ def test_recarray_from_names(self):
228
+ ra = np.rec.array([
229
+ (1, 'abc', 3.7000002861022949, 0),
230
+ (2, 'xy', 6.6999998092651367, 1),
231
+ (0, ' ', 0.40000000596046448, 0)],
232
+ names='c1, c2, c3, c4')
233
+ pa = np.rec.fromrecords([
234
+ (1, 'abc', 3.7000002861022949, 0),
235
+ (2, 'xy', 6.6999998092651367, 1),
236
+ (0, ' ', 0.40000000596046448, 0)],
237
+ names='c1, c2, c3, c4')
238
+ assert_(ra.dtype == pa.dtype)
239
+ assert_(ra.shape == pa.shape)
240
+ for k in range(len(ra)):
241
+ assert_(ra[k].item() == pa[k].item())
242
+
243
+ def test_recarray_conflict_fields(self):
244
+ ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
245
+ (3, 'wrs', 1.3)],
246
+ names='field, shape, mean')
247
+ ra.mean = [1.1, 2.2, 3.3]
248
+ assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3])
249
+ assert_(type(ra.mean) is type(ra.var))
250
+ ra.shape = (1, 3)
251
+ assert_(ra.shape == (1, 3))
252
+ ra.shape = ['A', 'B', 'C']
253
+ assert_array_equal(ra['shape'], [['A', 'B', 'C']])
254
+ ra.field = 5
255
+ assert_array_equal(ra['field'], [[5, 5, 5]])
256
+ assert_(isinstance(ra.field, collections.abc.Callable))
257
+
258
+ def test_fromrecords_with_explicit_dtype(self):
259
+ a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
260
+ dtype=[('a', int), ('b', object)])
261
+ assert_equal(a.a, [1, 2])
262
+ assert_equal(a[0].a, 1)
263
+ assert_equal(a.b, ['a', 'bbb'])
264
+ assert_equal(a[-1].b, 'bbb')
265
+ #
266
+ ndtype = np.dtype([('a', int), ('b', object)])
267
+ a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype)
268
+ assert_equal(a.a, [1, 2])
269
+ assert_equal(a[0].a, 1)
270
+ assert_equal(a.b, ['a', 'bbb'])
271
+ assert_equal(a[-1].b, 'bbb')
272
+
273
+ def test_recarray_stringtypes(self):
274
+ # Issue #3993
275
+ a = np.array([('abc ', 1), ('abc', 2)],
276
+ dtype=[('foo', 'S4'), ('bar', int)])
277
+ a = a.view(np.recarray)
278
+ assert_equal(a.foo[0] == a.foo[1], False)
279
+
280
+ def test_recarray_returntypes(self):
281
+ qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)}
282
+ a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')),
283
+ ('abc', (2,3), 1, ('abcde', 'jklmn'))],
284
+ dtype=[('foo', 'S4'),
285
+ ('bar', [('A', int), ('B', int)]),
286
+ ('baz', int), ('qux', qux_fields)])
287
+ assert_equal(type(a.foo), np.ndarray)
288
+ assert_equal(type(a['foo']), np.ndarray)
289
+ assert_equal(type(a.bar), np.recarray)
290
+ assert_equal(type(a['bar']), np.recarray)
291
+ assert_equal(a.bar.dtype.type, np.record)
292
+ assert_equal(type(a['qux']), np.recarray)
293
+ assert_equal(a.qux.dtype.type, np.record)
294
+ assert_equal(dict(a.qux.dtype.fields), qux_fields)
295
+ assert_equal(type(a.baz), np.ndarray)
296
+ assert_equal(type(a['baz']), np.ndarray)
297
+ assert_equal(type(a[0].bar), np.record)
298
+ assert_equal(type(a[0]['bar']), np.record)
299
+ assert_equal(a[0].bar.A, 1)
300
+ assert_equal(a[0].bar['A'], 1)
301
+ assert_equal(a[0]['bar'].A, 1)
302
+ assert_equal(a[0]['bar']['A'], 1)
303
+ assert_equal(a[0].qux.D, b'fgehi')
304
+ assert_equal(a[0].qux['D'], b'fgehi')
305
+ assert_equal(a[0]['qux'].D, b'fgehi')
306
+ assert_equal(a[0]['qux']['D'], b'fgehi')
307
+
308
+ def test_zero_width_strings(self):
309
+ # Test for #6430, based on the test case from #1901
310
+
311
+ cols = [['test'] * 3, [''] * 3]
312
+ rec = np.rec.fromarrays(cols)
313
+ assert_equal(rec['f0'], ['test', 'test', 'test'])
314
+ assert_equal(rec['f1'], ['', '', ''])
315
+
316
+ dt = np.dtype([('f0', '|S4'), ('f1', '|S')])
317
+ rec = np.rec.fromarrays(cols, dtype=dt)
318
+ assert_equal(rec.itemsize, 4)
319
+ assert_equal(rec['f0'], [b'test', b'test', b'test'])
320
+ assert_equal(rec['f1'], [b'', b'', b''])
321
+
322
+
323
+ class TestPathUsage:
324
+ # Test that pathlib.Path can be used
325
+ def test_tofile_fromfile(self):
326
+ with temppath(suffix='.bin') as path:
327
+ path = Path(path)
328
+ np.random.seed(123)
329
+ a = np.random.rand(10).astype('f8,i4,a5')
330
+ a[5] = (0.5,10,'abcde')
331
+ with path.open("wb") as fd:
332
+ a.tofile(fd)
333
+ x = np.core.records.fromfile(path,
334
+ formats='f8,i4,a5',
335
+ shape=10)
336
+ assert_array_equal(x, a)
337
+
338
+
339
+ class TestRecord:
340
+ def setup_method(self):
341
+ self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
342
+ dtype=[("col1", "<i4"),
343
+ ("col2", "<i4"),
344
+ ("col3", "<i4")])
345
+
346
+ def test_assignment1(self):
347
+ a = self.data
348
+ assert_equal(a.col1[0], 1)
349
+ a[0].col1 = 0
350
+ assert_equal(a.col1[0], 0)
351
+
352
+ def test_assignment2(self):
353
+ a = self.data
354
+ assert_equal(a.col1[0], 1)
355
+ a.col1[0] = 0
356
+ assert_equal(a.col1[0], 0)
357
+
358
+ def test_invalid_assignment(self):
359
+ a = self.data
360
+
361
+ def assign_invalid_column(x):
362
+ x[0].col5 = 1
363
+
364
+ assert_raises(AttributeError, assign_invalid_column, a)
365
+
366
+ def test_nonwriteable_setfield(self):
367
+ # gh-8171
368
+ r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')])
369
+ r.flags.writeable = False
370
+ with assert_raises(ValueError):
371
+ r.f = [2, 3]
372
+ with assert_raises(ValueError):
373
+ r.setfield([2,3], *r.dtype.fields['f'])
374
+
375
+ def test_out_of_order_fields(self):
376
+ # names in the same order, padding added to descr
377
+ x = self.data[['col1', 'col2']]
378
+ assert_equal(x.dtype.names, ('col1', 'col2'))
379
+ assert_equal(x.dtype.descr,
380
+ [('col1', '<i4'), ('col2', '<i4'), ('', '|V4')])
381
+
382
+ # names change order to match indexing, as of 1.14 - descr can't
383
+ # represent that
384
+ y = self.data[['col2', 'col1']]
385
+ assert_equal(y.dtype.names, ('col2', 'col1'))
386
+ assert_raises(ValueError, lambda: y.dtype.descr)
387
+
388
+ def test_pickle_1(self):
389
+ # Issue #1529
390
+ a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
391
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
392
+ assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto)))
393
+ assert_equal(a[0], pickle.loads(pickle.dumps(a[0],
394
+ protocol=proto)))
395
+
396
+ def test_pickle_2(self):
397
+ a = self.data
398
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
399
+ assert_equal(a, pickle.loads(pickle.dumps(a, protocol=proto)))
400
+ assert_equal(a[0], pickle.loads(pickle.dumps(a[0],
401
+ protocol=proto)))
402
+
403
+ def test_pickle_3(self):
404
+ # Issue #7140
405
+ a = self.data
406
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
407
+ pa = pickle.loads(pickle.dumps(a[0], protocol=proto))
408
+ assert_(pa.flags.c_contiguous)
409
+ assert_(pa.flags.f_contiguous)
410
+ assert_(pa.flags.writeable)
411
+ assert_(pa.flags.aligned)
412
+
413
+ def test_pickle_void(self):
414
+ # issue gh-13593
415
+ dt = np.dtype([('obj', 'O'), ('int', 'i')])
416
+ a = np.empty(1, dtype=dt)
417
+ data = (bytearray(b'eman'),)
418
+ a['obj'] = data
419
+ a['int'] = 42
420
+ ctor, args = a[0].__reduce__()
421
+ # check the constructor is what we expect before interpreting the arguments
422
+ assert ctor is np.core.multiarray.scalar
423
+ dtype, obj = args
424
+ # make sure we did not pickle the address
425
+ assert not isinstance(obj, bytes)
426
+
427
+ assert_raises(RuntimeError, ctor, dtype, 13)
428
+
429
+ # Test roundtrip:
430
+ dump = pickle.dumps(a[0])
431
+ unpickled = pickle.loads(dump)
432
+ assert a[0] == unpickled
433
+
434
+ # Also check the similar (impossible) "object scalar" path:
435
+ with pytest.warns(DeprecationWarning):
436
+ assert ctor(np.dtype("O"), data) is data
437
+
438
+ def test_objview_record(self):
439
+ # https://github.com/numpy/numpy/issues/2599
440
+ dt = np.dtype([('foo', 'i8'), ('bar', 'O')])
441
+ r = np.zeros((1,3), dtype=dt).view(np.recarray)
442
+ r.foo = np.array([1, 2, 3]) # TypeError?
443
+
444
+ # https://github.com/numpy/numpy/issues/3256
445
+ ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)])
446
+ ra[['x','y']] # TypeError?
447
+
448
+ def test_record_scalar_setitem(self):
449
+ # https://github.com/numpy/numpy/issues/3561
450
+ rec = np.recarray(1, dtype=[('x', float, 5)])
451
+ rec[0].x = 1
452
+ assert_equal(rec[0].x, np.ones(5))
453
+
454
+ def test_missing_field(self):
455
+ # https://github.com/numpy/numpy/issues/4806
456
+ arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
457
+ assert_raises(KeyError, lambda: arr[['nofield']])
458
+
459
+ def test_fromarrays_nested_structured_arrays(self):
460
+ arrays = [
461
+ np.arange(10),
462
+ np.ones(10, dtype=[('a', '<u2'), ('b', '<f4')]),
463
+ ]
464
+ arr = np.rec.fromarrays(arrays) # ValueError?
465
+
466
+ @pytest.mark.parametrize('nfields', [0, 1, 2])
467
+ def test_assign_dtype_attribute(self, nfields):
468
+ dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields])
469
+ data = np.zeros(3, dt).view(np.recarray)
470
+
471
+ # the original and resulting dtypes differ on whether they are records
472
+ assert data.dtype.type == np.record
473
+ assert dt.type != np.record
474
+
475
+ # ensure that the dtype remains a record even when assigned
476
+ data.dtype = dt
477
+ assert data.dtype.type == np.record
478
+
479
+ @pytest.mark.parametrize('nfields', [0, 1, 2])
480
+ def test_nested_fields_are_records(self, nfields):
481
+ """ Test that nested structured types are treated as records too """
482
+ dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)][:nfields])
483
+ dt_outer = np.dtype([('inner', dt)])
484
+
485
+ data = np.zeros(3, dt_outer).view(np.recarray)
486
+ assert isinstance(data, np.recarray)
487
+ assert isinstance(data['inner'], np.recarray)
488
+
489
+ data0 = data[0]
490
+ assert isinstance(data0, np.record)
491
+ assert isinstance(data0['inner'], np.record)
492
+
493
+ def test_nested_dtype_padding(self):
494
+ """ test that trailing padding is preserved """
495
+ # construct a dtype with padding at the end
496
+ dt = np.dtype([('a', np.uint8), ('b', np.uint8), ('c', np.uint8)])
497
+ dt_padded_end = dt[['a', 'b']]
498
+ assert dt_padded_end.itemsize == dt.itemsize
499
+
500
+ dt_outer = np.dtype([('inner', dt_padded_end)])
501
+
502
+ data = np.zeros(3, dt_outer).view(np.recarray)
503
+ assert_equal(data['inner'].dtype, dt_padded_end)
504
+
505
+ data0 = data[0]
506
+ assert_equal(data0['inner'].dtype, dt_padded_end)
507
+
508
+
509
+ def test_find_duplicate():
510
+ l1 = [1, 2, 3, 4, 5, 6]
511
+ assert_(np.rec.find_duplicate(l1) == [])
512
+
513
+ l2 = [1, 2, 1, 4, 5, 6]
514
+ assert_(np.rec.find_duplicate(l2) == [1])
515
+
516
+ l3 = [1, 2, 1, 4, 1, 6, 2, 3]
517
+ assert_(np.rec.find_duplicate(l3) == [1, 2])
518
+
519
+ l3 = [2, 2, 1, 4, 1, 6, 2, 3]
520
+ assert_(np.rec.find_duplicate(l3) == [2, 1])
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalar_methods.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test the scalar constructors, which also do type-coercion
3
+ """
4
+ import fractions
5
+ import platform
6
+ import types
7
+ from typing import Any, Type
8
+
9
+ import pytest
10
+ import numpy as np
11
+
12
+ from numpy.testing import assert_equal, assert_raises, IS_MUSL
13
+
14
+
15
+ class TestAsIntegerRatio:
16
+ # derived in part from the cpython test "test_floatasratio"
17
+
18
+ @pytest.mark.parametrize("ftype", [
19
+ np.half, np.single, np.double, np.longdouble])
20
+ @pytest.mark.parametrize("f, ratio", [
21
+ (0.875, (7, 8)),
22
+ (-0.875, (-7, 8)),
23
+ (0.0, (0, 1)),
24
+ (11.5, (23, 2)),
25
+ ])
26
+ def test_small(self, ftype, f, ratio):
27
+ assert_equal(ftype(f).as_integer_ratio(), ratio)
28
+
29
+ @pytest.mark.parametrize("ftype", [
30
+ np.half, np.single, np.double, np.longdouble])
31
+ def test_simple_fractions(self, ftype):
32
+ R = fractions.Fraction
33
+ assert_equal(R(0, 1),
34
+ R(*ftype(0.0).as_integer_ratio()))
35
+ assert_equal(R(5, 2),
36
+ R(*ftype(2.5).as_integer_ratio()))
37
+ assert_equal(R(1, 2),
38
+ R(*ftype(0.5).as_integer_ratio()))
39
+ assert_equal(R(-2100, 1),
40
+ R(*ftype(-2100.0).as_integer_ratio()))
41
+
42
+ @pytest.mark.parametrize("ftype", [
43
+ np.half, np.single, np.double, np.longdouble])
44
+ def test_errors(self, ftype):
45
+ assert_raises(OverflowError, ftype('inf').as_integer_ratio)
46
+ assert_raises(OverflowError, ftype('-inf').as_integer_ratio)
47
+ assert_raises(ValueError, ftype('nan').as_integer_ratio)
48
+
49
+ def test_against_known_values(self):
50
+ R = fractions.Fraction
51
+ assert_equal(R(1075, 512),
52
+ R(*np.half(2.1).as_integer_ratio()))
53
+ assert_equal(R(-1075, 512),
54
+ R(*np.half(-2.1).as_integer_ratio()))
55
+ assert_equal(R(4404019, 2097152),
56
+ R(*np.single(2.1).as_integer_ratio()))
57
+ assert_equal(R(-4404019, 2097152),
58
+ R(*np.single(-2.1).as_integer_ratio()))
59
+ assert_equal(R(4728779608739021, 2251799813685248),
60
+ R(*np.double(2.1).as_integer_ratio()))
61
+ assert_equal(R(-4728779608739021, 2251799813685248),
62
+ R(*np.double(-2.1).as_integer_ratio()))
63
+ # longdouble is platform dependent
64
+
65
+ @pytest.mark.parametrize("ftype, frac_vals, exp_vals", [
66
+ # dtype test cases generated using hypothesis
67
+ # first five generated cases per dtype
68
+ (np.half, [0.0, 0.01154830649280303, 0.31082276347447274,
69
+ 0.527350517124794, 0.8308562335072596],
70
+ [0, 1, 0, -8, 12]),
71
+ (np.single, [0.0, 0.09248576989263226, 0.8160498218131407,
72
+ 0.17389442853722373, 0.7956044195067877],
73
+ [0, 12, 10, 17, -26]),
74
+ (np.double, [0.0, 0.031066908499895136, 0.5214135908877832,
75
+ 0.45780736035689296, 0.5906586745934036],
76
+ [0, -801, 51, 194, -653]),
77
+ pytest.param(
78
+ np.longdouble,
79
+ [0.0, 0.20492557202724854, 0.4277180662199366, 0.9888085019891495,
80
+ 0.9620175814461964],
81
+ [0, -7400, 14266, -7822, -8721],
82
+ marks=[
83
+ pytest.mark.skipif(
84
+ np.finfo(np.double) == np.finfo(np.longdouble),
85
+ reason="long double is same as double"),
86
+ pytest.mark.skipif(
87
+ platform.machine().startswith("ppc"),
88
+ reason="IBM double double"),
89
+ ]
90
+ )
91
+ ])
92
+ def test_roundtrip(self, ftype, frac_vals, exp_vals):
93
+ for frac, exp in zip(frac_vals, exp_vals):
94
+ f = np.ldexp(ftype(frac), exp)
95
+ assert f.dtype == ftype
96
+ n, d = f.as_integer_ratio()
97
+
98
+ try:
99
+ nf = np.longdouble(n)
100
+ df = np.longdouble(d)
101
+ if not np.isfinite(df):
102
+ raise OverflowError
103
+ except (OverflowError, RuntimeWarning):
104
+ # the values may not fit in any float type
105
+ pytest.skip("longdouble too small on this platform")
106
+
107
+ assert_equal(nf / df, f, "{}/{}".format(n, d))
108
+
109
+
110
+ class TestIsInteger:
111
+ @pytest.mark.parametrize("str_value", ["inf", "nan"])
112
+ @pytest.mark.parametrize("code", np.typecodes["Float"])
113
+ def test_special(self, code: str, str_value: str) -> None:
114
+ cls = np.dtype(code).type
115
+ value = cls(str_value)
116
+ assert not value.is_integer()
117
+
118
+ @pytest.mark.parametrize(
119
+ "code", np.typecodes["Float"] + np.typecodes["AllInteger"]
120
+ )
121
+ def test_true(self, code: str) -> None:
122
+ float_array = np.arange(-5, 5).astype(code)
123
+ for value in float_array:
124
+ assert value.is_integer()
125
+
126
+ @pytest.mark.parametrize("code", np.typecodes["Float"])
127
+ def test_false(self, code: str) -> None:
128
+ float_array = np.arange(-5, 5).astype(code)
129
+ float_array *= 1.1
130
+ for value in float_array:
131
+ if value == 0:
132
+ continue
133
+ assert not value.is_integer()
134
+
135
+
136
+ class TestClassGetItem:
137
+ @pytest.mark.parametrize("cls", [
138
+ np.number,
139
+ np.integer,
140
+ np.inexact,
141
+ np.unsignedinteger,
142
+ np.signedinteger,
143
+ np.floating,
144
+ ])
145
+ def test_abc(self, cls: Type[np.number]) -> None:
146
+ alias = cls[Any]
147
+ assert isinstance(alias, types.GenericAlias)
148
+ assert alias.__origin__ is cls
149
+
150
+ def test_abc_complexfloating(self) -> None:
151
+ alias = np.complexfloating[Any, Any]
152
+ assert isinstance(alias, types.GenericAlias)
153
+ assert alias.__origin__ is np.complexfloating
154
+
155
+ @pytest.mark.parametrize("arg_len", range(4))
156
+ def test_abc_complexfloating_subscript_tuple(self, arg_len: int) -> None:
157
+ arg_tup = (Any,) * arg_len
158
+ if arg_len in (1, 2):
159
+ assert np.complexfloating[arg_tup]
160
+ else:
161
+ match = f"Too {'few' if arg_len == 0 else 'many'} arguments"
162
+ with pytest.raises(TypeError, match=match):
163
+ np.complexfloating[arg_tup]
164
+
165
+ @pytest.mark.parametrize("cls", [np.generic, np.flexible, np.character])
166
+ def test_abc_non_numeric(self, cls: Type[np.generic]) -> None:
167
+ with pytest.raises(TypeError):
168
+ cls[Any]
169
+
170
+ @pytest.mark.parametrize("code", np.typecodes["All"])
171
+ def test_concrete(self, code: str) -> None:
172
+ cls = np.dtype(code).type
173
+ with pytest.raises(TypeError):
174
+ cls[Any]
175
+
176
+ @pytest.mark.parametrize("arg_len", range(4))
177
+ def test_subscript_tuple(self, arg_len: int) -> None:
178
+ arg_tup = (Any,) * arg_len
179
+ if arg_len == 1:
180
+ assert np.number[arg_tup]
181
+ else:
182
+ with pytest.raises(TypeError):
183
+ np.number[arg_tup]
184
+
185
+ def test_subscript_scalar(self) -> None:
186
+ assert np.number[Any]
187
+
188
+
189
+ class TestBitCount:
190
+ # derived in part from the cpython test "test_bit_count"
191
+
192
+ @pytest.mark.parametrize("itype", np.sctypes['int']+np.sctypes['uint'])
193
+ def test_small(self, itype):
194
+ for a in range(max(np.iinfo(itype).min, 0), 128):
195
+ msg = f"Smoke test for {itype}({a}).bit_count()"
196
+ assert itype(a).bit_count() == bin(a).count("1"), msg
197
+
198
+ def test_bit_count(self):
199
+ for exp in [10, 17, 63]:
200
+ a = 2**exp
201
+ assert np.uint64(a).bit_count() == 1
202
+ assert np.uint64(a - 1).bit_count() == exp
203
+ assert np.uint64(a ^ 63).bit_count() == 7
204
+ assert np.uint64((a - 1) ^ 510).bit_count() == exp - 8
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalarbuffer.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test scalar buffer interface adheres to PEP 3118
3
+ """
4
+ import numpy as np
5
+ from numpy.core._rational_tests import rational
6
+ from numpy.core._multiarray_tests import get_buffer_info
7
+ import pytest
8
+
9
+ from numpy.testing import assert_, assert_equal, assert_raises
10
+
11
+ # PEP3118 format strings for native (standard alignment and byteorder) types
12
+ scalars_and_codes = [
13
+ (np.bool_, '?'),
14
+ (np.byte, 'b'),
15
+ (np.short, 'h'),
16
+ (np.intc, 'i'),
17
+ (np.int_, 'l'),
18
+ (np.longlong, 'q'),
19
+ (np.ubyte, 'B'),
20
+ (np.ushort, 'H'),
21
+ (np.uintc, 'I'),
22
+ (np.uint, 'L'),
23
+ (np.ulonglong, 'Q'),
24
+ (np.half, 'e'),
25
+ (np.single, 'f'),
26
+ (np.double, 'd'),
27
+ (np.longdouble, 'g'),
28
+ (np.csingle, 'Zf'),
29
+ (np.cdouble, 'Zd'),
30
+ (np.clongdouble, 'Zg'),
31
+ ]
32
+ scalars_only, codes_only = zip(*scalars_and_codes)
33
+
34
+
35
+ class TestScalarPEP3118:
36
+
37
+ @pytest.mark.parametrize('scalar', scalars_only, ids=codes_only)
38
+ def test_scalar_match_array(self, scalar):
39
+ x = scalar()
40
+ a = np.array([], dtype=np.dtype(scalar))
41
+ mv_x = memoryview(x)
42
+ mv_a = memoryview(a)
43
+ assert_equal(mv_x.format, mv_a.format)
44
+
45
+ @pytest.mark.parametrize('scalar', scalars_only, ids=codes_only)
46
+ def test_scalar_dim(self, scalar):
47
+ x = scalar()
48
+ mv_x = memoryview(x)
49
+ assert_equal(mv_x.itemsize, np.dtype(scalar).itemsize)
50
+ assert_equal(mv_x.ndim, 0)
51
+ assert_equal(mv_x.shape, ())
52
+ assert_equal(mv_x.strides, ())
53
+ assert_equal(mv_x.suboffsets, ())
54
+
55
+ @pytest.mark.parametrize('scalar, code', scalars_and_codes, ids=codes_only)
56
+ def test_scalar_code_and_properties(self, scalar, code):
57
+ x = scalar()
58
+ expected = dict(strides=(), itemsize=x.dtype.itemsize, ndim=0,
59
+ shape=(), format=code, readonly=True)
60
+
61
+ mv_x = memoryview(x)
62
+ assert self._as_dict(mv_x) == expected
63
+
64
+ @pytest.mark.parametrize('scalar', scalars_only, ids=codes_only)
65
+ def test_scalar_buffers_readonly(self, scalar):
66
+ x = scalar()
67
+ with pytest.raises(BufferError, match="scalar buffer is readonly"):
68
+ get_buffer_info(x, ["WRITABLE"])
69
+
70
+ def test_void_scalar_structured_data(self):
71
+ dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
72
+ x = np.array(('ndarray_scalar', (1.2, 3.0)), dtype=dt)[()]
73
+ assert_(isinstance(x, np.void))
74
+ mv_x = memoryview(x)
75
+ expected_size = 16 * np.dtype((np.str_, 1)).itemsize
76
+ expected_size += 2 * np.dtype(np.float64).itemsize
77
+ assert_equal(mv_x.itemsize, expected_size)
78
+ assert_equal(mv_x.ndim, 0)
79
+ assert_equal(mv_x.shape, ())
80
+ assert_equal(mv_x.strides, ())
81
+ assert_equal(mv_x.suboffsets, ())
82
+
83
+ # check scalar format string against ndarray format string
84
+ a = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
85
+ assert_(isinstance(a, np.ndarray))
86
+ mv_a = memoryview(a)
87
+ assert_equal(mv_x.itemsize, mv_a.itemsize)
88
+ assert_equal(mv_x.format, mv_a.format)
89
+
90
+ # Check that we do not allow writeable buffer export (technically
91
+ # we could allow it sometimes here...)
92
+ with pytest.raises(BufferError, match="scalar buffer is readonly"):
93
+ get_buffer_info(x, ["WRITABLE"])
94
+
95
+ def _as_dict(self, m):
96
+ return dict(strides=m.strides, shape=m.shape, itemsize=m.itemsize,
97
+ ndim=m.ndim, format=m.format, readonly=m.readonly)
98
+
99
+ def test_datetime_memoryview(self):
100
+ # gh-11656
101
+ # Values verified with v1.13.3, shape is not () as in test_scalar_dim
102
+
103
+ dt1 = np.datetime64('2016-01-01')
104
+ dt2 = np.datetime64('2017-01-01')
105
+ expected = dict(strides=(1,), itemsize=1, ndim=1, shape=(8,),
106
+ format='B', readonly=True)
107
+ v = memoryview(dt1)
108
+ assert self._as_dict(v) == expected
109
+
110
+ v = memoryview(dt2 - dt1)
111
+ assert self._as_dict(v) == expected
112
+
113
+ dt = np.dtype([('a', 'uint16'), ('b', 'M8[s]')])
114
+ a = np.empty(1, dt)
115
+ # Fails to create a PEP 3118 valid buffer
116
+ assert_raises((ValueError, BufferError), memoryview, a[0])
117
+
118
+ # Check that we do not allow writeable buffer export
119
+ with pytest.raises(BufferError, match="scalar buffer is readonly"):
120
+ get_buffer_info(dt1, ["WRITABLE"])
121
+
122
+ @pytest.mark.parametrize('s', [
123
+ pytest.param("\x32\x32", id="ascii"),
124
+ pytest.param("\uFE0F\uFE0F", id="basic multilingual"),
125
+ pytest.param("\U0001f4bb\U0001f4bb", id="non-BMP"),
126
+ ])
127
+ def test_str_ucs4(self, s):
128
+ s = np.str_(s) # only our subclass implements the buffer protocol
129
+
130
+ # all the same, characters always encode as ucs4
131
+ expected = dict(strides=(), itemsize=8, ndim=0, shape=(), format='2w',
132
+ readonly=True)
133
+
134
+ v = memoryview(s)
135
+ assert self._as_dict(v) == expected
136
+
137
+ # integers of the paltform-appropriate endianness
138
+ code_points = np.frombuffer(v, dtype='i4')
139
+
140
+ assert_equal(code_points, [ord(c) for c in s])
141
+
142
+ # Check that we do not allow writeable buffer export
143
+ with pytest.raises(BufferError, match="scalar buffer is readonly"):
144
+ get_buffer_info(s, ["WRITABLE"])
145
+
146
+ def test_user_scalar_fails_buffer(self):
147
+ r = rational(1)
148
+ with assert_raises(TypeError):
149
+ memoryview(r)
150
+
151
+ # Check that we do not allow writeable buffer export
152
+ with pytest.raises(BufferError, match="scalar buffer is readonly"):
153
+ get_buffer_info(r, ["WRITABLE"])
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_scalarinherit.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test printing of scalar types.
2
+
3
+ """
4
+ import pytest
5
+
6
+ import numpy as np
7
+ from numpy.testing import assert_, assert_raises
8
+
9
+
10
+ class A:
11
+ pass
12
+ class B(A, np.float64):
13
+ pass
14
+
15
+ class C(B):
16
+ pass
17
+ class D(C, B):
18
+ pass
19
+
20
+ class B0(np.float64, A):
21
+ pass
22
+ class C0(B0):
23
+ pass
24
+
25
+ class HasNew:
26
+ def __new__(cls, *args, **kwargs):
27
+ return cls, args, kwargs
28
+
29
+ class B1(np.float64, HasNew):
30
+ pass
31
+
32
+
33
+ class TestInherit:
34
+ def test_init(self):
35
+ x = B(1.0)
36
+ assert_(str(x) == '1.0')
37
+ y = C(2.0)
38
+ assert_(str(y) == '2.0')
39
+ z = D(3.0)
40
+ assert_(str(z) == '3.0')
41
+
42
+ def test_init2(self):
43
+ x = B0(1.0)
44
+ assert_(str(x) == '1.0')
45
+ y = C0(2.0)
46
+ assert_(str(y) == '2.0')
47
+
48
+ def test_gh_15395(self):
49
+ # HasNew is the second base, so `np.float64` should have priority
50
+ x = B1(1.0)
51
+ assert_(str(x) == '1.0')
52
+
53
+ # previously caused RecursionError!?
54
+ with pytest.raises(TypeError):
55
+ B1(1.0, 2.0)
56
+
57
+
58
+ class TestCharacter:
59
+ def test_char_radd(self):
60
+ # GH issue 9620, reached gentype_add and raise TypeError
61
+ np_s = np.bytes_('abc')
62
+ np_u = np.str_('abc')
63
+ s = b'def'
64
+ u = 'def'
65
+ assert_(np_s.__radd__(np_s) is NotImplemented)
66
+ assert_(np_s.__radd__(np_u) is NotImplemented)
67
+ assert_(np_s.__radd__(s) is NotImplemented)
68
+ assert_(np_s.__radd__(u) is NotImplemented)
69
+ assert_(np_u.__radd__(np_s) is NotImplemented)
70
+ assert_(np_u.__radd__(np_u) is NotImplemented)
71
+ assert_(np_u.__radd__(s) is NotImplemented)
72
+ assert_(np_u.__radd__(u) is NotImplemented)
73
+ assert_(s + np_s == b'defabc')
74
+ assert_(u + np_u == 'defabc')
75
+
76
+ class MyStr(str, np.generic):
77
+ # would segfault
78
+ pass
79
+
80
+ with assert_raises(TypeError):
81
+ # Previously worked, but gave completely wrong result
82
+ ret = s + MyStr('abc')
83
+
84
+ class MyBytes(bytes, np.generic):
85
+ # would segfault
86
+ pass
87
+
88
+ ret = s + MyBytes(b'abc')
89
+ assert(type(ret) is type(s))
90
+ assert ret == b"defabc"
91
+
92
+ def test_char_repeat(self):
93
+ np_s = np.bytes_('abc')
94
+ np_u = np.str_('abc')
95
+ res_s = b'abc' * 5
96
+ res_u = 'abc' * 5
97
+ assert_(np_s * 5 == res_s)
98
+ assert_(np_u * 5 == res_u)
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_strings.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import operator
4
+ import numpy as np
5
+
6
+ from numpy.testing import assert_array_equal
7
+
8
+
9
+ COMPARISONS = [
10
+ (operator.eq, np.equal, "=="),
11
+ (operator.ne, np.not_equal, "!="),
12
+ (operator.lt, np.less, "<"),
13
+ (operator.le, np.less_equal, "<="),
14
+ (operator.gt, np.greater, ">"),
15
+ (operator.ge, np.greater_equal, ">="),
16
+ ]
17
+
18
+
19
+ @pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
20
+ def test_mixed_string_comparison_ufuncs_fail(op, ufunc, sym):
21
+ arr_string = np.array(["a", "b"], dtype="S")
22
+ arr_unicode = np.array(["a", "c"], dtype="U")
23
+
24
+ with pytest.raises(TypeError, match="did not contain a loop"):
25
+ ufunc(arr_string, arr_unicode)
26
+
27
+ with pytest.raises(TypeError, match="did not contain a loop"):
28
+ ufunc(arr_unicode, arr_string)
29
+
30
+ @pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
31
+ def test_mixed_string_comparisons_ufuncs_with_cast(op, ufunc, sym):
32
+ arr_string = np.array(["a", "b"], dtype="S")
33
+ arr_unicode = np.array(["a", "c"], dtype="U")
34
+
35
+ # While there is no loop, manual casting is acceptable:
36
+ res1 = ufunc(arr_string, arr_unicode, signature="UU->?", casting="unsafe")
37
+ res2 = ufunc(arr_string, arr_unicode, signature="SS->?", casting="unsafe")
38
+
39
+ expected = op(arr_string.astype('U'), arr_unicode)
40
+ assert_array_equal(res1, expected)
41
+ assert_array_equal(res2, expected)
42
+
43
+
44
+ @pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
45
+ @pytest.mark.parametrize("dtypes", [
46
+ ("S2", "S2"), ("S2", "S10"),
47
+ ("<U1", "<U1"), ("<U1", ">U1"), (">U1", ">U1"),
48
+ ("<U1", "<U10"), ("<U1", ">U10")])
49
+ @pytest.mark.parametrize("aligned", [True, False])
50
+ def test_string_comparisons(op, ufunc, sym, dtypes, aligned):
51
+ # ensure native byte-order for the first view to stay within unicode range
52
+ native_dt = np.dtype(dtypes[0]).newbyteorder("=")
53
+ arr = np.arange(2**15).view(native_dt).astype(dtypes[0])
54
+ if not aligned:
55
+ # Make `arr` unaligned:
56
+ new = np.zeros(arr.nbytes + 1, dtype=np.uint8)[1:].view(dtypes[0])
57
+ new[...] = arr
58
+ arr = new
59
+
60
+ arr2 = arr.astype(dtypes[1], copy=True)
61
+ np.random.shuffle(arr2)
62
+ arr[0] = arr2[0] # make sure one matches
63
+
64
+ expected = [op(d1, d2) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
65
+ assert_array_equal(op(arr, arr2), expected)
66
+ assert_array_equal(ufunc(arr, arr2), expected)
67
+ assert_array_equal(np.compare_chararrays(arr, arr2, sym, False), expected)
68
+
69
+ expected = [op(d2, d1) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
70
+ assert_array_equal(op(arr2, arr), expected)
71
+ assert_array_equal(ufunc(arr2, arr), expected)
72
+ assert_array_equal(np.compare_chararrays(arr2, arr, sym, False), expected)
73
+
74
+
75
+ @pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS)
76
+ @pytest.mark.parametrize("dtypes", [
77
+ ("S2", "S2"), ("S2", "S10"), ("<U1", "<U1"), ("<U1", ">U10")])
78
+ def test_string_comparisons_empty(op, ufunc, sym, dtypes):
79
+ arr = np.empty((1, 0, 1, 5), dtype=dtypes[0])
80
+ arr2 = np.empty((100, 1, 0, 1), dtype=dtypes[1])
81
+
82
+ expected = np.empty(np.broadcast_shapes(arr.shape, arr2.shape), dtype=bool)
83
+ assert_array_equal(op(arr, arr2), expected)
84
+ assert_array_equal(ufunc(arr, arr2), expected)
85
+ assert_array_equal(np.compare_chararrays(arr, arr2, sym, False), expected)
86
+
87
+
88
+ @pytest.mark.parametrize("str_dt", ["S", "U"])
89
+ @pytest.mark.parametrize("float_dt", np.typecodes["AllFloat"])
90
+ def test_float_to_string_cast(str_dt, float_dt):
91
+ float_dt = np.dtype(float_dt)
92
+ fi = np.finfo(float_dt)
93
+ arr = np.array([np.nan, np.inf, -np.inf, fi.max, fi.min], dtype=float_dt)
94
+ expected = ["nan", "inf", "-inf", repr(fi.max), repr(fi.min)]
95
+ if float_dt.kind == 'c':
96
+ expected = [f"({r}+0j)" for r in expected]
97
+
98
+ res = arr.astype(str_dt)
99
+ assert_array_equal(res, np.array(expected, dtype=str_dt))
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_umath.py ADDED
The diff for this file is too large to render. See raw diff
 
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/numpy/core/tests/test_umath_accuracy.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+ from os import path
4
+ import sys
5
+ import pytest
6
+ from ctypes import c_longlong, c_double, c_float, c_int, cast, pointer, POINTER
7
+ from numpy.testing import assert_array_max_ulp
8
+ from numpy.testing._private.utils import _glibc_older_than
9
+ from numpy.core._multiarray_umath import __cpu_features__
10
+
11
+ UNARY_UFUNCS = [obj for obj in np.core.umath.__dict__.values() if
12
+ isinstance(obj, np.ufunc)]
13
+ UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types]
14
+ UNARY_OBJECT_UFUNCS.remove(getattr(np, 'invert'))
15
+
16
+ IS_AVX = __cpu_features__.get('AVX512F', False) or \
17
+ (__cpu_features__.get('FMA3', False) and __cpu_features__.get('AVX2', False))
18
+ # only run on linux with AVX, also avoid old glibc (numpy/numpy#20448).
19
+ runtest = (sys.platform.startswith('linux')
20
+ and IS_AVX and not _glibc_older_than("2.17"))
21
+ platform_skip = pytest.mark.skipif(not runtest,
22
+ reason="avoid testing inconsistent platform "
23
+ "library implementations")
24
+
25
+ # convert string to hex function taken from:
26
+ # https://stackoverflow.com/questions/1592158/convert-hex-to-float #
27
+ def convert(s, datatype="np.float32"):
28
+ i = int(s, 16) # convert from hex to a Python int
29
+ if (datatype == "np.float64"):
30
+ cp = pointer(c_longlong(i)) # make this into a c long long integer
31
+ fp = cast(cp, POINTER(c_double)) # cast the int pointer to a double pointer
32
+ else:
33
+ cp = pointer(c_int(i)) # make this into a c integer
34
+ fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer
35
+
36
+ return fp.contents.value # dereference the pointer, get the float
37
+
38
+ str_to_float = np.vectorize(convert)
39
+
40
+ class TestAccuracy:
41
+ @platform_skip
42
+ def test_validate_transcendentals(self):
43
+ with np.errstate(all='ignore'):
44
+ data_dir = path.join(path.dirname(__file__), 'data')
45
+ files = os.listdir(data_dir)
46
+ files = list(filter(lambda f: f.endswith('.csv'), files))
47
+ for filename in files:
48
+ filepath = path.join(data_dir, filename)
49
+ with open(filepath) as fid:
50
+ file_without_comments = (r for r in fid if not r[0] in ('$', '#'))
51
+ data = np.genfromtxt(file_without_comments,
52
+ dtype=('|S39','|S39','|S39',int),
53
+ names=('type','input','output','ulperr'),
54
+ delimiter=',',
55
+ skip_header=1)
56
+ npname = path.splitext(filename)[0].split('-')[3]
57
+ npfunc = getattr(np, npname)
58
+ for datatype in np.unique(data['type']):
59
+ data_subset = data[data['type'] == datatype]
60
+ inval = np.array(str_to_float(data_subset['input'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
61
+ outval = np.array(str_to_float(data_subset['output'].astype(str), data_subset['type'].astype(str)), dtype=eval(datatype))
62
+ perm = np.random.permutation(len(inval))
63
+ inval = inval[perm]
64
+ outval = outval[perm]
65
+ maxulperr = data_subset['ulperr'].max()
66
+ assert_array_max_ulp(npfunc(inval), outval, maxulperr)
67
+
68
+ @pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS)
69
+ def test_validate_fp16_transcendentals(self, ufunc):
70
+ with np.errstate(all='ignore'):
71
+ arr = np.arange(65536, dtype=np.int16)
72
+ datafp16 = np.frombuffer(arr.tobytes(), dtype=np.float16)
73
+ datafp32 = datafp16.astype(np.float32)
74
+ assert_array_max_ulp(ufunc(datafp16), ufunc(datafp32),
75
+ maxulp=1, dtype=np.float16)
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_lm1b_lr3e3_nobottleneck_step97k_decode1024_ema_selfcond_20260613_223847.log ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [start] 2026-06-13T22:38:47+00:00
2
+ checkpoint=runs/lm1b_t5_pack_len128_C1_to_1024_pow1_d768_l12_h12_gbs512_4gpu_50ep_lr3e3_ema0p9999_elfopt_not5_nobottleneck_unfixed_norm_stateprobadd_selfcond_ce_fast_20260611_232614/step_097000.pt
3
+ use_ema=1
4
+ step=097000
5
+ decode_steps=1024
6
+ n=64 chunk_n=8 gpu=0
7
+ out_base=/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614
8
+ [2026-06-13T22:38:47+00:00] infer step=097000 decode=1024 -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_selfcond_step097000_ema_sc1p0_decode1024_n64
9
+ [2026-06-13T22:38:47+00:00] run decode=1024 chunk=0 n=8 seed=123
10
+ [2026-06-13T22:39:03+00:00] done decode=1024 chunk=0
11
+ [2026-06-13T22:39:03+00:00] run decode=1024 chunk=1 n=8 seed=124
12
+ [2026-06-13T22:39:19+00:00] done decode=1024 chunk=1
13
+ [2026-06-13T22:39:19+00:00] run decode=1024 chunk=2 n=8 seed=125
14
+ [2026-06-13T22:39:34+00:00] done decode=1024 chunk=2
15
+ [2026-06-13T22:39:34+00:00] run decode=1024 chunk=3 n=8 seed=126
16
+ [2026-06-13T22:39:50+00:00] done decode=1024 chunk=3
17
+ [2026-06-13T22:39:50+00:00] run decode=1024 chunk=4 n=8 seed=127
18
+ [2026-06-13T22:40:06+00:00] done decode=1024 chunk=4
19
+ [2026-06-13T22:40:06+00:00] run decode=1024 chunk=5 n=8 seed=128
20
+ [2026-06-13T22:40:21+00:00] done decode=1024 chunk=5
21
+ [2026-06-13T22:40:21+00:00] run decode=1024 chunk=6 n=8 seed=129
22
+ [2026-06-13T22:40:37+00:00] done decode=1024 chunk=6
23
+ [2026-06-13T22:40:37+00:00] run decode=1024 chunk=7 n=8 seed=130
24
+ [2026-06-13T22:40:53+00:00] done decode=1024 chunk=7
25
+ merged 64 samples -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_selfcond_step097000_ema_sc1p0_decode1024_n64/sc1p0/samples64.txt
26
+ loading scorer /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard dtype=fp32 device=cuda
27
+ run kind ppl mean_entropy distinct_1 distinct_2 top_token_mass eos_rows eos_total ppl_tokens t5_tokens path
28
+ sc1p0 raw_full 46.28551224661415 4.071705804822175 0.17464549751545266 0.5646060606060606 0.10374500060598715 64 128 6991 8251 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_selfcond_step097000_ema_sc1p0_decode1024_n64/sc1p0
29
+ sc1p0 pre_eos nan 0.0 0.015625 0.015873015873015872 1.0 0 0 0 64 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/lm1b_len128_lr3e3_not5_nobottleneck_step97k_selfcond_step097000_ema_sc1p0_decode1024_n64/sc1p0
30
+ [2026-06-13T22:41:01+00:00] done
31
+ [exit] 2026-06-13T22:41:01+00:00 rc=0
LTA_openwebtext_dualt/mini_owt_logdirichlet/logs/infer_owt_lr3e3_not5_nobottleneck_250k_decode64_ema_20260613_225804.log ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [start] 2026-06-13T22:58:04+00:00 tag=nobottleneck gpu=3
2
+ checkpoint=runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr3e3_ema0p9999_elfopt_not5_nobottleneck_unfixed_norm_stateprobadd_selfcond_ce_fast_20260611_220316/step_250000.pt
3
+ use_ema=1
4
+ step=250000
5
+ decode_steps=64
6
+ n=64 chunk_n=8 gpu=3
7
+ out_base=/e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614
8
+ [2026-06-13T22:58:04+00:00] infer step=250000 decode=64 -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/owt_lr3e3_not5_nobottleneck_step250000_ema_sc1p0_decode64_n64
9
+ [2026-06-13T22:58:04+00:00] run decode=64 chunk=0 n=8 seed=123
10
+ [2026-06-13T22:58:15+00:00] done decode=64 chunk=0
11
+ [2026-06-13T22:58:15+00:00] run decode=64 chunk=1 n=8 seed=124
12
+ [2026-06-13T22:58:25+00:00] done decode=64 chunk=1
13
+ [2026-06-13T22:58:25+00:00] run decode=64 chunk=2 n=8 seed=125
14
+ [2026-06-13T22:58:36+00:00] done decode=64 chunk=2
15
+ [2026-06-13T22:58:36+00:00] run decode=64 chunk=3 n=8 seed=126
16
+ [2026-06-13T22:58:46+00:00] done decode=64 chunk=3
17
+ [2026-06-13T22:58:46+00:00] run decode=64 chunk=4 n=8 seed=127
18
+ [2026-06-13T22:58:56+00:00] done decode=64 chunk=4
19
+ [2026-06-13T22:58:56+00:00] run decode=64 chunk=5 n=8 seed=128
20
+ [2026-06-13T22:59:06+00:00] done decode=64 chunk=5
21
+ [2026-06-13T22:59:06+00:00] run decode=64 chunk=6 n=8 seed=129
22
+ [2026-06-13T22:59:16+00:00] done decode=64 chunk=6
23
+ [2026-06-13T22:59:16+00:00] run decode=64 chunk=7 n=8 seed=130
24
+ [2026-06-13T22:59:26+00:00] done decode=64 chunk=7
25
+ merged 64 samples -> /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/owt_lr3e3_not5_nobottleneck_step250000_ema_sc1p0_decode64_n64/sc1p0/samples64.txt
26
+ loading scorer /e2e-data/evad-tech-vla/wanghan58/models/flowtext_scorers/gpt2-large-standard dtype=fp32 device=cuda
27
+ run kind ppl mean_entropy distinct_1 distinct_2 top_token_mass eos_rows eos_total ppl_tokens t5_tokens path
28
+ sc1p0 raw_full 14.022381162335854 4.914212015412217 0.049311139252094044 0.3446339751609655 0.03200952046747937 64 64 64840 65543 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/owt_lr3e3_not5_nobottleneck_step250000_ema_sc1p0_decode64_n64/sc1p0
29
+ sc1p0 pre_eos 15.70514521711768 4.941422532573047 0.05089792060491494 0.35577119992438444 0.03304977945809704 0 0 60677 63480 /e2e-data/evad-tech-vla/wanghan58/workspace/LTA_openwebtext_dualt/docs/lta_samples/metrics_20260614/owt_lr3e3_not5_nobottleneck_step250000_ema_sc1p0_decode64_n64/sc1p0
30
+ [2026-06-13T22:59:40+00:00] done
31
+ [exit] 2026-06-13T22:59:40+00:00 tag=nobottleneck rc=0