JayKimDevolved
commited on
JayKimDevolved/deepseek
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- README.md +58 -0
- adapter_config.json +35 -0
- adapter_model.safetensors +3 -0
- data-gym-cache/6c7ea1a7e38e3a7f062df639a5b80947f075ffe6 +0 -0
- data-gym-cache/6d1cbeee0f20b3d9449abfede4726ed8212e3aee +0 -0
- data-gym-cache/9b5ad71b2ce5302211f9c61530b329a4922fc6a4 +0 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/BENTO_BUILD.txt +22 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/COMPATIBILITY +59 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/DEV_README.txt +18 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/INSTALL.txt +138 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/LICENSE.txt +30 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/MANIFEST.in +26 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/PKG-INFO +39 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/README.txt +22 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/THANKS.txt +64 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/__config__.py +36 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/__init__.py +216 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/_import_tools.py +348 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/add_newdocs.py +0 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/__init__.py +20 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/_inspect.py +221 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/py3k.py +89 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/setup.py +12 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/__init__.py +78 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/_dummy.cpython-310-x86_64-linux-gnu.so +0 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/_internal.py +570 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/_methods.py +134 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/arrayprint.py +752 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/cversions.py +15 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/defchararray.py +2687 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/fromnumeric.py +2930 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/function_base.py +188 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/generate_numpy_api.py +259 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/getlimits.py +306 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/info.py +87 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/machar.py +338 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/memmap.py +308 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/numeric.py +2842 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/numerictypes.py +1042 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/records.py +808 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/setup.py +1013 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/setup_common.py +321 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/shape_base.py +277 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/ctypeslib.py +426 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__config__.py +36 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__init__.py +39 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__version__.py +6 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/ccompiler.py +656 -0
- pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/command/__init__.py +43 -0
.gitattributes
CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/temp.linux-x86_64-cpython-310/build/src.linux-x86_64-3.1/numpy/core/src/multiarray/arraytypes.o filter=lfs diff=lfs merge=lfs -text
|
37 |
+
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/temp.linux-x86_64-cpython-310/libnpysort.a filter=lfs diff=lfs merge=lfs -text
|
38 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
base_model: deepseek-ai/DeepSeek-R1-Distill-Llama-8B
|
3 |
+
library_name: transformers
|
4 |
+
model_name: tmp
|
5 |
+
tags:
|
6 |
+
- generated_from_trainer
|
7 |
+
- trl
|
8 |
+
- sft
|
9 |
+
licence: license
|
10 |
+
---
|
11 |
+
|
12 |
+
# Model Card for tmp
|
13 |
+
|
14 |
+
This model is a fine-tuned version of [deepseek-ai/DeepSeek-R1-Distill-Llama-8B](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B).
|
15 |
+
It has been trained using [TRL](https://github.com/huggingface/trl).
|
16 |
+
|
17 |
+
## Quick start
|
18 |
+
|
19 |
+
```python
|
20 |
+
from transformers import pipeline
|
21 |
+
|
22 |
+
question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?"
|
23 |
+
generator = pipeline("text-generation", model="JayKimDevolved/tmp", device="cuda")
|
24 |
+
output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0]
|
25 |
+
print(output["generated_text"])
|
26 |
+
```
|
27 |
+
|
28 |
+
## Training procedure
|
29 |
+
|
30 |
+
|
31 |
+
|
32 |
+
|
33 |
+
This model was trained with SFT.
|
34 |
+
|
35 |
+
### Framework versions
|
36 |
+
|
37 |
+
- TRL: 0.13.0
|
38 |
+
- Transformers: 4.47.1
|
39 |
+
- Pytorch: 2.1.0+cu118
|
40 |
+
- Datasets: 3.2.0
|
41 |
+
- Tokenizers: 0.21.0
|
42 |
+
|
43 |
+
## Citations
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
Cite TRL as:
|
48 |
+
|
49 |
+
```bibtex
|
50 |
+
@misc{vonwerra2022trl,
|
51 |
+
title = {{TRL: Transformer Reinforcement Learning}},
|
52 |
+
author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallouédec},
|
53 |
+
year = 2020,
|
54 |
+
journal = {GitHub repository},
|
55 |
+
publisher = {GitHub},
|
56 |
+
howpublished = {\url{https://github.com/huggingface/trl}}
|
57 |
+
}
|
58 |
+
```
|
adapter_config.json
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"alpha_pattern": {},
|
3 |
+
"auto_mapping": null,
|
4 |
+
"base_model_name_or_path": "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
|
5 |
+
"bias": "none",
|
6 |
+
"eva_config": null,
|
7 |
+
"exclude_modules": null,
|
8 |
+
"fan_in_fan_out": false,
|
9 |
+
"inference_mode": true,
|
10 |
+
"init_lora_weights": true,
|
11 |
+
"layer_replication": null,
|
12 |
+
"layers_pattern": null,
|
13 |
+
"layers_to_transform": null,
|
14 |
+
"loftq_config": {},
|
15 |
+
"lora_alpha": 16,
|
16 |
+
"lora_bias": false,
|
17 |
+
"lora_dropout": 0.1,
|
18 |
+
"megatron_config": null,
|
19 |
+
"megatron_core": "megatron.core",
|
20 |
+
"modules_to_save": null,
|
21 |
+
"peft_type": "LORA",
|
22 |
+
"r": 64,
|
23 |
+
"rank_pattern": {},
|
24 |
+
"revision": null,
|
25 |
+
"target_modules": [
|
26 |
+
"v_proj",
|
27 |
+
"q_proj",
|
28 |
+
"k_proj",
|
29 |
+
"gate_proj",
|
30 |
+
"o_proj"
|
31 |
+
],
|
32 |
+
"task_type": "CAUSAL_LM",
|
33 |
+
"use_dora": false,
|
34 |
+
"use_rslora": false
|
35 |
+
}
|
adapter_model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f97148c039e09f4ff984bdcfd6d0e5826e975028772c12694ac52a2b3c3360d3
|
3 |
+
size 369142184
|
data-gym-cache/6c7ea1a7e38e3a7f062df639a5b80947f075ffe6
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data-gym-cache/6d1cbeee0f20b3d9449abfede4726ed8212e3aee
ADDED
The diff for this file is too large to render.
See raw diff
|
|
data-gym-cache/9b5ad71b2ce5302211f9c61530b329a4922fc6a4
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/BENTO_BUILD.txt
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
No-frill version:
|
2 |
+
|
3 |
+
* Clone bento::
|
4 |
+
|
5 |
+
git clone git://github.com/cournape/Bento.git bento-git
|
6 |
+
|
7 |
+
* Bootstrap bento::
|
8 |
+
|
9 |
+
cd bento-git && python bootstrap.py
|
10 |
+
|
11 |
+
* Download waf >= 1.6.5 from a release (or from git)::
|
12 |
+
|
13 |
+
git clone https://code.google.com/p/waf/
|
14 |
+
|
15 |
+
* Build numpy with bento:
|
16 |
+
|
17 |
+
export WAFDIR=ROOT_OF_WAF_CHECKOUT # WAFDIR should be such as $WAFDIR/waflib exists
|
18 |
+
$BENTO_ROOT/bentomaker build -j 4 # 4 threads in parallel
|
19 |
+
# or with progress bar
|
20 |
+
$BENTO_ROOT/bentomaker build -p
|
21 |
+
# or with verbose output
|
22 |
+
$BENTO_ROOT/bentomaker build -v
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/COMPATIBILITY
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
X.flat returns an indexable 1-D iterator (mostly similar to an array
|
4 |
+
but always 1-d) --- only has .copy and .__array__ attributes of an array!!!
|
5 |
+
|
6 |
+
.typecode() --> .dtype.char
|
7 |
+
|
8 |
+
.iscontiguous() --> .flags['CONTIGUOUS'] or .flags.contiguous
|
9 |
+
|
10 |
+
.byteswapped() -> .byteswap()
|
11 |
+
|
12 |
+
.itemsize() -> .itemsize
|
13 |
+
|
14 |
+
.toscalar() -> .item()
|
15 |
+
|
16 |
+
If you used typecode characters:
|
17 |
+
|
18 |
+
'c' -> 'S1' or 'c'
|
19 |
+
'b' -> 'B'
|
20 |
+
'1' -> 'b'
|
21 |
+
's' -> 'h'
|
22 |
+
'w' -> 'H'
|
23 |
+
'u' -> 'I'
|
24 |
+
|
25 |
+
|
26 |
+
C -level
|
27 |
+
|
28 |
+
some API calls that used to take PyObject * now take PyArrayObject *
|
29 |
+
(this should only cause warnings during compile and not actual problems).
|
30 |
+
PyArray_Take
|
31 |
+
|
32 |
+
These commands now return a buffer that must be freed once it is used
|
33 |
+
using PyMemData_FREE(ptr);
|
34 |
+
|
35 |
+
a->descr->zero --> PyArray_Zero(a)
|
36 |
+
a->descr->one --> PyArray_One(a)
|
37 |
+
|
38 |
+
Numeric/arrayobject.h --> numpy/oldnumeric.h
|
39 |
+
|
40 |
+
|
41 |
+
# These will actually work and are defines for PyArray_BYTE,
|
42 |
+
# but you really should change it in your code
|
43 |
+
PyArray_CHAR --> PyArray_CHAR
|
44 |
+
(or PyArray_STRING which is more flexible)
|
45 |
+
PyArray_SBYTE --> PyArray_BYTE
|
46 |
+
|
47 |
+
Any uses of character codes will need adjusting....
|
48 |
+
use PyArray_XXXLTR where XXX is the name of the type.
|
49 |
+
|
50 |
+
|
51 |
+
If you used function pointers directly (why did you do that?),
|
52 |
+
the arguments have changed. Everything that was an int is now an intp.
|
53 |
+
Also, arrayobjects should be passed in at the end.
|
54 |
+
|
55 |
+
a->descr->cast[i](fromdata, fromstep, todata, tostep, n)
|
56 |
+
a->descr->cast[i](fromdata, todata, n, PyArrayObject *in, PyArrayObject *out)
|
57 |
+
anything but single-stepping is not supported by this function
|
58 |
+
use the PyArray_CastXXXX functions.
|
59 |
+
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/DEV_README.txt
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Thank you for your willingness to help make NumPy the best array system
|
2 |
+
available.
|
3 |
+
|
4 |
+
We have a few simple rules:
|
5 |
+
|
6 |
+
* try hard to keep the Git repository in a buildable state and to not
|
7 |
+
indiscriminately muck with what others have contributed.
|
8 |
+
|
9 |
+
* Simple changes (including bug fixes) and obvious improvements are
|
10 |
+
always welcome. Changes that fundamentally change behavior need
|
11 |
+
discussion on numpy-discussions@scipy.org before anything is
|
12 |
+
done.
|
13 |
+
|
14 |
+
* Please add meaningful comments when you check changes in. These
|
15 |
+
comments form the basis of the change-log.
|
16 |
+
|
17 |
+
* Add unit tests to exercise new code, and regression tests
|
18 |
+
whenever you fix a bug.
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/INSTALL.txt
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.. -*- rest -*-
|
2 |
+
.. vim:syntax=rest
|
3 |
+
.. NB! Keep this document a valid restructured document.
|
4 |
+
|
5 |
+
Building and installing NumPy
|
6 |
+
+++++++++++++++++++++++++++++
|
7 |
+
|
8 |
+
:Authors: Numpy Developers <numpy-discussion@scipy.org>
|
9 |
+
:Discussions to: numpy-discussion@scipy.org
|
10 |
+
|
11 |
+
.. Contents::
|
12 |
+
|
13 |
+
PREREQUISITES
|
14 |
+
=============
|
15 |
+
|
16 |
+
Building NumPy requires the following software installed:
|
17 |
+
|
18 |
+
1) For Python 2, Python__ 2.6.x or newer.
|
19 |
+
For Python 3, Python__ 3.2.x or newer.
|
20 |
+
|
21 |
+
On Debian and derivative (Ubuntu): python python-dev
|
22 |
+
|
23 |
+
On Windows: the official python installer on Python__ is enough
|
24 |
+
|
25 |
+
Make sure that the Python package distutils is installed before
|
26 |
+
continuing. For example, in Debian GNU/Linux, distutils is included
|
27 |
+
in the python-dev package.
|
28 |
+
|
29 |
+
Python must also be compiled with the zlib module enabled.
|
30 |
+
|
31 |
+
2) nose__ (optional) 0.10.3 or later
|
32 |
+
|
33 |
+
This is required for testing numpy, but not for using it.
|
34 |
+
|
35 |
+
Python__ http://www.python.org
|
36 |
+
nose__ http://somethingaboutorange.com/mrl/projects/nose/
|
37 |
+
|
38 |
+
Fortran ABI mismatch
|
39 |
+
====================
|
40 |
+
|
41 |
+
The two most popular open source fortran compilers are g77 and gfortran.
|
42 |
+
Unfortunately, they are not ABI compatible, which means that concretely you
|
43 |
+
should avoid mixing libraries built with one with another. In particular,
|
44 |
+
if your blas/lapack/atlas is built with g77, you *must* use g77 when
|
45 |
+
building numpy and scipy; on the contrary, if your atlas is built with
|
46 |
+
gfortran, you *must* build numpy/scipy with gfortran.
|
47 |
+
|
48 |
+
Choosing the fortran compiler
|
49 |
+
-----------------------------
|
50 |
+
|
51 |
+
To build with g77:
|
52 |
+
|
53 |
+
python setup.py build --fcompiler=gnu
|
54 |
+
|
55 |
+
To build with gfortran:
|
56 |
+
|
57 |
+
python setup.py build --fcompiler=gnu95
|
58 |
+
|
59 |
+
How to check the ABI of blas/lapack/atlas
|
60 |
+
-----------------------------------------
|
61 |
+
|
62 |
+
One relatively simple and reliable way to check for the compiler used to
|
63 |
+
build a library is to use ldd on the library. If libg2c.so is a dependency,
|
64 |
+
this means that g77 has been used. If libgfortran.so is a dependency,
|
65 |
+
gfortran has been used. If both are dependencies, this means both have been
|
66 |
+
used, which is almost always a very bad idea.
|
67 |
+
|
68 |
+
Building with ATLAS support
|
69 |
+
===========================
|
70 |
+
|
71 |
+
Ubuntu 8.10 (Intrepid)
|
72 |
+
----------------------
|
73 |
+
|
74 |
+
You can install the necessary packages for optimized ATLAS with this
|
75 |
+
command:
|
76 |
+
|
77 |
+
sudo apt-get install libatlas-base-dev
|
78 |
+
|
79 |
+
If you have a recent CPU with SIMD support (SSE, SSE2, etc...), you should
|
80 |
+
also install the corresponding package for optimal performance. For
|
81 |
+
example, for SSE2:
|
82 |
+
|
83 |
+
sudo apt-get install libatlas3gf-sse2
|
84 |
+
|
85 |
+
*NOTE*: if you build your own atlas, Intrepid changed its default fortran
|
86 |
+
compiler to gfortran. So you should rebuild everything from scratch,
|
87 |
+
including lapack, to use it on Intrepid.
|
88 |
+
|
89 |
+
Ubuntu 8.04 and lower
|
90 |
+
---------------------
|
91 |
+
|
92 |
+
You can install the necessary packages for optimized ATLAS with this
|
93 |
+
command:
|
94 |
+
|
95 |
+
sudo apt-get install atlas3-base-dev
|
96 |
+
|
97 |
+
If you have a recent CPU with SIMD support (SSE, SSE2, etc...), you should
|
98 |
+
also install the corresponding package for optimal performance. For
|
99 |
+
example, for SSE2:
|
100 |
+
|
101 |
+
sudo apt-get install atlas3-sse2
|
102 |
+
|
103 |
+
Windows 64 bits notes
|
104 |
+
=====================
|
105 |
+
|
106 |
+
Note: only AMD64 is supported (IA64 is not) - AMD64 is the version most
|
107 |
+
people want.
|
108 |
+
|
109 |
+
Free compilers (mingw-w64)
|
110 |
+
--------------------------
|
111 |
+
|
112 |
+
http://mingw-w64.sourceforge.net/
|
113 |
+
|
114 |
+
To use the free compilers (mingw-w64), you need to build your own
|
115 |
+
toolchain, as the mingw project only distribute cross-compilers
|
116 |
+
(cross-compilation is not supported by numpy). Since this toolchain is
|
117 |
+
still being worked on, serious compiler bugs can be expected. binutil 2.19
|
118 |
+
+ gcc 4.3.3 + mingw-w64 runtime gives you a working C compiler (but the C++
|
119 |
+
is broken). gcc 4.4 will hopefully be able to run natively.
|
120 |
+
|
121 |
+
This is the only tested way to get a numpy with a FULL blas/lapack (scipy
|
122 |
+
does not work because of C++).
|
123 |
+
|
124 |
+
MS compilers
|
125 |
+
------------
|
126 |
+
|
127 |
+
If you are familiar with MS tools, that's obviously the easiest path, and
|
128 |
+
the compilers are hopefully more mature (although in my experience, they
|
129 |
+
are quite fragile, and often segfault on invalid C code). The main drawback
|
130 |
+
is that no fortran compiler + MS compiler combination has been tested -
|
131 |
+
mingw-w64 gfortran + MS compiler does not work at all (it is unclear
|
132 |
+
whether it ever will).
|
133 |
+
|
134 |
+
For python 2.6, you need VS 2008. The freely available version does not
|
135 |
+
contains 64 bits compilers (you also need the PSDK, v6.1).
|
136 |
+
|
137 |
+
It is crucial to use the right MS compiler version. For python 2.6, you
|
138 |
+
must use version 15. You can check the compiler version with cl.exe /?.
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/LICENSE.txt
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2005-2011, NumPy Developers.
|
2 |
+
All rights reserved.
|
3 |
+
|
4 |
+
Redistribution and use in source and binary forms, with or without
|
5 |
+
modification, are permitted provided that the following conditions are
|
6 |
+
met:
|
7 |
+
|
8 |
+
* Redistributions of source code must retain the above copyright
|
9 |
+
notice, this list of conditions and the following disclaimer.
|
10 |
+
|
11 |
+
* Redistributions in binary form must reproduce the above
|
12 |
+
copyright notice, this list of conditions and the following
|
13 |
+
disclaimer in the documentation and/or other materials provided
|
14 |
+
with the distribution.
|
15 |
+
|
16 |
+
* Neither the name of the NumPy Developers nor the names of any
|
17 |
+
contributors may be used to endorse or promote products derived
|
18 |
+
from this software without specific prior written permission.
|
19 |
+
|
20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
21 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
22 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
23 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
24 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
25 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
26 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
27 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
28 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
29 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
30 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/MANIFEST.in
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Use .add_data_files and .add_data_dir methods in a appropriate
|
3 |
+
# setup.py files to include non-python files such as documentation,
|
4 |
+
# data, etc files to distribution. Avoid using MANIFEST.in for that.
|
5 |
+
#
|
6 |
+
include MANIFEST.in
|
7 |
+
include COMPATIBILITY
|
8 |
+
include *.txt
|
9 |
+
include setupegg.py
|
10 |
+
include site.cfg.example
|
11 |
+
include numpy/random/mtrand/generate_mtrand_c.py
|
12 |
+
recursive-include numpy/random/mtrand *.pyx *.pxd
|
13 |
+
# Adding scons build related files not found by distutils
|
14 |
+
recursive-include numpy/core/code_generators *.py *.txt
|
15 |
+
recursive-include numpy/core *.in *.h
|
16 |
+
# Add documentation: we don't use add_data_dir since we do not want to include
|
17 |
+
# this at installation, only for sdist-generated tarballs
|
18 |
+
include doc/Makefile doc/postprocess.py
|
19 |
+
recursive-include doc/release *
|
20 |
+
recursive-include doc/source *
|
21 |
+
recursive-include doc/sphinxext *
|
22 |
+
recursive-include tools/swig *
|
23 |
+
recursive-include doc/scipy-sphinx-theme *
|
24 |
+
recursive-include doc/f2py *
|
25 |
+
|
26 |
+
global-exclude *.pyc *.pyo *.pyd
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/PKG-INFO
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 1.1
|
2 |
+
Name: numpy
|
3 |
+
Version: 1.9.0
|
4 |
+
Summary: NumPy: array processing for numbers, strings, records, and objects.
|
5 |
+
Home-page: http://www.numpy.org
|
6 |
+
Author: NumPy Developers
|
7 |
+
Author-email: numpy-discussion@scipy.org
|
8 |
+
License: BSD
|
9 |
+
Download-URL: http://sourceforge.net/projects/numpy/files/NumPy/
|
10 |
+
Description: NumPy is a general-purpose array-processing package designed to
|
11 |
+
efficiently manipulate large multi-dimensional arrays of arbitrary
|
12 |
+
records without sacrificing too much speed for small multi-dimensional
|
13 |
+
arrays. NumPy is built on the Numeric code base and adds features
|
14 |
+
introduced by numarray as well as an extended C-API and the ability to
|
15 |
+
create arrays of arbitrary type which also makes NumPy suitable for
|
16 |
+
interfacing with general-purpose data-base applications.
|
17 |
+
|
18 |
+
There are also basic facilities for discrete fourier transform,
|
19 |
+
basic linear algebra and random number generation.
|
20 |
+
|
21 |
+
|
22 |
+
Platform: Windows
|
23 |
+
Platform: Linux
|
24 |
+
Platform: Solaris
|
25 |
+
Platform: Mac OS-X
|
26 |
+
Platform: Unix
|
27 |
+
Classifier: Development Status :: 5 - Production/Stable
|
28 |
+
Classifier: Intended Audience :: Science/Research
|
29 |
+
Classifier: Intended Audience :: Developers
|
30 |
+
Classifier: License :: OSI Approved
|
31 |
+
Classifier: Programming Language :: C
|
32 |
+
Classifier: Programming Language :: Python
|
33 |
+
Classifier: Programming Language :: Python :: 3
|
34 |
+
Classifier: Topic :: Software Development
|
35 |
+
Classifier: Topic :: Scientific/Engineering
|
36 |
+
Classifier: Operating System :: Microsoft :: Windows
|
37 |
+
Classifier: Operating System :: POSIX
|
38 |
+
Classifier: Operating System :: Unix
|
39 |
+
Classifier: Operating System :: MacOS
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/README.txt
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
NumPy is the fundamental package needed for scientific computing with Python.
|
2 |
+
This package contains:
|
3 |
+
|
4 |
+
* a powerful N-dimensional array object
|
5 |
+
* sophisticated (broadcasting) functions
|
6 |
+
* tools for integrating C/C++ and Fortran code
|
7 |
+
* useful linear algebra, Fourier transform, and random number capabilities.
|
8 |
+
|
9 |
+
It derives from the old Numeric code base and can be used as a replacement for Numeric. It also adds the features introduced by numarray and can be used to replace numarray.
|
10 |
+
|
11 |
+
More information can be found at the website:
|
12 |
+
|
13 |
+
http://www.numpy.org
|
14 |
+
|
15 |
+
After installation, tests can be run with:
|
16 |
+
|
17 |
+
python -c 'import numpy; numpy.test()'
|
18 |
+
|
19 |
+
The most current development version is always available from our
|
20 |
+
git repository:
|
21 |
+
|
22 |
+
http://github.com/numpy/numpy
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/THANKS.txt
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Travis Oliphant for the NumPy core, the NumPy guide, various
|
2 |
+
bug-fixes and code contributions.
|
3 |
+
Paul Dubois, who implemented the original Masked Arrays.
|
4 |
+
Pearu Peterson for f2py, numpy.distutils and help with code
|
5 |
+
organization.
|
6 |
+
Robert Kern for mtrand, bug fixes, help with distutils, code
|
7 |
+
organization, strided tricks and much more.
|
8 |
+
Eric Jones for planning and code contributions.
|
9 |
+
Fernando Perez for code snippets, ideas, bugfixes, and testing.
|
10 |
+
Ed Schofield for matrix.py patches, bugfixes, testing, and docstrings.
|
11 |
+
Robert Cimrman for array set operations and numpy.distutils help.
|
12 |
+
John Hunter for code snippets from matplotlib.
|
13 |
+
Chris Hanley for help with records.py, testing, and bug fixes.
|
14 |
+
Travis Vaught for administration, community coordination and
|
15 |
+
marketing.
|
16 |
+
Joe Cooper, Jeff Strunk for administration.
|
17 |
+
Eric Firing for bugfixes.
|
18 |
+
Arnd Baecker for 64-bit testing.
|
19 |
+
David Cooke for many code improvements including the auto-generated C-API,
|
20 |
+
and optimizations.
|
21 |
+
Andrew Straw for help with the web-page, documentation, packaging and
|
22 |
+
testing.
|
23 |
+
Alexander Belopolsky (Sasha) for Masked array bug-fixes and tests,
|
24 |
+
rank-0 array improvements, scalar math help and other code additions.
|
25 |
+
Francesc Altet for unicode, work on nested record arrays, and bug-fixes.
|
26 |
+
Tim Hochberg for getting the build working on MSVC, optimization
|
27 |
+
improvements, and code review.
|
28 |
+
Charles (Chuck) Harris for the sorting code originally written for
|
29 |
+
Numarray and for improvements to polyfit, many bug fixes, delving
|
30 |
+
into the C code, release management, and documentation.
|
31 |
+
David Huard for histogram improvements including 2-D and d-D code and
|
32 |
+
other bug-fixes.
|
33 |
+
Stefan van der Walt for numerous bug-fixes, testing and documentation.
|
34 |
+
Albert Strasheim for documentation, bug-fixes, regression tests and
|
35 |
+
Valgrind expertise.
|
36 |
+
David Cournapeau for build support, doc-and-bug fixes, and code
|
37 |
+
contributions including fast_clipping.
|
38 |
+
Jarrod Millman for release management, community coordination, and code
|
39 |
+
clean up.
|
40 |
+
Chris Burns for work on memory mapped arrays and bug-fixes.
|
41 |
+
Pauli Virtanen for documentation, bug-fixes, lookfor and the
|
42 |
+
documentation editor.
|
43 |
+
A.M. Archibald for no-copy-reshape code, strided array tricks,
|
44 |
+
documentation and bug-fixes.
|
45 |
+
Pierre Gerard-Marchant for rewriting masked array functionality.
|
46 |
+
Roberto de Almeida for the buffered array iterator.
|
47 |
+
Alan McIntyre for updating the NumPy test framework to use nose, improve
|
48 |
+
the test coverage, and enhancing the test system documentation.
|
49 |
+
Joe Harrington for administering the 2008 Documentation Sprint.
|
50 |
+
Mark Wiebe for the new NumPy iterator, the float16 data type, improved
|
51 |
+
low-level data type operations, and other NumPy core improvements.
|
52 |
+
|
53 |
+
NumPy is based on the Numeric (Jim Hugunin, Paul Dubois, Konrad
|
54 |
+
Hinsen, and David Ascher) and NumArray (Perry Greenfield, J Todd
|
55 |
+
Miller, Rick White and Paul Barrett) projects. We thank them for
|
56 |
+
paving the way ahead.
|
57 |
+
|
58 |
+
Institutions
|
59 |
+
------------
|
60 |
+
|
61 |
+
Enthought for providing resources and finances for development of NumPy.
|
62 |
+
UC Berkeley for providing travel money and hosting numerous sprints.
|
63 |
+
The University of Central Florida for funding the 2008 Documentation Marathon.
|
64 |
+
The University of Stellenbosch for hosting the buildbot.
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/__config__.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is generated by /tmp/pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/setup.py
|
2 |
+
# It contains system_info results at the time of building this package.
|
3 |
+
__all__ = ["get_info","show"]
|
4 |
+
|
5 |
+
blas_mkl_info={}
|
6 |
+
openblas_info={}
|
7 |
+
atlas_blas_threads_info={}
|
8 |
+
atlas_blas_info={}
|
9 |
+
blas_info={}
|
10 |
+
blas_src_info={}
|
11 |
+
blas_opt_info={}
|
12 |
+
openblas_lapack_info={}
|
13 |
+
mkl_info={}
|
14 |
+
lapack_mkl_info={}
|
15 |
+
atlas_threads_info={}
|
16 |
+
atlas_info={}
|
17 |
+
lapack_info={}
|
18 |
+
lapack_src_info={}
|
19 |
+
lapack_opt_info={}
|
20 |
+
|
21 |
+
def get_info(name):
|
22 |
+
g = globals()
|
23 |
+
return g.get(name, g.get(name + "_info", {}))
|
24 |
+
|
25 |
+
def show():
|
26 |
+
for name,info_dict in globals().items():
|
27 |
+
if name[0] == "_" or type(info_dict) is not type({}): continue
|
28 |
+
print(name + ":")
|
29 |
+
if not info_dict:
|
30 |
+
print(" NOT AVAILABLE")
|
31 |
+
for k,v in info_dict.items():
|
32 |
+
v = str(v)
|
33 |
+
if k == "sources" and len(v) > 200:
|
34 |
+
v = v[:60] + " ...\n... " + v[-60:]
|
35 |
+
print(" %s = %s" % (k,v))
|
36 |
+
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/__init__.py
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
NumPy
|
3 |
+
=====
|
4 |
+
|
5 |
+
Provides
|
6 |
+
1. An array object of arbitrary homogeneous items
|
7 |
+
2. Fast mathematical operations over arrays
|
8 |
+
3. Linear Algebra, Fourier Transforms, Random Number Generation
|
9 |
+
|
10 |
+
How to use the documentation
|
11 |
+
----------------------------
|
12 |
+
Documentation is available in two forms: docstrings provided
|
13 |
+
with the code, and a loose standing reference guide, available from
|
14 |
+
`the NumPy homepage <http://www.scipy.org>`_.
|
15 |
+
|
16 |
+
We recommend exploring the docstrings using
|
17 |
+
`IPython <http://ipython.scipy.org>`_, an advanced Python shell with
|
18 |
+
TAB-completion and introspection capabilities. See below for further
|
19 |
+
instructions.
|
20 |
+
|
21 |
+
The docstring examples assume that `numpy` has been imported as `np`::
|
22 |
+
|
23 |
+
>>> import numpy as np
|
24 |
+
|
25 |
+
Code snippets are indicated by three greater-than signs::
|
26 |
+
|
27 |
+
>>> x = 42
|
28 |
+
>>> x = x + 1
|
29 |
+
|
30 |
+
Use the built-in ``help`` function to view a function's docstring::
|
31 |
+
|
32 |
+
>>> help(np.sort)
|
33 |
+
... # doctest: +SKIP
|
34 |
+
|
35 |
+
For some objects, ``np.info(obj)`` may provide additional help. This is
|
36 |
+
particularly true if you see the line "Help on ufunc object:" at the top
|
37 |
+
of the help() page. Ufuncs are implemented in C, not Python, for speed.
|
38 |
+
The native Python help() does not know how to view their help, but our
|
39 |
+
np.info() function does.
|
40 |
+
|
41 |
+
To search for documents containing a keyword, do::
|
42 |
+
|
43 |
+
>>> np.lookfor('keyword')
|
44 |
+
... # doctest: +SKIP
|
45 |
+
|
46 |
+
General-purpose documents like a glossary and help on the basic concepts
|
47 |
+
of numpy are available under the ``doc`` sub-module::
|
48 |
+
|
49 |
+
>>> from numpy import doc
|
50 |
+
>>> help(doc)
|
51 |
+
... # doctest: +SKIP
|
52 |
+
|
53 |
+
Available subpackages
|
54 |
+
---------------------
|
55 |
+
doc
|
56 |
+
Topical documentation on broadcasting, indexing, etc.
|
57 |
+
lib
|
58 |
+
Basic functions used by several sub-packages.
|
59 |
+
random
|
60 |
+
Core Random Tools
|
61 |
+
linalg
|
62 |
+
Core Linear Algebra Tools
|
63 |
+
fft
|
64 |
+
Core FFT routines
|
65 |
+
polynomial
|
66 |
+
Polynomial tools
|
67 |
+
testing
|
68 |
+
Numpy testing tools
|
69 |
+
f2py
|
70 |
+
Fortran to Python Interface Generator.
|
71 |
+
distutils
|
72 |
+
Enhancements to distutils with support for
|
73 |
+
Fortran compilers support and more.
|
74 |
+
|
75 |
+
Utilities
|
76 |
+
---------
|
77 |
+
test
|
78 |
+
Run numpy unittests
|
79 |
+
show_config
|
80 |
+
Show numpy build configuration
|
81 |
+
dual
|
82 |
+
Overwrite certain functions with high-performance Scipy tools
|
83 |
+
matlib
|
84 |
+
Make everything matrices.
|
85 |
+
__version__
|
86 |
+
Numpy version string
|
87 |
+
|
88 |
+
Viewing documentation using IPython
|
89 |
+
-----------------------------------
|
90 |
+
Start IPython with the NumPy profile (``ipython -p numpy``), which will
|
91 |
+
import `numpy` under the alias `np`. Then, use the ``cpaste`` command to
|
92 |
+
paste examples into the shell. To see which functions are available in
|
93 |
+
`numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
|
94 |
+
``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
|
95 |
+
down the list. To view the docstring for a function, use
|
96 |
+
``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
|
97 |
+
the source code).
|
98 |
+
|
99 |
+
Copies vs. in-place operation
|
100 |
+
-----------------------------
|
101 |
+
Most of the functions in `numpy` return a copy of the array argument
|
102 |
+
(e.g., `np.sort`). In-place versions of these functions are often
|
103 |
+
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
|
104 |
+
Exceptions to this rule are documented.
|
105 |
+
|
106 |
+
"""
|
107 |
+
from __future__ import division, absolute_import, print_function
|
108 |
+
|
109 |
+
import sys
|
110 |
+
|
111 |
+
|
112 |
+
class ModuleDeprecationWarning(DeprecationWarning):
|
113 |
+
"""Module deprecation warning.
|
114 |
+
|
115 |
+
The nose tester turns ordinary Deprecation warnings into test failures.
|
116 |
+
That makes it hard to deprecate whole modules, because they get
|
117 |
+
imported by default. So this is a special Deprecation warning that the
|
118 |
+
nose tester will let pass without making tests fail.
|
119 |
+
|
120 |
+
"""
|
121 |
+
pass
|
122 |
+
|
123 |
+
|
124 |
+
class VisibleDeprecationWarning(UserWarning):
|
125 |
+
"""Visible deprecation warning.
|
126 |
+
|
127 |
+
By default, python will not show deprecation warnings, so this class
|
128 |
+
can be used when a very visible warning is helpful, for example because
|
129 |
+
the usage is most likely a user bug.
|
130 |
+
|
131 |
+
"""
|
132 |
+
pass
|
133 |
+
|
134 |
+
|
135 |
+
# oldnumeric and numarray were removed in 1.9. In case some packages import
|
136 |
+
# but do not use them, we define them here for backward compatibility.
|
137 |
+
oldnumeric = 'removed'
|
138 |
+
numarray = 'removed'
|
139 |
+
|
140 |
+
|
141 |
+
# We first need to detect if we're being called as part of the numpy setup
|
142 |
+
# procedure itself in a reliable manner.
|
143 |
+
try:
|
144 |
+
__NUMPY_SETUP__
|
145 |
+
except NameError:
|
146 |
+
__NUMPY_SETUP__ = False
|
147 |
+
|
148 |
+
|
149 |
+
if __NUMPY_SETUP__:
|
150 |
+
import sys as _sys
|
151 |
+
_sys.stderr.write('Running from numpy source directory.\n')
|
152 |
+
del _sys
|
153 |
+
else:
|
154 |
+
try:
|
155 |
+
from numpy.__config__ import show as show_config
|
156 |
+
except ImportError:
|
157 |
+
msg = """Error importing numpy: you should not try to import numpy from
|
158 |
+
its source directory; please exit the numpy source tree, and relaunch
|
159 |
+
your python interpreter from there."""
|
160 |
+
raise ImportError(msg)
|
161 |
+
from .version import git_revision as __git_revision__
|
162 |
+
from .version import version as __version__
|
163 |
+
|
164 |
+
from ._import_tools import PackageLoader
|
165 |
+
|
166 |
+
def pkgload(*packages, **options):
|
167 |
+
loader = PackageLoader(infunc=True)
|
168 |
+
return loader(*packages, **options)
|
169 |
+
|
170 |
+
from . import add_newdocs
|
171 |
+
__all__ = ['add_newdocs',
|
172 |
+
'ModuleDeprecationWarning',
|
173 |
+
'VisibleDeprecationWarning']
|
174 |
+
|
175 |
+
pkgload.__doc__ = PackageLoader.__call__.__doc__
|
176 |
+
|
177 |
+
from .testing import Tester
|
178 |
+
test = Tester().test
|
179 |
+
bench = Tester().bench
|
180 |
+
|
181 |
+
from . import core
|
182 |
+
from .core import *
|
183 |
+
from . import compat
|
184 |
+
from . import lib
|
185 |
+
from .lib import *
|
186 |
+
from . import linalg
|
187 |
+
from . import fft
|
188 |
+
from . import polynomial
|
189 |
+
from . import random
|
190 |
+
from . import ctypeslib
|
191 |
+
from . import ma
|
192 |
+
from . import matrixlib as _mat
|
193 |
+
from .matrixlib import *
|
194 |
+
from .compat import long
|
195 |
+
|
196 |
+
# Make these accessible from numpy name-space
|
197 |
+
# but not imported in from numpy import *
|
198 |
+
if sys.version_info[0] >= 3:
|
199 |
+
from builtins import bool, int, float, complex, object, str
|
200 |
+
unicode = str
|
201 |
+
else:
|
202 |
+
from __builtin__ import bool, int, float, complex, object, unicode, str
|
203 |
+
|
204 |
+
from .core import round, abs, max, min
|
205 |
+
|
206 |
+
__all__.extend(['__version__', 'pkgload', 'PackageLoader',
|
207 |
+
'show_config'])
|
208 |
+
__all__.extend(core.__all__)
|
209 |
+
__all__.extend(_mat.__all__)
|
210 |
+
__all__.extend(lib.__all__)
|
211 |
+
__all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
|
212 |
+
|
213 |
+
# Filter annoying Cython warnings that serve no good purpose.
|
214 |
+
import warnings
|
215 |
+
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
|
216 |
+
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/_import_tools.py
ADDED
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
|
6 |
+
__all__ = ['PackageLoader']
|
7 |
+
|
8 |
+
class PackageLoader(object):
|
9 |
+
def __init__(self, verbose=False, infunc=False):
|
10 |
+
""" Manages loading packages.
|
11 |
+
"""
|
12 |
+
|
13 |
+
if infunc:
|
14 |
+
_level = 2
|
15 |
+
else:
|
16 |
+
_level = 1
|
17 |
+
self.parent_frame = frame = sys._getframe(_level)
|
18 |
+
self.parent_name = eval('__name__', frame.f_globals, frame.f_locals)
|
19 |
+
parent_path = eval('__path__', frame.f_globals, frame.f_locals)
|
20 |
+
if isinstance(parent_path, str):
|
21 |
+
parent_path = [parent_path]
|
22 |
+
self.parent_path = parent_path
|
23 |
+
if '__all__' not in frame.f_locals:
|
24 |
+
exec('__all__ = []', frame.f_globals, frame.f_locals)
|
25 |
+
self.parent_export_names = eval('__all__', frame.f_globals, frame.f_locals)
|
26 |
+
|
27 |
+
self.info_modules = {}
|
28 |
+
self.imported_packages = []
|
29 |
+
self.verbose = None
|
30 |
+
|
31 |
+
def _get_info_files(self, package_dir, parent_path, parent_package=None):
|
32 |
+
""" Return list of (package name,info.py file) from parent_path subdirectories.
|
33 |
+
"""
|
34 |
+
from glob import glob
|
35 |
+
files = glob(os.path.join(parent_path, package_dir, 'info.py'))
|
36 |
+
for info_file in glob(os.path.join(parent_path, package_dir, 'info.pyc')):
|
37 |
+
if info_file[:-1] not in files:
|
38 |
+
files.append(info_file)
|
39 |
+
info_files = []
|
40 |
+
for info_file in files:
|
41 |
+
package_name = os.path.dirname(info_file[len(parent_path)+1:])\
|
42 |
+
.replace(os.sep, '.')
|
43 |
+
if parent_package:
|
44 |
+
package_name = parent_package + '.' + package_name
|
45 |
+
info_files.append((package_name, info_file))
|
46 |
+
info_files.extend(self._get_info_files('*',
|
47 |
+
os.path.dirname(info_file),
|
48 |
+
package_name))
|
49 |
+
return info_files
|
50 |
+
|
51 |
+
def _init_info_modules(self, packages=None):
|
52 |
+
"""Initialize info_modules = {<package_name>: <package info.py module>}.
|
53 |
+
"""
|
54 |
+
import imp
|
55 |
+
info_files = []
|
56 |
+
info_modules = self.info_modules
|
57 |
+
|
58 |
+
if packages is None:
|
59 |
+
for path in self.parent_path:
|
60 |
+
info_files.extend(self._get_info_files('*', path))
|
61 |
+
else:
|
62 |
+
for package_name in packages:
|
63 |
+
package_dir = os.path.join(*package_name.split('.'))
|
64 |
+
for path in self.parent_path:
|
65 |
+
names_files = self._get_info_files(package_dir, path)
|
66 |
+
if names_files:
|
67 |
+
info_files.extend(names_files)
|
68 |
+
break
|
69 |
+
else:
|
70 |
+
try:
|
71 |
+
exec('import %s.info as info' % (package_name))
|
72 |
+
info_modules[package_name] = info
|
73 |
+
except ImportError as msg:
|
74 |
+
self.warn('No scipy-style subpackage %r found in %s. '\
|
75 |
+
'Ignoring: %s'\
|
76 |
+
% (package_name, ':'.join(self.parent_path), msg))
|
77 |
+
|
78 |
+
for package_name, info_file in info_files:
|
79 |
+
if package_name in info_modules:
|
80 |
+
continue
|
81 |
+
fullname = self.parent_name +'.'+ package_name
|
82 |
+
if info_file[-1]=='c':
|
83 |
+
filedescriptor = ('.pyc', 'rb', 2)
|
84 |
+
else:
|
85 |
+
filedescriptor = ('.py', 'U', 1)
|
86 |
+
|
87 |
+
try:
|
88 |
+
info_module = imp.load_module(fullname+'.info',
|
89 |
+
open(info_file, filedescriptor[1]),
|
90 |
+
info_file,
|
91 |
+
filedescriptor)
|
92 |
+
except Exception as msg:
|
93 |
+
self.error(msg)
|
94 |
+
info_module = None
|
95 |
+
|
96 |
+
if info_module is None or getattr(info_module, 'ignore', False):
|
97 |
+
info_modules.pop(package_name, None)
|
98 |
+
else:
|
99 |
+
self._init_info_modules(getattr(info_module, 'depends', []))
|
100 |
+
info_modules[package_name] = info_module
|
101 |
+
|
102 |
+
return
|
103 |
+
|
104 |
+
def _get_sorted_names(self):
|
105 |
+
""" Return package names sorted in the order as they should be
|
106 |
+
imported due to dependence relations between packages.
|
107 |
+
"""
|
108 |
+
|
109 |
+
depend_dict = {}
|
110 |
+
for name, info_module in self.info_modules.items():
|
111 |
+
depend_dict[name] = getattr(info_module, 'depends', [])
|
112 |
+
package_names = []
|
113 |
+
|
114 |
+
for name in list(depend_dict.keys()):
|
115 |
+
if not depend_dict[name]:
|
116 |
+
package_names.append(name)
|
117 |
+
del depend_dict[name]
|
118 |
+
|
119 |
+
while depend_dict:
|
120 |
+
for name, lst in list(depend_dict.items()):
|
121 |
+
new_lst = [n for n in lst if n in depend_dict]
|
122 |
+
if not new_lst:
|
123 |
+
package_names.append(name)
|
124 |
+
del depend_dict[name]
|
125 |
+
else:
|
126 |
+
depend_dict[name] = new_lst
|
127 |
+
|
128 |
+
return package_names
|
129 |
+
|
130 |
+
def __call__(self,*packages, **options):
|
131 |
+
"""Load one or more packages into parent package top-level namespace.
|
132 |
+
|
133 |
+
This function is intended to shorten the need to import many
|
134 |
+
subpackages, say of scipy, constantly with statements such as
|
135 |
+
|
136 |
+
import scipy.linalg, scipy.fftpack, scipy.etc...
|
137 |
+
|
138 |
+
Instead, you can say:
|
139 |
+
|
140 |
+
import scipy
|
141 |
+
scipy.pkgload('linalg','fftpack',...)
|
142 |
+
|
143 |
+
or
|
144 |
+
|
145 |
+
scipy.pkgload()
|
146 |
+
|
147 |
+
to load all of them in one call.
|
148 |
+
|
149 |
+
If a name which doesn't exist in scipy's namespace is
|
150 |
+
given, a warning is shown.
|
151 |
+
|
152 |
+
Parameters
|
153 |
+
----------
|
154 |
+
*packages : arg-tuple
|
155 |
+
the names (one or more strings) of all the modules one
|
156 |
+
wishes to load into the top-level namespace.
|
157 |
+
verbose= : integer
|
158 |
+
verbosity level [default: -1].
|
159 |
+
verbose=-1 will suspend also warnings.
|
160 |
+
force= : bool
|
161 |
+
when True, force reloading loaded packages [default: False].
|
162 |
+
postpone= : bool
|
163 |
+
when True, don't load packages [default: False]
|
164 |
+
|
165 |
+
"""
|
166 |
+
frame = self.parent_frame
|
167 |
+
self.info_modules = {}
|
168 |
+
if options.get('force', False):
|
169 |
+
self.imported_packages = []
|
170 |
+
self.verbose = verbose = options.get('verbose', -1)
|
171 |
+
postpone = options.get('postpone', None)
|
172 |
+
self._init_info_modules(packages or None)
|
173 |
+
|
174 |
+
self.log('Imports to %r namespace\n----------------------------'\
|
175 |
+
% self.parent_name)
|
176 |
+
|
177 |
+
for package_name in self._get_sorted_names():
|
178 |
+
if package_name in self.imported_packages:
|
179 |
+
continue
|
180 |
+
info_module = self.info_modules[package_name]
|
181 |
+
global_symbols = getattr(info_module, 'global_symbols', [])
|
182 |
+
postpone_import = getattr(info_module, 'postpone_import', False)
|
183 |
+
if (postpone and not global_symbols) \
|
184 |
+
or (postpone_import and postpone is not None):
|
185 |
+
continue
|
186 |
+
|
187 |
+
old_object = frame.f_locals.get(package_name, None)
|
188 |
+
|
189 |
+
cmdstr = 'import '+package_name
|
190 |
+
if self._execcmd(cmdstr):
|
191 |
+
continue
|
192 |
+
self.imported_packages.append(package_name)
|
193 |
+
|
194 |
+
if verbose!=-1:
|
195 |
+
new_object = frame.f_locals.get(package_name)
|
196 |
+
if old_object is not None and old_object is not new_object:
|
197 |
+
self.warn('Overwriting %s=%s (was %s)' \
|
198 |
+
% (package_name, self._obj2repr(new_object),
|
199 |
+
self._obj2repr(old_object)))
|
200 |
+
|
201 |
+
if '.' not in package_name:
|
202 |
+
self.parent_export_names.append(package_name)
|
203 |
+
|
204 |
+
for symbol in global_symbols:
|
205 |
+
if symbol=='*':
|
206 |
+
symbols = eval('getattr(%s,"__all__",None)'\
|
207 |
+
% (package_name),
|
208 |
+
frame.f_globals, frame.f_locals)
|
209 |
+
if symbols is None:
|
210 |
+
symbols = eval('dir(%s)' % (package_name),
|
211 |
+
frame.f_globals, frame.f_locals)
|
212 |
+
symbols = [s for s in symbols if not s.startswith('_')]
|
213 |
+
else:
|
214 |
+
symbols = [symbol]
|
215 |
+
|
216 |
+
if verbose!=-1:
|
217 |
+
old_objects = {}
|
218 |
+
for s in symbols:
|
219 |
+
if s in frame.f_locals:
|
220 |
+
old_objects[s] = frame.f_locals[s]
|
221 |
+
|
222 |
+
cmdstr = 'from '+package_name+' import '+symbol
|
223 |
+
if self._execcmd(cmdstr):
|
224 |
+
continue
|
225 |
+
|
226 |
+
if verbose!=-1:
|
227 |
+
for s, old_object in old_objects.items():
|
228 |
+
new_object = frame.f_locals[s]
|
229 |
+
if new_object is not old_object:
|
230 |
+
self.warn('Overwriting %s=%s (was %s)' \
|
231 |
+
% (s, self._obj2repr(new_object),
|
232 |
+
self._obj2repr(old_object)))
|
233 |
+
|
234 |
+
if symbol=='*':
|
235 |
+
self.parent_export_names.extend(symbols)
|
236 |
+
else:
|
237 |
+
self.parent_export_names.append(symbol)
|
238 |
+
|
239 |
+
return
|
240 |
+
|
241 |
+
def _execcmd(self, cmdstr):
|
242 |
+
""" Execute command in parent_frame."""
|
243 |
+
frame = self.parent_frame
|
244 |
+
try:
|
245 |
+
exec (cmdstr, frame.f_globals, frame.f_locals)
|
246 |
+
except Exception as msg:
|
247 |
+
self.error('%s -> failed: %s' % (cmdstr, msg))
|
248 |
+
return True
|
249 |
+
else:
|
250 |
+
self.log('%s -> success' % (cmdstr))
|
251 |
+
return
|
252 |
+
|
253 |
+
def _obj2repr(self, obj):
|
254 |
+
""" Return repr(obj) with"""
|
255 |
+
module = getattr(obj, '__module__', None)
|
256 |
+
file = getattr(obj, '__file__', None)
|
257 |
+
if module is not None:
|
258 |
+
return repr(obj) + ' from ' + module
|
259 |
+
if file is not None:
|
260 |
+
return repr(obj) + ' from ' + file
|
261 |
+
return repr(obj)
|
262 |
+
|
263 |
+
def log(self, mess):
|
264 |
+
if self.verbose>1:
|
265 |
+
print(str(mess), file=sys.stderr)
|
266 |
+
def warn(self, mess):
|
267 |
+
if self.verbose>=0:
|
268 |
+
print(str(mess), file=sys.stderr)
|
269 |
+
def error(self, mess):
|
270 |
+
if self.verbose!=-1:
|
271 |
+
print(str(mess), file=sys.stderr)
|
272 |
+
|
273 |
+
def _get_doc_title(self, info_module):
|
274 |
+
""" Get the title from a package info.py file.
|
275 |
+
"""
|
276 |
+
title = getattr(info_module, '__doc_title__', None)
|
277 |
+
if title is not None:
|
278 |
+
return title
|
279 |
+
title = getattr(info_module, '__doc__', None)
|
280 |
+
if title is not None:
|
281 |
+
title = title.lstrip().split('\n', 1)[0]
|
282 |
+
return title
|
283 |
+
return '* Not Available *'
|
284 |
+
|
285 |
+
def _format_titles(self,titles,colsep='---'):
|
286 |
+
display_window_width = 70 # How to determine the correct value in runtime??
|
287 |
+
lengths = [len(name)-name.find('.')-1 for (name, title) in titles]+[0]
|
288 |
+
max_length = max(lengths)
|
289 |
+
lines = []
|
290 |
+
for (name, title) in titles:
|
291 |
+
name = name[name.find('.')+1:]
|
292 |
+
w = max_length - len(name)
|
293 |
+
words = title.split()
|
294 |
+
line = '%s%s %s' % (name, w*' ', colsep)
|
295 |
+
tab = len(line) * ' '
|
296 |
+
while words:
|
297 |
+
word = words.pop(0)
|
298 |
+
if len(line)+len(word)>display_window_width:
|
299 |
+
lines.append(line)
|
300 |
+
line = tab
|
301 |
+
line += ' ' + word
|
302 |
+
else:
|
303 |
+
lines.append(line)
|
304 |
+
return '\n'.join(lines)
|
305 |
+
|
306 |
+
def get_pkgdocs(self):
|
307 |
+
""" Return documentation summary of subpackages.
|
308 |
+
"""
|
309 |
+
import sys
|
310 |
+
self.info_modules = {}
|
311 |
+
self._init_info_modules(None)
|
312 |
+
|
313 |
+
titles = []
|
314 |
+
symbols = []
|
315 |
+
for package_name, info_module in self.info_modules.items():
|
316 |
+
global_symbols = getattr(info_module, 'global_symbols', [])
|
317 |
+
fullname = self.parent_name +'.'+ package_name
|
318 |
+
note = ''
|
319 |
+
if fullname not in sys.modules:
|
320 |
+
note = ' [*]'
|
321 |
+
titles.append((fullname, self._get_doc_title(info_module) + note))
|
322 |
+
if global_symbols:
|
323 |
+
symbols.append((package_name, ', '.join(global_symbols)))
|
324 |
+
|
325 |
+
retstr = self._format_titles(titles) +\
|
326 |
+
'\n [*] - using a package requires explicit import (see pkgload)'
|
327 |
+
|
328 |
+
|
329 |
+
if symbols:
|
330 |
+
retstr += """\n\nGlobal symbols from subpackages"""\
|
331 |
+
"""\n-------------------------------\n""" +\
|
332 |
+
self._format_titles(symbols, '-->')
|
333 |
+
|
334 |
+
return retstr
|
335 |
+
|
336 |
+
class PackageLoaderDebug(PackageLoader):
|
337 |
+
def _execcmd(self, cmdstr):
|
338 |
+
""" Execute command in parent_frame."""
|
339 |
+
frame = self.parent_frame
|
340 |
+
print('Executing', repr(cmdstr), '...', end=' ')
|
341 |
+
sys.stdout.flush()
|
342 |
+
exec (cmdstr, frame.f_globals, frame.f_locals)
|
343 |
+
print('ok')
|
344 |
+
sys.stdout.flush()
|
345 |
+
return
|
346 |
+
|
347 |
+
if int(os.environ.get('NUMPY_IMPORT_DEBUG', '0')):
|
348 |
+
PackageLoader = PackageLoaderDebug
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/add_newdocs.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/__init__.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Compatibility module.
|
3 |
+
|
4 |
+
This module contains duplicated code from Python itself or 3rd party
|
5 |
+
extensions, which may be included for the following reasons:
|
6 |
+
|
7 |
+
* compatibility
|
8 |
+
* we may only need a small subset of the copied library/module
|
9 |
+
|
10 |
+
"""
|
11 |
+
from __future__ import division, absolute_import, print_function
|
12 |
+
|
13 |
+
from . import _inspect
|
14 |
+
from . import py3k
|
15 |
+
from ._inspect import getargspec, formatargspec
|
16 |
+
from .py3k import *
|
17 |
+
|
18 |
+
__all__ = []
|
19 |
+
__all__.extend(_inspect.__all__)
|
20 |
+
__all__.extend(py3k.__all__)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/_inspect.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Subset of inspect module from upstream python
|
2 |
+
|
3 |
+
We use this instead of upstream because upstream inspect is slow to import, and
|
4 |
+
significanly contributes to numpy import times. Importing this copy has almost
|
5 |
+
no overhead.
|
6 |
+
|
7 |
+
"""
|
8 |
+
from __future__ import division, absolute_import, print_function
|
9 |
+
|
10 |
+
import types
|
11 |
+
|
12 |
+
__all__ = ['getargspec', 'formatargspec']
|
13 |
+
|
14 |
+
# ----------------------------------------------------------- type-checking
|
15 |
+
def ismethod(object):
|
16 |
+
"""Return true if the object is an instance method.
|
17 |
+
|
18 |
+
Instance method objects provide these attributes:
|
19 |
+
__doc__ documentation string
|
20 |
+
__name__ name with which this method was defined
|
21 |
+
im_class class object in which this method belongs
|
22 |
+
im_func function object containing implementation of method
|
23 |
+
im_self instance to which this method is bound, or None"""
|
24 |
+
return isinstance(object, types.MethodType)
|
25 |
+
|
26 |
+
def isfunction(object):
|
27 |
+
"""Return true if the object is a user-defined function.
|
28 |
+
|
29 |
+
Function objects provide these attributes:
|
30 |
+
__doc__ documentation string
|
31 |
+
__name__ name with which this function was defined
|
32 |
+
func_code code object containing compiled function bytecode
|
33 |
+
func_defaults tuple of any default values for arguments
|
34 |
+
func_doc (same as __doc__)
|
35 |
+
func_globals global namespace in which this function was defined
|
36 |
+
func_name (same as __name__)"""
|
37 |
+
return isinstance(object, types.FunctionType)
|
38 |
+
|
39 |
+
def iscode(object):
|
40 |
+
"""Return true if the object is a code object.
|
41 |
+
|
42 |
+
Code objects provide these attributes:
|
43 |
+
co_argcount number of arguments (not including * or ** args)
|
44 |
+
co_code string of raw compiled bytecode
|
45 |
+
co_consts tuple of constants used in the bytecode
|
46 |
+
co_filename name of file in which this code object was created
|
47 |
+
co_firstlineno number of first line in Python source code
|
48 |
+
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
|
49 |
+
co_lnotab encoded mapping of line numbers to bytecode indices
|
50 |
+
co_name name with which this code object was defined
|
51 |
+
co_names tuple of names of local variables
|
52 |
+
co_nlocals number of local variables
|
53 |
+
co_stacksize virtual machine stack space required
|
54 |
+
co_varnames tuple of names of arguments and local variables"""
|
55 |
+
return isinstance(object, types.CodeType)
|
56 |
+
|
57 |
+
# ------------------------------------------------ argument list extraction
|
58 |
+
# These constants are from Python's compile.h.
|
59 |
+
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
|
60 |
+
|
61 |
+
def getargs(co):
|
62 |
+
"""Get information about the arguments accepted by a code object.
|
63 |
+
|
64 |
+
Three things are returned: (args, varargs, varkw), where 'args' is
|
65 |
+
a list of argument names (possibly containing nested lists), and
|
66 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None."""
|
67 |
+
|
68 |
+
if not iscode(co):
|
69 |
+
raise TypeError('arg is not a code object')
|
70 |
+
|
71 |
+
code = co.co_code
|
72 |
+
nargs = co.co_argcount
|
73 |
+
names = co.co_varnames
|
74 |
+
args = list(names[:nargs])
|
75 |
+
step = 0
|
76 |
+
|
77 |
+
# The following acrobatics are for anonymous (tuple) arguments.
|
78 |
+
for i in range(nargs):
|
79 |
+
if args[i][:1] in ['', '.']:
|
80 |
+
stack, remain, count = [], [], []
|
81 |
+
while step < len(code):
|
82 |
+
op = ord(code[step])
|
83 |
+
step = step + 1
|
84 |
+
if op >= dis.HAVE_ARGUMENT:
|
85 |
+
opname = dis.opname[op]
|
86 |
+
value = ord(code[step]) + ord(code[step+1])*256
|
87 |
+
step = step + 2
|
88 |
+
if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']:
|
89 |
+
remain.append(value)
|
90 |
+
count.append(value)
|
91 |
+
elif opname == 'STORE_FAST':
|
92 |
+
stack.append(names[value])
|
93 |
+
|
94 |
+
# Special case for sublists of length 1: def foo((bar))
|
95 |
+
# doesn't generate the UNPACK_TUPLE bytecode, so if
|
96 |
+
# `remain` is empty here, we have such a sublist.
|
97 |
+
if not remain:
|
98 |
+
stack[0] = [stack[0]]
|
99 |
+
break
|
100 |
+
else:
|
101 |
+
remain[-1] = remain[-1] - 1
|
102 |
+
while remain[-1] == 0:
|
103 |
+
remain.pop()
|
104 |
+
size = count.pop()
|
105 |
+
stack[-size:] = [stack[-size:]]
|
106 |
+
if not remain: break
|
107 |
+
remain[-1] = remain[-1] - 1
|
108 |
+
if not remain: break
|
109 |
+
args[i] = stack[0]
|
110 |
+
|
111 |
+
varargs = None
|
112 |
+
if co.co_flags & CO_VARARGS:
|
113 |
+
varargs = co.co_varnames[nargs]
|
114 |
+
nargs = nargs + 1
|
115 |
+
varkw = None
|
116 |
+
if co.co_flags & CO_VARKEYWORDS:
|
117 |
+
varkw = co.co_varnames[nargs]
|
118 |
+
return args, varargs, varkw
|
119 |
+
|
120 |
+
def getargspec(func):
|
121 |
+
"""Get the names and default values of a function's arguments.
|
122 |
+
|
123 |
+
A tuple of four things is returned: (args, varargs, varkw, defaults).
|
124 |
+
'args' is a list of the argument names (it may contain nested lists).
|
125 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
126 |
+
'defaults' is an n-tuple of the default values of the last n arguments.
|
127 |
+
"""
|
128 |
+
|
129 |
+
if ismethod(func):
|
130 |
+
func = func.__func__
|
131 |
+
if not isfunction(func):
|
132 |
+
raise TypeError('arg is not a Python function')
|
133 |
+
args, varargs, varkw = getargs(func.__code__)
|
134 |
+
return args, varargs, varkw, func.__defaults__
|
135 |
+
|
136 |
+
def getargvalues(frame):
|
137 |
+
"""Get information about arguments passed into a particular frame.
|
138 |
+
|
139 |
+
A tuple of four things is returned: (args, varargs, varkw, locals).
|
140 |
+
'args' is a list of the argument names (it may contain nested lists).
|
141 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
142 |
+
'locals' is the locals dictionary of the given frame."""
|
143 |
+
args, varargs, varkw = getargs(frame.f_code)
|
144 |
+
return args, varargs, varkw, frame.f_locals
|
145 |
+
|
146 |
+
def joinseq(seq):
|
147 |
+
if len(seq) == 1:
|
148 |
+
return '(' + seq[0] + ',)'
|
149 |
+
else:
|
150 |
+
return '(' + ', '.join(seq) + ')'
|
151 |
+
|
152 |
+
def strseq(object, convert, join=joinseq):
|
153 |
+
"""Recursively walk a sequence, stringifying each element."""
|
154 |
+
if type(object) in [list, tuple]:
|
155 |
+
return join([strseq(_o, convert, join) for _o in object])
|
156 |
+
else:
|
157 |
+
return convert(object)
|
158 |
+
|
159 |
+
def formatargspec(args, varargs=None, varkw=None, defaults=None,
|
160 |
+
formatarg=str,
|
161 |
+
formatvarargs=lambda name: '*' + name,
|
162 |
+
formatvarkw=lambda name: '**' + name,
|
163 |
+
formatvalue=lambda value: '=' + repr(value),
|
164 |
+
join=joinseq):
|
165 |
+
"""Format an argument spec from the 4 values returned by getargspec.
|
166 |
+
|
167 |
+
The first four arguments are (args, varargs, varkw, defaults). The
|
168 |
+
other four arguments are the corresponding optional formatting functions
|
169 |
+
that are called to turn names and values into strings. The ninth
|
170 |
+
argument is an optional function to format the sequence of arguments."""
|
171 |
+
specs = []
|
172 |
+
if defaults:
|
173 |
+
firstdefault = len(args) - len(defaults)
|
174 |
+
for i in range(len(args)):
|
175 |
+
spec = strseq(args[i], formatarg, join)
|
176 |
+
if defaults and i >= firstdefault:
|
177 |
+
spec = spec + formatvalue(defaults[i - firstdefault])
|
178 |
+
specs.append(spec)
|
179 |
+
if varargs is not None:
|
180 |
+
specs.append(formatvarargs(varargs))
|
181 |
+
if varkw is not None:
|
182 |
+
specs.append(formatvarkw(varkw))
|
183 |
+
return '(' + ', '.join(specs) + ')'
|
184 |
+
|
185 |
+
def formatargvalues(args, varargs, varkw, locals,
|
186 |
+
formatarg=str,
|
187 |
+
formatvarargs=lambda name: '*' + name,
|
188 |
+
formatvarkw=lambda name: '**' + name,
|
189 |
+
formatvalue=lambda value: '=' + repr(value),
|
190 |
+
join=joinseq):
|
191 |
+
"""Format an argument spec from the 4 values returned by getargvalues.
|
192 |
+
|
193 |
+
The first four arguments are (args, varargs, varkw, locals). The
|
194 |
+
next four arguments are the corresponding optional formatting functions
|
195 |
+
that are called to turn names and values into strings. The ninth
|
196 |
+
argument is an optional function to format the sequence of arguments."""
|
197 |
+
def convert(name, locals=locals,
|
198 |
+
formatarg=formatarg, formatvalue=formatvalue):
|
199 |
+
return formatarg(name) + formatvalue(locals[name])
|
200 |
+
specs = []
|
201 |
+
for i in range(len(args)):
|
202 |
+
specs.append(strseq(args[i], convert, join))
|
203 |
+
if varargs:
|
204 |
+
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
|
205 |
+
if varkw:
|
206 |
+
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
|
207 |
+
return '(' + string.join(specs, ', ') + ')'
|
208 |
+
|
209 |
+
if __name__ == '__main__':
|
210 |
+
import inspect
|
211 |
+
def foo(x, y, z=None):
|
212 |
+
return None
|
213 |
+
|
214 |
+
print(inspect.getargs(foo.__code__))
|
215 |
+
print(getargs(foo.__code__))
|
216 |
+
|
217 |
+
print(inspect.getargspec(foo))
|
218 |
+
print(getargspec(foo))
|
219 |
+
|
220 |
+
print(inspect.formatargspec(*inspect.getargspec(foo)))
|
221 |
+
print(formatargspec(*getargspec(foo)))
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/py3k.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Python 3 compatibility tools.
|
3 |
+
|
4 |
+
"""
|
5 |
+
from __future__ import division, absolute_import, print_function
|
6 |
+
|
7 |
+
__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
|
8 |
+
'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
|
9 |
+
'asstr', 'open_latin1', 'long', 'basestring', 'sixu',
|
10 |
+
'integer_types']
|
11 |
+
|
12 |
+
import sys
|
13 |
+
|
14 |
+
if sys.version_info[0] >= 3:
|
15 |
+
import io
|
16 |
+
|
17 |
+
long = int
|
18 |
+
integer_types = (int,)
|
19 |
+
basestring = str
|
20 |
+
unicode = str
|
21 |
+
bytes = bytes
|
22 |
+
|
23 |
+
def asunicode(s):
|
24 |
+
if isinstance(s, bytes):
|
25 |
+
return s.decode('latin1')
|
26 |
+
return str(s)
|
27 |
+
|
28 |
+
def asbytes(s):
|
29 |
+
if isinstance(s, bytes):
|
30 |
+
return s
|
31 |
+
return str(s).encode('latin1')
|
32 |
+
|
33 |
+
def asstr(s):
|
34 |
+
if isinstance(s, bytes):
|
35 |
+
return s.decode('latin1')
|
36 |
+
return str(s)
|
37 |
+
|
38 |
+
def isfileobj(f):
|
39 |
+
return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter))
|
40 |
+
|
41 |
+
def open_latin1(filename, mode='r'):
|
42 |
+
return open(filename, mode=mode, encoding='iso-8859-1')
|
43 |
+
|
44 |
+
def sixu(s):
|
45 |
+
return s
|
46 |
+
|
47 |
+
strchar = 'U'
|
48 |
+
|
49 |
+
|
50 |
+
else:
|
51 |
+
bytes = str
|
52 |
+
long = long
|
53 |
+
basestring = basestring
|
54 |
+
unicode = unicode
|
55 |
+
integer_types = (int, long)
|
56 |
+
asbytes = str
|
57 |
+
asstr = str
|
58 |
+
strchar = 'S'
|
59 |
+
|
60 |
+
|
61 |
+
def isfileobj(f):
|
62 |
+
return isinstance(f, file)
|
63 |
+
|
64 |
+
def asunicode(s):
|
65 |
+
if isinstance(s, unicode):
|
66 |
+
return s
|
67 |
+
return str(s).decode('ascii')
|
68 |
+
|
69 |
+
def open_latin1(filename, mode='r'):
|
70 |
+
return open(filename, mode=mode)
|
71 |
+
|
72 |
+
def sixu(s):
|
73 |
+
return unicode(s, 'unicode_escape')
|
74 |
+
|
75 |
+
|
76 |
+
def getexception():
|
77 |
+
return sys.exc_info()[1]
|
78 |
+
|
79 |
+
def asbytes_nested(x):
|
80 |
+
if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
|
81 |
+
return [asbytes_nested(y) for y in x]
|
82 |
+
else:
|
83 |
+
return asbytes(x)
|
84 |
+
|
85 |
+
def asunicode_nested(x):
|
86 |
+
if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)):
|
87 |
+
return [asunicode_nested(y) for y in x]
|
88 |
+
else:
|
89 |
+
return asunicode(x)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/compat/setup.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
from __future__ import division, print_function
|
3 |
+
|
4 |
+
|
5 |
+
def configuration(parent_package='',top_path=None):
|
6 |
+
from numpy.distutils.misc_util import Configuration
|
7 |
+
config = Configuration('compat', parent_package, top_path)
|
8 |
+
return config
|
9 |
+
|
10 |
+
if __name__ == '__main__':
|
11 |
+
from numpy.distutils.core import setup
|
12 |
+
setup(configuration=configuration)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/__init__.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
from .info import __doc__
|
4 |
+
from numpy.version import version as __version__
|
5 |
+
|
6 |
+
from . import multiarray
|
7 |
+
from . import umath
|
8 |
+
from . import _internal # for freeze programs
|
9 |
+
from . import numerictypes as nt
|
10 |
+
multiarray.set_typeDict(nt.sctypeDict)
|
11 |
+
from . import numeric
|
12 |
+
from .numeric import *
|
13 |
+
from . import fromnumeric
|
14 |
+
from .fromnumeric import *
|
15 |
+
from . import defchararray as char
|
16 |
+
from . import records as rec
|
17 |
+
from .records import *
|
18 |
+
from .memmap import *
|
19 |
+
from .defchararray import chararray
|
20 |
+
from . import scalarmath
|
21 |
+
from . import function_base
|
22 |
+
from .function_base import *
|
23 |
+
from . import machar
|
24 |
+
from .machar import *
|
25 |
+
from . import getlimits
|
26 |
+
from .getlimits import *
|
27 |
+
from . import shape_base
|
28 |
+
from .shape_base import *
|
29 |
+
del nt
|
30 |
+
|
31 |
+
from .fromnumeric import amax as max, amin as min, \
|
32 |
+
round_ as round
|
33 |
+
from .numeric import absolute as abs
|
34 |
+
|
35 |
+
__all__ = ['char', 'rec', 'memmap']
|
36 |
+
__all__ += numeric.__all__
|
37 |
+
__all__ += fromnumeric.__all__
|
38 |
+
__all__ += rec.__all__
|
39 |
+
__all__ += ['chararray']
|
40 |
+
__all__ += function_base.__all__
|
41 |
+
__all__ += machar.__all__
|
42 |
+
__all__ += getlimits.__all__
|
43 |
+
__all__ += shape_base.__all__
|
44 |
+
|
45 |
+
|
46 |
+
from numpy.testing import Tester
|
47 |
+
test = Tester().test
|
48 |
+
bench = Tester().bench
|
49 |
+
|
50 |
+
# Make it possible so that ufuncs can be pickled
|
51 |
+
# Here are the loading and unloading functions
|
52 |
+
# The name numpy.core._ufunc_reconstruct must be
|
53 |
+
# available for unpickling to work.
|
54 |
+
def _ufunc_reconstruct(module, name):
|
55 |
+
# The `fromlist` kwarg is required to ensure that `mod` points to the
|
56 |
+
# inner-most module rather than the parent package when module name is
|
57 |
+
# nested. This makes it possible to pickle non-toplevel ufuncs such as
|
58 |
+
# scipy.special.expit for instance.
|
59 |
+
mod = __import__(module, fromlist=[name])
|
60 |
+
return getattr(mod, name)
|
61 |
+
|
62 |
+
def _ufunc_reduce(func):
|
63 |
+
from pickle import whichmodule
|
64 |
+
name = func.__name__
|
65 |
+
return _ufunc_reconstruct, (whichmodule(func, name), name)
|
66 |
+
|
67 |
+
|
68 |
+
import sys
|
69 |
+
if sys.version_info[0] >= 3:
|
70 |
+
import copyreg
|
71 |
+
else:
|
72 |
+
import copy_reg as copyreg
|
73 |
+
|
74 |
+
copyreg.pickle(ufunc, _ufunc_reduce, _ufunc_reconstruct)
|
75 |
+
# Unclutter namespace (must keep _ufunc_reconstruct for unpickling)
|
76 |
+
del copyreg
|
77 |
+
del sys
|
78 |
+
del _ufunc_reduce
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/_dummy.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (24 kB). View file
|
|
pip-install-ghxuqwgs/numpy_78e94bf2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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A place for code to be called from core C-code.
|
3 |
+
|
4 |
+
Some things are more easily handled Python.
|
5 |
+
|
6 |
+
"""
|
7 |
+
from __future__ import division, absolute_import, print_function
|
8 |
+
|
9 |
+
import re
|
10 |
+
import sys
|
11 |
+
import warnings
|
12 |
+
|
13 |
+
from numpy.compat import asbytes, bytes
|
14 |
+
|
15 |
+
if (sys.byteorder == 'little'):
|
16 |
+
_nbo = asbytes('<')
|
17 |
+
else:
|
18 |
+
_nbo = asbytes('>')
|
19 |
+
|
20 |
+
def _makenames_list(adict, align):
|
21 |
+
from .multiarray import dtype
|
22 |
+
allfields = []
|
23 |
+
fnames = list(adict.keys())
|
24 |
+
for fname in fnames:
|
25 |
+
obj = adict[fname]
|
26 |
+
n = len(obj)
|
27 |
+
if not isinstance(obj, tuple) or n not in [2, 3]:
|
28 |
+
raise ValueError("entry not a 2- or 3- tuple")
|
29 |
+
if (n > 2) and (obj[2] == fname):
|
30 |
+
continue
|
31 |
+
num = int(obj[1])
|
32 |
+
if (num < 0):
|
33 |
+
raise ValueError("invalid offset.")
|
34 |
+
format = dtype(obj[0], align=align)
|
35 |
+
if (format.itemsize == 0):
|
36 |
+
raise ValueError("all itemsizes must be fixed.")
|
37 |
+
if (n > 2):
|
38 |
+
title = obj[2]
|
39 |
+
else:
|
40 |
+
title = None
|
41 |
+
allfields.append((fname, format, num, title))
|
42 |
+
# sort by offsets
|
43 |
+
allfields.sort(key=lambda x: x[2])
|
44 |
+
names = [x[0] for x in allfields]
|
45 |
+
formats = [x[1] for x in allfields]
|
46 |
+
offsets = [x[2] for x in allfields]
|
47 |
+
titles = [x[3] for x in allfields]
|
48 |
+
|
49 |
+
return names, formats, offsets, titles
|
50 |
+
|
51 |
+
# Called in PyArray_DescrConverter function when
|
52 |
+
# a dictionary without "names" and "formats"
|
53 |
+
# fields is used as a data-type descriptor.
|
54 |
+
def _usefields(adict, align):
|
55 |
+
from .multiarray import dtype
|
56 |
+
try:
|
57 |
+
names = adict[-1]
|
58 |
+
except KeyError:
|
59 |
+
names = None
|
60 |
+
if names is None:
|
61 |
+
names, formats, offsets, titles = _makenames_list(adict, align)
|
62 |
+
else:
|
63 |
+
formats = []
|
64 |
+
offsets = []
|
65 |
+
titles = []
|
66 |
+
for name in names:
|
67 |
+
res = adict[name]
|
68 |
+
formats.append(res[0])
|
69 |
+
offsets.append(res[1])
|
70 |
+
if (len(res) > 2):
|
71 |
+
titles.append(res[2])
|
72 |
+
else:
|
73 |
+
titles.append(None)
|
74 |
+
|
75 |
+
return dtype({"names" : names,
|
76 |
+
"formats" : formats,
|
77 |
+
"offsets" : offsets,
|
78 |
+
"titles" : titles}, align)
|
79 |
+
|
80 |
+
|
81 |
+
# construct an array_protocol descriptor list
|
82 |
+
# from the fields attribute of a descriptor
|
83 |
+
# This calls itself recursively but should eventually hit
|
84 |
+
# a descriptor that has no fields and then return
|
85 |
+
# a simple typestring
|
86 |
+
|
87 |
+
def _array_descr(descriptor):
|
88 |
+
fields = descriptor.fields
|
89 |
+
if fields is None:
|
90 |
+
subdtype = descriptor.subdtype
|
91 |
+
if subdtype is None:
|
92 |
+
if descriptor.metadata is None:
|
93 |
+
return descriptor.str
|
94 |
+
else:
|
95 |
+
new = descriptor.metadata.copy()
|
96 |
+
if new:
|
97 |
+
return (descriptor.str, new)
|
98 |
+
else:
|
99 |
+
return descriptor.str
|
100 |
+
else:
|
101 |
+
return (_array_descr(subdtype[0]), subdtype[1])
|
102 |
+
|
103 |
+
|
104 |
+
names = descriptor.names
|
105 |
+
ordered_fields = [fields[x] + (x,) for x in names]
|
106 |
+
result = []
|
107 |
+
offset = 0
|
108 |
+
for field in ordered_fields:
|
109 |
+
if field[1] > offset:
|
110 |
+
num = field[1] - offset
|
111 |
+
result.append(('', '|V%d' % num))
|
112 |
+
offset += num
|
113 |
+
if len(field) > 3:
|
114 |
+
name = (field[2], field[3])
|
115 |
+
else:
|
116 |
+
name = field[2]
|
117 |
+
if field[0].subdtype:
|
118 |
+
tup = (name, _array_descr(field[0].subdtype[0]),
|
119 |
+
field[0].subdtype[1])
|
120 |
+
else:
|
121 |
+
tup = (name, _array_descr(field[0]))
|
122 |
+
offset += field[0].itemsize
|
123 |
+
result.append(tup)
|
124 |
+
|
125 |
+
return result
|
126 |
+
|
127 |
+
# Build a new array from the information in a pickle.
|
128 |
+
# Note that the name numpy.core._internal._reconstruct is embedded in
|
129 |
+
# pickles of ndarrays made with NumPy before release 1.0
|
130 |
+
# so don't remove the name here, or you'll
|
131 |
+
# break backward compatibilty.
|
132 |
+
def _reconstruct(subtype, shape, dtype):
|
133 |
+
from .multiarray import ndarray
|
134 |
+
return ndarray.__new__(subtype, shape, dtype)
|
135 |
+
|
136 |
+
|
137 |
+
# format_re was originally from numarray by J. Todd Miller
|
138 |
+
|
139 |
+
format_re = re.compile(asbytes(
|
140 |
+
r'(?P<order1>[<>|=]?)'
|
141 |
+
r'(?P<repeats> *[(]?[ ,0-9L]*[)]? *)'
|
142 |
+
r'(?P<order2>[<>|=]?)'
|
143 |
+
r'(?P<dtype>[A-Za-z0-9.]*(?:\[[a-zA-Z0-9,.]+\])?)'))
|
144 |
+
sep_re = re.compile(asbytes(r'\s*,\s*'))
|
145 |
+
space_re = re.compile(asbytes(r'\s+$'))
|
146 |
+
|
147 |
+
# astr is a string (perhaps comma separated)
|
148 |
+
|
149 |
+
_convorder = {asbytes('='): _nbo}
|
150 |
+
|
151 |
+
def _commastring(astr):
|
152 |
+
startindex = 0
|
153 |
+
result = []
|
154 |
+
while startindex < len(astr):
|
155 |
+
mo = format_re.match(astr, pos=startindex)
|
156 |
+
try:
|
157 |
+
(order1, repeats, order2, dtype) = mo.groups()
|
158 |
+
except (TypeError, AttributeError):
|
159 |
+
raise ValueError('format number %d of "%s" is not recognized' %
|
160 |
+
(len(result)+1, astr))
|
161 |
+
startindex = mo.end()
|
162 |
+
# Separator or ending padding
|
163 |
+
if startindex < len(astr):
|
164 |
+
if space_re.match(astr, pos=startindex):
|
165 |
+
startindex = len(astr)
|
166 |
+
else:
|
167 |
+
mo = sep_re.match(astr, pos=startindex)
|
168 |
+
if not mo:
|
169 |
+
raise ValueError(
|
170 |
+
'format number %d of "%s" is not recognized' %
|
171 |
+
(len(result)+1, astr))
|
172 |
+
startindex = mo.end()
|
173 |
+
|
174 |
+
if order2 == asbytes(''):
|
175 |
+
order = order1
|
176 |
+
elif order1 == asbytes(''):
|
177 |
+
order = order2
|
178 |
+
else:
|
179 |
+
order1 = _convorder.get(order1, order1)
|
180 |
+
order2 = _convorder.get(order2, order2)
|
181 |
+
if (order1 != order2):
|
182 |
+
raise ValueError('inconsistent byte-order specification %s and %s' % (order1, order2))
|
183 |
+
order = order1
|
184 |
+
|
185 |
+
if order in [asbytes('|'), asbytes('='), _nbo]:
|
186 |
+
order = asbytes('')
|
187 |
+
dtype = order + dtype
|
188 |
+
if (repeats == asbytes('')):
|
189 |
+
newitem = dtype
|
190 |
+
else:
|
191 |
+
newitem = (dtype, eval(repeats))
|
192 |
+
result.append(newitem)
|
193 |
+
|
194 |
+
return result
|
195 |
+
|
196 |
+
def _getintp_ctype():
|
197 |
+
from .multiarray import dtype
|
198 |
+
val = _getintp_ctype.cache
|
199 |
+
if val is not None:
|
200 |
+
return val
|
201 |
+
char = dtype('p').char
|
202 |
+
import ctypes
|
203 |
+
if (char == 'i'):
|
204 |
+
val = ctypes.c_int
|
205 |
+
elif char == 'l':
|
206 |
+
val = ctypes.c_long
|
207 |
+
elif char == 'q':
|
208 |
+
val = ctypes.c_longlong
|
209 |
+
else:
|
210 |
+
val = ctypes.c_long
|
211 |
+
_getintp_ctype.cache = val
|
212 |
+
return val
|
213 |
+
_getintp_ctype.cache = None
|
214 |
+
|
215 |
+
# Used for .ctypes attribute of ndarray
|
216 |
+
|
217 |
+
class _missing_ctypes(object):
|
218 |
+
def cast(self, num, obj):
|
219 |
+
return num
|
220 |
+
|
221 |
+
def c_void_p(self, num):
|
222 |
+
return num
|
223 |
+
|
224 |
+
class _ctypes(object):
|
225 |
+
def __init__(self, array, ptr=None):
|
226 |
+
try:
|
227 |
+
import ctypes
|
228 |
+
self._ctypes = ctypes
|
229 |
+
except ImportError:
|
230 |
+
self._ctypes = _missing_ctypes()
|
231 |
+
self._arr = array
|
232 |
+
self._data = ptr
|
233 |
+
if self._arr.ndim == 0:
|
234 |
+
self._zerod = True
|
235 |
+
else:
|
236 |
+
self._zerod = False
|
237 |
+
|
238 |
+
def data_as(self, obj):
|
239 |
+
return self._ctypes.cast(self._data, obj)
|
240 |
+
|
241 |
+
def shape_as(self, obj):
|
242 |
+
if self._zerod:
|
243 |
+
return None
|
244 |
+
return (obj*self._arr.ndim)(*self._arr.shape)
|
245 |
+
|
246 |
+
def strides_as(self, obj):
|
247 |
+
if self._zerod:
|
248 |
+
return None
|
249 |
+
return (obj*self._arr.ndim)(*self._arr.strides)
|
250 |
+
|
251 |
+
def get_data(self):
|
252 |
+
return self._data
|
253 |
+
|
254 |
+
def get_shape(self):
|
255 |
+
if self._zerod:
|
256 |
+
return None
|
257 |
+
return (_getintp_ctype()*self._arr.ndim)(*self._arr.shape)
|
258 |
+
|
259 |
+
def get_strides(self):
|
260 |
+
if self._zerod:
|
261 |
+
return None
|
262 |
+
return (_getintp_ctype()*self._arr.ndim)(*self._arr.strides)
|
263 |
+
|
264 |
+
def get_as_parameter(self):
|
265 |
+
return self._ctypes.c_void_p(self._data)
|
266 |
+
|
267 |
+
data = property(get_data, None, doc="c-types data")
|
268 |
+
shape = property(get_shape, None, doc="c-types shape")
|
269 |
+
strides = property(get_strides, None, doc="c-types strides")
|
270 |
+
_as_parameter_ = property(get_as_parameter, None, doc="_as parameter_")
|
271 |
+
|
272 |
+
|
273 |
+
# Given a datatype and an order object
|
274 |
+
# return a new names tuple
|
275 |
+
# with the order indicated
|
276 |
+
def _newnames(datatype, order):
|
277 |
+
oldnames = datatype.names
|
278 |
+
nameslist = list(oldnames)
|
279 |
+
if isinstance(order, str):
|
280 |
+
order = [order]
|
281 |
+
if isinstance(order, (list, tuple)):
|
282 |
+
for name in order:
|
283 |
+
try:
|
284 |
+
nameslist.remove(name)
|
285 |
+
except ValueError:
|
286 |
+
raise ValueError("unknown field name: %s" % (name,))
|
287 |
+
return tuple(list(order) + nameslist)
|
288 |
+
raise ValueError("unsupported order value: %s" % (order,))
|
289 |
+
|
290 |
+
# Given an array with fields and a sequence of field names
|
291 |
+
# construct a new array with just those fields copied over
|
292 |
+
def _index_fields(ary, fields):
|
293 |
+
from .multiarray import empty, dtype, array
|
294 |
+
dt = ary.dtype
|
295 |
+
|
296 |
+
names = [name for name in fields if name in dt.names]
|
297 |
+
formats = [dt.fields[name][0] for name in fields if name in dt.names]
|
298 |
+
offsets = [dt.fields[name][1] for name in fields if name in dt.names]
|
299 |
+
|
300 |
+
view_dtype = {'names':names, 'formats':formats, 'offsets':offsets, 'itemsize':dt.itemsize}
|
301 |
+
view = ary.view(dtype=view_dtype)
|
302 |
+
|
303 |
+
# Return a copy for now until behavior is fully deprecated
|
304 |
+
# in favor of returning view
|
305 |
+
copy_dtype = {'names':view_dtype['names'], 'formats':view_dtype['formats']}
|
306 |
+
return array(view, dtype=copy_dtype, copy=True)
|
307 |
+
|
308 |
+
# Given a string containing a PEP 3118 format specifier,
|
309 |
+
# construct a Numpy dtype
|
310 |
+
|
311 |
+
_pep3118_native_map = {
|
312 |
+
'?': '?',
|
313 |
+
'b': 'b',
|
314 |
+
'B': 'B',
|
315 |
+
'h': 'h',
|
316 |
+
'H': 'H',
|
317 |
+
'i': 'i',
|
318 |
+
'I': 'I',
|
319 |
+
'l': 'l',
|
320 |
+
'L': 'L',
|
321 |
+
'q': 'q',
|
322 |
+
'Q': 'Q',
|
323 |
+
'e': 'e',
|
324 |
+
'f': 'f',
|
325 |
+
'd': 'd',
|
326 |
+
'g': 'g',
|
327 |
+
'Zf': 'F',
|
328 |
+
'Zd': 'D',
|
329 |
+
'Zg': 'G',
|
330 |
+
's': 'S',
|
331 |
+
'w': 'U',
|
332 |
+
'O': 'O',
|
333 |
+
'x': 'V', # padding
|
334 |
+
}
|
335 |
+
_pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
|
336 |
+
|
337 |
+
_pep3118_standard_map = {
|
338 |
+
'?': '?',
|
339 |
+
'b': 'b',
|
340 |
+
'B': 'B',
|
341 |
+
'h': 'i2',
|
342 |
+
'H': 'u2',
|
343 |
+
'i': 'i4',
|
344 |
+
'I': 'u4',
|
345 |
+
'l': 'i4',
|
346 |
+
'L': 'u4',
|
347 |
+
'q': 'i8',
|
348 |
+
'Q': 'u8',
|
349 |
+
'e': 'f2',
|
350 |
+
'f': 'f',
|
351 |
+
'd': 'd',
|
352 |
+
'Zf': 'F',
|
353 |
+
'Zd': 'D',
|
354 |
+
's': 'S',
|
355 |
+
'w': 'U',
|
356 |
+
'O': 'O',
|
357 |
+
'x': 'V', # padding
|
358 |
+
}
|
359 |
+
_pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
|
360 |
+
|
361 |
+
def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False):
|
362 |
+
from numpy.core.multiarray import dtype
|
363 |
+
|
364 |
+
fields = {}
|
365 |
+
offset = 0
|
366 |
+
explicit_name = False
|
367 |
+
this_explicit_name = False
|
368 |
+
common_alignment = 1
|
369 |
+
is_padding = False
|
370 |
+
last_offset = 0
|
371 |
+
|
372 |
+
dummy_name_index = [0]
|
373 |
+
def next_dummy_name():
|
374 |
+
dummy_name_index[0] += 1
|
375 |
+
def get_dummy_name():
|
376 |
+
while True:
|
377 |
+
name = 'f%d' % dummy_name_index[0]
|
378 |
+
if name not in fields:
|
379 |
+
return name
|
380 |
+
next_dummy_name()
|
381 |
+
|
382 |
+
# Parse spec
|
383 |
+
while spec:
|
384 |
+
value = None
|
385 |
+
|
386 |
+
# End of structure, bail out to upper level
|
387 |
+
if spec[0] == '}':
|
388 |
+
spec = spec[1:]
|
389 |
+
break
|
390 |
+
|
391 |
+
# Sub-arrays (1)
|
392 |
+
shape = None
|
393 |
+
if spec[0] == '(':
|
394 |
+
j = spec.index(')')
|
395 |
+
shape = tuple(map(int, spec[1:j].split(',')))
|
396 |
+
spec = spec[j+1:]
|
397 |
+
|
398 |
+
# Byte order
|
399 |
+
if spec[0] in ('@', '=', '<', '>', '^', '!'):
|
400 |
+
byteorder = spec[0]
|
401 |
+
if byteorder == '!':
|
402 |
+
byteorder = '>'
|
403 |
+
spec = spec[1:]
|
404 |
+
|
405 |
+
# Byte order characters also control native vs. standard type sizes
|
406 |
+
if byteorder in ('@', '^'):
|
407 |
+
type_map = _pep3118_native_map
|
408 |
+
type_map_chars = _pep3118_native_typechars
|
409 |
+
else:
|
410 |
+
type_map = _pep3118_standard_map
|
411 |
+
type_map_chars = _pep3118_standard_typechars
|
412 |
+
|
413 |
+
# Item sizes
|
414 |
+
itemsize = 1
|
415 |
+
if spec[0].isdigit():
|
416 |
+
j = 1
|
417 |
+
for j in range(1, len(spec)):
|
418 |
+
if not spec[j].isdigit():
|
419 |
+
break
|
420 |
+
itemsize = int(spec[:j])
|
421 |
+
spec = spec[j:]
|
422 |
+
|
423 |
+
# Data types
|
424 |
+
is_padding = False
|
425 |
+
|
426 |
+
if spec[:2] == 'T{':
|
427 |
+
value, spec, align, next_byteorder = _dtype_from_pep3118(
|
428 |
+
spec[2:], byteorder=byteorder, is_subdtype=True)
|
429 |
+
elif spec[0] in type_map_chars:
|
430 |
+
next_byteorder = byteorder
|
431 |
+
if spec[0] == 'Z':
|
432 |
+
j = 2
|
433 |
+
else:
|
434 |
+
j = 1
|
435 |
+
typechar = spec[:j]
|
436 |
+
spec = spec[j:]
|
437 |
+
is_padding = (typechar == 'x')
|
438 |
+
dtypechar = type_map[typechar]
|
439 |
+
if dtypechar in 'USV':
|
440 |
+
dtypechar += '%d' % itemsize
|
441 |
+
itemsize = 1
|
442 |
+
numpy_byteorder = {'@': '=', '^': '='}.get(byteorder, byteorder)
|
443 |
+
value = dtype(numpy_byteorder + dtypechar)
|
444 |
+
align = value.alignment
|
445 |
+
else:
|
446 |
+
raise ValueError("Unknown PEP 3118 data type specifier %r" % spec)
|
447 |
+
|
448 |
+
#
|
449 |
+
# Native alignment may require padding
|
450 |
+
#
|
451 |
+
# Here we assume that the presence of a '@' character implicitly implies
|
452 |
+
# that the start of the array is *already* aligned.
|
453 |
+
#
|
454 |
+
extra_offset = 0
|
455 |
+
if byteorder == '@':
|
456 |
+
start_padding = (-offset) % align
|
457 |
+
intra_padding = (-value.itemsize) % align
|
458 |
+
|
459 |
+
offset += start_padding
|
460 |
+
|
461 |
+
if intra_padding != 0:
|
462 |
+
if itemsize > 1 or (shape is not None and _prod(shape) > 1):
|
463 |
+
# Inject internal padding to the end of the sub-item
|
464 |
+
value = _add_trailing_padding(value, intra_padding)
|
465 |
+
else:
|
466 |
+
# We can postpone the injection of internal padding,
|
467 |
+
# as the item appears at most once
|
468 |
+
extra_offset += intra_padding
|
469 |
+
|
470 |
+
# Update common alignment
|
471 |
+
common_alignment = (align*common_alignment
|
472 |
+
/ _gcd(align, common_alignment))
|
473 |
+
|
474 |
+
# Convert itemsize to sub-array
|
475 |
+
if itemsize != 1:
|
476 |
+
value = dtype((value, (itemsize,)))
|
477 |
+
|
478 |
+
# Sub-arrays (2)
|
479 |
+
if shape is not None:
|
480 |
+
value = dtype((value, shape))
|
481 |
+
|
482 |
+
# Field name
|
483 |
+
this_explicit_name = False
|
484 |
+
if spec and spec.startswith(':'):
|
485 |
+
i = spec[1:].index(':') + 1
|
486 |
+
name = spec[1:i]
|
487 |
+
spec = spec[i+1:]
|
488 |
+
explicit_name = True
|
489 |
+
this_explicit_name = True
|
490 |
+
else:
|
491 |
+
name = get_dummy_name()
|
492 |
+
|
493 |
+
if not is_padding or this_explicit_name:
|
494 |
+
if name in fields:
|
495 |
+
raise RuntimeError("Duplicate field name '%s' in PEP3118 format"
|
496 |
+
% name)
|
497 |
+
fields[name] = (value, offset)
|
498 |
+
last_offset = offset
|
499 |
+
if not this_explicit_name:
|
500 |
+
next_dummy_name()
|
501 |
+
|
502 |
+
byteorder = next_byteorder
|
503 |
+
|
504 |
+
offset += value.itemsize
|
505 |
+
offset += extra_offset
|
506 |
+
|
507 |
+
# Check if this was a simple 1-item type
|
508 |
+
if len(fields) == 1 and not explicit_name and fields['f0'][1] == 0 \
|
509 |
+
and not is_subdtype:
|
510 |
+
ret = fields['f0'][0]
|
511 |
+
else:
|
512 |
+
ret = dtype(fields)
|
513 |
+
|
514 |
+
# Trailing padding must be explicitly added
|
515 |
+
padding = offset - ret.itemsize
|
516 |
+
if byteorder == '@':
|
517 |
+
padding += (-offset) % common_alignment
|
518 |
+
if is_padding and not this_explicit_name:
|
519 |
+
ret = _add_trailing_padding(ret, padding)
|
520 |
+
|
521 |
+
# Finished
|
522 |
+
if is_subdtype:
|
523 |
+
return ret, spec, common_alignment, byteorder
|
524 |
+
else:
|
525 |
+
return ret
|
526 |
+
|
527 |
+
def _add_trailing_padding(value, padding):
|
528 |
+
"""Inject the specified number of padding bytes at the end of a dtype"""
|
529 |
+
from numpy.core.multiarray import dtype
|
530 |
+
|
531 |
+
if value.fields is None:
|
532 |
+
vfields = {'f0': (value, 0)}
|
533 |
+
else:
|
534 |
+
vfields = dict(value.fields)
|
535 |
+
|
536 |
+
if value.names and value.names[-1] == '' and \
|
537 |
+
value[''].char == 'V':
|
538 |
+
# A trailing padding field is already present
|
539 |
+
vfields[''] = ('V%d' % (vfields[''][0].itemsize + padding),
|
540 |
+
vfields[''][1])
|
541 |
+
value = dtype(vfields)
|
542 |
+
else:
|
543 |
+
# Get a free name for the padding field
|
544 |
+
j = 0
|
545 |
+
while True:
|
546 |
+
name = 'pad%d' % j
|
547 |
+
if name not in vfields:
|
548 |
+
vfields[name] = ('V%d' % padding, value.itemsize)
|
549 |
+
break
|
550 |
+
j += 1
|
551 |
+
|
552 |
+
value = dtype(vfields)
|
553 |
+
if '' not in vfields:
|
554 |
+
# Strip out the name of the padding field
|
555 |
+
names = list(value.names)
|
556 |
+
names[-1] = ''
|
557 |
+
value.names = tuple(names)
|
558 |
+
return value
|
559 |
+
|
560 |
+
def _prod(a):
|
561 |
+
p = 1
|
562 |
+
for x in a:
|
563 |
+
p *= x
|
564 |
+
return p
|
565 |
+
|
566 |
+
def _gcd(a, b):
|
567 |
+
"""Calculate the greatest common divisor of a and b"""
|
568 |
+
while b:
|
569 |
+
a, b = b, a%b
|
570 |
+
return a
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/_methods.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Array methods which are called by both the C-code for the method
|
3 |
+
and the Python code for the NumPy-namespace function
|
4 |
+
|
5 |
+
"""
|
6 |
+
from __future__ import division, absolute_import, print_function
|
7 |
+
|
8 |
+
import warnings
|
9 |
+
|
10 |
+
from numpy.core import multiarray as mu
|
11 |
+
from numpy.core import umath as um
|
12 |
+
from numpy.core.numeric import asanyarray
|
13 |
+
from numpy.core import numerictypes as nt
|
14 |
+
|
15 |
+
# save those O(100) nanoseconds!
|
16 |
+
umr_maximum = um.maximum.reduce
|
17 |
+
umr_minimum = um.minimum.reduce
|
18 |
+
umr_sum = um.add.reduce
|
19 |
+
umr_prod = um.multiply.reduce
|
20 |
+
umr_any = um.logical_or.reduce
|
21 |
+
umr_all = um.logical_and.reduce
|
22 |
+
|
23 |
+
# avoid keyword arguments to speed up parsing, saves about 15%-20% for very
|
24 |
+
# small reductions
|
25 |
+
def _amax(a, axis=None, out=None, keepdims=False):
|
26 |
+
return umr_maximum(a, axis, None, out, keepdims)
|
27 |
+
|
28 |
+
def _amin(a, axis=None, out=None, keepdims=False):
|
29 |
+
return umr_minimum(a, axis, None, out, keepdims)
|
30 |
+
|
31 |
+
def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
|
32 |
+
return umr_sum(a, axis, dtype, out, keepdims)
|
33 |
+
|
34 |
+
def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
|
35 |
+
return umr_prod(a, axis, dtype, out, keepdims)
|
36 |
+
|
37 |
+
def _any(a, axis=None, dtype=None, out=None, keepdims=False):
|
38 |
+
return umr_any(a, axis, dtype, out, keepdims)
|
39 |
+
|
40 |
+
def _all(a, axis=None, dtype=None, out=None, keepdims=False):
|
41 |
+
return umr_all(a, axis, dtype, out, keepdims)
|
42 |
+
|
43 |
+
def _count_reduce_items(arr, axis):
|
44 |
+
if axis is None:
|
45 |
+
axis = tuple(range(arr.ndim))
|
46 |
+
if not isinstance(axis, tuple):
|
47 |
+
axis = (axis,)
|
48 |
+
items = 1
|
49 |
+
for ax in axis:
|
50 |
+
items *= arr.shape[ax]
|
51 |
+
return items
|
52 |
+
|
53 |
+
def _mean(a, axis=None, dtype=None, out=None, keepdims=False):
|
54 |
+
arr = asanyarray(a)
|
55 |
+
|
56 |
+
rcount = _count_reduce_items(arr, axis)
|
57 |
+
# Make this warning show up first
|
58 |
+
if rcount == 0:
|
59 |
+
warnings.warn("Mean of empty slice.", RuntimeWarning)
|
60 |
+
|
61 |
+
|
62 |
+
# Cast bool, unsigned int, and int to float64 by default
|
63 |
+
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
|
64 |
+
dtype = mu.dtype('f8')
|
65 |
+
|
66 |
+
ret = umr_sum(arr, axis, dtype, out, keepdims)
|
67 |
+
if isinstance(ret, mu.ndarray):
|
68 |
+
ret = um.true_divide(
|
69 |
+
ret, rcount, out=ret, casting='unsafe', subok=False)
|
70 |
+
elif hasattr(ret, 'dtype'):
|
71 |
+
ret = ret.dtype.type(ret / rcount)
|
72 |
+
else:
|
73 |
+
ret = ret / rcount
|
74 |
+
|
75 |
+
return ret
|
76 |
+
|
77 |
+
def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
|
78 |
+
arr = asanyarray(a)
|
79 |
+
|
80 |
+
rcount = _count_reduce_items(arr, axis)
|
81 |
+
# Make this warning show up on top.
|
82 |
+
if ddof >= rcount:
|
83 |
+
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
|
84 |
+
|
85 |
+
# Cast bool, unsigned int, and int to float64 by default
|
86 |
+
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
|
87 |
+
dtype = mu.dtype('f8')
|
88 |
+
|
89 |
+
# Compute the mean.
|
90 |
+
# Note that if dtype is not of inexact type then arraymean will
|
91 |
+
# not be either.
|
92 |
+
arrmean = umr_sum(arr, axis, dtype, keepdims=True)
|
93 |
+
if isinstance(arrmean, mu.ndarray):
|
94 |
+
arrmean = um.true_divide(
|
95 |
+
arrmean, rcount, out=arrmean, casting='unsafe', subok=False)
|
96 |
+
else:
|
97 |
+
arrmean = arrmean.dtype.type(arrmean / rcount)
|
98 |
+
|
99 |
+
# Compute sum of squared deviations from mean
|
100 |
+
# Note that x may not be inexact and that we need it to be an array,
|
101 |
+
# not a scalar.
|
102 |
+
x = asanyarray(arr - arrmean)
|
103 |
+
if issubclass(arr.dtype.type, nt.complexfloating):
|
104 |
+
x = um.multiply(x, um.conjugate(x), out=x).real
|
105 |
+
else:
|
106 |
+
x = um.multiply(x, x, out=x)
|
107 |
+
ret = umr_sum(x, axis, dtype, out, keepdims)
|
108 |
+
|
109 |
+
# Compute degrees of freedom and make sure it is not negative.
|
110 |
+
rcount = max([rcount - ddof, 0])
|
111 |
+
|
112 |
+
# divide by degrees of freedom
|
113 |
+
if isinstance(ret, mu.ndarray):
|
114 |
+
ret = um.true_divide(
|
115 |
+
ret, rcount, out=ret, casting='unsafe', subok=False)
|
116 |
+
elif hasattr(ret, 'dtype'):
|
117 |
+
ret = ret.dtype.type(ret / rcount)
|
118 |
+
else:
|
119 |
+
ret = ret / rcount
|
120 |
+
|
121 |
+
return ret
|
122 |
+
|
123 |
+
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
|
124 |
+
ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
|
125 |
+
keepdims=keepdims)
|
126 |
+
|
127 |
+
if isinstance(ret, mu.ndarray):
|
128 |
+
ret = um.sqrt(ret, out=ret)
|
129 |
+
elif hasattr(ret, 'dtype'):
|
130 |
+
ret = ret.dtype.type(um.sqrt(ret))
|
131 |
+
else:
|
132 |
+
ret = um.sqrt(ret)
|
133 |
+
|
134 |
+
return ret
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux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ing function
|
2 |
+
|
3 |
+
$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
|
4 |
+
|
5 |
+
"""
|
6 |
+
from __future__ import division, absolute_import, print_function
|
7 |
+
|
8 |
+
__all__ = ["array2string", "set_printoptions", "get_printoptions"]
|
9 |
+
__docformat__ = 'restructuredtext'
|
10 |
+
|
11 |
+
#
|
12 |
+
# Written by Konrad Hinsen <hinsenk@ere.umontreal.ca>
|
13 |
+
# last revision: 1996-3-13
|
14 |
+
# modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
|
15 |
+
# and by Perry Greenfield 2000-4-1 for numarray
|
16 |
+
# and by Travis Oliphant 2005-8-22 for numpy
|
17 |
+
|
18 |
+
import sys
|
19 |
+
from functools import reduce
|
20 |
+
from . import numerictypes as _nt
|
21 |
+
from .umath import maximum, minimum, absolute, not_equal, isnan, isinf
|
22 |
+
from .multiarray import format_longfloat, datetime_as_string, datetime_data
|
23 |
+
from .fromnumeric import ravel
|
24 |
+
|
25 |
+
if sys.version_info[0] >= 3:
|
26 |
+
_MAXINT = sys.maxsize
|
27 |
+
_MININT = -sys.maxsize - 1
|
28 |
+
else:
|
29 |
+
_MAXINT = sys.maxint
|
30 |
+
_MININT = -sys.maxint - 1
|
31 |
+
|
32 |
+
def product(x, y): return x*y
|
33 |
+
|
34 |
+
_summaryEdgeItems = 3 # repr N leading and trailing items of each dimension
|
35 |
+
_summaryThreshold = 1000 # total items > triggers array summarization
|
36 |
+
|
37 |
+
_float_output_precision = 8
|
38 |
+
_float_output_suppress_small = False
|
39 |
+
_line_width = 75
|
40 |
+
_nan_str = 'nan'
|
41 |
+
_inf_str = 'inf'
|
42 |
+
_formatter = None # formatting function for array elements
|
43 |
+
|
44 |
+
|
45 |
+
def set_printoptions(precision=None, threshold=None, edgeitems=None,
|
46 |
+
linewidth=None, suppress=None,
|
47 |
+
nanstr=None, infstr=None,
|
48 |
+
formatter=None):
|
49 |
+
"""
|
50 |
+
Set printing options.
|
51 |
+
|
52 |
+
These options determine the way floating point numbers, arrays and
|
53 |
+
other NumPy objects are displayed.
|
54 |
+
|
55 |
+
Parameters
|
56 |
+
----------
|
57 |
+
precision : int, optional
|
58 |
+
Number of digits of precision for floating point output (default 8).
|
59 |
+
threshold : int, optional
|
60 |
+
Total number of array elements which trigger summarization
|
61 |
+
rather than full repr (default 1000).
|
62 |
+
edgeitems : int, optional
|
63 |
+
Number of array items in summary at beginning and end of
|
64 |
+
each dimension (default 3).
|
65 |
+
linewidth : int, optional
|
66 |
+
The number of characters per line for the purpose of inserting
|
67 |
+
line breaks (default 75).
|
68 |
+
suppress : bool, optional
|
69 |
+
Whether or not suppress printing of small floating point values
|
70 |
+
using scientific notation (default False).
|
71 |
+
nanstr : str, optional
|
72 |
+
String representation of floating point not-a-number (default nan).
|
73 |
+
infstr : str, optional
|
74 |
+
String representation of floating point infinity (default inf).
|
75 |
+
formatter : dict of callables, optional
|
76 |
+
If not None, the keys should indicate the type(s) that the respective
|
77 |
+
formatting function applies to. Callables should return a string.
|
78 |
+
Types that are not specified (by their corresponding keys) are handled
|
79 |
+
by the default formatters. Individual types for which a formatter
|
80 |
+
can be set are::
|
81 |
+
|
82 |
+
- 'bool'
|
83 |
+
- 'int'
|
84 |
+
- 'timedelta' : a `numpy.timedelta64`
|
85 |
+
- 'datetime' : a `numpy.datetime64`
|
86 |
+
- 'float'
|
87 |
+
- 'longfloat' : 128-bit floats
|
88 |
+
- 'complexfloat'
|
89 |
+
- 'longcomplexfloat' : composed of two 128-bit floats
|
90 |
+
- 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
|
91 |
+
- 'str' : all other strings
|
92 |
+
|
93 |
+
Other keys that can be used to set a group of types at once are::
|
94 |
+
|
95 |
+
- 'all' : sets all types
|
96 |
+
- 'int_kind' : sets 'int'
|
97 |
+
- 'float_kind' : sets 'float' and 'longfloat'
|
98 |
+
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
|
99 |
+
- 'str_kind' : sets 'str' and 'numpystr'
|
100 |
+
|
101 |
+
See Also
|
102 |
+
--------
|
103 |
+
get_printoptions, set_string_function, array2string
|
104 |
+
|
105 |
+
Notes
|
106 |
+
-----
|
107 |
+
`formatter` is always reset with a call to `set_printoptions`.
|
108 |
+
|
109 |
+
Examples
|
110 |
+
--------
|
111 |
+
Floating point precision can be set:
|
112 |
+
|
113 |
+
>>> np.set_printoptions(precision=4)
|
114 |
+
>>> print np.array([1.123456789])
|
115 |
+
[ 1.1235]
|
116 |
+
|
117 |
+
Long arrays can be summarised:
|
118 |
+
|
119 |
+
>>> np.set_printoptions(threshold=5)
|
120 |
+
>>> print np.arange(10)
|
121 |
+
[0 1 2 ..., 7 8 9]
|
122 |
+
|
123 |
+
Small results can be suppressed:
|
124 |
+
|
125 |
+
>>> eps = np.finfo(float).eps
|
126 |
+
>>> x = np.arange(4.)
|
127 |
+
>>> x**2 - (x + eps)**2
|
128 |
+
array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
|
129 |
+
>>> np.set_printoptions(suppress=True)
|
130 |
+
>>> x**2 - (x + eps)**2
|
131 |
+
array([-0., -0., 0., 0.])
|
132 |
+
|
133 |
+
A custom formatter can be used to display array elements as desired:
|
134 |
+
|
135 |
+
>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
|
136 |
+
>>> x = np.arange(3)
|
137 |
+
>>> x
|
138 |
+
array([int: 0, int: -1, int: -2])
|
139 |
+
>>> np.set_printoptions() # formatter gets reset
|
140 |
+
>>> x
|
141 |
+
array([0, 1, 2])
|
142 |
+
|
143 |
+
To put back the default options, you can use:
|
144 |
+
|
145 |
+
>>> np.set_printoptions(edgeitems=3,infstr='inf',
|
146 |
+
... linewidth=75, nanstr='nan', precision=8,
|
147 |
+
... suppress=False, threshold=1000, formatter=None)
|
148 |
+
"""
|
149 |
+
|
150 |
+
global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \
|
151 |
+
_line_width, _float_output_suppress_small, _nan_str, _inf_str, \
|
152 |
+
_formatter
|
153 |
+
if linewidth is not None:
|
154 |
+
_line_width = linewidth
|
155 |
+
if threshold is not None:
|
156 |
+
_summaryThreshold = threshold
|
157 |
+
if edgeitems is not None:
|
158 |
+
_summaryEdgeItems = edgeitems
|
159 |
+
if precision is not None:
|
160 |
+
_float_output_precision = precision
|
161 |
+
if suppress is not None:
|
162 |
+
_float_output_suppress_small = not not suppress
|
163 |
+
if nanstr is not None:
|
164 |
+
_nan_str = nanstr
|
165 |
+
if infstr is not None:
|
166 |
+
_inf_str = infstr
|
167 |
+
_formatter = formatter
|
168 |
+
|
169 |
+
def get_printoptions():
|
170 |
+
"""
|
171 |
+
Return the current print options.
|
172 |
+
|
173 |
+
Returns
|
174 |
+
-------
|
175 |
+
print_opts : dict
|
176 |
+
Dictionary of current print options with keys
|
177 |
+
|
178 |
+
- precision : int
|
179 |
+
- threshold : int
|
180 |
+
- edgeitems : int
|
181 |
+
- linewidth : int
|
182 |
+
- suppress : bool
|
183 |
+
- nanstr : str
|
184 |
+
- infstr : str
|
185 |
+
- formatter : dict of callables
|
186 |
+
|
187 |
+
For a full description of these options, see `set_printoptions`.
|
188 |
+
|
189 |
+
See Also
|
190 |
+
--------
|
191 |
+
set_printoptions, set_string_function
|
192 |
+
|
193 |
+
"""
|
194 |
+
d = dict(precision=_float_output_precision,
|
195 |
+
threshold=_summaryThreshold,
|
196 |
+
edgeitems=_summaryEdgeItems,
|
197 |
+
linewidth=_line_width,
|
198 |
+
suppress=_float_output_suppress_small,
|
199 |
+
nanstr=_nan_str,
|
200 |
+
infstr=_inf_str,
|
201 |
+
formatter=_formatter)
|
202 |
+
return d
|
203 |
+
|
204 |
+
def _leading_trailing(a):
|
205 |
+
from . import numeric as _nc
|
206 |
+
if a.ndim == 1:
|
207 |
+
if len(a) > 2*_summaryEdgeItems:
|
208 |
+
b = _nc.concatenate((a[:_summaryEdgeItems],
|
209 |
+
a[-_summaryEdgeItems:]))
|
210 |
+
else:
|
211 |
+
b = a
|
212 |
+
else:
|
213 |
+
if len(a) > 2*_summaryEdgeItems:
|
214 |
+
l = [_leading_trailing(a[i]) for i in range(
|
215 |
+
min(len(a), _summaryEdgeItems))]
|
216 |
+
l.extend([_leading_trailing(a[-i]) for i in range(
|
217 |
+
min(len(a), _summaryEdgeItems), 0, -1)])
|
218 |
+
else:
|
219 |
+
l = [_leading_trailing(a[i]) for i in range(0, len(a))]
|
220 |
+
b = _nc.concatenate(tuple(l))
|
221 |
+
return b
|
222 |
+
|
223 |
+
def _boolFormatter(x):
|
224 |
+
if x:
|
225 |
+
return ' True'
|
226 |
+
else:
|
227 |
+
return 'False'
|
228 |
+
|
229 |
+
|
230 |
+
def repr_format(x):
|
231 |
+
return repr(x)
|
232 |
+
|
233 |
+
def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
|
234 |
+
prefix="", formatter=None):
|
235 |
+
|
236 |
+
if max_line_width is None:
|
237 |
+
max_line_width = _line_width
|
238 |
+
|
239 |
+
if precision is None:
|
240 |
+
precision = _float_output_precision
|
241 |
+
|
242 |
+
if suppress_small is None:
|
243 |
+
suppress_small = _float_output_suppress_small
|
244 |
+
|
245 |
+
if formatter is None:
|
246 |
+
formatter = _formatter
|
247 |
+
|
248 |
+
if a.size > _summaryThreshold:
|
249 |
+
summary_insert = "..., "
|
250 |
+
data = _leading_trailing(a)
|
251 |
+
else:
|
252 |
+
summary_insert = ""
|
253 |
+
data = ravel(a)
|
254 |
+
|
255 |
+
formatdict = {'bool' : _boolFormatter,
|
256 |
+
'int' : IntegerFormat(data),
|
257 |
+
'float' : FloatFormat(data, precision, suppress_small),
|
258 |
+
'longfloat' : LongFloatFormat(precision),
|
259 |
+
'complexfloat' : ComplexFormat(data, precision,
|
260 |
+
suppress_small),
|
261 |
+
'longcomplexfloat' : LongComplexFormat(precision),
|
262 |
+
'datetime' : DatetimeFormat(data),
|
263 |
+
'timedelta' : TimedeltaFormat(data),
|
264 |
+
'numpystr' : repr_format,
|
265 |
+
'str' : str}
|
266 |
+
|
267 |
+
if formatter is not None:
|
268 |
+
fkeys = [k for k in formatter.keys() if formatter[k] is not None]
|
269 |
+
if 'all' in fkeys:
|
270 |
+
for key in formatdict.keys():
|
271 |
+
formatdict[key] = formatter['all']
|
272 |
+
if 'int_kind' in fkeys:
|
273 |
+
for key in ['int']:
|
274 |
+
formatdict[key] = formatter['int_kind']
|
275 |
+
if 'float_kind' in fkeys:
|
276 |
+
for key in ['float', 'longfloat']:
|
277 |
+
formatdict[key] = formatter['float_kind']
|
278 |
+
if 'complex_kind' in fkeys:
|
279 |
+
for key in ['complexfloat', 'longcomplexfloat']:
|
280 |
+
formatdict[key] = formatter['complex_kind']
|
281 |
+
if 'str_kind' in fkeys:
|
282 |
+
for key in ['numpystr', 'str']:
|
283 |
+
formatdict[key] = formatter['str_kind']
|
284 |
+
for key in formatdict.keys():
|
285 |
+
if key in fkeys:
|
286 |
+
formatdict[key] = formatter[key]
|
287 |
+
|
288 |
+
try:
|
289 |
+
format_function = a._format
|
290 |
+
msg = "The `_format` attribute is deprecated in Numpy 2.0 and " \
|
291 |
+
"will be removed in 2.1. Use the `formatter` kw instead."
|
292 |
+
import warnings
|
293 |
+
warnings.warn(msg, DeprecationWarning)
|
294 |
+
except AttributeError:
|
295 |
+
# find the right formatting function for the array
|
296 |
+
dtypeobj = a.dtype.type
|
297 |
+
if issubclass(dtypeobj, _nt.bool_):
|
298 |
+
format_function = formatdict['bool']
|
299 |
+
elif issubclass(dtypeobj, _nt.integer):
|
300 |
+
if issubclass(dtypeobj, _nt.timedelta64):
|
301 |
+
format_function = formatdict['timedelta']
|
302 |
+
else:
|
303 |
+
format_function = formatdict['int']
|
304 |
+
elif issubclass(dtypeobj, _nt.floating):
|
305 |
+
if issubclass(dtypeobj, _nt.longfloat):
|
306 |
+
format_function = formatdict['longfloat']
|
307 |
+
else:
|
308 |
+
format_function = formatdict['float']
|
309 |
+
elif issubclass(dtypeobj, _nt.complexfloating):
|
310 |
+
if issubclass(dtypeobj, _nt.clongfloat):
|
311 |
+
format_function = formatdict['longcomplexfloat']
|
312 |
+
else:
|
313 |
+
format_function = formatdict['complexfloat']
|
314 |
+
elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)):
|
315 |
+
format_function = formatdict['numpystr']
|
316 |
+
elif issubclass(dtypeobj, _nt.datetime64):
|
317 |
+
format_function = formatdict['datetime']
|
318 |
+
else:
|
319 |
+
format_function = formatdict['numpystr']
|
320 |
+
|
321 |
+
# skip over "["
|
322 |
+
next_line_prefix = " "
|
323 |
+
# skip over array(
|
324 |
+
next_line_prefix += " "*len(prefix)
|
325 |
+
|
326 |
+
lst = _formatArray(a, format_function, len(a.shape), max_line_width,
|
327 |
+
next_line_prefix, separator,
|
328 |
+
_summaryEdgeItems, summary_insert)[:-1]
|
329 |
+
return lst
|
330 |
+
|
331 |
+
def _convert_arrays(obj):
|
332 |
+
from . import numeric as _nc
|
333 |
+
newtup = []
|
334 |
+
for k in obj:
|
335 |
+
if isinstance(k, _nc.ndarray):
|
336 |
+
k = k.tolist()
|
337 |
+
elif isinstance(k, tuple):
|
338 |
+
k = _convert_arrays(k)
|
339 |
+
newtup.append(k)
|
340 |
+
return tuple(newtup)
|
341 |
+
|
342 |
+
|
343 |
+
def array2string(a, max_line_width=None, precision=None,
|
344 |
+
suppress_small=None, separator=' ', prefix="",
|
345 |
+
style=repr, formatter=None):
|
346 |
+
"""
|
347 |
+
Return a string representation of an array.
|
348 |
+
|
349 |
+
Parameters
|
350 |
+
----------
|
351 |
+
a : ndarray
|
352 |
+
Input array.
|
353 |
+
max_line_width : int, optional
|
354 |
+
The maximum number of columns the string should span. Newline
|
355 |
+
characters splits the string appropriately after array elements.
|
356 |
+
precision : int, optional
|
357 |
+
Floating point precision. Default is the current printing
|
358 |
+
precision (usually 8), which can be altered using `set_printoptions`.
|
359 |
+
suppress_small : bool, optional
|
360 |
+
Represent very small numbers as zero. A number is "very small" if it
|
361 |
+
is smaller than the current printing precision.
|
362 |
+
separator : str, optional
|
363 |
+
Inserted between elements.
|
364 |
+
prefix : str, optional
|
365 |
+
An array is typically printed as::
|
366 |
+
|
367 |
+
'prefix(' + array2string(a) + ')'
|
368 |
+
|
369 |
+
The length of the prefix string is used to align the
|
370 |
+
output correctly.
|
371 |
+
style : function, optional
|
372 |
+
A function that accepts an ndarray and returns a string. Used only
|
373 |
+
when the shape of `a` is equal to ``()``, i.e. for 0-D arrays.
|
374 |
+
formatter : dict of callables, optional
|
375 |
+
If not None, the keys should indicate the type(s) that the respective
|
376 |
+
formatting function applies to. Callables should return a string.
|
377 |
+
Types that are not specified (by their corresponding keys) are handled
|
378 |
+
by the default formatters. Individual types for which a formatter
|
379 |
+
can be set are::
|
380 |
+
|
381 |
+
- 'bool'
|
382 |
+
- 'int'
|
383 |
+
- 'timedelta' : a `numpy.timedelta64`
|
384 |
+
- 'datetime' : a `numpy.datetime64`
|
385 |
+
- 'float'
|
386 |
+
- 'longfloat' : 128-bit floats
|
387 |
+
- 'complexfloat'
|
388 |
+
- 'longcomplexfloat' : composed of two 128-bit floats
|
389 |
+
- 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
|
390 |
+
- 'str' : all other strings
|
391 |
+
|
392 |
+
Other keys that can be used to set a group of types at once are::
|
393 |
+
|
394 |
+
- 'all' : sets all types
|
395 |
+
- 'int_kind' : sets 'int'
|
396 |
+
- 'float_kind' : sets 'float' and 'longfloat'
|
397 |
+
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
|
398 |
+
- 'str_kind' : sets 'str' and 'numpystr'
|
399 |
+
|
400 |
+
Returns
|
401 |
+
-------
|
402 |
+
array_str : str
|
403 |
+
String representation of the array.
|
404 |
+
|
405 |
+
Raises
|
406 |
+
------
|
407 |
+
TypeError
|
408 |
+
if a callable in `formatter` does not return a string.
|
409 |
+
|
410 |
+
See Also
|
411 |
+
--------
|
412 |
+
array_str, array_repr, set_printoptions, get_printoptions
|
413 |
+
|
414 |
+
Notes
|
415 |
+
-----
|
416 |
+
If a formatter is specified for a certain type, the `precision` keyword is
|
417 |
+
ignored for that type.
|
418 |
+
|
419 |
+
Examples
|
420 |
+
--------
|
421 |
+
>>> x = np.array([1e-16,1,2,3])
|
422 |
+
>>> print np.array2string(x, precision=2, separator=',',
|
423 |
+
... suppress_small=True)
|
424 |
+
[ 0., 1., 2., 3.]
|
425 |
+
|
426 |
+
>>> x = np.arange(3.)
|
427 |
+
>>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
|
428 |
+
'[0.00 1.00 2.00]'
|
429 |
+
|
430 |
+
>>> x = np.arange(3)
|
431 |
+
>>> np.array2string(x, formatter={'int':lambda x: hex(x)})
|
432 |
+
'[0x0L 0x1L 0x2L]'
|
433 |
+
|
434 |
+
"""
|
435 |
+
|
436 |
+
if a.shape == ():
|
437 |
+
x = a.item()
|
438 |
+
try:
|
439 |
+
lst = a._format(x)
|
440 |
+
msg = "The `_format` attribute is deprecated in Numpy " \
|
441 |
+
"2.0 and will be removed in 2.1. Use the " \
|
442 |
+
"`formatter` kw instead."
|
443 |
+
import warnings
|
444 |
+
warnings.warn(msg, DeprecationWarning)
|
445 |
+
except AttributeError:
|
446 |
+
if isinstance(x, tuple):
|
447 |
+
x = _convert_arrays(x)
|
448 |
+
lst = style(x)
|
449 |
+
elif reduce(product, a.shape) == 0:
|
450 |
+
# treat as a null array if any of shape elements == 0
|
451 |
+
lst = "[]"
|
452 |
+
else:
|
453 |
+
lst = _array2string(a, max_line_width, precision, suppress_small,
|
454 |
+
separator, prefix, formatter=formatter)
|
455 |
+
return lst
|
456 |
+
|
457 |
+
def _extendLine(s, line, word, max_line_len, next_line_prefix):
|
458 |
+
if len(line.rstrip()) + len(word.rstrip()) >= max_line_len:
|
459 |
+
s += line.rstrip() + "\n"
|
460 |
+
line = next_line_prefix
|
461 |
+
line += word
|
462 |
+
return s, line
|
463 |
+
|
464 |
+
|
465 |
+
def _formatArray(a, format_function, rank, max_line_len,
|
466 |
+
next_line_prefix, separator, edge_items, summary_insert):
|
467 |
+
"""formatArray is designed for two modes of operation:
|
468 |
+
|
469 |
+
1. Full output
|
470 |
+
|
471 |
+
2. Summarized output
|
472 |
+
|
473 |
+
"""
|
474 |
+
if rank == 0:
|
475 |
+
obj = a.item()
|
476 |
+
if isinstance(obj, tuple):
|
477 |
+
obj = _convert_arrays(obj)
|
478 |
+
return str(obj)
|
479 |
+
|
480 |
+
if summary_insert and 2*edge_items < len(a):
|
481 |
+
leading_items, trailing_items, summary_insert1 = \
|
482 |
+
edge_items, edge_items, summary_insert
|
483 |
+
else:
|
484 |
+
leading_items, trailing_items, summary_insert1 = 0, len(a), ""
|
485 |
+
|
486 |
+
if rank == 1:
|
487 |
+
s = ""
|
488 |
+
line = next_line_prefix
|
489 |
+
for i in range(leading_items):
|
490 |
+
word = format_function(a[i]) + separator
|
491 |
+
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
|
492 |
+
|
493 |
+
if summary_insert1:
|
494 |
+
s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix)
|
495 |
+
|
496 |
+
for i in range(trailing_items, 1, -1):
|
497 |
+
word = format_function(a[-i]) + separator
|
498 |
+
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
|
499 |
+
|
500 |
+
word = format_function(a[-1])
|
501 |
+
s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
|
502 |
+
s += line + "]\n"
|
503 |
+
s = '[' + s[len(next_line_prefix):]
|
504 |
+
else:
|
505 |
+
s = '['
|
506 |
+
sep = separator.rstrip()
|
507 |
+
for i in range(leading_items):
|
508 |
+
if i > 0:
|
509 |
+
s += next_line_prefix
|
510 |
+
s += _formatArray(a[i], format_function, rank-1, max_line_len,
|
511 |
+
" " + next_line_prefix, separator, edge_items,
|
512 |
+
summary_insert)
|
513 |
+
s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1)
|
514 |
+
|
515 |
+
if summary_insert1:
|
516 |
+
s += next_line_prefix + summary_insert1 + "\n"
|
517 |
+
|
518 |
+
for i in range(trailing_items, 1, -1):
|
519 |
+
if leading_items or i != trailing_items:
|
520 |
+
s += next_line_prefix
|
521 |
+
s += _formatArray(a[-i], format_function, rank-1, max_line_len,
|
522 |
+
" " + next_line_prefix, separator, edge_items,
|
523 |
+
summary_insert)
|
524 |
+
s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1)
|
525 |
+
if leading_items or trailing_items > 1:
|
526 |
+
s += next_line_prefix
|
527 |
+
s += _formatArray(a[-1], format_function, rank-1, max_line_len,
|
528 |
+
" " + next_line_prefix, separator, edge_items,
|
529 |
+
summary_insert).rstrip()+']\n'
|
530 |
+
return s
|
531 |
+
|
532 |
+
class FloatFormat(object):
|
533 |
+
def __init__(self, data, precision, suppress_small, sign=False):
|
534 |
+
self.precision = precision
|
535 |
+
self.suppress_small = suppress_small
|
536 |
+
self.sign = sign
|
537 |
+
self.exp_format = False
|
538 |
+
self.large_exponent = False
|
539 |
+
self.max_str_len = 0
|
540 |
+
try:
|
541 |
+
self.fillFormat(data)
|
542 |
+
except (TypeError, NotImplementedError):
|
543 |
+
# if reduce(data) fails, this instance will not be called, just
|
544 |
+
# instantiated in formatdict.
|
545 |
+
pass
|
546 |
+
|
547 |
+
def fillFormat(self, data):
|
548 |
+
from . import numeric as _nc
|
549 |
+
|
550 |
+
with _nc.errstate(all='ignore'):
|
551 |
+
special = isnan(data) | isinf(data)
|
552 |
+
valid = not_equal(data, 0) & ~special
|
553 |
+
non_zero = absolute(data.compress(valid))
|
554 |
+
if len(non_zero) == 0:
|
555 |
+
max_val = 0.
|
556 |
+
min_val = 0.
|
557 |
+
else:
|
558 |
+
max_val = maximum.reduce(non_zero)
|
559 |
+
min_val = minimum.reduce(non_zero)
|
560 |
+
if max_val >= 1.e8:
|
561 |
+
self.exp_format = True
|
562 |
+
if not self.suppress_small and (min_val < 0.0001
|
563 |
+
or max_val/min_val > 1000.):
|
564 |
+
self.exp_format = True
|
565 |
+
|
566 |
+
if self.exp_format:
|
567 |
+
self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100
|
568 |
+
self.max_str_len = 8 + self.precision
|
569 |
+
if self.large_exponent:
|
570 |
+
self.max_str_len += 1
|
571 |
+
if self.sign:
|
572 |
+
format = '%+'
|
573 |
+
else:
|
574 |
+
format = '%'
|
575 |
+
format = format + '%d.%de' % (self.max_str_len, self.precision)
|
576 |
+
else:
|
577 |
+
format = '%%.%df' % (self.precision,)
|
578 |
+
if len(non_zero):
|
579 |
+
precision = max([_digits(x, self.precision, format)
|
580 |
+
for x in non_zero])
|
581 |
+
else:
|
582 |
+
precision = 0
|
583 |
+
precision = min(self.precision, precision)
|
584 |
+
self.max_str_len = len(str(int(max_val))) + precision + 2
|
585 |
+
if _nc.any(special):
|
586 |
+
self.max_str_len = max(self.max_str_len,
|
587 |
+
len(_nan_str),
|
588 |
+
len(_inf_str)+1)
|
589 |
+
if self.sign:
|
590 |
+
format = '%#+'
|
591 |
+
else:
|
592 |
+
format = '%#'
|
593 |
+
format = format + '%d.%df' % (self.max_str_len, precision)
|
594 |
+
|
595 |
+
self.special_fmt = '%%%ds' % (self.max_str_len,)
|
596 |
+
self.format = format
|
597 |
+
|
598 |
+
def __call__(self, x, strip_zeros=True):
|
599 |
+
from . import numeric as _nc
|
600 |
+
|
601 |
+
with _nc.errstate(invalid='ignore'):
|
602 |
+
if isnan(x):
|
603 |
+
if self.sign:
|
604 |
+
return self.special_fmt % ('+' + _nan_str,)
|
605 |
+
else:
|
606 |
+
return self.special_fmt % (_nan_str,)
|
607 |
+
elif isinf(x):
|
608 |
+
if x > 0:
|
609 |
+
if self.sign:
|
610 |
+
return self.special_fmt % ('+' + _inf_str,)
|
611 |
+
else:
|
612 |
+
return self.special_fmt % (_inf_str,)
|
613 |
+
else:
|
614 |
+
return self.special_fmt % ('-' + _inf_str,)
|
615 |
+
|
616 |
+
s = self.format % x
|
617 |
+
if self.large_exponent:
|
618 |
+
# 3-digit exponent
|
619 |
+
expsign = s[-3]
|
620 |
+
if expsign == '+' or expsign == '-':
|
621 |
+
s = s[1:-2] + '0' + s[-2:]
|
622 |
+
elif self.exp_format:
|
623 |
+
# 2-digit exponent
|
624 |
+
if s[-3] == '0':
|
625 |
+
s = ' ' + s[:-3] + s[-2:]
|
626 |
+
elif strip_zeros:
|
627 |
+
z = s.rstrip('0')
|
628 |
+
s = z + ' '*(len(s)-len(z))
|
629 |
+
return s
|
630 |
+
|
631 |
+
|
632 |
+
def _digits(x, precision, format):
|
633 |
+
s = format % x
|
634 |
+
z = s.rstrip('0')
|
635 |
+
return precision - len(s) + len(z)
|
636 |
+
|
637 |
+
|
638 |
+
class IntegerFormat(object):
|
639 |
+
def __init__(self, data):
|
640 |
+
try:
|
641 |
+
max_str_len = max(len(str(maximum.reduce(data))),
|
642 |
+
len(str(minimum.reduce(data))))
|
643 |
+
self.format = '%' + str(max_str_len) + 'd'
|
644 |
+
except (TypeError, NotImplementedError):
|
645 |
+
# if reduce(data) fails, this instance will not be called, just
|
646 |
+
# instantiated in formatdict.
|
647 |
+
pass
|
648 |
+
except ValueError:
|
649 |
+
# this occurs when everything is NA
|
650 |
+
pass
|
651 |
+
|
652 |
+
def __call__(self, x):
|
653 |
+
if _MININT < x < _MAXINT:
|
654 |
+
return self.format % x
|
655 |
+
else:
|
656 |
+
return "%s" % x
|
657 |
+
|
658 |
+
class LongFloatFormat(object):
|
659 |
+
# XXX Have to add something to determine the width to use a la FloatFormat
|
660 |
+
# Right now, things won't line up properly
|
661 |
+
def __init__(self, precision, sign=False):
|
662 |
+
self.precision = precision
|
663 |
+
self.sign = sign
|
664 |
+
|
665 |
+
def __call__(self, x):
|
666 |
+
if isnan(x):
|
667 |
+
if self.sign:
|
668 |
+
return '+' + _nan_str
|
669 |
+
else:
|
670 |
+
return ' ' + _nan_str
|
671 |
+
elif isinf(x):
|
672 |
+
if x > 0:
|
673 |
+
if self.sign:
|
674 |
+
return '+' + _inf_str
|
675 |
+
else:
|
676 |
+
return ' ' + _inf_str
|
677 |
+
else:
|
678 |
+
return '-' + _inf_str
|
679 |
+
elif x >= 0:
|
680 |
+
if self.sign:
|
681 |
+
return '+' + format_longfloat(x, self.precision)
|
682 |
+
else:
|
683 |
+
return ' ' + format_longfloat(x, self.precision)
|
684 |
+
else:
|
685 |
+
return format_longfloat(x, self.precision)
|
686 |
+
|
687 |
+
|
688 |
+
class LongComplexFormat(object):
|
689 |
+
def __init__(self, precision):
|
690 |
+
self.real_format = LongFloatFormat(precision)
|
691 |
+
self.imag_format = LongFloatFormat(precision, sign=True)
|
692 |
+
|
693 |
+
def __call__(self, x):
|
694 |
+
r = self.real_format(x.real)
|
695 |
+
i = self.imag_format(x.imag)
|
696 |
+
return r + i + 'j'
|
697 |
+
|
698 |
+
|
699 |
+
class ComplexFormat(object):
|
700 |
+
def __init__(self, x, precision, suppress_small):
|
701 |
+
self.real_format = FloatFormat(x.real, precision, suppress_small)
|
702 |
+
self.imag_format = FloatFormat(x.imag, precision, suppress_small,
|
703 |
+
sign=True)
|
704 |
+
|
705 |
+
def __call__(self, x):
|
706 |
+
r = self.real_format(x.real, strip_zeros=False)
|
707 |
+
i = self.imag_format(x.imag, strip_zeros=False)
|
708 |
+
if not self.imag_format.exp_format:
|
709 |
+
z = i.rstrip('0')
|
710 |
+
i = z + 'j' + ' '*(len(i)-len(z))
|
711 |
+
else:
|
712 |
+
i = i + 'j'
|
713 |
+
return r + i
|
714 |
+
|
715 |
+
class DatetimeFormat(object):
|
716 |
+
def __init__(self, x, unit=None,
|
717 |
+
timezone=None, casting='same_kind'):
|
718 |
+
# Get the unit from the dtype
|
719 |
+
if unit is None:
|
720 |
+
if x.dtype.kind == 'M':
|
721 |
+
unit = datetime_data(x.dtype)[0]
|
722 |
+
else:
|
723 |
+
unit = 's'
|
724 |
+
|
725 |
+
# If timezone is default, make it 'local' or 'UTC' based on the unit
|
726 |
+
if timezone is None:
|
727 |
+
# Date units -> UTC, time units -> local
|
728 |
+
if unit in ('Y', 'M', 'W', 'D'):
|
729 |
+
self.timezone = 'UTC'
|
730 |
+
else:
|
731 |
+
self.timezone = 'local'
|
732 |
+
else:
|
733 |
+
self.timezone = timezone
|
734 |
+
self.unit = unit
|
735 |
+
self.casting = casting
|
736 |
+
|
737 |
+
def __call__(self, x):
|
738 |
+
return "'%s'" % datetime_as_string(x,
|
739 |
+
unit=self.unit,
|
740 |
+
timezone=self.timezone,
|
741 |
+
casting=self.casting)
|
742 |
+
|
743 |
+
class TimedeltaFormat(object):
|
744 |
+
def __init__(self, data):
|
745 |
+
if data.dtype.kind == 'm':
|
746 |
+
v = data.view('i8')
|
747 |
+
max_str_len = max(len(str(maximum.reduce(v))),
|
748 |
+
len(str(minimum.reduce(v))))
|
749 |
+
self.format = '%' + str(max_str_len) + 'd'
|
750 |
+
|
751 |
+
def __call__(self, x):
|
752 |
+
return self.format % x.astype('i8')
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/cversions.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 __future__ import division, absolute_import, print_function
|
7 |
+
|
8 |
+
from os.path import dirname
|
9 |
+
|
10 |
+
from code_generators.genapi import fullapi_hash
|
11 |
+
from code_generators.numpy_api import full_api
|
12 |
+
|
13 |
+
if __name__ == '__main__':
|
14 |
+
curdir = dirname(__file__)
|
15 |
+
print(fullapi_hash(full_api))
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/defchararray.py
ADDED
@@ -0,0 +1,2687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_`, `string_` or `unicode_`, 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 |
+
from __future__ import division, absolute_import, print_function
|
19 |
+
|
20 |
+
import sys
|
21 |
+
from .numerictypes import string_, unicode_, integer, object_, bool_, character
|
22 |
+
from .numeric import ndarray, compare_chararrays
|
23 |
+
from .numeric import array as narray
|
24 |
+
from numpy.core.multiarray import _vec_string
|
25 |
+
from numpy.compat import asbytes, long
|
26 |
+
import numpy
|
27 |
+
|
28 |
+
__all__ = ['chararray',
|
29 |
+
'equal', 'not_equal', 'greater_equal', 'less_equal', 'greater', 'less',
|
30 |
+
'str_len', 'add', 'multiply', 'mod', 'capitalize', 'center', 'count',
|
31 |
+
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format',
|
32 |
+
'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
|
33 |
+
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
|
34 |
+
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
|
35 |
+
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
|
36 |
+
'swapcase', 'title', 'translate', 'upper', 'zfill',
|
37 |
+
'isnumeric', 'isdecimal',
|
38 |
+
'array', 'asarray']
|
39 |
+
|
40 |
+
_globalvar = 0
|
41 |
+
if sys.version_info[0] >= 3:
|
42 |
+
_unicode = str
|
43 |
+
_bytes = bytes
|
44 |
+
else:
|
45 |
+
_unicode = unicode
|
46 |
+
_bytes = str
|
47 |
+
_len = len
|
48 |
+
|
49 |
+
def _use_unicode(*args):
|
50 |
+
"""
|
51 |
+
Helper function for determining the output type of some string
|
52 |
+
operations.
|
53 |
+
|
54 |
+
For an operation on two ndarrays, if at least one is unicode, the
|
55 |
+
result should be unicode.
|
56 |
+
"""
|
57 |
+
for x in args:
|
58 |
+
if (isinstance(x, _unicode)
|
59 |
+
or issubclass(numpy.asarray(x).dtype.type, unicode_)):
|
60 |
+
return unicode_
|
61 |
+
return string_
|
62 |
+
|
63 |
+
def _to_string_or_unicode_array(result):
|
64 |
+
"""
|
65 |
+
Helper function to cast a result back into a string or unicode array
|
66 |
+
if an object array must be used as an intermediary.
|
67 |
+
"""
|
68 |
+
return numpy.asarray(result.tolist())
|
69 |
+
|
70 |
+
def _clean_args(*args):
|
71 |
+
"""
|
72 |
+
Helper function for delegating arguments to Python string
|
73 |
+
functions.
|
74 |
+
|
75 |
+
Many of the Python string operations that have optional arguments
|
76 |
+
do not use 'None' to indicate a default value. In these cases,
|
77 |
+
we need to remove all `None` arguments, and those following them.
|
78 |
+
"""
|
79 |
+
newargs = []
|
80 |
+
for chk in args:
|
81 |
+
if chk is None:
|
82 |
+
break
|
83 |
+
newargs.append(chk)
|
84 |
+
return newargs
|
85 |
+
|
86 |
+
def _get_num_chars(a):
|
87 |
+
"""
|
88 |
+
Helper function that returns the number of characters per field in
|
89 |
+
a string or unicode array. This is to abstract out the fact that
|
90 |
+
for a unicode array this is itemsize / 4.
|
91 |
+
"""
|
92 |
+
if issubclass(a.dtype.type, unicode_):
|
93 |
+
return a.itemsize // 4
|
94 |
+
return a.itemsize
|
95 |
+
|
96 |
+
|
97 |
+
def equal(x1, x2):
|
98 |
+
"""
|
99 |
+
Return (x1 == x2) element-wise.
|
100 |
+
|
101 |
+
Unlike `numpy.equal`, this comparison is performed by first
|
102 |
+
stripping whitespace characters from the end of the string. This
|
103 |
+
behavior is provided for backward-compatibility with numarray.
|
104 |
+
|
105 |
+
Parameters
|
106 |
+
----------
|
107 |
+
x1, x2 : array_like of str or unicode
|
108 |
+
Input arrays of the same shape.
|
109 |
+
|
110 |
+
Returns
|
111 |
+
-------
|
112 |
+
out : {ndarray, bool}
|
113 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
114 |
+
|
115 |
+
See Also
|
116 |
+
--------
|
117 |
+
not_equal, greater_equal, less_equal, greater, less
|
118 |
+
"""
|
119 |
+
return compare_chararrays(x1, x2, '==', True)
|
120 |
+
|
121 |
+
def not_equal(x1, x2):
|
122 |
+
"""
|
123 |
+
Return (x1 != x2) element-wise.
|
124 |
+
|
125 |
+
Unlike `numpy.not_equal`, this comparison is performed by first
|
126 |
+
stripping whitespace characters from the end of the string. This
|
127 |
+
behavior is provided for backward-compatibility with numarray.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
x1, x2 : array_like of str or unicode
|
132 |
+
Input arrays of the same shape.
|
133 |
+
|
134 |
+
Returns
|
135 |
+
-------
|
136 |
+
out : {ndarray, bool}
|
137 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
138 |
+
|
139 |
+
See Also
|
140 |
+
--------
|
141 |
+
equal, greater_equal, less_equal, greater, less
|
142 |
+
"""
|
143 |
+
return compare_chararrays(x1, x2, '!=', True)
|
144 |
+
|
145 |
+
def greater_equal(x1, x2):
|
146 |
+
"""
|
147 |
+
Return (x1 >= x2) element-wise.
|
148 |
+
|
149 |
+
Unlike `numpy.greater_equal`, this comparison is performed by
|
150 |
+
first stripping whitespace characters from the end of the string.
|
151 |
+
This behavior is provided for backward-compatibility with
|
152 |
+
numarray.
|
153 |
+
|
154 |
+
Parameters
|
155 |
+
----------
|
156 |
+
x1, x2 : array_like of str or unicode
|
157 |
+
Input arrays of the same shape.
|
158 |
+
|
159 |
+
Returns
|
160 |
+
-------
|
161 |
+
out : {ndarray, bool}
|
162 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
163 |
+
|
164 |
+
See Also
|
165 |
+
--------
|
166 |
+
equal, not_equal, less_equal, greater, less
|
167 |
+
"""
|
168 |
+
return compare_chararrays(x1, x2, '>=', True)
|
169 |
+
|
170 |
+
def less_equal(x1, x2):
|
171 |
+
"""
|
172 |
+
Return (x1 <= x2) element-wise.
|
173 |
+
|
174 |
+
Unlike `numpy.less_equal`, this comparison is performed by first
|
175 |
+
stripping whitespace characters from the end of the string. This
|
176 |
+
behavior is provided for backward-compatibility with numarray.
|
177 |
+
|
178 |
+
Parameters
|
179 |
+
----------
|
180 |
+
x1, x2 : array_like of str or unicode
|
181 |
+
Input arrays of the same shape.
|
182 |
+
|
183 |
+
Returns
|
184 |
+
-------
|
185 |
+
out : {ndarray, bool}
|
186 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
187 |
+
|
188 |
+
See Also
|
189 |
+
--------
|
190 |
+
equal, not_equal, greater_equal, greater, less
|
191 |
+
"""
|
192 |
+
return compare_chararrays(x1, x2, '<=', True)
|
193 |
+
|
194 |
+
def greater(x1, x2):
|
195 |
+
"""
|
196 |
+
Return (x1 > x2) element-wise.
|
197 |
+
|
198 |
+
Unlike `numpy.greater`, this comparison is performed by first
|
199 |
+
stripping whitespace characters from the end of the string. This
|
200 |
+
behavior is provided for backward-compatibility with numarray.
|
201 |
+
|
202 |
+
Parameters
|
203 |
+
----------
|
204 |
+
x1, x2 : array_like of str or unicode
|
205 |
+
Input arrays of the same shape.
|
206 |
+
|
207 |
+
Returns
|
208 |
+
-------
|
209 |
+
out : {ndarray, bool}
|
210 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
211 |
+
|
212 |
+
See Also
|
213 |
+
--------
|
214 |
+
equal, not_equal, greater_equal, less_equal, less
|
215 |
+
"""
|
216 |
+
return compare_chararrays(x1, x2, '>', True)
|
217 |
+
|
218 |
+
def less(x1, x2):
|
219 |
+
"""
|
220 |
+
Return (x1 < x2) element-wise.
|
221 |
+
|
222 |
+
Unlike `numpy.greater`, this comparison is performed by first
|
223 |
+
stripping whitespace characters from the end of the string. This
|
224 |
+
behavior is provided for backward-compatibility with numarray.
|
225 |
+
|
226 |
+
Parameters
|
227 |
+
----------
|
228 |
+
x1, x2 : array_like of str or unicode
|
229 |
+
Input arrays of the same shape.
|
230 |
+
|
231 |
+
Returns
|
232 |
+
-------
|
233 |
+
out : {ndarray, bool}
|
234 |
+
Output array of bools, or a single bool if x1 and x2 are scalars.
|
235 |
+
|
236 |
+
See Also
|
237 |
+
--------
|
238 |
+
equal, not_equal, greater_equal, less_equal, greater
|
239 |
+
"""
|
240 |
+
return compare_chararrays(x1, x2, '<', True)
|
241 |
+
|
242 |
+
def str_len(a):
|
243 |
+
"""
|
244 |
+
Return len(a) element-wise.
|
245 |
+
|
246 |
+
Parameters
|
247 |
+
----------
|
248 |
+
a : array_like of str or unicode
|
249 |
+
|
250 |
+
Returns
|
251 |
+
-------
|
252 |
+
out : ndarray
|
253 |
+
Output array of integers
|
254 |
+
|
255 |
+
See also
|
256 |
+
--------
|
257 |
+
__builtin__.len
|
258 |
+
"""
|
259 |
+
return _vec_string(a, integer, '__len__')
|
260 |
+
|
261 |
+
def add(x1, x2):
|
262 |
+
"""
|
263 |
+
Return element-wise string concatenation for two arrays of str or unicode.
|
264 |
+
|
265 |
+
Arrays `x1` and `x2` must have the same shape.
|
266 |
+
|
267 |
+
Parameters
|
268 |
+
----------
|
269 |
+
x1 : array_like of str or unicode
|
270 |
+
Input array.
|
271 |
+
x2 : array_like of str or unicode
|
272 |
+
Input array.
|
273 |
+
|
274 |
+
Returns
|
275 |
+
-------
|
276 |
+
add : ndarray
|
277 |
+
Output array of `string_` or `unicode_`, depending on input types
|
278 |
+
of the same shape as `x1` and `x2`.
|
279 |
+
|
280 |
+
"""
|
281 |
+
arr1 = numpy.asarray(x1)
|
282 |
+
arr2 = numpy.asarray(x2)
|
283 |
+
out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
|
284 |
+
dtype = _use_unicode(arr1, arr2)
|
285 |
+
return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,))
|
286 |
+
|
287 |
+
def multiply(a, i):
|
288 |
+
"""
|
289 |
+
Return (a * i), that is string multiple concatenation,
|
290 |
+
element-wise.
|
291 |
+
|
292 |
+
Values in `i` of less than 0 are treated as 0 (which yields an
|
293 |
+
empty string).
|
294 |
+
|
295 |
+
Parameters
|
296 |
+
----------
|
297 |
+
a : array_like of str or unicode
|
298 |
+
|
299 |
+
i : array_like of ints
|
300 |
+
|
301 |
+
Returns
|
302 |
+
-------
|
303 |
+
out : ndarray
|
304 |
+
Output array of str or unicode, depending on input types
|
305 |
+
|
306 |
+
"""
|
307 |
+
a_arr = numpy.asarray(a)
|
308 |
+
i_arr = numpy.asarray(i)
|
309 |
+
if not issubclass(i_arr.dtype.type, integer):
|
310 |
+
raise ValueError("Can only multiply by integers")
|
311 |
+
out_size = _get_num_chars(a_arr) * max(long(i_arr.max()), 0)
|
312 |
+
return _vec_string(
|
313 |
+
a_arr, (a_arr.dtype.type, out_size), '__mul__', (i_arr,))
|
314 |
+
|
315 |
+
def mod(a, values):
|
316 |
+
"""
|
317 |
+
Return (a % i), that is pre-Python 2.6 string formatting
|
318 |
+
(iterpolation), element-wise for a pair of array_likes of str
|
319 |
+
or unicode.
|
320 |
+
|
321 |
+
Parameters
|
322 |
+
----------
|
323 |
+
a : array_like of str or unicode
|
324 |
+
|
325 |
+
values : array_like of values
|
326 |
+
These values will be element-wise interpolated into the string.
|
327 |
+
|
328 |
+
Returns
|
329 |
+
-------
|
330 |
+
out : ndarray
|
331 |
+
Output array of str or unicode, depending on input types
|
332 |
+
|
333 |
+
See also
|
334 |
+
--------
|
335 |
+
str.__mod__
|
336 |
+
|
337 |
+
"""
|
338 |
+
return _to_string_or_unicode_array(
|
339 |
+
_vec_string(a, object_, '__mod__', (values,)))
|
340 |
+
|
341 |
+
def capitalize(a):
|
342 |
+
"""
|
343 |
+
Return a copy of `a` with only the first character of each element
|
344 |
+
capitalized.
|
345 |
+
|
346 |
+
Calls `str.capitalize` element-wise.
|
347 |
+
|
348 |
+
For 8-bit strings, this method is locale-dependent.
|
349 |
+
|
350 |
+
Parameters
|
351 |
+
----------
|
352 |
+
a : array_like of str or unicode
|
353 |
+
Input array of strings to capitalize.
|
354 |
+
|
355 |
+
Returns
|
356 |
+
-------
|
357 |
+
out : ndarray
|
358 |
+
Output array of str or unicode, depending on input
|
359 |
+
types
|
360 |
+
|
361 |
+
See also
|
362 |
+
--------
|
363 |
+
str.capitalize
|
364 |
+
|
365 |
+
Examples
|
366 |
+
--------
|
367 |
+
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
|
368 |
+
array(['a1b2', '1b2a', 'b2a1', '2a1b'],
|
369 |
+
dtype='|S4')
|
370 |
+
>>> np.char.capitalize(c)
|
371 |
+
array(['A1b2', '1b2a', 'B2a1', '2a1b'],
|
372 |
+
dtype='|S4')
|
373 |
+
|
374 |
+
"""
|
375 |
+
a_arr = numpy.asarray(a)
|
376 |
+
return _vec_string(a_arr, a_arr.dtype, 'capitalize')
|
377 |
+
|
378 |
+
|
379 |
+
def center(a, width, fillchar=' '):
|
380 |
+
"""
|
381 |
+
Return a copy of `a` with its elements centered in a string of
|
382 |
+
length `width`.
|
383 |
+
|
384 |
+
Calls `str.center` element-wise.
|
385 |
+
|
386 |
+
Parameters
|
387 |
+
----------
|
388 |
+
a : array_like of str or unicode
|
389 |
+
|
390 |
+
width : int
|
391 |
+
The length of the resulting strings
|
392 |
+
fillchar : str or unicode, optional
|
393 |
+
The padding character to use (default is space).
|
394 |
+
|
395 |
+
Returns
|
396 |
+
-------
|
397 |
+
out : ndarray
|
398 |
+
Output array of str or unicode, depending on input
|
399 |
+
types
|
400 |
+
|
401 |
+
See also
|
402 |
+
--------
|
403 |
+
str.center
|
404 |
+
|
405 |
+
"""
|
406 |
+
a_arr = numpy.asarray(a)
|
407 |
+
width_arr = numpy.asarray(width)
|
408 |
+
size = long(numpy.max(width_arr.flat))
|
409 |
+
if numpy.issubdtype(a_arr.dtype, numpy.string_):
|
410 |
+
fillchar = asbytes(fillchar)
|
411 |
+
return _vec_string(
|
412 |
+
a_arr, (a_arr.dtype.type, size), 'center', (width_arr, fillchar))
|
413 |
+
|
414 |
+
|
415 |
+
def count(a, sub, start=0, end=None):
|
416 |
+
"""
|
417 |
+
Returns an array with the number of non-overlapping occurrences of
|
418 |
+
substring `sub` in the range [`start`, `end`].
|
419 |
+
|
420 |
+
Calls `str.count` element-wise.
|
421 |
+
|
422 |
+
Parameters
|
423 |
+
----------
|
424 |
+
a : array_like of str or unicode
|
425 |
+
|
426 |
+
sub : str or unicode
|
427 |
+
The substring to search for.
|
428 |
+
|
429 |
+
start, end : int, optional
|
430 |
+
Optional arguments `start` and `end` are interpreted as slice
|
431 |
+
notation to specify the range in which to count.
|
432 |
+
|
433 |
+
Returns
|
434 |
+
-------
|
435 |
+
out : ndarray
|
436 |
+
Output array of ints.
|
437 |
+
|
438 |
+
See also
|
439 |
+
--------
|
440 |
+
str.count
|
441 |
+
|
442 |
+
Examples
|
443 |
+
--------
|
444 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
445 |
+
>>> c
|
446 |
+
array(['aAaAaA', ' aA ', 'abBABba'],
|
447 |
+
dtype='|S7')
|
448 |
+
>>> np.char.count(c, 'A')
|
449 |
+
array([3, 1, 1])
|
450 |
+
>>> np.char.count(c, 'aA')
|
451 |
+
array([3, 1, 0])
|
452 |
+
>>> np.char.count(c, 'A', start=1, end=4)
|
453 |
+
array([2, 1, 1])
|
454 |
+
>>> np.char.count(c, 'A', start=1, end=3)
|
455 |
+
array([1, 0, 0])
|
456 |
+
|
457 |
+
"""
|
458 |
+
return _vec_string(a, integer, 'count', [sub, start] + _clean_args(end))
|
459 |
+
|
460 |
+
|
461 |
+
def decode(a, encoding=None, errors=None):
|
462 |
+
"""
|
463 |
+
Calls `str.decode` element-wise.
|
464 |
+
|
465 |
+
The set of available codecs comes from the Python standard library,
|
466 |
+
and may be extended at runtime. For more information, see the
|
467 |
+
:mod:`codecs` module.
|
468 |
+
|
469 |
+
Parameters
|
470 |
+
----------
|
471 |
+
a : array_like of str or unicode
|
472 |
+
|
473 |
+
encoding : str, optional
|
474 |
+
The name of an encoding
|
475 |
+
|
476 |
+
errors : str, optional
|
477 |
+
Specifies how to handle encoding errors
|
478 |
+
|
479 |
+
Returns
|
480 |
+
-------
|
481 |
+
out : ndarray
|
482 |
+
|
483 |
+
See also
|
484 |
+
--------
|
485 |
+
str.decode
|
486 |
+
|
487 |
+
Notes
|
488 |
+
-----
|
489 |
+
The type of the result will depend on the encoding specified.
|
490 |
+
|
491 |
+
Examples
|
492 |
+
--------
|
493 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
494 |
+
>>> c
|
495 |
+
array(['aAaAaA', ' aA ', 'abBABba'],
|
496 |
+
dtype='|S7')
|
497 |
+
>>> np.char.encode(c, encoding='cp037')
|
498 |
+
array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
|
499 |
+
'\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
|
500 |
+
dtype='|S7')
|
501 |
+
|
502 |
+
"""
|
503 |
+
return _to_string_or_unicode_array(
|
504 |
+
_vec_string(a, object_, 'decode', _clean_args(encoding, errors)))
|
505 |
+
|
506 |
+
|
507 |
+
def encode(a, encoding=None, errors=None):
|
508 |
+
"""
|
509 |
+
Calls `str.encode` element-wise.
|
510 |
+
|
511 |
+
The set of available codecs comes from the Python standard library,
|
512 |
+
and may be extended at runtime. For more information, see the codecs
|
513 |
+
module.
|
514 |
+
|
515 |
+
Parameters
|
516 |
+
----------
|
517 |
+
a : array_like of str or unicode
|
518 |
+
|
519 |
+
encoding : str, optional
|
520 |
+
The name of an encoding
|
521 |
+
|
522 |
+
errors : str, optional
|
523 |
+
Specifies how to handle encoding errors
|
524 |
+
|
525 |
+
Returns
|
526 |
+
-------
|
527 |
+
out : ndarray
|
528 |
+
|
529 |
+
See also
|
530 |
+
--------
|
531 |
+
str.encode
|
532 |
+
|
533 |
+
Notes
|
534 |
+
-----
|
535 |
+
The type of the result will depend on the encoding specified.
|
536 |
+
|
537 |
+
"""
|
538 |
+
return _to_string_or_unicode_array(
|
539 |
+
_vec_string(a, object_, 'encode', _clean_args(encoding, errors)))
|
540 |
+
|
541 |
+
|
542 |
+
def endswith(a, suffix, start=0, end=None):
|
543 |
+
"""
|
544 |
+
Returns a boolean array which is `True` where the string element
|
545 |
+
in `a` ends with `suffix`, otherwise `False`.
|
546 |
+
|
547 |
+
Calls `str.endswith` element-wise.
|
548 |
+
|
549 |
+
Parameters
|
550 |
+
----------
|
551 |
+
a : array_like of str or unicode
|
552 |
+
|
553 |
+
suffix : str
|
554 |
+
|
555 |
+
start, end : int, optional
|
556 |
+
With optional `start`, test beginning at that position. With
|
557 |
+
optional `end`, stop comparing at that position.
|
558 |
+
|
559 |
+
Returns
|
560 |
+
-------
|
561 |
+
out : ndarray
|
562 |
+
Outputs an array of bools.
|
563 |
+
|
564 |
+
See also
|
565 |
+
--------
|
566 |
+
str.endswith
|
567 |
+
|
568 |
+
Examples
|
569 |
+
--------
|
570 |
+
>>> s = np.array(['foo', 'bar'])
|
571 |
+
>>> s[0] = 'foo'
|
572 |
+
>>> s[1] = 'bar'
|
573 |
+
>>> s
|
574 |
+
array(['foo', 'bar'],
|
575 |
+
dtype='|S3')
|
576 |
+
>>> np.char.endswith(s, 'ar')
|
577 |
+
array([False, True], dtype=bool)
|
578 |
+
>>> np.char.endswith(s, 'a', start=1, end=2)
|
579 |
+
array([False, True], dtype=bool)
|
580 |
+
|
581 |
+
"""
|
582 |
+
return _vec_string(
|
583 |
+
a, bool_, 'endswith', [suffix, start] + _clean_args(end))
|
584 |
+
|
585 |
+
|
586 |
+
def expandtabs(a, tabsize=8):
|
587 |
+
"""
|
588 |
+
Return a copy of each string element where all tab characters are
|
589 |
+
replaced by one or more spaces.
|
590 |
+
|
591 |
+
Calls `str.expandtabs` element-wise.
|
592 |
+
|
593 |
+
Return a copy of each string element where all tab characters are
|
594 |
+
replaced by one or more spaces, depending on the current column
|
595 |
+
and the given `tabsize`. The column number is reset to zero after
|
596 |
+
each newline occurring in the string. This doesn't understand other
|
597 |
+
non-printing characters or escape sequences.
|
598 |
+
|
599 |
+
Parameters
|
600 |
+
----------
|
601 |
+
a : array_like of str or unicode
|
602 |
+
Input array
|
603 |
+
tabsize : int, optional
|
604 |
+
Replace tabs with `tabsize` number of spaces. If not given defaults
|
605 |
+
to 8 spaces.
|
606 |
+
|
607 |
+
Returns
|
608 |
+
-------
|
609 |
+
out : ndarray
|
610 |
+
Output array of str or unicode, depending on input type
|
611 |
+
|
612 |
+
See also
|
613 |
+
--------
|
614 |
+
str.expandtabs
|
615 |
+
|
616 |
+
"""
|
617 |
+
return _to_string_or_unicode_array(
|
618 |
+
_vec_string(a, object_, 'expandtabs', (tabsize,)))
|
619 |
+
|
620 |
+
|
621 |
+
def find(a, sub, start=0, end=None):
|
622 |
+
"""
|
623 |
+
For each element, return the lowest index in the string where
|
624 |
+
substring `sub` is found.
|
625 |
+
|
626 |
+
Calls `str.find` element-wise.
|
627 |
+
|
628 |
+
For each element, return the lowest index in the string where
|
629 |
+
substring `sub` is found, such that `sub` is contained in the
|
630 |
+
range [`start`, `end`].
|
631 |
+
|
632 |
+
Parameters
|
633 |
+
----------
|
634 |
+
a : array_like of str or unicode
|
635 |
+
|
636 |
+
sub : str or unicode
|
637 |
+
|
638 |
+
start, end : int, optional
|
639 |
+
Optional arguments `start` and `end` are interpreted as in
|
640 |
+
slice notation.
|
641 |
+
|
642 |
+
Returns
|
643 |
+
-------
|
644 |
+
out : ndarray or int
|
645 |
+
Output array of ints. Returns -1 if `sub` is not found.
|
646 |
+
|
647 |
+
See also
|
648 |
+
--------
|
649 |
+
str.find
|
650 |
+
|
651 |
+
"""
|
652 |
+
return _vec_string(
|
653 |
+
a, integer, 'find', [sub, start] + _clean_args(end))
|
654 |
+
|
655 |
+
|
656 |
+
def index(a, sub, start=0, end=None):
|
657 |
+
"""
|
658 |
+
Like `find`, but raises `ValueError` when the substring is not found.
|
659 |
+
|
660 |
+
Calls `str.index` element-wise.
|
661 |
+
|
662 |
+
Parameters
|
663 |
+
----------
|
664 |
+
a : array_like of str or unicode
|
665 |
+
|
666 |
+
sub : str or unicode
|
667 |
+
|
668 |
+
start, end : int, optional
|
669 |
+
|
670 |
+
Returns
|
671 |
+
-------
|
672 |
+
out : ndarray
|
673 |
+
Output array of ints. Returns -1 if `sub` is not found.
|
674 |
+
|
675 |
+
See also
|
676 |
+
--------
|
677 |
+
find, str.find
|
678 |
+
|
679 |
+
"""
|
680 |
+
return _vec_string(
|
681 |
+
a, integer, 'index', [sub, start] + _clean_args(end))
|
682 |
+
|
683 |
+
def isalnum(a):
|
684 |
+
"""
|
685 |
+
Returns true for each element if all characters in the string are
|
686 |
+
alphanumeric and there is at least one character, false otherwise.
|
687 |
+
|
688 |
+
Calls `str.isalnum` element-wise.
|
689 |
+
|
690 |
+
For 8-bit strings, this method is locale-dependent.
|
691 |
+
|
692 |
+
Parameters
|
693 |
+
----------
|
694 |
+
a : array_like of str or unicode
|
695 |
+
|
696 |
+
Returns
|
697 |
+
-------
|
698 |
+
out : ndarray
|
699 |
+
Output array of str or unicode, depending on input type
|
700 |
+
|
701 |
+
See also
|
702 |
+
--------
|
703 |
+
str.isalnum
|
704 |
+
"""
|
705 |
+
return _vec_string(a, bool_, 'isalnum')
|
706 |
+
|
707 |
+
def isalpha(a):
|
708 |
+
"""
|
709 |
+
Returns true for each element if all characters in the string are
|
710 |
+
alphabetic and there is at least one character, false otherwise.
|
711 |
+
|
712 |
+
Calls `str.isalpha` element-wise.
|
713 |
+
|
714 |
+
For 8-bit strings, this method is locale-dependent.
|
715 |
+
|
716 |
+
Parameters
|
717 |
+
----------
|
718 |
+
a : array_like of str or unicode
|
719 |
+
|
720 |
+
Returns
|
721 |
+
-------
|
722 |
+
out : ndarray
|
723 |
+
Output array of bools
|
724 |
+
|
725 |
+
See also
|
726 |
+
--------
|
727 |
+
str.isalpha
|
728 |
+
"""
|
729 |
+
return _vec_string(a, bool_, 'isalpha')
|
730 |
+
|
731 |
+
def isdigit(a):
|
732 |
+
"""
|
733 |
+
Returns true for each element if all characters in the string are
|
734 |
+
digits and there is at least one character, false otherwise.
|
735 |
+
|
736 |
+
Calls `str.isdigit` element-wise.
|
737 |
+
|
738 |
+
For 8-bit strings, this method is locale-dependent.
|
739 |
+
|
740 |
+
Parameters
|
741 |
+
----------
|
742 |
+
a : array_like of str or unicode
|
743 |
+
|
744 |
+
Returns
|
745 |
+
-------
|
746 |
+
out : ndarray
|
747 |
+
Output array of bools
|
748 |
+
|
749 |
+
See also
|
750 |
+
--------
|
751 |
+
str.isdigit
|
752 |
+
"""
|
753 |
+
return _vec_string(a, bool_, 'isdigit')
|
754 |
+
|
755 |
+
def islower(a):
|
756 |
+
"""
|
757 |
+
Returns true for each element if all cased characters in the
|
758 |
+
string are lowercase and there is at least one cased character,
|
759 |
+
false otherwise.
|
760 |
+
|
761 |
+
Calls `str.islower` element-wise.
|
762 |
+
|
763 |
+
For 8-bit strings, this method is locale-dependent.
|
764 |
+
|
765 |
+
Parameters
|
766 |
+
----------
|
767 |
+
a : array_like of str or unicode
|
768 |
+
|
769 |
+
Returns
|
770 |
+
-------
|
771 |
+
out : ndarray
|
772 |
+
Output array of bools
|
773 |
+
|
774 |
+
See also
|
775 |
+
--------
|
776 |
+
str.islower
|
777 |
+
"""
|
778 |
+
return _vec_string(a, bool_, 'islower')
|
779 |
+
|
780 |
+
def isspace(a):
|
781 |
+
"""
|
782 |
+
Returns true for each element if there are only whitespace
|
783 |
+
characters in the string and there is at least one character,
|
784 |
+
false otherwise.
|
785 |
+
|
786 |
+
Calls `str.isspace` element-wise.
|
787 |
+
|
788 |
+
For 8-bit strings, this method is locale-dependent.
|
789 |
+
|
790 |
+
Parameters
|
791 |
+
----------
|
792 |
+
a : array_like of str or unicode
|
793 |
+
|
794 |
+
Returns
|
795 |
+
-------
|
796 |
+
out : ndarray
|
797 |
+
Output array of bools
|
798 |
+
|
799 |
+
See also
|
800 |
+
--------
|
801 |
+
str.isspace
|
802 |
+
"""
|
803 |
+
return _vec_string(a, bool_, 'isspace')
|
804 |
+
|
805 |
+
def istitle(a):
|
806 |
+
"""
|
807 |
+
Returns true for each element if the element is a titlecased
|
808 |
+
string and there is at least one character, false otherwise.
|
809 |
+
|
810 |
+
Call `str.istitle` element-wise.
|
811 |
+
|
812 |
+
For 8-bit strings, this method is locale-dependent.
|
813 |
+
|
814 |
+
Parameters
|
815 |
+
----------
|
816 |
+
a : array_like of str or unicode
|
817 |
+
|
818 |
+
Returns
|
819 |
+
-------
|
820 |
+
out : ndarray
|
821 |
+
Output array of bools
|
822 |
+
|
823 |
+
See also
|
824 |
+
--------
|
825 |
+
str.istitle
|
826 |
+
"""
|
827 |
+
return _vec_string(a, bool_, 'istitle')
|
828 |
+
|
829 |
+
def isupper(a):
|
830 |
+
"""
|
831 |
+
Returns true for each element if all cased characters in the
|
832 |
+
string are uppercase and there is at least one character, false
|
833 |
+
otherwise.
|
834 |
+
|
835 |
+
Call `str.isupper` element-wise.
|
836 |
+
|
837 |
+
For 8-bit strings, this method is locale-dependent.
|
838 |
+
|
839 |
+
Parameters
|
840 |
+
----------
|
841 |
+
a : array_like of str or unicode
|
842 |
+
|
843 |
+
Returns
|
844 |
+
-------
|
845 |
+
out : ndarray
|
846 |
+
Output array of bools
|
847 |
+
|
848 |
+
See also
|
849 |
+
--------
|
850 |
+
str.isupper
|
851 |
+
"""
|
852 |
+
return _vec_string(a, bool_, 'isupper')
|
853 |
+
|
854 |
+
def join(sep, seq):
|
855 |
+
"""
|
856 |
+
Return a string which is the concatenation of the strings in the
|
857 |
+
sequence `seq`.
|
858 |
+
|
859 |
+
Calls `str.join` element-wise.
|
860 |
+
|
861 |
+
Parameters
|
862 |
+
----------
|
863 |
+
sep : array_like of str or unicode
|
864 |
+
seq : array_like of str or unicode
|
865 |
+
|
866 |
+
Returns
|
867 |
+
-------
|
868 |
+
out : ndarray
|
869 |
+
Output array of str or unicode, depending on input types
|
870 |
+
|
871 |
+
See also
|
872 |
+
--------
|
873 |
+
str.join
|
874 |
+
"""
|
875 |
+
return _to_string_or_unicode_array(
|
876 |
+
_vec_string(sep, object_, 'join', (seq,)))
|
877 |
+
|
878 |
+
|
879 |
+
def ljust(a, width, fillchar=' '):
|
880 |
+
"""
|
881 |
+
Return an array with the elements of `a` left-justified in a
|
882 |
+
string of length `width`.
|
883 |
+
|
884 |
+
Calls `str.ljust` element-wise.
|
885 |
+
|
886 |
+
Parameters
|
887 |
+
----------
|
888 |
+
a : array_like of str or unicode
|
889 |
+
|
890 |
+
width : int
|
891 |
+
The length of the resulting strings
|
892 |
+
fillchar : str or unicode, optional
|
893 |
+
The character to use for padding
|
894 |
+
|
895 |
+
Returns
|
896 |
+
-------
|
897 |
+
out : ndarray
|
898 |
+
Output array of str or unicode, depending on input type
|
899 |
+
|
900 |
+
See also
|
901 |
+
--------
|
902 |
+
str.ljust
|
903 |
+
|
904 |
+
"""
|
905 |
+
a_arr = numpy.asarray(a)
|
906 |
+
width_arr = numpy.asarray(width)
|
907 |
+
size = long(numpy.max(width_arr.flat))
|
908 |
+
if numpy.issubdtype(a_arr.dtype, numpy.string_):
|
909 |
+
fillchar = asbytes(fillchar)
|
910 |
+
return _vec_string(
|
911 |
+
a_arr, (a_arr.dtype.type, size), 'ljust', (width_arr, fillchar))
|
912 |
+
|
913 |
+
|
914 |
+
def lower(a):
|
915 |
+
"""
|
916 |
+
Return an array with the elements converted to lowercase.
|
917 |
+
|
918 |
+
Call `str.lower` element-wise.
|
919 |
+
|
920 |
+
For 8-bit strings, this method is locale-dependent.
|
921 |
+
|
922 |
+
Parameters
|
923 |
+
----------
|
924 |
+
a : array_like, {str, unicode}
|
925 |
+
Input array.
|
926 |
+
|
927 |
+
Returns
|
928 |
+
-------
|
929 |
+
out : ndarray, {str, unicode}
|
930 |
+
Output array of str or unicode, depending on input type
|
931 |
+
|
932 |
+
See also
|
933 |
+
--------
|
934 |
+
str.lower
|
935 |
+
|
936 |
+
Examples
|
937 |
+
--------
|
938 |
+
>>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
|
939 |
+
array(['A1B C', '1BCA', 'BCA1'],
|
940 |
+
dtype='|S5')
|
941 |
+
>>> np.char.lower(c)
|
942 |
+
array(['a1b c', '1bca', 'bca1'],
|
943 |
+
dtype='|S5')
|
944 |
+
|
945 |
+
"""
|
946 |
+
a_arr = numpy.asarray(a)
|
947 |
+
return _vec_string(a_arr, a_arr.dtype, 'lower')
|
948 |
+
|
949 |
+
|
950 |
+
def lstrip(a, chars=None):
|
951 |
+
"""
|
952 |
+
For each element in `a`, return a copy with the leading characters
|
953 |
+
removed.
|
954 |
+
|
955 |
+
Calls `str.lstrip` element-wise.
|
956 |
+
|
957 |
+
Parameters
|
958 |
+
----------
|
959 |
+
a : array-like, {str, unicode}
|
960 |
+
Input array.
|
961 |
+
|
962 |
+
chars : {str, unicode}, optional
|
963 |
+
The `chars` argument is a string specifying the set of
|
964 |
+
characters to be removed. If omitted or None, the `chars`
|
965 |
+
argument defaults to removing whitespace. The `chars` argument
|
966 |
+
is not a prefix; rather, all combinations of its values are
|
967 |
+
stripped.
|
968 |
+
|
969 |
+
Returns
|
970 |
+
-------
|
971 |
+
out : ndarray, {str, unicode}
|
972 |
+
Output array of str or unicode, depending on input type
|
973 |
+
|
974 |
+
See also
|
975 |
+
--------
|
976 |
+
str.lstrip
|
977 |
+
|
978 |
+
Examples
|
979 |
+
--------
|
980 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
981 |
+
>>> c
|
982 |
+
array(['aAaAaA', ' aA ', 'abBABba'],
|
983 |
+
dtype='|S7')
|
984 |
+
|
985 |
+
The 'a' variable is unstripped from c[1] because whitespace leading.
|
986 |
+
|
987 |
+
>>> np.char.lstrip(c, 'a')
|
988 |
+
array(['AaAaA', ' aA ', 'bBABba'],
|
989 |
+
dtype='|S7')
|
990 |
+
|
991 |
+
|
992 |
+
>>> np.char.lstrip(c, 'A') # leaves c unchanged
|
993 |
+
array(['aAaAaA', ' aA ', 'abBABba'],
|
994 |
+
dtype='|S7')
|
995 |
+
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
|
996 |
+
... # XXX: is this a regression? this line now returns False
|
997 |
+
... # np.char.lstrip(c,'') does not modify c at all.
|
998 |
+
True
|
999 |
+
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
|
1000 |
+
True
|
1001 |
+
|
1002 |
+
"""
|
1003 |
+
a_arr = numpy.asarray(a)
|
1004 |
+
return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
|
1005 |
+
|
1006 |
+
|
1007 |
+
def partition(a, sep):
|
1008 |
+
"""
|
1009 |
+
Partition each element in `a` around `sep`.
|
1010 |
+
|
1011 |
+
Calls `str.partition` element-wise.
|
1012 |
+
|
1013 |
+
For each element in `a`, split the element as the first
|
1014 |
+
occurrence of `sep`, and return 3 strings containing the part
|
1015 |
+
before the separator, the separator itself, and the part after
|
1016 |
+
the separator. If the separator is not found, return 3 strings
|
1017 |
+
containing the string itself, followed by two empty strings.
|
1018 |
+
|
1019 |
+
Parameters
|
1020 |
+
----------
|
1021 |
+
a : array_like, {str, unicode}
|
1022 |
+
Input array
|
1023 |
+
sep : {str, unicode}
|
1024 |
+
Separator to split each string element in `a`.
|
1025 |
+
|
1026 |
+
Returns
|
1027 |
+
-------
|
1028 |
+
out : ndarray, {str, unicode}
|
1029 |
+
Output array of str or unicode, depending on input type.
|
1030 |
+
The output array will have an extra dimension with 3
|
1031 |
+
elements per input element.
|
1032 |
+
|
1033 |
+
See also
|
1034 |
+
--------
|
1035 |
+
str.partition
|
1036 |
+
|
1037 |
+
"""
|
1038 |
+
return _to_string_or_unicode_array(
|
1039 |
+
_vec_string(a, object_, 'partition', (sep,)))
|
1040 |
+
|
1041 |
+
|
1042 |
+
def replace(a, old, new, count=None):
|
1043 |
+
"""
|
1044 |
+
For each element in `a`, return a copy of the string with all
|
1045 |
+
occurrences of substring `old` replaced by `new`.
|
1046 |
+
|
1047 |
+
Calls `str.replace` element-wise.
|
1048 |
+
|
1049 |
+
Parameters
|
1050 |
+
----------
|
1051 |
+
a : array-like of str or unicode
|
1052 |
+
|
1053 |
+
old, new : str or unicode
|
1054 |
+
|
1055 |
+
count : int, optional
|
1056 |
+
If the optional argument `count` is given, only the first
|
1057 |
+
`count` occurrences are replaced.
|
1058 |
+
|
1059 |
+
Returns
|
1060 |
+
-------
|
1061 |
+
out : ndarray
|
1062 |
+
Output array of str or unicode, depending on input type
|
1063 |
+
|
1064 |
+
See also
|
1065 |
+
--------
|
1066 |
+
str.replace
|
1067 |
+
|
1068 |
+
"""
|
1069 |
+
return _to_string_or_unicode_array(
|
1070 |
+
_vec_string(
|
1071 |
+
a, object_, 'replace', [old, new] +_clean_args(count)))
|
1072 |
+
|
1073 |
+
|
1074 |
+
def rfind(a, sub, start=0, end=None):
|
1075 |
+
"""
|
1076 |
+
For each element in `a`, return the highest index in the string
|
1077 |
+
where substring `sub` is found, such that `sub` is contained
|
1078 |
+
within [`start`, `end`].
|
1079 |
+
|
1080 |
+
Calls `str.rfind` element-wise.
|
1081 |
+
|
1082 |
+
Parameters
|
1083 |
+
----------
|
1084 |
+
a : array-like of str or unicode
|
1085 |
+
|
1086 |
+
sub : str or unicode
|
1087 |
+
|
1088 |
+
start, end : int, optional
|
1089 |
+
Optional arguments `start` and `end` are interpreted as in
|
1090 |
+
slice notation.
|
1091 |
+
|
1092 |
+
Returns
|
1093 |
+
-------
|
1094 |
+
out : ndarray
|
1095 |
+
Output array of ints. Return -1 on failure.
|
1096 |
+
|
1097 |
+
See also
|
1098 |
+
--------
|
1099 |
+
str.rfind
|
1100 |
+
|
1101 |
+
"""
|
1102 |
+
return _vec_string(
|
1103 |
+
a, integer, 'rfind', [sub, start] + _clean_args(end))
|
1104 |
+
|
1105 |
+
|
1106 |
+
def rindex(a, sub, start=0, end=None):
|
1107 |
+
"""
|
1108 |
+
Like `rfind`, but raises `ValueError` when the substring `sub` is
|
1109 |
+
not found.
|
1110 |
+
|
1111 |
+
Calls `str.rindex` element-wise.
|
1112 |
+
|
1113 |
+
Parameters
|
1114 |
+
----------
|
1115 |
+
a : array-like of str or unicode
|
1116 |
+
|
1117 |
+
sub : str or unicode
|
1118 |
+
|
1119 |
+
start, end : int, optional
|
1120 |
+
|
1121 |
+
Returns
|
1122 |
+
-------
|
1123 |
+
out : ndarray
|
1124 |
+
Output array of ints.
|
1125 |
+
|
1126 |
+
See also
|
1127 |
+
--------
|
1128 |
+
rfind, str.rindex
|
1129 |
+
|
1130 |
+
"""
|
1131 |
+
return _vec_string(
|
1132 |
+
a, integer, 'rindex', [sub, start] + _clean_args(end))
|
1133 |
+
|
1134 |
+
|
1135 |
+
def rjust(a, width, fillchar=' '):
|
1136 |
+
"""
|
1137 |
+
Return an array with the elements of `a` right-justified in a
|
1138 |
+
string of length `width`.
|
1139 |
+
|
1140 |
+
Calls `str.rjust` element-wise.
|
1141 |
+
|
1142 |
+
Parameters
|
1143 |
+
----------
|
1144 |
+
a : array_like of str or unicode
|
1145 |
+
|
1146 |
+
width : int
|
1147 |
+
The length of the resulting strings
|
1148 |
+
fillchar : str or unicode, optional
|
1149 |
+
The character to use for padding
|
1150 |
+
|
1151 |
+
Returns
|
1152 |
+
-------
|
1153 |
+
out : ndarray
|
1154 |
+
Output array of str or unicode, depending on input type
|
1155 |
+
|
1156 |
+
See also
|
1157 |
+
--------
|
1158 |
+
str.rjust
|
1159 |
+
|
1160 |
+
"""
|
1161 |
+
a_arr = numpy.asarray(a)
|
1162 |
+
width_arr = numpy.asarray(width)
|
1163 |
+
size = long(numpy.max(width_arr.flat))
|
1164 |
+
if numpy.issubdtype(a_arr.dtype, numpy.string_):
|
1165 |
+
fillchar = asbytes(fillchar)
|
1166 |
+
return _vec_string(
|
1167 |
+
a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar))
|
1168 |
+
|
1169 |
+
|
1170 |
+
def rpartition(a, sep):
|
1171 |
+
"""
|
1172 |
+
Partition (split) each element around the right-most separator.
|
1173 |
+
|
1174 |
+
Calls `str.rpartition` element-wise.
|
1175 |
+
|
1176 |
+
For each element in `a`, split the element as the last
|
1177 |
+
occurrence of `sep`, and return 3 strings containing the part
|
1178 |
+
before the separator, the separator itself, and the part after
|
1179 |
+
the separator. If the separator is not found, return 3 strings
|
1180 |
+
containing the string itself, followed by two empty strings.
|
1181 |
+
|
1182 |
+
Parameters
|
1183 |
+
----------
|
1184 |
+
a : array_like of str or unicode
|
1185 |
+
Input array
|
1186 |
+
sep : str or unicode
|
1187 |
+
Right-most separator to split each element in array.
|
1188 |
+
|
1189 |
+
Returns
|
1190 |
+
-------
|
1191 |
+
out : ndarray
|
1192 |
+
Output array of string or unicode, depending on input
|
1193 |
+
type. The output array will have an extra dimension with
|
1194 |
+
3 elements per input element.
|
1195 |
+
|
1196 |
+
See also
|
1197 |
+
--------
|
1198 |
+
str.rpartition
|
1199 |
+
|
1200 |
+
"""
|
1201 |
+
return _to_string_or_unicode_array(
|
1202 |
+
_vec_string(a, object_, 'rpartition', (sep,)))
|
1203 |
+
|
1204 |
+
|
1205 |
+
def rsplit(a, sep=None, maxsplit=None):
|
1206 |
+
"""
|
1207 |
+
For each element in `a`, return a list of the words in the
|
1208 |
+
string, using `sep` as the delimiter string.
|
1209 |
+
|
1210 |
+
Calls `str.rsplit` element-wise.
|
1211 |
+
|
1212 |
+
Except for splitting from the right, `rsplit`
|
1213 |
+
behaves like `split`.
|
1214 |
+
|
1215 |
+
Parameters
|
1216 |
+
----------
|
1217 |
+
a : array_like of str or unicode
|
1218 |
+
|
1219 |
+
sep : str or unicode, optional
|
1220 |
+
If `sep` is not specified or `None`, any whitespace string
|
1221 |
+
is a separator.
|
1222 |
+
maxsplit : int, optional
|
1223 |
+
If `maxsplit` is given, at most `maxsplit` splits are done,
|
1224 |
+
the rightmost ones.
|
1225 |
+
|
1226 |
+
Returns
|
1227 |
+
-------
|
1228 |
+
out : ndarray
|
1229 |
+
Array of list objects
|
1230 |
+
|
1231 |
+
See also
|
1232 |
+
--------
|
1233 |
+
str.rsplit, split
|
1234 |
+
|
1235 |
+
"""
|
1236 |
+
# This will return an array of lists of different sizes, so we
|
1237 |
+
# leave it as an object array
|
1238 |
+
return _vec_string(
|
1239 |
+
a, object_, 'rsplit', [sep] + _clean_args(maxsplit))
|
1240 |
+
|
1241 |
+
|
1242 |
+
def rstrip(a, chars=None):
|
1243 |
+
"""
|
1244 |
+
For each element in `a`, return a copy with the trailing
|
1245 |
+
characters removed.
|
1246 |
+
|
1247 |
+
Calls `str.rstrip` element-wise.
|
1248 |
+
|
1249 |
+
Parameters
|
1250 |
+
----------
|
1251 |
+
a : array-like of str or unicode
|
1252 |
+
|
1253 |
+
chars : str or unicode, optional
|
1254 |
+
The `chars` argument is a string specifying the set of
|
1255 |
+
characters to be removed. If omitted or None, the `chars`
|
1256 |
+
argument defaults to removing whitespace. The `chars` argument
|
1257 |
+
is not a suffix; rather, all combinations of its values are
|
1258 |
+
stripped.
|
1259 |
+
|
1260 |
+
Returns
|
1261 |
+
-------
|
1262 |
+
out : ndarray
|
1263 |
+
Output array of str or unicode, depending on input type
|
1264 |
+
|
1265 |
+
See also
|
1266 |
+
--------
|
1267 |
+
str.rstrip
|
1268 |
+
|
1269 |
+
Examples
|
1270 |
+
--------
|
1271 |
+
>>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
|
1272 |
+
array(['aAaAaA', 'abBABba'],
|
1273 |
+
dtype='|S7')
|
1274 |
+
>>> np.char.rstrip(c, 'a')
|
1275 |
+
array(['aAaAaA', 'abBABb'],
|
1276 |
+
dtype='|S7')
|
1277 |
+
>>> np.char.rstrip(c, 'A')
|
1278 |
+
array(['aAaAa', 'abBABba'],
|
1279 |
+
dtype='|S7')
|
1280 |
+
|
1281 |
+
"""
|
1282 |
+
a_arr = numpy.asarray(a)
|
1283 |
+
return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,))
|
1284 |
+
|
1285 |
+
|
1286 |
+
def split(a, sep=None, maxsplit=None):
|
1287 |
+
"""
|
1288 |
+
For each element in `a`, return a list of the words in the
|
1289 |
+
string, using `sep` as the delimiter string.
|
1290 |
+
|
1291 |
+
Calls `str.rsplit` element-wise.
|
1292 |
+
|
1293 |
+
Parameters
|
1294 |
+
----------
|
1295 |
+
a : array_like of str or unicode
|
1296 |
+
|
1297 |
+
sep : str or unicode, optional
|
1298 |
+
If `sep` is not specified or `None`, any whitespace string is a
|
1299 |
+
separator.
|
1300 |
+
|
1301 |
+
maxsplit : int, optional
|
1302 |
+
If `maxsplit` is given, at most `maxsplit` splits are done.
|
1303 |
+
|
1304 |
+
Returns
|
1305 |
+
-------
|
1306 |
+
out : ndarray
|
1307 |
+
Array of list objects
|
1308 |
+
|
1309 |
+
See also
|
1310 |
+
--------
|
1311 |
+
str.split, rsplit
|
1312 |
+
|
1313 |
+
"""
|
1314 |
+
# This will return an array of lists of different sizes, so we
|
1315 |
+
# leave it as an object array
|
1316 |
+
return _vec_string(
|
1317 |
+
a, object_, 'split', [sep] + _clean_args(maxsplit))
|
1318 |
+
|
1319 |
+
|
1320 |
+
def splitlines(a, keepends=None):
|
1321 |
+
"""
|
1322 |
+
For each element in `a`, return a list of the lines in the
|
1323 |
+
element, breaking at line boundaries.
|
1324 |
+
|
1325 |
+
Calls `str.splitlines` element-wise.
|
1326 |
+
|
1327 |
+
Parameters
|
1328 |
+
----------
|
1329 |
+
a : array_like of str or unicode
|
1330 |
+
|
1331 |
+
keepends : bool, optional
|
1332 |
+
Line breaks are not included in the resulting list unless
|
1333 |
+
keepends is given and true.
|
1334 |
+
|
1335 |
+
Returns
|
1336 |
+
-------
|
1337 |
+
out : ndarray
|
1338 |
+
Array of list objects
|
1339 |
+
|
1340 |
+
See also
|
1341 |
+
--------
|
1342 |
+
str.splitlines
|
1343 |
+
|
1344 |
+
"""
|
1345 |
+
return _vec_string(
|
1346 |
+
a, object_, 'splitlines', _clean_args(keepends))
|
1347 |
+
|
1348 |
+
|
1349 |
+
def startswith(a, prefix, start=0, end=None):
|
1350 |
+
"""
|
1351 |
+
Returns a boolean array which is `True` where the string element
|
1352 |
+
in `a` starts with `prefix`, otherwise `False`.
|
1353 |
+
|
1354 |
+
Calls `str.startswith` element-wise.
|
1355 |
+
|
1356 |
+
Parameters
|
1357 |
+
----------
|
1358 |
+
a : array_like of str or unicode
|
1359 |
+
|
1360 |
+
prefix : str
|
1361 |
+
|
1362 |
+
start, end : int, optional
|
1363 |
+
With optional `start`, test beginning at that position. With
|
1364 |
+
optional `end`, stop comparing at that position.
|
1365 |
+
|
1366 |
+
Returns
|
1367 |
+
-------
|
1368 |
+
out : ndarray
|
1369 |
+
Array of booleans
|
1370 |
+
|
1371 |
+
See also
|
1372 |
+
--------
|
1373 |
+
str.startswith
|
1374 |
+
|
1375 |
+
"""
|
1376 |
+
return _vec_string(
|
1377 |
+
a, bool_, 'startswith', [prefix, start] + _clean_args(end))
|
1378 |
+
|
1379 |
+
|
1380 |
+
def strip(a, chars=None):
|
1381 |
+
"""
|
1382 |
+
For each element in `a`, return a copy with the leading and
|
1383 |
+
trailing characters removed.
|
1384 |
+
|
1385 |
+
Calls `str.rstrip` element-wise.
|
1386 |
+
|
1387 |
+
Parameters
|
1388 |
+
----------
|
1389 |
+
a : array-like of str or unicode
|
1390 |
+
|
1391 |
+
chars : str or unicode, optional
|
1392 |
+
The `chars` argument is a string specifying the set of
|
1393 |
+
characters to be removed. If omitted or None, the `chars`
|
1394 |
+
argument defaults to removing whitespace. The `chars` argument
|
1395 |
+
is not a prefix or suffix; rather, all combinations of its
|
1396 |
+
values are stripped.
|
1397 |
+
|
1398 |
+
Returns
|
1399 |
+
-------
|
1400 |
+
out : ndarray
|
1401 |
+
Output array of str or unicode, depending on input type
|
1402 |
+
|
1403 |
+
See also
|
1404 |
+
--------
|
1405 |
+
str.strip
|
1406 |
+
|
1407 |
+
Examples
|
1408 |
+
--------
|
1409 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
1410 |
+
>>> c
|
1411 |
+
array(['aAaAaA', ' aA ', 'abBABba'],
|
1412 |
+
dtype='|S7')
|
1413 |
+
>>> np.char.strip(c)
|
1414 |
+
array(['aAaAaA', 'aA', 'abBABba'],
|
1415 |
+
dtype='|S7')
|
1416 |
+
>>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
|
1417 |
+
array(['AaAaA', ' aA ', 'bBABb'],
|
1418 |
+
dtype='|S7')
|
1419 |
+
>>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
|
1420 |
+
array(['aAaAa', ' aA ', 'abBABba'],
|
1421 |
+
dtype='|S7')
|
1422 |
+
|
1423 |
+
"""
|
1424 |
+
a_arr = numpy.asarray(a)
|
1425 |
+
return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
|
1426 |
+
|
1427 |
+
|
1428 |
+
def swapcase(a):
|
1429 |
+
"""
|
1430 |
+
Return element-wise a copy of the string with
|
1431 |
+
uppercase characters converted to lowercase and vice versa.
|
1432 |
+
|
1433 |
+
Calls `str.swapcase` element-wise.
|
1434 |
+
|
1435 |
+
For 8-bit strings, this method is locale-dependent.
|
1436 |
+
|
1437 |
+
Parameters
|
1438 |
+
----------
|
1439 |
+
a : array_like, {str, unicode}
|
1440 |
+
Input array.
|
1441 |
+
|
1442 |
+
Returns
|
1443 |
+
-------
|
1444 |
+
out : ndarray, {str, unicode}
|
1445 |
+
Output array of str or unicode, depending on input type
|
1446 |
+
|
1447 |
+
See also
|
1448 |
+
--------
|
1449 |
+
str.swapcase
|
1450 |
+
|
1451 |
+
Examples
|
1452 |
+
--------
|
1453 |
+
>>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
|
1454 |
+
array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
|
1455 |
+
dtype='|S5')
|
1456 |
+
>>> np.char.swapcase(c)
|
1457 |
+
array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
|
1458 |
+
dtype='|S5')
|
1459 |
+
|
1460 |
+
"""
|
1461 |
+
a_arr = numpy.asarray(a)
|
1462 |
+
return _vec_string(a_arr, a_arr.dtype, 'swapcase')
|
1463 |
+
|
1464 |
+
|
1465 |
+
def title(a):
|
1466 |
+
"""
|
1467 |
+
Return element-wise title cased version of string or unicode.
|
1468 |
+
|
1469 |
+
Title case words start with uppercase characters, all remaining cased
|
1470 |
+
characters are lowercase.
|
1471 |
+
|
1472 |
+
Calls `str.title` element-wise.
|
1473 |
+
|
1474 |
+
For 8-bit strings, this method is locale-dependent.
|
1475 |
+
|
1476 |
+
Parameters
|
1477 |
+
----------
|
1478 |
+
a : array_like, {str, unicode}
|
1479 |
+
Input array.
|
1480 |
+
|
1481 |
+
Returns
|
1482 |
+
-------
|
1483 |
+
out : ndarray
|
1484 |
+
Output array of str or unicode, depending on input type
|
1485 |
+
|
1486 |
+
See also
|
1487 |
+
--------
|
1488 |
+
str.title
|
1489 |
+
|
1490 |
+
Examples
|
1491 |
+
--------
|
1492 |
+
>>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
|
1493 |
+
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
|
1494 |
+
dtype='|S5')
|
1495 |
+
>>> np.char.title(c)
|
1496 |
+
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
|
1497 |
+
dtype='|S5')
|
1498 |
+
|
1499 |
+
"""
|
1500 |
+
a_arr = numpy.asarray(a)
|
1501 |
+
return _vec_string(a_arr, a_arr.dtype, 'title')
|
1502 |
+
|
1503 |
+
|
1504 |
+
def translate(a, table, deletechars=None):
|
1505 |
+
"""
|
1506 |
+
For each element in `a`, return a copy of the string where all
|
1507 |
+
characters occurring in the optional argument `deletechars` are
|
1508 |
+
removed, and the remaining characters have been mapped through the
|
1509 |
+
given translation table.
|
1510 |
+
|
1511 |
+
Calls `str.translate` element-wise.
|
1512 |
+
|
1513 |
+
Parameters
|
1514 |
+
----------
|
1515 |
+
a : array-like of str or unicode
|
1516 |
+
|
1517 |
+
table : str of length 256
|
1518 |
+
|
1519 |
+
deletechars : str
|
1520 |
+
|
1521 |
+
Returns
|
1522 |
+
-------
|
1523 |
+
out : ndarray
|
1524 |
+
Output array of str or unicode, depending on input type
|
1525 |
+
|
1526 |
+
See also
|
1527 |
+
--------
|
1528 |
+
str.translate
|
1529 |
+
|
1530 |
+
"""
|
1531 |
+
a_arr = numpy.asarray(a)
|
1532 |
+
if issubclass(a_arr.dtype.type, unicode_):
|
1533 |
+
return _vec_string(
|
1534 |
+
a_arr, a_arr.dtype, 'translate', (table,))
|
1535 |
+
else:
|
1536 |
+
return _vec_string(
|
1537 |
+
a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars))
|
1538 |
+
|
1539 |
+
|
1540 |
+
def upper(a):
|
1541 |
+
"""
|
1542 |
+
Return an array with the elements converted to uppercase.
|
1543 |
+
|
1544 |
+
Calls `str.upper` element-wise.
|
1545 |
+
|
1546 |
+
For 8-bit strings, this method is locale-dependent.
|
1547 |
+
|
1548 |
+
Parameters
|
1549 |
+
----------
|
1550 |
+
a : array_like, {str, unicode}
|
1551 |
+
Input array.
|
1552 |
+
|
1553 |
+
Returns
|
1554 |
+
-------
|
1555 |
+
out : ndarray, {str, unicode}
|
1556 |
+
Output array of str or unicode, depending on input type
|
1557 |
+
|
1558 |
+
See also
|
1559 |
+
--------
|
1560 |
+
str.upper
|
1561 |
+
|
1562 |
+
Examples
|
1563 |
+
--------
|
1564 |
+
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
|
1565 |
+
array(['a1b c', '1bca', 'bca1'],
|
1566 |
+
dtype='|S5')
|
1567 |
+
>>> np.char.upper(c)
|
1568 |
+
array(['A1B C', '1BCA', 'BCA1'],
|
1569 |
+
dtype='|S5')
|
1570 |
+
|
1571 |
+
"""
|
1572 |
+
a_arr = numpy.asarray(a)
|
1573 |
+
return _vec_string(a_arr, a_arr.dtype, 'upper')
|
1574 |
+
|
1575 |
+
|
1576 |
+
def zfill(a, width):
|
1577 |
+
"""
|
1578 |
+
Return the numeric string left-filled with zeros
|
1579 |
+
|
1580 |
+
Calls `str.zfill` element-wise.
|
1581 |
+
|
1582 |
+
Parameters
|
1583 |
+
----------
|
1584 |
+
a : array_like, {str, unicode}
|
1585 |
+
Input array.
|
1586 |
+
width : int
|
1587 |
+
Width of string to left-fill elements in `a`.
|
1588 |
+
|
1589 |
+
Returns
|
1590 |
+
-------
|
1591 |
+
out : ndarray, {str, unicode}
|
1592 |
+
Output array of str or unicode, depending on input type
|
1593 |
+
|
1594 |
+
See also
|
1595 |
+
--------
|
1596 |
+
str.zfill
|
1597 |
+
|
1598 |
+
"""
|
1599 |
+
a_arr = numpy.asarray(a)
|
1600 |
+
width_arr = numpy.asarray(width)
|
1601 |
+
size = long(numpy.max(width_arr.flat))
|
1602 |
+
return _vec_string(
|
1603 |
+
a_arr, (a_arr.dtype.type, size), 'zfill', (width_arr,))
|
1604 |
+
|
1605 |
+
|
1606 |
+
def isnumeric(a):
|
1607 |
+
"""
|
1608 |
+
For each element, return True if there are only numeric
|
1609 |
+
characters in the element.
|
1610 |
+
|
1611 |
+
Calls `unicode.isnumeric` element-wise.
|
1612 |
+
|
1613 |
+
Numeric characters include digit characters, and all characters
|
1614 |
+
that have the Unicode numeric value property, e.g. ``U+2155,
|
1615 |
+
VULGAR FRACTION ONE FIFTH``.
|
1616 |
+
|
1617 |
+
Parameters
|
1618 |
+
----------
|
1619 |
+
a : array_like, unicode
|
1620 |
+
Input array.
|
1621 |
+
|
1622 |
+
Returns
|
1623 |
+
-------
|
1624 |
+
out : ndarray, bool
|
1625 |
+
Array of booleans of same shape as `a`.
|
1626 |
+
|
1627 |
+
See also
|
1628 |
+
--------
|
1629 |
+
unicode.isnumeric
|
1630 |
+
|
1631 |
+
"""
|
1632 |
+
if _use_unicode(a) != unicode_:
|
1633 |
+
raise TypeError("isnumeric is only available for Unicode strings and arrays")
|
1634 |
+
return _vec_string(a, bool_, 'isnumeric')
|
1635 |
+
|
1636 |
+
|
1637 |
+
def isdecimal(a):
|
1638 |
+
"""
|
1639 |
+
For each element, return True if there are only decimal
|
1640 |
+
characters in the element.
|
1641 |
+
|
1642 |
+
Calls `unicode.isdecimal` element-wise.
|
1643 |
+
|
1644 |
+
Decimal characters include digit characters, and all characters
|
1645 |
+
that that can be used to form decimal-radix numbers,
|
1646 |
+
e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
|
1647 |
+
|
1648 |
+
Parameters
|
1649 |
+
----------
|
1650 |
+
a : array_like, unicode
|
1651 |
+
Input array.
|
1652 |
+
|
1653 |
+
Returns
|
1654 |
+
-------
|
1655 |
+
out : ndarray, bool
|
1656 |
+
Array of booleans identical in shape to `a`.
|
1657 |
+
|
1658 |
+
See also
|
1659 |
+
--------
|
1660 |
+
unicode.isdecimal
|
1661 |
+
|
1662 |
+
"""
|
1663 |
+
if _use_unicode(a) != unicode_:
|
1664 |
+
raise TypeError("isnumeric is only available for Unicode strings and arrays")
|
1665 |
+
return _vec_string(a, bool_, 'isdecimal')
|
1666 |
+
|
1667 |
+
|
1668 |
+
class chararray(ndarray):
|
1669 |
+
"""
|
1670 |
+
chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
|
1671 |
+
strides=None, order=None)
|
1672 |
+
|
1673 |
+
Provides a convenient view on arrays of string and unicode values.
|
1674 |
+
|
1675 |
+
.. note::
|
1676 |
+
The `chararray` class exists for backwards compatibility with
|
1677 |
+
Numarray, it is not recommended for new development. Starting from numpy
|
1678 |
+
1.4, if one needs arrays of strings, it is recommended to use arrays of
|
1679 |
+
`dtype` `object_`, `string_` or `unicode_`, and use the free functions
|
1680 |
+
in the `numpy.char` module for fast vectorized string operations.
|
1681 |
+
|
1682 |
+
Versus a regular Numpy array of type `str` or `unicode`, this
|
1683 |
+
class adds the following functionality:
|
1684 |
+
|
1685 |
+
1) values automatically have whitespace removed from the end
|
1686 |
+
when indexed
|
1687 |
+
|
1688 |
+
2) comparison operators automatically remove whitespace from the
|
1689 |
+
end when comparing values
|
1690 |
+
|
1691 |
+
3) vectorized string operations are provided as methods
|
1692 |
+
(e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
|
1693 |
+
|
1694 |
+
chararrays should be created using `numpy.char.array` or
|
1695 |
+
`numpy.char.asarray`, rather than this constructor directly.
|
1696 |
+
|
1697 |
+
This constructor creates the array, using `buffer` (with `offset`
|
1698 |
+
and `strides`) if it is not ``None``. If `buffer` is ``None``, then
|
1699 |
+
constructs a new array with `strides` in "C order", unless both
|
1700 |
+
``len(shape) >= 2`` and ``order='Fortran'``, in which case `strides`
|
1701 |
+
is in "Fortran order".
|
1702 |
+
|
1703 |
+
Methods
|
1704 |
+
-------
|
1705 |
+
astype
|
1706 |
+
argsort
|
1707 |
+
copy
|
1708 |
+
count
|
1709 |
+
decode
|
1710 |
+
dump
|
1711 |
+
dumps
|
1712 |
+
encode
|
1713 |
+
endswith
|
1714 |
+
expandtabs
|
1715 |
+
fill
|
1716 |
+
find
|
1717 |
+
flatten
|
1718 |
+
getfield
|
1719 |
+
index
|
1720 |
+
isalnum
|
1721 |
+
isalpha
|
1722 |
+
isdecimal
|
1723 |
+
isdigit
|
1724 |
+
islower
|
1725 |
+
isnumeric
|
1726 |
+
isspace
|
1727 |
+
istitle
|
1728 |
+
isupper
|
1729 |
+
item
|
1730 |
+
join
|
1731 |
+
ljust
|
1732 |
+
lower
|
1733 |
+
lstrip
|
1734 |
+
nonzero
|
1735 |
+
put
|
1736 |
+
ravel
|
1737 |
+
repeat
|
1738 |
+
replace
|
1739 |
+
reshape
|
1740 |
+
resize
|
1741 |
+
rfind
|
1742 |
+
rindex
|
1743 |
+
rjust
|
1744 |
+
rsplit
|
1745 |
+
rstrip
|
1746 |
+
searchsorted
|
1747 |
+
setfield
|
1748 |
+
setflags
|
1749 |
+
sort
|
1750 |
+
split
|
1751 |
+
splitlines
|
1752 |
+
squeeze
|
1753 |
+
startswith
|
1754 |
+
strip
|
1755 |
+
swapaxes
|
1756 |
+
swapcase
|
1757 |
+
take
|
1758 |
+
title
|
1759 |
+
tofile
|
1760 |
+
tolist
|
1761 |
+
tostring
|
1762 |
+
translate
|
1763 |
+
transpose
|
1764 |
+
upper
|
1765 |
+
view
|
1766 |
+
zfill
|
1767 |
+
|
1768 |
+
Parameters
|
1769 |
+
----------
|
1770 |
+
shape : tuple
|
1771 |
+
Shape of the array.
|
1772 |
+
itemsize : int, optional
|
1773 |
+
Length of each array element, in number of characters. Default is 1.
|
1774 |
+
unicode : bool, optional
|
1775 |
+
Are the array elements of type unicode (True) or string (False).
|
1776 |
+
Default is False.
|
1777 |
+
buffer : int, optional
|
1778 |
+
Memory address of the start of the array data. Default is None,
|
1779 |
+
in which case a new array is created.
|
1780 |
+
offset : int, optional
|
1781 |
+
Fixed stride displacement from the beginning of an axis?
|
1782 |
+
Default is 0. Needs to be >=0.
|
1783 |
+
strides : array_like of ints, optional
|
1784 |
+
Strides for the array (see `ndarray.strides` for full description).
|
1785 |
+
Default is None.
|
1786 |
+
order : {'C', 'F'}, optional
|
1787 |
+
The order in which the array data is stored in memory: 'C' ->
|
1788 |
+
"row major" order (the default), 'F' -> "column major"
|
1789 |
+
(Fortran) order.
|
1790 |
+
|
1791 |
+
Examples
|
1792 |
+
--------
|
1793 |
+
>>> charar = np.chararray((3, 3))
|
1794 |
+
>>> charar[:] = 'a'
|
1795 |
+
>>> charar
|
1796 |
+
chararray([['a', 'a', 'a'],
|
1797 |
+
['a', 'a', 'a'],
|
1798 |
+
['a', 'a', 'a']],
|
1799 |
+
dtype='|S1')
|
1800 |
+
|
1801 |
+
>>> charar = np.chararray(charar.shape, itemsize=5)
|
1802 |
+
>>> charar[:] = 'abc'
|
1803 |
+
>>> charar
|
1804 |
+
chararray([['abc', 'abc', 'abc'],
|
1805 |
+
['abc', 'abc', 'abc'],
|
1806 |
+
['abc', 'abc', 'abc']],
|
1807 |
+
dtype='|S5')
|
1808 |
+
|
1809 |
+
"""
|
1810 |
+
def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
|
1811 |
+
offset=0, strides=None, order='C'):
|
1812 |
+
global _globalvar
|
1813 |
+
|
1814 |
+
if unicode:
|
1815 |
+
dtype = unicode_
|
1816 |
+
else:
|
1817 |
+
dtype = string_
|
1818 |
+
|
1819 |
+
# force itemsize to be a Python long, since using Numpy integer
|
1820 |
+
# types results in itemsize.itemsize being used as the size of
|
1821 |
+
# strings in the new array.
|
1822 |
+
itemsize = long(itemsize)
|
1823 |
+
|
1824 |
+
if sys.version_info[0] >= 3 and isinstance(buffer, _unicode):
|
1825 |
+
# On Py3, unicode objects do not have the buffer interface
|
1826 |
+
filler = buffer
|
1827 |
+
buffer = None
|
1828 |
+
else:
|
1829 |
+
filler = None
|
1830 |
+
|
1831 |
+
_globalvar = 1
|
1832 |
+
if buffer is None:
|
1833 |
+
self = ndarray.__new__(subtype, shape, (dtype, itemsize),
|
1834 |
+
order=order)
|
1835 |
+
else:
|
1836 |
+
self = ndarray.__new__(subtype, shape, (dtype, itemsize),
|
1837 |
+
buffer=buffer,
|
1838 |
+
offset=offset, strides=strides,
|
1839 |
+
order=order)
|
1840 |
+
if filler is not None:
|
1841 |
+
self[...] = filler
|
1842 |
+
_globalvar = 0
|
1843 |
+
return self
|
1844 |
+
|
1845 |
+
def __array_finalize__(self, obj):
|
1846 |
+
# The b is a special case because it is used for reconstructing.
|
1847 |
+
if not _globalvar and self.dtype.char not in 'SUbc':
|
1848 |
+
raise ValueError("Can only create a chararray from string data.")
|
1849 |
+
|
1850 |
+
def __getitem__(self, obj):
|
1851 |
+
val = ndarray.__getitem__(self, obj)
|
1852 |
+
if issubclass(val.dtype.type, character) and not _len(val) == 0:
|
1853 |
+
temp = val.rstrip()
|
1854 |
+
if _len(temp) == 0:
|
1855 |
+
val = ''
|
1856 |
+
else:
|
1857 |
+
val = temp
|
1858 |
+
return val
|
1859 |
+
|
1860 |
+
# IMPLEMENTATION NOTE: Most of the methods of this class are
|
1861 |
+
# direct delegations to the free functions in this module.
|
1862 |
+
# However, those that return an array of strings should instead
|
1863 |
+
# return a chararray, so some extra wrapping is required.
|
1864 |
+
|
1865 |
+
def __eq__(self, other):
|
1866 |
+
"""
|
1867 |
+
Return (self == other) element-wise.
|
1868 |
+
|
1869 |
+
See also
|
1870 |
+
--------
|
1871 |
+
equal
|
1872 |
+
"""
|
1873 |
+
return equal(self, other)
|
1874 |
+
|
1875 |
+
def __ne__(self, other):
|
1876 |
+
"""
|
1877 |
+
Return (self != other) element-wise.
|
1878 |
+
|
1879 |
+
See also
|
1880 |
+
--------
|
1881 |
+
not_equal
|
1882 |
+
"""
|
1883 |
+
return not_equal(self, other)
|
1884 |
+
|
1885 |
+
def __ge__(self, other):
|
1886 |
+
"""
|
1887 |
+
Return (self >= other) element-wise.
|
1888 |
+
|
1889 |
+
See also
|
1890 |
+
--------
|
1891 |
+
greater_equal
|
1892 |
+
"""
|
1893 |
+
return greater_equal(self, other)
|
1894 |
+
|
1895 |
+
def __le__(self, other):
|
1896 |
+
"""
|
1897 |
+
Return (self <= other) element-wise.
|
1898 |
+
|
1899 |
+
See also
|
1900 |
+
--------
|
1901 |
+
less_equal
|
1902 |
+
"""
|
1903 |
+
return less_equal(self, other)
|
1904 |
+
|
1905 |
+
def __gt__(self, other):
|
1906 |
+
"""
|
1907 |
+
Return (self > other) element-wise.
|
1908 |
+
|
1909 |
+
See also
|
1910 |
+
--------
|
1911 |
+
greater
|
1912 |
+
"""
|
1913 |
+
return greater(self, other)
|
1914 |
+
|
1915 |
+
def __lt__(self, other):
|
1916 |
+
"""
|
1917 |
+
Return (self < other) element-wise.
|
1918 |
+
|
1919 |
+
See also
|
1920 |
+
--------
|
1921 |
+
less
|
1922 |
+
"""
|
1923 |
+
return less(self, other)
|
1924 |
+
|
1925 |
+
def __add__(self, other):
|
1926 |
+
"""
|
1927 |
+
Return (self + other), that is string concatenation,
|
1928 |
+
element-wise for a pair of array_likes of str or unicode.
|
1929 |
+
|
1930 |
+
See also
|
1931 |
+
--------
|
1932 |
+
add
|
1933 |
+
"""
|
1934 |
+
return asarray(add(self, other))
|
1935 |
+
|
1936 |
+
def __radd__(self, other):
|
1937 |
+
"""
|
1938 |
+
Return (other + self), that is string concatenation,
|
1939 |
+
element-wise for a pair of array_likes of `string_` or `unicode_`.
|
1940 |
+
|
1941 |
+
See also
|
1942 |
+
--------
|
1943 |
+
add
|
1944 |
+
"""
|
1945 |
+
return asarray(add(numpy.asarray(other), self))
|
1946 |
+
|
1947 |
+
def __mul__(self, i):
|
1948 |
+
"""
|
1949 |
+
Return (self * i), that is string multiple concatenation,
|
1950 |
+
element-wise.
|
1951 |
+
|
1952 |
+
See also
|
1953 |
+
--------
|
1954 |
+
multiply
|
1955 |
+
"""
|
1956 |
+
return asarray(multiply(self, i))
|
1957 |
+
|
1958 |
+
def __rmul__(self, i):
|
1959 |
+
"""
|
1960 |
+
Return (self * i), that is string multiple concatenation,
|
1961 |
+
element-wise.
|
1962 |
+
|
1963 |
+
See also
|
1964 |
+
--------
|
1965 |
+
multiply
|
1966 |
+
"""
|
1967 |
+
return asarray(multiply(self, i))
|
1968 |
+
|
1969 |
+
def __mod__(self, i):
|
1970 |
+
"""
|
1971 |
+
Return (self % i), that is pre-Python 2.6 string formatting
|
1972 |
+
(iterpolation), element-wise for a pair of array_likes of `string_`
|
1973 |
+
or `unicode_`.
|
1974 |
+
|
1975 |
+
See also
|
1976 |
+
--------
|
1977 |
+
mod
|
1978 |
+
"""
|
1979 |
+
return asarray(mod(self, i))
|
1980 |
+
|
1981 |
+
def __rmod__(self, other):
|
1982 |
+
return NotImplemented
|
1983 |
+
|
1984 |
+
def argsort(self, axis=-1, kind='quicksort', order=None):
|
1985 |
+
"""
|
1986 |
+
Return the indices that sort the array lexicographically.
|
1987 |
+
|
1988 |
+
For full documentation see `numpy.argsort`, for which this method is
|
1989 |
+
in fact merely a "thin wrapper."
|
1990 |
+
|
1991 |
+
Examples
|
1992 |
+
--------
|
1993 |
+
>>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
|
1994 |
+
>>> c = c.view(np.chararray); c
|
1995 |
+
chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
|
1996 |
+
dtype='|S5')
|
1997 |
+
>>> c[c.argsort()]
|
1998 |
+
chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
|
1999 |
+
dtype='|S5')
|
2000 |
+
|
2001 |
+
"""
|
2002 |
+
return self.__array__().argsort(axis, kind, order)
|
2003 |
+
argsort.__doc__ = ndarray.argsort.__doc__
|
2004 |
+
|
2005 |
+
def capitalize(self):
|
2006 |
+
"""
|
2007 |
+
Return a copy of `self` with only the first character of each element
|
2008 |
+
capitalized.
|
2009 |
+
|
2010 |
+
See also
|
2011 |
+
--------
|
2012 |
+
char.capitalize
|
2013 |
+
|
2014 |
+
"""
|
2015 |
+
return asarray(capitalize(self))
|
2016 |
+
|
2017 |
+
def center(self, width, fillchar=' '):
|
2018 |
+
"""
|
2019 |
+
Return a copy of `self` with its elements centered in a
|
2020 |
+
string of length `width`.
|
2021 |
+
|
2022 |
+
See also
|
2023 |
+
--------
|
2024 |
+
center
|
2025 |
+
"""
|
2026 |
+
return asarray(center(self, width, fillchar))
|
2027 |
+
|
2028 |
+
def count(self, sub, start=0, end=None):
|
2029 |
+
"""
|
2030 |
+
Returns an array with the number of non-overlapping occurrences of
|
2031 |
+
substring `sub` in the range [`start`, `end`].
|
2032 |
+
|
2033 |
+
See also
|
2034 |
+
--------
|
2035 |
+
char.count
|
2036 |
+
|
2037 |
+
"""
|
2038 |
+
return count(self, sub, start, end)
|
2039 |
+
|
2040 |
+
|
2041 |
+
def decode(self, encoding=None, errors=None):
|
2042 |
+
"""
|
2043 |
+
Calls `str.decode` element-wise.
|
2044 |
+
|
2045 |
+
See also
|
2046 |
+
--------
|
2047 |
+
char.decode
|
2048 |
+
|
2049 |
+
"""
|
2050 |
+
return decode(self, encoding, errors)
|
2051 |
+
|
2052 |
+
def encode(self, encoding=None, errors=None):
|
2053 |
+
"""
|
2054 |
+
Calls `str.encode` element-wise.
|
2055 |
+
|
2056 |
+
See also
|
2057 |
+
--------
|
2058 |
+
char.encode
|
2059 |
+
|
2060 |
+
"""
|
2061 |
+
return encode(self, encoding, errors)
|
2062 |
+
|
2063 |
+
def endswith(self, suffix, start=0, end=None):
|
2064 |
+
"""
|
2065 |
+
Returns a boolean array which is `True` where the string element
|
2066 |
+
in `self` ends with `suffix`, otherwise `False`.
|
2067 |
+
|
2068 |
+
See also
|
2069 |
+
--------
|
2070 |
+
char.endswith
|
2071 |
+
|
2072 |
+
"""
|
2073 |
+
return endswith(self, suffix, start, end)
|
2074 |
+
|
2075 |
+
def expandtabs(self, tabsize=8):
|
2076 |
+
"""
|
2077 |
+
Return a copy of each string element where all tab characters are
|
2078 |
+
replaced by one or more spaces.
|
2079 |
+
|
2080 |
+
See also
|
2081 |
+
--------
|
2082 |
+
char.expandtabs
|
2083 |
+
|
2084 |
+
"""
|
2085 |
+
return asarray(expandtabs(self, tabsize))
|
2086 |
+
|
2087 |
+
def find(self, sub, start=0, end=None):
|
2088 |
+
"""
|
2089 |
+
For each element, return the lowest index in the string where
|
2090 |
+
substring `sub` is found.
|
2091 |
+
|
2092 |
+
See also
|
2093 |
+
--------
|
2094 |
+
char.find
|
2095 |
+
|
2096 |
+
"""
|
2097 |
+
return find(self, sub, start, end)
|
2098 |
+
|
2099 |
+
def index(self, sub, start=0, end=None):
|
2100 |
+
"""
|
2101 |
+
Like `find`, but raises `ValueError` when the substring is not found.
|
2102 |
+
|
2103 |
+
See also
|
2104 |
+
--------
|
2105 |
+
char.index
|
2106 |
+
|
2107 |
+
"""
|
2108 |
+
return index(self, sub, start, end)
|
2109 |
+
|
2110 |
+
def isalnum(self):
|
2111 |
+
"""
|
2112 |
+
Returns true for each element if all characters in the string
|
2113 |
+
are alphanumeric and there is at least one character, false
|
2114 |
+
otherwise.
|
2115 |
+
|
2116 |
+
See also
|
2117 |
+
--------
|
2118 |
+
char.isalnum
|
2119 |
+
|
2120 |
+
"""
|
2121 |
+
return isalnum(self)
|
2122 |
+
|
2123 |
+
def isalpha(self):
|
2124 |
+
"""
|
2125 |
+
Returns true for each element if all characters in the string
|
2126 |
+
are alphabetic and there is at least one character, false
|
2127 |
+
otherwise.
|
2128 |
+
|
2129 |
+
See also
|
2130 |
+
--------
|
2131 |
+
char.isalpha
|
2132 |
+
|
2133 |
+
"""
|
2134 |
+
return isalpha(self)
|
2135 |
+
|
2136 |
+
def isdigit(self):
|
2137 |
+
"""
|
2138 |
+
Returns true for each element if all characters in the string are
|
2139 |
+
digits and there is at least one character, false otherwise.
|
2140 |
+
|
2141 |
+
See also
|
2142 |
+
--------
|
2143 |
+
char.isdigit
|
2144 |
+
|
2145 |
+
"""
|
2146 |
+
return isdigit(self)
|
2147 |
+
|
2148 |
+
def islower(self):
|
2149 |
+
"""
|
2150 |
+
Returns true for each element if all cased characters in the
|
2151 |
+
string are lowercase and there is at least one cased character,
|
2152 |
+
false otherwise.
|
2153 |
+
|
2154 |
+
See also
|
2155 |
+
--------
|
2156 |
+
char.islower
|
2157 |
+
|
2158 |
+
"""
|
2159 |
+
return islower(self)
|
2160 |
+
|
2161 |
+
def isspace(self):
|
2162 |
+
"""
|
2163 |
+
Returns true for each element if there are only whitespace
|
2164 |
+
characters in the string and there is at least one character,
|
2165 |
+
false otherwise.
|
2166 |
+
|
2167 |
+
See also
|
2168 |
+
--------
|
2169 |
+
char.isspace
|
2170 |
+
|
2171 |
+
"""
|
2172 |
+
return isspace(self)
|
2173 |
+
|
2174 |
+
def istitle(self):
|
2175 |
+
"""
|
2176 |
+
Returns true for each element if the element is a titlecased
|
2177 |
+
string and there is at least one character, false otherwise.
|
2178 |
+
|
2179 |
+
See also
|
2180 |
+
--------
|
2181 |
+
char.istitle
|
2182 |
+
|
2183 |
+
"""
|
2184 |
+
return istitle(self)
|
2185 |
+
|
2186 |
+
def isupper(self):
|
2187 |
+
"""
|
2188 |
+
Returns true for each element if all cased characters in the
|
2189 |
+
string are uppercase and there is at least one character, false
|
2190 |
+
otherwise.
|
2191 |
+
|
2192 |
+
See also
|
2193 |
+
--------
|
2194 |
+
char.isupper
|
2195 |
+
|
2196 |
+
"""
|
2197 |
+
return isupper(self)
|
2198 |
+
|
2199 |
+
def join(self, seq):
|
2200 |
+
"""
|
2201 |
+
Return a string which is the concatenation of the strings in the
|
2202 |
+
sequence `seq`.
|
2203 |
+
|
2204 |
+
See also
|
2205 |
+
--------
|
2206 |
+
char.join
|
2207 |
+
|
2208 |
+
"""
|
2209 |
+
return join(self, seq)
|
2210 |
+
|
2211 |
+
def ljust(self, width, fillchar=' '):
|
2212 |
+
"""
|
2213 |
+
Return an array with the elements of `self` left-justified in a
|
2214 |
+
string of length `width`.
|
2215 |
+
|
2216 |
+
See also
|
2217 |
+
--------
|
2218 |
+
char.ljust
|
2219 |
+
|
2220 |
+
"""
|
2221 |
+
return asarray(ljust(self, width, fillchar))
|
2222 |
+
|
2223 |
+
def lower(self):
|
2224 |
+
"""
|
2225 |
+
Return an array with the elements of `self` converted to
|
2226 |
+
lowercase.
|
2227 |
+
|
2228 |
+
See also
|
2229 |
+
--------
|
2230 |
+
char.lower
|
2231 |
+
|
2232 |
+
"""
|
2233 |
+
return asarray(lower(self))
|
2234 |
+
|
2235 |
+
def lstrip(self, chars=None):
|
2236 |
+
"""
|
2237 |
+
For each element in `self`, return a copy with the leading characters
|
2238 |
+
removed.
|
2239 |
+
|
2240 |
+
See also
|
2241 |
+
--------
|
2242 |
+
char.lstrip
|
2243 |
+
|
2244 |
+
"""
|
2245 |
+
return asarray(lstrip(self, chars))
|
2246 |
+
|
2247 |
+
def partition(self, sep):
|
2248 |
+
"""
|
2249 |
+
Partition each element in `self` around `sep`.
|
2250 |
+
|
2251 |
+
See also
|
2252 |
+
--------
|
2253 |
+
partition
|
2254 |
+
"""
|
2255 |
+
return asarray(partition(self, sep))
|
2256 |
+
|
2257 |
+
def replace(self, old, new, count=None):
|
2258 |
+
"""
|
2259 |
+
For each element in `self`, return a copy of the string with all
|
2260 |
+
occurrences of substring `old` replaced by `new`.
|
2261 |
+
|
2262 |
+
See also
|
2263 |
+
--------
|
2264 |
+
char.replace
|
2265 |
+
|
2266 |
+
"""
|
2267 |
+
return asarray(replace(self, old, new, count))
|
2268 |
+
|
2269 |
+
def rfind(self, sub, start=0, end=None):
|
2270 |
+
"""
|
2271 |
+
For each element in `self`, return the highest index in the string
|
2272 |
+
where substring `sub` is found, such that `sub` is contained
|
2273 |
+
within [`start`, `end`].
|
2274 |
+
|
2275 |
+
See also
|
2276 |
+
--------
|
2277 |
+
char.rfind
|
2278 |
+
|
2279 |
+
"""
|
2280 |
+
return rfind(self, sub, start, end)
|
2281 |
+
|
2282 |
+
def rindex(self, sub, start=0, end=None):
|
2283 |
+
"""
|
2284 |
+
Like `rfind`, but raises `ValueError` when the substring `sub` is
|
2285 |
+
not found.
|
2286 |
+
|
2287 |
+
See also
|
2288 |
+
--------
|
2289 |
+
char.rindex
|
2290 |
+
|
2291 |
+
"""
|
2292 |
+
return rindex(self, sub, start, end)
|
2293 |
+
|
2294 |
+
def rjust(self, width, fillchar=' '):
|
2295 |
+
"""
|
2296 |
+
Return an array with the elements of `self`
|
2297 |
+
right-justified in a string of length `width`.
|
2298 |
+
|
2299 |
+
See also
|
2300 |
+
--------
|
2301 |
+
char.rjust
|
2302 |
+
|
2303 |
+
"""
|
2304 |
+
return asarray(rjust(self, width, fillchar))
|
2305 |
+
|
2306 |
+
def rpartition(self, sep):
|
2307 |
+
"""
|
2308 |
+
Partition each element in `self` around `sep`.
|
2309 |
+
|
2310 |
+
See also
|
2311 |
+
--------
|
2312 |
+
rpartition
|
2313 |
+
"""
|
2314 |
+
return asarray(rpartition(self, sep))
|
2315 |
+
|
2316 |
+
def rsplit(self, sep=None, maxsplit=None):
|
2317 |
+
"""
|
2318 |
+
For each element in `self`, return a list of the words in
|
2319 |
+
the string, using `sep` as the delimiter string.
|
2320 |
+
|
2321 |
+
See also
|
2322 |
+
--------
|
2323 |
+
char.rsplit
|
2324 |
+
|
2325 |
+
"""
|
2326 |
+
return rsplit(self, sep, maxsplit)
|
2327 |
+
|
2328 |
+
def rstrip(self, chars=None):
|
2329 |
+
"""
|
2330 |
+
For each element in `self`, return a copy with the trailing
|
2331 |
+
characters removed.
|
2332 |
+
|
2333 |
+
See also
|
2334 |
+
--------
|
2335 |
+
char.rstrip
|
2336 |
+
|
2337 |
+
"""
|
2338 |
+
return asarray(rstrip(self, chars))
|
2339 |
+
|
2340 |
+
def split(self, sep=None, maxsplit=None):
|
2341 |
+
"""
|
2342 |
+
For each element in `self`, return a list of the words in the
|
2343 |
+
string, using `sep` as the delimiter string.
|
2344 |
+
|
2345 |
+
See also
|
2346 |
+
--------
|
2347 |
+
char.split
|
2348 |
+
|
2349 |
+
"""
|
2350 |
+
return split(self, sep, maxsplit)
|
2351 |
+
|
2352 |
+
def splitlines(self, keepends=None):
|
2353 |
+
"""
|
2354 |
+
For each element in `self`, return a list of the lines in the
|
2355 |
+
element, breaking at line boundaries.
|
2356 |
+
|
2357 |
+
See also
|
2358 |
+
--------
|
2359 |
+
char.splitlines
|
2360 |
+
|
2361 |
+
"""
|
2362 |
+
return splitlines(self, keepends)
|
2363 |
+
|
2364 |
+
def startswith(self, prefix, start=0, end=None):
|
2365 |
+
"""
|
2366 |
+
Returns a boolean array which is `True` where the string element
|
2367 |
+
in `self` starts with `prefix`, otherwise `False`.
|
2368 |
+
|
2369 |
+
See also
|
2370 |
+
--------
|
2371 |
+
char.startswith
|
2372 |
+
|
2373 |
+
"""
|
2374 |
+
return startswith(self, prefix, start, end)
|
2375 |
+
|
2376 |
+
def strip(self, chars=None):
|
2377 |
+
"""
|
2378 |
+
For each element in `self`, return a copy with the leading and
|
2379 |
+
trailing characters removed.
|
2380 |
+
|
2381 |
+
See also
|
2382 |
+
--------
|
2383 |
+
char.strip
|
2384 |
+
|
2385 |
+
"""
|
2386 |
+
return asarray(strip(self, chars))
|
2387 |
+
|
2388 |
+
def swapcase(self):
|
2389 |
+
"""
|
2390 |
+
For each element in `self`, return a copy of the string with
|
2391 |
+
uppercase characters converted to lowercase and vice versa.
|
2392 |
+
|
2393 |
+
See also
|
2394 |
+
--------
|
2395 |
+
char.swapcase
|
2396 |
+
|
2397 |
+
"""
|
2398 |
+
return asarray(swapcase(self))
|
2399 |
+
|
2400 |
+
def title(self):
|
2401 |
+
"""
|
2402 |
+
For each element in `self`, return a titlecased version of the
|
2403 |
+
string: words start with uppercase characters, all remaining cased
|
2404 |
+
characters are lowercase.
|
2405 |
+
|
2406 |
+
See also
|
2407 |
+
--------
|
2408 |
+
char.title
|
2409 |
+
|
2410 |
+
"""
|
2411 |
+
return asarray(title(self))
|
2412 |
+
|
2413 |
+
def translate(self, table, deletechars=None):
|
2414 |
+
"""
|
2415 |
+
For each element in `self`, return a copy of the string where
|
2416 |
+
all characters occurring in the optional argument
|
2417 |
+
`deletechars` are removed, and the remaining characters have
|
2418 |
+
been mapped through the given translation table.
|
2419 |
+
|
2420 |
+
See also
|
2421 |
+
--------
|
2422 |
+
char.translate
|
2423 |
+
|
2424 |
+
"""
|
2425 |
+
return asarray(translate(self, table, deletechars))
|
2426 |
+
|
2427 |
+
def upper(self):
|
2428 |
+
"""
|
2429 |
+
Return an array with the elements of `self` converted to
|
2430 |
+
uppercase.
|
2431 |
+
|
2432 |
+
See also
|
2433 |
+
--------
|
2434 |
+
char.upper
|
2435 |
+
|
2436 |
+
"""
|
2437 |
+
return asarray(upper(self))
|
2438 |
+
|
2439 |
+
def zfill(self, width):
|
2440 |
+
"""
|
2441 |
+
Return the numeric string left-filled with zeros in a string of
|
2442 |
+
length `width`.
|
2443 |
+
|
2444 |
+
See also
|
2445 |
+
--------
|
2446 |
+
char.zfill
|
2447 |
+
|
2448 |
+
"""
|
2449 |
+
return asarray(zfill(self, width))
|
2450 |
+
|
2451 |
+
def isnumeric(self):
|
2452 |
+
"""
|
2453 |
+
For each element in `self`, return True if there are only
|
2454 |
+
numeric characters in the element.
|
2455 |
+
|
2456 |
+
See also
|
2457 |
+
--------
|
2458 |
+
char.isnumeric
|
2459 |
+
|
2460 |
+
"""
|
2461 |
+
return isnumeric(self)
|
2462 |
+
|
2463 |
+
def isdecimal(self):
|
2464 |
+
"""
|
2465 |
+
For each element in `self`, return True if there are only
|
2466 |
+
decimal characters in the element.
|
2467 |
+
|
2468 |
+
See also
|
2469 |
+
--------
|
2470 |
+
char.isdecimal
|
2471 |
+
|
2472 |
+
"""
|
2473 |
+
return isdecimal(self)
|
2474 |
+
|
2475 |
+
|
2476 |
+
def array(obj, itemsize=None, copy=True, unicode=None, order=None):
|
2477 |
+
"""
|
2478 |
+
Create a `chararray`.
|
2479 |
+
|
2480 |
+
.. note::
|
2481 |
+
This class is provided for numarray backward-compatibility.
|
2482 |
+
New code (not concerned with numarray compatibility) should use
|
2483 |
+
arrays of type `string_` or `unicode_` and use the free functions
|
2484 |
+
in :mod:`numpy.char <numpy.core.defchararray>` for fast
|
2485 |
+
vectorized string operations instead.
|
2486 |
+
|
2487 |
+
Versus a regular Numpy array of type `str` or `unicode`, this
|
2488 |
+
class adds the following functionality:
|
2489 |
+
|
2490 |
+
1) values automatically have whitespace removed from the end
|
2491 |
+
when indexed
|
2492 |
+
|
2493 |
+
2) comparison operators automatically remove whitespace from the
|
2494 |
+
end when comparing values
|
2495 |
+
|
2496 |
+
3) vectorized string operations are provided as methods
|
2497 |
+
(e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``)
|
2498 |
+
|
2499 |
+
Parameters
|
2500 |
+
----------
|
2501 |
+
obj : array of str or unicode-like
|
2502 |
+
|
2503 |
+
itemsize : int, optional
|
2504 |
+
`itemsize` is the number of characters per scalar in the
|
2505 |
+
resulting array. If `itemsize` is None, and `obj` is an
|
2506 |
+
object array or a Python list, the `itemsize` will be
|
2507 |
+
automatically determined. If `itemsize` is provided and `obj`
|
2508 |
+
is of type str or unicode, then the `obj` string will be
|
2509 |
+
chunked into `itemsize` pieces.
|
2510 |
+
|
2511 |
+
copy : bool, optional
|
2512 |
+
If true (default), then the object is copied. Otherwise, a copy
|
2513 |
+
will only be made if __array__ returns a copy, if obj is a
|
2514 |
+
nested sequence, or if a copy is needed to satisfy any of the other
|
2515 |
+
requirements (`itemsize`, unicode, `order`, etc.).
|
2516 |
+
|
2517 |
+
unicode : bool, optional
|
2518 |
+
When true, the resulting `chararray` can contain Unicode
|
2519 |
+
characters, when false only 8-bit characters. If unicode is
|
2520 |
+
`None` and `obj` is one of the following:
|
2521 |
+
|
2522 |
+
- a `chararray`,
|
2523 |
+
- an ndarray of type `str` or `unicode`
|
2524 |
+
- a Python str or unicode object,
|
2525 |
+
|
2526 |
+
then the unicode setting of the output array will be
|
2527 |
+
automatically determined.
|
2528 |
+
|
2529 |
+
order : {'C', 'F', 'A'}, optional
|
2530 |
+
Specify the order of the array. If order is 'C' (default), then the
|
2531 |
+
array will be in C-contiguous order (last-index varies the
|
2532 |
+
fastest). If order is 'F', then the returned array
|
2533 |
+
will be in Fortran-contiguous order (first-index varies the
|
2534 |
+
fastest). If order is 'A', then the returned array may
|
2535 |
+
be in any order (either C-, Fortran-contiguous, or even
|
2536 |
+
discontiguous).
|
2537 |
+
"""
|
2538 |
+
if isinstance(obj, (_bytes, _unicode)):
|
2539 |
+
if unicode is None:
|
2540 |
+
if isinstance(obj, _unicode):
|
2541 |
+
unicode = True
|
2542 |
+
else:
|
2543 |
+
unicode = False
|
2544 |
+
|
2545 |
+
if itemsize is None:
|
2546 |
+
itemsize = _len(obj)
|
2547 |
+
shape = _len(obj) // itemsize
|
2548 |
+
|
2549 |
+
if unicode:
|
2550 |
+
if sys.maxunicode == 0xffff:
|
2551 |
+
# On a narrow Python build, the buffer for Unicode
|
2552 |
+
# strings is UCS2, which doesn't match the buffer for
|
2553 |
+
# Numpy Unicode types, which is ALWAYS UCS4.
|
2554 |
+
# Therefore, we need to convert the buffer. On Python
|
2555 |
+
# 2.6 and later, we can use the utf_32 codec. Earlier
|
2556 |
+
# versions don't have that codec, so we convert to a
|
2557 |
+
# numerical array that matches the input buffer, and
|
2558 |
+
# then use Numpy to convert it to UCS4. All of this
|
2559 |
+
# should happen in native endianness.
|
2560 |
+
if sys.hexversion >= 0x2060000:
|
2561 |
+
obj = obj.encode('utf_32')
|
2562 |
+
else:
|
2563 |
+
if isinstance(obj, str):
|
2564 |
+
ascii = numpy.frombuffer(obj, 'u1')
|
2565 |
+
ucs4 = numpy.array(ascii, 'u4')
|
2566 |
+
obj = ucs4.data
|
2567 |
+
else:
|
2568 |
+
ucs2 = numpy.frombuffer(obj, 'u2')
|
2569 |
+
ucs4 = numpy.array(ucs2, 'u4')
|
2570 |
+
obj = ucs4.data
|
2571 |
+
else:
|
2572 |
+
obj = _unicode(obj)
|
2573 |
+
else:
|
2574 |
+
# Let the default Unicode -> string encoding (if any) take
|
2575 |
+
# precedence.
|
2576 |
+
obj = _bytes(obj)
|
2577 |
+
|
2578 |
+
return chararray(shape, itemsize=itemsize, unicode=unicode,
|
2579 |
+
buffer=obj, order=order)
|
2580 |
+
|
2581 |
+
if isinstance(obj, (list, tuple)):
|
2582 |
+
obj = numpy.asarray(obj)
|
2583 |
+
|
2584 |
+
if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
|
2585 |
+
# If we just have a vanilla chararray, create a chararray
|
2586 |
+
# view around it.
|
2587 |
+
if not isinstance(obj, chararray):
|
2588 |
+
obj = obj.view(chararray)
|
2589 |
+
|
2590 |
+
if itemsize is None:
|
2591 |
+
itemsize = obj.itemsize
|
2592 |
+
# itemsize is in 8-bit chars, so for Unicode, we need
|
2593 |
+
# to divide by the size of a single Unicode character,
|
2594 |
+
# which for Numpy is always 4
|
2595 |
+
if issubclass(obj.dtype.type, unicode_):
|
2596 |
+
itemsize //= 4
|
2597 |
+
|
2598 |
+
if unicode is None:
|
2599 |
+
if issubclass(obj.dtype.type, unicode_):
|
2600 |
+
unicode = True
|
2601 |
+
else:
|
2602 |
+
unicode = False
|
2603 |
+
|
2604 |
+
if unicode:
|
2605 |
+
dtype = unicode_
|
2606 |
+
else:
|
2607 |
+
dtype = string_
|
2608 |
+
|
2609 |
+
if order is not None:
|
2610 |
+
obj = numpy.asarray(obj, order=order)
|
2611 |
+
if (copy
|
2612 |
+
or (itemsize != obj.itemsize)
|
2613 |
+
or (not unicode and isinstance(obj, unicode_))
|
2614 |
+
or (unicode and isinstance(obj, string_))):
|
2615 |
+
obj = obj.astype((dtype, long(itemsize)))
|
2616 |
+
return obj
|
2617 |
+
|
2618 |
+
if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
|
2619 |
+
if itemsize is None:
|
2620 |
+
# Since no itemsize was specified, convert the input array to
|
2621 |
+
# a list so the ndarray constructor will automatically
|
2622 |
+
# determine the itemsize for us.
|
2623 |
+
obj = obj.tolist()
|
2624 |
+
# Fall through to the default case
|
2625 |
+
|
2626 |
+
if unicode:
|
2627 |
+
dtype = unicode_
|
2628 |
+
else:
|
2629 |
+
dtype = string_
|
2630 |
+
|
2631 |
+
if itemsize is None:
|
2632 |
+
val = narray(obj, dtype=dtype, order=order, subok=True)
|
2633 |
+
else:
|
2634 |
+
val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
|
2635 |
+
return val.view(chararray)
|
2636 |
+
|
2637 |
+
|
2638 |
+
def asarray(obj, itemsize=None, unicode=None, order=None):
|
2639 |
+
"""
|
2640 |
+
Convert the input to a `chararray`, copying the data only if
|
2641 |
+
necessary.
|
2642 |
+
|
2643 |
+
Versus a regular Numpy array of type `str` or `unicode`, this
|
2644 |
+
class adds the following functionality:
|
2645 |
+
|
2646 |
+
1) values automatically have whitespace removed from the end
|
2647 |
+
when indexed
|
2648 |
+
|
2649 |
+
2) comparison operators automatically remove whitespace from the
|
2650 |
+
end when comparing values
|
2651 |
+
|
2652 |
+
3) vectorized string operations are provided as methods
|
2653 |
+
(e.g. `str.endswith`) and infix operators (e.g. +, *, %)
|
2654 |
+
|
2655 |
+
Parameters
|
2656 |
+
----------
|
2657 |
+
obj : array of str or unicode-like
|
2658 |
+
|
2659 |
+
itemsize : int, optional
|
2660 |
+
`itemsize` is the number of characters per scalar in the
|
2661 |
+
resulting array. If `itemsize` is None, and `obj` is an
|
2662 |
+
object array or a Python list, the `itemsize` will be
|
2663 |
+
automatically determined. If `itemsize` is provided and `obj`
|
2664 |
+
is of type str or unicode, then the `obj` string will be
|
2665 |
+
chunked into `itemsize` pieces.
|
2666 |
+
|
2667 |
+
unicode : bool, optional
|
2668 |
+
When true, the resulting `chararray` can contain Unicode
|
2669 |
+
characters, when false only 8-bit characters. If unicode is
|
2670 |
+
`None` and `obj` is one of the following:
|
2671 |
+
|
2672 |
+
- a `chararray`,
|
2673 |
+
- an ndarray of type `str` or 'unicode`
|
2674 |
+
- a Python str or unicode object,
|
2675 |
+
|
2676 |
+
then the unicode setting of the output array will be
|
2677 |
+
automatically determined.
|
2678 |
+
|
2679 |
+
order : {'C', 'F'}, optional
|
2680 |
+
Specify the order of the array. If order is 'C' (default), then the
|
2681 |
+
array will be in C-contiguous order (last-index varies the
|
2682 |
+
fastest). If order is 'F', then the returned array
|
2683 |
+
will be in Fortran-contiguous order (first-index varies the
|
2684 |
+
fastest).
|
2685 |
+
"""
|
2686 |
+
return array(obj, itemsize, copy=False,
|
2687 |
+
unicode=unicode, order=order)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/fromnumeric.py
ADDED
@@ -0,0 +1,2930 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Module containing non-deprecated functions borrowed from Numeric.
|
2 |
+
|
3 |
+
"""
|
4 |
+
from __future__ import division, absolute_import, print_function
|
5 |
+
|
6 |
+
import types
|
7 |
+
import warnings
|
8 |
+
|
9 |
+
from .. import VisibleDeprecationWarning
|
10 |
+
from . import multiarray as mu
|
11 |
+
from . import umath as um
|
12 |
+
from . import numerictypes as nt
|
13 |
+
from .numeric import asarray, array, asanyarray, concatenate
|
14 |
+
from . import _methods
|
15 |
+
|
16 |
+
_dt_ = nt.sctype2char
|
17 |
+
|
18 |
+
|
19 |
+
# functions that are methods
|
20 |
+
__all__ = [
|
21 |
+
'alen', 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
|
22 |
+
'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
|
23 |
+
'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
|
24 |
+
'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
|
25 |
+
'rank', 'ravel', 'repeat', 'reshape', 'resize', 'round_',
|
26 |
+
'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
|
27 |
+
'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
|
28 |
+
]
|
29 |
+
|
30 |
+
|
31 |
+
try:
|
32 |
+
_gentype = types.GeneratorType
|
33 |
+
except AttributeError:
|
34 |
+
_gentype = type(None)
|
35 |
+
|
36 |
+
# save away Python sum
|
37 |
+
_sum_ = sum
|
38 |
+
|
39 |
+
# functions that are now methods
|
40 |
+
def _wrapit(obj, method, *args, **kwds):
|
41 |
+
try:
|
42 |
+
wrap = obj.__array_wrap__
|
43 |
+
except AttributeError:
|
44 |
+
wrap = None
|
45 |
+
result = getattr(asarray(obj), method)(*args, **kwds)
|
46 |
+
if wrap:
|
47 |
+
if not isinstance(result, mu.ndarray):
|
48 |
+
result = asarray(result)
|
49 |
+
result = wrap(result)
|
50 |
+
return result
|
51 |
+
|
52 |
+
|
53 |
+
def take(a, indices, axis=None, out=None, mode='raise'):
|
54 |
+
"""
|
55 |
+
Take elements from an array along an axis.
|
56 |
+
|
57 |
+
This function does the same thing as "fancy" indexing (indexing arrays
|
58 |
+
using arrays); however, it can be easier to use if you need elements
|
59 |
+
along a given axis.
|
60 |
+
|
61 |
+
Parameters
|
62 |
+
----------
|
63 |
+
a : array_like
|
64 |
+
The source array.
|
65 |
+
indices : array_like
|
66 |
+
The indices of the values to extract.
|
67 |
+
|
68 |
+
.. versionadded:: 1.8.0
|
69 |
+
|
70 |
+
Also allow scalars for indices.
|
71 |
+
axis : int, optional
|
72 |
+
The axis over which to select values. By default, the flattened
|
73 |
+
input array is used.
|
74 |
+
out : ndarray, optional
|
75 |
+
If provided, the result will be placed in this array. It should
|
76 |
+
be of the appropriate shape and dtype.
|
77 |
+
mode : {'raise', 'wrap', 'clip'}, optional
|
78 |
+
Specifies how out-of-bounds indices will behave.
|
79 |
+
|
80 |
+
* 'raise' -- raise an error (default)
|
81 |
+
* 'wrap' -- wrap around
|
82 |
+
* 'clip' -- clip to the range
|
83 |
+
|
84 |
+
'clip' mode means that all indices that are too large are replaced
|
85 |
+
by the index that addresses the last element along that axis. Note
|
86 |
+
that this disables indexing with negative numbers.
|
87 |
+
|
88 |
+
Returns
|
89 |
+
-------
|
90 |
+
subarray : ndarray
|
91 |
+
The returned array has the same type as `a`.
|
92 |
+
|
93 |
+
See Also
|
94 |
+
--------
|
95 |
+
compress : Take elements using a boolean mask
|
96 |
+
ndarray.take : equivalent method
|
97 |
+
|
98 |
+
Examples
|
99 |
+
--------
|
100 |
+
>>> a = [4, 3, 5, 7, 6, 8]
|
101 |
+
>>> indices = [0, 1, 4]
|
102 |
+
>>> np.take(a, indices)
|
103 |
+
array([4, 3, 6])
|
104 |
+
|
105 |
+
In this example if `a` is an ndarray, "fancy" indexing can be used.
|
106 |
+
|
107 |
+
>>> a = np.array(a)
|
108 |
+
>>> a[indices]
|
109 |
+
array([4, 3, 6])
|
110 |
+
|
111 |
+
If `indices` is not one dimensional, the output also has these dimensions.
|
112 |
+
|
113 |
+
>>> np.take(a, [[0, 1], [2, 3]])
|
114 |
+
array([[4, 3],
|
115 |
+
[5, 7]])
|
116 |
+
"""
|
117 |
+
try:
|
118 |
+
take = a.take
|
119 |
+
except AttributeError:
|
120 |
+
return _wrapit(a, 'take', indices, axis, out, mode)
|
121 |
+
return take(indices, axis, out, mode)
|
122 |
+
|
123 |
+
|
124 |
+
# not deprecated --- copy if necessary, view otherwise
|
125 |
+
def reshape(a, newshape, order='C'):
|
126 |
+
"""
|
127 |
+
Gives a new shape to an array without changing its data.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
a : array_like
|
132 |
+
Array to be reshaped.
|
133 |
+
newshape : int or tuple of ints
|
134 |
+
The new shape should be compatible with the original shape. If
|
135 |
+
an integer, then the result will be a 1-D array of that length.
|
136 |
+
One shape dimension can be -1. In this case, the value is inferred
|
137 |
+
from the length of the array and remaining dimensions.
|
138 |
+
order : {'C', 'F', 'A'}, optional
|
139 |
+
Read the elements of `a` using this index order, and place the elements
|
140 |
+
into the reshaped array using this index order. 'C' means to
|
141 |
+
read / write the elements using C-like index order, with the last axis index
|
142 |
+
changing fastest, back to the first axis index changing slowest. 'F'
|
143 |
+
means to read / write the elements using Fortran-like index order, with
|
144 |
+
the first index changing fastest, and the last index changing slowest.
|
145 |
+
Note that the 'C' and 'F' options take no account of the memory layout
|
146 |
+
of the underlying array, and only refer to the order of indexing. 'A'
|
147 |
+
means to read / write the elements in Fortran-like index order if `a` is
|
148 |
+
Fortran *contiguous* in memory, C-like order otherwise.
|
149 |
+
|
150 |
+
Returns
|
151 |
+
-------
|
152 |
+
reshaped_array : ndarray
|
153 |
+
This will be a new view object if possible; otherwise, it will
|
154 |
+
be a copy. Note there is no guarantee of the *memory layout* (C- or
|
155 |
+
Fortran- contiguous) of the returned array.
|
156 |
+
|
157 |
+
See Also
|
158 |
+
--------
|
159 |
+
ndarray.reshape : Equivalent method.
|
160 |
+
|
161 |
+
Notes
|
162 |
+
-----
|
163 |
+
It is not always possible to change the shape of an array without
|
164 |
+
copying the data. If you want an error to be raise if the data is copied,
|
165 |
+
you should assign the new shape to the shape attribute of the array::
|
166 |
+
|
167 |
+
>>> a = np.zeros((10, 2))
|
168 |
+
# A transpose make the array non-contiguous
|
169 |
+
>>> b = a.T
|
170 |
+
# Taking a view makes it possible to modify the shape without modifying the
|
171 |
+
# initial object.
|
172 |
+
>>> c = b.view()
|
173 |
+
>>> c.shape = (20)
|
174 |
+
AttributeError: incompatible shape for a non-contiguous array
|
175 |
+
|
176 |
+
The `order` keyword gives the index ordering both for *fetching* the values
|
177 |
+
from `a`, and then *placing* the values into the output array. For example,
|
178 |
+
let's say you have an array:
|
179 |
+
|
180 |
+
>>> a = np.arange(6).reshape((3, 2))
|
181 |
+
>>> a
|
182 |
+
array([[0, 1],
|
183 |
+
[2, 3],
|
184 |
+
[4, 5]])
|
185 |
+
|
186 |
+
You can think of reshaping as first raveling the array (using the given
|
187 |
+
index order), then inserting the elements from the raveled array into the
|
188 |
+
new array using the same kind of index ordering as was used for the
|
189 |
+
raveling.
|
190 |
+
|
191 |
+
>>> np.reshape(a, (2, 3)) # C-like index ordering
|
192 |
+
array([[0, 1, 2],
|
193 |
+
[3, 4, 5]])
|
194 |
+
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
|
195 |
+
array([[0, 1, 2],
|
196 |
+
[3, 4, 5]])
|
197 |
+
>>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
|
198 |
+
array([[0, 4, 3],
|
199 |
+
[2, 1, 5]])
|
200 |
+
>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
|
201 |
+
array([[0, 4, 3],
|
202 |
+
[2, 1, 5]])
|
203 |
+
|
204 |
+
Examples
|
205 |
+
--------
|
206 |
+
>>> a = np.array([[1,2,3], [4,5,6]])
|
207 |
+
>>> np.reshape(a, 6)
|
208 |
+
array([1, 2, 3, 4, 5, 6])
|
209 |
+
>>> np.reshape(a, 6, order='F')
|
210 |
+
array([1, 4, 2, 5, 3, 6])
|
211 |
+
|
212 |
+
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
|
213 |
+
array([[1, 2],
|
214 |
+
[3, 4],
|
215 |
+
[5, 6]])
|
216 |
+
"""
|
217 |
+
try:
|
218 |
+
reshape = a.reshape
|
219 |
+
except AttributeError:
|
220 |
+
return _wrapit(a, 'reshape', newshape, order=order)
|
221 |
+
return reshape(newshape, order=order)
|
222 |
+
|
223 |
+
|
224 |
+
def choose(a, choices, out=None, mode='raise'):
|
225 |
+
"""
|
226 |
+
Construct an array from an index array and a set of arrays to choose from.
|
227 |
+
|
228 |
+
First of all, if confused or uncertain, definitely look at the Examples -
|
229 |
+
in its full generality, this function is less simple than it might
|
230 |
+
seem from the following code description (below ndi =
|
231 |
+
`numpy.lib.index_tricks`):
|
232 |
+
|
233 |
+
``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
|
234 |
+
|
235 |
+
But this omits some subtleties. Here is a fully general summary:
|
236 |
+
|
237 |
+
Given an "index" array (`a`) of integers and a sequence of `n` arrays
|
238 |
+
(`choices`), `a` and each choice array are first broadcast, as necessary,
|
239 |
+
to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
|
240 |
+
0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
|
241 |
+
for each `i`. Then, a new array with shape ``Ba.shape`` is created as
|
242 |
+
follows:
|
243 |
+
|
244 |
+
* if ``mode=raise`` (the default), then, first of all, each element of
|
245 |
+
`a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that
|
246 |
+
`i` (in that range) is the value at the `(j0, j1, ..., jm)` position
|
247 |
+
in `Ba` - then the value at the same position in the new array is the
|
248 |
+
value in `Bchoices[i]` at that same position;
|
249 |
+
|
250 |
+
* if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed)
|
251 |
+
integer; modular arithmetic is used to map integers outside the range
|
252 |
+
`[0, n-1]` back into that range; and then the new array is constructed
|
253 |
+
as above;
|
254 |
+
|
255 |
+
* if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed)
|
256 |
+
integer; negative integers are mapped to 0; values greater than `n-1`
|
257 |
+
are mapped to `n-1`; and then the new array is constructed as above.
|
258 |
+
|
259 |
+
Parameters
|
260 |
+
----------
|
261 |
+
a : int array
|
262 |
+
This array must contain integers in `[0, n-1]`, where `n` is the number
|
263 |
+
of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any
|
264 |
+
integers are permissible.
|
265 |
+
choices : sequence of arrays
|
266 |
+
Choice arrays. `a` and all of the choices must be broadcastable to the
|
267 |
+
same shape. If `choices` is itself an array (not recommended), then
|
268 |
+
its outermost dimension (i.e., the one corresponding to
|
269 |
+
``choices.shape[0]``) is taken as defining the "sequence".
|
270 |
+
out : array, optional
|
271 |
+
If provided, the result will be inserted into this array. It should
|
272 |
+
be of the appropriate shape and dtype.
|
273 |
+
mode : {'raise' (default), 'wrap', 'clip'}, optional
|
274 |
+
Specifies how indices outside `[0, n-1]` will be treated:
|
275 |
+
|
276 |
+
* 'raise' : an exception is raised
|
277 |
+
* 'wrap' : value becomes value mod `n`
|
278 |
+
* 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
|
279 |
+
|
280 |
+
Returns
|
281 |
+
-------
|
282 |
+
merged_array : array
|
283 |
+
The merged result.
|
284 |
+
|
285 |
+
Raises
|
286 |
+
------
|
287 |
+
ValueError: shape mismatch
|
288 |
+
If `a` and each choice array are not all broadcastable to the same
|
289 |
+
shape.
|
290 |
+
|
291 |
+
See Also
|
292 |
+
--------
|
293 |
+
ndarray.choose : equivalent method
|
294 |
+
|
295 |
+
Notes
|
296 |
+
-----
|
297 |
+
To reduce the chance of misinterpretation, even though the following
|
298 |
+
"abuse" is nominally supported, `choices` should neither be, nor be
|
299 |
+
thought of as, a single array, i.e., the outermost sequence-like container
|
300 |
+
should be either a list or a tuple.
|
301 |
+
|
302 |
+
Examples
|
303 |
+
--------
|
304 |
+
|
305 |
+
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
|
306 |
+
... [20, 21, 22, 23], [30, 31, 32, 33]]
|
307 |
+
>>> np.choose([2, 3, 1, 0], choices
|
308 |
+
... # the first element of the result will be the first element of the
|
309 |
+
... # third (2+1) "array" in choices, namely, 20; the second element
|
310 |
+
... # will be the second element of the fourth (3+1) choice array, i.e.,
|
311 |
+
... # 31, etc.
|
312 |
+
... )
|
313 |
+
array([20, 31, 12, 3])
|
314 |
+
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
|
315 |
+
array([20, 31, 12, 3])
|
316 |
+
>>> # because there are 4 choice arrays
|
317 |
+
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
|
318 |
+
array([20, 1, 12, 3])
|
319 |
+
>>> # i.e., 0
|
320 |
+
|
321 |
+
A couple examples illustrating how choose broadcasts:
|
322 |
+
|
323 |
+
>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
|
324 |
+
>>> choices = [-10, 10]
|
325 |
+
>>> np.choose(a, choices)
|
326 |
+
array([[ 10, -10, 10],
|
327 |
+
[-10, 10, -10],
|
328 |
+
[ 10, -10, 10]])
|
329 |
+
|
330 |
+
>>> # With thanks to Anne Archibald
|
331 |
+
>>> a = np.array([0, 1]).reshape((2,1,1))
|
332 |
+
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
|
333 |
+
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
|
334 |
+
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
|
335 |
+
array([[[ 1, 1, 1, 1, 1],
|
336 |
+
[ 2, 2, 2, 2, 2],
|
337 |
+
[ 3, 3, 3, 3, 3]],
|
338 |
+
[[-1, -2, -3, -4, -5],
|
339 |
+
[-1, -2, -3, -4, -5],
|
340 |
+
[-1, -2, -3, -4, -5]]])
|
341 |
+
|
342 |
+
"""
|
343 |
+
try:
|
344 |
+
choose = a.choose
|
345 |
+
except AttributeError:
|
346 |
+
return _wrapit(a, 'choose', choices, out=out, mode=mode)
|
347 |
+
return choose(choices, out=out, mode=mode)
|
348 |
+
|
349 |
+
|
350 |
+
def repeat(a, repeats, axis=None):
|
351 |
+
"""
|
352 |
+
Repeat elements of an array.
|
353 |
+
|
354 |
+
Parameters
|
355 |
+
----------
|
356 |
+
a : array_like
|
357 |
+
Input array.
|
358 |
+
repeats : {int, array of ints}
|
359 |
+
The number of repetitions for each element. `repeats` is broadcasted
|
360 |
+
to fit the shape of the given axis.
|
361 |
+
axis : int, optional
|
362 |
+
The axis along which to repeat values. By default, use the
|
363 |
+
flattened input array, and return a flat output array.
|
364 |
+
|
365 |
+
Returns
|
366 |
+
-------
|
367 |
+
repeated_array : ndarray
|
368 |
+
Output array which has the same shape as `a`, except along
|
369 |
+
the given axis.
|
370 |
+
|
371 |
+
See Also
|
372 |
+
--------
|
373 |
+
tile : Tile an array.
|
374 |
+
|
375 |
+
Examples
|
376 |
+
--------
|
377 |
+
>>> x = np.array([[1,2],[3,4]])
|
378 |
+
>>> np.repeat(x, 2)
|
379 |
+
array([1, 1, 2, 2, 3, 3, 4, 4])
|
380 |
+
>>> np.repeat(x, 3, axis=1)
|
381 |
+
array([[1, 1, 1, 2, 2, 2],
|
382 |
+
[3, 3, 3, 4, 4, 4]])
|
383 |
+
>>> np.repeat(x, [1, 2], axis=0)
|
384 |
+
array([[1, 2],
|
385 |
+
[3, 4],
|
386 |
+
[3, 4]])
|
387 |
+
|
388 |
+
"""
|
389 |
+
try:
|
390 |
+
repeat = a.repeat
|
391 |
+
except AttributeError:
|
392 |
+
return _wrapit(a, 'repeat', repeats, axis)
|
393 |
+
return repeat(repeats, axis)
|
394 |
+
|
395 |
+
|
396 |
+
def put(a, ind, v, mode='raise'):
|
397 |
+
"""
|
398 |
+
Replaces specified elements of an array with given values.
|
399 |
+
|
400 |
+
The indexing works on the flattened target array. `put` is roughly
|
401 |
+
equivalent to:
|
402 |
+
|
403 |
+
::
|
404 |
+
|
405 |
+
a.flat[ind] = v
|
406 |
+
|
407 |
+
Parameters
|
408 |
+
----------
|
409 |
+
a : ndarray
|
410 |
+
Target array.
|
411 |
+
ind : array_like
|
412 |
+
Target indices, interpreted as integers.
|
413 |
+
v : array_like
|
414 |
+
Values to place in `a` at target indices. If `v` is shorter than
|
415 |
+
`ind` it will be repeated as necessary.
|
416 |
+
mode : {'raise', 'wrap', 'clip'}, optional
|
417 |
+
Specifies how out-of-bounds indices will behave.
|
418 |
+
|
419 |
+
* 'raise' -- raise an error (default)
|
420 |
+
* 'wrap' -- wrap around
|
421 |
+
* 'clip' -- clip to the range
|
422 |
+
|
423 |
+
'clip' mode means that all indices that are too large are replaced
|
424 |
+
by the index that addresses the last element along that axis. Note
|
425 |
+
that this disables indexing with negative numbers.
|
426 |
+
|
427 |
+
See Also
|
428 |
+
--------
|
429 |
+
putmask, place
|
430 |
+
|
431 |
+
Examples
|
432 |
+
--------
|
433 |
+
>>> a = np.arange(5)
|
434 |
+
>>> np.put(a, [0, 2], [-44, -55])
|
435 |
+
>>> a
|
436 |
+
array([-44, 1, -55, 3, 4])
|
437 |
+
|
438 |
+
>>> a = np.arange(5)
|
439 |
+
>>> np.put(a, 22, -5, mode='clip')
|
440 |
+
>>> a
|
441 |
+
array([ 0, 1, 2, 3, -5])
|
442 |
+
|
443 |
+
"""
|
444 |
+
return a.put(ind, v, mode)
|
445 |
+
|
446 |
+
|
447 |
+
def swapaxes(a, axis1, axis2):
|
448 |
+
"""
|
449 |
+
Interchange two axes of an array.
|
450 |
+
|
451 |
+
Parameters
|
452 |
+
----------
|
453 |
+
a : array_like
|
454 |
+
Input array.
|
455 |
+
axis1 : int
|
456 |
+
First axis.
|
457 |
+
axis2 : int
|
458 |
+
Second axis.
|
459 |
+
|
460 |
+
Returns
|
461 |
+
-------
|
462 |
+
a_swapped : ndarray
|
463 |
+
If `a` is an ndarray, then a view of `a` is returned; otherwise
|
464 |
+
a new array is created.
|
465 |
+
|
466 |
+
Examples
|
467 |
+
--------
|
468 |
+
>>> x = np.array([[1,2,3]])
|
469 |
+
>>> np.swapaxes(x,0,1)
|
470 |
+
array([[1],
|
471 |
+
[2],
|
472 |
+
[3]])
|
473 |
+
|
474 |
+
>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
|
475 |
+
>>> x
|
476 |
+
array([[[0, 1],
|
477 |
+
[2, 3]],
|
478 |
+
[[4, 5],
|
479 |
+
[6, 7]]])
|
480 |
+
|
481 |
+
>>> np.swapaxes(x,0,2)
|
482 |
+
array([[[0, 4],
|
483 |
+
[2, 6]],
|
484 |
+
[[1, 5],
|
485 |
+
[3, 7]]])
|
486 |
+
|
487 |
+
"""
|
488 |
+
try:
|
489 |
+
swapaxes = a.swapaxes
|
490 |
+
except AttributeError:
|
491 |
+
return _wrapit(a, 'swapaxes', axis1, axis2)
|
492 |
+
return swapaxes(axis1, axis2)
|
493 |
+
|
494 |
+
|
495 |
+
def transpose(a, axes=None):
|
496 |
+
"""
|
497 |
+
Permute the dimensions of an array.
|
498 |
+
|
499 |
+
Parameters
|
500 |
+
----------
|
501 |
+
a : array_like
|
502 |
+
Input array.
|
503 |
+
axes : list of ints, optional
|
504 |
+
By default, reverse the dimensions, otherwise permute the axes
|
505 |
+
according to the values given.
|
506 |
+
|
507 |
+
Returns
|
508 |
+
-------
|
509 |
+
p : ndarray
|
510 |
+
`a` with its axes permuted. A view is returned whenever
|
511 |
+
possible.
|
512 |
+
|
513 |
+
See Also
|
514 |
+
--------
|
515 |
+
rollaxis
|
516 |
+
|
517 |
+
Examples
|
518 |
+
--------
|
519 |
+
>>> x = np.arange(4).reshape((2,2))
|
520 |
+
>>> x
|
521 |
+
array([[0, 1],
|
522 |
+
[2, 3]])
|
523 |
+
|
524 |
+
>>> np.transpose(x)
|
525 |
+
array([[0, 2],
|
526 |
+
[1, 3]])
|
527 |
+
|
528 |
+
>>> x = np.ones((1, 2, 3))
|
529 |
+
>>> np.transpose(x, (1, 0, 2)).shape
|
530 |
+
(2, 1, 3)
|
531 |
+
|
532 |
+
"""
|
533 |
+
try:
|
534 |
+
transpose = a.transpose
|
535 |
+
except AttributeError:
|
536 |
+
return _wrapit(a, 'transpose', axes)
|
537 |
+
return transpose(axes)
|
538 |
+
|
539 |
+
|
540 |
+
def partition(a, kth, axis=-1, kind='introselect', order=None):
|
541 |
+
"""
|
542 |
+
Return a partitioned copy of an array.
|
543 |
+
|
544 |
+
Creates a copy of the array with its elements rearranged in such a way that
|
545 |
+
the value of the element in kth position is in the position it would be in
|
546 |
+
a sorted array. All elements smaller than the kth element are moved before
|
547 |
+
this element and all equal or greater are moved behind it. The ordering of
|
548 |
+
the elements in the two partitions is undefined.
|
549 |
+
|
550 |
+
.. versionadded:: 1.8.0
|
551 |
+
|
552 |
+
Parameters
|
553 |
+
----------
|
554 |
+
a : array_like
|
555 |
+
Array to be sorted.
|
556 |
+
kth : int or sequence of ints
|
557 |
+
Element index to partition by. The kth value of the element will be in
|
558 |
+
its final sorted position and all smaller elements will be moved before
|
559 |
+
it and all equal or greater elements behind it.
|
560 |
+
The order all elements in the partitions is undefined.
|
561 |
+
If provided with a sequence of kth it will partition all elements
|
562 |
+
indexed by kth of them into their sorted position at once.
|
563 |
+
axis : int or None, optional
|
564 |
+
Axis along which to sort. If None, the array is flattened before
|
565 |
+
sorting. The default is -1, which sorts along the last axis.
|
566 |
+
kind : {'introselect'}, optional
|
567 |
+
Selection algorithm. Default is 'introselect'.
|
568 |
+
order : list, optional
|
569 |
+
When `a` is a structured array, this argument specifies which fields
|
570 |
+
to compare first, second, and so on. This list does not need to
|
571 |
+
include all of the fields.
|
572 |
+
|
573 |
+
Returns
|
574 |
+
-------
|
575 |
+
partitioned_array : ndarray
|
576 |
+
Array of the same type and shape as `a`.
|
577 |
+
|
578 |
+
See Also
|
579 |
+
--------
|
580 |
+
ndarray.partition : Method to sort an array in-place.
|
581 |
+
argpartition : Indirect partition.
|
582 |
+
sort : Full sorting
|
583 |
+
|
584 |
+
Notes
|
585 |
+
-----
|
586 |
+
The various selection algorithms are characterized by their average speed,
|
587 |
+
worst case performance, work space size, and whether they are stable. A
|
588 |
+
stable sort keeps items with the same key in the same relative order. The
|
589 |
+
available algorithms have the following properties:
|
590 |
+
|
591 |
+
================= ======= ============= ============ =======
|
592 |
+
kind speed worst case work space stable
|
593 |
+
================= ======= ============= ============ =======
|
594 |
+
'introselect' 1 O(n) 0 no
|
595 |
+
================= ======= ============= ============ =======
|
596 |
+
|
597 |
+
All the partition algorithms make temporary copies of the data when
|
598 |
+
partitioning along any but the last axis. Consequently, partitioning
|
599 |
+
along the last axis is faster and uses less space than partitioning
|
600 |
+
along any other axis.
|
601 |
+
|
602 |
+
The sort order for complex numbers is lexicographic. If both the real
|
603 |
+
and imaginary parts are non-nan then the order is determined by the
|
604 |
+
real parts except when they are equal, in which case the order is
|
605 |
+
determined by the imaginary parts.
|
606 |
+
|
607 |
+
Examples
|
608 |
+
--------
|
609 |
+
>>> a = np.array([3, 4, 2, 1])
|
610 |
+
>>> np.partition(a, 3)
|
611 |
+
array([2, 1, 3, 4])
|
612 |
+
|
613 |
+
>>> np.partition(a, (1, 3))
|
614 |
+
array([1, 2, 3, 4])
|
615 |
+
|
616 |
+
"""
|
617 |
+
if axis is None:
|
618 |
+
a = asanyarray(a).flatten()
|
619 |
+
axis = 0
|
620 |
+
else:
|
621 |
+
a = asanyarray(a).copy(order="K")
|
622 |
+
a.partition(kth, axis=axis, kind=kind, order=order)
|
623 |
+
return a
|
624 |
+
|
625 |
+
|
626 |
+
def argpartition(a, kth, axis=-1, kind='introselect', order=None):
|
627 |
+
"""
|
628 |
+
Perform an indirect partition along the given axis using the algorithm
|
629 |
+
specified by the `kind` keyword. It returns an array of indices of the
|
630 |
+
same shape as `a` that index data along the given axis in partitioned
|
631 |
+
order.
|
632 |
+
|
633 |
+
.. versionadded:: 1.8.0
|
634 |
+
|
635 |
+
Parameters
|
636 |
+
----------
|
637 |
+
a : array_like
|
638 |
+
Array to sort.
|
639 |
+
kth : int or sequence of ints
|
640 |
+
Element index to partition by. The kth element will be in its final
|
641 |
+
sorted position and all smaller elements will be moved before it and
|
642 |
+
all larger elements behind it.
|
643 |
+
The order all elements in the partitions is undefined.
|
644 |
+
If provided with a sequence of kth it will partition all of them into
|
645 |
+
their sorted position at once.
|
646 |
+
axis : int or None, optional
|
647 |
+
Axis along which to sort. The default is -1 (the last axis). If None,
|
648 |
+
the flattened array is used.
|
649 |
+
kind : {'introselect'}, optional
|
650 |
+
Selection algorithm. Default is 'introselect'
|
651 |
+
order : list, optional
|
652 |
+
When `a` is an array with fields defined, this argument specifies
|
653 |
+
which fields to compare first, second, etc. Not all fields need be
|
654 |
+
specified.
|
655 |
+
|
656 |
+
Returns
|
657 |
+
-------
|
658 |
+
index_array : ndarray, int
|
659 |
+
Array of indices that partition `a` along the specified axis.
|
660 |
+
In other words, ``a[index_array]`` yields a sorted `a`.
|
661 |
+
|
662 |
+
See Also
|
663 |
+
--------
|
664 |
+
partition : Describes partition algorithms used.
|
665 |
+
ndarray.partition : Inplace partition.
|
666 |
+
argsort : Full indirect sort
|
667 |
+
|
668 |
+
Notes
|
669 |
+
-----
|
670 |
+
See `partition` for notes on the different selection algorithms.
|
671 |
+
|
672 |
+
Examples
|
673 |
+
--------
|
674 |
+
One dimensional array:
|
675 |
+
|
676 |
+
>>> x = np.array([3, 4, 2, 1])
|
677 |
+
>>> x[np.argpartition(x, 3)]
|
678 |
+
array([2, 1, 3, 4])
|
679 |
+
>>> x[np.argpartition(x, (1, 3))]
|
680 |
+
array([1, 2, 3, 4])
|
681 |
+
|
682 |
+
"""
|
683 |
+
return a.argpartition(kth, axis, kind=kind, order=order)
|
684 |
+
|
685 |
+
|
686 |
+
def sort(a, axis=-1, kind='quicksort', order=None):
|
687 |
+
"""
|
688 |
+
Return a sorted copy of an array.
|
689 |
+
|
690 |
+
Parameters
|
691 |
+
----------
|
692 |
+
a : array_like
|
693 |
+
Array to be sorted.
|
694 |
+
axis : int or None, optional
|
695 |
+
Axis along which to sort. If None, the array is flattened before
|
696 |
+
sorting. The default is -1, which sorts along the last axis.
|
697 |
+
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
|
698 |
+
Sorting algorithm. Default is 'quicksort'.
|
699 |
+
order : list, optional
|
700 |
+
When `a` is a structured array, this argument specifies which fields
|
701 |
+
to compare first, second, and so on. This list does not need to
|
702 |
+
include all of the fields.
|
703 |
+
|
704 |
+
Returns
|
705 |
+
-------
|
706 |
+
sorted_array : ndarray
|
707 |
+
Array of the same type and shape as `a`.
|
708 |
+
|
709 |
+
See Also
|
710 |
+
--------
|
711 |
+
ndarray.sort : Method to sort an array in-place.
|
712 |
+
argsort : Indirect sort.
|
713 |
+
lexsort : Indirect stable sort on multiple keys.
|
714 |
+
searchsorted : Find elements in a sorted array.
|
715 |
+
partition : Partial sort.
|
716 |
+
|
717 |
+
Notes
|
718 |
+
-----
|
719 |
+
The various sorting algorithms are characterized by their average speed,
|
720 |
+
worst case performance, work space size, and whether they are stable. A
|
721 |
+
stable sort keeps items with the same key in the same relative
|
722 |
+
order. The three available algorithms have the following
|
723 |
+
properties:
|
724 |
+
|
725 |
+
=========== ======= ============= ============ =======
|
726 |
+
kind speed worst case work space stable
|
727 |
+
=========== ======= ============= ============ =======
|
728 |
+
'quicksort' 1 O(n^2) 0 no
|
729 |
+
'mergesort' 2 O(n*log(n)) ~n/2 yes
|
730 |
+
'heapsort' 3 O(n*log(n)) 0 no
|
731 |
+
=========== ======= ============= ============ =======
|
732 |
+
|
733 |
+
All the sort algorithms make temporary copies of the data when
|
734 |
+
sorting along any but the last axis. Consequently, sorting along
|
735 |
+
the last axis is faster and uses less space than sorting along
|
736 |
+
any other axis.
|
737 |
+
|
738 |
+
The sort order for complex numbers is lexicographic. If both the real
|
739 |
+
and imaginary parts are non-nan then the order is determined by the
|
740 |
+
real parts except when they are equal, in which case the order is
|
741 |
+
determined by the imaginary parts.
|
742 |
+
|
743 |
+
Previous to numpy 1.4.0 sorting real and complex arrays containing nan
|
744 |
+
values led to undefined behaviour. In numpy versions >= 1.4.0 nan
|
745 |
+
values are sorted to the end. The extended sort order is:
|
746 |
+
|
747 |
+
* Real: [R, nan]
|
748 |
+
* Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
|
749 |
+
|
750 |
+
where R is a non-nan real value. Complex values with the same nan
|
751 |
+
placements are sorted according to the non-nan part if it exists.
|
752 |
+
Non-nan values are sorted as before.
|
753 |
+
|
754 |
+
Examples
|
755 |
+
--------
|
756 |
+
>>> a = np.array([[1,4],[3,1]])
|
757 |
+
>>> np.sort(a) # sort along the last axis
|
758 |
+
array([[1, 4],
|
759 |
+
[1, 3]])
|
760 |
+
>>> np.sort(a, axis=None) # sort the flattened array
|
761 |
+
array([1, 1, 3, 4])
|
762 |
+
>>> np.sort(a, axis=0) # sort along the first axis
|
763 |
+
array([[1, 1],
|
764 |
+
[3, 4]])
|
765 |
+
|
766 |
+
Use the `order` keyword to specify a field to use when sorting a
|
767 |
+
structured array:
|
768 |
+
|
769 |
+
>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
|
770 |
+
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
|
771 |
+
... ('Galahad', 1.7, 38)]
|
772 |
+
>>> a = np.array(values, dtype=dtype) # create a structured array
|
773 |
+
>>> np.sort(a, order='height') # doctest: +SKIP
|
774 |
+
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
|
775 |
+
('Lancelot', 1.8999999999999999, 38)],
|
776 |
+
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
|
777 |
+
|
778 |
+
Sort by age, then height if ages are equal:
|
779 |
+
|
780 |
+
>>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
|
781 |
+
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
|
782 |
+
('Arthur', 1.8, 41)],
|
783 |
+
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
|
784 |
+
|
785 |
+
"""
|
786 |
+
if axis is None:
|
787 |
+
a = asanyarray(a).flatten()
|
788 |
+
axis = 0
|
789 |
+
else:
|
790 |
+
a = asanyarray(a).copy(order="K")
|
791 |
+
a.sort(axis, kind, order)
|
792 |
+
return a
|
793 |
+
|
794 |
+
|
795 |
+
def argsort(a, axis=-1, kind='quicksort', order=None):
|
796 |
+
"""
|
797 |
+
Returns the indices that would sort an array.
|
798 |
+
|
799 |
+
Perform an indirect sort along the given axis using the algorithm specified
|
800 |
+
by the `kind` keyword. It returns an array of indices of the same shape as
|
801 |
+
`a` that index data along the given axis in sorted order.
|
802 |
+
|
803 |
+
Parameters
|
804 |
+
----------
|
805 |
+
a : array_like
|
806 |
+
Array to sort.
|
807 |
+
axis : int or None, optional
|
808 |
+
Axis along which to sort. The default is -1 (the last axis). If None,
|
809 |
+
the flattened array is used.
|
810 |
+
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
|
811 |
+
Sorting algorithm.
|
812 |
+
order : list, optional
|
813 |
+
When `a` is an array with fields defined, this argument specifies
|
814 |
+
which fields to compare first, second, etc. Not all fields need be
|
815 |
+
specified.
|
816 |
+
|
817 |
+
Returns
|
818 |
+
-------
|
819 |
+
index_array : ndarray, int
|
820 |
+
Array of indices that sort `a` along the specified axis.
|
821 |
+
In other words, ``a[index_array]`` yields a sorted `a`.
|
822 |
+
|
823 |
+
See Also
|
824 |
+
--------
|
825 |
+
sort : Describes sorting algorithms used.
|
826 |
+
lexsort : Indirect stable sort with multiple keys.
|
827 |
+
ndarray.sort : Inplace sort.
|
828 |
+
argpartition : Indirect partial sort.
|
829 |
+
|
830 |
+
Notes
|
831 |
+
-----
|
832 |
+
See `sort` for notes on the different sorting algorithms.
|
833 |
+
|
834 |
+
As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
|
835 |
+
nan values. The enhanced sort order is documented in `sort`.
|
836 |
+
|
837 |
+
Examples
|
838 |
+
--------
|
839 |
+
One dimensional array:
|
840 |
+
|
841 |
+
>>> x = np.array([3, 1, 2])
|
842 |
+
>>> np.argsort(x)
|
843 |
+
array([1, 2, 0])
|
844 |
+
|
845 |
+
Two-dimensional array:
|
846 |
+
|
847 |
+
>>> x = np.array([[0, 3], [2, 2]])
|
848 |
+
>>> x
|
849 |
+
array([[0, 3],
|
850 |
+
[2, 2]])
|
851 |
+
|
852 |
+
>>> np.argsort(x, axis=0)
|
853 |
+
array([[0, 1],
|
854 |
+
[1, 0]])
|
855 |
+
|
856 |
+
>>> np.argsort(x, axis=1)
|
857 |
+
array([[0, 1],
|
858 |
+
[0, 1]])
|
859 |
+
|
860 |
+
Sorting with keys:
|
861 |
+
|
862 |
+
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
|
863 |
+
>>> x
|
864 |
+
array([(1, 0), (0, 1)],
|
865 |
+
dtype=[('x', '<i4'), ('y', '<i4')])
|
866 |
+
|
867 |
+
>>> np.argsort(x, order=('x','y'))
|
868 |
+
array([1, 0])
|
869 |
+
|
870 |
+
>>> np.argsort(x, order=('y','x'))
|
871 |
+
array([0, 1])
|
872 |
+
|
873 |
+
"""
|
874 |
+
try:
|
875 |
+
argsort = a.argsort
|
876 |
+
except AttributeError:
|
877 |
+
return _wrapit(a, 'argsort', axis, kind, order)
|
878 |
+
return argsort(axis, kind, order)
|
879 |
+
|
880 |
+
|
881 |
+
def argmax(a, axis=None):
|
882 |
+
"""
|
883 |
+
Indices of the maximum values along an axis.
|
884 |
+
|
885 |
+
Parameters
|
886 |
+
----------
|
887 |
+
a : array_like
|
888 |
+
Input array.
|
889 |
+
axis : int, optional
|
890 |
+
By default, the index is into the flattened array, otherwise
|
891 |
+
along the specified axis.
|
892 |
+
|
893 |
+
Returns
|
894 |
+
-------
|
895 |
+
index_array : ndarray of ints
|
896 |
+
Array of indices into the array. It has the same shape as `a.shape`
|
897 |
+
with the dimension along `axis` removed.
|
898 |
+
|
899 |
+
See Also
|
900 |
+
--------
|
901 |
+
ndarray.argmax, argmin
|
902 |
+
amax : The maximum value along a given axis.
|
903 |
+
unravel_index : Convert a flat index into an index tuple.
|
904 |
+
|
905 |
+
Notes
|
906 |
+
-----
|
907 |
+
In case of multiple occurrences of the maximum values, the indices
|
908 |
+
corresponding to the first occurrence are returned.
|
909 |
+
|
910 |
+
Examples
|
911 |
+
--------
|
912 |
+
>>> a = np.arange(6).reshape(2,3)
|
913 |
+
>>> a
|
914 |
+
array([[0, 1, 2],
|
915 |
+
[3, 4, 5]])
|
916 |
+
>>> np.argmax(a)
|
917 |
+
5
|
918 |
+
>>> np.argmax(a, axis=0)
|
919 |
+
array([1, 1, 1])
|
920 |
+
>>> np.argmax(a, axis=1)
|
921 |
+
array([2, 2])
|
922 |
+
|
923 |
+
>>> b = np.arange(6)
|
924 |
+
>>> b[1] = 5
|
925 |
+
>>> b
|
926 |
+
array([0, 5, 2, 3, 4, 5])
|
927 |
+
>>> np.argmax(b) # Only the first occurrence is returned.
|
928 |
+
1
|
929 |
+
|
930 |
+
"""
|
931 |
+
try:
|
932 |
+
argmax = a.argmax
|
933 |
+
except AttributeError:
|
934 |
+
return _wrapit(a, 'argmax', axis)
|
935 |
+
return argmax(axis)
|
936 |
+
|
937 |
+
|
938 |
+
def argmin(a, axis=None):
|
939 |
+
"""
|
940 |
+
Return the indices of the minimum values along an axis.
|
941 |
+
|
942 |
+
See Also
|
943 |
+
--------
|
944 |
+
argmax : Similar function. Please refer to `numpy.argmax` for detailed
|
945 |
+
documentation.
|
946 |
+
|
947 |
+
"""
|
948 |
+
try:
|
949 |
+
argmin = a.argmin
|
950 |
+
except AttributeError:
|
951 |
+
return _wrapit(a, 'argmin', axis)
|
952 |
+
return argmin(axis)
|
953 |
+
|
954 |
+
|
955 |
+
def searchsorted(a, v, side='left', sorter=None):
|
956 |
+
"""
|
957 |
+
Find indices where elements should be inserted to maintain order.
|
958 |
+
|
959 |
+
Find the indices into a sorted array `a` such that, if the
|
960 |
+
corresponding elements in `v` were inserted before the indices, the
|
961 |
+
order of `a` would be preserved.
|
962 |
+
|
963 |
+
Parameters
|
964 |
+
----------
|
965 |
+
a : 1-D array_like
|
966 |
+
Input array. If `sorter` is None, then it must be sorted in
|
967 |
+
ascending order, otherwise `sorter` must be an array of indices
|
968 |
+
that sort it.
|
969 |
+
v : array_like
|
970 |
+
Values to insert into `a`.
|
971 |
+
side : {'left', 'right'}, optional
|
972 |
+
If 'left', the index of the first suitable location found is given.
|
973 |
+
If 'right', return the last such index. If there is no suitable
|
974 |
+
index, return either 0 or N (where N is the length of `a`).
|
975 |
+
sorter : 1-D array_like, optional
|
976 |
+
.. versionadded:: 1.7.0
|
977 |
+
Optional array of integer indices that sort array a into ascending
|
978 |
+
order. They are typically the result of argsort.
|
979 |
+
|
980 |
+
Returns
|
981 |
+
-------
|
982 |
+
indices : array of ints
|
983 |
+
Array of insertion points with the same shape as `v`.
|
984 |
+
|
985 |
+
See Also
|
986 |
+
--------
|
987 |
+
sort : Return a sorted copy of an array.
|
988 |
+
histogram : Produce histogram from 1-D data.
|
989 |
+
|
990 |
+
Notes
|
991 |
+
-----
|
992 |
+
Binary search is used to find the required insertion points.
|
993 |
+
|
994 |
+
As of Numpy 1.4.0 `searchsorted` works with real/complex arrays containing
|
995 |
+
`nan` values. The enhanced sort order is documented in `sort`.
|
996 |
+
|
997 |
+
Examples
|
998 |
+
--------
|
999 |
+
>>> np.searchsorted([1,2,3,4,5], 3)
|
1000 |
+
2
|
1001 |
+
>>> np.searchsorted([1,2,3,4,5], 3, side='right')
|
1002 |
+
3
|
1003 |
+
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
|
1004 |
+
array([0, 5, 1, 2])
|
1005 |
+
|
1006 |
+
"""
|
1007 |
+
try:
|
1008 |
+
searchsorted = a.searchsorted
|
1009 |
+
except AttributeError:
|
1010 |
+
return _wrapit(a, 'searchsorted', v, side, sorter)
|
1011 |
+
return searchsorted(v, side, sorter)
|
1012 |
+
|
1013 |
+
|
1014 |
+
def resize(a, new_shape):
|
1015 |
+
"""
|
1016 |
+
Return a new array with the specified shape.
|
1017 |
+
|
1018 |
+
If the new array is larger than the original array, then the new
|
1019 |
+
array is filled with repeated copies of `a`. Note that this behavior
|
1020 |
+
is different from a.resize(new_shape) which fills with zeros instead
|
1021 |
+
of repeated copies of `a`.
|
1022 |
+
|
1023 |
+
Parameters
|
1024 |
+
----------
|
1025 |
+
a : array_like
|
1026 |
+
Array to be resized.
|
1027 |
+
|
1028 |
+
new_shape : int or tuple of int
|
1029 |
+
Shape of resized array.
|
1030 |
+
|
1031 |
+
Returns
|
1032 |
+
-------
|
1033 |
+
reshaped_array : ndarray
|
1034 |
+
The new array is formed from the data in the old array, repeated
|
1035 |
+
if necessary to fill out the required number of elements. The
|
1036 |
+
data are repeated in the order that they are stored in memory.
|
1037 |
+
|
1038 |
+
See Also
|
1039 |
+
--------
|
1040 |
+
ndarray.resize : resize an array in-place.
|
1041 |
+
|
1042 |
+
Examples
|
1043 |
+
--------
|
1044 |
+
>>> a=np.array([[0,1],[2,3]])
|
1045 |
+
>>> np.resize(a,(1,4))
|
1046 |
+
array([[0, 1, 2, 3]])
|
1047 |
+
>>> np.resize(a,(2,4))
|
1048 |
+
array([[0, 1, 2, 3],
|
1049 |
+
[0, 1, 2, 3]])
|
1050 |
+
|
1051 |
+
"""
|
1052 |
+
if isinstance(new_shape, (int, nt.integer)):
|
1053 |
+
new_shape = (new_shape,)
|
1054 |
+
a = ravel(a)
|
1055 |
+
Na = len(a)
|
1056 |
+
if not Na: return mu.zeros(new_shape, a.dtype.char)
|
1057 |
+
total_size = um.multiply.reduce(new_shape)
|
1058 |
+
n_copies = int(total_size / Na)
|
1059 |
+
extra = total_size % Na
|
1060 |
+
|
1061 |
+
if total_size == 0:
|
1062 |
+
return a[:0]
|
1063 |
+
|
1064 |
+
if extra != 0:
|
1065 |
+
n_copies = n_copies+1
|
1066 |
+
extra = Na-extra
|
1067 |
+
|
1068 |
+
a = concatenate( (a,)*n_copies)
|
1069 |
+
if extra > 0:
|
1070 |
+
a = a[:-extra]
|
1071 |
+
|
1072 |
+
return reshape(a, new_shape)
|
1073 |
+
|
1074 |
+
|
1075 |
+
def squeeze(a, axis=None):
|
1076 |
+
"""
|
1077 |
+
Remove single-dimensional entries from the shape of an array.
|
1078 |
+
|
1079 |
+
Parameters
|
1080 |
+
----------
|
1081 |
+
a : array_like
|
1082 |
+
Input data.
|
1083 |
+
axis : None or int or tuple of ints, optional
|
1084 |
+
.. versionadded:: 1.7.0
|
1085 |
+
|
1086 |
+
Selects a subset of the single-dimensional entries in the
|
1087 |
+
shape. If an axis is selected with shape entry greater than
|
1088 |
+
one, an error is raised.
|
1089 |
+
|
1090 |
+
Returns
|
1091 |
+
-------
|
1092 |
+
squeezed : ndarray
|
1093 |
+
The input array, but with all or a subset of the
|
1094 |
+
dimensions of length 1 removed. This is always `a` itself
|
1095 |
+
or a view into `a`.
|
1096 |
+
|
1097 |
+
Examples
|
1098 |
+
--------
|
1099 |
+
>>> x = np.array([[[0], [1], [2]]])
|
1100 |
+
>>> x.shape
|
1101 |
+
(1, 3, 1)
|
1102 |
+
>>> np.squeeze(x).shape
|
1103 |
+
(3,)
|
1104 |
+
>>> np.squeeze(x, axis=(2,)).shape
|
1105 |
+
(1, 3)
|
1106 |
+
|
1107 |
+
"""
|
1108 |
+
try:
|
1109 |
+
squeeze = a.squeeze
|
1110 |
+
except AttributeError:
|
1111 |
+
return _wrapit(a, 'squeeze')
|
1112 |
+
try:
|
1113 |
+
# First try to use the new axis= parameter
|
1114 |
+
return squeeze(axis=axis)
|
1115 |
+
except TypeError:
|
1116 |
+
# For backwards compatibility
|
1117 |
+
return squeeze()
|
1118 |
+
|
1119 |
+
|
1120 |
+
def diagonal(a, offset=0, axis1=0, axis2=1):
|
1121 |
+
"""
|
1122 |
+
Return specified diagonals.
|
1123 |
+
|
1124 |
+
If `a` is 2-D, returns the diagonal of `a` with the given offset,
|
1125 |
+
i.e., the collection of elements of the form ``a[i, i+offset]``. If
|
1126 |
+
`a` has more than two dimensions, then the axes specified by `axis1`
|
1127 |
+
and `axis2` are used to determine the 2-D sub-array whose diagonal is
|
1128 |
+
returned. The shape of the resulting array can be determined by
|
1129 |
+
removing `axis1` and `axis2` and appending an index to the right equal
|
1130 |
+
to the size of the resulting diagonals.
|
1131 |
+
|
1132 |
+
In versions of NumPy prior to 1.7, this function always returned a new,
|
1133 |
+
independent array containing a copy of the values in the diagonal.
|
1134 |
+
|
1135 |
+
In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
|
1136 |
+
but depending on this fact is deprecated. Writing to the resulting
|
1137 |
+
array continues to work as it used to, but a FutureWarning is issued.
|
1138 |
+
|
1139 |
+
In NumPy 1.9 it returns a read-only view on the original array.
|
1140 |
+
Attempting to write to the resulting array will produce an error.
|
1141 |
+
|
1142 |
+
In NumPy 1.10, it will return a read/write view, Writing to the returned
|
1143 |
+
array will alter your original array.
|
1144 |
+
|
1145 |
+
If you don't write to the array returned by this function, then you can
|
1146 |
+
just ignore all of the above.
|
1147 |
+
|
1148 |
+
If you depend on the current behavior, then we suggest copying the
|
1149 |
+
returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead of
|
1150 |
+
just ``np.diagonal(a)``. This will work with both past and future versions
|
1151 |
+
of NumPy.
|
1152 |
+
|
1153 |
+
Parameters
|
1154 |
+
----------
|
1155 |
+
a : array_like
|
1156 |
+
Array from which the diagonals are taken.
|
1157 |
+
offset : int, optional
|
1158 |
+
Offset of the diagonal from the main diagonal. Can be positive or
|
1159 |
+
negative. Defaults to main diagonal (0).
|
1160 |
+
axis1 : int, optional
|
1161 |
+
Axis to be used as the first axis of the 2-D sub-arrays from which
|
1162 |
+
the diagonals should be taken. Defaults to first axis (0).
|
1163 |
+
axis2 : int, optional
|
1164 |
+
Axis to be used as the second axis of the 2-D sub-arrays from
|
1165 |
+
which the diagonals should be taken. Defaults to second axis (1).
|
1166 |
+
|
1167 |
+
Returns
|
1168 |
+
-------
|
1169 |
+
array_of_diagonals : ndarray
|
1170 |
+
If `a` is 2-D, a 1-D array containing the diagonal is returned.
|
1171 |
+
If the dimension of `a` is larger, then an array of diagonals is
|
1172 |
+
returned, "packed" from left-most dimension to right-most (e.g.,
|
1173 |
+
if `a` is 3-D, then the diagonals are "packed" along rows).
|
1174 |
+
|
1175 |
+
Raises
|
1176 |
+
------
|
1177 |
+
ValueError
|
1178 |
+
If the dimension of `a` is less than 2.
|
1179 |
+
|
1180 |
+
See Also
|
1181 |
+
--------
|
1182 |
+
diag : MATLAB work-a-like for 1-D and 2-D arrays.
|
1183 |
+
diagflat : Create diagonal arrays.
|
1184 |
+
trace : Sum along diagonals.
|
1185 |
+
|
1186 |
+
Examples
|
1187 |
+
--------
|
1188 |
+
>>> a = np.arange(4).reshape(2,2)
|
1189 |
+
>>> a
|
1190 |
+
array([[0, 1],
|
1191 |
+
[2, 3]])
|
1192 |
+
>>> a.diagonal()
|
1193 |
+
array([0, 3])
|
1194 |
+
>>> a.diagonal(1)
|
1195 |
+
array([1])
|
1196 |
+
|
1197 |
+
A 3-D example:
|
1198 |
+
|
1199 |
+
>>> a = np.arange(8).reshape(2,2,2); a
|
1200 |
+
array([[[0, 1],
|
1201 |
+
[2, 3]],
|
1202 |
+
[[4, 5],
|
1203 |
+
[6, 7]]])
|
1204 |
+
>>> a.diagonal(0, # Main diagonals of two arrays created by skipping
|
1205 |
+
... 0, # across the outer(left)-most axis last and
|
1206 |
+
... 1) # the "middle" (row) axis first.
|
1207 |
+
array([[0, 6],
|
1208 |
+
[1, 7]])
|
1209 |
+
|
1210 |
+
The sub-arrays whose main diagonals we just obtained; note that each
|
1211 |
+
corresponds to fixing the right-most (column) axis, and that the
|
1212 |
+
diagonals are "packed" in rows.
|
1213 |
+
|
1214 |
+
>>> a[:,:,0] # main diagonal is [0 6]
|
1215 |
+
array([[0, 2],
|
1216 |
+
[4, 6]])
|
1217 |
+
>>> a[:,:,1] # main diagonal is [1 7]
|
1218 |
+
array([[1, 3],
|
1219 |
+
[5, 7]])
|
1220 |
+
|
1221 |
+
"""
|
1222 |
+
return asarray(a).diagonal(offset, axis1, axis2)
|
1223 |
+
|
1224 |
+
|
1225 |
+
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
|
1226 |
+
"""
|
1227 |
+
Return the sum along diagonals of the array.
|
1228 |
+
|
1229 |
+
If `a` is 2-D, the sum along its diagonal with the given offset
|
1230 |
+
is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
|
1231 |
+
|
1232 |
+
If `a` has more than two dimensions, then the axes specified by axis1 and
|
1233 |
+
axis2 are used to determine the 2-D sub-arrays whose traces are returned.
|
1234 |
+
The shape of the resulting array is the same as that of `a` with `axis1`
|
1235 |
+
and `axis2` removed.
|
1236 |
+
|
1237 |
+
Parameters
|
1238 |
+
----------
|
1239 |
+
a : array_like
|
1240 |
+
Input array, from which the diagonals are taken.
|
1241 |
+
offset : int, optional
|
1242 |
+
Offset of the diagonal from the main diagonal. Can be both positive
|
1243 |
+
and negative. Defaults to 0.
|
1244 |
+
axis1, axis2 : int, optional
|
1245 |
+
Axes to be used as the first and second axis of the 2-D sub-arrays
|
1246 |
+
from which the diagonals should be taken. Defaults are the first two
|
1247 |
+
axes of `a`.
|
1248 |
+
dtype : dtype, optional
|
1249 |
+
Determines the data-type of the returned array and of the accumulator
|
1250 |
+
where the elements are summed. If dtype has the value None and `a` is
|
1251 |
+
of integer type of precision less than the default integer
|
1252 |
+
precision, then the default integer precision is used. Otherwise,
|
1253 |
+
the precision is the same as that of `a`.
|
1254 |
+
out : ndarray, optional
|
1255 |
+
Array into which the output is placed. Its type is preserved and
|
1256 |
+
it must be of the right shape to hold the output.
|
1257 |
+
|
1258 |
+
Returns
|
1259 |
+
-------
|
1260 |
+
sum_along_diagonals : ndarray
|
1261 |
+
If `a` is 2-D, the sum along the diagonal is returned. If `a` has
|
1262 |
+
larger dimensions, then an array of sums along diagonals is returned.
|
1263 |
+
|
1264 |
+
See Also
|
1265 |
+
--------
|
1266 |
+
diag, diagonal, diagflat
|
1267 |
+
|
1268 |
+
Examples
|
1269 |
+
--------
|
1270 |
+
>>> np.trace(np.eye(3))
|
1271 |
+
3.0
|
1272 |
+
>>> a = np.arange(8).reshape((2,2,2))
|
1273 |
+
>>> np.trace(a)
|
1274 |
+
array([6, 8])
|
1275 |
+
|
1276 |
+
>>> a = np.arange(24).reshape((2,2,2,3))
|
1277 |
+
>>> np.trace(a).shape
|
1278 |
+
(2, 3)
|
1279 |
+
|
1280 |
+
"""
|
1281 |
+
return asarray(a).trace(offset, axis1, axis2, dtype, out)
|
1282 |
+
|
1283 |
+
def ravel(a, order='C'):
|
1284 |
+
"""
|
1285 |
+
Return a flattened array.
|
1286 |
+
|
1287 |
+
A 1-D array, containing the elements of the input, is returned. A copy is
|
1288 |
+
made only if needed.
|
1289 |
+
|
1290 |
+
Parameters
|
1291 |
+
----------
|
1292 |
+
a : array_like
|
1293 |
+
Input array. The elements in `a` are read in the order specified by
|
1294 |
+
`order`, and packed as a 1-D array.
|
1295 |
+
order : {'C','F', 'A', 'K'}, optional
|
1296 |
+
The elements of `a` are read using this index order. 'C' means to
|
1297 |
+
index the elements in C-like order, with the last axis index changing
|
1298 |
+
fastest, back to the first axis index changing slowest. 'F' means to
|
1299 |
+
index the elements in Fortran-like index order, with the first index
|
1300 |
+
changing fastest, and the last index changing slowest. Note that the 'C'
|
1301 |
+
and 'F' options take no account of the memory layout of the underlying
|
1302 |
+
array, and only refer to the order of axis indexing. 'A' means to read
|
1303 |
+
the elements in Fortran-like index order if `a` is Fortran *contiguous*
|
1304 |
+
in memory, C-like order otherwise. 'K' means to read the elements in
|
1305 |
+
the order they occur in memory, except for reversing the data when
|
1306 |
+
strides are negative. By default, 'C' index order is used.
|
1307 |
+
|
1308 |
+
Returns
|
1309 |
+
-------
|
1310 |
+
1d_array : ndarray
|
1311 |
+
Output of the same dtype as `a`, and of shape ``(a.size,)``.
|
1312 |
+
|
1313 |
+
See Also
|
1314 |
+
--------
|
1315 |
+
ndarray.flat : 1-D iterator over an array.
|
1316 |
+
ndarray.flatten : 1-D array copy of the elements of an array
|
1317 |
+
in row-major order.
|
1318 |
+
|
1319 |
+
Notes
|
1320 |
+
-----
|
1321 |
+
In C-like (row-major) order, in two dimensions, the row index varies the
|
1322 |
+
slowest, and the column index the quickest. This can be generalized to
|
1323 |
+
multiple dimensions, where row-major order implies that the index along the
|
1324 |
+
first axis varies slowest, and the index along the last quickest. The
|
1325 |
+
opposite holds for Fortran-like, or column-major, index ordering.
|
1326 |
+
|
1327 |
+
Examples
|
1328 |
+
--------
|
1329 |
+
It is equivalent to ``reshape(-1, order=order)``.
|
1330 |
+
|
1331 |
+
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
|
1332 |
+
>>> print np.ravel(x)
|
1333 |
+
[1 2 3 4 5 6]
|
1334 |
+
|
1335 |
+
>>> print x.reshape(-1)
|
1336 |
+
[1 2 3 4 5 6]
|
1337 |
+
|
1338 |
+
>>> print np.ravel(x, order='F')
|
1339 |
+
[1 4 2 5 3 6]
|
1340 |
+
|
1341 |
+
When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
|
1342 |
+
|
1343 |
+
>>> print np.ravel(x.T)
|
1344 |
+
[1 4 2 5 3 6]
|
1345 |
+
>>> print np.ravel(x.T, order='A')
|
1346 |
+
[1 2 3 4 5 6]
|
1347 |
+
|
1348 |
+
When ``order`` is 'K', it will preserve orderings that are neither 'C'
|
1349 |
+
nor 'F', but won't reverse axes:
|
1350 |
+
|
1351 |
+
>>> a = np.arange(3)[::-1]; a
|
1352 |
+
array([2, 1, 0])
|
1353 |
+
>>> a.ravel(order='C')
|
1354 |
+
array([2, 1, 0])
|
1355 |
+
>>> a.ravel(order='K')
|
1356 |
+
array([2, 1, 0])
|
1357 |
+
|
1358 |
+
>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
|
1359 |
+
array([[[ 0, 2, 4],
|
1360 |
+
[ 1, 3, 5]],
|
1361 |
+
[[ 6, 8, 10],
|
1362 |
+
[ 7, 9, 11]]])
|
1363 |
+
>>> a.ravel(order='C')
|
1364 |
+
array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
|
1365 |
+
>>> a.ravel(order='K')
|
1366 |
+
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
|
1367 |
+
|
1368 |
+
"""
|
1369 |
+
return asarray(a).ravel(order)
|
1370 |
+
|
1371 |
+
|
1372 |
+
def nonzero(a):
|
1373 |
+
"""
|
1374 |
+
Return the indices of the elements that are non-zero.
|
1375 |
+
|
1376 |
+
Returns a tuple of arrays, one for each dimension of `a`, containing
|
1377 |
+
the indices of the non-zero elements in that dimension. The
|
1378 |
+
corresponding non-zero values can be obtained with::
|
1379 |
+
|
1380 |
+
a[nonzero(a)]
|
1381 |
+
|
1382 |
+
To group the indices by element, rather than dimension, use::
|
1383 |
+
|
1384 |
+
transpose(nonzero(a))
|
1385 |
+
|
1386 |
+
The result of this is always a 2-D array, with a row for
|
1387 |
+
each non-zero element.
|
1388 |
+
|
1389 |
+
Parameters
|
1390 |
+
----------
|
1391 |
+
a : array_like
|
1392 |
+
Input array.
|
1393 |
+
|
1394 |
+
Returns
|
1395 |
+
-------
|
1396 |
+
tuple_of_arrays : tuple
|
1397 |
+
Indices of elements that are non-zero.
|
1398 |
+
|
1399 |
+
See Also
|
1400 |
+
--------
|
1401 |
+
flatnonzero :
|
1402 |
+
Return indices that are non-zero in the flattened version of the input
|
1403 |
+
array.
|
1404 |
+
ndarray.nonzero :
|
1405 |
+
Equivalent ndarray method.
|
1406 |
+
count_nonzero :
|
1407 |
+
Counts the number of non-zero elements in the input array.
|
1408 |
+
|
1409 |
+
Examples
|
1410 |
+
--------
|
1411 |
+
>>> x = np.eye(3)
|
1412 |
+
>>> x
|
1413 |
+
array([[ 1., 0., 0.],
|
1414 |
+
[ 0., 1., 0.],
|
1415 |
+
[ 0., 0., 1.]])
|
1416 |
+
>>> np.nonzero(x)
|
1417 |
+
(array([0, 1, 2]), array([0, 1, 2]))
|
1418 |
+
|
1419 |
+
>>> x[np.nonzero(x)]
|
1420 |
+
array([ 1., 1., 1.])
|
1421 |
+
>>> np.transpose(np.nonzero(x))
|
1422 |
+
array([[0, 0],
|
1423 |
+
[1, 1],
|
1424 |
+
[2, 2]])
|
1425 |
+
|
1426 |
+
A common use for ``nonzero`` is to find the indices of an array, where
|
1427 |
+
a condition is True. Given an array `a`, the condition `a` > 3 is a
|
1428 |
+
boolean array and since False is interpreted as 0, np.nonzero(a > 3)
|
1429 |
+
yields the indices of the `a` where the condition is true.
|
1430 |
+
|
1431 |
+
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
|
1432 |
+
>>> a > 3
|
1433 |
+
array([[False, False, False],
|
1434 |
+
[ True, True, True],
|
1435 |
+
[ True, True, True]], dtype=bool)
|
1436 |
+
>>> np.nonzero(a > 3)
|
1437 |
+
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
1438 |
+
|
1439 |
+
The ``nonzero`` method of the boolean array can also be called.
|
1440 |
+
|
1441 |
+
>>> (a > 3).nonzero()
|
1442 |
+
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
1443 |
+
|
1444 |
+
"""
|
1445 |
+
try:
|
1446 |
+
nonzero = a.nonzero
|
1447 |
+
except AttributeError:
|
1448 |
+
res = _wrapit(a, 'nonzero')
|
1449 |
+
else:
|
1450 |
+
res = nonzero()
|
1451 |
+
return res
|
1452 |
+
|
1453 |
+
|
1454 |
+
def shape(a):
|
1455 |
+
"""
|
1456 |
+
Return the shape of an array.
|
1457 |
+
|
1458 |
+
Parameters
|
1459 |
+
----------
|
1460 |
+
a : array_like
|
1461 |
+
Input array.
|
1462 |
+
|
1463 |
+
Returns
|
1464 |
+
-------
|
1465 |
+
shape : tuple of ints
|
1466 |
+
The elements of the shape tuple give the lengths of the
|
1467 |
+
corresponding array dimensions.
|
1468 |
+
|
1469 |
+
See Also
|
1470 |
+
--------
|
1471 |
+
alen
|
1472 |
+
ndarray.shape : Equivalent array method.
|
1473 |
+
|
1474 |
+
Examples
|
1475 |
+
--------
|
1476 |
+
>>> np.shape(np.eye(3))
|
1477 |
+
(3, 3)
|
1478 |
+
>>> np.shape([[1, 2]])
|
1479 |
+
(1, 2)
|
1480 |
+
>>> np.shape([0])
|
1481 |
+
(1,)
|
1482 |
+
>>> np.shape(0)
|
1483 |
+
()
|
1484 |
+
|
1485 |
+
>>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
|
1486 |
+
>>> np.shape(a)
|
1487 |
+
(2,)
|
1488 |
+
>>> a.shape
|
1489 |
+
(2,)
|
1490 |
+
|
1491 |
+
"""
|
1492 |
+
try:
|
1493 |
+
result = a.shape
|
1494 |
+
except AttributeError:
|
1495 |
+
result = asarray(a).shape
|
1496 |
+
return result
|
1497 |
+
|
1498 |
+
|
1499 |
+
def compress(condition, a, axis=None, out=None):
|
1500 |
+
"""
|
1501 |
+
Return selected slices of an array along given axis.
|
1502 |
+
|
1503 |
+
When working along a given axis, a slice along that axis is returned in
|
1504 |
+
`output` for each index where `condition` evaluates to True. When
|
1505 |
+
working on a 1-D array, `compress` is equivalent to `extract`.
|
1506 |
+
|
1507 |
+
Parameters
|
1508 |
+
----------
|
1509 |
+
condition : 1-D array of bools
|
1510 |
+
Array that selects which entries to return. If len(condition)
|
1511 |
+
is less than the size of `a` along the given axis, then output is
|
1512 |
+
truncated to the length of the condition array.
|
1513 |
+
a : array_like
|
1514 |
+
Array from which to extract a part.
|
1515 |
+
axis : int, optional
|
1516 |
+
Axis along which to take slices. If None (default), work on the
|
1517 |
+
flattened array.
|
1518 |
+
out : ndarray, optional
|
1519 |
+
Output array. Its type is preserved and it must be of the right
|
1520 |
+
shape to hold the output.
|
1521 |
+
|
1522 |
+
Returns
|
1523 |
+
-------
|
1524 |
+
compressed_array : ndarray
|
1525 |
+
A copy of `a` without the slices along axis for which `condition`
|
1526 |
+
is false.
|
1527 |
+
|
1528 |
+
See Also
|
1529 |
+
--------
|
1530 |
+
take, choose, diag, diagonal, select
|
1531 |
+
ndarray.compress : Equivalent method in ndarray
|
1532 |
+
np.extract: Equivalent method when working on 1-D arrays
|
1533 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
1534 |
+
|
1535 |
+
Examples
|
1536 |
+
--------
|
1537 |
+
>>> a = np.array([[1, 2], [3, 4], [5, 6]])
|
1538 |
+
>>> a
|
1539 |
+
array([[1, 2],
|
1540 |
+
[3, 4],
|
1541 |
+
[5, 6]])
|
1542 |
+
>>> np.compress([0, 1], a, axis=0)
|
1543 |
+
array([[3, 4]])
|
1544 |
+
>>> np.compress([False, True, True], a, axis=0)
|
1545 |
+
array([[3, 4],
|
1546 |
+
[5, 6]])
|
1547 |
+
>>> np.compress([False, True], a, axis=1)
|
1548 |
+
array([[2],
|
1549 |
+
[4],
|
1550 |
+
[6]])
|
1551 |
+
|
1552 |
+
Working on the flattened array does not return slices along an axis but
|
1553 |
+
selects elements.
|
1554 |
+
|
1555 |
+
>>> np.compress([False, True], a)
|
1556 |
+
array([2])
|
1557 |
+
|
1558 |
+
"""
|
1559 |
+
try:
|
1560 |
+
compress = a.compress
|
1561 |
+
except AttributeError:
|
1562 |
+
return _wrapit(a, 'compress', condition, axis, out)
|
1563 |
+
return compress(condition, axis, out)
|
1564 |
+
|
1565 |
+
|
1566 |
+
def clip(a, a_min, a_max, out=None):
|
1567 |
+
"""
|
1568 |
+
Clip (limit) the values in an array.
|
1569 |
+
|
1570 |
+
Given an interval, values outside the interval are clipped to
|
1571 |
+
the interval edges. For example, if an interval of ``[0, 1]``
|
1572 |
+
is specified, values smaller than 0 become 0, and values larger
|
1573 |
+
than 1 become 1.
|
1574 |
+
|
1575 |
+
Parameters
|
1576 |
+
----------
|
1577 |
+
a : array_like
|
1578 |
+
Array containing elements to clip.
|
1579 |
+
a_min : scalar or array_like
|
1580 |
+
Minimum value.
|
1581 |
+
a_max : scalar or array_like
|
1582 |
+
Maximum value. If `a_min` or `a_max` are array_like, then they will
|
1583 |
+
be broadcasted to the shape of `a`.
|
1584 |
+
out : ndarray, optional
|
1585 |
+
The results will be placed in this array. It may be the input
|
1586 |
+
array for in-place clipping. `out` must be of the right shape
|
1587 |
+
to hold the output. Its type is preserved.
|
1588 |
+
|
1589 |
+
Returns
|
1590 |
+
-------
|
1591 |
+
clipped_array : ndarray
|
1592 |
+
An array with the elements of `a`, but where values
|
1593 |
+
< `a_min` are replaced with `a_min`, and those > `a_max`
|
1594 |
+
with `a_max`.
|
1595 |
+
|
1596 |
+
See Also
|
1597 |
+
--------
|
1598 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
1599 |
+
|
1600 |
+
Examples
|
1601 |
+
--------
|
1602 |
+
>>> a = np.arange(10)
|
1603 |
+
>>> np.clip(a, 1, 8)
|
1604 |
+
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
|
1605 |
+
>>> a
|
1606 |
+
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
1607 |
+
>>> np.clip(a, 3, 6, out=a)
|
1608 |
+
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
|
1609 |
+
>>> a = np.arange(10)
|
1610 |
+
>>> a
|
1611 |
+
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
1612 |
+
>>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
|
1613 |
+
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
|
1614 |
+
|
1615 |
+
"""
|
1616 |
+
try:
|
1617 |
+
clip = a.clip
|
1618 |
+
except AttributeError:
|
1619 |
+
return _wrapit(a, 'clip', a_min, a_max, out)
|
1620 |
+
return clip(a_min, a_max, out)
|
1621 |
+
|
1622 |
+
|
1623 |
+
def sum(a, axis=None, dtype=None, out=None, keepdims=False):
|
1624 |
+
"""
|
1625 |
+
Sum of array elements over a given axis.
|
1626 |
+
|
1627 |
+
Parameters
|
1628 |
+
----------
|
1629 |
+
a : array_like
|
1630 |
+
Elements to sum.
|
1631 |
+
axis : None or int or tuple of ints, optional
|
1632 |
+
Axis or axes along which a sum is performed.
|
1633 |
+
The default (`axis` = `None`) is perform a sum over all
|
1634 |
+
the dimensions of the input array. `axis` may be negative, in
|
1635 |
+
which case it counts from the last to the first axis.
|
1636 |
+
|
1637 |
+
.. versionadded:: 1.7.0
|
1638 |
+
|
1639 |
+
If this is a tuple of ints, a sum is performed on multiple
|
1640 |
+
axes, instead of a single axis or all the axes as before.
|
1641 |
+
dtype : dtype, optional
|
1642 |
+
The type of the returned array and of the accumulator in which
|
1643 |
+
the elements are summed. By default, the dtype of `a` is used.
|
1644 |
+
An exception is when `a` has an integer type with less precision
|
1645 |
+
than the default platform integer. In that case, the default
|
1646 |
+
platform integer is used instead.
|
1647 |
+
out : ndarray, optional
|
1648 |
+
Array into which the output is placed. By default, a new array is
|
1649 |
+
created. If `out` is given, it must be of the appropriate shape
|
1650 |
+
(the shape of `a` with `axis` removed, i.e.,
|
1651 |
+
``numpy.delete(a.shape, axis)``). Its type is preserved. See
|
1652 |
+
`doc.ufuncs` (Section "Output arguments") for more details.
|
1653 |
+
keepdims : bool, optional
|
1654 |
+
If this is set to True, the axes which are reduced are left
|
1655 |
+
in the result as dimensions with size one. With this option,
|
1656 |
+
the result will broadcast correctly against the original `arr`.
|
1657 |
+
|
1658 |
+
Returns
|
1659 |
+
-------
|
1660 |
+
sum_along_axis : ndarray
|
1661 |
+
An array with the same shape as `a`, with the specified
|
1662 |
+
axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
|
1663 |
+
is returned. If an output array is specified, a reference to
|
1664 |
+
`out` is returned.
|
1665 |
+
|
1666 |
+
See Also
|
1667 |
+
--------
|
1668 |
+
ndarray.sum : Equivalent method.
|
1669 |
+
|
1670 |
+
cumsum : Cumulative sum of array elements.
|
1671 |
+
|
1672 |
+
trapz : Integration of array values using the composite trapezoidal rule.
|
1673 |
+
|
1674 |
+
mean, average
|
1675 |
+
|
1676 |
+
Notes
|
1677 |
+
-----
|
1678 |
+
Arithmetic is modular when using integer types, and no error is
|
1679 |
+
raised on overflow.
|
1680 |
+
|
1681 |
+
Examples
|
1682 |
+
--------
|
1683 |
+
>>> np.sum([0.5, 1.5])
|
1684 |
+
2.0
|
1685 |
+
>>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
|
1686 |
+
1
|
1687 |
+
>>> np.sum([[0, 1], [0, 5]])
|
1688 |
+
6
|
1689 |
+
>>> np.sum([[0, 1], [0, 5]], axis=0)
|
1690 |
+
array([0, 6])
|
1691 |
+
>>> np.sum([[0, 1], [0, 5]], axis=1)
|
1692 |
+
array([1, 5])
|
1693 |
+
|
1694 |
+
If the accumulator is too small, overflow occurs:
|
1695 |
+
|
1696 |
+
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
|
1697 |
+
-128
|
1698 |
+
|
1699 |
+
"""
|
1700 |
+
if isinstance(a, _gentype):
|
1701 |
+
res = _sum_(a)
|
1702 |
+
if out is not None:
|
1703 |
+
out[...] = res
|
1704 |
+
return out
|
1705 |
+
return res
|
1706 |
+
elif type(a) is not mu.ndarray:
|
1707 |
+
try:
|
1708 |
+
sum = a.sum
|
1709 |
+
except AttributeError:
|
1710 |
+
return _methods._sum(a, axis=axis, dtype=dtype,
|
1711 |
+
out=out, keepdims=keepdims)
|
1712 |
+
# NOTE: Dropping the keepdims parameters here...
|
1713 |
+
return sum(axis=axis, dtype=dtype, out=out)
|
1714 |
+
else:
|
1715 |
+
return _methods._sum(a, axis=axis, dtype=dtype,
|
1716 |
+
out=out, keepdims=keepdims)
|
1717 |
+
|
1718 |
+
def product (a, axis=None, dtype=None, out=None, keepdims=False):
|
1719 |
+
"""
|
1720 |
+
Return the product of array elements over a given axis.
|
1721 |
+
|
1722 |
+
See Also
|
1723 |
+
--------
|
1724 |
+
prod : equivalent function; see for details.
|
1725 |
+
|
1726 |
+
"""
|
1727 |
+
return um.multiply.reduce(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
|
1728 |
+
|
1729 |
+
|
1730 |
+
def sometrue(a, axis=None, out=None, keepdims=False):
|
1731 |
+
"""
|
1732 |
+
Check whether some values are true.
|
1733 |
+
|
1734 |
+
Refer to `any` for full documentation.
|
1735 |
+
|
1736 |
+
See Also
|
1737 |
+
--------
|
1738 |
+
any : equivalent function
|
1739 |
+
|
1740 |
+
"""
|
1741 |
+
arr = asanyarray(a)
|
1742 |
+
|
1743 |
+
try:
|
1744 |
+
return arr.any(axis=axis, out=out, keepdims=keepdims)
|
1745 |
+
except TypeError:
|
1746 |
+
return arr.any(axis=axis, out=out)
|
1747 |
+
|
1748 |
+
def alltrue (a, axis=None, out=None, keepdims=False):
|
1749 |
+
"""
|
1750 |
+
Check if all elements of input array are true.
|
1751 |
+
|
1752 |
+
See Also
|
1753 |
+
--------
|
1754 |
+
numpy.all : Equivalent function; see for details.
|
1755 |
+
|
1756 |
+
"""
|
1757 |
+
arr = asanyarray(a)
|
1758 |
+
|
1759 |
+
try:
|
1760 |
+
return arr.all(axis=axis, out=out, keepdims=keepdims)
|
1761 |
+
except TypeError:
|
1762 |
+
return arr.all(axis=axis, out=out)
|
1763 |
+
|
1764 |
+
def any(a, axis=None, out=None, keepdims=False):
|
1765 |
+
"""
|
1766 |
+
Test whether any array element along a given axis evaluates to True.
|
1767 |
+
|
1768 |
+
Returns single boolean unless `axis` is not ``None``
|
1769 |
+
|
1770 |
+
Parameters
|
1771 |
+
----------
|
1772 |
+
a : array_like
|
1773 |
+
Input array or object that can be converted to an array.
|
1774 |
+
axis : None or int or tuple of ints, optional
|
1775 |
+
Axis or axes along which a logical OR reduction is performed.
|
1776 |
+
The default (`axis` = `None`) is to perform a logical OR over all
|
1777 |
+
the dimensions of the input array. `axis` may be negative, in
|
1778 |
+
which case it counts from the last to the first axis.
|
1779 |
+
|
1780 |
+
.. versionadded:: 1.7.0
|
1781 |
+
|
1782 |
+
If this is a tuple of ints, a reduction is performed on multiple
|
1783 |
+
axes, instead of a single axis or all the axes as before.
|
1784 |
+
out : ndarray, optional
|
1785 |
+
Alternate output array in which to place the result. It must have
|
1786 |
+
the same shape as the expected output and its type is preserved
|
1787 |
+
(e.g., if it is of type float, then it will remain so, returning
|
1788 |
+
1.0 for True and 0.0 for False, regardless of the type of `a`).
|
1789 |
+
See `doc.ufuncs` (Section "Output arguments") for details.
|
1790 |
+
keepdims : bool, optional
|
1791 |
+
If this is set to True, the axes which are reduced are left
|
1792 |
+
in the result as dimensions with size one. With this option,
|
1793 |
+
the result will broadcast correctly against the original `arr`.
|
1794 |
+
|
1795 |
+
Returns
|
1796 |
+
-------
|
1797 |
+
any : bool or ndarray
|
1798 |
+
A new boolean or `ndarray` is returned unless `out` is specified,
|
1799 |
+
in which case a reference to `out` is returned.
|
1800 |
+
|
1801 |
+
See Also
|
1802 |
+
--------
|
1803 |
+
ndarray.any : equivalent method
|
1804 |
+
|
1805 |
+
all : Test whether all elements along a given axis evaluate to True.
|
1806 |
+
|
1807 |
+
Notes
|
1808 |
+
-----
|
1809 |
+
Not a Number (NaN), positive infinity and negative infinity evaluate
|
1810 |
+
to `True` because these are not equal to zero.
|
1811 |
+
|
1812 |
+
Examples
|
1813 |
+
--------
|
1814 |
+
>>> np.any([[True, False], [True, True]])
|
1815 |
+
True
|
1816 |
+
|
1817 |
+
>>> np.any([[True, False], [False, False]], axis=0)
|
1818 |
+
array([ True, False], dtype=bool)
|
1819 |
+
|
1820 |
+
>>> np.any([-1, 0, 5])
|
1821 |
+
True
|
1822 |
+
|
1823 |
+
>>> np.any(np.nan)
|
1824 |
+
True
|
1825 |
+
|
1826 |
+
>>> o=np.array([False])
|
1827 |
+
>>> z=np.any([-1, 4, 5], out=o)
|
1828 |
+
>>> z, o
|
1829 |
+
(array([ True], dtype=bool), array([ True], dtype=bool))
|
1830 |
+
>>> # Check now that z is a reference to o
|
1831 |
+
>>> z is o
|
1832 |
+
True
|
1833 |
+
>>> id(z), id(o) # identity of z and o # doctest: +SKIP
|
1834 |
+
(191614240, 191614240)
|
1835 |
+
|
1836 |
+
"""
|
1837 |
+
arr = asanyarray(a)
|
1838 |
+
|
1839 |
+
try:
|
1840 |
+
return arr.any(axis=axis, out=out, keepdims=keepdims)
|
1841 |
+
except TypeError:
|
1842 |
+
return arr.any(axis=axis, out=out)
|
1843 |
+
|
1844 |
+
def all(a, axis=None, out=None, keepdims=False):
|
1845 |
+
"""
|
1846 |
+
Test whether all array elements along a given axis evaluate to True.
|
1847 |
+
|
1848 |
+
Parameters
|
1849 |
+
----------
|
1850 |
+
a : array_like
|
1851 |
+
Input array or object that can be converted to an array.
|
1852 |
+
axis : None or int or tuple of ints, optional
|
1853 |
+
Axis or axes along which a logical AND reduction is performed.
|
1854 |
+
The default (`axis` = `None`) is to perform a logical AND over all
|
1855 |
+
the dimensions of the input array. `axis` may be negative, in
|
1856 |
+
which case it counts from the last to the first axis.
|
1857 |
+
|
1858 |
+
.. versionadded:: 1.7.0
|
1859 |
+
|
1860 |
+
If this is a tuple of ints, a reduction is performed on multiple
|
1861 |
+
axes, instead of a single axis or all the axes as before.
|
1862 |
+
out : ndarray, optional
|
1863 |
+
Alternate output array in which to place the result.
|
1864 |
+
It must have the same shape as the expected output and its
|
1865 |
+
type is preserved (e.g., if ``dtype(out)`` is float, the result
|
1866 |
+
will consist of 0.0's and 1.0's). See `doc.ufuncs` (Section
|
1867 |
+
"Output arguments") for more details.
|
1868 |
+
keepdims : bool, optional
|
1869 |
+
If this is set to True, the axes which are reduced are left
|
1870 |
+
in the result as dimensions with size one. With this option,
|
1871 |
+
the result will broadcast correctly against the original `arr`.
|
1872 |
+
|
1873 |
+
Returns
|
1874 |
+
-------
|
1875 |
+
all : ndarray, bool
|
1876 |
+
A new boolean or array is returned unless `out` is specified,
|
1877 |
+
in which case a reference to `out` is returned.
|
1878 |
+
|
1879 |
+
See Also
|
1880 |
+
--------
|
1881 |
+
ndarray.all : equivalent method
|
1882 |
+
|
1883 |
+
any : Test whether any element along a given axis evaluates to True.
|
1884 |
+
|
1885 |
+
Notes
|
1886 |
+
-----
|
1887 |
+
Not a Number (NaN), positive infinity and negative infinity
|
1888 |
+
evaluate to `True` because these are not equal to zero.
|
1889 |
+
|
1890 |
+
Examples
|
1891 |
+
--------
|
1892 |
+
>>> np.all([[True,False],[True,True]])
|
1893 |
+
False
|
1894 |
+
|
1895 |
+
>>> np.all([[True,False],[True,True]], axis=0)
|
1896 |
+
array([ True, False], dtype=bool)
|
1897 |
+
|
1898 |
+
>>> np.all([-1, 4, 5])
|
1899 |
+
True
|
1900 |
+
|
1901 |
+
>>> np.all([1.0, np.nan])
|
1902 |
+
True
|
1903 |
+
|
1904 |
+
>>> o=np.array([False])
|
1905 |
+
>>> z=np.all([-1, 4, 5], out=o)
|
1906 |
+
>>> id(z), id(o), z # doctest: +SKIP
|
1907 |
+
(28293632, 28293632, array([ True], dtype=bool))
|
1908 |
+
|
1909 |
+
"""
|
1910 |
+
arr = asanyarray(a)
|
1911 |
+
|
1912 |
+
try:
|
1913 |
+
return arr.all(axis=axis, out=out, keepdims=keepdims)
|
1914 |
+
except TypeError:
|
1915 |
+
return arr.all(axis=axis, out=out)
|
1916 |
+
|
1917 |
+
def cumsum (a, axis=None, dtype=None, out=None):
|
1918 |
+
"""
|
1919 |
+
Return the cumulative sum of the elements along a given axis.
|
1920 |
+
|
1921 |
+
Parameters
|
1922 |
+
----------
|
1923 |
+
a : array_like
|
1924 |
+
Input array.
|
1925 |
+
axis : int, optional
|
1926 |
+
Axis along which the cumulative sum is computed. The default
|
1927 |
+
(None) is to compute the cumsum over the flattened array.
|
1928 |
+
dtype : dtype, optional
|
1929 |
+
Type of the returned array and of the accumulator in which the
|
1930 |
+
elements are summed. If `dtype` is not specified, it defaults
|
1931 |
+
to the dtype of `a`, unless `a` has an integer dtype with a
|
1932 |
+
precision less than that of the default platform integer. In
|
1933 |
+
that case, the default platform integer is used.
|
1934 |
+
out : ndarray, optional
|
1935 |
+
Alternative output array in which to place the result. It must
|
1936 |
+
have the same shape and buffer length as the expected output
|
1937 |
+
but the type will be cast if necessary. See `doc.ufuncs`
|
1938 |
+
(Section "Output arguments") for more details.
|
1939 |
+
|
1940 |
+
Returns
|
1941 |
+
-------
|
1942 |
+
cumsum_along_axis : ndarray.
|
1943 |
+
A new array holding the result is returned unless `out` is
|
1944 |
+
specified, in which case a reference to `out` is returned. The
|
1945 |
+
result has the same size as `a`, and the same shape as `a` if
|
1946 |
+
`axis` is not None or `a` is a 1-d array.
|
1947 |
+
|
1948 |
+
|
1949 |
+
See Also
|
1950 |
+
--------
|
1951 |
+
sum : Sum array elements.
|
1952 |
+
|
1953 |
+
trapz : Integration of array values using the composite trapezoidal rule.
|
1954 |
+
|
1955 |
+
diff : Calculate the n-th order discrete difference along given axis.
|
1956 |
+
|
1957 |
+
Notes
|
1958 |
+
-----
|
1959 |
+
Arithmetic is modular when using integer types, and no error is
|
1960 |
+
raised on overflow.
|
1961 |
+
|
1962 |
+
Examples
|
1963 |
+
--------
|
1964 |
+
>>> a = np.array([[1,2,3], [4,5,6]])
|
1965 |
+
>>> a
|
1966 |
+
array([[1, 2, 3],
|
1967 |
+
[4, 5, 6]])
|
1968 |
+
>>> np.cumsum(a)
|
1969 |
+
array([ 1, 3, 6, 10, 15, 21])
|
1970 |
+
>>> np.cumsum(a, dtype=float) # specifies type of output value(s)
|
1971 |
+
array([ 1., 3., 6., 10., 15., 21.])
|
1972 |
+
|
1973 |
+
>>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
|
1974 |
+
array([[1, 2, 3],
|
1975 |
+
[5, 7, 9]])
|
1976 |
+
>>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
|
1977 |
+
array([[ 1, 3, 6],
|
1978 |
+
[ 4, 9, 15]])
|
1979 |
+
|
1980 |
+
"""
|
1981 |
+
try:
|
1982 |
+
cumsum = a.cumsum
|
1983 |
+
except AttributeError:
|
1984 |
+
return _wrapit(a, 'cumsum', axis, dtype, out)
|
1985 |
+
return cumsum(axis, dtype, out)
|
1986 |
+
|
1987 |
+
|
1988 |
+
def cumproduct(a, axis=None, dtype=None, out=None):
|
1989 |
+
"""
|
1990 |
+
Return the cumulative product over the given axis.
|
1991 |
+
|
1992 |
+
|
1993 |
+
See Also
|
1994 |
+
--------
|
1995 |
+
cumprod : equivalent function; see for details.
|
1996 |
+
|
1997 |
+
"""
|
1998 |
+
try:
|
1999 |
+
cumprod = a.cumprod
|
2000 |
+
except AttributeError:
|
2001 |
+
return _wrapit(a, 'cumprod', axis, dtype, out)
|
2002 |
+
return cumprod(axis, dtype, out)
|
2003 |
+
|
2004 |
+
|
2005 |
+
def ptp(a, axis=None, out=None):
|
2006 |
+
"""
|
2007 |
+
Range of values (maximum - minimum) along an axis.
|
2008 |
+
|
2009 |
+
The name of the function comes from the acronym for 'peak to peak'.
|
2010 |
+
|
2011 |
+
Parameters
|
2012 |
+
----------
|
2013 |
+
a : array_like
|
2014 |
+
Input values.
|
2015 |
+
axis : int, optional
|
2016 |
+
Axis along which to find the peaks. By default, flatten the
|
2017 |
+
array.
|
2018 |
+
out : array_like
|
2019 |
+
Alternative output array in which to place the result. It must
|
2020 |
+
have the same shape and buffer length as the expected output,
|
2021 |
+
but the type of the output values will be cast if necessary.
|
2022 |
+
|
2023 |
+
Returns
|
2024 |
+
-------
|
2025 |
+
ptp : ndarray
|
2026 |
+
A new array holding the result, unless `out` was
|
2027 |
+
specified, in which case a reference to `out` is returned.
|
2028 |
+
|
2029 |
+
Examples
|
2030 |
+
--------
|
2031 |
+
>>> x = np.arange(4).reshape((2,2))
|
2032 |
+
>>> x
|
2033 |
+
array([[0, 1],
|
2034 |
+
[2, 3]])
|
2035 |
+
|
2036 |
+
>>> np.ptp(x, axis=0)
|
2037 |
+
array([2, 2])
|
2038 |
+
|
2039 |
+
>>> np.ptp(x, axis=1)
|
2040 |
+
array([1, 1])
|
2041 |
+
|
2042 |
+
"""
|
2043 |
+
try:
|
2044 |
+
ptp = a.ptp
|
2045 |
+
except AttributeError:
|
2046 |
+
return _wrapit(a, 'ptp', axis, out)
|
2047 |
+
return ptp(axis, out)
|
2048 |
+
|
2049 |
+
|
2050 |
+
def amax(a, axis=None, out=None, keepdims=False):
|
2051 |
+
"""
|
2052 |
+
Return the maximum of an array or maximum along an axis.
|
2053 |
+
|
2054 |
+
Parameters
|
2055 |
+
----------
|
2056 |
+
a : array_like
|
2057 |
+
Input data.
|
2058 |
+
axis : int, optional
|
2059 |
+
Axis along which to operate. By default, flattened input is used.
|
2060 |
+
out : ndarray, optional
|
2061 |
+
Alternative output array in which to place the result. Must
|
2062 |
+
be of the same shape and buffer length as the expected output.
|
2063 |
+
See `doc.ufuncs` (Section "Output arguments") for more details.
|
2064 |
+
keepdims : bool, optional
|
2065 |
+
If this is set to True, the axes which are reduced are left
|
2066 |
+
in the result as dimensions with size one. With this option,
|
2067 |
+
the result will broadcast correctly against the original `arr`.
|
2068 |
+
|
2069 |
+
Returns
|
2070 |
+
-------
|
2071 |
+
amax : ndarray or scalar
|
2072 |
+
Maximum of `a`. If `axis` is None, the result is a scalar value.
|
2073 |
+
If `axis` is given, the result is an array of dimension
|
2074 |
+
``a.ndim - 1``.
|
2075 |
+
|
2076 |
+
See Also
|
2077 |
+
--------
|
2078 |
+
amin :
|
2079 |
+
The minimum value of an array along a given axis, propagating any NaNs.
|
2080 |
+
nanmax :
|
2081 |
+
The maximum value of an array along a given axis, ignoring any NaNs.
|
2082 |
+
maximum :
|
2083 |
+
Element-wise maximum of two arrays, propagating any NaNs.
|
2084 |
+
fmax :
|
2085 |
+
Element-wise maximum of two arrays, ignoring any NaNs.
|
2086 |
+
argmax :
|
2087 |
+
Return the indices of the maximum values.
|
2088 |
+
|
2089 |
+
nanmin, minimum, fmin
|
2090 |
+
|
2091 |
+
Notes
|
2092 |
+
-----
|
2093 |
+
NaN values are propagated, that is if at least one item is NaN, the
|
2094 |
+
corresponding max value will be NaN as well. To ignore NaN values
|
2095 |
+
(MATLAB behavior), please use nanmax.
|
2096 |
+
|
2097 |
+
Don't use `amax` for element-wise comparison of 2 arrays; when
|
2098 |
+
``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
|
2099 |
+
``amax(a, axis=0)``.
|
2100 |
+
|
2101 |
+
Examples
|
2102 |
+
--------
|
2103 |
+
>>> a = np.arange(4).reshape((2,2))
|
2104 |
+
>>> a
|
2105 |
+
array([[0, 1],
|
2106 |
+
[2, 3]])
|
2107 |
+
>>> np.amax(a) # Maximum of the flattened array
|
2108 |
+
3
|
2109 |
+
>>> np.amax(a, axis=0) # Maxima along the first axis
|
2110 |
+
array([2, 3])
|
2111 |
+
>>> np.amax(a, axis=1) # Maxima along the second axis
|
2112 |
+
array([1, 3])
|
2113 |
+
|
2114 |
+
>>> b = np.arange(5, dtype=np.float)
|
2115 |
+
>>> b[2] = np.NaN
|
2116 |
+
>>> np.amax(b)
|
2117 |
+
nan
|
2118 |
+
>>> np.nanmax(b)
|
2119 |
+
4.0
|
2120 |
+
|
2121 |
+
"""
|
2122 |
+
if type(a) is not mu.ndarray:
|
2123 |
+
try:
|
2124 |
+
amax = a.max
|
2125 |
+
except AttributeError:
|
2126 |
+
return _methods._amax(a, axis=axis,
|
2127 |
+
out=out, keepdims=keepdims)
|
2128 |
+
# NOTE: Dropping the keepdims parameter
|
2129 |
+
return amax(axis=axis, out=out)
|
2130 |
+
else:
|
2131 |
+
return _methods._amax(a, axis=axis,
|
2132 |
+
out=out, keepdims=keepdims)
|
2133 |
+
|
2134 |
+
def amin(a, axis=None, out=None, keepdims=False):
|
2135 |
+
"""
|
2136 |
+
Return the minimum of an array or minimum along an axis.
|
2137 |
+
|
2138 |
+
Parameters
|
2139 |
+
----------
|
2140 |
+
a : array_like
|
2141 |
+
Input data.
|
2142 |
+
axis : int, optional
|
2143 |
+
Axis along which to operate. By default, flattened input is used.
|
2144 |
+
out : ndarray, optional
|
2145 |
+
Alternative output array in which to place the result. Must
|
2146 |
+
be of the same shape and buffer length as the expected output.
|
2147 |
+
See `doc.ufuncs` (Section "Output arguments") for more details.
|
2148 |
+
keepdims : bool, optional
|
2149 |
+
If this is set to True, the axes which are reduced are left
|
2150 |
+
in the result as dimensions with size one. With this option,
|
2151 |
+
the result will broadcast correctly against the original `arr`.
|
2152 |
+
|
2153 |
+
Returns
|
2154 |
+
-------
|
2155 |
+
amin : ndarray or scalar
|
2156 |
+
Minimum of `a`. If `axis` is None, the result is a scalar value.
|
2157 |
+
If `axis` is given, the result is an array of dimension
|
2158 |
+
``a.ndim - 1``.
|
2159 |
+
|
2160 |
+
See Also
|
2161 |
+
--------
|
2162 |
+
amax :
|
2163 |
+
The maximum value of an array along a given axis, propagating any NaNs.
|
2164 |
+
nanmin :
|
2165 |
+
The minimum value of an array along a given axis, ignoring any NaNs.
|
2166 |
+
minimum :
|
2167 |
+
Element-wise minimum of two arrays, propagating any NaNs.
|
2168 |
+
fmin :
|
2169 |
+
Element-wise minimum of two arrays, ignoring any NaNs.
|
2170 |
+
argmin :
|
2171 |
+
Return the indices of the minimum values.
|
2172 |
+
|
2173 |
+
nanmax, maximum, fmax
|
2174 |
+
|
2175 |
+
Notes
|
2176 |
+
-----
|
2177 |
+
NaN values are propagated, that is if at least one item is NaN, the
|
2178 |
+
corresponding min value will be NaN as well. To ignore NaN values
|
2179 |
+
(MATLAB behavior), please use nanmin.
|
2180 |
+
|
2181 |
+
Don't use `amin` for element-wise comparison of 2 arrays; when
|
2182 |
+
``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
|
2183 |
+
``amin(a, axis=0)``.
|
2184 |
+
|
2185 |
+
Examples
|
2186 |
+
--------
|
2187 |
+
>>> a = np.arange(4).reshape((2,2))
|
2188 |
+
>>> a
|
2189 |
+
array([[0, 1],
|
2190 |
+
[2, 3]])
|
2191 |
+
>>> np.amin(a) # Minimum of the flattened array
|
2192 |
+
0
|
2193 |
+
>>> np.amin(a, axis=0) # Minima along the first axis
|
2194 |
+
array([0, 1])
|
2195 |
+
>>> np.amin(a, axis=1) # Minima along the second axis
|
2196 |
+
array([0, 2])
|
2197 |
+
|
2198 |
+
>>> b = np.arange(5, dtype=np.float)
|
2199 |
+
>>> b[2] = np.NaN
|
2200 |
+
>>> np.amin(b)
|
2201 |
+
nan
|
2202 |
+
>>> np.nanmin(b)
|
2203 |
+
0.0
|
2204 |
+
|
2205 |
+
"""
|
2206 |
+
if type(a) is not mu.ndarray:
|
2207 |
+
try:
|
2208 |
+
amin = a.min
|
2209 |
+
except AttributeError:
|
2210 |
+
return _methods._amin(a, axis=axis,
|
2211 |
+
out=out, keepdims=keepdims)
|
2212 |
+
# NOTE: Dropping the keepdims parameter
|
2213 |
+
return amin(axis=axis, out=out)
|
2214 |
+
else:
|
2215 |
+
return _methods._amin(a, axis=axis,
|
2216 |
+
out=out, keepdims=keepdims)
|
2217 |
+
|
2218 |
+
def alen(a):
|
2219 |
+
"""
|
2220 |
+
Return the length of the first dimension of the input array.
|
2221 |
+
|
2222 |
+
Parameters
|
2223 |
+
----------
|
2224 |
+
a : array_like
|
2225 |
+
Input array.
|
2226 |
+
|
2227 |
+
Returns
|
2228 |
+
-------
|
2229 |
+
alen : int
|
2230 |
+
Length of the first dimension of `a`.
|
2231 |
+
|
2232 |
+
See Also
|
2233 |
+
--------
|
2234 |
+
shape, size
|
2235 |
+
|
2236 |
+
Examples
|
2237 |
+
--------
|
2238 |
+
>>> a = np.zeros((7,4,5))
|
2239 |
+
>>> a.shape[0]
|
2240 |
+
7
|
2241 |
+
>>> np.alen(a)
|
2242 |
+
7
|
2243 |
+
|
2244 |
+
"""
|
2245 |
+
try:
|
2246 |
+
return len(a)
|
2247 |
+
except TypeError:
|
2248 |
+
return len(array(a, ndmin=1))
|
2249 |
+
|
2250 |
+
|
2251 |
+
def prod(a, axis=None, dtype=None, out=None, keepdims=False):
|
2252 |
+
"""
|
2253 |
+
Return the product of array elements over a given axis.
|
2254 |
+
|
2255 |
+
Parameters
|
2256 |
+
----------
|
2257 |
+
a : array_like
|
2258 |
+
Input data.
|
2259 |
+
axis : None or int or tuple of ints, optional
|
2260 |
+
Axis or axes along which a product is performed.
|
2261 |
+
The default (`axis` = `None`) is perform a product over all
|
2262 |
+
the dimensions of the input array. `axis` may be negative, in
|
2263 |
+
which case it counts from the last to the first axis.
|
2264 |
+
|
2265 |
+
.. versionadded:: 1.7.0
|
2266 |
+
|
2267 |
+
If this is a tuple of ints, a product is performed on multiple
|
2268 |
+
axes, instead of a single axis or all the axes as before.
|
2269 |
+
dtype : data-type, optional
|
2270 |
+
The data-type of the returned array, as well as of the accumulator
|
2271 |
+
in which the elements are multiplied. By default, if `a` is of
|
2272 |
+
integer type, `dtype` is the default platform integer. (Note: if
|
2273 |
+
the type of `a` is unsigned, then so is `dtype`.) Otherwise,
|
2274 |
+
the dtype is the same as that of `a`.
|
2275 |
+
out : ndarray, optional
|
2276 |
+
Alternative output array in which to place the result. It must have
|
2277 |
+
the same shape as the expected output, but the type of the
|
2278 |
+
output values will be cast if necessary.
|
2279 |
+
keepdims : bool, optional
|
2280 |
+
If this is set to True, the axes which are reduced are left
|
2281 |
+
in the result as dimensions with size one. With this option,
|
2282 |
+
the result will broadcast correctly against the original `arr`.
|
2283 |
+
|
2284 |
+
Returns
|
2285 |
+
-------
|
2286 |
+
product_along_axis : ndarray, see `dtype` parameter above.
|
2287 |
+
An array shaped as `a` but with the specified axis removed.
|
2288 |
+
Returns a reference to `out` if specified.
|
2289 |
+
|
2290 |
+
See Also
|
2291 |
+
--------
|
2292 |
+
ndarray.prod : equivalent method
|
2293 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
2294 |
+
|
2295 |
+
Notes
|
2296 |
+
-----
|
2297 |
+
Arithmetic is modular when using integer types, and no error is
|
2298 |
+
raised on overflow. That means that, on a 32-bit platform:
|
2299 |
+
|
2300 |
+
>>> x = np.array([536870910, 536870910, 536870910, 536870910])
|
2301 |
+
>>> np.prod(x) #random
|
2302 |
+
16
|
2303 |
+
|
2304 |
+
Examples
|
2305 |
+
--------
|
2306 |
+
By default, calculate the product of all elements:
|
2307 |
+
|
2308 |
+
>>> np.prod([1.,2.])
|
2309 |
+
2.0
|
2310 |
+
|
2311 |
+
Even when the input array is two-dimensional:
|
2312 |
+
|
2313 |
+
>>> np.prod([[1.,2.],[3.,4.]])
|
2314 |
+
24.0
|
2315 |
+
|
2316 |
+
But we can also specify the axis over which to multiply:
|
2317 |
+
|
2318 |
+
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
|
2319 |
+
array([ 2., 12.])
|
2320 |
+
|
2321 |
+
If the type of `x` is unsigned, then the output type is
|
2322 |
+
the unsigned platform integer:
|
2323 |
+
|
2324 |
+
>>> x = np.array([1, 2, 3], dtype=np.uint8)
|
2325 |
+
>>> np.prod(x).dtype == np.uint
|
2326 |
+
True
|
2327 |
+
|
2328 |
+
If `x` is of a signed integer type, then the output type
|
2329 |
+
is the default platform integer:
|
2330 |
+
|
2331 |
+
>>> x = np.array([1, 2, 3], dtype=np.int8)
|
2332 |
+
>>> np.prod(x).dtype == np.int
|
2333 |
+
True
|
2334 |
+
|
2335 |
+
"""
|
2336 |
+
if type(a) is not mu.ndarray:
|
2337 |
+
try:
|
2338 |
+
prod = a.prod
|
2339 |
+
except AttributeError:
|
2340 |
+
return _methods._prod(a, axis=axis, dtype=dtype,
|
2341 |
+
out=out, keepdims=keepdims)
|
2342 |
+
return prod(axis=axis, dtype=dtype, out=out)
|
2343 |
+
else:
|
2344 |
+
return _methods._prod(a, axis=axis, dtype=dtype,
|
2345 |
+
out=out, keepdims=keepdims)
|
2346 |
+
|
2347 |
+
def cumprod(a, axis=None, dtype=None, out=None):
|
2348 |
+
"""
|
2349 |
+
Return the cumulative product of elements along a given axis.
|
2350 |
+
|
2351 |
+
Parameters
|
2352 |
+
----------
|
2353 |
+
a : array_like
|
2354 |
+
Input array.
|
2355 |
+
axis : int, optional
|
2356 |
+
Axis along which the cumulative product is computed. By default
|
2357 |
+
the input is flattened.
|
2358 |
+
dtype : dtype, optional
|
2359 |
+
Type of the returned array, as well as of the accumulator in which
|
2360 |
+
the elements are multiplied. If *dtype* is not specified, it
|
2361 |
+
defaults to the dtype of `a`, unless `a` has an integer dtype with
|
2362 |
+
a precision less than that of the default platform integer. In
|
2363 |
+
that case, the default platform integer is used instead.
|
2364 |
+
out : ndarray, optional
|
2365 |
+
Alternative output array in which to place the result. It must
|
2366 |
+
have the same shape and buffer length as the expected output
|
2367 |
+
but the type of the resulting values will be cast if necessary.
|
2368 |
+
|
2369 |
+
Returns
|
2370 |
+
-------
|
2371 |
+
cumprod : ndarray
|
2372 |
+
A new array holding the result is returned unless `out` is
|
2373 |
+
specified, in which case a reference to out is returned.
|
2374 |
+
|
2375 |
+
See Also
|
2376 |
+
--------
|
2377 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
2378 |
+
|
2379 |
+
Notes
|
2380 |
+
-----
|
2381 |
+
Arithmetic is modular when using integer types, and no error is
|
2382 |
+
raised on overflow.
|
2383 |
+
|
2384 |
+
Examples
|
2385 |
+
--------
|
2386 |
+
>>> a = np.array([1,2,3])
|
2387 |
+
>>> np.cumprod(a) # intermediate results 1, 1*2
|
2388 |
+
... # total product 1*2*3 = 6
|
2389 |
+
array([1, 2, 6])
|
2390 |
+
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
|
2391 |
+
>>> np.cumprod(a, dtype=float) # specify type of output
|
2392 |
+
array([ 1., 2., 6., 24., 120., 720.])
|
2393 |
+
|
2394 |
+
The cumulative product for each column (i.e., over the rows) of `a`:
|
2395 |
+
|
2396 |
+
>>> np.cumprod(a, axis=0)
|
2397 |
+
array([[ 1, 2, 3],
|
2398 |
+
[ 4, 10, 18]])
|
2399 |
+
|
2400 |
+
The cumulative product for each row (i.e. over the columns) of `a`:
|
2401 |
+
|
2402 |
+
>>> np.cumprod(a,axis=1)
|
2403 |
+
array([[ 1, 2, 6],
|
2404 |
+
[ 4, 20, 120]])
|
2405 |
+
|
2406 |
+
"""
|
2407 |
+
try:
|
2408 |
+
cumprod = a.cumprod
|
2409 |
+
except AttributeError:
|
2410 |
+
return _wrapit(a, 'cumprod', axis, dtype, out)
|
2411 |
+
return cumprod(axis, dtype, out)
|
2412 |
+
|
2413 |
+
|
2414 |
+
def ndim(a):
|
2415 |
+
"""
|
2416 |
+
Return the number of dimensions of an array.
|
2417 |
+
|
2418 |
+
Parameters
|
2419 |
+
----------
|
2420 |
+
a : array_like
|
2421 |
+
Input array. If it is not already an ndarray, a conversion is
|
2422 |
+
attempted.
|
2423 |
+
|
2424 |
+
Returns
|
2425 |
+
-------
|
2426 |
+
number_of_dimensions : int
|
2427 |
+
The number of dimensions in `a`. Scalars are zero-dimensional.
|
2428 |
+
|
2429 |
+
See Also
|
2430 |
+
--------
|
2431 |
+
ndarray.ndim : equivalent method
|
2432 |
+
shape : dimensions of array
|
2433 |
+
ndarray.shape : dimensions of array
|
2434 |
+
|
2435 |
+
Examples
|
2436 |
+
--------
|
2437 |
+
>>> np.ndim([[1,2,3],[4,5,6]])
|
2438 |
+
2
|
2439 |
+
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
|
2440 |
+
2
|
2441 |
+
>>> np.ndim(1)
|
2442 |
+
0
|
2443 |
+
|
2444 |
+
"""
|
2445 |
+
try:
|
2446 |
+
return a.ndim
|
2447 |
+
except AttributeError:
|
2448 |
+
return asarray(a).ndim
|
2449 |
+
|
2450 |
+
|
2451 |
+
def rank(a):
|
2452 |
+
"""
|
2453 |
+
Return the number of dimensions of an array.
|
2454 |
+
|
2455 |
+
If `a` is not already an array, a conversion is attempted.
|
2456 |
+
Scalars are zero dimensional.
|
2457 |
+
|
2458 |
+
.. note::
|
2459 |
+
This function is deprecated in NumPy 1.9 to avoid confusion with
|
2460 |
+
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
|
2461 |
+
should be used instead.
|
2462 |
+
|
2463 |
+
Parameters
|
2464 |
+
----------
|
2465 |
+
a : array_like
|
2466 |
+
Array whose number of dimensions is desired. If `a` is not an array,
|
2467 |
+
a conversion is attempted.
|
2468 |
+
|
2469 |
+
Returns
|
2470 |
+
-------
|
2471 |
+
number_of_dimensions : int
|
2472 |
+
The number of dimensions in the array.
|
2473 |
+
|
2474 |
+
See Also
|
2475 |
+
--------
|
2476 |
+
ndim : equivalent function
|
2477 |
+
ndarray.ndim : equivalent property
|
2478 |
+
shape : dimensions of array
|
2479 |
+
ndarray.shape : dimensions of array
|
2480 |
+
|
2481 |
+
Notes
|
2482 |
+
-----
|
2483 |
+
In the old Numeric package, `rank` was the term used for the number of
|
2484 |
+
dimensions, but in Numpy `ndim` is used instead.
|
2485 |
+
|
2486 |
+
Examples
|
2487 |
+
--------
|
2488 |
+
>>> np.rank([1,2,3])
|
2489 |
+
1
|
2490 |
+
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
|
2491 |
+
2
|
2492 |
+
>>> np.rank(1)
|
2493 |
+
0
|
2494 |
+
|
2495 |
+
"""
|
2496 |
+
warnings.warn(
|
2497 |
+
"`rank` is deprecated; use the `ndim` attribute or function instead. "
|
2498 |
+
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
|
2499 |
+
VisibleDeprecationWarning)
|
2500 |
+
try:
|
2501 |
+
return a.ndim
|
2502 |
+
except AttributeError:
|
2503 |
+
return asarray(a).ndim
|
2504 |
+
|
2505 |
+
|
2506 |
+
def size(a, axis=None):
|
2507 |
+
"""
|
2508 |
+
Return the number of elements along a given axis.
|
2509 |
+
|
2510 |
+
Parameters
|
2511 |
+
----------
|
2512 |
+
a : array_like
|
2513 |
+
Input data.
|
2514 |
+
axis : int, optional
|
2515 |
+
Axis along which the elements are counted. By default, give
|
2516 |
+
the total number of elements.
|
2517 |
+
|
2518 |
+
Returns
|
2519 |
+
-------
|
2520 |
+
element_count : int
|
2521 |
+
Number of elements along the specified axis.
|
2522 |
+
|
2523 |
+
See Also
|
2524 |
+
--------
|
2525 |
+
shape : dimensions of array
|
2526 |
+
ndarray.shape : dimensions of array
|
2527 |
+
ndarray.size : number of elements in array
|
2528 |
+
|
2529 |
+
Examples
|
2530 |
+
--------
|
2531 |
+
>>> a = np.array([[1,2,3],[4,5,6]])
|
2532 |
+
>>> np.size(a)
|
2533 |
+
6
|
2534 |
+
>>> np.size(a,1)
|
2535 |
+
3
|
2536 |
+
>>> np.size(a,0)
|
2537 |
+
2
|
2538 |
+
|
2539 |
+
"""
|
2540 |
+
if axis is None:
|
2541 |
+
try:
|
2542 |
+
return a.size
|
2543 |
+
except AttributeError:
|
2544 |
+
return asarray(a).size
|
2545 |
+
else:
|
2546 |
+
try:
|
2547 |
+
return a.shape[axis]
|
2548 |
+
except AttributeError:
|
2549 |
+
return asarray(a).shape[axis]
|
2550 |
+
|
2551 |
+
|
2552 |
+
def around(a, decimals=0, out=None):
|
2553 |
+
"""
|
2554 |
+
Evenly round to the given number of decimals.
|
2555 |
+
|
2556 |
+
Parameters
|
2557 |
+
----------
|
2558 |
+
a : array_like
|
2559 |
+
Input data.
|
2560 |
+
decimals : int, optional
|
2561 |
+
Number of decimal places to round to (default: 0). If
|
2562 |
+
decimals is negative, it specifies the number of positions to
|
2563 |
+
the left of the decimal point.
|
2564 |
+
out : ndarray, optional
|
2565 |
+
Alternative output array in which to place the result. It must have
|
2566 |
+
the same shape as the expected output, but the type of the output
|
2567 |
+
values will be cast if necessary. See `doc.ufuncs` (Section
|
2568 |
+
"Output arguments") for details.
|
2569 |
+
|
2570 |
+
Returns
|
2571 |
+
-------
|
2572 |
+
rounded_array : ndarray
|
2573 |
+
An array of the same type as `a`, containing the rounded values.
|
2574 |
+
Unless `out` was specified, a new array is created. A reference to
|
2575 |
+
the result is returned.
|
2576 |
+
|
2577 |
+
The real and imaginary parts of complex numbers are rounded
|
2578 |
+
separately. The result of rounding a float is a float.
|
2579 |
+
|
2580 |
+
See Also
|
2581 |
+
--------
|
2582 |
+
ndarray.round : equivalent method
|
2583 |
+
|
2584 |
+
ceil, fix, floor, rint, trunc
|
2585 |
+
|
2586 |
+
|
2587 |
+
Notes
|
2588 |
+
-----
|
2589 |
+
For values exactly halfway between rounded decimal values, Numpy
|
2590 |
+
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
|
2591 |
+
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
|
2592 |
+
to the inexact representation of decimal fractions in the IEEE
|
2593 |
+
floating point standard [1]_ and errors introduced when scaling
|
2594 |
+
by powers of ten.
|
2595 |
+
|
2596 |
+
References
|
2597 |
+
----------
|
2598 |
+
.. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
|
2599 |
+
http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
|
2600 |
+
.. [2] "How Futile are Mindless Assessments of
|
2601 |
+
Roundoff in Floating-Point Computation?", William Kahan,
|
2602 |
+
http://www.cs.berkeley.edu/~wkahan/Mindless.pdf
|
2603 |
+
|
2604 |
+
Examples
|
2605 |
+
--------
|
2606 |
+
>>> np.around([0.37, 1.64])
|
2607 |
+
array([ 0., 2.])
|
2608 |
+
>>> np.around([0.37, 1.64], decimals=1)
|
2609 |
+
array([ 0.4, 1.6])
|
2610 |
+
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
|
2611 |
+
array([ 0., 2., 2., 4., 4.])
|
2612 |
+
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
|
2613 |
+
array([ 1, 2, 3, 11])
|
2614 |
+
>>> np.around([1,2,3,11], decimals=-1)
|
2615 |
+
array([ 0, 0, 0, 10])
|
2616 |
+
|
2617 |
+
"""
|
2618 |
+
try:
|
2619 |
+
round = a.round
|
2620 |
+
except AttributeError:
|
2621 |
+
return _wrapit(a, 'round', decimals, out)
|
2622 |
+
return round(decimals, out)
|
2623 |
+
|
2624 |
+
|
2625 |
+
def round_(a, decimals=0, out=None):
|
2626 |
+
"""
|
2627 |
+
Round an array to the given number of decimals.
|
2628 |
+
|
2629 |
+
Refer to `around` for full documentation.
|
2630 |
+
|
2631 |
+
See Also
|
2632 |
+
--------
|
2633 |
+
around : equivalent function
|
2634 |
+
|
2635 |
+
"""
|
2636 |
+
try:
|
2637 |
+
round = a.round
|
2638 |
+
except AttributeError:
|
2639 |
+
return _wrapit(a, 'round', decimals, out)
|
2640 |
+
return round(decimals, out)
|
2641 |
+
|
2642 |
+
|
2643 |
+
def mean(a, axis=None, dtype=None, out=None, keepdims=False):
|
2644 |
+
"""
|
2645 |
+
Compute the arithmetic mean along the specified axis.
|
2646 |
+
|
2647 |
+
Returns the average of the array elements. The average is taken over
|
2648 |
+
the flattened array by default, otherwise over the specified axis.
|
2649 |
+
`float64` intermediate and return values are used for integer inputs.
|
2650 |
+
|
2651 |
+
Parameters
|
2652 |
+
----------
|
2653 |
+
a : array_like
|
2654 |
+
Array containing numbers whose mean is desired. If `a` is not an
|
2655 |
+
array, a conversion is attempted.
|
2656 |
+
axis : int, optional
|
2657 |
+
Axis along which the means are computed. The default is to compute
|
2658 |
+
the mean of the flattened array.
|
2659 |
+
dtype : data-type, optional
|
2660 |
+
Type to use in computing the mean. For integer inputs, the default
|
2661 |
+
is `float64`; for floating point inputs, it is the same as the
|
2662 |
+
input dtype.
|
2663 |
+
out : ndarray, optional
|
2664 |
+
Alternate output array in which to place the result. The default
|
2665 |
+
is ``None``; if provided, it must have the same shape as the
|
2666 |
+
expected output, but the type will be cast if necessary.
|
2667 |
+
See `doc.ufuncs` for details.
|
2668 |
+
keepdims : bool, optional
|
2669 |
+
If this is set to True, the axes which are reduced are left
|
2670 |
+
in the result as dimensions with size one. With this option,
|
2671 |
+
the result will broadcast correctly against the original `arr`.
|
2672 |
+
|
2673 |
+
Returns
|
2674 |
+
-------
|
2675 |
+
m : ndarray, see dtype parameter above
|
2676 |
+
If `out=None`, returns a new array containing the mean values,
|
2677 |
+
otherwise a reference to the output array is returned.
|
2678 |
+
|
2679 |
+
See Also
|
2680 |
+
--------
|
2681 |
+
average : Weighted average
|
2682 |
+
std, var, nanmean, nanstd, nanvar
|
2683 |
+
|
2684 |
+
Notes
|
2685 |
+
-----
|
2686 |
+
The arithmetic mean is the sum of the elements along the axis divided
|
2687 |
+
by the number of elements.
|
2688 |
+
|
2689 |
+
Note that for floating-point input, the mean is computed using the
|
2690 |
+
same precision the input has. Depending on the input data, this can
|
2691 |
+
cause the results to be inaccurate, especially for `float32` (see
|
2692 |
+
example below). Specifying a higher-precision accumulator using the
|
2693 |
+
`dtype` keyword can alleviate this issue.
|
2694 |
+
|
2695 |
+
Examples
|
2696 |
+
--------
|
2697 |
+
>>> a = np.array([[1, 2], [3, 4]])
|
2698 |
+
>>> np.mean(a)
|
2699 |
+
2.5
|
2700 |
+
>>> np.mean(a, axis=0)
|
2701 |
+
array([ 2., 3.])
|
2702 |
+
>>> np.mean(a, axis=1)
|
2703 |
+
array([ 1.5, 3.5])
|
2704 |
+
|
2705 |
+
In single precision, `mean` can be inaccurate:
|
2706 |
+
|
2707 |
+
>>> a = np.zeros((2, 512*512), dtype=np.float32)
|
2708 |
+
>>> a[0, :] = 1.0
|
2709 |
+
>>> a[1, :] = 0.1
|
2710 |
+
>>> np.mean(a)
|
2711 |
+
0.546875
|
2712 |
+
|
2713 |
+
Computing the mean in float64 is more accurate:
|
2714 |
+
|
2715 |
+
>>> np.mean(a, dtype=np.float64)
|
2716 |
+
0.55000000074505806
|
2717 |
+
|
2718 |
+
"""
|
2719 |
+
if type(a) is not mu.ndarray:
|
2720 |
+
try:
|
2721 |
+
mean = a.mean
|
2722 |
+
return mean(axis=axis, dtype=dtype, out=out)
|
2723 |
+
except AttributeError:
|
2724 |
+
pass
|
2725 |
+
|
2726 |
+
return _methods._mean(a, axis=axis, dtype=dtype,
|
2727 |
+
out=out, keepdims=keepdims)
|
2728 |
+
|
2729 |
+
def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
|
2730 |
+
"""
|
2731 |
+
Compute the standard deviation along the specified axis.
|
2732 |
+
|
2733 |
+
Returns the standard deviation, a measure of the spread of a distribution,
|
2734 |
+
of the array elements. The standard deviation is computed for the
|
2735 |
+
flattened array by default, otherwise over the specified axis.
|
2736 |
+
|
2737 |
+
Parameters
|
2738 |
+
----------
|
2739 |
+
a : array_like
|
2740 |
+
Calculate the standard deviation of these values.
|
2741 |
+
axis : int, optional
|
2742 |
+
Axis along which the standard deviation is computed. The default is
|
2743 |
+
to compute the standard deviation of the flattened array.
|
2744 |
+
dtype : dtype, optional
|
2745 |
+
Type to use in computing the standard deviation. For arrays of
|
2746 |
+
integer type the default is float64, for arrays of float types it is
|
2747 |
+
the same as the array type.
|
2748 |
+
out : ndarray, optional
|
2749 |
+
Alternative output array in which to place the result. It must have
|
2750 |
+
the same shape as the expected output but the type (of the calculated
|
2751 |
+
values) will be cast if necessary.
|
2752 |
+
ddof : int, optional
|
2753 |
+
Means Delta Degrees of Freedom. The divisor used in calculations
|
2754 |
+
is ``N - ddof``, where ``N`` represents the number of elements.
|
2755 |
+
By default `ddof` is zero.
|
2756 |
+
keepdims : bool, optional
|
2757 |
+
If this is set to True, the axes which are reduced are left
|
2758 |
+
in the result as dimensions with size one. With this option,
|
2759 |
+
the result will broadcast correctly against the original `arr`.
|
2760 |
+
|
2761 |
+
Returns
|
2762 |
+
-------
|
2763 |
+
standard_deviation : ndarray, see dtype parameter above.
|
2764 |
+
If `out` is None, return a new array containing the standard deviation,
|
2765 |
+
otherwise return a reference to the output array.
|
2766 |
+
|
2767 |
+
See Also
|
2768 |
+
--------
|
2769 |
+
var, mean, nanmean, nanstd, nanvar
|
2770 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
2771 |
+
|
2772 |
+
Notes
|
2773 |
+
-----
|
2774 |
+
The standard deviation is the square root of the average of the squared
|
2775 |
+
deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
|
2776 |
+
|
2777 |
+
The average squared deviation is normally calculated as
|
2778 |
+
``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified,
|
2779 |
+
the divisor ``N - ddof`` is used instead. In standard statistical
|
2780 |
+
practice, ``ddof=1`` provides an unbiased estimator of the variance
|
2781 |
+
of the infinite population. ``ddof=0`` provides a maximum likelihood
|
2782 |
+
estimate of the variance for normally distributed variables. The
|
2783 |
+
standard deviation computed in this function is the square root of
|
2784 |
+
the estimated variance, so even with ``ddof=1``, it will not be an
|
2785 |
+
unbiased estimate of the standard deviation per se.
|
2786 |
+
|
2787 |
+
Note that, for complex numbers, `std` takes the absolute
|
2788 |
+
value before squaring, so that the result is always real and nonnegative.
|
2789 |
+
|
2790 |
+
For floating-point input, the *std* is computed using the same
|
2791 |
+
precision the input has. Depending on the input data, this can cause
|
2792 |
+
the results to be inaccurate, especially for float32 (see example below).
|
2793 |
+
Specifying a higher-accuracy accumulator using the `dtype` keyword can
|
2794 |
+
alleviate this issue.
|
2795 |
+
|
2796 |
+
Examples
|
2797 |
+
--------
|
2798 |
+
>>> a = np.array([[1, 2], [3, 4]])
|
2799 |
+
>>> np.std(a)
|
2800 |
+
1.1180339887498949
|
2801 |
+
>>> np.std(a, axis=0)
|
2802 |
+
array([ 1., 1.])
|
2803 |
+
>>> np.std(a, axis=1)
|
2804 |
+
array([ 0.5, 0.5])
|
2805 |
+
|
2806 |
+
In single precision, std() can be inaccurate:
|
2807 |
+
|
2808 |
+
>>> a = np.zeros((2,512*512), dtype=np.float32)
|
2809 |
+
>>> a[0,:] = 1.0
|
2810 |
+
>>> a[1,:] = 0.1
|
2811 |
+
>>> np.std(a)
|
2812 |
+
0.45172946707416706
|
2813 |
+
|
2814 |
+
Computing the standard deviation in float64 is more accurate:
|
2815 |
+
|
2816 |
+
>>> np.std(a, dtype=np.float64)
|
2817 |
+
0.44999999925552653
|
2818 |
+
|
2819 |
+
"""
|
2820 |
+
if type(a) is not mu.ndarray:
|
2821 |
+
try:
|
2822 |
+
std = a.std
|
2823 |
+
return std(axis=axis, dtype=dtype, out=out, ddof=ddof)
|
2824 |
+
except AttributeError:
|
2825 |
+
pass
|
2826 |
+
|
2827 |
+
return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
|
2828 |
+
keepdims=keepdims)
|
2829 |
+
|
2830 |
+
def var(a, axis=None, dtype=None, out=None, ddof=0,
|
2831 |
+
keepdims=False):
|
2832 |
+
"""
|
2833 |
+
Compute the variance along the specified axis.
|
2834 |
+
|
2835 |
+
Returns the variance of the array elements, a measure of the spread of a
|
2836 |
+
distribution. The variance is computed for the flattened array by
|
2837 |
+
default, otherwise over the specified axis.
|
2838 |
+
|
2839 |
+
Parameters
|
2840 |
+
----------
|
2841 |
+
a : array_like
|
2842 |
+
Array containing numbers whose variance is desired. If `a` is not an
|
2843 |
+
array, a conversion is attempted.
|
2844 |
+
axis : int, optional
|
2845 |
+
Axis along which the variance is computed. The default is to compute
|
2846 |
+
the variance of the flattened array.
|
2847 |
+
dtype : data-type, optional
|
2848 |
+
Type to use in computing the variance. For arrays of integer type
|
2849 |
+
the default is `float32`; for arrays of float types it is the same as
|
2850 |
+
the array type.
|
2851 |
+
out : ndarray, optional
|
2852 |
+
Alternate output array in which to place the result. It must have
|
2853 |
+
the same shape as the expected output, but the type is cast if
|
2854 |
+
necessary.
|
2855 |
+
ddof : int, optional
|
2856 |
+
"Delta Degrees of Freedom": the divisor used in the calculation is
|
2857 |
+
``N - ddof``, where ``N`` represents the number of elements. By
|
2858 |
+
default `ddof` is zero.
|
2859 |
+
keepdims : bool, optional
|
2860 |
+
If this is set to True, the axes which are reduced are left
|
2861 |
+
in the result as dimensions with size one. With this option,
|
2862 |
+
the result will broadcast correctly against the original `arr`.
|
2863 |
+
|
2864 |
+
Returns
|
2865 |
+
-------
|
2866 |
+
variance : ndarray, see dtype parameter above
|
2867 |
+
If ``out=None``, returns a new array containing the variance;
|
2868 |
+
otherwise, a reference to the output array is returned.
|
2869 |
+
|
2870 |
+
See Also
|
2871 |
+
--------
|
2872 |
+
std , mean, nanmean, nanstd, nanvar
|
2873 |
+
numpy.doc.ufuncs : Section "Output arguments"
|
2874 |
+
|
2875 |
+
Notes
|
2876 |
+
-----
|
2877 |
+
The variance is the average of the squared deviations from the mean,
|
2878 |
+
i.e., ``var = mean(abs(x - x.mean())**2)``.
|
2879 |
+
|
2880 |
+
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
|
2881 |
+
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
|
2882 |
+
instead. In standard statistical practice, ``ddof=1`` provides an
|
2883 |
+
unbiased estimator of the variance of a hypothetical infinite population.
|
2884 |
+
``ddof=0`` provides a maximum likelihood estimate of the variance for
|
2885 |
+
normally distributed variables.
|
2886 |
+
|
2887 |
+
Note that for complex numbers, the absolute value is taken before
|
2888 |
+
squaring, so that the result is always real and nonnegative.
|
2889 |
+
|
2890 |
+
For floating-point input, the variance is computed using the same
|
2891 |
+
precision the input has. Depending on the input data, this can cause
|
2892 |
+
the results to be inaccurate, especially for `float32` (see example
|
2893 |
+
below). Specifying a higher-accuracy accumulator using the ``dtype``
|
2894 |
+
keyword can alleviate this issue.
|
2895 |
+
|
2896 |
+
Examples
|
2897 |
+
--------
|
2898 |
+
>>> a = np.array([[1,2],[3,4]])
|
2899 |
+
>>> np.var(a)
|
2900 |
+
1.25
|
2901 |
+
>>> np.var(a, axis=0)
|
2902 |
+
array([ 1., 1.])
|
2903 |
+
>>> np.var(a, axis=1)
|
2904 |
+
array([ 0.25, 0.25])
|
2905 |
+
|
2906 |
+
In single precision, var() can be inaccurate:
|
2907 |
+
|
2908 |
+
>>> a = np.zeros((2,512*512), dtype=np.float32)
|
2909 |
+
>>> a[0,:] = 1.0
|
2910 |
+
>>> a[1,:] = 0.1
|
2911 |
+
>>> np.var(a)
|
2912 |
+
0.20405951142311096
|
2913 |
+
|
2914 |
+
Computing the variance in float64 is more accurate:
|
2915 |
+
|
2916 |
+
>>> np.var(a, dtype=np.float64)
|
2917 |
+
0.20249999932997387
|
2918 |
+
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
|
2919 |
+
0.20250000000000001
|
2920 |
+
|
2921 |
+
"""
|
2922 |
+
if type(a) is not mu.ndarray:
|
2923 |
+
try:
|
2924 |
+
var = a.var
|
2925 |
+
return var(axis=axis, dtype=dtype, out=out, ddof=ddof)
|
2926 |
+
except AttributeError:
|
2927 |
+
pass
|
2928 |
+
|
2929 |
+
return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
|
2930 |
+
keepdims=keepdims)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/function_base.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
__all__ = ['logspace', 'linspace']
|
4 |
+
|
5 |
+
from . import numeric as _nx
|
6 |
+
from .numeric import array, result_type
|
7 |
+
|
8 |
+
|
9 |
+
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
|
10 |
+
"""
|
11 |
+
Return evenly spaced numbers over a specified interval.
|
12 |
+
|
13 |
+
Returns `num` evenly spaced samples, calculated over the
|
14 |
+
interval [`start`, `stop` ].
|
15 |
+
|
16 |
+
The endpoint of the interval can optionally be excluded.
|
17 |
+
|
18 |
+
Parameters
|
19 |
+
----------
|
20 |
+
start : scalar
|
21 |
+
The starting value of the sequence.
|
22 |
+
stop : scalar
|
23 |
+
The end value of the sequence, unless `endpoint` is set to False.
|
24 |
+
In that case, the sequence consists of all but the last of ``num + 1``
|
25 |
+
evenly spaced samples, so that `stop` is excluded. Note that the step
|
26 |
+
size changes when `endpoint` is False.
|
27 |
+
num : int, optional
|
28 |
+
Number of samples to generate. Default is 50.
|
29 |
+
endpoint : bool, optional
|
30 |
+
If True, `stop` is the last sample. Otherwise, it is not included.
|
31 |
+
Default is True.
|
32 |
+
retstep : bool, optional
|
33 |
+
If True, return (`samples`, `step`), where `step` is the spacing
|
34 |
+
between samples.
|
35 |
+
dtype : dtype
|
36 |
+
The type of the output array. If `dtype` is not given, infer the data
|
37 |
+
type from the other input arguments.
|
38 |
+
|
39 |
+
.. versionadded:: 1.9.0
|
40 |
+
|
41 |
+
Returns
|
42 |
+
-------
|
43 |
+
samples : ndarray
|
44 |
+
There are `num` equally spaced samples in the closed interval
|
45 |
+
``[start, stop]`` or the half-open interval ``[start, stop)``
|
46 |
+
(depending on whether `endpoint` is True or False).
|
47 |
+
step : float (only if `retstep` is True)
|
48 |
+
Size of spacing between samples.
|
49 |
+
|
50 |
+
|
51 |
+
See Also
|
52 |
+
--------
|
53 |
+
arange : Similar to `linspace`, but uses a step size (instead of the
|
54 |
+
number of samples).
|
55 |
+
logspace : Samples uniformly distributed in log space.
|
56 |
+
|
57 |
+
Examples
|
58 |
+
--------
|
59 |
+
>>> np.linspace(2.0, 3.0, num=5)
|
60 |
+
array([ 2. , 2.25, 2.5 , 2.75, 3. ])
|
61 |
+
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
|
62 |
+
array([ 2. , 2.2, 2.4, 2.6, 2.8])
|
63 |
+
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
|
64 |
+
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
|
65 |
+
|
66 |
+
Graphical illustration:
|
67 |
+
|
68 |
+
>>> import matplotlib.pyplot as plt
|
69 |
+
>>> N = 8
|
70 |
+
>>> y = np.zeros(N)
|
71 |
+
>>> x1 = np.linspace(0, 10, N, endpoint=True)
|
72 |
+
>>> x2 = np.linspace(0, 10, N, endpoint=False)
|
73 |
+
>>> plt.plot(x1, y, 'o')
|
74 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
75 |
+
>>> plt.plot(x2, y + 0.5, 'o')
|
76 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
77 |
+
>>> plt.ylim([-0.5, 1])
|
78 |
+
(-0.5, 1)
|
79 |
+
>>> plt.show()
|
80 |
+
|
81 |
+
"""
|
82 |
+
num = int(num)
|
83 |
+
|
84 |
+
# Convert float/complex array scalars to float, gh-3504
|
85 |
+
start = start * 1.
|
86 |
+
stop = stop * 1.
|
87 |
+
|
88 |
+
if dtype is None:
|
89 |
+
dtype = result_type(start, stop, float(num))
|
90 |
+
|
91 |
+
if num <= 0:
|
92 |
+
return array([], dtype)
|
93 |
+
if endpoint:
|
94 |
+
if num == 1:
|
95 |
+
return array([start], dtype=dtype)
|
96 |
+
step = (stop-start)/float((num-1))
|
97 |
+
y = _nx.arange(0, num, dtype=dtype) * step + start
|
98 |
+
y[-1] = stop
|
99 |
+
else:
|
100 |
+
step = (stop-start)/float(num)
|
101 |
+
y = _nx.arange(0, num, dtype=dtype) * step + start
|
102 |
+
if retstep:
|
103 |
+
return y.astype(dtype), step
|
104 |
+
else:
|
105 |
+
return y.astype(dtype)
|
106 |
+
|
107 |
+
|
108 |
+
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
|
109 |
+
"""
|
110 |
+
Return numbers spaced evenly on a log scale.
|
111 |
+
|
112 |
+
In linear space, the sequence starts at ``base ** start``
|
113 |
+
(`base` to the power of `start`) and ends with ``base ** stop``
|
114 |
+
(see `endpoint` below).
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
start : float
|
119 |
+
``base ** start`` is the starting value of the sequence.
|
120 |
+
stop : float
|
121 |
+
``base ** stop`` is the final value of the sequence, unless `endpoint`
|
122 |
+
is False. In that case, ``num + 1`` values are spaced over the
|
123 |
+
interval in log-space, of which all but the last (a sequence of
|
124 |
+
length ``num``) are returned.
|
125 |
+
num : integer, optional
|
126 |
+
Number of samples to generate. Default is 50.
|
127 |
+
endpoint : boolean, optional
|
128 |
+
If true, `stop` is the last sample. Otherwise, it is not included.
|
129 |
+
Default is True.
|
130 |
+
base : float, optional
|
131 |
+
The base of the log space. The step size between the elements in
|
132 |
+
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
|
133 |
+
Default is 10.0.
|
134 |
+
dtype : dtype
|
135 |
+
The type of the output array. If `dtype` is not given, infer the data
|
136 |
+
type from the other input arguments.
|
137 |
+
|
138 |
+
Returns
|
139 |
+
-------
|
140 |
+
samples : ndarray
|
141 |
+
`num` samples, equally spaced on a log scale.
|
142 |
+
|
143 |
+
See Also
|
144 |
+
--------
|
145 |
+
arange : Similar to linspace, with the step size specified instead of the
|
146 |
+
number of samples. Note that, when used with a float endpoint, the
|
147 |
+
endpoint may or may not be included.
|
148 |
+
linspace : Similar to logspace, but with the samples uniformly distributed
|
149 |
+
in linear space, instead of log space.
|
150 |
+
|
151 |
+
Notes
|
152 |
+
-----
|
153 |
+
Logspace is equivalent to the code
|
154 |
+
|
155 |
+
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
|
156 |
+
... # doctest: +SKIP
|
157 |
+
>>> power(base, y).astype(dtype)
|
158 |
+
... # doctest: +SKIP
|
159 |
+
|
160 |
+
Examples
|
161 |
+
--------
|
162 |
+
>>> np.logspace(2.0, 3.0, num=4)
|
163 |
+
array([ 100. , 215.443469 , 464.15888336, 1000. ])
|
164 |
+
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
|
165 |
+
array([ 100. , 177.827941 , 316.22776602, 562.34132519])
|
166 |
+
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
|
167 |
+
array([ 4. , 5.0396842 , 6.34960421, 8. ])
|
168 |
+
|
169 |
+
Graphical illustration:
|
170 |
+
|
171 |
+
>>> import matplotlib.pyplot as plt
|
172 |
+
>>> N = 10
|
173 |
+
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
|
174 |
+
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
|
175 |
+
>>> y = np.zeros(N)
|
176 |
+
>>> plt.plot(x1, y, 'o')
|
177 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
178 |
+
>>> plt.plot(x2, y + 0.5, 'o')
|
179 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
180 |
+
>>> plt.ylim([-0.5, 1])
|
181 |
+
(-0.5, 1)
|
182 |
+
>>> plt.show()
|
183 |
+
|
184 |
+
"""
|
185 |
+
y = linspace(start, stop, num=num, endpoint=endpoint)
|
186 |
+
if dtype is None:
|
187 |
+
return _nx.power(base, y)
|
188 |
+
return _nx.power(base, y).astype(dtype)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/generate_numpy_api.py
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, print_function
|
2 |
+
|
3 |
+
import os
|
4 |
+
import genapi
|
5 |
+
|
6 |
+
from genapi import \
|
7 |
+
TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi
|
8 |
+
|
9 |
+
import numpy_api
|
10 |
+
|
11 |
+
# use annotated api when running under cpychecker
|
12 |
+
h_template = r"""
|
13 |
+
#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE)
|
14 |
+
|
15 |
+
typedef struct {
|
16 |
+
PyObject_HEAD
|
17 |
+
npy_bool obval;
|
18 |
+
} PyBoolScalarObject;
|
19 |
+
|
20 |
+
#ifdef NPY_ENABLE_SEPARATE_COMPILATION
|
21 |
+
extern NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type;
|
22 |
+
extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;
|
23 |
+
extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];
|
24 |
+
#else
|
25 |
+
NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type;
|
26 |
+
NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;
|
27 |
+
NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2];
|
28 |
+
#endif
|
29 |
+
|
30 |
+
%s
|
31 |
+
|
32 |
+
#else
|
33 |
+
|
34 |
+
#if defined(PY_ARRAY_UNIQUE_SYMBOL)
|
35 |
+
#define PyArray_API PY_ARRAY_UNIQUE_SYMBOL
|
36 |
+
#endif
|
37 |
+
|
38 |
+
#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)
|
39 |
+
extern void **PyArray_API;
|
40 |
+
#else
|
41 |
+
#if defined(PY_ARRAY_UNIQUE_SYMBOL)
|
42 |
+
void **PyArray_API;
|
43 |
+
#else
|
44 |
+
static void **PyArray_API=NULL;
|
45 |
+
#endif
|
46 |
+
#endif
|
47 |
+
|
48 |
+
%s
|
49 |
+
|
50 |
+
#if !defined(NO_IMPORT_ARRAY) && !defined(NO_IMPORT)
|
51 |
+
static int
|
52 |
+
_import_array(void)
|
53 |
+
{
|
54 |
+
int st;
|
55 |
+
PyObject *numpy = PyImport_ImportModule("numpy.core.multiarray");
|
56 |
+
PyObject *c_api = NULL;
|
57 |
+
|
58 |
+
if (numpy == NULL) {
|
59 |
+
PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import");
|
60 |
+
return -1;
|
61 |
+
}
|
62 |
+
c_api = PyObject_GetAttrString(numpy, "_ARRAY_API");
|
63 |
+
Py_DECREF(numpy);
|
64 |
+
if (c_api == NULL) {
|
65 |
+
PyErr_SetString(PyExc_AttributeError, "_ARRAY_API not found");
|
66 |
+
return -1;
|
67 |
+
}
|
68 |
+
|
69 |
+
#if PY_VERSION_HEX >= 0x03000000
|
70 |
+
if (!PyCapsule_CheckExact(c_api)) {
|
71 |
+
PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object");
|
72 |
+
Py_DECREF(c_api);
|
73 |
+
return -1;
|
74 |
+
}
|
75 |
+
PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL);
|
76 |
+
#else
|
77 |
+
if (!PyCObject_Check(c_api)) {
|
78 |
+
PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCObject object");
|
79 |
+
Py_DECREF(c_api);
|
80 |
+
return -1;
|
81 |
+
}
|
82 |
+
PyArray_API = (void **)PyCObject_AsVoidPtr(c_api);
|
83 |
+
#endif
|
84 |
+
Py_DECREF(c_api);
|
85 |
+
if (PyArray_API == NULL) {
|
86 |
+
PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer");
|
87 |
+
return -1;
|
88 |
+
}
|
89 |
+
|
90 |
+
/* Perform runtime check of C API version */
|
91 |
+
if (NPY_VERSION != PyArray_GetNDArrayCVersion()) {
|
92 |
+
PyErr_Format(PyExc_RuntimeError, "module compiled against "\
|
93 |
+
"ABI version %%x but this version of numpy is %%x", \
|
94 |
+
(int) NPY_VERSION, (int) PyArray_GetNDArrayCVersion());
|
95 |
+
return -1;
|
96 |
+
}
|
97 |
+
if (NPY_FEATURE_VERSION > PyArray_GetNDArrayCFeatureVersion()) {
|
98 |
+
PyErr_Format(PyExc_RuntimeError, "module compiled against "\
|
99 |
+
"API version %%x but this version of numpy is %%x", \
|
100 |
+
(int) NPY_FEATURE_VERSION, (int) PyArray_GetNDArrayCFeatureVersion());
|
101 |
+
return -1;
|
102 |
+
}
|
103 |
+
|
104 |
+
/*
|
105 |
+
* Perform runtime check of endianness and check it matches the one set by
|
106 |
+
* the headers (npy_endian.h) as a safeguard
|
107 |
+
*/
|
108 |
+
st = PyArray_GetEndianness();
|
109 |
+
if (st == NPY_CPU_UNKNOWN_ENDIAN) {
|
110 |
+
PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as unknown endian");
|
111 |
+
return -1;
|
112 |
+
}
|
113 |
+
#if NPY_BYTE_ORDER == NPY_BIG_ENDIAN
|
114 |
+
if (st != NPY_CPU_BIG) {
|
115 |
+
PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\
|
116 |
+
"big endian, but detected different endianness at runtime");
|
117 |
+
return -1;
|
118 |
+
}
|
119 |
+
#elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN
|
120 |
+
if (st != NPY_CPU_LITTLE) {
|
121 |
+
PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\
|
122 |
+
"little endian, but detected different endianness at runtime");
|
123 |
+
return -1;
|
124 |
+
}
|
125 |
+
#endif
|
126 |
+
|
127 |
+
return 0;
|
128 |
+
}
|
129 |
+
|
130 |
+
#if PY_VERSION_HEX >= 0x03000000
|
131 |
+
#define NUMPY_IMPORT_ARRAY_RETVAL NULL
|
132 |
+
#else
|
133 |
+
#define NUMPY_IMPORT_ARRAY_RETVAL
|
134 |
+
#endif
|
135 |
+
|
136 |
+
#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } }
|
137 |
+
|
138 |
+
#define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } }
|
139 |
+
|
140 |
+
#define import_array2(msg, ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; } }
|
141 |
+
|
142 |
+
#endif
|
143 |
+
|
144 |
+
#endif
|
145 |
+
"""
|
146 |
+
|
147 |
+
|
148 |
+
c_template = r"""
|
149 |
+
/* These pointers will be stored in the C-object for use in other
|
150 |
+
extension modules
|
151 |
+
*/
|
152 |
+
|
153 |
+
void *PyArray_API[] = {
|
154 |
+
%s
|
155 |
+
};
|
156 |
+
"""
|
157 |
+
|
158 |
+
c_api_header = """
|
159 |
+
===========
|
160 |
+
Numpy C-API
|
161 |
+
===========
|
162 |
+
"""
|
163 |
+
|
164 |
+
def generate_api(output_dir, force=False):
|
165 |
+
basename = 'multiarray_api'
|
166 |
+
|
167 |
+
h_file = os.path.join(output_dir, '__%s.h' % basename)
|
168 |
+
c_file = os.path.join(output_dir, '__%s.c' % basename)
|
169 |
+
d_file = os.path.join(output_dir, '%s.txt' % basename)
|
170 |
+
targets = (h_file, c_file, d_file)
|
171 |
+
|
172 |
+
sources = numpy_api.multiarray_api
|
173 |
+
|
174 |
+
if (not force and not genapi.should_rebuild(targets, [numpy_api.__file__, __file__])):
|
175 |
+
return targets
|
176 |
+
else:
|
177 |
+
do_generate_api(targets, sources)
|
178 |
+
|
179 |
+
return targets
|
180 |
+
|
181 |
+
def do_generate_api(targets, sources):
|
182 |
+
header_file = targets[0]
|
183 |
+
c_file = targets[1]
|
184 |
+
doc_file = targets[2]
|
185 |
+
|
186 |
+
global_vars = sources[0]
|
187 |
+
scalar_bool_values = sources[1]
|
188 |
+
types_api = sources[2]
|
189 |
+
multiarray_funcs = sources[3]
|
190 |
+
|
191 |
+
multiarray_api = sources[:]
|
192 |
+
|
193 |
+
module_list = []
|
194 |
+
extension_list = []
|
195 |
+
init_list = []
|
196 |
+
|
197 |
+
# Check multiarray api indexes
|
198 |
+
multiarray_api_index = genapi.merge_api_dicts(multiarray_api)
|
199 |
+
genapi.check_api_dict(multiarray_api_index)
|
200 |
+
|
201 |
+
numpyapi_list = genapi.get_api_functions('NUMPY_API',
|
202 |
+
multiarray_funcs)
|
203 |
+
ordered_funcs_api = genapi.order_dict(multiarray_funcs)
|
204 |
+
|
205 |
+
# Create dict name -> *Api instance
|
206 |
+
api_name = 'PyArray_API'
|
207 |
+
multiarray_api_dict = {}
|
208 |
+
for f in numpyapi_list:
|
209 |
+
name = f.name
|
210 |
+
index = multiarray_funcs[name][0]
|
211 |
+
annotations = multiarray_funcs[name][1:]
|
212 |
+
multiarray_api_dict[f.name] = FunctionApi(f.name, index, annotations,
|
213 |
+
f.return_type,
|
214 |
+
f.args, api_name)
|
215 |
+
|
216 |
+
for name, val in global_vars.items():
|
217 |
+
index, type = val
|
218 |
+
multiarray_api_dict[name] = GlobalVarApi(name, index, type, api_name)
|
219 |
+
|
220 |
+
for name, val in scalar_bool_values.items():
|
221 |
+
index = val[0]
|
222 |
+
multiarray_api_dict[name] = BoolValuesApi(name, index, api_name)
|
223 |
+
|
224 |
+
for name, val in types_api.items():
|
225 |
+
index = val[0]
|
226 |
+
multiarray_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name)
|
227 |
+
|
228 |
+
if len(multiarray_api_dict) != len(multiarray_api_index):
|
229 |
+
raise AssertionError("Multiarray API size mismatch %d %d" %
|
230 |
+
(len(multiarray_api_dict), len(multiarray_api_index)))
|
231 |
+
|
232 |
+
extension_list = []
|
233 |
+
for name, index in genapi.order_dict(multiarray_api_index):
|
234 |
+
api_item = multiarray_api_dict[name]
|
235 |
+
extension_list.append(api_item.define_from_array_api_string())
|
236 |
+
init_list.append(api_item.array_api_define())
|
237 |
+
module_list.append(api_item.internal_define())
|
238 |
+
|
239 |
+
# Write to header
|
240 |
+
fid = open(header_file, 'w')
|
241 |
+
s = h_template % ('\n'.join(module_list), '\n'.join(extension_list))
|
242 |
+
fid.write(s)
|
243 |
+
fid.close()
|
244 |
+
|
245 |
+
# Write to c-code
|
246 |
+
fid = open(c_file, 'w')
|
247 |
+
s = c_template % ',\n'.join(init_list)
|
248 |
+
fid.write(s)
|
249 |
+
fid.close()
|
250 |
+
|
251 |
+
# write to documentation
|
252 |
+
fid = open(doc_file, 'w')
|
253 |
+
fid.write(c_api_header)
|
254 |
+
for func in numpyapi_list:
|
255 |
+
fid.write(func.to_ReST())
|
256 |
+
fid.write('\n\n')
|
257 |
+
fid.close()
|
258 |
+
|
259 |
+
return targets
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/getlim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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Machine limits for Float32 and Float64 and (long double) if available...
|
2 |
+
|
3 |
+
"""
|
4 |
+
from __future__ import division, absolute_import, print_function
|
5 |
+
|
6 |
+
__all__ = ['finfo', 'iinfo']
|
7 |
+
|
8 |
+
from .machar import MachAr
|
9 |
+
from . import numeric
|
10 |
+
from . import numerictypes as ntypes
|
11 |
+
from .numeric import array
|
12 |
+
|
13 |
+
def _frz(a):
|
14 |
+
"""fix rank-0 --> rank-1"""
|
15 |
+
if a.ndim == 0: a.shape = (1,)
|
16 |
+
return a
|
17 |
+
|
18 |
+
_convert_to_float = {
|
19 |
+
ntypes.csingle: ntypes.single,
|
20 |
+
ntypes.complex_: ntypes.float_,
|
21 |
+
ntypes.clongfloat: ntypes.longfloat
|
22 |
+
}
|
23 |
+
|
24 |
+
class finfo(object):
|
25 |
+
"""
|
26 |
+
finfo(dtype)
|
27 |
+
|
28 |
+
Machine limits for floating point types.
|
29 |
+
|
30 |
+
Attributes
|
31 |
+
----------
|
32 |
+
eps : float
|
33 |
+
The smallest representable positive number such that
|
34 |
+
``1.0 + eps != 1.0``. Type of `eps` is an appropriate floating
|
35 |
+
point type.
|
36 |
+
epsneg : floating point number of the appropriate type
|
37 |
+
The smallest representable positive number such that
|
38 |
+
``1.0 - epsneg != 1.0``.
|
39 |
+
iexp : int
|
40 |
+
The number of bits in the exponent portion of the floating point
|
41 |
+
representation.
|
42 |
+
machar : MachAr
|
43 |
+
The object which calculated these parameters and holds more
|
44 |
+
detailed information.
|
45 |
+
machep : int
|
46 |
+
The exponent that yields `eps`.
|
47 |
+
max : floating point number of the appropriate type
|
48 |
+
The largest representable number.
|
49 |
+
maxexp : int
|
50 |
+
The smallest positive power of the base (2) that causes overflow.
|
51 |
+
min : floating point number of the appropriate type
|
52 |
+
The smallest representable number, typically ``-max``.
|
53 |
+
minexp : int
|
54 |
+
The most negative power of the base (2) consistent with there
|
55 |
+
being no leading 0's in the mantissa.
|
56 |
+
negep : int
|
57 |
+
The exponent that yields `epsneg`.
|
58 |
+
nexp : int
|
59 |
+
The number of bits in the exponent including its sign and bias.
|
60 |
+
nmant : int
|
61 |
+
The number of bits in the mantissa.
|
62 |
+
precision : int
|
63 |
+
The approximate number of decimal digits to which this kind of
|
64 |
+
float is precise.
|
65 |
+
resolution : floating point number of the appropriate type
|
66 |
+
The approximate decimal resolution of this type, i.e.,
|
67 |
+
``10**-precision``.
|
68 |
+
tiny : float
|
69 |
+
The smallest positive usable number. Type of `tiny` is an
|
70 |
+
appropriate floating point type.
|
71 |
+
|
72 |
+
Parameters
|
73 |
+
----------
|
74 |
+
dtype : float, dtype, or instance
|
75 |
+
Kind of floating point data-type about which to get information.
|
76 |
+
|
77 |
+
See Also
|
78 |
+
--------
|
79 |
+
MachAr : The implementation of the tests that produce this information.
|
80 |
+
iinfo : The equivalent for integer data types.
|
81 |
+
|
82 |
+
Notes
|
83 |
+
-----
|
84 |
+
For developers of NumPy: do not instantiate this at the module level.
|
85 |
+
The initial calculation of these parameters is expensive and negatively
|
86 |
+
impacts import times. These objects are cached, so calling ``finfo()``
|
87 |
+
repeatedly inside your functions is not a problem.
|
88 |
+
|
89 |
+
"""
|
90 |
+
|
91 |
+
_finfo_cache = {}
|
92 |
+
|
93 |
+
def __new__(cls, dtype):
|
94 |
+
try:
|
95 |
+
dtype = numeric.dtype(dtype)
|
96 |
+
except TypeError:
|
97 |
+
# In case a float instance was given
|
98 |
+
dtype = numeric.dtype(type(dtype))
|
99 |
+
|
100 |
+
obj = cls._finfo_cache.get(dtype, None)
|
101 |
+
if obj is not None:
|
102 |
+
return obj
|
103 |
+
dtypes = [dtype]
|
104 |
+
newdtype = numeric.obj2sctype(dtype)
|
105 |
+
if newdtype is not dtype:
|
106 |
+
dtypes.append(newdtype)
|
107 |
+
dtype = newdtype
|
108 |
+
if not issubclass(dtype, numeric.inexact):
|
109 |
+
raise ValueError("data type %r not inexact" % (dtype))
|
110 |
+
obj = cls._finfo_cache.get(dtype, None)
|
111 |
+
if obj is not None:
|
112 |
+
return obj
|
113 |
+
if not issubclass(dtype, numeric.floating):
|
114 |
+
newdtype = _convert_to_float[dtype]
|
115 |
+
if newdtype is not dtype:
|
116 |
+
dtypes.append(newdtype)
|
117 |
+
dtype = newdtype
|
118 |
+
obj = cls._finfo_cache.get(dtype, None)
|
119 |
+
if obj is not None:
|
120 |
+
return obj
|
121 |
+
obj = object.__new__(cls)._init(dtype)
|
122 |
+
for dt in dtypes:
|
123 |
+
cls._finfo_cache[dt] = obj
|
124 |
+
return obj
|
125 |
+
|
126 |
+
def _init(self, dtype):
|
127 |
+
self.dtype = numeric.dtype(dtype)
|
128 |
+
if dtype is ntypes.double:
|
129 |
+
itype = ntypes.int64
|
130 |
+
fmt = '%24.16e'
|
131 |
+
precname = 'double'
|
132 |
+
elif dtype is ntypes.single:
|
133 |
+
itype = ntypes.int32
|
134 |
+
fmt = '%15.7e'
|
135 |
+
precname = 'single'
|
136 |
+
elif dtype is ntypes.longdouble:
|
137 |
+
itype = ntypes.longlong
|
138 |
+
fmt = '%s'
|
139 |
+
precname = 'long double'
|
140 |
+
elif dtype is ntypes.half:
|
141 |
+
itype = ntypes.int16
|
142 |
+
fmt = '%12.5e'
|
143 |
+
precname = 'half'
|
144 |
+
else:
|
145 |
+
raise ValueError(repr(dtype))
|
146 |
+
|
147 |
+
machar = MachAr(lambda v:array([v], dtype),
|
148 |
+
lambda v:_frz(v.astype(itype))[0],
|
149 |
+
lambda v:array(_frz(v)[0], dtype),
|
150 |
+
lambda v: fmt % array(_frz(v)[0], dtype),
|
151 |
+
'numpy %s precision floating point number' % precname)
|
152 |
+
|
153 |
+
for word in ['precision', 'iexp',
|
154 |
+
'maxexp', 'minexp', 'negep',
|
155 |
+
'machep']:
|
156 |
+
setattr(self, word, getattr(machar, word))
|
157 |
+
for word in ['tiny', 'resolution', 'epsneg']:
|
158 |
+
setattr(self, word, getattr(machar, word).flat[0])
|
159 |
+
self.max = machar.huge.flat[0]
|
160 |
+
self.min = -self.max
|
161 |
+
self.eps = machar.eps.flat[0]
|
162 |
+
self.nexp = machar.iexp
|
163 |
+
self.nmant = machar.it
|
164 |
+
self.machar = machar
|
165 |
+
self._str_tiny = machar._str_xmin.strip()
|
166 |
+
self._str_max = machar._str_xmax.strip()
|
167 |
+
self._str_epsneg = machar._str_epsneg.strip()
|
168 |
+
self._str_eps = machar._str_eps.strip()
|
169 |
+
self._str_resolution = machar._str_resolution.strip()
|
170 |
+
return self
|
171 |
+
|
172 |
+
def __str__(self):
|
173 |
+
return '''\
|
174 |
+
Machine parameters for %(dtype)s
|
175 |
+
---------------------------------------------------------------------
|
176 |
+
precision=%(precision)3s resolution= %(_str_resolution)s
|
177 |
+
machep=%(machep)6s eps= %(_str_eps)s
|
178 |
+
negep =%(negep)6s epsneg= %(_str_epsneg)s
|
179 |
+
minexp=%(minexp)6s tiny= %(_str_tiny)s
|
180 |
+
maxexp=%(maxexp)6s max= %(_str_max)s
|
181 |
+
nexp =%(nexp)6s min= -max
|
182 |
+
---------------------------------------------------------------------
|
183 |
+
''' % self.__dict__
|
184 |
+
|
185 |
+
def __repr__(self):
|
186 |
+
c = self.__class__.__name__
|
187 |
+
d = self.__dict__.copy()
|
188 |
+
d['klass'] = c
|
189 |
+
return ("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s," \
|
190 |
+
+ " max=%(_str_max)s, dtype=%(dtype)s)") \
|
191 |
+
% d
|
192 |
+
|
193 |
+
|
194 |
+
class iinfo(object):
|
195 |
+
"""
|
196 |
+
iinfo(type)
|
197 |
+
|
198 |
+
Machine limits for integer types.
|
199 |
+
|
200 |
+
Attributes
|
201 |
+
----------
|
202 |
+
min : int
|
203 |
+
The smallest integer expressible by the type.
|
204 |
+
max : int
|
205 |
+
The largest integer expressible by the type.
|
206 |
+
|
207 |
+
Parameters
|
208 |
+
----------
|
209 |
+
type : integer type, dtype, or instance
|
210 |
+
The kind of integer data type to get information about.
|
211 |
+
|
212 |
+
See Also
|
213 |
+
--------
|
214 |
+
finfo : The equivalent for floating point data types.
|
215 |
+
|
216 |
+
Examples
|
217 |
+
--------
|
218 |
+
With types:
|
219 |
+
|
220 |
+
>>> ii16 = np.iinfo(np.int16)
|
221 |
+
>>> ii16.min
|
222 |
+
-32768
|
223 |
+
>>> ii16.max
|
224 |
+
32767
|
225 |
+
>>> ii32 = np.iinfo(np.int32)
|
226 |
+
>>> ii32.min
|
227 |
+
-2147483648
|
228 |
+
>>> ii32.max
|
229 |
+
2147483647
|
230 |
+
|
231 |
+
With instances:
|
232 |
+
|
233 |
+
>>> ii32 = np.iinfo(np.int32(10))
|
234 |
+
>>> ii32.min
|
235 |
+
-2147483648
|
236 |
+
>>> ii32.max
|
237 |
+
2147483647
|
238 |
+
|
239 |
+
"""
|
240 |
+
|
241 |
+
_min_vals = {}
|
242 |
+
_max_vals = {}
|
243 |
+
|
244 |
+
def __init__(self, int_type):
|
245 |
+
try:
|
246 |
+
self.dtype = numeric.dtype(int_type)
|
247 |
+
except TypeError:
|
248 |
+
self.dtype = numeric.dtype(type(int_type))
|
249 |
+
self.kind = self.dtype.kind
|
250 |
+
self.bits = self.dtype.itemsize * 8
|
251 |
+
self.key = "%s%d" % (self.kind, self.bits)
|
252 |
+
if not self.kind in 'iu':
|
253 |
+
raise ValueError("Invalid integer data type.")
|
254 |
+
|
255 |
+
def min(self):
|
256 |
+
"""Minimum value of given dtype."""
|
257 |
+
if self.kind == 'u':
|
258 |
+
return 0
|
259 |
+
else:
|
260 |
+
try:
|
261 |
+
val = iinfo._min_vals[self.key]
|
262 |
+
except KeyError:
|
263 |
+
val = int(-(1 << (self.bits-1)))
|
264 |
+
iinfo._min_vals[self.key] = val
|
265 |
+
return val
|
266 |
+
|
267 |
+
min = property(min)
|
268 |
+
|
269 |
+
def max(self):
|
270 |
+
"""Maximum value of given dtype."""
|
271 |
+
try:
|
272 |
+
val = iinfo._max_vals[self.key]
|
273 |
+
except KeyError:
|
274 |
+
if self.kind == 'u':
|
275 |
+
val = int((1 << self.bits) - 1)
|
276 |
+
else:
|
277 |
+
val = int((1 << (self.bits-1)) - 1)
|
278 |
+
iinfo._max_vals[self.key] = val
|
279 |
+
return val
|
280 |
+
|
281 |
+
max = property(max)
|
282 |
+
|
283 |
+
def __str__(self):
|
284 |
+
"""String representation."""
|
285 |
+
return '''\
|
286 |
+
Machine parameters for %(dtype)s
|
287 |
+
---------------------------------------------------------------------
|
288 |
+
min = %(min)s
|
289 |
+
max = %(max)s
|
290 |
+
---------------------------------------------------------------------
|
291 |
+
''' % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
|
292 |
+
|
293 |
+
def __repr__(self):
|
294 |
+
return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
|
295 |
+
self.min, self.max, self.dtype)
|
296 |
+
|
297 |
+
if __name__ == '__main__':
|
298 |
+
f = finfo(ntypes.single)
|
299 |
+
print('single epsilon:', f.eps)
|
300 |
+
print('single tiny:', f.tiny)
|
301 |
+
f = finfo(ntypes.float)
|
302 |
+
print('float epsilon:', f.eps)
|
303 |
+
print('float tiny:', f.tiny)
|
304 |
+
f = finfo(ntypes.longfloat)
|
305 |
+
print('longfloat epsilon:', f.eps)
|
306 |
+
print('longfloat tiny:', f.tiny)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/info.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Defines a multi-dimensional array and useful procedures for Numerical computation.
|
2 |
+
|
3 |
+
Functions
|
4 |
+
|
5 |
+
- array - NumPy Array construction
|
6 |
+
- zeros - Return an array of all zeros
|
7 |
+
- empty - Return an unitialized array
|
8 |
+
- shape - Return shape of sequence or array
|
9 |
+
- rank - Return number of dimensions
|
10 |
+
- size - Return number of elements in entire array or a
|
11 |
+
certain dimension
|
12 |
+
- fromstring - Construct array from (byte) string
|
13 |
+
- take - Select sub-arrays using sequence of indices
|
14 |
+
- put - Set sub-arrays using sequence of 1-D indices
|
15 |
+
- putmask - Set portion of arrays using a mask
|
16 |
+
- reshape - Return array with new shape
|
17 |
+
- repeat - Repeat elements of array
|
18 |
+
- choose - Construct new array from indexed array tuple
|
19 |
+
- correlate - Correlate two 1-d arrays
|
20 |
+
- searchsorted - Search for element in 1-d array
|
21 |
+
- sum - Total sum over a specified dimension
|
22 |
+
- average - Average, possibly weighted, over axis or array.
|
23 |
+
- cumsum - Cumulative sum over a specified dimension
|
24 |
+
- product - Total product over a specified dimension
|
25 |
+
- cumproduct - Cumulative product over a specified dimension
|
26 |
+
- alltrue - Logical and over an entire axis
|
27 |
+
- sometrue - Logical or over an entire axis
|
28 |
+
- allclose - Tests if sequences are essentially equal
|
29 |
+
|
30 |
+
More Functions:
|
31 |
+
|
32 |
+
- arange - Return regularly spaced array
|
33 |
+
- asarray - Guarantee NumPy array
|
34 |
+
- convolve - Convolve two 1-d arrays
|
35 |
+
- swapaxes - Exchange axes
|
36 |
+
- concatenate - Join arrays together
|
37 |
+
- transpose - Permute axes
|
38 |
+
- sort - Sort elements of array
|
39 |
+
- argsort - Indices of sorted array
|
40 |
+
- argmax - Index of largest value
|
41 |
+
- argmin - Index of smallest value
|
42 |
+
- inner - Innerproduct of two arrays
|
43 |
+
- dot - Dot product (matrix multiplication)
|
44 |
+
- outer - Outerproduct of two arrays
|
45 |
+
- resize - Return array with arbitrary new shape
|
46 |
+
- indices - Tuple of indices
|
47 |
+
- fromfunction - Construct array from universal function
|
48 |
+
- diagonal - Return diagonal array
|
49 |
+
- trace - Trace of array
|
50 |
+
- dump - Dump array to file object (pickle)
|
51 |
+
- dumps - Return pickled string representing data
|
52 |
+
- load - Return array stored in file object
|
53 |
+
- loads - Return array from pickled string
|
54 |
+
- ravel - Return array as 1-D
|
55 |
+
- nonzero - Indices of nonzero elements for 1-D array
|
56 |
+
- shape - Shape of array
|
57 |
+
- where - Construct array from binary result
|
58 |
+
- compress - Elements of array where condition is true
|
59 |
+
- clip - Clip array between two values
|
60 |
+
- ones - Array of all ones
|
61 |
+
- identity - 2-D identity array (matrix)
|
62 |
+
|
63 |
+
(Universal) Math Functions
|
64 |
+
|
65 |
+
add logical_or exp
|
66 |
+
subtract logical_xor log
|
67 |
+
multiply logical_not log10
|
68 |
+
divide maximum sin
|
69 |
+
divide_safe minimum sinh
|
70 |
+
conjugate bitwise_and sqrt
|
71 |
+
power bitwise_or tan
|
72 |
+
absolute bitwise_xor tanh
|
73 |
+
negative invert ceil
|
74 |
+
greater left_shift fabs
|
75 |
+
greater_equal right_shift floor
|
76 |
+
less arccos arctan2
|
77 |
+
less_equal arcsin fmod
|
78 |
+
equal arctan hypot
|
79 |
+
not_equal cos around
|
80 |
+
logical_and cosh sign
|
81 |
+
arccosh arcsinh arctanh
|
82 |
+
|
83 |
+
"""
|
84 |
+
from __future__ import division, absolute_import, print_function
|
85 |
+
|
86 |
+
depends = ['testing']
|
87 |
+
global_symbols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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Machine arithmetics - determine the parameters of the
|
3 |
+
floating-point arithmetic system
|
4 |
+
|
5 |
+
Author: Pearu Peterson, September 2003
|
6 |
+
|
7 |
+
"""
|
8 |
+
from __future__ import division, absolute_import, print_function
|
9 |
+
|
10 |
+
__all__ = ['MachAr']
|
11 |
+
|
12 |
+
from numpy.core.fromnumeric import any
|
13 |
+
from numpy.core.numeric import errstate
|
14 |
+
|
15 |
+
# Need to speed this up...especially for longfloat
|
16 |
+
|
17 |
+
class MachAr(object):
|
18 |
+
"""
|
19 |
+
Diagnosing machine parameters.
|
20 |
+
|
21 |
+
Attributes
|
22 |
+
----------
|
23 |
+
ibeta : int
|
24 |
+
Radix in which numbers are represented.
|
25 |
+
it : int
|
26 |
+
Number of base-`ibeta` digits in the floating point mantissa M.
|
27 |
+
machep : int
|
28 |
+
Exponent of the smallest (most negative) power of `ibeta` that,
|
29 |
+
added to 1.0, gives something different from 1.0
|
30 |
+
eps : float
|
31 |
+
Floating-point number ``beta**machep`` (floating point precision)
|
32 |
+
negep : int
|
33 |
+
Exponent of the smallest power of `ibeta` that, substracted
|
34 |
+
from 1.0, gives something different from 1.0.
|
35 |
+
epsneg : float
|
36 |
+
Floating-point number ``beta**negep``.
|
37 |
+
iexp : int
|
38 |
+
Number of bits in the exponent (including its sign and bias).
|
39 |
+
minexp : int
|
40 |
+
Smallest (most negative) power of `ibeta` consistent with there
|
41 |
+
being no leading zeros in the mantissa.
|
42 |
+
xmin : float
|
43 |
+
Floating point number ``beta**minexp`` (the smallest [in
|
44 |
+
magnitude] usable floating value).
|
45 |
+
maxexp : int
|
46 |
+
Smallest (positive) power of `ibeta` that causes overflow.
|
47 |
+
xmax : float
|
48 |
+
``(1-epsneg) * beta**maxexp`` (the largest [in magnitude]
|
49 |
+
usable floating value).
|
50 |
+
irnd : int
|
51 |
+
In ``range(6)``, information on what kind of rounding is done
|
52 |
+
in addition, and on how underflow is handled.
|
53 |
+
ngrd : int
|
54 |
+
Number of 'guard digits' used when truncating the product
|
55 |
+
of two mantissas to fit the representation.
|
56 |
+
epsilon : float
|
57 |
+
Same as `eps`.
|
58 |
+
tiny : float
|
59 |
+
Same as `xmin`.
|
60 |
+
huge : float
|
61 |
+
Same as `xmax`.
|
62 |
+
precision : float
|
63 |
+
``- int(-log10(eps))``
|
64 |
+
resolution : float
|
65 |
+
``- 10**(-precision)``
|
66 |
+
|
67 |
+
Parameters
|
68 |
+
----------
|
69 |
+
float_conv : function, optional
|
70 |
+
Function that converts an integer or integer array to a float
|
71 |
+
or float array. Default is `float`.
|
72 |
+
int_conv : function, optional
|
73 |
+
Function that converts a float or float array to an integer or
|
74 |
+
integer array. Default is `int`.
|
75 |
+
float_to_float : function, optional
|
76 |
+
Function that converts a float array to float. Default is `float`.
|
77 |
+
Note that this does not seem to do anything useful in the current
|
78 |
+
implementation.
|
79 |
+
float_to_str : function, optional
|
80 |
+
Function that converts a single float to a string. Default is
|
81 |
+
``lambda v:'%24.16e' %v``.
|
82 |
+
title : str, optional
|
83 |
+
Title that is printed in the string representation of `MachAr`.
|
84 |
+
|
85 |
+
See Also
|
86 |
+
--------
|
87 |
+
finfo : Machine limits for floating point types.
|
88 |
+
iinfo : Machine limits for integer types.
|
89 |
+
|
90 |
+
References
|
91 |
+
----------
|
92 |
+
.. [1] Press, Teukolsky, Vetterling and Flannery,
|
93 |
+
"Numerical Recipes in C++," 2nd ed,
|
94 |
+
Cambridge University Press, 2002, p. 31.
|
95 |
+
|
96 |
+
"""
|
97 |
+
def __init__(self, float_conv=float,int_conv=int,
|
98 |
+
float_to_float=float,
|
99 |
+
float_to_str = lambda v:'%24.16e' % v,
|
100 |
+
title = 'Python floating point number'):
|
101 |
+
"""
|
102 |
+
float_conv - convert integer to float (array)
|
103 |
+
int_conv - convert float (array) to integer
|
104 |
+
float_to_float - convert float array to float
|
105 |
+
float_to_str - convert array float to str
|
106 |
+
title - description of used floating point numbers
|
107 |
+
"""
|
108 |
+
# We ignore all errors here because we are purposely triggering
|
109 |
+
# underflow to detect the properties of the runninng arch.
|
110 |
+
with errstate(under='ignore'):
|
111 |
+
self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)
|
112 |
+
|
113 |
+
def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title):
|
114 |
+
max_iterN = 10000
|
115 |
+
msg = "Did not converge after %d tries with %s"
|
116 |
+
one = float_conv(1)
|
117 |
+
two = one + one
|
118 |
+
zero = one - one
|
119 |
+
|
120 |
+
# Do we really need to do this? Aren't they 2 and 2.0?
|
121 |
+
# Determine ibeta and beta
|
122 |
+
a = one
|
123 |
+
for _ in range(max_iterN):
|
124 |
+
a = a + a
|
125 |
+
temp = a + one
|
126 |
+
temp1 = temp - a
|
127 |
+
if any(temp1 - one != zero):
|
128 |
+
break
|
129 |
+
else:
|
130 |
+
raise RuntimeError(msg % (_, one.dtype))
|
131 |
+
b = one
|
132 |
+
for _ in range(max_iterN):
|
133 |
+
b = b + b
|
134 |
+
temp = a + b
|
135 |
+
itemp = int_conv(temp-a)
|
136 |
+
if any(itemp != 0):
|
137 |
+
break
|
138 |
+
else:
|
139 |
+
raise RuntimeError(msg % (_, one.dtype))
|
140 |
+
ibeta = itemp
|
141 |
+
beta = float_conv(ibeta)
|
142 |
+
|
143 |
+
# Determine it and irnd
|
144 |
+
it = -1
|
145 |
+
b = one
|
146 |
+
for _ in range(max_iterN):
|
147 |
+
it = it + 1
|
148 |
+
b = b * beta
|
149 |
+
temp = b + one
|
150 |
+
temp1 = temp - b
|
151 |
+
if any(temp1 - one != zero):
|
152 |
+
break
|
153 |
+
else:
|
154 |
+
raise RuntimeError(msg % (_, one.dtype))
|
155 |
+
|
156 |
+
betah = beta / two
|
157 |
+
a = one
|
158 |
+
for _ in range(max_iterN):
|
159 |
+
a = a + a
|
160 |
+
temp = a + one
|
161 |
+
temp1 = temp - a
|
162 |
+
if any(temp1 - one != zero):
|
163 |
+
break
|
164 |
+
else:
|
165 |
+
raise RuntimeError(msg % (_, one.dtype))
|
166 |
+
temp = a + betah
|
167 |
+
irnd = 0
|
168 |
+
if any(temp-a != zero):
|
169 |
+
irnd = 1
|
170 |
+
tempa = a + beta
|
171 |
+
temp = tempa + betah
|
172 |
+
if irnd==0 and any(temp-tempa != zero):
|
173 |
+
irnd = 2
|
174 |
+
|
175 |
+
# Determine negep and epsneg
|
176 |
+
negep = it + 3
|
177 |
+
betain = one / beta
|
178 |
+
a = one
|
179 |
+
for i in range(negep):
|
180 |
+
a = a * betain
|
181 |
+
b = a
|
182 |
+
for _ in range(max_iterN):
|
183 |
+
temp = one - a
|
184 |
+
if any(temp-one != zero):
|
185 |
+
break
|
186 |
+
a = a * beta
|
187 |
+
negep = negep - 1
|
188 |
+
# Prevent infinite loop on PPC with gcc 4.0:
|
189 |
+
if negep < 0:
|
190 |
+
raise RuntimeError("could not determine machine tolerance "
|
191 |
+
"for 'negep', locals() -> %s" % (locals()))
|
192 |
+
else:
|
193 |
+
raise RuntimeError(msg % (_, one.dtype))
|
194 |
+
negep = -negep
|
195 |
+
epsneg = a
|
196 |
+
|
197 |
+
# Determine machep and eps
|
198 |
+
machep = - it - 3
|
199 |
+
a = b
|
200 |
+
|
201 |
+
for _ in range(max_iterN):
|
202 |
+
temp = one + a
|
203 |
+
if any(temp-one != zero):
|
204 |
+
break
|
205 |
+
a = a * beta
|
206 |
+
machep = machep + 1
|
207 |
+
else:
|
208 |
+
raise RuntimeError(msg % (_, one.dtype))
|
209 |
+
eps = a
|
210 |
+
|
211 |
+
# Determine ngrd
|
212 |
+
ngrd = 0
|
213 |
+
temp = one + eps
|
214 |
+
if irnd==0 and any(temp*one - one != zero):
|
215 |
+
ngrd = 1
|
216 |
+
|
217 |
+
# Determine iexp
|
218 |
+
i = 0
|
219 |
+
k = 1
|
220 |
+
z = betain
|
221 |
+
t = one + eps
|
222 |
+
nxres = 0
|
223 |
+
for _ in range(max_iterN):
|
224 |
+
y = z
|
225 |
+
z = y*y
|
226 |
+
a = z*one # Check here for underflow
|
227 |
+
temp = z*t
|
228 |
+
if any(a+a == zero) or any(abs(z)>=y):
|
229 |
+
break
|
230 |
+
temp1 = temp * betain
|
231 |
+
if any(temp1*beta == z):
|
232 |
+
break
|
233 |
+
i = i + 1
|
234 |
+
k = k + k
|
235 |
+
else:
|
236 |
+
raise RuntimeError(msg % (_, one.dtype))
|
237 |
+
if ibeta != 10:
|
238 |
+
iexp = i + 1
|
239 |
+
mx = k + k
|
240 |
+
else:
|
241 |
+
iexp = 2
|
242 |
+
iz = ibeta
|
243 |
+
while k >= iz:
|
244 |
+
iz = iz * ibeta
|
245 |
+
iexp = iexp + 1
|
246 |
+
mx = iz + iz - 1
|
247 |
+
|
248 |
+
# Determine minexp and xmin
|
249 |
+
for _ in range(max_iterN):
|
250 |
+
xmin = y
|
251 |
+
y = y * betain
|
252 |
+
a = y * one
|
253 |
+
temp = y * t
|
254 |
+
if any(a+a != zero) and any(abs(y) < xmin):
|
255 |
+
k = k + 1
|
256 |
+
temp1 = temp * betain
|
257 |
+
if any(temp1*beta == y) and any(temp != y):
|
258 |
+
nxres = 3
|
259 |
+
xmin = y
|
260 |
+
break
|
261 |
+
else:
|
262 |
+
break
|
263 |
+
else:
|
264 |
+
raise RuntimeError(msg % (_, one.dtype))
|
265 |
+
minexp = -k
|
266 |
+
|
267 |
+
# Determine maxexp, xmax
|
268 |
+
if mx <= k + k - 3 and ibeta != 10:
|
269 |
+
mx = mx + mx
|
270 |
+
iexp = iexp + 1
|
271 |
+
maxexp = mx + minexp
|
272 |
+
irnd = irnd + nxres
|
273 |
+
if irnd >= 2:
|
274 |
+
maxexp = maxexp - 2
|
275 |
+
i = maxexp + minexp
|
276 |
+
if ibeta == 2 and not i:
|
277 |
+
maxexp = maxexp - 1
|
278 |
+
if i > 20:
|
279 |
+
maxexp = maxexp - 1
|
280 |
+
if any(a != y):
|
281 |
+
maxexp = maxexp - 2
|
282 |
+
xmax = one - epsneg
|
283 |
+
if any(xmax*one != xmax):
|
284 |
+
xmax = one - beta*epsneg
|
285 |
+
xmax = xmax / (xmin*beta*beta*beta)
|
286 |
+
i = maxexp + minexp + 3
|
287 |
+
for j in range(i):
|
288 |
+
if ibeta==2:
|
289 |
+
xmax = xmax + xmax
|
290 |
+
else:
|
291 |
+
xmax = xmax * beta
|
292 |
+
|
293 |
+
self.ibeta = ibeta
|
294 |
+
self.it = it
|
295 |
+
self.negep = negep
|
296 |
+
self.epsneg = float_to_float(epsneg)
|
297 |
+
self._str_epsneg = float_to_str(epsneg)
|
298 |
+
self.machep = machep
|
299 |
+
self.eps = float_to_float(eps)
|
300 |
+
self._str_eps = float_to_str(eps)
|
301 |
+
self.ngrd = ngrd
|
302 |
+
self.iexp = iexp
|
303 |
+
self.minexp = minexp
|
304 |
+
self.xmin = float_to_float(xmin)
|
305 |
+
self._str_xmin = float_to_str(xmin)
|
306 |
+
self.maxexp = maxexp
|
307 |
+
self.xmax = float_to_float(xmax)
|
308 |
+
self._str_xmax = float_to_str(xmax)
|
309 |
+
self.irnd = irnd
|
310 |
+
|
311 |
+
self.title = title
|
312 |
+
# Commonly used parameters
|
313 |
+
self.epsilon = self.eps
|
314 |
+
self.tiny = self.xmin
|
315 |
+
self.huge = self.xmax
|
316 |
+
|
317 |
+
import math
|
318 |
+
self.precision = int(-math.log10(float_to_float(self.eps)))
|
319 |
+
ten = two + two + two + two + two
|
320 |
+
resolution = ten ** (-self.precision)
|
321 |
+
self.resolution = float_to_float(resolution)
|
322 |
+
self._str_resolution = float_to_str(resolution)
|
323 |
+
|
324 |
+
def __str__(self):
|
325 |
+
return '''\
|
326 |
+
Machine parameters for %(title)s
|
327 |
+
---------------------------------------------------------------------
|
328 |
+
ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s
|
329 |
+
machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon)
|
330 |
+
negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg)
|
331 |
+
minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny)
|
332 |
+
maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge)
|
333 |
+
---------------------------------------------------------------------
|
334 |
+
''' % self.__dict__
|
335 |
+
|
336 |
+
|
337 |
+
if __name__ == '__main__':
|
338 |
+
print(MachAr())
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/memmap.py
ADDED
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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eric import uint8, ndarray, dtype
|
10 |
+
from numpy.compat import long, basestring
|
11 |
+
|
12 |
+
dtypedescr = dtype
|
13 |
+
valid_filemodes = ["r", "c", "r+", "w+"]
|
14 |
+
writeable_filemodes = ["r+", "w+"]
|
15 |
+
|
16 |
+
mode_equivalents = {
|
17 |
+
"readonly":"r",
|
18 |
+
"copyonwrite":"c",
|
19 |
+
"readwrite":"r+",
|
20 |
+
"write":"w+"
|
21 |
+
}
|
22 |
+
|
23 |
+
class memmap(ndarray):
|
24 |
+
"""
|
25 |
+
Create a memory-map to an array stored in a *binary* file on disk.
|
26 |
+
|
27 |
+
Memory-mapped files are used for accessing small segments of large files
|
28 |
+
on disk, without reading the entire file into memory. Numpy's
|
29 |
+
memmap's are array-like objects. This differs from Python's ``mmap``
|
30 |
+
module, which uses file-like objects.
|
31 |
+
|
32 |
+
This subclass of ndarray has some unpleasant interactions with
|
33 |
+
some operations, because it doesn't quite fit properly as a subclass.
|
34 |
+
An alternative to using this subclass is to create the ``mmap``
|
35 |
+
object yourself, then create an ndarray with ndarray.__new__ directly,
|
36 |
+
passing the object created in its 'buffer=' parameter.
|
37 |
+
|
38 |
+
This class may at some point be turned into a factory function
|
39 |
+
which returns a view into an mmap buffer.
|
40 |
+
|
41 |
+
Delete the memmap instance to close.
|
42 |
+
|
43 |
+
|
44 |
+
Parameters
|
45 |
+
----------
|
46 |
+
filename : str or file-like object
|
47 |
+
The file name or file object to be used as the array data buffer.
|
48 |
+
dtype : data-type, optional
|
49 |
+
The data-type used to interpret the file contents.
|
50 |
+
Default is `uint8`.
|
51 |
+
mode : {'r+', 'r', 'w+', 'c'}, optional
|
52 |
+
The file is opened in this mode:
|
53 |
+
|
54 |
+
+------+-------------------------------------------------------------+
|
55 |
+
| 'r' | Open existing file for reading only. |
|
56 |
+
+------+-------------------------------------------------------------+
|
57 |
+
| 'r+' | Open existing file for reading and writing. |
|
58 |
+
+------+-------------------------------------------------------------+
|
59 |
+
| 'w+' | Create or overwrite existing file for reading and writing. |
|
60 |
+
+------+-------------------------------------------------------------+
|
61 |
+
| 'c' | Copy-on-write: assignments affect data in memory, but |
|
62 |
+
| | changes are not saved to disk. The file on disk is |
|
63 |
+
| | read-only. |
|
64 |
+
+------+-------------------------------------------------------------+
|
65 |
+
|
66 |
+
Default is 'r+'.
|
67 |
+
offset : int, optional
|
68 |
+
In the file, array data starts at this offset. Since `offset` is
|
69 |
+
measured in bytes, it should normally be a multiple of the byte-size
|
70 |
+
of `dtype`. When ``mode != 'r'``, even positive offsets beyond end of
|
71 |
+
file are valid; The file will be extended to accommodate the
|
72 |
+
additional data. By default, ``memmap`` will start at the beginning of
|
73 |
+
the file, even if ``filename`` is a file pointer ``fp`` and
|
74 |
+
``fp.tell() != 0``.
|
75 |
+
shape : tuple, optional
|
76 |
+
The desired shape of the array. If ``mode == 'r'`` and the number
|
77 |
+
of remaining bytes after `offset` is not a multiple of the byte-size
|
78 |
+
of `dtype`, you must specify `shape`. By default, the returned array
|
79 |
+
will be 1-D with the number of elements determined by file size
|
80 |
+
and data-type.
|
81 |
+
order : {'C', 'F'}, optional
|
82 |
+
Specify the order of the ndarray memory layout: C (row-major) or
|
83 |
+
Fortran (column-major). This only has an effect if the shape is
|
84 |
+
greater than 1-D. The default order is 'C'.
|
85 |
+
|
86 |
+
Attributes
|
87 |
+
----------
|
88 |
+
filename : str
|
89 |
+
Path to the mapped file.
|
90 |
+
offset : int
|
91 |
+
Offset position in the file.
|
92 |
+
mode : str
|
93 |
+
File mode.
|
94 |
+
|
95 |
+
Methods
|
96 |
+
-------
|
97 |
+
flush
|
98 |
+
Flush any changes in memory to file on disk.
|
99 |
+
When you delete a memmap object, flush is called first to write
|
100 |
+
changes to disk before removing the object.
|
101 |
+
|
102 |
+
|
103 |
+
Notes
|
104 |
+
-----
|
105 |
+
The memmap object can be used anywhere an ndarray is accepted.
|
106 |
+
Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
|
107 |
+
``True``.
|
108 |
+
|
109 |
+
Memory-mapped arrays use the Python memory-map object which
|
110 |
+
(prior to Python 2.5) does not allow files to be larger than a
|
111 |
+
certain size depending on the platform. This size is always < 2GB
|
112 |
+
even on 64-bit systems.
|
113 |
+
|
114 |
+
Examples
|
115 |
+
--------
|
116 |
+
>>> data = np.arange(12, dtype='float32')
|
117 |
+
>>> data.resize((3,4))
|
118 |
+
|
119 |
+
This example uses a temporary file so that doctest doesn't write
|
120 |
+
files to your directory. You would use a 'normal' filename.
|
121 |
+
|
122 |
+
>>> from tempfile import mkdtemp
|
123 |
+
>>> import os.path as path
|
124 |
+
>>> filename = path.join(mkdtemp(), 'newfile.dat')
|
125 |
+
|
126 |
+
Create a memmap with dtype and shape that matches our data:
|
127 |
+
|
128 |
+
>>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
|
129 |
+
>>> fp
|
130 |
+
memmap([[ 0., 0., 0., 0.],
|
131 |
+
[ 0., 0., 0., 0.],
|
132 |
+
[ 0., 0., 0., 0.]], dtype=float32)
|
133 |
+
|
134 |
+
Write data to memmap array:
|
135 |
+
|
136 |
+
>>> fp[:] = data[:]
|
137 |
+
>>> fp
|
138 |
+
memmap([[ 0., 1., 2., 3.],
|
139 |
+
[ 4., 5., 6., 7.],
|
140 |
+
[ 8., 9., 10., 11.]], dtype=float32)
|
141 |
+
|
142 |
+
>>> fp.filename == path.abspath(filename)
|
143 |
+
True
|
144 |
+
|
145 |
+
Deletion flushes memory changes to disk before removing the object:
|
146 |
+
|
147 |
+
>>> del fp
|
148 |
+
|
149 |
+
Load the memmap and verify data was stored:
|
150 |
+
|
151 |
+
>>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
|
152 |
+
>>> newfp
|
153 |
+
memmap([[ 0., 1., 2., 3.],
|
154 |
+
[ 4., 5., 6., 7.],
|
155 |
+
[ 8., 9., 10., 11.]], dtype=float32)
|
156 |
+
|
157 |
+
Read-only memmap:
|
158 |
+
|
159 |
+
>>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
|
160 |
+
>>> fpr.flags.writeable
|
161 |
+
False
|
162 |
+
|
163 |
+
Copy-on-write memmap:
|
164 |
+
|
165 |
+
>>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
|
166 |
+
>>> fpc.flags.writeable
|
167 |
+
True
|
168 |
+
|
169 |
+
It's possible to assign to copy-on-write array, but values are only
|
170 |
+
written into the memory copy of the array, and not written to disk:
|
171 |
+
|
172 |
+
>>> fpc
|
173 |
+
memmap([[ 0., 1., 2., 3.],
|
174 |
+
[ 4., 5., 6., 7.],
|
175 |
+
[ 8., 9., 10., 11.]], dtype=float32)
|
176 |
+
>>> fpc[0,:] = 0
|
177 |
+
>>> fpc
|
178 |
+
memmap([[ 0., 0., 0., 0.],
|
179 |
+
[ 4., 5., 6., 7.],
|
180 |
+
[ 8., 9., 10., 11.]], dtype=float32)
|
181 |
+
|
182 |
+
File on disk is unchanged:
|
183 |
+
|
184 |
+
>>> fpr
|
185 |
+
memmap([[ 0., 1., 2., 3.],
|
186 |
+
[ 4., 5., 6., 7.],
|
187 |
+
[ 8., 9., 10., 11.]], dtype=float32)
|
188 |
+
|
189 |
+
Offset into a memmap:
|
190 |
+
|
191 |
+
>>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
|
192 |
+
>>> fpo
|
193 |
+
memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
|
194 |
+
|
195 |
+
"""
|
196 |
+
|
197 |
+
__array_priority__ = -100.0
|
198 |
+
def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
|
199 |
+
shape=None, order='C'):
|
200 |
+
# Import here to minimize 'import numpy' overhead
|
201 |
+
import mmap
|
202 |
+
import os.path
|
203 |
+
try:
|
204 |
+
mode = mode_equivalents[mode]
|
205 |
+
except KeyError:
|
206 |
+
if mode not in valid_filemodes:
|
207 |
+
raise ValueError("mode must be one of %s" %
|
208 |
+
(valid_filemodes + list(mode_equivalents.keys())))
|
209 |
+
|
210 |
+
if hasattr(filename, 'read'):
|
211 |
+
fid = filename
|
212 |
+
own_file = False
|
213 |
+
else:
|
214 |
+
fid = open(filename, (mode == 'c' and 'r' or mode)+'b')
|
215 |
+
own_file = True
|
216 |
+
|
217 |
+
if (mode == 'w+') and shape is None:
|
218 |
+
raise ValueError("shape must be given")
|
219 |
+
|
220 |
+
fid.seek(0, 2)
|
221 |
+
flen = fid.tell()
|
222 |
+
descr = dtypedescr(dtype)
|
223 |
+
_dbytes = descr.itemsize
|
224 |
+
|
225 |
+
if shape is None:
|
226 |
+
bytes = flen - offset
|
227 |
+
if (bytes % _dbytes):
|
228 |
+
fid.close()
|
229 |
+
raise ValueError("Size of available data is not a "
|
230 |
+
"multiple of the data-type size.")
|
231 |
+
size = bytes // _dbytes
|
232 |
+
shape = (size,)
|
233 |
+
else:
|
234 |
+
if not isinstance(shape, tuple):
|
235 |
+
shape = (shape,)
|
236 |
+
size = 1
|
237 |
+
for k in shape:
|
238 |
+
size *= k
|
239 |
+
|
240 |
+
bytes = long(offset + size*_dbytes)
|
241 |
+
|
242 |
+
if mode == 'w+' or (mode == 'r+' and flen < bytes):
|
243 |
+
fid.seek(bytes - 1, 0)
|
244 |
+
fid.write(np.compat.asbytes('\0'))
|
245 |
+
fid.flush()
|
246 |
+
|
247 |
+
if mode == 'c':
|
248 |
+
acc = mmap.ACCESS_COPY
|
249 |
+
elif mode == 'r':
|
250 |
+
acc = mmap.ACCESS_READ
|
251 |
+
else:
|
252 |
+
acc = mmap.ACCESS_WRITE
|
253 |
+
|
254 |
+
start = offset - offset % mmap.ALLOCATIONGRANULARITY
|
255 |
+
bytes -= start
|
256 |
+
offset -= start
|
257 |
+
mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start)
|
258 |
+
|
259 |
+
self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm,
|
260 |
+
offset=offset, order=order)
|
261 |
+
self._mmap = mm
|
262 |
+
self.offset = offset
|
263 |
+
self.mode = mode
|
264 |
+
|
265 |
+
if isinstance(filename, basestring):
|
266 |
+
self.filename = os.path.abspath(filename)
|
267 |
+
# py3 returns int for TemporaryFile().name
|
268 |
+
elif (hasattr(filename, "name") and
|
269 |
+
isinstance(filename.name, basestring)):
|
270 |
+
self.filename = os.path.abspath(filename.name)
|
271 |
+
# same as memmap copies (e.g. memmap + 1)
|
272 |
+
else:
|
273 |
+
self.filename = None
|
274 |
+
|
275 |
+
if own_file:
|
276 |
+
fid.close()
|
277 |
+
|
278 |
+
return self
|
279 |
+
|
280 |
+
def __array_finalize__(self, obj):
|
281 |
+
if hasattr(obj, '_mmap') and np.may_share_memory(self, obj):
|
282 |
+
self._mmap = obj._mmap
|
283 |
+
self.filename = obj.filename
|
284 |
+
self.offset = obj.offset
|
285 |
+
self.mode = obj.mode
|
286 |
+
else:
|
287 |
+
self._mmap = None
|
288 |
+
self.filename = None
|
289 |
+
self.offset = None
|
290 |
+
self.mode = None
|
291 |
+
|
292 |
+
def flush(self):
|
293 |
+
"""
|
294 |
+
Write any changes in the array to the file on disk.
|
295 |
+
|
296 |
+
For further information, see `memmap`.
|
297 |
+
|
298 |
+
Parameters
|
299 |
+
----------
|
300 |
+
None
|
301 |
+
|
302 |
+
See Also
|
303 |
+
--------
|
304 |
+
memmap
|
305 |
+
|
306 |
+
"""
|
307 |
+
if self.base is not None and hasattr(self.base, 'flush'):
|
308 |
+
self.base.flush()
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/numeric.py
ADDED
@@ -0,0 +1,2842 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
import warnings
|
6 |
+
import collections
|
7 |
+
from . import multiarray
|
8 |
+
from . import umath
|
9 |
+
from .umath import (invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE,
|
10 |
+
ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG,
|
11 |
+
ERR_DEFAULT, PINF, NAN)
|
12 |
+
from . import numerictypes
|
13 |
+
from .numerictypes import longlong, intc, int_, float_, complex_, bool_
|
14 |
+
|
15 |
+
if sys.version_info[0] >= 3:
|
16 |
+
import pickle
|
17 |
+
basestring = str
|
18 |
+
else:
|
19 |
+
import cPickle as pickle
|
20 |
+
|
21 |
+
loads = pickle.loads
|
22 |
+
|
23 |
+
|
24 |
+
__all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
|
25 |
+
'arange', 'array', 'zeros', 'count_nonzero',
|
26 |
+
'empty', 'broadcast', 'dtype', 'fromstring', 'fromfile',
|
27 |
+
'frombuffer', 'int_asbuffer', 'where', 'argwhere', 'copyto',
|
28 |
+
'concatenate', 'fastCopyAndTranspose', 'lexsort', 'set_numeric_ops',
|
29 |
+
'can_cast', 'promote_types', 'min_scalar_type', 'result_type',
|
30 |
+
'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray',
|
31 |
+
'isfortran', 'empty_like', 'zeros_like', 'ones_like',
|
32 |
+
'correlate', 'convolve', 'inner', 'dot', 'einsum', 'outer', 'vdot',
|
33 |
+
'alterdot', 'restoredot', 'roll', 'rollaxis', 'cross', 'tensordot',
|
34 |
+
'array2string', 'get_printoptions', 'set_printoptions',
|
35 |
+
'array_repr', 'array_str', 'set_string_function',
|
36 |
+
'little_endian', 'require',
|
37 |
+
'fromiter', 'array_equal', 'array_equiv',
|
38 |
+
'indices', 'fromfunction', 'isclose',
|
39 |
+
'load', 'loads', 'isscalar', 'binary_repr', 'base_repr',
|
40 |
+
'ones', 'identity', 'allclose', 'compare_chararrays', 'putmask',
|
41 |
+
'seterr', 'geterr', 'setbufsize', 'getbufsize',
|
42 |
+
'seterrcall', 'geterrcall', 'errstate', 'flatnonzero',
|
43 |
+
'Inf', 'inf', 'infty', 'Infinity',
|
44 |
+
'nan', 'NaN', 'False_', 'True_', 'bitwise_not',
|
45 |
+
'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS',
|
46 |
+
'ComplexWarning', 'may_share_memory', 'full', 'full_like']
|
47 |
+
|
48 |
+
if sys.version_info[0] < 3:
|
49 |
+
__all__.extend(['getbuffer', 'newbuffer'])
|
50 |
+
|
51 |
+
|
52 |
+
class ComplexWarning(RuntimeWarning):
|
53 |
+
"""
|
54 |
+
The warning raised when casting a complex dtype to a real dtype.
|
55 |
+
|
56 |
+
As implemented, casting a complex number to a real discards its imaginary
|
57 |
+
part, but this behavior may not be what the user actually wants.
|
58 |
+
|
59 |
+
"""
|
60 |
+
pass
|
61 |
+
|
62 |
+
bitwise_not = invert
|
63 |
+
|
64 |
+
CLIP = multiarray.CLIP
|
65 |
+
WRAP = multiarray.WRAP
|
66 |
+
RAISE = multiarray.RAISE
|
67 |
+
MAXDIMS = multiarray.MAXDIMS
|
68 |
+
ALLOW_THREADS = multiarray.ALLOW_THREADS
|
69 |
+
BUFSIZE = multiarray.BUFSIZE
|
70 |
+
|
71 |
+
ndarray = multiarray.ndarray
|
72 |
+
flatiter = multiarray.flatiter
|
73 |
+
nditer = multiarray.nditer
|
74 |
+
nested_iters = multiarray.nested_iters
|
75 |
+
broadcast = multiarray.broadcast
|
76 |
+
dtype = multiarray.dtype
|
77 |
+
copyto = multiarray.copyto
|
78 |
+
ufunc = type(sin)
|
79 |
+
|
80 |
+
|
81 |
+
def zeros_like(a, dtype=None, order='K', subok=True):
|
82 |
+
"""
|
83 |
+
Return an array of zeros with the same shape and type as a given array.
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
----------
|
87 |
+
a : array_like
|
88 |
+
The shape and data-type of `a` define these same attributes of
|
89 |
+
the returned array.
|
90 |
+
dtype : data-type, optional
|
91 |
+
.. versionadded:: 1.6.0
|
92 |
+
Overrides the data type of the result.
|
93 |
+
order : {'C', 'F', 'A', or 'K'}, optional
|
94 |
+
.. versionadded:: 1.6.0
|
95 |
+
Overrides the memory layout of the result. 'C' means C-order,
|
96 |
+
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
|
97 |
+
'C' otherwise. 'K' means match the layout of `a` as closely
|
98 |
+
as possible.
|
99 |
+
subok : bool, optional.
|
100 |
+
If True, then the newly created array will use the sub-class
|
101 |
+
type of 'a', otherwise it will be a base-class array. Defaults
|
102 |
+
to True.
|
103 |
+
|
104 |
+
Returns
|
105 |
+
-------
|
106 |
+
out : ndarray
|
107 |
+
Array of zeros with the same shape and type as `a`.
|
108 |
+
|
109 |
+
See Also
|
110 |
+
--------
|
111 |
+
ones_like : Return an array of ones with shape and type of input.
|
112 |
+
empty_like : Return an empty array with shape and type of input.
|
113 |
+
zeros : Return a new array setting values to zero.
|
114 |
+
ones : Return a new array setting values to one.
|
115 |
+
empty : Return a new uninitialized array.
|
116 |
+
|
117 |
+
Examples
|
118 |
+
--------
|
119 |
+
>>> x = np.arange(6)
|
120 |
+
>>> x = x.reshape((2, 3))
|
121 |
+
>>> x
|
122 |
+
array([[0, 1, 2],
|
123 |
+
[3, 4, 5]])
|
124 |
+
>>> np.zeros_like(x)
|
125 |
+
array([[0, 0, 0],
|
126 |
+
[0, 0, 0]])
|
127 |
+
|
128 |
+
>>> y = np.arange(3, dtype=np.float)
|
129 |
+
>>> y
|
130 |
+
array([ 0., 1., 2.])
|
131 |
+
>>> np.zeros_like(y)
|
132 |
+
array([ 0., 0., 0.])
|
133 |
+
|
134 |
+
"""
|
135 |
+
res = empty_like(a, dtype=dtype, order=order, subok=subok)
|
136 |
+
# needed instead of a 0 to get same result as zeros for for string dtypes
|
137 |
+
z = zeros(1, dtype=res.dtype)
|
138 |
+
multiarray.copyto(res, z, casting='unsafe')
|
139 |
+
return res
|
140 |
+
|
141 |
+
def ones(shape, dtype=None, order='C'):
|
142 |
+
"""
|
143 |
+
Return a new array of given shape and type, filled with ones.
|
144 |
+
|
145 |
+
Parameters
|
146 |
+
----------
|
147 |
+
shape : int or sequence of ints
|
148 |
+
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
|
149 |
+
dtype : data-type, optional
|
150 |
+
The desired data-type for the array, e.g., `numpy.int8`. Default is
|
151 |
+
`numpy.float64`.
|
152 |
+
order : {'C', 'F'}, optional
|
153 |
+
Whether to store multidimensional data in C- or Fortran-contiguous
|
154 |
+
(row- or column-wise) order in memory.
|
155 |
+
|
156 |
+
Returns
|
157 |
+
-------
|
158 |
+
out : ndarray
|
159 |
+
Array of ones with the given shape, dtype, and order.
|
160 |
+
|
161 |
+
See Also
|
162 |
+
--------
|
163 |
+
zeros, ones_like
|
164 |
+
|
165 |
+
Examples
|
166 |
+
--------
|
167 |
+
>>> np.ones(5)
|
168 |
+
array([ 1., 1., 1., 1., 1.])
|
169 |
+
|
170 |
+
>>> np.ones((5,), dtype=np.int)
|
171 |
+
array([1, 1, 1, 1, 1])
|
172 |
+
|
173 |
+
>>> np.ones((2, 1))
|
174 |
+
array([[ 1.],
|
175 |
+
[ 1.]])
|
176 |
+
|
177 |
+
>>> s = (2,2)
|
178 |
+
>>> np.ones(s)
|
179 |
+
array([[ 1., 1.],
|
180 |
+
[ 1., 1.]])
|
181 |
+
|
182 |
+
"""
|
183 |
+
a = empty(shape, dtype, order)
|
184 |
+
multiarray.copyto(a, 1, casting='unsafe')
|
185 |
+
return a
|
186 |
+
|
187 |
+
def ones_like(a, dtype=None, order='K', subok=True):
|
188 |
+
"""
|
189 |
+
Return an array of ones with the same shape and type as a given array.
|
190 |
+
|
191 |
+
Parameters
|
192 |
+
----------
|
193 |
+
a : array_like
|
194 |
+
The shape and data-type of `a` define these same attributes of
|
195 |
+
the returned array.
|
196 |
+
dtype : data-type, optional
|
197 |
+
.. versionadded:: 1.6.0
|
198 |
+
Overrides the data type of the result.
|
199 |
+
order : {'C', 'F', 'A', or 'K'}, optional
|
200 |
+
.. versionadded:: 1.6.0
|
201 |
+
Overrides the memory layout of the result. 'C' means C-order,
|
202 |
+
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
|
203 |
+
'C' otherwise. 'K' means match the layout of `a` as closely
|
204 |
+
as possible.
|
205 |
+
subok : bool, optional.
|
206 |
+
If True, then the newly created array will use the sub-class
|
207 |
+
type of 'a', otherwise it will be a base-class array. Defaults
|
208 |
+
to True.
|
209 |
+
|
210 |
+
Returns
|
211 |
+
-------
|
212 |
+
out : ndarray
|
213 |
+
Array of ones with the same shape and type as `a`.
|
214 |
+
|
215 |
+
See Also
|
216 |
+
--------
|
217 |
+
zeros_like : Return an array of zeros with shape and type of input.
|
218 |
+
empty_like : Return an empty array with shape and type of input.
|
219 |
+
zeros : Return a new array setting values to zero.
|
220 |
+
ones : Return a new array setting values to one.
|
221 |
+
empty : Return a new uninitialized array.
|
222 |
+
|
223 |
+
Examples
|
224 |
+
--------
|
225 |
+
>>> x = np.arange(6)
|
226 |
+
>>> x = x.reshape((2, 3))
|
227 |
+
>>> x
|
228 |
+
array([[0, 1, 2],
|
229 |
+
[3, 4, 5]])
|
230 |
+
>>> np.ones_like(x)
|
231 |
+
array([[1, 1, 1],
|
232 |
+
[1, 1, 1]])
|
233 |
+
|
234 |
+
>>> y = np.arange(3, dtype=np.float)
|
235 |
+
>>> y
|
236 |
+
array([ 0., 1., 2.])
|
237 |
+
>>> np.ones_like(y)
|
238 |
+
array([ 1., 1., 1.])
|
239 |
+
|
240 |
+
"""
|
241 |
+
res = empty_like(a, dtype=dtype, order=order, subok=subok)
|
242 |
+
multiarray.copyto(res, 1, casting='unsafe')
|
243 |
+
return res
|
244 |
+
|
245 |
+
def full(shape, fill_value, dtype=None, order='C'):
|
246 |
+
"""
|
247 |
+
Return a new array of given shape and type, filled with `fill_value`.
|
248 |
+
|
249 |
+
Parameters
|
250 |
+
----------
|
251 |
+
shape : int or sequence of ints
|
252 |
+
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
|
253 |
+
fill_value : scalar
|
254 |
+
Fill value.
|
255 |
+
dtype : data-type, optional
|
256 |
+
The desired data-type for the array, e.g., `numpy.int8`. Default is
|
257 |
+
is chosen as `np.array(fill_value).dtype`.
|
258 |
+
order : {'C', 'F'}, optional
|
259 |
+
Whether to store multidimensional data in C- or Fortran-contiguous
|
260 |
+
(row- or column-wise) order in memory.
|
261 |
+
|
262 |
+
Returns
|
263 |
+
-------
|
264 |
+
out : ndarray
|
265 |
+
Array of `fill_value` with the given shape, dtype, and order.
|
266 |
+
|
267 |
+
See Also
|
268 |
+
--------
|
269 |
+
zeros_like : Return an array of zeros with shape and type of input.
|
270 |
+
ones_like : Return an array of ones with shape and type of input.
|
271 |
+
empty_like : Return an empty array with shape and type of input.
|
272 |
+
full_like : Fill an array with shape and type of input.
|
273 |
+
zeros : Return a new array setting values to zero.
|
274 |
+
ones : Return a new array setting values to one.
|
275 |
+
empty : Return a new uninitialized array.
|
276 |
+
|
277 |
+
Examples
|
278 |
+
--------
|
279 |
+
>>> np.full((2, 2), np.inf)
|
280 |
+
array([[ inf, inf],
|
281 |
+
[ inf, inf]])
|
282 |
+
>>> np.full((2, 2), 10, dtype=np.int)
|
283 |
+
array([[10, 10],
|
284 |
+
[10, 10]])
|
285 |
+
|
286 |
+
"""
|
287 |
+
a = empty(shape, dtype, order)
|
288 |
+
multiarray.copyto(a, fill_value, casting='unsafe')
|
289 |
+
return a
|
290 |
+
|
291 |
+
def full_like(a, fill_value, dtype=None, order='K', subok=True):
|
292 |
+
"""
|
293 |
+
Return a full array with the same shape and type as a given array.
|
294 |
+
|
295 |
+
Parameters
|
296 |
+
----------
|
297 |
+
a : array_like
|
298 |
+
The shape and data-type of `a` define these same attributes of
|
299 |
+
the returned array.
|
300 |
+
fill_value : scalar
|
301 |
+
Fill value.
|
302 |
+
dtype : data-type, optional
|
303 |
+
Overrides the data type of the result.
|
304 |
+
order : {'C', 'F', 'A', or 'K'}, optional
|
305 |
+
Overrides the memory layout of the result. 'C' means C-order,
|
306 |
+
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
|
307 |
+
'C' otherwise. 'K' means match the layout of `a` as closely
|
308 |
+
as possible.
|
309 |
+
subok : bool, optional.
|
310 |
+
If True, then the newly created array will use the sub-class
|
311 |
+
type of 'a', otherwise it will be a base-class array. Defaults
|
312 |
+
to True.
|
313 |
+
|
314 |
+
Returns
|
315 |
+
-------
|
316 |
+
out : ndarray
|
317 |
+
Array of `fill_value` with the same shape and type as `a`.
|
318 |
+
|
319 |
+
See Also
|
320 |
+
--------
|
321 |
+
zeros_like : Return an array of zeros with shape and type of input.
|
322 |
+
ones_like : Return an array of ones with shape and type of input.
|
323 |
+
empty_like : Return an empty array with shape and type of input.
|
324 |
+
zeros : Return a new array setting values to zero.
|
325 |
+
ones : Return a new array setting values to one.
|
326 |
+
empty : Return a new uninitialized array.
|
327 |
+
full : Fill a new array.
|
328 |
+
|
329 |
+
Examples
|
330 |
+
--------
|
331 |
+
>>> x = np.arange(6, dtype=np.int)
|
332 |
+
>>> np.full_like(x, 1)
|
333 |
+
array([1, 1, 1, 1, 1, 1])
|
334 |
+
>>> np.full_like(x, 0.1)
|
335 |
+
array([0, 0, 0, 0, 0, 0])
|
336 |
+
>>> np.full_like(x, 0.1, dtype=np.double)
|
337 |
+
array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
|
338 |
+
>>> np.full_like(x, np.nan, dtype=np.double)
|
339 |
+
array([ nan, nan, nan, nan, nan, nan])
|
340 |
+
|
341 |
+
>>> y = np.arange(6, dtype=np.double)
|
342 |
+
>>> np.full_like(y, 0.1)
|
343 |
+
array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
|
344 |
+
|
345 |
+
"""
|
346 |
+
res = empty_like(a, dtype=dtype, order=order, subok=subok)
|
347 |
+
multiarray.copyto(res, fill_value, casting='unsafe')
|
348 |
+
return res
|
349 |
+
|
350 |
+
|
351 |
+
def extend_all(module):
|
352 |
+
adict = {}
|
353 |
+
for a in __all__:
|
354 |
+
adict[a] = 1
|
355 |
+
try:
|
356 |
+
mall = getattr(module, '__all__')
|
357 |
+
except AttributeError:
|
358 |
+
mall = [k for k in module.__dict__.keys() if not k.startswith('_')]
|
359 |
+
for a in mall:
|
360 |
+
if a not in adict:
|
361 |
+
__all__.append(a)
|
362 |
+
|
363 |
+
newaxis = None
|
364 |
+
|
365 |
+
|
366 |
+
arange = multiarray.arange
|
367 |
+
array = multiarray.array
|
368 |
+
zeros = multiarray.zeros
|
369 |
+
count_nonzero = multiarray.count_nonzero
|
370 |
+
empty = multiarray.empty
|
371 |
+
empty_like = multiarray.empty_like
|
372 |
+
fromstring = multiarray.fromstring
|
373 |
+
fromiter = multiarray.fromiter
|
374 |
+
fromfile = multiarray.fromfile
|
375 |
+
frombuffer = multiarray.frombuffer
|
376 |
+
may_share_memory = multiarray.may_share_memory
|
377 |
+
if sys.version_info[0] < 3:
|
378 |
+
newbuffer = multiarray.newbuffer
|
379 |
+
getbuffer = multiarray.getbuffer
|
380 |
+
int_asbuffer = multiarray.int_asbuffer
|
381 |
+
where = multiarray.where
|
382 |
+
concatenate = multiarray.concatenate
|
383 |
+
fastCopyAndTranspose = multiarray._fastCopyAndTranspose
|
384 |
+
set_numeric_ops = multiarray.set_numeric_ops
|
385 |
+
can_cast = multiarray.can_cast
|
386 |
+
promote_types = multiarray.promote_types
|
387 |
+
min_scalar_type = multiarray.min_scalar_type
|
388 |
+
result_type = multiarray.result_type
|
389 |
+
lexsort = multiarray.lexsort
|
390 |
+
compare_chararrays = multiarray.compare_chararrays
|
391 |
+
putmask = multiarray.putmask
|
392 |
+
einsum = multiarray.einsum
|
393 |
+
|
394 |
+
def asarray(a, dtype=None, order=None):
|
395 |
+
"""
|
396 |
+
Convert the input to an array.
|
397 |
+
|
398 |
+
Parameters
|
399 |
+
----------
|
400 |
+
a : array_like
|
401 |
+
Input data, in any form that can be converted to an array. This
|
402 |
+
includes lists, lists of tuples, tuples, tuples of tuples, tuples
|
403 |
+
of lists and ndarrays.
|
404 |
+
dtype : data-type, optional
|
405 |
+
By default, the data-type is inferred from the input data.
|
406 |
+
order : {'C', 'F'}, optional
|
407 |
+
Whether to use row-major ('C') or column-major ('F' for FORTRAN)
|
408 |
+
memory representation. Defaults to 'C'.
|
409 |
+
|
410 |
+
Returns
|
411 |
+
-------
|
412 |
+
out : ndarray
|
413 |
+
Array interpretation of `a`. No copy is performed if the input
|
414 |
+
is already an ndarray. If `a` is a subclass of ndarray, a base
|
415 |
+
class ndarray is returned.
|
416 |
+
|
417 |
+
See Also
|
418 |
+
--------
|
419 |
+
asanyarray : Similar function which passes through subclasses.
|
420 |
+
ascontiguousarray : Convert input to a contiguous array.
|
421 |
+
asfarray : Convert input to a floating point ndarray.
|
422 |
+
asfortranarray : Convert input to an ndarray with column-major
|
423 |
+
memory order.
|
424 |
+
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
|
425 |
+
fromiter : Create an array from an iterator.
|
426 |
+
fromfunction : Construct an array by executing a function on grid
|
427 |
+
positions.
|
428 |
+
|
429 |
+
Examples
|
430 |
+
--------
|
431 |
+
Convert a list into an array:
|
432 |
+
|
433 |
+
>>> a = [1, 2]
|
434 |
+
>>> np.asarray(a)
|
435 |
+
array([1, 2])
|
436 |
+
|
437 |
+
Existing arrays are not copied:
|
438 |
+
|
439 |
+
>>> a = np.array([1, 2])
|
440 |
+
>>> np.asarray(a) is a
|
441 |
+
True
|
442 |
+
|
443 |
+
If `dtype` is set, array is copied only if dtype does not match:
|
444 |
+
|
445 |
+
>>> a = np.array([1, 2], dtype=np.float32)
|
446 |
+
>>> np.asarray(a, dtype=np.float32) is a
|
447 |
+
True
|
448 |
+
>>> np.asarray(a, dtype=np.float64) is a
|
449 |
+
False
|
450 |
+
|
451 |
+
Contrary to `asanyarray`, ndarray subclasses are not passed through:
|
452 |
+
|
453 |
+
>>> issubclass(np.matrix, np.ndarray)
|
454 |
+
True
|
455 |
+
>>> a = np.matrix([[1, 2]])
|
456 |
+
>>> np.asarray(a) is a
|
457 |
+
False
|
458 |
+
>>> np.asanyarray(a) is a
|
459 |
+
True
|
460 |
+
|
461 |
+
"""
|
462 |
+
return array(a, dtype, copy=False, order=order)
|
463 |
+
|
464 |
+
def asanyarray(a, dtype=None, order=None):
|
465 |
+
"""
|
466 |
+
Convert the input to an ndarray, but pass ndarray subclasses through.
|
467 |
+
|
468 |
+
Parameters
|
469 |
+
----------
|
470 |
+
a : array_like
|
471 |
+
Input data, in any form that can be converted to an array. This
|
472 |
+
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
|
473 |
+
tuples of lists, and ndarrays.
|
474 |
+
dtype : data-type, optional
|
475 |
+
By default, the data-type is inferred from the input data.
|
476 |
+
order : {'C', 'F'}, optional
|
477 |
+
Whether to use row-major ('C') or column-major ('F') memory
|
478 |
+
representation. Defaults to 'C'.
|
479 |
+
|
480 |
+
Returns
|
481 |
+
-------
|
482 |
+
out : ndarray or an ndarray subclass
|
483 |
+
Array interpretation of `a`. If `a` is an ndarray or a subclass
|
484 |
+
of ndarray, it is returned as-is and no copy is performed.
|
485 |
+
|
486 |
+
See Also
|
487 |
+
--------
|
488 |
+
asarray : Similar function which always returns ndarrays.
|
489 |
+
ascontiguousarray : Convert input to a contiguous array.
|
490 |
+
asfarray : Convert input to a floating point ndarray.
|
491 |
+
asfortranarray : Convert input to an ndarray with column-major
|
492 |
+
memory order.
|
493 |
+
asarray_chkfinite : Similar function which checks input for NaNs and
|
494 |
+
Infs.
|
495 |
+
fromiter : Create an array from an iterator.
|
496 |
+
fromfunction : Construct an array by executing a function on grid
|
497 |
+
positions.
|
498 |
+
|
499 |
+
Examples
|
500 |
+
--------
|
501 |
+
Convert a list into an array:
|
502 |
+
|
503 |
+
>>> a = [1, 2]
|
504 |
+
>>> np.asanyarray(a)
|
505 |
+
array([1, 2])
|
506 |
+
|
507 |
+
Instances of `ndarray` subclasses are passed through as-is:
|
508 |
+
|
509 |
+
>>> a = np.matrix([1, 2])
|
510 |
+
>>> np.asanyarray(a) is a
|
511 |
+
True
|
512 |
+
|
513 |
+
"""
|
514 |
+
return array(a, dtype, copy=False, order=order, subok=True)
|
515 |
+
|
516 |
+
def ascontiguousarray(a, dtype=None):
|
517 |
+
"""
|
518 |
+
Return a contiguous array in memory (C order).
|
519 |
+
|
520 |
+
Parameters
|
521 |
+
----------
|
522 |
+
a : array_like
|
523 |
+
Input array.
|
524 |
+
dtype : str or dtype object, optional
|
525 |
+
Data-type of returned array.
|
526 |
+
|
527 |
+
Returns
|
528 |
+
-------
|
529 |
+
out : ndarray
|
530 |
+
Contiguous array of same shape and content as `a`, with type `dtype`
|
531 |
+
if specified.
|
532 |
+
|
533 |
+
See Also
|
534 |
+
--------
|
535 |
+
asfortranarray : Convert input to an ndarray with column-major
|
536 |
+
memory order.
|
537 |
+
require : Return an ndarray that satisfies requirements.
|
538 |
+
ndarray.flags : Information about the memory layout of the array.
|
539 |
+
|
540 |
+
Examples
|
541 |
+
--------
|
542 |
+
>>> x = np.arange(6).reshape(2,3)
|
543 |
+
>>> np.ascontiguousarray(x, dtype=np.float32)
|
544 |
+
array([[ 0., 1., 2.],
|
545 |
+
[ 3., 4., 5.]], dtype=float32)
|
546 |
+
>>> x.flags['C_CONTIGUOUS']
|
547 |
+
True
|
548 |
+
|
549 |
+
"""
|
550 |
+
return array(a, dtype, copy=False, order='C', ndmin=1)
|
551 |
+
|
552 |
+
def asfortranarray(a, dtype=None):
|
553 |
+
"""
|
554 |
+
Return an array laid out in Fortran order in memory.
|
555 |
+
|
556 |
+
Parameters
|
557 |
+
----------
|
558 |
+
a : array_like
|
559 |
+
Input array.
|
560 |
+
dtype : str or dtype object, optional
|
561 |
+
By default, the data-type is inferred from the input data.
|
562 |
+
|
563 |
+
Returns
|
564 |
+
-------
|
565 |
+
out : ndarray
|
566 |
+
The input `a` in Fortran, or column-major, order.
|
567 |
+
|
568 |
+
See Also
|
569 |
+
--------
|
570 |
+
ascontiguousarray : Convert input to a contiguous (C order) array.
|
571 |
+
asanyarray : Convert input to an ndarray with either row or
|
572 |
+
column-major memory order.
|
573 |
+
require : Return an ndarray that satisfies requirements.
|
574 |
+
ndarray.flags : Information about the memory layout of the array.
|
575 |
+
|
576 |
+
Examples
|
577 |
+
--------
|
578 |
+
>>> x = np.arange(6).reshape(2,3)
|
579 |
+
>>> y = np.asfortranarray(x)
|
580 |
+
>>> x.flags['F_CONTIGUOUS']
|
581 |
+
False
|
582 |
+
>>> y.flags['F_CONTIGUOUS']
|
583 |
+
True
|
584 |
+
|
585 |
+
"""
|
586 |
+
return array(a, dtype, copy=False, order='F', ndmin=1)
|
587 |
+
|
588 |
+
def require(a, dtype=None, requirements=None):
|
589 |
+
"""
|
590 |
+
Return an ndarray of the provided type that satisfies requirements.
|
591 |
+
|
592 |
+
This function is useful to be sure that an array with the correct flags
|
593 |
+
is returned for passing to compiled code (perhaps through ctypes).
|
594 |
+
|
595 |
+
Parameters
|
596 |
+
----------
|
597 |
+
a : array_like
|
598 |
+
The object to be converted to a type-and-requirement-satisfying array.
|
599 |
+
dtype : data-type
|
600 |
+
The required data-type, the default data-type is float64).
|
601 |
+
requirements : str or list of str
|
602 |
+
The requirements list can be any of the following
|
603 |
+
|
604 |
+
* 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
|
605 |
+
* 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
|
606 |
+
* 'ALIGNED' ('A') - ensure a data-type aligned array
|
607 |
+
* 'WRITEABLE' ('W') - ensure a writable array
|
608 |
+
* 'OWNDATA' ('O') - ensure an array that owns its own data
|
609 |
+
|
610 |
+
See Also
|
611 |
+
--------
|
612 |
+
asarray : Convert input to an ndarray.
|
613 |
+
asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
|
614 |
+
ascontiguousarray : Convert input to a contiguous array.
|
615 |
+
asfortranarray : Convert input to an ndarray with column-major
|
616 |
+
memory order.
|
617 |
+
ndarray.flags : Information about the memory layout of the array.
|
618 |
+
|
619 |
+
Notes
|
620 |
+
-----
|
621 |
+
The returned array will be guaranteed to have the listed requirements
|
622 |
+
by making a copy if needed.
|
623 |
+
|
624 |
+
Examples
|
625 |
+
--------
|
626 |
+
>>> x = np.arange(6).reshape(2,3)
|
627 |
+
>>> x.flags
|
628 |
+
C_CONTIGUOUS : True
|
629 |
+
F_CONTIGUOUS : False
|
630 |
+
OWNDATA : False
|
631 |
+
WRITEABLE : True
|
632 |
+
ALIGNED : True
|
633 |
+
UPDATEIFCOPY : False
|
634 |
+
|
635 |
+
>>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
|
636 |
+
>>> y.flags
|
637 |
+
C_CONTIGUOUS : False
|
638 |
+
F_CONTIGUOUS : True
|
639 |
+
OWNDATA : True
|
640 |
+
WRITEABLE : True
|
641 |
+
ALIGNED : True
|
642 |
+
UPDATEIFCOPY : False
|
643 |
+
|
644 |
+
"""
|
645 |
+
if requirements is None:
|
646 |
+
requirements = []
|
647 |
+
else:
|
648 |
+
requirements = [x.upper() for x in requirements]
|
649 |
+
|
650 |
+
if not requirements:
|
651 |
+
return asanyarray(a, dtype=dtype)
|
652 |
+
|
653 |
+
if 'ENSUREARRAY' in requirements or 'E' in requirements:
|
654 |
+
subok = False
|
655 |
+
else:
|
656 |
+
subok = True
|
657 |
+
|
658 |
+
arr = array(a, dtype=dtype, copy=False, subok=subok)
|
659 |
+
|
660 |
+
copychar = 'A'
|
661 |
+
if 'FORTRAN' in requirements or \
|
662 |
+
'F_CONTIGUOUS' in requirements or \
|
663 |
+
'F' in requirements:
|
664 |
+
copychar = 'F'
|
665 |
+
elif 'CONTIGUOUS' in requirements or \
|
666 |
+
'C_CONTIGUOUS' in requirements or \
|
667 |
+
'C' in requirements:
|
668 |
+
copychar = 'C'
|
669 |
+
|
670 |
+
for prop in requirements:
|
671 |
+
if not arr.flags[prop]:
|
672 |
+
arr = arr.copy(copychar)
|
673 |
+
break
|
674 |
+
return arr
|
675 |
+
|
676 |
+
def isfortran(a):
|
677 |
+
"""
|
678 |
+
Returns True if array is arranged in Fortran-order in memory
|
679 |
+
and not C-order.
|
680 |
+
|
681 |
+
Parameters
|
682 |
+
----------
|
683 |
+
a : ndarray
|
684 |
+
Input array.
|
685 |
+
|
686 |
+
|
687 |
+
Examples
|
688 |
+
--------
|
689 |
+
|
690 |
+
np.array allows to specify whether the array is written in C-contiguous
|
691 |
+
order (last index varies the fastest), or FORTRAN-contiguous order in
|
692 |
+
memory (first index varies the fastest).
|
693 |
+
|
694 |
+
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
|
695 |
+
>>> a
|
696 |
+
array([[1, 2, 3],
|
697 |
+
[4, 5, 6]])
|
698 |
+
>>> np.isfortran(a)
|
699 |
+
False
|
700 |
+
|
701 |
+
>>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN')
|
702 |
+
>>> b
|
703 |
+
array([[1, 2, 3],
|
704 |
+
[4, 5, 6]])
|
705 |
+
>>> np.isfortran(b)
|
706 |
+
True
|
707 |
+
|
708 |
+
|
709 |
+
The transpose of a C-ordered array is a FORTRAN-ordered array.
|
710 |
+
|
711 |
+
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
|
712 |
+
>>> a
|
713 |
+
array([[1, 2, 3],
|
714 |
+
[4, 5, 6]])
|
715 |
+
>>> np.isfortran(a)
|
716 |
+
False
|
717 |
+
>>> b = a.T
|
718 |
+
>>> b
|
719 |
+
array([[1, 4],
|
720 |
+
[2, 5],
|
721 |
+
[3, 6]])
|
722 |
+
>>> np.isfortran(b)
|
723 |
+
True
|
724 |
+
|
725 |
+
C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
|
726 |
+
|
727 |
+
>>> np.isfortran(np.array([1, 2], order='FORTRAN'))
|
728 |
+
False
|
729 |
+
|
730 |
+
"""
|
731 |
+
return a.flags.fnc
|
732 |
+
|
733 |
+
def argwhere(a):
|
734 |
+
"""
|
735 |
+
Find the indices of array elements that are non-zero, grouped by element.
|
736 |
+
|
737 |
+
Parameters
|
738 |
+
----------
|
739 |
+
a : array_like
|
740 |
+
Input data.
|
741 |
+
|
742 |
+
Returns
|
743 |
+
-------
|
744 |
+
index_array : ndarray
|
745 |
+
Indices of elements that are non-zero. Indices are grouped by element.
|
746 |
+
|
747 |
+
See Also
|
748 |
+
--------
|
749 |
+
where, nonzero
|
750 |
+
|
751 |
+
Notes
|
752 |
+
-----
|
753 |
+
``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``.
|
754 |
+
|
755 |
+
The output of ``argwhere`` is not suitable for indexing arrays.
|
756 |
+
For this purpose use ``where(a)`` instead.
|
757 |
+
|
758 |
+
Examples
|
759 |
+
--------
|
760 |
+
>>> x = np.arange(6).reshape(2,3)
|
761 |
+
>>> x
|
762 |
+
array([[0, 1, 2],
|
763 |
+
[3, 4, 5]])
|
764 |
+
>>> np.argwhere(x>1)
|
765 |
+
array([[0, 2],
|
766 |
+
[1, 0],
|
767 |
+
[1, 1],
|
768 |
+
[1, 2]])
|
769 |
+
|
770 |
+
"""
|
771 |
+
return transpose(nonzero(a))
|
772 |
+
|
773 |
+
def flatnonzero(a):
|
774 |
+
"""
|
775 |
+
Return indices that are non-zero in the flattened version of a.
|
776 |
+
|
777 |
+
This is equivalent to a.ravel().nonzero()[0].
|
778 |
+
|
779 |
+
Parameters
|
780 |
+
----------
|
781 |
+
a : ndarray
|
782 |
+
Input array.
|
783 |
+
|
784 |
+
Returns
|
785 |
+
-------
|
786 |
+
res : ndarray
|
787 |
+
Output array, containing the indices of the elements of `a.ravel()`
|
788 |
+
that are non-zero.
|
789 |
+
|
790 |
+
See Also
|
791 |
+
--------
|
792 |
+
nonzero : Return the indices of the non-zero elements of the input array.
|
793 |
+
ravel : Return a 1-D array containing the elements of the input array.
|
794 |
+
|
795 |
+
Examples
|
796 |
+
--------
|
797 |
+
>>> x = np.arange(-2, 3)
|
798 |
+
>>> x
|
799 |
+
array([-2, -1, 0, 1, 2])
|
800 |
+
>>> np.flatnonzero(x)
|
801 |
+
array([0, 1, 3, 4])
|
802 |
+
|
803 |
+
Use the indices of the non-zero elements as an index array to extract
|
804 |
+
these elements:
|
805 |
+
|
806 |
+
>>> x.ravel()[np.flatnonzero(x)]
|
807 |
+
array([-2, -1, 1, 2])
|
808 |
+
|
809 |
+
"""
|
810 |
+
return a.ravel().nonzero()[0]
|
811 |
+
|
812 |
+
_mode_from_name_dict = {'v': 0,
|
813 |
+
's' : 1,
|
814 |
+
'f' : 2}
|
815 |
+
|
816 |
+
def _mode_from_name(mode):
|
817 |
+
if isinstance(mode, basestring):
|
818 |
+
return _mode_from_name_dict[mode.lower()[0]]
|
819 |
+
return mode
|
820 |
+
|
821 |
+
def correlate(a, v, mode='valid', old_behavior=False):
|
822 |
+
"""
|
823 |
+
Cross-correlation of two 1-dimensional sequences.
|
824 |
+
|
825 |
+
This function computes the correlation as generally defined in signal
|
826 |
+
processing texts::
|
827 |
+
|
828 |
+
c_{av}[k] = sum_n a[n+k] * conj(v[n])
|
829 |
+
|
830 |
+
with a and v sequences being zero-padded where necessary and conj being
|
831 |
+
the conjugate.
|
832 |
+
|
833 |
+
Parameters
|
834 |
+
----------
|
835 |
+
a, v : array_like
|
836 |
+
Input sequences.
|
837 |
+
mode : {'valid', 'same', 'full'}, optional
|
838 |
+
Refer to the `convolve` docstring. Note that the default
|
839 |
+
is `valid`, unlike `convolve`, which uses `full`.
|
840 |
+
old_behavior : bool
|
841 |
+
If True, uses the old behavior from Numeric,
|
842 |
+
(correlate(a,v) == correlate(v,a), and the conjugate is not taken
|
843 |
+
for complex arrays). If False, uses the conventional signal
|
844 |
+
processing definition.
|
845 |
+
|
846 |
+
Returns
|
847 |
+
-------
|
848 |
+
out : ndarray
|
849 |
+
Discrete cross-correlation of `a` and `v`.
|
850 |
+
|
851 |
+
See Also
|
852 |
+
--------
|
853 |
+
convolve : Discrete, linear convolution of two one-dimensional sequences.
|
854 |
+
|
855 |
+
Notes
|
856 |
+
-----
|
857 |
+
The definition of correlation above is not unique and sometimes correlation
|
858 |
+
may be defined differently. Another common definition is::
|
859 |
+
|
860 |
+
c'_{av}[k] = sum_n a[n] conj(v[n+k])
|
861 |
+
|
862 |
+
which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``.
|
863 |
+
|
864 |
+
Examples
|
865 |
+
--------
|
866 |
+
>>> np.correlate([1, 2, 3], [0, 1, 0.5])
|
867 |
+
array([ 3.5])
|
868 |
+
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
|
869 |
+
array([ 2. , 3.5, 3. ])
|
870 |
+
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
|
871 |
+
array([ 0.5, 2. , 3.5, 3. , 0. ])
|
872 |
+
|
873 |
+
Using complex sequences:
|
874 |
+
|
875 |
+
>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
|
876 |
+
array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
|
877 |
+
|
878 |
+
Note that you get the time reversed, complex conjugated result
|
879 |
+
when the two input sequences change places, i.e.,
|
880 |
+
``c_{va}[k] = c^{*}_{av}[-k]``:
|
881 |
+
|
882 |
+
>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
|
883 |
+
array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
|
884 |
+
|
885 |
+
"""
|
886 |
+
mode = _mode_from_name(mode)
|
887 |
+
# the old behavior should be made available under a different name, see thread
|
888 |
+
# http://thread.gmane.org/gmane.comp.python.numeric.general/12609/focus=12630
|
889 |
+
if old_behavior:
|
890 |
+
warnings.warn("""
|
891 |
+
The old behavior of correlate was deprecated for 1.4.0, and will be completely removed
|
892 |
+
for NumPy 2.0.
|
893 |
+
|
894 |
+
The new behavior fits the conventional definition of correlation: inputs are
|
895 |
+
never swapped, and the second argument is conjugated for complex arrays.""",
|
896 |
+
DeprecationWarning)
|
897 |
+
return multiarray.correlate(a, v, mode)
|
898 |
+
else:
|
899 |
+
return multiarray.correlate2(a, v, mode)
|
900 |
+
|
901 |
+
def convolve(a,v,mode='full'):
|
902 |
+
"""
|
903 |
+
Returns the discrete, linear convolution of two one-dimensional sequences.
|
904 |
+
|
905 |
+
The convolution operator is often seen in signal processing, where it
|
906 |
+
models the effect of a linear time-invariant system on a signal [1]_. In
|
907 |
+
probability theory, the sum of two independent random variables is
|
908 |
+
distributed according to the convolution of their individual
|
909 |
+
distributions.
|
910 |
+
|
911 |
+
If `v` is longer than `a`, the arrays are swapped before computation.
|
912 |
+
|
913 |
+
Parameters
|
914 |
+
----------
|
915 |
+
a : (N,) array_like
|
916 |
+
First one-dimensional input array.
|
917 |
+
v : (M,) array_like
|
918 |
+
Second one-dimensional input array.
|
919 |
+
mode : {'full', 'valid', 'same'}, optional
|
920 |
+
'full':
|
921 |
+
By default, mode is 'full'. This returns the convolution
|
922 |
+
at each point of overlap, with an output shape of (N+M-1,). At
|
923 |
+
the end-points of the convolution, the signals do not overlap
|
924 |
+
completely, and boundary effects may be seen.
|
925 |
+
|
926 |
+
'same':
|
927 |
+
Mode `same` returns output of length ``max(M, N)``. Boundary
|
928 |
+
effects are still visible.
|
929 |
+
|
930 |
+
'valid':
|
931 |
+
Mode `valid` returns output of length
|
932 |
+
``max(M, N) - min(M, N) + 1``. The convolution product is only given
|
933 |
+
for points where the signals overlap completely. Values outside
|
934 |
+
the signal boundary have no effect.
|
935 |
+
|
936 |
+
Returns
|
937 |
+
-------
|
938 |
+
out : ndarray
|
939 |
+
Discrete, linear convolution of `a` and `v`.
|
940 |
+
|
941 |
+
See Also
|
942 |
+
--------
|
943 |
+
scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
|
944 |
+
Transform.
|
945 |
+
scipy.linalg.toeplitz : Used to construct the convolution operator.
|
946 |
+
polymul : Polynomial multiplication. Same output as convolve, but also
|
947 |
+
accepts poly1d objects as input.
|
948 |
+
|
949 |
+
Notes
|
950 |
+
-----
|
951 |
+
The discrete convolution operation is defined as
|
952 |
+
|
953 |
+
.. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m]
|
954 |
+
|
955 |
+
It can be shown that a convolution :math:`x(t) * y(t)` in time/space
|
956 |
+
is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
|
957 |
+
domain, after appropriate padding (padding is necessary to prevent
|
958 |
+
circular convolution). Since multiplication is more efficient (faster)
|
959 |
+
than convolution, the function `scipy.signal.fftconvolve` exploits the
|
960 |
+
FFT to calculate the convolution of large data-sets.
|
961 |
+
|
962 |
+
References
|
963 |
+
----------
|
964 |
+
.. [1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution.
|
965 |
+
|
966 |
+
Examples
|
967 |
+
--------
|
968 |
+
Note how the convolution operator flips the second array
|
969 |
+
before "sliding" the two across one another:
|
970 |
+
|
971 |
+
>>> np.convolve([1, 2, 3], [0, 1, 0.5])
|
972 |
+
array([ 0. , 1. , 2.5, 4. , 1.5])
|
973 |
+
|
974 |
+
Only return the middle values of the convolution.
|
975 |
+
Contains boundary effects, where zeros are taken
|
976 |
+
into account:
|
977 |
+
|
978 |
+
>>> np.convolve([1,2,3],[0,1,0.5], 'same')
|
979 |
+
array([ 1. , 2.5, 4. ])
|
980 |
+
|
981 |
+
The two arrays are of the same length, so there
|
982 |
+
is only one position where they completely overlap:
|
983 |
+
|
984 |
+
>>> np.convolve([1,2,3],[0,1,0.5], 'valid')
|
985 |
+
array([ 2.5])
|
986 |
+
|
987 |
+
"""
|
988 |
+
a, v = array(a, ndmin=1), array(v, ndmin=1)
|
989 |
+
if (len(v) > len(a)):
|
990 |
+
a, v = v, a
|
991 |
+
if len(a) == 0 :
|
992 |
+
raise ValueError('a cannot be empty')
|
993 |
+
if len(v) == 0 :
|
994 |
+
raise ValueError('v cannot be empty')
|
995 |
+
mode = _mode_from_name(mode)
|
996 |
+
return multiarray.correlate(a, v[::-1], mode)
|
997 |
+
|
998 |
+
def outer(a, b, out=None):
|
999 |
+
"""
|
1000 |
+
Compute the outer product of two vectors.
|
1001 |
+
|
1002 |
+
Given two vectors, ``a = [a0, a1, ..., aM]`` and
|
1003 |
+
``b = [b0, b1, ..., bN]``,
|
1004 |
+
the outer product [1]_ is::
|
1005 |
+
|
1006 |
+
[[a0*b0 a0*b1 ... a0*bN ]
|
1007 |
+
[a1*b0 .
|
1008 |
+
[ ... .
|
1009 |
+
[aM*b0 aM*bN ]]
|
1010 |
+
|
1011 |
+
Parameters
|
1012 |
+
----------
|
1013 |
+
a : (M,) array_like
|
1014 |
+
First input vector. Input is flattened if
|
1015 |
+
not already 1-dimensional.
|
1016 |
+
b : (N,) array_like
|
1017 |
+
Second input vector. Input is flattened if
|
1018 |
+
not already 1-dimensional.
|
1019 |
+
out : (M, N) ndarray, optional
|
1020 |
+
A location where the result is stored
|
1021 |
+
|
1022 |
+
.. versionadded:: 1.9.0
|
1023 |
+
|
1024 |
+
Returns
|
1025 |
+
-------
|
1026 |
+
out : (M, N) ndarray
|
1027 |
+
``out[i, j] = a[i] * b[j]``
|
1028 |
+
|
1029 |
+
See also
|
1030 |
+
--------
|
1031 |
+
inner, einsum
|
1032 |
+
|
1033 |
+
References
|
1034 |
+
----------
|
1035 |
+
.. [1] : G. H. Golub and C. F. van Loan, *Matrix Computations*, 3rd
|
1036 |
+
ed., Baltimore, MD, Johns Hopkins University Press, 1996,
|
1037 |
+
pg. 8.
|
1038 |
+
|
1039 |
+
Examples
|
1040 |
+
--------
|
1041 |
+
Make a (*very* coarse) grid for computing a Mandelbrot set:
|
1042 |
+
|
1043 |
+
>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
|
1044 |
+
>>> rl
|
1045 |
+
array([[-2., -1., 0., 1., 2.],
|
1046 |
+
[-2., -1., 0., 1., 2.],
|
1047 |
+
[-2., -1., 0., 1., 2.],
|
1048 |
+
[-2., -1., 0., 1., 2.],
|
1049 |
+
[-2., -1., 0., 1., 2.]])
|
1050 |
+
>>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
|
1051 |
+
>>> im
|
1052 |
+
array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
|
1053 |
+
[ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
|
1054 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
|
1055 |
+
[ 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
|
1056 |
+
[ 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
|
1057 |
+
>>> grid = rl + im
|
1058 |
+
>>> grid
|
1059 |
+
array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
|
1060 |
+
[-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
|
1061 |
+
[-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
|
1062 |
+
[-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
|
1063 |
+
[-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
|
1064 |
+
|
1065 |
+
An example using a "vector" of letters:
|
1066 |
+
|
1067 |
+
>>> x = np.array(['a', 'b', 'c'], dtype=object)
|
1068 |
+
>>> np.outer(x, [1, 2, 3])
|
1069 |
+
array([[a, aa, aaa],
|
1070 |
+
[b, bb, bbb],
|
1071 |
+
[c, cc, ccc]], dtype=object)
|
1072 |
+
|
1073 |
+
"""
|
1074 |
+
a = asarray(a)
|
1075 |
+
b = asarray(b)
|
1076 |
+
return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out)
|
1077 |
+
|
1078 |
+
# try to import blas optimized dot if available
|
1079 |
+
envbak = os.environ.copy()
|
1080 |
+
try:
|
1081 |
+
# importing this changes the dot function for basic 4 types
|
1082 |
+
# to blas-optimized versions.
|
1083 |
+
|
1084 |
+
# disables openblas affinity setting of the main thread that limits
|
1085 |
+
# python threads or processes to one core
|
1086 |
+
if 'OPENBLAS_MAIN_FREE' not in os.environ:
|
1087 |
+
os.environ['OPENBLAS_MAIN_FREE'] = '1'
|
1088 |
+
if 'GOTOBLAS_MAIN_FREE' not in os.environ:
|
1089 |
+
os.environ['GOTOBLAS_MAIN_FREE'] = '1'
|
1090 |
+
from ._dotblas import dot, vdot, inner, alterdot, restoredot
|
1091 |
+
except ImportError:
|
1092 |
+
# docstrings are in add_newdocs.py
|
1093 |
+
inner = multiarray.inner
|
1094 |
+
dot = multiarray.dot
|
1095 |
+
def vdot(a, b):
|
1096 |
+
return dot(asarray(a).ravel().conj(), asarray(b).ravel())
|
1097 |
+
def alterdot():
|
1098 |
+
pass
|
1099 |
+
def restoredot():
|
1100 |
+
pass
|
1101 |
+
finally:
|
1102 |
+
os.environ.clear()
|
1103 |
+
os.environ.update(envbak)
|
1104 |
+
del envbak
|
1105 |
+
|
1106 |
+
def tensordot(a, b, axes=2):
|
1107 |
+
"""
|
1108 |
+
Compute tensor dot product along specified axes for arrays >= 1-D.
|
1109 |
+
|
1110 |
+
Given two tensors (arrays of dimension greater than or equal to one),
|
1111 |
+
`a` and `b`, and an array_like object containing two array_like
|
1112 |
+
objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s
|
1113 |
+
elements (components) over the axes specified by ``a_axes`` and
|
1114 |
+
``b_axes``. The third argument can be a single non-negative
|
1115 |
+
integer_like scalar, ``N``; if it is such, then the last ``N``
|
1116 |
+
dimensions of `a` and the first ``N`` dimensions of `b` are summed
|
1117 |
+
over.
|
1118 |
+
|
1119 |
+
Parameters
|
1120 |
+
----------
|
1121 |
+
a, b : array_like, len(shape) >= 1
|
1122 |
+
Tensors to "dot".
|
1123 |
+
axes : variable type
|
1124 |
+
* integer_like scalar
|
1125 |
+
Number of axes to sum over (applies to both arrays); or
|
1126 |
+
* (2,) array_like, both elements array_like of the same length
|
1127 |
+
List of axes to be summed over, first sequence applying to `a`,
|
1128 |
+
second to `b`.
|
1129 |
+
|
1130 |
+
See Also
|
1131 |
+
--------
|
1132 |
+
dot, einsum
|
1133 |
+
|
1134 |
+
Notes
|
1135 |
+
-----
|
1136 |
+
When there is more than one axis to sum over - and they are not the last
|
1137 |
+
(first) axes of `a` (`b`) - the argument `axes` should consist of
|
1138 |
+
two sequences of the same length, with the first axis to sum over given
|
1139 |
+
first in both sequences, the second axis second, and so forth.
|
1140 |
+
|
1141 |
+
Examples
|
1142 |
+
--------
|
1143 |
+
A "traditional" example:
|
1144 |
+
|
1145 |
+
>>> a = np.arange(60.).reshape(3,4,5)
|
1146 |
+
>>> b = np.arange(24.).reshape(4,3,2)
|
1147 |
+
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
|
1148 |
+
>>> c.shape
|
1149 |
+
(5, 2)
|
1150 |
+
>>> c
|
1151 |
+
array([[ 4400., 4730.],
|
1152 |
+
[ 4532., 4874.],
|
1153 |
+
[ 4664., 5018.],
|
1154 |
+
[ 4796., 5162.],
|
1155 |
+
[ 4928., 5306.]])
|
1156 |
+
>>> # A slower but equivalent way of computing the same...
|
1157 |
+
>>> d = np.zeros((5,2))
|
1158 |
+
>>> for i in range(5):
|
1159 |
+
... for j in range(2):
|
1160 |
+
... for k in range(3):
|
1161 |
+
... for n in range(4):
|
1162 |
+
... d[i,j] += a[k,n,i] * b[n,k,j]
|
1163 |
+
>>> c == d
|
1164 |
+
array([[ True, True],
|
1165 |
+
[ True, True],
|
1166 |
+
[ True, True],
|
1167 |
+
[ True, True],
|
1168 |
+
[ True, True]], dtype=bool)
|
1169 |
+
|
1170 |
+
An extended example taking advantage of the overloading of + and \\*:
|
1171 |
+
|
1172 |
+
>>> a = np.array(range(1, 9))
|
1173 |
+
>>> a.shape = (2, 2, 2)
|
1174 |
+
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
|
1175 |
+
>>> A.shape = (2, 2)
|
1176 |
+
>>> a; A
|
1177 |
+
array([[[1, 2],
|
1178 |
+
[3, 4]],
|
1179 |
+
[[5, 6],
|
1180 |
+
[7, 8]]])
|
1181 |
+
array([[a, b],
|
1182 |
+
[c, d]], dtype=object)
|
1183 |
+
|
1184 |
+
>>> np.tensordot(a, A) # third argument default is 2
|
1185 |
+
array([abbcccdddd, aaaaabbbbbbcccccccdddddddd], dtype=object)
|
1186 |
+
|
1187 |
+
>>> np.tensordot(a, A, 1)
|
1188 |
+
array([[[acc, bdd],
|
1189 |
+
[aaacccc, bbbdddd]],
|
1190 |
+
[[aaaaacccccc, bbbbbdddddd],
|
1191 |
+
[aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object)
|
1192 |
+
|
1193 |
+
>>> np.tensordot(a, A, 0) # "Left for reader" (result too long to incl.)
|
1194 |
+
array([[[[[a, b],
|
1195 |
+
[c, d]],
|
1196 |
+
...
|
1197 |
+
|
1198 |
+
>>> np.tensordot(a, A, (0, 1))
|
1199 |
+
array([[[abbbbb, cddddd],
|
1200 |
+
[aabbbbbb, ccdddddd]],
|
1201 |
+
[[aaabbbbbbb, cccddddddd],
|
1202 |
+
[aaaabbbbbbbb, ccccdddddddd]]], dtype=object)
|
1203 |
+
|
1204 |
+
>>> np.tensordot(a, A, (2, 1))
|
1205 |
+
array([[[abb, cdd],
|
1206 |
+
[aaabbbb, cccdddd]],
|
1207 |
+
[[aaaaabbbbbb, cccccdddddd],
|
1208 |
+
[aaaaaaabbbbbbbb, cccccccdddddddd]]], dtype=object)
|
1209 |
+
|
1210 |
+
>>> np.tensordot(a, A, ((0, 1), (0, 1)))
|
1211 |
+
array([abbbcccccddddddd, aabbbbccccccdddddddd], dtype=object)
|
1212 |
+
|
1213 |
+
>>> np.tensordot(a, A, ((2, 1), (1, 0)))
|
1214 |
+
array([acccbbdddd, aaaaacccccccbbbbbbdddddddd], dtype=object)
|
1215 |
+
|
1216 |
+
"""
|
1217 |
+
try:
|
1218 |
+
iter(axes)
|
1219 |
+
except:
|
1220 |
+
axes_a = list(range(-axes, 0))
|
1221 |
+
axes_b = list(range(0, axes))
|
1222 |
+
else:
|
1223 |
+
axes_a, axes_b = axes
|
1224 |
+
try:
|
1225 |
+
na = len(axes_a)
|
1226 |
+
axes_a = list(axes_a)
|
1227 |
+
except TypeError:
|
1228 |
+
axes_a = [axes_a]
|
1229 |
+
na = 1
|
1230 |
+
try:
|
1231 |
+
nb = len(axes_b)
|
1232 |
+
axes_b = list(axes_b)
|
1233 |
+
except TypeError:
|
1234 |
+
axes_b = [axes_b]
|
1235 |
+
nb = 1
|
1236 |
+
|
1237 |
+
a, b = asarray(a), asarray(b)
|
1238 |
+
as_ = a.shape
|
1239 |
+
nda = len(a.shape)
|
1240 |
+
bs = b.shape
|
1241 |
+
ndb = len(b.shape)
|
1242 |
+
equal = True
|
1243 |
+
if (na != nb): equal = False
|
1244 |
+
else:
|
1245 |
+
for k in range(na):
|
1246 |
+
if as_[axes_a[k]] != bs[axes_b[k]]:
|
1247 |
+
equal = False
|
1248 |
+
break
|
1249 |
+
if axes_a[k] < 0:
|
1250 |
+
axes_a[k] += nda
|
1251 |
+
if axes_b[k] < 0:
|
1252 |
+
axes_b[k] += ndb
|
1253 |
+
if not equal:
|
1254 |
+
raise ValueError("shape-mismatch for sum")
|
1255 |
+
|
1256 |
+
# Move the axes to sum over to the end of "a"
|
1257 |
+
# and to the front of "b"
|
1258 |
+
notin = [k for k in range(nda) if k not in axes_a]
|
1259 |
+
newaxes_a = notin + axes_a
|
1260 |
+
N2 = 1
|
1261 |
+
for axis in axes_a:
|
1262 |
+
N2 *= as_[axis]
|
1263 |
+
newshape_a = (-1, N2)
|
1264 |
+
olda = [as_[axis] for axis in notin]
|
1265 |
+
|
1266 |
+
notin = [k for k in range(ndb) if k not in axes_b]
|
1267 |
+
newaxes_b = axes_b + notin
|
1268 |
+
N2 = 1
|
1269 |
+
for axis in axes_b:
|
1270 |
+
N2 *= bs[axis]
|
1271 |
+
newshape_b = (N2, -1)
|
1272 |
+
oldb = [bs[axis] for axis in notin]
|
1273 |
+
|
1274 |
+
at = a.transpose(newaxes_a).reshape(newshape_a)
|
1275 |
+
bt = b.transpose(newaxes_b).reshape(newshape_b)
|
1276 |
+
res = dot(at, bt)
|
1277 |
+
return res.reshape(olda + oldb)
|
1278 |
+
|
1279 |
+
def roll(a, shift, axis=None):
|
1280 |
+
"""
|
1281 |
+
Roll array elements along a given axis.
|
1282 |
+
|
1283 |
+
Elements that roll beyond the last position are re-introduced at
|
1284 |
+
the first.
|
1285 |
+
|
1286 |
+
Parameters
|
1287 |
+
----------
|
1288 |
+
a : array_like
|
1289 |
+
Input array.
|
1290 |
+
shift : int
|
1291 |
+
The number of places by which elements are shifted.
|
1292 |
+
axis : int, optional
|
1293 |
+
The axis along which elements are shifted. By default, the array
|
1294 |
+
is flattened before shifting, after which the original
|
1295 |
+
shape is restored.
|
1296 |
+
|
1297 |
+
Returns
|
1298 |
+
-------
|
1299 |
+
res : ndarray
|
1300 |
+
Output array, with the same shape as `a`.
|
1301 |
+
|
1302 |
+
See Also
|
1303 |
+
--------
|
1304 |
+
rollaxis : Roll the specified axis backwards, until it lies in a
|
1305 |
+
given position.
|
1306 |
+
|
1307 |
+
Examples
|
1308 |
+
--------
|
1309 |
+
>>> x = np.arange(10)
|
1310 |
+
>>> np.roll(x, 2)
|
1311 |
+
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
|
1312 |
+
|
1313 |
+
>>> x2 = np.reshape(x, (2,5))
|
1314 |
+
>>> x2
|
1315 |
+
array([[0, 1, 2, 3, 4],
|
1316 |
+
[5, 6, 7, 8, 9]])
|
1317 |
+
>>> np.roll(x2, 1)
|
1318 |
+
array([[9, 0, 1, 2, 3],
|
1319 |
+
[4, 5, 6, 7, 8]])
|
1320 |
+
>>> np.roll(x2, 1, axis=0)
|
1321 |
+
array([[5, 6, 7, 8, 9],
|
1322 |
+
[0, 1, 2, 3, 4]])
|
1323 |
+
>>> np.roll(x2, 1, axis=1)
|
1324 |
+
array([[4, 0, 1, 2, 3],
|
1325 |
+
[9, 5, 6, 7, 8]])
|
1326 |
+
|
1327 |
+
"""
|
1328 |
+
a = asanyarray(a)
|
1329 |
+
if axis is None:
|
1330 |
+
n = a.size
|
1331 |
+
reshape = True
|
1332 |
+
else:
|
1333 |
+
try:
|
1334 |
+
n = a.shape[axis]
|
1335 |
+
except IndexError:
|
1336 |
+
raise ValueError('axis must be >= 0 and < %d' % a.ndim)
|
1337 |
+
reshape = False
|
1338 |
+
if n == 0:
|
1339 |
+
return a
|
1340 |
+
shift %= n
|
1341 |
+
indexes = concatenate((arange(n - shift, n), arange(n - shift)))
|
1342 |
+
res = a.take(indexes, axis)
|
1343 |
+
if reshape:
|
1344 |
+
res = res.reshape(a.shape)
|
1345 |
+
return res
|
1346 |
+
|
1347 |
+
def rollaxis(a, axis, start=0):
|
1348 |
+
"""
|
1349 |
+
Roll the specified axis backwards, until it lies in a given position.
|
1350 |
+
|
1351 |
+
Parameters
|
1352 |
+
----------
|
1353 |
+
a : ndarray
|
1354 |
+
Input array.
|
1355 |
+
axis : int
|
1356 |
+
The axis to roll backwards. The positions of the other axes do not
|
1357 |
+
change relative to one another.
|
1358 |
+
start : int, optional
|
1359 |
+
The axis is rolled until it lies before this position. The default,
|
1360 |
+
0, results in a "complete" roll.
|
1361 |
+
|
1362 |
+
Returns
|
1363 |
+
-------
|
1364 |
+
res : ndarray
|
1365 |
+
Output array.
|
1366 |
+
|
1367 |
+
See Also
|
1368 |
+
--------
|
1369 |
+
roll : Roll the elements of an array by a number of positions along a
|
1370 |
+
given axis.
|
1371 |
+
|
1372 |
+
Examples
|
1373 |
+
--------
|
1374 |
+
>>> a = np.ones((3,4,5,6))
|
1375 |
+
>>> np.rollaxis(a, 3, 1).shape
|
1376 |
+
(3, 6, 4, 5)
|
1377 |
+
>>> np.rollaxis(a, 2).shape
|
1378 |
+
(5, 3, 4, 6)
|
1379 |
+
>>> np.rollaxis(a, 1, 4).shape
|
1380 |
+
(3, 5, 6, 4)
|
1381 |
+
|
1382 |
+
"""
|
1383 |
+
n = a.ndim
|
1384 |
+
if axis < 0:
|
1385 |
+
axis += n
|
1386 |
+
if start < 0:
|
1387 |
+
start += n
|
1388 |
+
msg = 'rollaxis: %s (%d) must be >=0 and < %d'
|
1389 |
+
if not (0 <= axis < n):
|
1390 |
+
raise ValueError(msg % ('axis', axis, n))
|
1391 |
+
if not (0 <= start < n+1):
|
1392 |
+
raise ValueError(msg % ('start', start, n+1))
|
1393 |
+
if (axis < start): # it's been removed
|
1394 |
+
start -= 1
|
1395 |
+
if axis==start:
|
1396 |
+
return a
|
1397 |
+
axes = list(range(0, n))
|
1398 |
+
axes.remove(axis)
|
1399 |
+
axes.insert(start, axis)
|
1400 |
+
return a.transpose(axes)
|
1401 |
+
|
1402 |
+
# fix hack in scipy which imports this function
|
1403 |
+
def _move_axis_to_0(a, axis):
|
1404 |
+
return rollaxis(a, axis, 0)
|
1405 |
+
|
1406 |
+
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
|
1407 |
+
"""
|
1408 |
+
Return the cross product of two (arrays of) vectors.
|
1409 |
+
|
1410 |
+
The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
|
1411 |
+
to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
|
1412 |
+
are defined by the last axis of `a` and `b` by default, and these axes
|
1413 |
+
can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
|
1414 |
+
2, the third component of the input vector is assumed to be zero and the
|
1415 |
+
cross product calculated accordingly. In cases where both input vectors
|
1416 |
+
have dimension 2, the z-component of the cross product is returned.
|
1417 |
+
|
1418 |
+
Parameters
|
1419 |
+
----------
|
1420 |
+
a : array_like
|
1421 |
+
Components of the first vector(s).
|
1422 |
+
b : array_like
|
1423 |
+
Components of the second vector(s).
|
1424 |
+
axisa : int, optional
|
1425 |
+
Axis of `a` that defines the vector(s). By default, the last axis.
|
1426 |
+
axisb : int, optional
|
1427 |
+
Axis of `b` that defines the vector(s). By default, the last axis.
|
1428 |
+
axisc : int, optional
|
1429 |
+
Axis of `c` containing the cross product vector(s). By default, the
|
1430 |
+
last axis.
|
1431 |
+
axis : int, optional
|
1432 |
+
If defined, the axis of `a`, `b` and `c` that defines the vector(s)
|
1433 |
+
and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
|
1434 |
+
|
1435 |
+
Returns
|
1436 |
+
-------
|
1437 |
+
c : ndarray
|
1438 |
+
Vector cross product(s).
|
1439 |
+
|
1440 |
+
Raises
|
1441 |
+
------
|
1442 |
+
ValueError
|
1443 |
+
When the dimension of the vector(s) in `a` and/or `b` does not
|
1444 |
+
equal 2 or 3.
|
1445 |
+
|
1446 |
+
See Also
|
1447 |
+
--------
|
1448 |
+
inner : Inner product
|
1449 |
+
outer : Outer product.
|
1450 |
+
ix_ : Construct index arrays.
|
1451 |
+
|
1452 |
+
Notes
|
1453 |
+
-----
|
1454 |
+
.. versionadded:: 1.9.0
|
1455 |
+
Supports full broadcasting of the inputs.
|
1456 |
+
|
1457 |
+
Examples
|
1458 |
+
--------
|
1459 |
+
Vector cross-product.
|
1460 |
+
|
1461 |
+
>>> x = [1, 2, 3]
|
1462 |
+
>>> y = [4, 5, 6]
|
1463 |
+
>>> np.cross(x, y)
|
1464 |
+
array([-3, 6, -3])
|
1465 |
+
|
1466 |
+
One vector with dimension 2.
|
1467 |
+
|
1468 |
+
>>> x = [1, 2]
|
1469 |
+
>>> y = [4, 5, 6]
|
1470 |
+
>>> np.cross(x, y)
|
1471 |
+
array([12, -6, -3])
|
1472 |
+
|
1473 |
+
Equivalently:
|
1474 |
+
|
1475 |
+
>>> x = [1, 2, 0]
|
1476 |
+
>>> y = [4, 5, 6]
|
1477 |
+
>>> np.cross(x, y)
|
1478 |
+
array([12, -6, -3])
|
1479 |
+
|
1480 |
+
Both vectors with dimension 2.
|
1481 |
+
|
1482 |
+
>>> x = [1,2]
|
1483 |
+
>>> y = [4,5]
|
1484 |
+
>>> np.cross(x, y)
|
1485 |
+
-3
|
1486 |
+
|
1487 |
+
Multiple vector cross-products. Note that the direction of the cross
|
1488 |
+
product vector is defined by the `right-hand rule`.
|
1489 |
+
|
1490 |
+
>>> x = np.array([[1,2,3], [4,5,6]])
|
1491 |
+
>>> y = np.array([[4,5,6], [1,2,3]])
|
1492 |
+
>>> np.cross(x, y)
|
1493 |
+
array([[-3, 6, -3],
|
1494 |
+
[ 3, -6, 3]])
|
1495 |
+
|
1496 |
+
The orientation of `c` can be changed using the `axisc` keyword.
|
1497 |
+
|
1498 |
+
>>> np.cross(x, y, axisc=0)
|
1499 |
+
array([[-3, 3],
|
1500 |
+
[ 6, -6],
|
1501 |
+
[-3, 3]])
|
1502 |
+
|
1503 |
+
Change the vector definition of `x` and `y` using `axisa` and `axisb`.
|
1504 |
+
|
1505 |
+
>>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
|
1506 |
+
>>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
|
1507 |
+
>>> np.cross(x, y)
|
1508 |
+
array([[ -6, 12, -6],
|
1509 |
+
[ 0, 0, 0],
|
1510 |
+
[ 6, -12, 6]])
|
1511 |
+
>>> np.cross(x, y, axisa=0, axisb=0)
|
1512 |
+
array([[-24, 48, -24],
|
1513 |
+
[-30, 60, -30],
|
1514 |
+
[-36, 72, -36]])
|
1515 |
+
|
1516 |
+
"""
|
1517 |
+
if axis is not None:
|
1518 |
+
axisa, axisb, axisc = (axis,) * 3
|
1519 |
+
a = asarray(a)
|
1520 |
+
b = asarray(b)
|
1521 |
+
# Move working axis to the end of the shape
|
1522 |
+
a = rollaxis(a, axisa, a.ndim)
|
1523 |
+
b = rollaxis(b, axisb, b.ndim)
|
1524 |
+
msg = ("incompatible dimensions for cross product\n"
|
1525 |
+
"(dimension must be 2 or 3)")
|
1526 |
+
if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
|
1527 |
+
raise ValueError(msg)
|
1528 |
+
|
1529 |
+
# Create the output array
|
1530 |
+
shape = broadcast(a[..., 0], b[..., 0]).shape
|
1531 |
+
if a.shape[-1] == 3 or b.shape[-1] == 3:
|
1532 |
+
shape += (3,)
|
1533 |
+
dtype = promote_types(a.dtype, b.dtype)
|
1534 |
+
cp = empty(shape, dtype)
|
1535 |
+
|
1536 |
+
# create local aliases for readability
|
1537 |
+
a0 = a[..., 0]
|
1538 |
+
a1 = a[..., 1]
|
1539 |
+
if a.shape[-1] == 3:
|
1540 |
+
a2 = a[..., 2]
|
1541 |
+
b0 = b[..., 0]
|
1542 |
+
b1 = b[..., 1]
|
1543 |
+
if b.shape[-1] == 3:
|
1544 |
+
b2 = b[..., 2]
|
1545 |
+
if cp.ndim != 0 and cp.shape[-1] == 3:
|
1546 |
+
cp0 = cp[..., 0]
|
1547 |
+
cp1 = cp[..., 1]
|
1548 |
+
cp2 = cp[..., 2]
|
1549 |
+
|
1550 |
+
if a.shape[-1] == 2:
|
1551 |
+
if b.shape[-1] == 2:
|
1552 |
+
# a0 * b1 - a1 * b0
|
1553 |
+
multiply(a0, b1, out=cp)
|
1554 |
+
cp -= a1 * b0
|
1555 |
+
if cp.ndim == 0:
|
1556 |
+
return cp
|
1557 |
+
else:
|
1558 |
+
# This works because we are moving the last axis
|
1559 |
+
return rollaxis(cp, -1, axisc)
|
1560 |
+
else:
|
1561 |
+
# cp0 = a1 * b2 - 0 (a2 = 0)
|
1562 |
+
# cp1 = 0 - a0 * b2 (a2 = 0)
|
1563 |
+
# cp2 = a0 * b1 - a1 * b0
|
1564 |
+
multiply(a1, b2, out=cp0)
|
1565 |
+
multiply(a0, b2, out=cp1)
|
1566 |
+
negative(cp1, out=cp1)
|
1567 |
+
multiply(a0, b1, out=cp2)
|
1568 |
+
cp2 -= a1 * b0
|
1569 |
+
elif a.shape[-1] == 3:
|
1570 |
+
if b.shape[-1] == 3:
|
1571 |
+
# cp0 = a1 * b2 - a2 * b1
|
1572 |
+
# cp1 = a2 * b0 - a0 * b2
|
1573 |
+
# cp2 = a0 * b1 - a1 * b0
|
1574 |
+
multiply(a1, b2, out=cp0)
|
1575 |
+
tmp = array(a2 * b1)
|
1576 |
+
cp0 -= tmp
|
1577 |
+
multiply(a2, b0, out=cp1)
|
1578 |
+
multiply(a0, b2, out=tmp)
|
1579 |
+
cp1 -= tmp
|
1580 |
+
multiply(a0, b1, out=cp2)
|
1581 |
+
multiply(a1, b0, out=tmp)
|
1582 |
+
cp2 -= tmp
|
1583 |
+
else:
|
1584 |
+
# cp0 = 0 - a2 * b1 (b2 = 0)
|
1585 |
+
# cp1 = a2 * b0 - 0 (b2 = 0)
|
1586 |
+
# cp2 = a0 * b1 - a1 * b0
|
1587 |
+
multiply(a2, b1, out=cp0)
|
1588 |
+
negative(cp0, out=cp0)
|
1589 |
+
multiply(a2, b0, out=cp1)
|
1590 |
+
multiply(a0, b1, out=cp2)
|
1591 |
+
cp2 -= a1 * b0
|
1592 |
+
|
1593 |
+
if cp.ndim == 1:
|
1594 |
+
return cp
|
1595 |
+
else:
|
1596 |
+
# This works because we are moving the last axis
|
1597 |
+
return rollaxis(cp, -1, axisc)
|
1598 |
+
|
1599 |
+
#Use numarray's printing function
|
1600 |
+
from .arrayprint import array2string, get_printoptions, set_printoptions
|
1601 |
+
|
1602 |
+
_typelessdata = [int_, float_, complex_]
|
1603 |
+
if issubclass(intc, int):
|
1604 |
+
_typelessdata.append(intc)
|
1605 |
+
|
1606 |
+
if issubclass(longlong, int):
|
1607 |
+
_typelessdata.append(longlong)
|
1608 |
+
|
1609 |
+
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
|
1610 |
+
"""
|
1611 |
+
Return the string representation of an array.
|
1612 |
+
|
1613 |
+
Parameters
|
1614 |
+
----------
|
1615 |
+
arr : ndarray
|
1616 |
+
Input array.
|
1617 |
+
max_line_width : int, optional
|
1618 |
+
The maximum number of columns the string should span. Newline
|
1619 |
+
characters split the string appropriately after array elements.
|
1620 |
+
precision : int, optional
|
1621 |
+
Floating point precision. Default is the current printing precision
|
1622 |
+
(usually 8), which can be altered using `set_printoptions`.
|
1623 |
+
suppress_small : bool, optional
|
1624 |
+
Represent very small numbers as zero, default is False. Very small
|
1625 |
+
is defined by `precision`, if the precision is 8 then
|
1626 |
+
numbers smaller than 5e-9 are represented as zero.
|
1627 |
+
|
1628 |
+
Returns
|
1629 |
+
-------
|
1630 |
+
string : str
|
1631 |
+
The string representation of an array.
|
1632 |
+
|
1633 |
+
See Also
|
1634 |
+
--------
|
1635 |
+
array_str, array2string, set_printoptions
|
1636 |
+
|
1637 |
+
Examples
|
1638 |
+
--------
|
1639 |
+
>>> np.array_repr(np.array([1,2]))
|
1640 |
+
'array([1, 2])'
|
1641 |
+
>>> np.array_repr(np.ma.array([0.]))
|
1642 |
+
'MaskedArray([ 0.])'
|
1643 |
+
>>> np.array_repr(np.array([], np.int32))
|
1644 |
+
'array([], dtype=int32)'
|
1645 |
+
|
1646 |
+
>>> x = np.array([1e-6, 4e-7, 2, 3])
|
1647 |
+
>>> np.array_repr(x, precision=6, suppress_small=True)
|
1648 |
+
'array([ 0.000001, 0. , 2. , 3. ])'
|
1649 |
+
|
1650 |
+
"""
|
1651 |
+
if arr.size > 0 or arr.shape==(0,):
|
1652 |
+
lst = array2string(arr, max_line_width, precision, suppress_small,
|
1653 |
+
', ', "array(")
|
1654 |
+
else: # show zero-length shape unless it is (0,)
|
1655 |
+
lst = "[], shape=%s" % (repr(arr.shape),)
|
1656 |
+
|
1657 |
+
if arr.__class__ is not ndarray:
|
1658 |
+
cName= arr.__class__.__name__
|
1659 |
+
else:
|
1660 |
+
cName = "array"
|
1661 |
+
|
1662 |
+
skipdtype = (arr.dtype.type in _typelessdata) and arr.size > 0
|
1663 |
+
|
1664 |
+
if skipdtype:
|
1665 |
+
return "%s(%s)" % (cName, lst)
|
1666 |
+
else:
|
1667 |
+
typename = arr.dtype.name
|
1668 |
+
# Quote typename in the output if it is "complex".
|
1669 |
+
if typename and not (typename[0].isalpha() and typename.isalnum()):
|
1670 |
+
typename = "'%s'" % typename
|
1671 |
+
|
1672 |
+
lf = ''
|
1673 |
+
if issubclass(arr.dtype.type, flexible):
|
1674 |
+
if arr.dtype.names:
|
1675 |
+
typename = "%s" % str(arr.dtype)
|
1676 |
+
else:
|
1677 |
+
typename = "'%s'" % str(arr.dtype)
|
1678 |
+
lf = '\n'+' '*len("array(")
|
1679 |
+
return cName + "(%s, %sdtype=%s)" % (lst, lf, typename)
|
1680 |
+
|
1681 |
+
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
|
1682 |
+
"""
|
1683 |
+
Return a string representation of the data in an array.
|
1684 |
+
|
1685 |
+
The data in the array is returned as a single string. This function is
|
1686 |
+
similar to `array_repr`, the difference being that `array_repr` also
|
1687 |
+
returns information on the kind of array and its data type.
|
1688 |
+
|
1689 |
+
Parameters
|
1690 |
+
----------
|
1691 |
+
a : ndarray
|
1692 |
+
Input array.
|
1693 |
+
max_line_width : int, optional
|
1694 |
+
Inserts newlines if text is longer than `max_line_width`. The
|
1695 |
+
default is, indirectly, 75.
|
1696 |
+
precision : int, optional
|
1697 |
+
Floating point precision. Default is the current printing precision
|
1698 |
+
(usually 8), which can be altered using `set_printoptions`.
|
1699 |
+
suppress_small : bool, optional
|
1700 |
+
Represent numbers "very close" to zero as zero; default is False.
|
1701 |
+
Very close is defined by precision: if the precision is 8, e.g.,
|
1702 |
+
numbers smaller (in absolute value) than 5e-9 are represented as
|
1703 |
+
zero.
|
1704 |
+
|
1705 |
+
See Also
|
1706 |
+
--------
|
1707 |
+
array2string, array_repr, set_printoptions
|
1708 |
+
|
1709 |
+
Examples
|
1710 |
+
--------
|
1711 |
+
>>> np.array_str(np.arange(3))
|
1712 |
+
'[0 1 2]'
|
1713 |
+
|
1714 |
+
"""
|
1715 |
+
return array2string(a, max_line_width, precision, suppress_small, ' ', "", str)
|
1716 |
+
|
1717 |
+
def set_string_function(f, repr=True):
|
1718 |
+
"""
|
1719 |
+
Set a Python function to be used when pretty printing arrays.
|
1720 |
+
|
1721 |
+
Parameters
|
1722 |
+
----------
|
1723 |
+
f : function or None
|
1724 |
+
Function to be used to pretty print arrays. The function should expect
|
1725 |
+
a single array argument and return a string of the representation of
|
1726 |
+
the array. If None, the function is reset to the default NumPy function
|
1727 |
+
to print arrays.
|
1728 |
+
repr : bool, optional
|
1729 |
+
If True (default), the function for pretty printing (``__repr__``)
|
1730 |
+
is set, if False the function that returns the default string
|
1731 |
+
representation (``__str__``) is set.
|
1732 |
+
|
1733 |
+
See Also
|
1734 |
+
--------
|
1735 |
+
set_printoptions, get_printoptions
|
1736 |
+
|
1737 |
+
Examples
|
1738 |
+
--------
|
1739 |
+
>>> def pprint(arr):
|
1740 |
+
... return 'HA! - What are you going to do now?'
|
1741 |
+
...
|
1742 |
+
>>> np.set_string_function(pprint)
|
1743 |
+
>>> a = np.arange(10)
|
1744 |
+
>>> a
|
1745 |
+
HA! - What are you going to do now?
|
1746 |
+
>>> print a
|
1747 |
+
[0 1 2 3 4 5 6 7 8 9]
|
1748 |
+
|
1749 |
+
We can reset the function to the default:
|
1750 |
+
|
1751 |
+
>>> np.set_string_function(None)
|
1752 |
+
>>> a
|
1753 |
+
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
1754 |
+
|
1755 |
+
`repr` affects either pretty printing or normal string representation.
|
1756 |
+
Note that ``__repr__`` is still affected by setting ``__str__``
|
1757 |
+
because the width of each array element in the returned string becomes
|
1758 |
+
equal to the length of the result of ``__str__()``.
|
1759 |
+
|
1760 |
+
>>> x = np.arange(4)
|
1761 |
+
>>> np.set_string_function(lambda x:'random', repr=False)
|
1762 |
+
>>> x.__str__()
|
1763 |
+
'random'
|
1764 |
+
>>> x.__repr__()
|
1765 |
+
'array([ 0, 1, 2, 3])'
|
1766 |
+
|
1767 |
+
"""
|
1768 |
+
if f is None:
|
1769 |
+
if repr:
|
1770 |
+
return multiarray.set_string_function(array_repr, 1)
|
1771 |
+
else:
|
1772 |
+
return multiarray.set_string_function(array_str, 0)
|
1773 |
+
else:
|
1774 |
+
return multiarray.set_string_function(f, repr)
|
1775 |
+
|
1776 |
+
set_string_function(array_str, 0)
|
1777 |
+
set_string_function(array_repr, 1)
|
1778 |
+
|
1779 |
+
little_endian = (sys.byteorder == 'little')
|
1780 |
+
|
1781 |
+
|
1782 |
+
def indices(dimensions, dtype=int):
|
1783 |
+
"""
|
1784 |
+
Return an array representing the indices of a grid.
|
1785 |
+
|
1786 |
+
Compute an array where the subarrays contain index values 0,1,...
|
1787 |
+
varying only along the corresponding axis.
|
1788 |
+
|
1789 |
+
Parameters
|
1790 |
+
----------
|
1791 |
+
dimensions : sequence of ints
|
1792 |
+
The shape of the grid.
|
1793 |
+
dtype : dtype, optional
|
1794 |
+
Data type of the result.
|
1795 |
+
|
1796 |
+
Returns
|
1797 |
+
-------
|
1798 |
+
grid : ndarray
|
1799 |
+
The array of grid indices,
|
1800 |
+
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
|
1801 |
+
|
1802 |
+
See Also
|
1803 |
+
--------
|
1804 |
+
mgrid, meshgrid
|
1805 |
+
|
1806 |
+
Notes
|
1807 |
+
-----
|
1808 |
+
The output shape is obtained by prepending the number of dimensions
|
1809 |
+
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
|
1810 |
+
``(r0, ..., rN-1)`` of length ``N``, the output shape is
|
1811 |
+
``(N,r0,...,rN-1)``.
|
1812 |
+
|
1813 |
+
The subarrays ``grid[k]`` contains the N-D array of indices along the
|
1814 |
+
``k-th`` axis. Explicitly::
|
1815 |
+
|
1816 |
+
grid[k,i0,i1,...,iN-1] = ik
|
1817 |
+
|
1818 |
+
Examples
|
1819 |
+
--------
|
1820 |
+
>>> grid = np.indices((2, 3))
|
1821 |
+
>>> grid.shape
|
1822 |
+
(2, 2, 3)
|
1823 |
+
>>> grid[0] # row indices
|
1824 |
+
array([[0, 0, 0],
|
1825 |
+
[1, 1, 1]])
|
1826 |
+
>>> grid[1] # column indices
|
1827 |
+
array([[0, 1, 2],
|
1828 |
+
[0, 1, 2]])
|
1829 |
+
|
1830 |
+
The indices can be used as an index into an array.
|
1831 |
+
|
1832 |
+
>>> x = np.arange(20).reshape(5, 4)
|
1833 |
+
>>> row, col = np.indices((2, 3))
|
1834 |
+
>>> x[row, col]
|
1835 |
+
array([[0, 1, 2],
|
1836 |
+
[4, 5, 6]])
|
1837 |
+
|
1838 |
+
Note that it would be more straightforward in the above example to
|
1839 |
+
extract the required elements directly with ``x[:2, :3]``.
|
1840 |
+
|
1841 |
+
"""
|
1842 |
+
dimensions = tuple(dimensions)
|
1843 |
+
N = len(dimensions)
|
1844 |
+
if N == 0:
|
1845 |
+
return array([], dtype=dtype)
|
1846 |
+
res = empty((N,)+dimensions, dtype=dtype)
|
1847 |
+
for i, dim in enumerate(dimensions):
|
1848 |
+
tmp = arange(dim, dtype=dtype)
|
1849 |
+
tmp.shape = (1,)*i + (dim,)+(1,)*(N-i-1)
|
1850 |
+
newdim = dimensions[:i] + (1,)+ dimensions[i+1:]
|
1851 |
+
val = zeros(newdim, dtype)
|
1852 |
+
add(tmp, val, res[i])
|
1853 |
+
return res
|
1854 |
+
|
1855 |
+
def fromfunction(function, shape, **kwargs):
|
1856 |
+
"""
|
1857 |
+
Construct an array by executing a function over each coordinate.
|
1858 |
+
|
1859 |
+
The resulting array therefore has a value ``fn(x, y, z)`` at
|
1860 |
+
coordinate ``(x, y, z)``.
|
1861 |
+
|
1862 |
+
Parameters
|
1863 |
+
----------
|
1864 |
+
function : callable
|
1865 |
+
The function is called with N parameters, where N is the rank of
|
1866 |
+
`shape`. Each parameter represents the coordinates of the array
|
1867 |
+
varying along a specific axis. For example, if `shape`
|
1868 |
+
were ``(2, 2)``, then the parameters in turn be (0, 0), (0, 1),
|
1869 |
+
(1, 0), (1, 1).
|
1870 |
+
shape : (N,) tuple of ints
|
1871 |
+
Shape of the output array, which also determines the shape of
|
1872 |
+
the coordinate arrays passed to `function`.
|
1873 |
+
dtype : data-type, optional
|
1874 |
+
Data-type of the coordinate arrays passed to `function`.
|
1875 |
+
By default, `dtype` is float.
|
1876 |
+
|
1877 |
+
Returns
|
1878 |
+
-------
|
1879 |
+
fromfunction : any
|
1880 |
+
The result of the call to `function` is passed back directly.
|
1881 |
+
Therefore the shape of `fromfunction` is completely determined by
|
1882 |
+
`function`. If `function` returns a scalar value, the shape of
|
1883 |
+
`fromfunction` would match the `shape` parameter.
|
1884 |
+
|
1885 |
+
See Also
|
1886 |
+
--------
|
1887 |
+
indices, meshgrid
|
1888 |
+
|
1889 |
+
Notes
|
1890 |
+
-----
|
1891 |
+
Keywords other than `dtype` are passed to `function`.
|
1892 |
+
|
1893 |
+
Examples
|
1894 |
+
--------
|
1895 |
+
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
|
1896 |
+
array([[ True, False, False],
|
1897 |
+
[False, True, False],
|
1898 |
+
[False, False, True]], dtype=bool)
|
1899 |
+
|
1900 |
+
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
|
1901 |
+
array([[0, 1, 2],
|
1902 |
+
[1, 2, 3],
|
1903 |
+
[2, 3, 4]])
|
1904 |
+
|
1905 |
+
"""
|
1906 |
+
dtype = kwargs.pop('dtype', float)
|
1907 |
+
args = indices(shape, dtype=dtype)
|
1908 |
+
return function(*args,**kwargs)
|
1909 |
+
|
1910 |
+
def isscalar(num):
|
1911 |
+
"""
|
1912 |
+
Returns True if the type of `num` is a scalar type.
|
1913 |
+
|
1914 |
+
Parameters
|
1915 |
+
----------
|
1916 |
+
num : any
|
1917 |
+
Input argument, can be of any type and shape.
|
1918 |
+
|
1919 |
+
Returns
|
1920 |
+
-------
|
1921 |
+
val : bool
|
1922 |
+
True if `num` is a scalar type, False if it is not.
|
1923 |
+
|
1924 |
+
Examples
|
1925 |
+
--------
|
1926 |
+
>>> np.isscalar(3.1)
|
1927 |
+
True
|
1928 |
+
>>> np.isscalar([3.1])
|
1929 |
+
False
|
1930 |
+
>>> np.isscalar(False)
|
1931 |
+
True
|
1932 |
+
|
1933 |
+
"""
|
1934 |
+
if isinstance(num, generic):
|
1935 |
+
return True
|
1936 |
+
else:
|
1937 |
+
return type(num) in ScalarType
|
1938 |
+
|
1939 |
+
_lkup = {
|
1940 |
+
'0':'0000',
|
1941 |
+
'1':'0001',
|
1942 |
+
'2':'0010',
|
1943 |
+
'3':'0011',
|
1944 |
+
'4':'0100',
|
1945 |
+
'5':'0101',
|
1946 |
+
'6':'0110',
|
1947 |
+
'7':'0111',
|
1948 |
+
'8':'1000',
|
1949 |
+
'9':'1001',
|
1950 |
+
'a':'1010',
|
1951 |
+
'b':'1011',
|
1952 |
+
'c':'1100',
|
1953 |
+
'd':'1101',
|
1954 |
+
'e':'1110',
|
1955 |
+
'f':'1111',
|
1956 |
+
'A':'1010',
|
1957 |
+
'B':'1011',
|
1958 |
+
'C':'1100',
|
1959 |
+
'D':'1101',
|
1960 |
+
'E':'1110',
|
1961 |
+
'F':'1111',
|
1962 |
+
'L':''}
|
1963 |
+
|
1964 |
+
def binary_repr(num, width=None):
|
1965 |
+
"""
|
1966 |
+
Return the binary representation of the input number as a string.
|
1967 |
+
|
1968 |
+
For negative numbers, if width is not given, a minus sign is added to the
|
1969 |
+
front. If width is given, the two's complement of the number is
|
1970 |
+
returned, with respect to that width.
|
1971 |
+
|
1972 |
+
In a two's-complement system negative numbers are represented by the two's
|
1973 |
+
complement of the absolute value. This is the most common method of
|
1974 |
+
representing signed integers on computers [1]_. A N-bit two's-complement
|
1975 |
+
system can represent every integer in the range
|
1976 |
+
:math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
|
1977 |
+
|
1978 |
+
Parameters
|
1979 |
+
----------
|
1980 |
+
num : int
|
1981 |
+
Only an integer decimal number can be used.
|
1982 |
+
width : int, optional
|
1983 |
+
The length of the returned string if `num` is positive, the length of
|
1984 |
+
the two's complement if `num` is negative.
|
1985 |
+
|
1986 |
+
Returns
|
1987 |
+
-------
|
1988 |
+
bin : str
|
1989 |
+
Binary representation of `num` or two's complement of `num`.
|
1990 |
+
|
1991 |
+
See Also
|
1992 |
+
--------
|
1993 |
+
base_repr: Return a string representation of a number in the given base
|
1994 |
+
system.
|
1995 |
+
|
1996 |
+
Notes
|
1997 |
+
-----
|
1998 |
+
`binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
|
1999 |
+
faster.
|
2000 |
+
|
2001 |
+
References
|
2002 |
+
----------
|
2003 |
+
.. [1] Wikipedia, "Two's complement",
|
2004 |
+
http://en.wikipedia.org/wiki/Two's_complement
|
2005 |
+
|
2006 |
+
Examples
|
2007 |
+
--------
|
2008 |
+
>>> np.binary_repr(3)
|
2009 |
+
'11'
|
2010 |
+
>>> np.binary_repr(-3)
|
2011 |
+
'-11'
|
2012 |
+
>>> np.binary_repr(3, width=4)
|
2013 |
+
'0011'
|
2014 |
+
|
2015 |
+
The two's complement is returned when the input number is negative and
|
2016 |
+
width is specified:
|
2017 |
+
|
2018 |
+
>>> np.binary_repr(-3, width=4)
|
2019 |
+
'1101'
|
2020 |
+
|
2021 |
+
"""
|
2022 |
+
# ' <-- unbreak Emacs fontification
|
2023 |
+
sign = ''
|
2024 |
+
if num < 0:
|
2025 |
+
if width is None:
|
2026 |
+
sign = '-'
|
2027 |
+
num = -num
|
2028 |
+
else:
|
2029 |
+
# replace num with its 2-complement
|
2030 |
+
num = 2**width + num
|
2031 |
+
elif num == 0:
|
2032 |
+
return '0'*(width or 1)
|
2033 |
+
ostr = hex(num)
|
2034 |
+
bin = ''.join([_lkup[ch] for ch in ostr[2:]])
|
2035 |
+
bin = bin.lstrip('0')
|
2036 |
+
if width is not None:
|
2037 |
+
bin = bin.zfill(width)
|
2038 |
+
return sign + bin
|
2039 |
+
|
2040 |
+
def base_repr(number, base=2, padding=0):
|
2041 |
+
"""
|
2042 |
+
Return a string representation of a number in the given base system.
|
2043 |
+
|
2044 |
+
Parameters
|
2045 |
+
----------
|
2046 |
+
number : int
|
2047 |
+
The value to convert. Only positive values are handled.
|
2048 |
+
base : int, optional
|
2049 |
+
Convert `number` to the `base` number system. The valid range is 2-36,
|
2050 |
+
the default value is 2.
|
2051 |
+
padding : int, optional
|
2052 |
+
Number of zeros padded on the left. Default is 0 (no padding).
|
2053 |
+
|
2054 |
+
Returns
|
2055 |
+
-------
|
2056 |
+
out : str
|
2057 |
+
String representation of `number` in `base` system.
|
2058 |
+
|
2059 |
+
See Also
|
2060 |
+
--------
|
2061 |
+
binary_repr : Faster version of `base_repr` for base 2.
|
2062 |
+
|
2063 |
+
Examples
|
2064 |
+
--------
|
2065 |
+
>>> np.base_repr(5)
|
2066 |
+
'101'
|
2067 |
+
>>> np.base_repr(6, 5)
|
2068 |
+
'11'
|
2069 |
+
>>> np.base_repr(7, base=5, padding=3)
|
2070 |
+
'00012'
|
2071 |
+
|
2072 |
+
>>> np.base_repr(10, base=16)
|
2073 |
+
'A'
|
2074 |
+
>>> np.base_repr(32, base=16)
|
2075 |
+
'20'
|
2076 |
+
|
2077 |
+
"""
|
2078 |
+
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
2079 |
+
if base > len(digits):
|
2080 |
+
raise ValueError("Bases greater than 36 not handled in base_repr.")
|
2081 |
+
|
2082 |
+
num = abs(number)
|
2083 |
+
res = []
|
2084 |
+
while num:
|
2085 |
+
res.append(digits[num % base])
|
2086 |
+
num //= base
|
2087 |
+
if padding:
|
2088 |
+
res.append('0' * padding)
|
2089 |
+
if number < 0:
|
2090 |
+
res.append('-')
|
2091 |
+
return ''.join(reversed(res or '0'))
|
2092 |
+
|
2093 |
+
|
2094 |
+
def load(file):
|
2095 |
+
"""
|
2096 |
+
Wrapper around cPickle.load which accepts either a file-like object or
|
2097 |
+
a filename.
|
2098 |
+
|
2099 |
+
Note that the NumPy binary format is not based on pickle/cPickle anymore.
|
2100 |
+
For details on the preferred way of loading and saving files, see `load`
|
2101 |
+
and `save`.
|
2102 |
+
|
2103 |
+
See Also
|
2104 |
+
--------
|
2105 |
+
load, save
|
2106 |
+
|
2107 |
+
"""
|
2108 |
+
if isinstance(file, type("")):
|
2109 |
+
file = open(file, "rb")
|
2110 |
+
return pickle.load(file)
|
2111 |
+
|
2112 |
+
# These are all essentially abbreviations
|
2113 |
+
# These might wind up in a special abbreviations module
|
2114 |
+
|
2115 |
+
def _maketup(descr, val):
|
2116 |
+
dt = dtype(descr)
|
2117 |
+
# Place val in all scalar tuples:
|
2118 |
+
fields = dt.fields
|
2119 |
+
if fields is None:
|
2120 |
+
return val
|
2121 |
+
else:
|
2122 |
+
res = [_maketup(fields[name][0], val) for name in dt.names]
|
2123 |
+
return tuple(res)
|
2124 |
+
|
2125 |
+
def identity(n, dtype=None):
|
2126 |
+
"""
|
2127 |
+
Return the identity array.
|
2128 |
+
|
2129 |
+
The identity array is a square array with ones on
|
2130 |
+
the main diagonal.
|
2131 |
+
|
2132 |
+
Parameters
|
2133 |
+
----------
|
2134 |
+
n : int
|
2135 |
+
Number of rows (and columns) in `n` x `n` output.
|
2136 |
+
dtype : data-type, optional
|
2137 |
+
Data-type of the output. Defaults to ``float``.
|
2138 |
+
|
2139 |
+
Returns
|
2140 |
+
-------
|
2141 |
+
out : ndarray
|
2142 |
+
`n` x `n` array with its main diagonal set to one,
|
2143 |
+
and all other elements 0.
|
2144 |
+
|
2145 |
+
Examples
|
2146 |
+
--------
|
2147 |
+
>>> np.identity(3)
|
2148 |
+
array([[ 1., 0., 0.],
|
2149 |
+
[ 0., 1., 0.],
|
2150 |
+
[ 0., 0., 1.]])
|
2151 |
+
|
2152 |
+
"""
|
2153 |
+
from numpy import eye
|
2154 |
+
return eye(n, dtype=dtype)
|
2155 |
+
|
2156 |
+
def allclose(a, b, rtol=1.e-5, atol=1.e-8):
|
2157 |
+
"""
|
2158 |
+
Returns True if two arrays are element-wise equal within a tolerance.
|
2159 |
+
|
2160 |
+
The tolerance values are positive, typically very small numbers. The
|
2161 |
+
relative difference (`rtol` * abs(`b`)) and the absolute difference
|
2162 |
+
`atol` are added together to compare against the absolute difference
|
2163 |
+
between `a` and `b`.
|
2164 |
+
|
2165 |
+
If either array contains one or more NaNs, False is returned.
|
2166 |
+
Infs are treated as equal if they are in the same place and of the same
|
2167 |
+
sign in both arrays.
|
2168 |
+
|
2169 |
+
Parameters
|
2170 |
+
----------
|
2171 |
+
a, b : array_like
|
2172 |
+
Input arrays to compare.
|
2173 |
+
rtol : float
|
2174 |
+
The relative tolerance parameter (see Notes).
|
2175 |
+
atol : float
|
2176 |
+
The absolute tolerance parameter (see Notes).
|
2177 |
+
|
2178 |
+
Returns
|
2179 |
+
-------
|
2180 |
+
allclose : bool
|
2181 |
+
Returns True if the two arrays are equal within the given
|
2182 |
+
tolerance; False otherwise.
|
2183 |
+
|
2184 |
+
See Also
|
2185 |
+
--------
|
2186 |
+
isclose, all, any
|
2187 |
+
|
2188 |
+
Notes
|
2189 |
+
-----
|
2190 |
+
If the following equation is element-wise True, then allclose returns
|
2191 |
+
True.
|
2192 |
+
|
2193 |
+
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
|
2194 |
+
|
2195 |
+
The above equation is not symmetric in `a` and `b`, so that
|
2196 |
+
`allclose(a, b)` might be different from `allclose(b, a)` in
|
2197 |
+
some rare cases.
|
2198 |
+
|
2199 |
+
Examples
|
2200 |
+
--------
|
2201 |
+
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
|
2202 |
+
False
|
2203 |
+
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
|
2204 |
+
True
|
2205 |
+
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
|
2206 |
+
False
|
2207 |
+
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
|
2208 |
+
False
|
2209 |
+
|
2210 |
+
"""
|
2211 |
+
x = array(a, copy=False, ndmin=1)
|
2212 |
+
y = array(b, copy=False, ndmin=1)
|
2213 |
+
|
2214 |
+
# make sure y is an inexact type to avoid abs(MIN_INT); will cause
|
2215 |
+
# casting of x later.
|
2216 |
+
dtype = multiarray.result_type(y, 1.)
|
2217 |
+
y = array(y, dtype=dtype, copy=False)
|
2218 |
+
|
2219 |
+
xinf = isinf(x)
|
2220 |
+
yinf = isinf(y)
|
2221 |
+
if any(xinf) or any(yinf):
|
2222 |
+
# Check that x and y have inf's only in the same positions
|
2223 |
+
if not all(xinf == yinf):
|
2224 |
+
return False
|
2225 |
+
# Check that sign of inf's in x and y is the same
|
2226 |
+
if not all(x[xinf] == y[xinf]):
|
2227 |
+
return False
|
2228 |
+
|
2229 |
+
x = x[~xinf]
|
2230 |
+
y = y[~xinf]
|
2231 |
+
|
2232 |
+
# ignore invalid fpe's
|
2233 |
+
with errstate(invalid='ignore'):
|
2234 |
+
r = all(less_equal(abs(x - y), atol + rtol * abs(y)))
|
2235 |
+
|
2236 |
+
return r
|
2237 |
+
|
2238 |
+
def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
|
2239 |
+
"""
|
2240 |
+
Returns a boolean array where two arrays are element-wise equal within a
|
2241 |
+
tolerance.
|
2242 |
+
|
2243 |
+
The tolerance values are positive, typically very small numbers. The
|
2244 |
+
relative difference (`rtol` * abs(`b`)) and the absolute difference
|
2245 |
+
`atol` are added together to compare against the absolute difference
|
2246 |
+
between `a` and `b`.
|
2247 |
+
|
2248 |
+
Parameters
|
2249 |
+
----------
|
2250 |
+
a, b : array_like
|
2251 |
+
Input arrays to compare.
|
2252 |
+
rtol : float
|
2253 |
+
The relative tolerance parameter (see Notes).
|
2254 |
+
atol : float
|
2255 |
+
The absolute tolerance parameter (see Notes).
|
2256 |
+
equal_nan : bool
|
2257 |
+
Whether to compare NaN's as equal. If True, NaN's in `a` will be
|
2258 |
+
considered equal to NaN's in `b` in the output array.
|
2259 |
+
|
2260 |
+
Returns
|
2261 |
+
-------
|
2262 |
+
y : array_like
|
2263 |
+
Returns a boolean array of where `a` and `b` are equal within the
|
2264 |
+
given tolerance. If both `a` and `b` are scalars, returns a single
|
2265 |
+
boolean value.
|
2266 |
+
|
2267 |
+
See Also
|
2268 |
+
--------
|
2269 |
+
allclose
|
2270 |
+
|
2271 |
+
Notes
|
2272 |
+
-----
|
2273 |
+
.. versionadded:: 1.7.0
|
2274 |
+
|
2275 |
+
For finite values, isclose uses the following equation to test whether
|
2276 |
+
two floating point values are equivalent.
|
2277 |
+
|
2278 |
+
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
|
2279 |
+
|
2280 |
+
The above equation is not symmetric in `a` and `b`, so that
|
2281 |
+
`isclose(a, b)` might be different from `isclose(b, a)` in
|
2282 |
+
some rare cases.
|
2283 |
+
|
2284 |
+
Examples
|
2285 |
+
--------
|
2286 |
+
>>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
|
2287 |
+
array([True, False])
|
2288 |
+
>>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
|
2289 |
+
array([True, True])
|
2290 |
+
>>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
|
2291 |
+
array([False, True])
|
2292 |
+
>>> np.isclose([1.0, np.nan], [1.0, np.nan])
|
2293 |
+
array([True, False])
|
2294 |
+
>>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
|
2295 |
+
array([True, True])
|
2296 |
+
"""
|
2297 |
+
def within_tol(x, y, atol, rtol):
|
2298 |
+
with errstate(invalid='ignore'):
|
2299 |
+
result = less_equal(abs(x-y), atol + rtol * abs(y))
|
2300 |
+
if isscalar(a) and isscalar(b):
|
2301 |
+
result = bool(result)
|
2302 |
+
return result
|
2303 |
+
|
2304 |
+
x = array(a, copy=False, subok=True, ndmin=1)
|
2305 |
+
y = array(b, copy=False, subok=True, ndmin=1)
|
2306 |
+
xfin = isfinite(x)
|
2307 |
+
yfin = isfinite(y)
|
2308 |
+
if all(xfin) and all(yfin):
|
2309 |
+
return within_tol(x, y, atol, rtol)
|
2310 |
+
else:
|
2311 |
+
finite = xfin & yfin
|
2312 |
+
cond = zeros_like(finite, subok=True)
|
2313 |
+
# Because we're using boolean indexing, x & y must be the same shape.
|
2314 |
+
# Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
|
2315 |
+
# lib.stride_tricks, though, so we can't import it here.
|
2316 |
+
x = x * ones_like(cond)
|
2317 |
+
y = y * ones_like(cond)
|
2318 |
+
# Avoid subtraction with infinite/nan values...
|
2319 |
+
cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
|
2320 |
+
# Check for equality of infinite values...
|
2321 |
+
cond[~finite] = (x[~finite] == y[~finite])
|
2322 |
+
if equal_nan:
|
2323 |
+
# Make NaN == NaN
|
2324 |
+
both_nan = isnan(x) & isnan(y)
|
2325 |
+
cond[both_nan] = both_nan[both_nan]
|
2326 |
+
return cond
|
2327 |
+
|
2328 |
+
def array_equal(a1, a2):
|
2329 |
+
"""
|
2330 |
+
True if two arrays have the same shape and elements, False otherwise.
|
2331 |
+
|
2332 |
+
Parameters
|
2333 |
+
----------
|
2334 |
+
a1, a2 : array_like
|
2335 |
+
Input arrays.
|
2336 |
+
|
2337 |
+
Returns
|
2338 |
+
-------
|
2339 |
+
b : bool
|
2340 |
+
Returns True if the arrays are equal.
|
2341 |
+
|
2342 |
+
See Also
|
2343 |
+
--------
|
2344 |
+
allclose: Returns True if two arrays are element-wise equal within a
|
2345 |
+
tolerance.
|
2346 |
+
array_equiv: Returns True if input arrays are shape consistent and all
|
2347 |
+
elements equal.
|
2348 |
+
|
2349 |
+
Examples
|
2350 |
+
--------
|
2351 |
+
>>> np.array_equal([1, 2], [1, 2])
|
2352 |
+
True
|
2353 |
+
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
|
2354 |
+
True
|
2355 |
+
>>> np.array_equal([1, 2], [1, 2, 3])
|
2356 |
+
False
|
2357 |
+
>>> np.array_equal([1, 2], [1, 4])
|
2358 |
+
False
|
2359 |
+
|
2360 |
+
"""
|
2361 |
+
try:
|
2362 |
+
a1, a2 = asarray(a1), asarray(a2)
|
2363 |
+
except:
|
2364 |
+
return False
|
2365 |
+
if a1.shape != a2.shape:
|
2366 |
+
return False
|
2367 |
+
return bool(asarray(a1 == a2).all())
|
2368 |
+
|
2369 |
+
def array_equiv(a1, a2):
|
2370 |
+
"""
|
2371 |
+
Returns True if input arrays are shape consistent and all elements equal.
|
2372 |
+
|
2373 |
+
Shape consistent means they are either the same shape, or one input array
|
2374 |
+
can be broadcasted to create the same shape as the other one.
|
2375 |
+
|
2376 |
+
Parameters
|
2377 |
+
----------
|
2378 |
+
a1, a2 : array_like
|
2379 |
+
Input arrays.
|
2380 |
+
|
2381 |
+
Returns
|
2382 |
+
-------
|
2383 |
+
out : bool
|
2384 |
+
True if equivalent, False otherwise.
|
2385 |
+
|
2386 |
+
Examples
|
2387 |
+
--------
|
2388 |
+
>>> np.array_equiv([1, 2], [1, 2])
|
2389 |
+
True
|
2390 |
+
>>> np.array_equiv([1, 2], [1, 3])
|
2391 |
+
False
|
2392 |
+
|
2393 |
+
Showing the shape equivalence:
|
2394 |
+
|
2395 |
+
>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
|
2396 |
+
True
|
2397 |
+
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
|
2398 |
+
False
|
2399 |
+
|
2400 |
+
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
|
2401 |
+
False
|
2402 |
+
|
2403 |
+
"""
|
2404 |
+
try:
|
2405 |
+
a1, a2 = asarray(a1), asarray(a2)
|
2406 |
+
except:
|
2407 |
+
return False
|
2408 |
+
try:
|
2409 |
+
multiarray.broadcast(a1, a2)
|
2410 |
+
except:
|
2411 |
+
return False
|
2412 |
+
|
2413 |
+
return bool(asarray(a1 == a2).all())
|
2414 |
+
|
2415 |
+
|
2416 |
+
_errdict = {"ignore":ERR_IGNORE,
|
2417 |
+
"warn":ERR_WARN,
|
2418 |
+
"raise":ERR_RAISE,
|
2419 |
+
"call":ERR_CALL,
|
2420 |
+
"print":ERR_PRINT,
|
2421 |
+
"log":ERR_LOG}
|
2422 |
+
|
2423 |
+
_errdict_rev = {}
|
2424 |
+
for key in _errdict.keys():
|
2425 |
+
_errdict_rev[_errdict[key]] = key
|
2426 |
+
del key
|
2427 |
+
|
2428 |
+
def seterr(all=None, divide=None, over=None, under=None, invalid=None):
|
2429 |
+
"""
|
2430 |
+
Set how floating-point errors are handled.
|
2431 |
+
|
2432 |
+
Note that operations on integer scalar types (such as `int16`) are
|
2433 |
+
handled like floating point, and are affected by these settings.
|
2434 |
+
|
2435 |
+
Parameters
|
2436 |
+
----------
|
2437 |
+
all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
2438 |
+
Set treatment for all types of floating-point errors at once:
|
2439 |
+
|
2440 |
+
- ignore: Take no action when the exception occurs.
|
2441 |
+
- warn: Print a `RuntimeWarning` (via the Python `warnings` module).
|
2442 |
+
- raise: Raise a `FloatingPointError`.
|
2443 |
+
- call: Call a function specified using the `seterrcall` function.
|
2444 |
+
- print: Print a warning directly to ``stdout``.
|
2445 |
+
- log: Record error in a Log object specified by `seterrcall`.
|
2446 |
+
|
2447 |
+
The default is not to change the current behavior.
|
2448 |
+
divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
2449 |
+
Treatment for division by zero.
|
2450 |
+
over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
2451 |
+
Treatment for floating-point overflow.
|
2452 |
+
under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
2453 |
+
Treatment for floating-point underflow.
|
2454 |
+
invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
2455 |
+
Treatment for invalid floating-point operation.
|
2456 |
+
|
2457 |
+
Returns
|
2458 |
+
-------
|
2459 |
+
old_settings : dict
|
2460 |
+
Dictionary containing the old settings.
|
2461 |
+
|
2462 |
+
See also
|
2463 |
+
--------
|
2464 |
+
seterrcall : Set a callback function for the 'call' mode.
|
2465 |
+
geterr, geterrcall, errstate
|
2466 |
+
|
2467 |
+
Notes
|
2468 |
+
-----
|
2469 |
+
The floating-point exceptions are defined in the IEEE 754 standard [1]:
|
2470 |
+
|
2471 |
+
- Division by zero: infinite result obtained from finite numbers.
|
2472 |
+
- Overflow: result too large to be expressed.
|
2473 |
+
- Underflow: result so close to zero that some precision
|
2474 |
+
was lost.
|
2475 |
+
- Invalid operation: result is not an expressible number, typically
|
2476 |
+
indicates that a NaN was produced.
|
2477 |
+
|
2478 |
+
.. [1] http://en.wikipedia.org/wiki/IEEE_754
|
2479 |
+
|
2480 |
+
Examples
|
2481 |
+
--------
|
2482 |
+
>>> old_settings = np.seterr(all='ignore') #seterr to known value
|
2483 |
+
>>> np.seterr(over='raise')
|
2484 |
+
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore',
|
2485 |
+
'under': 'ignore'}
|
2486 |
+
>>> np.seterr(**old_settings) # reset to default
|
2487 |
+
{'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
|
2488 |
+
|
2489 |
+
>>> np.int16(32000) * np.int16(3)
|
2490 |
+
30464
|
2491 |
+
>>> old_settings = np.seterr(all='warn', over='raise')
|
2492 |
+
>>> np.int16(32000) * np.int16(3)
|
2493 |
+
Traceback (most recent call last):
|
2494 |
+
File "<stdin>", line 1, in <module>
|
2495 |
+
FloatingPointError: overflow encountered in short_scalars
|
2496 |
+
|
2497 |
+
>>> old_settings = np.seterr(all='print')
|
2498 |
+
>>> np.geterr()
|
2499 |
+
{'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'}
|
2500 |
+
>>> np.int16(32000) * np.int16(3)
|
2501 |
+
Warning: overflow encountered in short_scalars
|
2502 |
+
30464
|
2503 |
+
|
2504 |
+
"""
|
2505 |
+
|
2506 |
+
pyvals = umath.geterrobj()
|
2507 |
+
old = geterr()
|
2508 |
+
|
2509 |
+
if divide is None: divide = all or old['divide']
|
2510 |
+
if over is None: over = all or old['over']
|
2511 |
+
if under is None: under = all or old['under']
|
2512 |
+
if invalid is None: invalid = all or old['invalid']
|
2513 |
+
|
2514 |
+
maskvalue = ((_errdict[divide] << SHIFT_DIVIDEBYZERO) +
|
2515 |
+
(_errdict[over] << SHIFT_OVERFLOW ) +
|
2516 |
+
(_errdict[under] << SHIFT_UNDERFLOW) +
|
2517 |
+
(_errdict[invalid] << SHIFT_INVALID))
|
2518 |
+
|
2519 |
+
pyvals[1] = maskvalue
|
2520 |
+
umath.seterrobj(pyvals)
|
2521 |
+
return old
|
2522 |
+
|
2523 |
+
|
2524 |
+
def geterr():
|
2525 |
+
"""
|
2526 |
+
Get the current way of handling floating-point errors.
|
2527 |
+
|
2528 |
+
Returns
|
2529 |
+
-------
|
2530 |
+
res : dict
|
2531 |
+
A dictionary with keys "divide", "over", "under", and "invalid",
|
2532 |
+
whose values are from the strings "ignore", "print", "log", "warn",
|
2533 |
+
"raise", and "call". The keys represent possible floating-point
|
2534 |
+
exceptions, and the values define how these exceptions are handled.
|
2535 |
+
|
2536 |
+
See Also
|
2537 |
+
--------
|
2538 |
+
geterrcall, seterr, seterrcall
|
2539 |
+
|
2540 |
+
Notes
|
2541 |
+
-----
|
2542 |
+
For complete documentation of the types of floating-point exceptions and
|
2543 |
+
treatment options, see `seterr`.
|
2544 |
+
|
2545 |
+
Examples
|
2546 |
+
--------
|
2547 |
+
>>> np.geterr()
|
2548 |
+
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn',
|
2549 |
+
'under': 'ignore'}
|
2550 |
+
>>> np.arange(3.) / np.arange(3.)
|
2551 |
+
array([ NaN, 1., 1.])
|
2552 |
+
|
2553 |
+
>>> oldsettings = np.seterr(all='warn', over='raise')
|
2554 |
+
>>> np.geterr()
|
2555 |
+
{'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'}
|
2556 |
+
>>> np.arange(3.) / np.arange(3.)
|
2557 |
+
__main__:1: RuntimeWarning: invalid value encountered in divide
|
2558 |
+
array([ NaN, 1., 1.])
|
2559 |
+
|
2560 |
+
"""
|
2561 |
+
maskvalue = umath.geterrobj()[1]
|
2562 |
+
mask = 7
|
2563 |
+
res = {}
|
2564 |
+
val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask
|
2565 |
+
res['divide'] = _errdict_rev[val]
|
2566 |
+
val = (maskvalue >> SHIFT_OVERFLOW) & mask
|
2567 |
+
res['over'] = _errdict_rev[val]
|
2568 |
+
val = (maskvalue >> SHIFT_UNDERFLOW) & mask
|
2569 |
+
res['under'] = _errdict_rev[val]
|
2570 |
+
val = (maskvalue >> SHIFT_INVALID) & mask
|
2571 |
+
res['invalid'] = _errdict_rev[val]
|
2572 |
+
return res
|
2573 |
+
|
2574 |
+
def setbufsize(size):
|
2575 |
+
"""
|
2576 |
+
Set the size of the buffer used in ufuncs.
|
2577 |
+
|
2578 |
+
Parameters
|
2579 |
+
----------
|
2580 |
+
size : int
|
2581 |
+
Size of buffer.
|
2582 |
+
|
2583 |
+
"""
|
2584 |
+
if size > 10e6:
|
2585 |
+
raise ValueError("Buffer size, %s, is too big." % size)
|
2586 |
+
if size < 5:
|
2587 |
+
raise ValueError("Buffer size, %s, is too small." %size)
|
2588 |
+
if size % 16 != 0:
|
2589 |
+
raise ValueError("Buffer size, %s, is not a multiple of 16." %size)
|
2590 |
+
|
2591 |
+
pyvals = umath.geterrobj()
|
2592 |
+
old = getbufsize()
|
2593 |
+
pyvals[0] = size
|
2594 |
+
umath.seterrobj(pyvals)
|
2595 |
+
return old
|
2596 |
+
|
2597 |
+
def getbufsize():
|
2598 |
+
"""
|
2599 |
+
Return the size of the buffer used in ufuncs.
|
2600 |
+
|
2601 |
+
Returns
|
2602 |
+
-------
|
2603 |
+
getbufsize : int
|
2604 |
+
Size of ufunc buffer in bytes.
|
2605 |
+
|
2606 |
+
"""
|
2607 |
+
return umath.geterrobj()[0]
|
2608 |
+
|
2609 |
+
def seterrcall(func):
|
2610 |
+
"""
|
2611 |
+
Set the floating-point error callback function or log object.
|
2612 |
+
|
2613 |
+
There are two ways to capture floating-point error messages. The first
|
2614 |
+
is to set the error-handler to 'call', using `seterr`. Then, set
|
2615 |
+
the function to call using this function.
|
2616 |
+
|
2617 |
+
The second is to set the error-handler to 'log', using `seterr`.
|
2618 |
+
Floating-point errors then trigger a call to the 'write' method of
|
2619 |
+
the provided object.
|
2620 |
+
|
2621 |
+
Parameters
|
2622 |
+
----------
|
2623 |
+
func : callable f(err, flag) or object with write method
|
2624 |
+
Function to call upon floating-point errors ('call'-mode) or
|
2625 |
+
object whose 'write' method is used to log such message ('log'-mode).
|
2626 |
+
|
2627 |
+
The call function takes two arguments. The first is the
|
2628 |
+
type of error (one of "divide", "over", "under", or "invalid"),
|
2629 |
+
and the second is the status flag. The flag is a byte, whose
|
2630 |
+
least-significant bits indicate the status::
|
2631 |
+
|
2632 |
+
[0 0 0 0 invalid over under invalid]
|
2633 |
+
|
2634 |
+
In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
|
2635 |
+
|
2636 |
+
If an object is provided, its write method should take one argument,
|
2637 |
+
a string.
|
2638 |
+
|
2639 |
+
Returns
|
2640 |
+
-------
|
2641 |
+
h : callable, log instance or None
|
2642 |
+
The old error handler.
|
2643 |
+
|
2644 |
+
See Also
|
2645 |
+
--------
|
2646 |
+
seterr, geterr, geterrcall
|
2647 |
+
|
2648 |
+
Examples
|
2649 |
+
--------
|
2650 |
+
Callback upon error:
|
2651 |
+
|
2652 |
+
>>> def err_handler(type, flag):
|
2653 |
+
... print "Floating point error (%s), with flag %s" % (type, flag)
|
2654 |
+
...
|
2655 |
+
|
2656 |
+
>>> saved_handler = np.seterrcall(err_handler)
|
2657 |
+
>>> save_err = np.seterr(all='call')
|
2658 |
+
|
2659 |
+
>>> np.array([1, 2, 3]) / 0.0
|
2660 |
+
Floating point error (divide by zero), with flag 1
|
2661 |
+
array([ Inf, Inf, Inf])
|
2662 |
+
|
2663 |
+
>>> np.seterrcall(saved_handler)
|
2664 |
+
<function err_handler at 0x...>
|
2665 |
+
>>> np.seterr(**save_err)
|
2666 |
+
{'over': 'call', 'divide': 'call', 'invalid': 'call', 'under': 'call'}
|
2667 |
+
|
2668 |
+
Log error message:
|
2669 |
+
|
2670 |
+
>>> class Log(object):
|
2671 |
+
... def write(self, msg):
|
2672 |
+
... print "LOG: %s" % msg
|
2673 |
+
...
|
2674 |
+
|
2675 |
+
>>> log = Log()
|
2676 |
+
>>> saved_handler = np.seterrcall(log)
|
2677 |
+
>>> save_err = np.seterr(all='log')
|
2678 |
+
|
2679 |
+
>>> np.array([1, 2, 3]) / 0.0
|
2680 |
+
LOG: Warning: divide by zero encountered in divide
|
2681 |
+
<BLANKLINE>
|
2682 |
+
array([ Inf, Inf, Inf])
|
2683 |
+
|
2684 |
+
>>> np.seterrcall(saved_handler)
|
2685 |
+
<__main__.Log object at 0x...>
|
2686 |
+
>>> np.seterr(**save_err)
|
2687 |
+
{'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'}
|
2688 |
+
|
2689 |
+
"""
|
2690 |
+
if func is not None and not isinstance(func, collections.Callable):
|
2691 |
+
if not hasattr(func, 'write') or not isinstance(func.write, collections.Callable):
|
2692 |
+
raise ValueError("Only callable can be used as callback")
|
2693 |
+
pyvals = umath.geterrobj()
|
2694 |
+
old = geterrcall()
|
2695 |
+
pyvals[2] = func
|
2696 |
+
umath.seterrobj(pyvals)
|
2697 |
+
return old
|
2698 |
+
|
2699 |
+
def geterrcall():
|
2700 |
+
"""
|
2701 |
+
Return the current callback function used on floating-point errors.
|
2702 |
+
|
2703 |
+
When the error handling for a floating-point error (one of "divide",
|
2704 |
+
"over", "under", or "invalid") is set to 'call' or 'log', the function
|
2705 |
+
that is called or the log instance that is written to is returned by
|
2706 |
+
`geterrcall`. This function or log instance has been set with
|
2707 |
+
`seterrcall`.
|
2708 |
+
|
2709 |
+
Returns
|
2710 |
+
-------
|
2711 |
+
errobj : callable, log instance or None
|
2712 |
+
The current error handler. If no handler was set through `seterrcall`,
|
2713 |
+
``None`` is returned.
|
2714 |
+
|
2715 |
+
See Also
|
2716 |
+
--------
|
2717 |
+
seterrcall, seterr, geterr
|
2718 |
+
|
2719 |
+
Notes
|
2720 |
+
-----
|
2721 |
+
For complete documentation of the types of floating-point exceptions and
|
2722 |
+
treatment options, see `seterr`.
|
2723 |
+
|
2724 |
+
Examples
|
2725 |
+
--------
|
2726 |
+
>>> np.geterrcall() # we did not yet set a handler, returns None
|
2727 |
+
|
2728 |
+
>>> oldsettings = np.seterr(all='call')
|
2729 |
+
>>> def err_handler(type, flag):
|
2730 |
+
... print "Floating point error (%s), with flag %s" % (type, flag)
|
2731 |
+
>>> oldhandler = np.seterrcall(err_handler)
|
2732 |
+
>>> np.array([1, 2, 3]) / 0.0
|
2733 |
+
Floating point error (divide by zero), with flag 1
|
2734 |
+
array([ Inf, Inf, Inf])
|
2735 |
+
|
2736 |
+
>>> cur_handler = np.geterrcall()
|
2737 |
+
>>> cur_handler is err_handler
|
2738 |
+
True
|
2739 |
+
|
2740 |
+
"""
|
2741 |
+
return umath.geterrobj()[2]
|
2742 |
+
|
2743 |
+
class _unspecified(object):
|
2744 |
+
pass
|
2745 |
+
_Unspecified = _unspecified()
|
2746 |
+
|
2747 |
+
class errstate(object):
|
2748 |
+
"""
|
2749 |
+
errstate(**kwargs)
|
2750 |
+
|
2751 |
+
Context manager for floating-point error handling.
|
2752 |
+
|
2753 |
+
Using an instance of `errstate` as a context manager allows statements in
|
2754 |
+
that context to execute with a known error handling behavior. Upon entering
|
2755 |
+
the context the error handling is set with `seterr` and `seterrcall`, and
|
2756 |
+
upon exiting it is reset to what it was before.
|
2757 |
+
|
2758 |
+
Parameters
|
2759 |
+
----------
|
2760 |
+
kwargs : {divide, over, under, invalid}
|
2761 |
+
Keyword arguments. The valid keywords are the possible floating-point
|
2762 |
+
exceptions. Each keyword should have a string value that defines the
|
2763 |
+
treatment for the particular error. Possible values are
|
2764 |
+
{'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
|
2765 |
+
|
2766 |
+
See Also
|
2767 |
+
--------
|
2768 |
+
seterr, geterr, seterrcall, geterrcall
|
2769 |
+
|
2770 |
+
Notes
|
2771 |
+
-----
|
2772 |
+
The ``with`` statement was introduced in Python 2.5, and can only be used
|
2773 |
+
there by importing it: ``from __future__ import with_statement``. In
|
2774 |
+
earlier Python versions the ``with`` statement is not available.
|
2775 |
+
|
2776 |
+
For complete documentation of the types of floating-point exceptions and
|
2777 |
+
treatment options, see `seterr`.
|
2778 |
+
|
2779 |
+
Examples
|
2780 |
+
--------
|
2781 |
+
>>> from __future__ import with_statement # use 'with' in Python 2.5
|
2782 |
+
>>> olderr = np.seterr(all='ignore') # Set error handling to known state.
|
2783 |
+
|
2784 |
+
>>> np.arange(3) / 0.
|
2785 |
+
array([ NaN, Inf, Inf])
|
2786 |
+
>>> with np.errstate(divide='warn'):
|
2787 |
+
... np.arange(3) / 0.
|
2788 |
+
...
|
2789 |
+
__main__:2: RuntimeWarning: divide by zero encountered in divide
|
2790 |
+
array([ NaN, Inf, Inf])
|
2791 |
+
|
2792 |
+
>>> np.sqrt(-1)
|
2793 |
+
nan
|
2794 |
+
>>> with np.errstate(invalid='raise'):
|
2795 |
+
... np.sqrt(-1)
|
2796 |
+
Traceback (most recent call last):
|
2797 |
+
File "<stdin>", line 2, in <module>
|
2798 |
+
FloatingPointError: invalid value encountered in sqrt
|
2799 |
+
|
2800 |
+
Outside the context the error handling behavior has not changed:
|
2801 |
+
|
2802 |
+
>>> np.geterr()
|
2803 |
+
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn',
|
2804 |
+
'under': 'ignore'}
|
2805 |
+
|
2806 |
+
"""
|
2807 |
+
# Note that we don't want to run the above doctests because they will fail
|
2808 |
+
# without a from __future__ import with_statement
|
2809 |
+
def __init__(self, **kwargs):
|
2810 |
+
self.call = kwargs.pop('call', _Unspecified)
|
2811 |
+
self.kwargs = kwargs
|
2812 |
+
|
2813 |
+
def __enter__(self):
|
2814 |
+
self.oldstate = seterr(**self.kwargs)
|
2815 |
+
if self.call is not _Unspecified:
|
2816 |
+
self.oldcall = seterrcall(self.call)
|
2817 |
+
|
2818 |
+
def __exit__(self, *exc_info):
|
2819 |
+
seterr(**self.oldstate)
|
2820 |
+
if self.call is not _Unspecified:
|
2821 |
+
seterrcall(self.oldcall)
|
2822 |
+
|
2823 |
+
|
2824 |
+
def _setdef():
|
2825 |
+
defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT, None]
|
2826 |
+
umath.seterrobj(defval)
|
2827 |
+
|
2828 |
+
# set the default values
|
2829 |
+
_setdef()
|
2830 |
+
|
2831 |
+
Inf = inf = infty = Infinity = PINF
|
2832 |
+
nan = NaN = NAN
|
2833 |
+
False_ = bool_(False)
|
2834 |
+
True_ = bool_(True)
|
2835 |
+
|
2836 |
+
from .umath import *
|
2837 |
+
from .numerictypes import *
|
2838 |
+
from . import fromnumeric
|
2839 |
+
from .fromnumeric import *
|
2840 |
+
extend_all(fromnumeric)
|
2841 |
+
extend_all(umath)
|
2842 |
+
extend_all(numerictypes)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/numerictypes.py
ADDED
@@ -0,0 +1,1042 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
numerictypes: Define the numeric type objects
|
3 |
+
|
4 |
+
This module is designed so "from numerictypes import \\*" is safe.
|
5 |
+
Exported symbols include:
|
6 |
+
|
7 |
+
Dictionary with all registered number types (including aliases):
|
8 |
+
typeDict
|
9 |
+
|
10 |
+
Type objects (not all will be available, depends on platform):
|
11 |
+
see variable sctypes for which ones you have
|
12 |
+
|
13 |
+
Bit-width names
|
14 |
+
|
15 |
+
int8 int16 int32 int64 int128
|
16 |
+
uint8 uint16 uint32 uint64 uint128
|
17 |
+
float16 float32 float64 float96 float128 float256
|
18 |
+
complex32 complex64 complex128 complex192 complex256 complex512
|
19 |
+
datetime64 timedelta64
|
20 |
+
|
21 |
+
c-based names
|
22 |
+
|
23 |
+
bool_
|
24 |
+
|
25 |
+
object_
|
26 |
+
|
27 |
+
void, str_, unicode_
|
28 |
+
|
29 |
+
byte, ubyte,
|
30 |
+
short, ushort
|
31 |
+
intc, uintc,
|
32 |
+
intp, uintp,
|
33 |
+
int_, uint,
|
34 |
+
longlong, ulonglong,
|
35 |
+
|
36 |
+
single, csingle,
|
37 |
+
float_, complex_,
|
38 |
+
longfloat, clongfloat,
|
39 |
+
|
40 |
+
As part of the type-hierarchy: xx -- is bit-width
|
41 |
+
|
42 |
+
generic
|
43 |
+
+-> bool_ (kind=b)
|
44 |
+
+-> number (kind=i)
|
45 |
+
| integer
|
46 |
+
| signedinteger (intxx)
|
47 |
+
| byte
|
48 |
+
| short
|
49 |
+
| intc
|
50 |
+
| intp int0
|
51 |
+
| int_
|
52 |
+
| longlong
|
53 |
+
+-> unsignedinteger (uintxx) (kind=u)
|
54 |
+
| ubyte
|
55 |
+
| ushort
|
56 |
+
| uintc
|
57 |
+
| uintp uint0
|
58 |
+
| uint_
|
59 |
+
| ulonglong
|
60 |
+
+-> inexact
|
61 |
+
| +-> floating (floatxx) (kind=f)
|
62 |
+
| | half
|
63 |
+
| | single
|
64 |
+
| | float_ (double)
|
65 |
+
| | longfloat
|
66 |
+
| \\-> complexfloating (complexxx) (kind=c)
|
67 |
+
| csingle (singlecomplex)
|
68 |
+
| complex_ (cfloat, cdouble)
|
69 |
+
| clongfloat (longcomplex)
|
70 |
+
+-> flexible
|
71 |
+
| character
|
72 |
+
| void (kind=V)
|
73 |
+
|
|
74 |
+
| str_ (string_, bytes_) (kind=S) [Python 2]
|
75 |
+
| unicode_ (kind=U) [Python 2]
|
76 |
+
|
|
77 |
+
| bytes_ (string_) (kind=S) [Python 3]
|
78 |
+
| str_ (unicode_) (kind=U) [Python 3]
|
79 |
+
|
|
80 |
+
\\-> object_ (not used much) (kind=O)
|
81 |
+
|
82 |
+
"""
|
83 |
+
from __future__ import division, absolute_import, print_function
|
84 |
+
|
85 |
+
# we add more at the bottom
|
86 |
+
__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes',
|
87 |
+
'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char',
|
88 |
+
'maximum_sctype', 'issctype', 'typecodes', 'find_common_type',
|
89 |
+
'issubdtype', 'datetime_data', 'datetime_as_string',
|
90 |
+
'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar',
|
91 |
+
]
|
92 |
+
|
93 |
+
from numpy.core.multiarray import (
|
94 |
+
typeinfo, ndarray, array, empty, dtype, datetime_data,
|
95 |
+
datetime_as_string, busday_offset, busday_count, is_busday,
|
96 |
+
busdaycalendar
|
97 |
+
)
|
98 |
+
import types as _types
|
99 |
+
import sys
|
100 |
+
from numpy.compat import bytes, long
|
101 |
+
import numbers
|
102 |
+
|
103 |
+
# we don't export these for import *, but we do want them accessible
|
104 |
+
# as numerictypes.bool, etc.
|
105 |
+
if sys.version_info[0] >= 3:
|
106 |
+
from builtins import bool, int, float, complex, object, str
|
107 |
+
unicode = str
|
108 |
+
else:
|
109 |
+
from __builtin__ import bool, int, float, complex, object, unicode, str
|
110 |
+
|
111 |
+
|
112 |
+
# String-handling utilities to avoid locale-dependence.
|
113 |
+
|
114 |
+
# "import string" is costly to import!
|
115 |
+
# Construct the translation tables directly
|
116 |
+
# "A" = chr(65), "a" = chr(97)
|
117 |
+
_all_chars = [chr(_m) for _m in range(256)]
|
118 |
+
_ascii_upper = _all_chars[65:65+26]
|
119 |
+
_ascii_lower = _all_chars[97:97+26]
|
120 |
+
LOWER_TABLE="".join(_all_chars[:65] + _ascii_lower + _all_chars[65+26:])
|
121 |
+
UPPER_TABLE="".join(_all_chars[:97] + _ascii_upper + _all_chars[97+26:])
|
122 |
+
|
123 |
+
#import string
|
124 |
+
# assert (string.maketrans(string.ascii_uppercase, string.ascii_lowercase) == \
|
125 |
+
# LOWER_TABLE)
|
126 |
+
# assert (string.maketrnas(string_ascii_lowercase, string.ascii_uppercase) == \
|
127 |
+
# UPPER_TABLE)
|
128 |
+
#LOWER_TABLE = string.maketrans(string.ascii_uppercase, string.ascii_lowercase)
|
129 |
+
#UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase)
|
130 |
+
|
131 |
+
def english_lower(s):
|
132 |
+
""" Apply English case rules to convert ASCII strings to all lower case.
|
133 |
+
|
134 |
+
This is an internal utility function to replace calls to str.lower() such
|
135 |
+
that we can avoid changing behavior with changing locales. In particular,
|
136 |
+
Turkish has distinct dotted and dotless variants of the Latin letter "I" in
|
137 |
+
both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale.
|
138 |
+
|
139 |
+
Parameters
|
140 |
+
----------
|
141 |
+
s : str
|
142 |
+
|
143 |
+
Returns
|
144 |
+
-------
|
145 |
+
lowered : str
|
146 |
+
|
147 |
+
Examples
|
148 |
+
--------
|
149 |
+
>>> from numpy.core.numerictypes import english_lower
|
150 |
+
>>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
|
151 |
+
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'
|
152 |
+
>>> english_lower('')
|
153 |
+
''
|
154 |
+
"""
|
155 |
+
lowered = s.translate(LOWER_TABLE)
|
156 |
+
return lowered
|
157 |
+
|
158 |
+
def english_upper(s):
|
159 |
+
""" Apply English case rules to convert ASCII strings to all upper case.
|
160 |
+
|
161 |
+
This is an internal utility function to replace calls to str.upper() such
|
162 |
+
that we can avoid changing behavior with changing locales. In particular,
|
163 |
+
Turkish has distinct dotted and dotless variants of the Latin letter "I" in
|
164 |
+
both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale.
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
----------
|
168 |
+
s : str
|
169 |
+
|
170 |
+
Returns
|
171 |
+
-------
|
172 |
+
uppered : str
|
173 |
+
|
174 |
+
Examples
|
175 |
+
--------
|
176 |
+
>>> from numpy.core.numerictypes import english_upper
|
177 |
+
>>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
|
178 |
+
'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
|
179 |
+
>>> english_upper('')
|
180 |
+
''
|
181 |
+
"""
|
182 |
+
uppered = s.translate(UPPER_TABLE)
|
183 |
+
return uppered
|
184 |
+
|
185 |
+
def english_capitalize(s):
|
186 |
+
""" Apply English case rules to convert the first character of an ASCII
|
187 |
+
string to upper case.
|
188 |
+
|
189 |
+
This is an internal utility function to replace calls to str.capitalize()
|
190 |
+
such that we can avoid changing behavior with changing locales.
|
191 |
+
|
192 |
+
Parameters
|
193 |
+
----------
|
194 |
+
s : str
|
195 |
+
|
196 |
+
Returns
|
197 |
+
-------
|
198 |
+
capitalized : str
|
199 |
+
|
200 |
+
Examples
|
201 |
+
--------
|
202 |
+
>>> from numpy.core.numerictypes import english_capitalize
|
203 |
+
>>> english_capitalize('int8')
|
204 |
+
'Int8'
|
205 |
+
>>> english_capitalize('Int8')
|
206 |
+
'Int8'
|
207 |
+
>>> english_capitalize('')
|
208 |
+
''
|
209 |
+
"""
|
210 |
+
if s:
|
211 |
+
return english_upper(s[0]) + s[1:]
|
212 |
+
else:
|
213 |
+
return s
|
214 |
+
|
215 |
+
|
216 |
+
sctypeDict = {} # Contains all leaf-node scalar types with aliases
|
217 |
+
sctypeNA = {} # Contails all leaf-node types -> numarray type equivalences
|
218 |
+
allTypes = {} # Collect the types we will add to the module here
|
219 |
+
|
220 |
+
def _evalname(name):
|
221 |
+
k = 0
|
222 |
+
for ch in name:
|
223 |
+
if ch in '0123456789':
|
224 |
+
break
|
225 |
+
k += 1
|
226 |
+
try:
|
227 |
+
bits = int(name[k:])
|
228 |
+
except ValueError:
|
229 |
+
bits = 0
|
230 |
+
base = name[:k]
|
231 |
+
return base, bits
|
232 |
+
|
233 |
+
def bitname(obj):
|
234 |
+
"""Return a bit-width name for a given type object"""
|
235 |
+
name = obj.__name__
|
236 |
+
base = ''
|
237 |
+
char = ''
|
238 |
+
try:
|
239 |
+
if name[-1] == '_':
|
240 |
+
newname = name[:-1]
|
241 |
+
else:
|
242 |
+
newname = name
|
243 |
+
info = typeinfo[english_upper(newname)]
|
244 |
+
assert(info[-1] == obj) # sanity check
|
245 |
+
bits = info[2]
|
246 |
+
|
247 |
+
except KeyError: # bit-width name
|
248 |
+
base, bits = _evalname(name)
|
249 |
+
char = base[0]
|
250 |
+
|
251 |
+
if name == 'bool_':
|
252 |
+
char = 'b'
|
253 |
+
base = 'bool'
|
254 |
+
elif name=='void':
|
255 |
+
char = 'V'
|
256 |
+
base = 'void'
|
257 |
+
elif name=='object_':
|
258 |
+
char = 'O'
|
259 |
+
base = 'object'
|
260 |
+
bits = 0
|
261 |
+
elif name=='datetime64':
|
262 |
+
char = 'M'
|
263 |
+
elif name=='timedelta64':
|
264 |
+
char = 'm'
|
265 |
+
|
266 |
+
if sys.version_info[0] >= 3:
|
267 |
+
if name=='bytes_':
|
268 |
+
char = 'S'
|
269 |
+
base = 'bytes'
|
270 |
+
elif name=='str_':
|
271 |
+
char = 'U'
|
272 |
+
base = 'str'
|
273 |
+
else:
|
274 |
+
if name=='string_':
|
275 |
+
char = 'S'
|
276 |
+
base = 'string'
|
277 |
+
elif name=='unicode_':
|
278 |
+
char = 'U'
|
279 |
+
base = 'unicode'
|
280 |
+
|
281 |
+
bytes = bits // 8
|
282 |
+
|
283 |
+
if char != '' and bytes != 0:
|
284 |
+
char = "%s%d" % (char, bytes)
|
285 |
+
|
286 |
+
return base, bits, char
|
287 |
+
|
288 |
+
|
289 |
+
def _add_types():
|
290 |
+
for a in typeinfo.keys():
|
291 |
+
name = english_lower(a)
|
292 |
+
if isinstance(typeinfo[a], tuple):
|
293 |
+
typeobj = typeinfo[a][-1]
|
294 |
+
|
295 |
+
# define C-name and insert typenum and typechar references also
|
296 |
+
allTypes[name] = typeobj
|
297 |
+
sctypeDict[name] = typeobj
|
298 |
+
sctypeDict[typeinfo[a][0]] = typeobj
|
299 |
+
sctypeDict[typeinfo[a][1]] = typeobj
|
300 |
+
|
301 |
+
else: # generic class
|
302 |
+
allTypes[name] = typeinfo[a]
|
303 |
+
_add_types()
|
304 |
+
|
305 |
+
def _add_aliases():
|
306 |
+
for a in typeinfo.keys():
|
307 |
+
name = english_lower(a)
|
308 |
+
if not isinstance(typeinfo[a], tuple):
|
309 |
+
continue
|
310 |
+
typeobj = typeinfo[a][-1]
|
311 |
+
# insert bit-width version for this class (if relevant)
|
312 |
+
base, bit, char = bitname(typeobj)
|
313 |
+
if base[-3:] == 'int' or char[0] in 'ui': continue
|
314 |
+
if base != '':
|
315 |
+
myname = "%s%d" % (base, bit)
|
316 |
+
if (name != 'longdouble' and name != 'clongdouble') or \
|
317 |
+
myname not in allTypes.keys():
|
318 |
+
allTypes[myname] = typeobj
|
319 |
+
sctypeDict[myname] = typeobj
|
320 |
+
if base == 'complex':
|
321 |
+
na_name = '%s%d' % (english_capitalize(base), bit//2)
|
322 |
+
elif base == 'bool':
|
323 |
+
na_name = english_capitalize(base)
|
324 |
+
sctypeDict[na_name] = typeobj
|
325 |
+
else:
|
326 |
+
na_name = "%s%d" % (english_capitalize(base), bit)
|
327 |
+
sctypeDict[na_name] = typeobj
|
328 |
+
sctypeNA[na_name] = typeobj
|
329 |
+
sctypeDict[na_name] = typeobj
|
330 |
+
sctypeNA[typeobj] = na_name
|
331 |
+
sctypeNA[typeinfo[a][0]] = na_name
|
332 |
+
if char != '':
|
333 |
+
sctypeDict[char] = typeobj
|
334 |
+
sctypeNA[char] = na_name
|
335 |
+
_add_aliases()
|
336 |
+
|
337 |
+
# Integers handled so that
|
338 |
+
# The int32, int64 types should agree exactly with
|
339 |
+
# PyArray_INT32, PyArray_INT64 in C
|
340 |
+
# We need to enforce the same checking as is done
|
341 |
+
# in arrayobject.h where the order of getting a
|
342 |
+
# bit-width match is:
|
343 |
+
# long, longlong, int, short, char
|
344 |
+
# for int8, int16, int32, int64, int128
|
345 |
+
|
346 |
+
def _add_integer_aliases():
|
347 |
+
_ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE']
|
348 |
+
for ctype in _ctypes:
|
349 |
+
val = typeinfo[ctype]
|
350 |
+
bits = val[2]
|
351 |
+
charname = 'i%d' % (bits//8,)
|
352 |
+
ucharname = 'u%d' % (bits//8,)
|
353 |
+
intname = 'int%d' % bits
|
354 |
+
UIntname = 'UInt%d' % bits
|
355 |
+
Intname = 'Int%d' % bits
|
356 |
+
uval = typeinfo['U'+ctype]
|
357 |
+
typeobj = val[-1]
|
358 |
+
utypeobj = uval[-1]
|
359 |
+
if intname not in allTypes.keys():
|
360 |
+
uintname = 'uint%d' % bits
|
361 |
+
allTypes[intname] = typeobj
|
362 |
+
allTypes[uintname] = utypeobj
|
363 |
+
sctypeDict[intname] = typeobj
|
364 |
+
sctypeDict[uintname] = utypeobj
|
365 |
+
sctypeDict[Intname] = typeobj
|
366 |
+
sctypeDict[UIntname] = utypeobj
|
367 |
+
sctypeDict[charname] = typeobj
|
368 |
+
sctypeDict[ucharname] = utypeobj
|
369 |
+
sctypeNA[Intname] = typeobj
|
370 |
+
sctypeNA[UIntname] = utypeobj
|
371 |
+
sctypeNA[charname] = typeobj
|
372 |
+
sctypeNA[ucharname] = utypeobj
|
373 |
+
sctypeNA[typeobj] = Intname
|
374 |
+
sctypeNA[utypeobj] = UIntname
|
375 |
+
sctypeNA[val[0]] = Intname
|
376 |
+
sctypeNA[uval[0]] = UIntname
|
377 |
+
_add_integer_aliases()
|
378 |
+
|
379 |
+
# We use these later
|
380 |
+
void = allTypes['void']
|
381 |
+
generic = allTypes['generic']
|
382 |
+
|
383 |
+
#
|
384 |
+
# Rework the Python names (so that float and complex and int are consistent
|
385 |
+
# with Python usage)
|
386 |
+
#
|
387 |
+
def _set_up_aliases():
|
388 |
+
type_pairs = [('complex_', 'cdouble'),
|
389 |
+
('int0', 'intp'),
|
390 |
+
('uint0', 'uintp'),
|
391 |
+
('single', 'float'),
|
392 |
+
('csingle', 'cfloat'),
|
393 |
+
('singlecomplex', 'cfloat'),
|
394 |
+
('float_', 'double'),
|
395 |
+
('intc', 'int'),
|
396 |
+
('uintc', 'uint'),
|
397 |
+
('int_', 'long'),
|
398 |
+
('uint', 'ulong'),
|
399 |
+
('cfloat', 'cdouble'),
|
400 |
+
('longfloat', 'longdouble'),
|
401 |
+
('clongfloat', 'clongdouble'),
|
402 |
+
('longcomplex', 'clongdouble'),
|
403 |
+
('bool_', 'bool'),
|
404 |
+
('unicode_', 'unicode'),
|
405 |
+
('object_', 'object')]
|
406 |
+
if sys.version_info[0] >= 3:
|
407 |
+
type_pairs.extend([('bytes_', 'string'),
|
408 |
+
('str_', 'unicode'),
|
409 |
+
('string_', 'string')])
|
410 |
+
else:
|
411 |
+
type_pairs.extend([('str_', 'string'),
|
412 |
+
('string_', 'string'),
|
413 |
+
('bytes_', 'string')])
|
414 |
+
for alias, t in type_pairs:
|
415 |
+
allTypes[alias] = allTypes[t]
|
416 |
+
sctypeDict[alias] = sctypeDict[t]
|
417 |
+
# Remove aliases overriding python types and modules
|
418 |
+
to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',
|
419 |
+
'complex', 'bool', 'string', 'datetime', 'timedelta']
|
420 |
+
if sys.version_info[0] >= 3:
|
421 |
+
# Py3K
|
422 |
+
to_remove.append('bytes')
|
423 |
+
to_remove.append('str')
|
424 |
+
to_remove.remove('unicode')
|
425 |
+
to_remove.remove('long')
|
426 |
+
for t in to_remove:
|
427 |
+
try:
|
428 |
+
del allTypes[t]
|
429 |
+
del sctypeDict[t]
|
430 |
+
except KeyError:
|
431 |
+
pass
|
432 |
+
_set_up_aliases()
|
433 |
+
|
434 |
+
# Now, construct dictionary to lookup character codes from types
|
435 |
+
_sctype2char_dict = {}
|
436 |
+
def _construct_char_code_lookup():
|
437 |
+
for name in typeinfo.keys():
|
438 |
+
tup = typeinfo[name]
|
439 |
+
if isinstance(tup, tuple):
|
440 |
+
if tup[0] not in ['p', 'P']:
|
441 |
+
_sctype2char_dict[tup[-1]] = tup[0]
|
442 |
+
_construct_char_code_lookup()
|
443 |
+
|
444 |
+
|
445 |
+
sctypes = {'int': [],
|
446 |
+
'uint':[],
|
447 |
+
'float':[],
|
448 |
+
'complex':[],
|
449 |
+
'others':[bool, object, str, unicode, void]}
|
450 |
+
|
451 |
+
def _add_array_type(typename, bits):
|
452 |
+
try:
|
453 |
+
t = allTypes['%s%d' % (typename, bits)]
|
454 |
+
except KeyError:
|
455 |
+
pass
|
456 |
+
else:
|
457 |
+
sctypes[typename].append(t)
|
458 |
+
|
459 |
+
def _set_array_types():
|
460 |
+
ibytes = [1, 2, 4, 8, 16, 32, 64]
|
461 |
+
fbytes = [2, 4, 8, 10, 12, 16, 32, 64]
|
462 |
+
for bytes in ibytes:
|
463 |
+
bits = 8*bytes
|
464 |
+
_add_array_type('int', bits)
|
465 |
+
_add_array_type('uint', bits)
|
466 |
+
for bytes in fbytes:
|
467 |
+
bits = 8*bytes
|
468 |
+
_add_array_type('float', bits)
|
469 |
+
_add_array_type('complex', 2*bits)
|
470 |
+
_gi = dtype('p')
|
471 |
+
if _gi.type not in sctypes['int']:
|
472 |
+
indx = 0
|
473 |
+
sz = _gi.itemsize
|
474 |
+
_lst = sctypes['int']
|
475 |
+
while (indx < len(_lst) and sz >= _lst[indx](0).itemsize):
|
476 |
+
indx += 1
|
477 |
+
sctypes['int'].insert(indx, _gi.type)
|
478 |
+
sctypes['uint'].insert(indx, dtype('P').type)
|
479 |
+
_set_array_types()
|
480 |
+
|
481 |
+
|
482 |
+
genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
|
483 |
+
'int32', 'uint32', 'int64', 'uint64', 'int128',
|
484 |
+
'uint128', 'float16',
|
485 |
+
'float32', 'float64', 'float80', 'float96', 'float128',
|
486 |
+
'float256',
|
487 |
+
'complex32', 'complex64', 'complex128', 'complex160',
|
488 |
+
'complex192', 'complex256', 'complex512', 'object']
|
489 |
+
|
490 |
+
def maximum_sctype(t):
|
491 |
+
"""
|
492 |
+
Return the scalar type of highest precision of the same kind as the input.
|
493 |
+
|
494 |
+
Parameters
|
495 |
+
----------
|
496 |
+
t : dtype or dtype specifier
|
497 |
+
The input data type. This can be a `dtype` object or an object that
|
498 |
+
is convertible to a `dtype`.
|
499 |
+
|
500 |
+
Returns
|
501 |
+
-------
|
502 |
+
out : dtype
|
503 |
+
The highest precision data type of the same kind (`dtype.kind`) as `t`.
|
504 |
+
|
505 |
+
See Also
|
506 |
+
--------
|
507 |
+
obj2sctype, mintypecode, sctype2char
|
508 |
+
dtype
|
509 |
+
|
510 |
+
Examples
|
511 |
+
--------
|
512 |
+
>>> np.maximum_sctype(np.int)
|
513 |
+
<type 'numpy.int64'>
|
514 |
+
>>> np.maximum_sctype(np.uint8)
|
515 |
+
<type 'numpy.uint64'>
|
516 |
+
>>> np.maximum_sctype(np.complex)
|
517 |
+
<type 'numpy.complex192'>
|
518 |
+
|
519 |
+
>>> np.maximum_sctype(str)
|
520 |
+
<type 'numpy.string_'>
|
521 |
+
|
522 |
+
>>> np.maximum_sctype('i2')
|
523 |
+
<type 'numpy.int64'>
|
524 |
+
>>> np.maximum_sctype('f4')
|
525 |
+
<type 'numpy.float96'>
|
526 |
+
|
527 |
+
"""
|
528 |
+
g = obj2sctype(t)
|
529 |
+
if g is None:
|
530 |
+
return t
|
531 |
+
t = g
|
532 |
+
name = t.__name__
|
533 |
+
base, bits = _evalname(name)
|
534 |
+
if bits == 0:
|
535 |
+
return t
|
536 |
+
else:
|
537 |
+
return sctypes[base][-1]
|
538 |
+
|
539 |
+
try:
|
540 |
+
buffer_type = _types.BufferType
|
541 |
+
except AttributeError:
|
542 |
+
# Py3K
|
543 |
+
buffer_type = memoryview
|
544 |
+
|
545 |
+
_python_types = {int: 'int_',
|
546 |
+
float: 'float_',
|
547 |
+
complex: 'complex_',
|
548 |
+
bool: 'bool_',
|
549 |
+
bytes: 'bytes_',
|
550 |
+
unicode: 'unicode_',
|
551 |
+
buffer_type: 'void',
|
552 |
+
}
|
553 |
+
|
554 |
+
if sys.version_info[0] >= 3:
|
555 |
+
def _python_type(t):
|
556 |
+
"""returns the type corresponding to a certain Python type"""
|
557 |
+
if not isinstance(t, type):
|
558 |
+
t = type(t)
|
559 |
+
return allTypes[_python_types.get(t, 'object_')]
|
560 |
+
else:
|
561 |
+
def _python_type(t):
|
562 |
+
"""returns the type corresponding to a certain Python type"""
|
563 |
+
if not isinstance(t, _types.TypeType):
|
564 |
+
t = type(t)
|
565 |
+
return allTypes[_python_types.get(t, 'object_')]
|
566 |
+
|
567 |
+
def issctype(rep):
|
568 |
+
"""
|
569 |
+
Determines whether the given object represents a scalar data-type.
|
570 |
+
|
571 |
+
Parameters
|
572 |
+
----------
|
573 |
+
rep : any
|
574 |
+
If `rep` is an instance of a scalar dtype, True is returned. If not,
|
575 |
+
False is returned.
|
576 |
+
|
577 |
+
Returns
|
578 |
+
-------
|
579 |
+
out : bool
|
580 |
+
Boolean result of check whether `rep` is a scalar dtype.
|
581 |
+
|
582 |
+
See Also
|
583 |
+
--------
|
584 |
+
issubsctype, issubdtype, obj2sctype, sctype2char
|
585 |
+
|
586 |
+
Examples
|
587 |
+
--------
|
588 |
+
>>> np.issctype(np.int32)
|
589 |
+
True
|
590 |
+
>>> np.issctype(list)
|
591 |
+
False
|
592 |
+
>>> np.issctype(1.1)
|
593 |
+
False
|
594 |
+
|
595 |
+
Strings are also a scalar type:
|
596 |
+
|
597 |
+
>>> np.issctype(np.dtype('str'))
|
598 |
+
True
|
599 |
+
|
600 |
+
"""
|
601 |
+
if not isinstance(rep, (type, dtype)):
|
602 |
+
return False
|
603 |
+
try:
|
604 |
+
res = obj2sctype(rep)
|
605 |
+
if res and res != object_:
|
606 |
+
return True
|
607 |
+
return False
|
608 |
+
except:
|
609 |
+
return False
|
610 |
+
|
611 |
+
def obj2sctype(rep, default=None):
|
612 |
+
"""
|
613 |
+
Return the scalar dtype or NumPy equivalent of Python type of an object.
|
614 |
+
|
615 |
+
Parameters
|
616 |
+
----------
|
617 |
+
rep : any
|
618 |
+
The object of which the type is returned.
|
619 |
+
default : any, optional
|
620 |
+
If given, this is returned for objects whose types can not be
|
621 |
+
determined. If not given, None is returned for those objects.
|
622 |
+
|
623 |
+
Returns
|
624 |
+
-------
|
625 |
+
dtype : dtype or Python type
|
626 |
+
The data type of `rep`.
|
627 |
+
|
628 |
+
See Also
|
629 |
+
--------
|
630 |
+
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
|
631 |
+
|
632 |
+
Examples
|
633 |
+
--------
|
634 |
+
>>> np.obj2sctype(np.int32)
|
635 |
+
<type 'numpy.int32'>
|
636 |
+
>>> np.obj2sctype(np.array([1., 2.]))
|
637 |
+
<type 'numpy.float64'>
|
638 |
+
>>> np.obj2sctype(np.array([1.j]))
|
639 |
+
<type 'numpy.complex128'>
|
640 |
+
|
641 |
+
>>> np.obj2sctype(dict)
|
642 |
+
<type 'numpy.object_'>
|
643 |
+
>>> np.obj2sctype('string')
|
644 |
+
<type 'numpy.string_'>
|
645 |
+
|
646 |
+
>>> np.obj2sctype(1, default=list)
|
647 |
+
<type 'list'>
|
648 |
+
|
649 |
+
"""
|
650 |
+
try:
|
651 |
+
if issubclass(rep, generic):
|
652 |
+
return rep
|
653 |
+
except TypeError:
|
654 |
+
pass
|
655 |
+
if isinstance(rep, dtype):
|
656 |
+
return rep.type
|
657 |
+
if isinstance(rep, type):
|
658 |
+
return _python_type(rep)
|
659 |
+
if isinstance(rep, ndarray):
|
660 |
+
return rep.dtype.type
|
661 |
+
try:
|
662 |
+
res = dtype(rep)
|
663 |
+
except:
|
664 |
+
return default
|
665 |
+
return res.type
|
666 |
+
|
667 |
+
|
668 |
+
def issubclass_(arg1, arg2):
|
669 |
+
"""
|
670 |
+
Determine if a class is a subclass of a second class.
|
671 |
+
|
672 |
+
`issubclass_` is equivalent to the Python built-in ``issubclass``,
|
673 |
+
except that it returns False instead of raising a TypeError is one
|
674 |
+
of the arguments is not a class.
|
675 |
+
|
676 |
+
Parameters
|
677 |
+
----------
|
678 |
+
arg1 : class
|
679 |
+
Input class. True is returned if `arg1` is a subclass of `arg2`.
|
680 |
+
arg2 : class or tuple of classes.
|
681 |
+
Input class. If a tuple of classes, True is returned if `arg1` is a
|
682 |
+
subclass of any of the tuple elements.
|
683 |
+
|
684 |
+
Returns
|
685 |
+
-------
|
686 |
+
out : bool
|
687 |
+
Whether `arg1` is a subclass of `arg2` or not.
|
688 |
+
|
689 |
+
See Also
|
690 |
+
--------
|
691 |
+
issubsctype, issubdtype, issctype
|
692 |
+
|
693 |
+
Examples
|
694 |
+
--------
|
695 |
+
>>> np.issubclass_(np.int32, np.int)
|
696 |
+
True
|
697 |
+
>>> np.issubclass_(np.int32, np.float)
|
698 |
+
False
|
699 |
+
|
700 |
+
"""
|
701 |
+
try:
|
702 |
+
return issubclass(arg1, arg2)
|
703 |
+
except TypeError:
|
704 |
+
return False
|
705 |
+
|
706 |
+
def issubsctype(arg1, arg2):
|
707 |
+
"""
|
708 |
+
Determine if the first argument is a subclass of the second argument.
|
709 |
+
|
710 |
+
Parameters
|
711 |
+
----------
|
712 |
+
arg1, arg2 : dtype or dtype specifier
|
713 |
+
Data-types.
|
714 |
+
|
715 |
+
Returns
|
716 |
+
-------
|
717 |
+
out : bool
|
718 |
+
The result.
|
719 |
+
|
720 |
+
See Also
|
721 |
+
--------
|
722 |
+
issctype, issubdtype,obj2sctype
|
723 |
+
|
724 |
+
Examples
|
725 |
+
--------
|
726 |
+
>>> np.issubsctype('S8', str)
|
727 |
+
True
|
728 |
+
>>> np.issubsctype(np.array([1]), np.int)
|
729 |
+
True
|
730 |
+
>>> np.issubsctype(np.array([1]), np.float)
|
731 |
+
False
|
732 |
+
|
733 |
+
"""
|
734 |
+
return issubclass(obj2sctype(arg1), obj2sctype(arg2))
|
735 |
+
|
736 |
+
def issubdtype(arg1, arg2):
|
737 |
+
"""
|
738 |
+
Returns True if first argument is a typecode lower/equal in type hierarchy.
|
739 |
+
|
740 |
+
Parameters
|
741 |
+
----------
|
742 |
+
arg1, arg2 : dtype_like
|
743 |
+
dtype or string representing a typecode.
|
744 |
+
|
745 |
+
Returns
|
746 |
+
-------
|
747 |
+
out : bool
|
748 |
+
|
749 |
+
See Also
|
750 |
+
--------
|
751 |
+
issubsctype, issubclass_
|
752 |
+
numpy.core.numerictypes : Overview of numpy type hierarchy.
|
753 |
+
|
754 |
+
Examples
|
755 |
+
--------
|
756 |
+
>>> np.issubdtype('S1', str)
|
757 |
+
True
|
758 |
+
>>> np.issubdtype(np.float64, np.float32)
|
759 |
+
False
|
760 |
+
|
761 |
+
"""
|
762 |
+
if issubclass_(arg2, generic):
|
763 |
+
return issubclass(dtype(arg1).type, arg2)
|
764 |
+
mro = dtype(arg2).type.mro()
|
765 |
+
if len(mro) > 1:
|
766 |
+
val = mro[1]
|
767 |
+
else:
|
768 |
+
val = mro[0]
|
769 |
+
return issubclass(dtype(arg1).type, val)
|
770 |
+
|
771 |
+
|
772 |
+
# This dictionary allows look up based on any alias for an array data-type
|
773 |
+
class _typedict(dict):
|
774 |
+
"""
|
775 |
+
Base object for a dictionary for look-up with any alias for an array dtype.
|
776 |
+
|
777 |
+
Instances of `_typedict` can not be used as dictionaries directly,
|
778 |
+
first they have to be populated.
|
779 |
+
|
780 |
+
"""
|
781 |
+
def __getitem__(self, obj):
|
782 |
+
return dict.__getitem__(self, obj2sctype(obj))
|
783 |
+
|
784 |
+
nbytes = _typedict()
|
785 |
+
_alignment = _typedict()
|
786 |
+
_maxvals = _typedict()
|
787 |
+
_minvals = _typedict()
|
788 |
+
def _construct_lookups():
|
789 |
+
for name, val in typeinfo.items():
|
790 |
+
if not isinstance(val, tuple):
|
791 |
+
continue
|
792 |
+
obj = val[-1]
|
793 |
+
nbytes[obj] = val[2] // 8
|
794 |
+
_alignment[obj] = val[3]
|
795 |
+
if (len(val) > 5):
|
796 |
+
_maxvals[obj] = val[4]
|
797 |
+
_minvals[obj] = val[5]
|
798 |
+
else:
|
799 |
+
_maxvals[obj] = None
|
800 |
+
_minvals[obj] = None
|
801 |
+
|
802 |
+
_construct_lookups()
|
803 |
+
|
804 |
+
def sctype2char(sctype):
|
805 |
+
"""
|
806 |
+
Return the string representation of a scalar dtype.
|
807 |
+
|
808 |
+
Parameters
|
809 |
+
----------
|
810 |
+
sctype : scalar dtype or object
|
811 |
+
If a scalar dtype, the corresponding string character is
|
812 |
+
returned. If an object, `sctype2char` tries to infer its scalar type
|
813 |
+
and then return the corresponding string character.
|
814 |
+
|
815 |
+
Returns
|
816 |
+
-------
|
817 |
+
typechar : str
|
818 |
+
The string character corresponding to the scalar type.
|
819 |
+
|
820 |
+
Raises
|
821 |
+
------
|
822 |
+
ValueError
|
823 |
+
If `sctype` is an object for which the type can not be inferred.
|
824 |
+
|
825 |
+
See Also
|
826 |
+
--------
|
827 |
+
obj2sctype, issctype, issubsctype, mintypecode
|
828 |
+
|
829 |
+
Examples
|
830 |
+
--------
|
831 |
+
>>> for sctype in [np.int32, np.float, np.complex, np.string_, np.ndarray]:
|
832 |
+
... print np.sctype2char(sctype)
|
833 |
+
l
|
834 |
+
d
|
835 |
+
D
|
836 |
+
S
|
837 |
+
O
|
838 |
+
|
839 |
+
>>> x = np.array([1., 2-1.j])
|
840 |
+
>>> np.sctype2char(x)
|
841 |
+
'D'
|
842 |
+
>>> np.sctype2char(list)
|
843 |
+
'O'
|
844 |
+
|
845 |
+
"""
|
846 |
+
sctype = obj2sctype(sctype)
|
847 |
+
if sctype is None:
|
848 |
+
raise ValueError("unrecognized type")
|
849 |
+
return _sctype2char_dict[sctype]
|
850 |
+
|
851 |
+
# Create dictionary of casting functions that wrap sequences
|
852 |
+
# indexed by type or type character
|
853 |
+
|
854 |
+
|
855 |
+
cast = _typedict()
|
856 |
+
try:
|
857 |
+
ScalarType = [_types.IntType, _types.FloatType, _types.ComplexType,
|
858 |
+
_types.LongType, _types.BooleanType,
|
859 |
+
_types.StringType, _types.UnicodeType, _types.BufferType]
|
860 |
+
except AttributeError:
|
861 |
+
# Py3K
|
862 |
+
ScalarType = [int, float, complex, int, bool, bytes, str, memoryview]
|
863 |
+
|
864 |
+
ScalarType.extend(_sctype2char_dict.keys())
|
865 |
+
ScalarType = tuple(ScalarType)
|
866 |
+
for key in _sctype2char_dict.keys():
|
867 |
+
cast[key] = lambda x, k=key : array(x, copy=False).astype(k)
|
868 |
+
|
869 |
+
# Create the typestring lookup dictionary
|
870 |
+
_typestr = _typedict()
|
871 |
+
for key in _sctype2char_dict.keys():
|
872 |
+
if issubclass(key, allTypes['flexible']):
|
873 |
+
_typestr[key] = _sctype2char_dict[key]
|
874 |
+
else:
|
875 |
+
_typestr[key] = empty((1,), key).dtype.str[1:]
|
876 |
+
|
877 |
+
# Make sure all typestrings are in sctypeDict
|
878 |
+
for key, val in _typestr.items():
|
879 |
+
if val not in sctypeDict:
|
880 |
+
sctypeDict[val] = key
|
881 |
+
|
882 |
+
# Add additional strings to the sctypeDict
|
883 |
+
|
884 |
+
if sys.version_info[0] >= 3:
|
885 |
+
_toadd = ['int', 'float', 'complex', 'bool', 'object',
|
886 |
+
'str', 'bytes', 'object', ('a', allTypes['bytes_'])]
|
887 |
+
else:
|
888 |
+
_toadd = ['int', 'float', 'complex', 'bool', 'object', 'string',
|
889 |
+
('str', allTypes['string_']),
|
890 |
+
'unicode', 'object', ('a', allTypes['string_'])]
|
891 |
+
|
892 |
+
for name in _toadd:
|
893 |
+
if isinstance(name, tuple):
|
894 |
+
sctypeDict[name[0]] = name[1]
|
895 |
+
else:
|
896 |
+
sctypeDict[name] = allTypes['%s_' % name]
|
897 |
+
|
898 |
+
del _toadd, name
|
899 |
+
|
900 |
+
# Now add the types we've determined to this module
|
901 |
+
for key in allTypes:
|
902 |
+
globals()[key] = allTypes[key]
|
903 |
+
__all__.append(key)
|
904 |
+
|
905 |
+
del key
|
906 |
+
|
907 |
+
typecodes = {'Character':'c',
|
908 |
+
'Integer':'bhilqp',
|
909 |
+
'UnsignedInteger':'BHILQP',
|
910 |
+
'Float':'efdg',
|
911 |
+
'Complex':'FDG',
|
912 |
+
'AllInteger':'bBhHiIlLqQpP',
|
913 |
+
'AllFloat':'efdgFDG',
|
914 |
+
'Datetime': 'Mm',
|
915 |
+
'All':'?bhilqpBHILQPefdgFDGSUVOMm'}
|
916 |
+
|
917 |
+
# backwards compatibility --- deprecated name
|
918 |
+
typeDict = sctypeDict
|
919 |
+
typeNA = sctypeNA
|
920 |
+
|
921 |
+
# b -> boolean
|
922 |
+
# u -> unsigned integer
|
923 |
+
# i -> signed integer
|
924 |
+
# f -> floating point
|
925 |
+
# c -> complex
|
926 |
+
# M -> datetime
|
927 |
+
# m -> timedelta
|
928 |
+
# S -> string
|
929 |
+
# U -> Unicode string
|
930 |
+
# V -> record
|
931 |
+
# O -> Python object
|
932 |
+
_kind_list = ['b', 'u', 'i', 'f', 'c', 'S', 'U', 'V', 'O', 'M', 'm']
|
933 |
+
|
934 |
+
__test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O'
|
935 |
+
__len_test_types = len(__test_types)
|
936 |
+
|
937 |
+
# Keep incrementing until a common type both can be coerced to
|
938 |
+
# is found. Otherwise, return None
|
939 |
+
def _find_common_coerce(a, b):
|
940 |
+
if a > b:
|
941 |
+
return a
|
942 |
+
try:
|
943 |
+
thisind = __test_types.index(a.char)
|
944 |
+
except ValueError:
|
945 |
+
return None
|
946 |
+
return _can_coerce_all([a, b], start=thisind)
|
947 |
+
|
948 |
+
# Find a data-type that all data-types in a list can be coerced to
|
949 |
+
def _can_coerce_all(dtypelist, start=0):
|
950 |
+
N = len(dtypelist)
|
951 |
+
if N == 0:
|
952 |
+
return None
|
953 |
+
if N == 1:
|
954 |
+
return dtypelist[0]
|
955 |
+
thisind = start
|
956 |
+
while thisind < __len_test_types:
|
957 |
+
newdtype = dtype(__test_types[thisind])
|
958 |
+
numcoerce = len([x for x in dtypelist if newdtype >= x])
|
959 |
+
if numcoerce == N:
|
960 |
+
return newdtype
|
961 |
+
thisind += 1
|
962 |
+
return None
|
963 |
+
|
964 |
+
def _register_types():
|
965 |
+
numbers.Integral.register(integer)
|
966 |
+
numbers.Complex.register(inexact)
|
967 |
+
numbers.Real.register(floating)
|
968 |
+
_register_types()
|
969 |
+
|
970 |
+
def find_common_type(array_types, scalar_types):
|
971 |
+
"""
|
972 |
+
Determine common type following standard coercion rules.
|
973 |
+
|
974 |
+
Parameters
|
975 |
+
----------
|
976 |
+
array_types : sequence
|
977 |
+
A list of dtypes or dtype convertible objects representing arrays.
|
978 |
+
scalar_types : sequence
|
979 |
+
A list of dtypes or dtype convertible objects representing scalars.
|
980 |
+
|
981 |
+
Returns
|
982 |
+
-------
|
983 |
+
datatype : dtype
|
984 |
+
The common data type, which is the maximum of `array_types` ignoring
|
985 |
+
`scalar_types`, unless the maximum of `scalar_types` is of a
|
986 |
+
different kind (`dtype.kind`). If the kind is not understood, then
|
987 |
+
None is returned.
|
988 |
+
|
989 |
+
See Also
|
990 |
+
--------
|
991 |
+
dtype, common_type, can_cast, mintypecode
|
992 |
+
|
993 |
+
Examples
|
994 |
+
--------
|
995 |
+
>>> np.find_common_type([], [np.int64, np.float32, np.complex])
|
996 |
+
dtype('complex128')
|
997 |
+
>>> np.find_common_type([np.int64, np.float32], [])
|
998 |
+
dtype('float64')
|
999 |
+
|
1000 |
+
The standard casting rules ensure that a scalar cannot up-cast an
|
1001 |
+
array unless the scalar is of a fundamentally different kind of data
|
1002 |
+
(i.e. under a different hierarchy in the data type hierarchy) then
|
1003 |
+
the array:
|
1004 |
+
|
1005 |
+
>>> np.find_common_type([np.float32], [np.int64, np.float64])
|
1006 |
+
dtype('float32')
|
1007 |
+
|
1008 |
+
Complex is of a different type, so it up-casts the float in the
|
1009 |
+
`array_types` argument:
|
1010 |
+
|
1011 |
+
>>> np.find_common_type([np.float32], [np.complex])
|
1012 |
+
dtype('complex128')
|
1013 |
+
|
1014 |
+
Type specifier strings are convertible to dtypes and can therefore
|
1015 |
+
be used instead of dtypes:
|
1016 |
+
|
1017 |
+
>>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
|
1018 |
+
dtype('complex128')
|
1019 |
+
|
1020 |
+
"""
|
1021 |
+
array_types = [dtype(x) for x in array_types]
|
1022 |
+
scalar_types = [dtype(x) for x in scalar_types]
|
1023 |
+
|
1024 |
+
maxa = _can_coerce_all(array_types)
|
1025 |
+
maxsc = _can_coerce_all(scalar_types)
|
1026 |
+
|
1027 |
+
if maxa is None:
|
1028 |
+
return maxsc
|
1029 |
+
|
1030 |
+
if maxsc is None:
|
1031 |
+
return maxa
|
1032 |
+
|
1033 |
+
try:
|
1034 |
+
index_a = _kind_list.index(maxa.kind)
|
1035 |
+
index_sc = _kind_list.index(maxsc.kind)
|
1036 |
+
except ValueError:
|
1037 |
+
return None
|
1038 |
+
|
1039 |
+
if index_sc > index_a:
|
1040 |
+
return _find_common_coerce(maxsc, maxa)
|
1041 |
+
else:
|
1042 |
+
return maxa
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/records.py
ADDED
@@ -0,0 +1,808 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Record Arrays
|
3 |
+
=============
|
4 |
+
Record arrays expose the fields of structured arrays as properties.
|
5 |
+
|
6 |
+
Most commonly, ndarrays contain elements of a single type, e.g. floats, integers,
|
7 |
+
bools etc. However, it is possible for elements to be combinations of these,
|
8 |
+
such as::
|
9 |
+
|
10 |
+
>>> a = np.array([(1, 2.0), (1, 2.0)], dtype=[('x', int), ('y', float)])
|
11 |
+
>>> a
|
12 |
+
array([(1, 2.0), (1, 2.0)],
|
13 |
+
dtype=[('x', '<i4'), ('y', '<f8')])
|
14 |
+
|
15 |
+
Here, each element consists of two fields: x (and int), and y (a float).
|
16 |
+
This is known as a structured array. The different fields are analogous
|
17 |
+
to columns in a spread-sheet. The different fields can be accessed as
|
18 |
+
one would a dictionary::
|
19 |
+
|
20 |
+
>>> a['x']
|
21 |
+
array([1, 1])
|
22 |
+
|
23 |
+
>>> a['y']
|
24 |
+
array([ 2., 2.])
|
25 |
+
|
26 |
+
Record arrays allow us to access fields as properties::
|
27 |
+
|
28 |
+
>>> ar = a.view(np.recarray)
|
29 |
+
|
30 |
+
>>> ar.x
|
31 |
+
array([1, 1])
|
32 |
+
|
33 |
+
>>> ar.y
|
34 |
+
array([ 2., 2.])
|
35 |
+
|
36 |
+
"""
|
37 |
+
from __future__ import division, absolute_import, print_function
|
38 |
+
|
39 |
+
import sys
|
40 |
+
import os
|
41 |
+
|
42 |
+
from . import numeric as sb
|
43 |
+
from .defchararray import chararray
|
44 |
+
from . import numerictypes as nt
|
45 |
+
from numpy.compat import isfileobj, bytes, long
|
46 |
+
|
47 |
+
# All of the functions allow formats to be a dtype
|
48 |
+
__all__ = ['record', 'recarray', 'format_parser']
|
49 |
+
|
50 |
+
|
51 |
+
ndarray = sb.ndarray
|
52 |
+
|
53 |
+
_byteorderconv = {'b':'>',
|
54 |
+
'l':'<',
|
55 |
+
'n':'=',
|
56 |
+
'B':'>',
|
57 |
+
'L':'<',
|
58 |
+
'N':'=',
|
59 |
+
'S':'s',
|
60 |
+
's':'s',
|
61 |
+
'>':'>',
|
62 |
+
'<':'<',
|
63 |
+
'=':'=',
|
64 |
+
'|':'|',
|
65 |
+
'I':'|',
|
66 |
+
'i':'|'}
|
67 |
+
|
68 |
+
# formats regular expression
|
69 |
+
# allows multidimension spec with a tuple syntax in front
|
70 |
+
# of the letter code '(2,3)f4' and ' ( 2 , 3 ) f4 '
|
71 |
+
# are equally allowed
|
72 |
+
|
73 |
+
numfmt = nt.typeDict
|
74 |
+
_typestr = nt._typestr
|
75 |
+
|
76 |
+
def find_duplicate(list):
|
77 |
+
"""Find duplication in a list, return a list of duplicated elements"""
|
78 |
+
dup = []
|
79 |
+
for i in range(len(list)):
|
80 |
+
if (list[i] in list[i + 1:]):
|
81 |
+
if (list[i] not in dup):
|
82 |
+
dup.append(list[i])
|
83 |
+
return dup
|
84 |
+
|
85 |
+
class format_parser:
|
86 |
+
"""
|
87 |
+
Class to convert formats, names, titles description to a dtype.
|
88 |
+
|
89 |
+
After constructing the format_parser object, the dtype attribute is
|
90 |
+
the converted data-type:
|
91 |
+
``dtype = format_parser(formats, names, titles).dtype``
|
92 |
+
|
93 |
+
Attributes
|
94 |
+
----------
|
95 |
+
dtype : dtype
|
96 |
+
The converted data-type.
|
97 |
+
|
98 |
+
Parameters
|
99 |
+
----------
|
100 |
+
formats : str or list of str
|
101 |
+
The format description, either specified as a string with
|
102 |
+
comma-separated format descriptions in the form ``'f8, i4, a5'``, or
|
103 |
+
a list of format description strings in the form
|
104 |
+
``['f8', 'i4', 'a5']``.
|
105 |
+
names : str or list/tuple of str
|
106 |
+
The field names, either specified as a comma-separated string in the
|
107 |
+
form ``'col1, col2, col3'``, or as a list or tuple of strings in the
|
108 |
+
form ``['col1', 'col2', 'col3']``.
|
109 |
+
An empty list can be used, in that case default field names
|
110 |
+
('f0', 'f1', ...) are used.
|
111 |
+
titles : sequence
|
112 |
+
Sequence of title strings. An empty list can be used to leave titles
|
113 |
+
out.
|
114 |
+
aligned : bool, optional
|
115 |
+
If True, align the fields by padding as the C-compiler would.
|
116 |
+
Default is False.
|
117 |
+
byteorder : str, optional
|
118 |
+
If specified, all the fields will be changed to the
|
119 |
+
provided byte-order. Otherwise, the default byte-order is
|
120 |
+
used. For all available string specifiers, see `dtype.newbyteorder`.
|
121 |
+
|
122 |
+
See Also
|
123 |
+
--------
|
124 |
+
dtype, typename, sctype2char
|
125 |
+
|
126 |
+
Examples
|
127 |
+
--------
|
128 |
+
>>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
|
129 |
+
... ['T1', 'T2', 'T3']).dtype
|
130 |
+
dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'),
|
131 |
+
(('T3', 'col3'), '|S5')])
|
132 |
+
|
133 |
+
`names` and/or `titles` can be empty lists. If `titles` is an empty list,
|
134 |
+
titles will simply not appear. If `names` is empty, default field names
|
135 |
+
will be used.
|
136 |
+
|
137 |
+
>>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
|
138 |
+
... []).dtype
|
139 |
+
dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '|S5')])
|
140 |
+
>>> np.format_parser(['f8', 'i4', 'a5'], [], []).dtype
|
141 |
+
dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', '|S5')])
|
142 |
+
|
143 |
+
"""
|
144 |
+
def __init__(self, formats, names, titles, aligned=False, byteorder=None):
|
145 |
+
self._parseFormats(formats, aligned)
|
146 |
+
self._setfieldnames(names, titles)
|
147 |
+
self._createdescr(byteorder)
|
148 |
+
self.dtype = self._descr
|
149 |
+
|
150 |
+
def _parseFormats(self, formats, aligned=0):
|
151 |
+
""" Parse the field formats """
|
152 |
+
|
153 |
+
if formats is None:
|
154 |
+
raise ValueError("Need formats argument")
|
155 |
+
if isinstance(formats, list):
|
156 |
+
if len(formats) < 2:
|
157 |
+
formats.append('')
|
158 |
+
formats = ','.join(formats)
|
159 |
+
dtype = sb.dtype(formats, aligned)
|
160 |
+
fields = dtype.fields
|
161 |
+
if fields is None:
|
162 |
+
dtype = sb.dtype([('f1', dtype)], aligned)
|
163 |
+
fields = dtype.fields
|
164 |
+
keys = dtype.names
|
165 |
+
self._f_formats = [fields[key][0] for key in keys]
|
166 |
+
self._offsets = [fields[key][1] for key in keys]
|
167 |
+
self._nfields = len(keys)
|
168 |
+
|
169 |
+
def _setfieldnames(self, names, titles):
|
170 |
+
"""convert input field names into a list and assign to the _names
|
171 |
+
attribute """
|
172 |
+
|
173 |
+
if (names):
|
174 |
+
if (type(names) in [list, tuple]):
|
175 |
+
pass
|
176 |
+
elif isinstance(names, str):
|
177 |
+
names = names.split(',')
|
178 |
+
else:
|
179 |
+
raise NameError("illegal input names %s" % repr(names))
|
180 |
+
|
181 |
+
self._names = [n.strip() for n in names[:self._nfields]]
|
182 |
+
else:
|
183 |
+
self._names = []
|
184 |
+
|
185 |
+
# if the names are not specified, they will be assigned as
|
186 |
+
# "f0, f1, f2,..."
|
187 |
+
# if not enough names are specified, they will be assigned as "f[n],
|
188 |
+
# f[n+1],..." etc. where n is the number of specified names..."
|
189 |
+
self._names += ['f%d' % i for i in range(len(self._names),
|
190 |
+
self._nfields)]
|
191 |
+
# check for redundant names
|
192 |
+
_dup = find_duplicate(self._names)
|
193 |
+
if _dup:
|
194 |
+
raise ValueError("Duplicate field names: %s" % _dup)
|
195 |
+
|
196 |
+
if (titles):
|
197 |
+
self._titles = [n.strip() for n in titles[:self._nfields]]
|
198 |
+
else:
|
199 |
+
self._titles = []
|
200 |
+
titles = []
|
201 |
+
|
202 |
+
if (self._nfields > len(titles)):
|
203 |
+
self._titles += [None] * (self._nfields - len(titles))
|
204 |
+
|
205 |
+
def _createdescr(self, byteorder):
|
206 |
+
descr = sb.dtype({'names':self._names,
|
207 |
+
'formats':self._f_formats,
|
208 |
+
'offsets':self._offsets,
|
209 |
+
'titles':self._titles})
|
210 |
+
if (byteorder is not None):
|
211 |
+
byteorder = _byteorderconv[byteorder[0]]
|
212 |
+
descr = descr.newbyteorder(byteorder)
|
213 |
+
|
214 |
+
self._descr = descr
|
215 |
+
|
216 |
+
class record(nt.void):
|
217 |
+
"""A data-type scalar that allows field access as attribute lookup.
|
218 |
+
"""
|
219 |
+
def __repr__(self):
|
220 |
+
return self.__str__()
|
221 |
+
|
222 |
+
def __str__(self):
|
223 |
+
return str(self.item())
|
224 |
+
|
225 |
+
def __getattribute__(self, attr):
|
226 |
+
if attr in ['setfield', 'getfield', 'dtype']:
|
227 |
+
return nt.void.__getattribute__(self, attr)
|
228 |
+
try:
|
229 |
+
return nt.void.__getattribute__(self, attr)
|
230 |
+
except AttributeError:
|
231 |
+
pass
|
232 |
+
fielddict = nt.void.__getattribute__(self, 'dtype').fields
|
233 |
+
res = fielddict.get(attr, None)
|
234 |
+
if res:
|
235 |
+
obj = self.getfield(*res[:2])
|
236 |
+
# if it has fields return a recarray,
|
237 |
+
# if it's a string ('SU') return a chararray
|
238 |
+
# otherwise return the object
|
239 |
+
try:
|
240 |
+
dt = obj.dtype
|
241 |
+
except AttributeError:
|
242 |
+
return obj
|
243 |
+
if dt.fields:
|
244 |
+
return obj.view(obj.__class__)
|
245 |
+
if dt.char in 'SU':
|
246 |
+
return obj.view(chararray)
|
247 |
+
return obj
|
248 |
+
else:
|
249 |
+
raise AttributeError("'record' object has no "
|
250 |
+
"attribute '%s'" % attr)
|
251 |
+
|
252 |
+
|
253 |
+
def __setattr__(self, attr, val):
|
254 |
+
if attr in ['setfield', 'getfield', 'dtype']:
|
255 |
+
raise AttributeError("Cannot set '%s' attribute" % attr)
|
256 |
+
fielddict = nt.void.__getattribute__(self, 'dtype').fields
|
257 |
+
res = fielddict.get(attr, None)
|
258 |
+
if res:
|
259 |
+
return self.setfield(val, *res[:2])
|
260 |
+
else:
|
261 |
+
if getattr(self, attr, None):
|
262 |
+
return nt.void.__setattr__(self, attr, val)
|
263 |
+
else:
|
264 |
+
raise AttributeError("'record' object has no "
|
265 |
+
"attribute '%s'" % attr)
|
266 |
+
|
267 |
+
def pprint(self):
|
268 |
+
"""Pretty-print all fields."""
|
269 |
+
# pretty-print all fields
|
270 |
+
names = self.dtype.names
|
271 |
+
maxlen = max([len(name) for name in names])
|
272 |
+
rows = []
|
273 |
+
fmt = '%% %ds: %%s' % maxlen
|
274 |
+
for name in names:
|
275 |
+
rows.append(fmt % (name, getattr(self, name)))
|
276 |
+
return "\n".join(rows)
|
277 |
+
|
278 |
+
# The recarray is almost identical to a standard array (which supports
|
279 |
+
# named fields already) The biggest difference is that it can use
|
280 |
+
# attribute-lookup to find the fields and it is constructed using
|
281 |
+
# a record.
|
282 |
+
|
283 |
+
# If byteorder is given it forces a particular byteorder on all
|
284 |
+
# the fields (and any subfields)
|
285 |
+
|
286 |
+
class recarray(ndarray):
|
287 |
+
"""
|
288 |
+
Construct an ndarray that allows field access using attributes.
|
289 |
+
|
290 |
+
Arrays may have a data-types containing fields, analogous
|
291 |
+
to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
|
292 |
+
where each entry in the array is a pair of ``(int, float)``. Normally,
|
293 |
+
these attributes are accessed using dictionary lookups such as ``arr['x']``
|
294 |
+
and ``arr['y']``. Record arrays allow the fields to be accessed as members
|
295 |
+
of the array, using ``arr.x`` and ``arr.y``.
|
296 |
+
|
297 |
+
Parameters
|
298 |
+
----------
|
299 |
+
shape : tuple
|
300 |
+
Shape of output array.
|
301 |
+
dtype : data-type, optional
|
302 |
+
The desired data-type. By default, the data-type is determined
|
303 |
+
from `formats`, `names`, `titles`, `aligned` and `byteorder`.
|
304 |
+
formats : list of data-types, optional
|
305 |
+
A list containing the data-types for the different columns, e.g.
|
306 |
+
``['i4', 'f8', 'i4']``. `formats` does *not* support the new
|
307 |
+
convention of using types directly, i.e. ``(int, float, int)``.
|
308 |
+
Note that `formats` must be a list, not a tuple.
|
309 |
+
Given that `formats` is somewhat limited, we recommend specifying
|
310 |
+
`dtype` instead.
|
311 |
+
names : tuple of str, optional
|
312 |
+
The name of each column, e.g. ``('x', 'y', 'z')``.
|
313 |
+
buf : buffer, optional
|
314 |
+
By default, a new array is created of the given shape and data-type.
|
315 |
+
If `buf` is specified and is an object exposing the buffer interface,
|
316 |
+
the array will use the memory from the existing buffer. In this case,
|
317 |
+
the `offset` and `strides` keywords are available.
|
318 |
+
|
319 |
+
Other Parameters
|
320 |
+
----------------
|
321 |
+
titles : tuple of str, optional
|
322 |
+
Aliases for column names. For example, if `names` were
|
323 |
+
``('x', 'y', 'z')`` and `titles` is
|
324 |
+
``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
|
325 |
+
``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
|
326 |
+
byteorder : {'<', '>', '='}, optional
|
327 |
+
Byte-order for all fields.
|
328 |
+
aligned : bool, optional
|
329 |
+
Align the fields in memory as the C-compiler would.
|
330 |
+
strides : tuple of ints, optional
|
331 |
+
Buffer (`buf`) is interpreted according to these strides (strides
|
332 |
+
define how many bytes each array element, row, column, etc.
|
333 |
+
occupy in memory).
|
334 |
+
offset : int, optional
|
335 |
+
Start reading buffer (`buf`) from this offset onwards.
|
336 |
+
order : {'C', 'F'}, optional
|
337 |
+
Row-major or column-major order.
|
338 |
+
|
339 |
+
Returns
|
340 |
+
-------
|
341 |
+
rec : recarray
|
342 |
+
Empty array of the given shape and type.
|
343 |
+
|
344 |
+
See Also
|
345 |
+
--------
|
346 |
+
rec.fromrecords : Construct a record array from data.
|
347 |
+
record : fundamental data-type for `recarray`.
|
348 |
+
format_parser : determine a data-type from formats, names, titles.
|
349 |
+
|
350 |
+
Notes
|
351 |
+
-----
|
352 |
+
This constructor can be compared to ``empty``: it creates a new record
|
353 |
+
array but does not fill it with data. To create a record array from data,
|
354 |
+
use one of the following methods:
|
355 |
+
|
356 |
+
1. Create a standard ndarray and convert it to a record array,
|
357 |
+
using ``arr.view(np.recarray)``
|
358 |
+
2. Use the `buf` keyword.
|
359 |
+
3. Use `np.rec.fromrecords`.
|
360 |
+
|
361 |
+
Examples
|
362 |
+
--------
|
363 |
+
Create an array with two fields, ``x`` and ``y``:
|
364 |
+
|
365 |
+
>>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])
|
366 |
+
>>> x
|
367 |
+
array([(1.0, 2), (3.0, 4)],
|
368 |
+
dtype=[('x', '<f8'), ('y', '<i4')])
|
369 |
+
|
370 |
+
>>> x['x']
|
371 |
+
array([ 1., 3.])
|
372 |
+
|
373 |
+
View the array as a record array:
|
374 |
+
|
375 |
+
>>> x = x.view(np.recarray)
|
376 |
+
|
377 |
+
>>> x.x
|
378 |
+
array([ 1., 3.])
|
379 |
+
|
380 |
+
>>> x.y
|
381 |
+
array([2, 4])
|
382 |
+
|
383 |
+
Create a new, empty record array:
|
384 |
+
|
385 |
+
>>> np.recarray((2,),
|
386 |
+
... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
|
387 |
+
rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
|
388 |
+
(3471280, 1.2134086255804012e-316, 0)],
|
389 |
+
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
|
390 |
+
|
391 |
+
"""
|
392 |
+
def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None,
|
393 |
+
formats=None, names=None, titles=None,
|
394 |
+
byteorder=None, aligned=False, order='C'):
|
395 |
+
|
396 |
+
if dtype is not None:
|
397 |
+
descr = sb.dtype(dtype)
|
398 |
+
else:
|
399 |
+
descr = format_parser(formats, names, titles, aligned, byteorder)._descr
|
400 |
+
|
401 |
+
if buf is None:
|
402 |
+
self = ndarray.__new__(subtype, shape, (record, descr), order=order)
|
403 |
+
else:
|
404 |
+
self = ndarray.__new__(subtype, shape, (record, descr),
|
405 |
+
buffer=buf, offset=offset,
|
406 |
+
strides=strides, order=order)
|
407 |
+
return self
|
408 |
+
|
409 |
+
def __getattribute__(self, attr):
|
410 |
+
try:
|
411 |
+
return object.__getattribute__(self, attr)
|
412 |
+
except AttributeError: # attr must be a fieldname
|
413 |
+
pass
|
414 |
+
fielddict = ndarray.__getattribute__(self, 'dtype').fields
|
415 |
+
try:
|
416 |
+
res = fielddict[attr][:2]
|
417 |
+
except (TypeError, KeyError):
|
418 |
+
raise AttributeError("record array has no attribute %s" % attr)
|
419 |
+
obj = self.getfield(*res)
|
420 |
+
# if it has fields return a recarray, otherwise return
|
421 |
+
# normal array
|
422 |
+
if obj.dtype.fields:
|
423 |
+
return obj
|
424 |
+
if obj.dtype.char in 'SU':
|
425 |
+
return obj.view(chararray)
|
426 |
+
return obj.view(ndarray)
|
427 |
+
|
428 |
+
# Save the dictionary
|
429 |
+
# If the attr is a field name and not in the saved dictionary
|
430 |
+
# Undo any "setting" of the attribute and do a setfield
|
431 |
+
# Thus, you can't create attributes on-the-fly that are field names.
|
432 |
+
|
433 |
+
def __setattr__(self, attr, val):
|
434 |
+
newattr = attr not in self.__dict__
|
435 |
+
try:
|
436 |
+
ret = object.__setattr__(self, attr, val)
|
437 |
+
except:
|
438 |
+
fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
|
439 |
+
if attr not in fielddict:
|
440 |
+
exctype, value = sys.exc_info()[:2]
|
441 |
+
raise exctype(value)
|
442 |
+
else:
|
443 |
+
fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
|
444 |
+
if attr not in fielddict:
|
445 |
+
return ret
|
446 |
+
if newattr: # We just added this one
|
447 |
+
try: # or this setattr worked on an internal
|
448 |
+
# attribute.
|
449 |
+
object.__delattr__(self, attr)
|
450 |
+
except:
|
451 |
+
return ret
|
452 |
+
try:
|
453 |
+
res = fielddict[attr][:2]
|
454 |
+
except (TypeError, KeyError):
|
455 |
+
raise AttributeError("record array has no attribute %s" % attr)
|
456 |
+
return self.setfield(val, *res)
|
457 |
+
|
458 |
+
def __getitem__(self, indx):
|
459 |
+
obj = ndarray.__getitem__(self, indx)
|
460 |
+
if (isinstance(obj, ndarray) and obj.dtype.isbuiltin):
|
461 |
+
return obj.view(ndarray)
|
462 |
+
return obj
|
463 |
+
|
464 |
+
def __repr__(self) :
|
465 |
+
ret = ndarray.__repr__(self)
|
466 |
+
return ret.replace("recarray", "rec.array", 1)
|
467 |
+
|
468 |
+
def field(self, attr, val=None):
|
469 |
+
if isinstance(attr, int):
|
470 |
+
names = ndarray.__getattribute__(self, 'dtype').names
|
471 |
+
attr = names[attr]
|
472 |
+
|
473 |
+
fielddict = ndarray.__getattribute__(self, 'dtype').fields
|
474 |
+
|
475 |
+
res = fielddict[attr][:2]
|
476 |
+
|
477 |
+
if val is None:
|
478 |
+
obj = self.getfield(*res)
|
479 |
+
if obj.dtype.fields:
|
480 |
+
return obj
|
481 |
+
if obj.dtype.char in 'SU':
|
482 |
+
return obj.view(chararray)
|
483 |
+
return obj.view(ndarray)
|
484 |
+
else:
|
485 |
+
return self.setfield(val, *res)
|
486 |
+
|
487 |
+
def view(self, dtype=None, type=None):
|
488 |
+
if dtype is None:
|
489 |
+
return ndarray.view(self, type)
|
490 |
+
elif type is None:
|
491 |
+
try:
|
492 |
+
if issubclass(dtype, ndarray):
|
493 |
+
return ndarray.view(self, dtype)
|
494 |
+
except TypeError:
|
495 |
+
pass
|
496 |
+
dtype = sb.dtype(dtype)
|
497 |
+
if dtype.fields is None:
|
498 |
+
return self.__array__().view(dtype)
|
499 |
+
return ndarray.view(self, dtype)
|
500 |
+
else:
|
501 |
+
return ndarray.view(self, dtype, type)
|
502 |
+
|
503 |
+
|
504 |
+
def fromarrays(arrayList, dtype=None, shape=None, formats=None,
|
505 |
+
names=None, titles=None, aligned=False, byteorder=None):
|
506 |
+
""" create a record array from a (flat) list of arrays
|
507 |
+
|
508 |
+
>>> x1=np.array([1,2,3,4])
|
509 |
+
>>> x2=np.array(['a','dd','xyz','12'])
|
510 |
+
>>> x3=np.array([1.1,2,3,4])
|
511 |
+
>>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')
|
512 |
+
>>> print r[1]
|
513 |
+
(2, 'dd', 2.0)
|
514 |
+
>>> x1[1]=34
|
515 |
+
>>> r.a
|
516 |
+
array([1, 2, 3, 4])
|
517 |
+
"""
|
518 |
+
|
519 |
+
arrayList = [sb.asarray(x) for x in arrayList]
|
520 |
+
|
521 |
+
if shape is None or shape == 0:
|
522 |
+
shape = arrayList[0].shape
|
523 |
+
|
524 |
+
if isinstance(shape, int):
|
525 |
+
shape = (shape,)
|
526 |
+
|
527 |
+
if formats is None and dtype is None:
|
528 |
+
# go through each object in the list to see if it is an ndarray
|
529 |
+
# and determine the formats.
|
530 |
+
formats = ''
|
531 |
+
for obj in arrayList:
|
532 |
+
if not isinstance(obj, ndarray):
|
533 |
+
raise ValueError("item in the array list must be an ndarray.")
|
534 |
+
formats += _typestr[obj.dtype.type]
|
535 |
+
if issubclass(obj.dtype.type, nt.flexible):
|
536 |
+
formats += repr(obj.itemsize)
|
537 |
+
formats += ','
|
538 |
+
formats = formats[:-1]
|
539 |
+
|
540 |
+
if dtype is not None:
|
541 |
+
descr = sb.dtype(dtype)
|
542 |
+
_names = descr.names
|
543 |
+
else:
|
544 |
+
parsed = format_parser(formats, names, titles, aligned, byteorder)
|
545 |
+
_names = parsed._names
|
546 |
+
descr = parsed._descr
|
547 |
+
|
548 |
+
# Determine shape from data-type.
|
549 |
+
if len(descr) != len(arrayList):
|
550 |
+
raise ValueError("mismatch between the number of fields "
|
551 |
+
"and the number of arrays")
|
552 |
+
|
553 |
+
d0 = descr[0].shape
|
554 |
+
nn = len(d0)
|
555 |
+
if nn > 0:
|
556 |
+
shape = shape[:-nn]
|
557 |
+
|
558 |
+
for k, obj in enumerate(arrayList):
|
559 |
+
nn = len(descr[k].shape)
|
560 |
+
testshape = obj.shape[:len(obj.shape) - nn]
|
561 |
+
if testshape != shape:
|
562 |
+
raise ValueError("array-shape mismatch in array %d" % k)
|
563 |
+
|
564 |
+
_array = recarray(shape, descr)
|
565 |
+
|
566 |
+
# populate the record array (makes a copy)
|
567 |
+
for i in range(len(arrayList)):
|
568 |
+
_array[_names[i]] = arrayList[i]
|
569 |
+
|
570 |
+
return _array
|
571 |
+
|
572 |
+
# shape must be 1-d if you use list of lists...
|
573 |
+
def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
|
574 |
+
titles=None, aligned=False, byteorder=None):
|
575 |
+
""" create a recarray from a list of records in text form
|
576 |
+
|
577 |
+
The data in the same field can be heterogeneous, they will be promoted
|
578 |
+
to the highest data type. This method is intended for creating
|
579 |
+
smaller record arrays. If used to create large array without formats
|
580 |
+
defined
|
581 |
+
|
582 |
+
r=fromrecords([(2,3.,'abc')]*100000)
|
583 |
+
|
584 |
+
it can be slow.
|
585 |
+
|
586 |
+
If formats is None, then this will auto-detect formats. Use list of
|
587 |
+
tuples rather than list of lists for faster processing.
|
588 |
+
|
589 |
+
>>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
|
590 |
+
... names='col1,col2,col3')
|
591 |
+
>>> print r[0]
|
592 |
+
(456, 'dbe', 1.2)
|
593 |
+
>>> r.col1
|
594 |
+
array([456, 2])
|
595 |
+
>>> r.col2
|
596 |
+
chararray(['dbe', 'de'],
|
597 |
+
dtype='|S3')
|
598 |
+
>>> import pickle
|
599 |
+
>>> print pickle.loads(pickle.dumps(r))
|
600 |
+
[(456, 'dbe', 1.2) (2, 'de', 1.3)]
|
601 |
+
"""
|
602 |
+
|
603 |
+
nfields = len(recList[0])
|
604 |
+
if formats is None and dtype is None: # slower
|
605 |
+
obj = sb.array(recList, dtype=object)
|
606 |
+
arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)]
|
607 |
+
return fromarrays(arrlist, formats=formats, shape=shape, names=names,
|
608 |
+
titles=titles, aligned=aligned, byteorder=byteorder)
|
609 |
+
|
610 |
+
if dtype is not None:
|
611 |
+
descr = sb.dtype((record, dtype))
|
612 |
+
else:
|
613 |
+
descr = format_parser(formats, names, titles, aligned, byteorder)._descr
|
614 |
+
|
615 |
+
try:
|
616 |
+
retval = sb.array(recList, dtype=descr)
|
617 |
+
except TypeError: # list of lists instead of list of tuples
|
618 |
+
if (shape is None or shape == 0):
|
619 |
+
shape = len(recList)
|
620 |
+
if isinstance(shape, (int, long)):
|
621 |
+
shape = (shape,)
|
622 |
+
if len(shape) > 1:
|
623 |
+
raise ValueError("Can only deal with 1-d array.")
|
624 |
+
_array = recarray(shape, descr)
|
625 |
+
for k in range(_array.size):
|
626 |
+
_array[k] = tuple(recList[k])
|
627 |
+
return _array
|
628 |
+
else:
|
629 |
+
if shape is not None and retval.shape != shape:
|
630 |
+
retval.shape = shape
|
631 |
+
|
632 |
+
res = retval.view(recarray)
|
633 |
+
|
634 |
+
return res
|
635 |
+
|
636 |
+
|
637 |
+
def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None,
|
638 |
+
names=None, titles=None, aligned=False, byteorder=None):
|
639 |
+
""" create a (read-only) record array from binary data contained in
|
640 |
+
a string"""
|
641 |
+
|
642 |
+
|
643 |
+
if dtype is None and formats is None:
|
644 |
+
raise ValueError("Must have dtype= or formats=")
|
645 |
+
|
646 |
+
if dtype is not None:
|
647 |
+
descr = sb.dtype(dtype)
|
648 |
+
else:
|
649 |
+
descr = format_parser(formats, names, titles, aligned, byteorder)._descr
|
650 |
+
|
651 |
+
itemsize = descr.itemsize
|
652 |
+
if (shape is None or shape == 0 or shape == -1):
|
653 |
+
shape = (len(datastring) - offset) / itemsize
|
654 |
+
|
655 |
+
_array = recarray(shape, descr, buf=datastring, offset=offset)
|
656 |
+
return _array
|
657 |
+
|
658 |
+
def get_remaining_size(fd):
|
659 |
+
try:
|
660 |
+
fn = fd.fileno()
|
661 |
+
except AttributeError:
|
662 |
+
return os.path.getsize(fd.name) - fd.tell()
|
663 |
+
st = os.fstat(fn)
|
664 |
+
size = st.st_size - fd.tell()
|
665 |
+
return size
|
666 |
+
|
667 |
+
def fromfile(fd, dtype=None, shape=None, offset=0, formats=None,
|
668 |
+
names=None, titles=None, aligned=False, byteorder=None):
|
669 |
+
"""Create an array from binary file data
|
670 |
+
|
671 |
+
If file is a string then that file is opened, else it is assumed
|
672 |
+
to be a file object.
|
673 |
+
|
674 |
+
>>> from tempfile import TemporaryFile
|
675 |
+
>>> a = np.empty(10,dtype='f8,i4,a5')
|
676 |
+
>>> a[5] = (0.5,10,'abcde')
|
677 |
+
>>>
|
678 |
+
>>> fd=TemporaryFile()
|
679 |
+
>>> a = a.newbyteorder('<')
|
680 |
+
>>> a.tofile(fd)
|
681 |
+
>>>
|
682 |
+
>>> fd.seek(0)
|
683 |
+
>>> r=np.core.records.fromfile(fd, formats='f8,i4,a5', shape=10,
|
684 |
+
... byteorder='<')
|
685 |
+
>>> print r[5]
|
686 |
+
(0.5, 10, 'abcde')
|
687 |
+
>>> r.shape
|
688 |
+
(10,)
|
689 |
+
"""
|
690 |
+
|
691 |
+
if (shape is None or shape == 0):
|
692 |
+
shape = (-1,)
|
693 |
+
elif isinstance(shape, (int, long)):
|
694 |
+
shape = (shape,)
|
695 |
+
|
696 |
+
name = 0
|
697 |
+
if isinstance(fd, str):
|
698 |
+
name = 1
|
699 |
+
fd = open(fd, 'rb')
|
700 |
+
if (offset > 0):
|
701 |
+
fd.seek(offset, 1)
|
702 |
+
size = get_remaining_size(fd)
|
703 |
+
|
704 |
+
if dtype is not None:
|
705 |
+
descr = sb.dtype(dtype)
|
706 |
+
else:
|
707 |
+
descr = format_parser(formats, names, titles, aligned, byteorder)._descr
|
708 |
+
|
709 |
+
itemsize = descr.itemsize
|
710 |
+
|
711 |
+
shapeprod = sb.array(shape).prod()
|
712 |
+
shapesize = shapeprod * itemsize
|
713 |
+
if shapesize < 0:
|
714 |
+
shape = list(shape)
|
715 |
+
shape[ shape.index(-1) ] = size / -shapesize
|
716 |
+
shape = tuple(shape)
|
717 |
+
shapeprod = sb.array(shape).prod()
|
718 |
+
|
719 |
+
nbytes = shapeprod * itemsize
|
720 |
+
|
721 |
+
if nbytes > size:
|
722 |
+
raise ValueError(
|
723 |
+
"Not enough bytes left in file for specified shape and type")
|
724 |
+
|
725 |
+
# create the array
|
726 |
+
_array = recarray(shape, descr)
|
727 |
+
nbytesread = fd.readinto(_array.data)
|
728 |
+
if nbytesread != nbytes:
|
729 |
+
raise IOError("Didn't read as many bytes as expected")
|
730 |
+
if name:
|
731 |
+
fd.close()
|
732 |
+
|
733 |
+
return _array
|
734 |
+
|
735 |
+
def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None,
|
736 |
+
names=None, titles=None, aligned=False, byteorder=None, copy=True):
|
737 |
+
"""Construct a record array from a wide-variety of objects.
|
738 |
+
"""
|
739 |
+
|
740 |
+
if (isinstance(obj, (type(None), str)) or isfileobj(obj)) \
|
741 |
+
and (formats is None) \
|
742 |
+
and (dtype is None):
|
743 |
+
raise ValueError("Must define formats (or dtype) if object is "\
|
744 |
+
"None, string, or an open file")
|
745 |
+
|
746 |
+
kwds = {}
|
747 |
+
if dtype is not None:
|
748 |
+
dtype = sb.dtype(dtype)
|
749 |
+
elif formats is not None:
|
750 |
+
dtype = format_parser(formats, names, titles,
|
751 |
+
aligned, byteorder)._descr
|
752 |
+
else:
|
753 |
+
kwds = {'formats': formats,
|
754 |
+
'names' : names,
|
755 |
+
'titles' : titles,
|
756 |
+
'aligned' : aligned,
|
757 |
+
'byteorder' : byteorder
|
758 |
+
}
|
759 |
+
|
760 |
+
if obj is None:
|
761 |
+
if shape is None:
|
762 |
+
raise ValueError("Must define a shape if obj is None")
|
763 |
+
return recarray(shape, dtype, buf=obj, offset=offset, strides=strides)
|
764 |
+
|
765 |
+
elif isinstance(obj, bytes):
|
766 |
+
return fromstring(obj, dtype, shape=shape, offset=offset, **kwds)
|
767 |
+
|
768 |
+
elif isinstance(obj, (list, tuple)):
|
769 |
+
if isinstance(obj[0], (tuple, list)):
|
770 |
+
return fromrecords(obj, dtype=dtype, shape=shape, **kwds)
|
771 |
+
else:
|
772 |
+
return fromarrays(obj, dtype=dtype, shape=shape, **kwds)
|
773 |
+
|
774 |
+
elif isinstance(obj, recarray):
|
775 |
+
if dtype is not None and (obj.dtype != dtype):
|
776 |
+
new = obj.view(dtype)
|
777 |
+
else:
|
778 |
+
new = obj
|
779 |
+
if copy:
|
780 |
+
new = new.copy()
|
781 |
+
return new
|
782 |
+
|
783 |
+
elif isfileobj(obj):
|
784 |
+
return fromfile(obj, dtype=dtype, shape=shape, offset=offset)
|
785 |
+
|
786 |
+
elif isinstance(obj, ndarray):
|
787 |
+
if dtype is not None and (obj.dtype != dtype):
|
788 |
+
new = obj.view(dtype)
|
789 |
+
else:
|
790 |
+
new = obj
|
791 |
+
if copy:
|
792 |
+
new = new.copy()
|
793 |
+
res = new.view(recarray)
|
794 |
+
if issubclass(res.dtype.type, nt.void):
|
795 |
+
res.dtype = sb.dtype((record, res.dtype))
|
796 |
+
return res
|
797 |
+
|
798 |
+
else:
|
799 |
+
interface = getattr(obj, "__array_interface__", None)
|
800 |
+
if interface is None or not isinstance(interface, dict):
|
801 |
+
raise ValueError("Unknown input type")
|
802 |
+
obj = sb.array(obj)
|
803 |
+
if dtype is not None and (obj.dtype != dtype):
|
804 |
+
obj = obj.view(dtype)
|
805 |
+
res = obj.view(recarray)
|
806 |
+
if issubclass(res.dtype.type, nt.void):
|
807 |
+
res.dtype = sb.dtype((record, res.dtype))
|
808 |
+
return res
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/setup.py
ADDED
@@ -0,0 +1,1013 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, print_function
|
2 |
+
|
3 |
+
import imp
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import shutil
|
7 |
+
import pickle
|
8 |
+
import copy
|
9 |
+
import warnings
|
10 |
+
import re
|
11 |
+
from os.path import join
|
12 |
+
from numpy.distutils import log
|
13 |
+
from distutils.dep_util import newer
|
14 |
+
from distutils.sysconfig import get_config_var
|
15 |
+
|
16 |
+
from setup_common import *
|
17 |
+
|
18 |
+
# Set to True to enable multiple file compilations (experimental)
|
19 |
+
ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0")
|
20 |
+
# Set to True to enable relaxed strides checking. This (mostly) means
|
21 |
+
# that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags.
|
22 |
+
NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "0") != "0")
|
23 |
+
|
24 |
+
# XXX: ugly, we use a class to avoid calling twice some expensive functions in
|
25 |
+
# config.h/numpyconfig.h. I don't see a better way because distutils force
|
26 |
+
# config.h generation inside an Extension class, and as such sharing
|
27 |
+
# configuration informations between extensions is not easy.
|
28 |
+
# Using a pickled-based memoize does not work because config_cmd is an instance
|
29 |
+
# method, which cPickle does not like.
|
30 |
+
#
|
31 |
+
# Use pickle in all cases, as cPickle is gone in python3 and the difference
|
32 |
+
# in time is only in build. -- Charles Harris, 2013-03-30
|
33 |
+
|
34 |
+
class CallOnceOnly(object):
|
35 |
+
def __init__(self):
|
36 |
+
self._check_types = None
|
37 |
+
self._check_ieee_macros = None
|
38 |
+
self._check_complex = None
|
39 |
+
|
40 |
+
def check_types(self, *a, **kw):
|
41 |
+
if self._check_types is None:
|
42 |
+
out = check_types(*a, **kw)
|
43 |
+
self._check_types = pickle.dumps(out)
|
44 |
+
else:
|
45 |
+
out = copy.deepcopy(pickle.loads(self._check_types))
|
46 |
+
return out
|
47 |
+
|
48 |
+
def check_ieee_macros(self, *a, **kw):
|
49 |
+
if self._check_ieee_macros is None:
|
50 |
+
out = check_ieee_macros(*a, **kw)
|
51 |
+
self._check_ieee_macros = pickle.dumps(out)
|
52 |
+
else:
|
53 |
+
out = copy.deepcopy(pickle.loads(self._check_ieee_macros))
|
54 |
+
return out
|
55 |
+
|
56 |
+
def check_complex(self, *a, **kw):
|
57 |
+
if self._check_complex is None:
|
58 |
+
out = check_complex(*a, **kw)
|
59 |
+
self._check_complex = pickle.dumps(out)
|
60 |
+
else:
|
61 |
+
out = copy.deepcopy(pickle.loads(self._check_complex))
|
62 |
+
return out
|
63 |
+
|
64 |
+
PYTHON_HAS_UNICODE_WIDE = True
|
65 |
+
|
66 |
+
def pythonlib_dir():
|
67 |
+
"""return path where libpython* is."""
|
68 |
+
if sys.platform == 'win32':
|
69 |
+
return os.path.join(sys.prefix, "libs")
|
70 |
+
else:
|
71 |
+
return get_config_var('LIBDIR')
|
72 |
+
|
73 |
+
def is_npy_no_signal():
|
74 |
+
"""Return True if the NPY_NO_SIGNAL symbol must be defined in configuration
|
75 |
+
header."""
|
76 |
+
return sys.platform == 'win32'
|
77 |
+
|
78 |
+
def is_npy_no_smp():
|
79 |
+
"""Return True if the NPY_NO_SMP symbol must be defined in public
|
80 |
+
header (when SMP support cannot be reliably enabled)."""
|
81 |
+
# Python 2.3 causes a segfault when
|
82 |
+
# trying to re-acquire the thread-state
|
83 |
+
# which is done in error-handling
|
84 |
+
# ufunc code. NPY_ALLOW_C_API and friends
|
85 |
+
# cause the segfault. So, we disable threading
|
86 |
+
# for now.
|
87 |
+
if sys.version[:5] < '2.4.2':
|
88 |
+
nosmp = 1
|
89 |
+
else:
|
90 |
+
# Perhaps a fancier check is in order here.
|
91 |
+
# so that threads are only enabled if there
|
92 |
+
# are actually multiple CPUS? -- but
|
93 |
+
# threaded code can be nice even on a single
|
94 |
+
# CPU so that long-calculating code doesn't
|
95 |
+
# block.
|
96 |
+
try:
|
97 |
+
nosmp = os.environ['NPY_NOSMP']
|
98 |
+
nosmp = 1
|
99 |
+
except KeyError:
|
100 |
+
nosmp = 0
|
101 |
+
return nosmp == 1
|
102 |
+
|
103 |
+
def win32_checks(deflist):
|
104 |
+
from numpy.distutils.misc_util import get_build_architecture
|
105 |
+
a = get_build_architecture()
|
106 |
+
|
107 |
+
# Distutils hack on AMD64 on windows
|
108 |
+
print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' %
|
109 |
+
(a, os.name, sys.platform))
|
110 |
+
if a == 'AMD64':
|
111 |
+
deflist.append('DISTUTILS_USE_SDK')
|
112 |
+
|
113 |
+
# On win32, force long double format string to be 'g', not
|
114 |
+
# 'Lg', since the MS runtime does not support long double whose
|
115 |
+
# size is > sizeof(double)
|
116 |
+
if a == "Intel" or a == "AMD64":
|
117 |
+
deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING')
|
118 |
+
|
119 |
+
def check_math_capabilities(config, moredefs, mathlibs):
|
120 |
+
def check_func(func_name):
|
121 |
+
return config.check_func(func_name, libraries=mathlibs,
|
122 |
+
decl=True, call=True)
|
123 |
+
|
124 |
+
def check_funcs_once(funcs_name):
|
125 |
+
decl = dict([(f, True) for f in funcs_name])
|
126 |
+
st = config.check_funcs_once(funcs_name, libraries=mathlibs,
|
127 |
+
decl=decl, call=decl)
|
128 |
+
if st:
|
129 |
+
moredefs.extend([(fname2def(f), 1) for f in funcs_name])
|
130 |
+
return st
|
131 |
+
|
132 |
+
def check_funcs(funcs_name):
|
133 |
+
# Use check_funcs_once first, and if it does not work, test func per
|
134 |
+
# func. Return success only if all the functions are available
|
135 |
+
if not check_funcs_once(funcs_name):
|
136 |
+
# Global check failed, check func per func
|
137 |
+
for f in funcs_name:
|
138 |
+
if check_func(f):
|
139 |
+
moredefs.append((fname2def(f), 1))
|
140 |
+
return 0
|
141 |
+
else:
|
142 |
+
return 1
|
143 |
+
|
144 |
+
#use_msvc = config.check_decl("_MSC_VER")
|
145 |
+
|
146 |
+
if not check_funcs_once(MANDATORY_FUNCS):
|
147 |
+
raise SystemError("One of the required function to build numpy is not"
|
148 |
+
" available (the list is %s)." % str(MANDATORY_FUNCS))
|
149 |
+
|
150 |
+
# Standard functions which may not be available and for which we have a
|
151 |
+
# replacement implementation. Note that some of these are C99 functions.
|
152 |
+
|
153 |
+
# XXX: hack to circumvent cpp pollution from python: python put its
|
154 |
+
# config.h in the public namespace, so we have a clash for the common
|
155 |
+
# functions we test. We remove every function tested by python's
|
156 |
+
# autoconf, hoping their own test are correct
|
157 |
+
for f in OPTIONAL_STDFUNCS_MAYBE:
|
158 |
+
if config.check_decl(fname2def(f),
|
159 |
+
headers=["Python.h", "math.h"]):
|
160 |
+
OPTIONAL_STDFUNCS.remove(f)
|
161 |
+
|
162 |
+
check_funcs(OPTIONAL_STDFUNCS)
|
163 |
+
|
164 |
+
for h in OPTIONAL_HEADERS:
|
165 |
+
if config.check_func("", decl=False, call=False, headers=[h]):
|
166 |
+
moredefs.append((fname2def(h).replace(".", "_"), 1))
|
167 |
+
|
168 |
+
for tup in OPTIONAL_INTRINSICS:
|
169 |
+
headers = None
|
170 |
+
if len(tup) == 2:
|
171 |
+
f, args = tup
|
172 |
+
else:
|
173 |
+
f, args, headers = tup[0], tup[1], [tup[2]]
|
174 |
+
if config.check_func(f, decl=False, call=True, call_args=args,
|
175 |
+
headers=headers):
|
176 |
+
moredefs.append((fname2def(f), 1))
|
177 |
+
|
178 |
+
for dec, fn in OPTIONAL_FUNCTION_ATTRIBUTES:
|
179 |
+
if config.check_func(fn, decl='int %s %s(void *);' % (dec, fn),
|
180 |
+
call=False):
|
181 |
+
moredefs.append((fname2def(fn), 1))
|
182 |
+
|
183 |
+
for fn in OPTIONAL_VARIABLE_ATTRIBUTES:
|
184 |
+
if config.check_func(fn, decl='int %s a;' % (fn), call=False):
|
185 |
+
m = fn.replace("(", "_").replace(")", "_")
|
186 |
+
moredefs.append((fname2def(m), 1))
|
187 |
+
|
188 |
+
# C99 functions: float and long double versions
|
189 |
+
check_funcs(C99_FUNCS_SINGLE)
|
190 |
+
check_funcs(C99_FUNCS_EXTENDED)
|
191 |
+
|
192 |
+
def check_complex(config, mathlibs):
|
193 |
+
priv = []
|
194 |
+
pub = []
|
195 |
+
|
196 |
+
try:
|
197 |
+
if os.uname()[0] == "Interix":
|
198 |
+
warnings.warn("Disabling broken complex support. See #1365")
|
199 |
+
return priv, pub
|
200 |
+
except:
|
201 |
+
# os.uname not available on all platforms. blanket except ugly but safe
|
202 |
+
pass
|
203 |
+
|
204 |
+
# Check for complex support
|
205 |
+
st = config.check_header('complex.h')
|
206 |
+
if st:
|
207 |
+
priv.append(('HAVE_COMPLEX_H', 1))
|
208 |
+
pub.append(('NPY_USE_C99_COMPLEX', 1))
|
209 |
+
|
210 |
+
for t in C99_COMPLEX_TYPES:
|
211 |
+
st = config.check_type(t, headers=["complex.h"])
|
212 |
+
if st:
|
213 |
+
pub.append(('NPY_HAVE_%s' % type2def(t), 1))
|
214 |
+
|
215 |
+
def check_prec(prec):
|
216 |
+
flist = [f + prec for f in C99_COMPLEX_FUNCS]
|
217 |
+
decl = dict([(f, True) for f in flist])
|
218 |
+
if not config.check_funcs_once(flist, call=decl, decl=decl,
|
219 |
+
libraries=mathlibs):
|
220 |
+
for f in flist:
|
221 |
+
if config.check_func(f, call=True, decl=True,
|
222 |
+
libraries=mathlibs):
|
223 |
+
priv.append((fname2def(f), 1))
|
224 |
+
else:
|
225 |
+
priv.extend([(fname2def(f), 1) for f in flist])
|
226 |
+
|
227 |
+
check_prec('')
|
228 |
+
check_prec('f')
|
229 |
+
check_prec('l')
|
230 |
+
|
231 |
+
return priv, pub
|
232 |
+
|
233 |
+
def check_ieee_macros(config):
|
234 |
+
priv = []
|
235 |
+
pub = []
|
236 |
+
|
237 |
+
macros = []
|
238 |
+
|
239 |
+
def _add_decl(f):
|
240 |
+
priv.append(fname2def("decl_%s" % f))
|
241 |
+
pub.append('NPY_%s' % fname2def("decl_%s" % f))
|
242 |
+
|
243 |
+
# XXX: hack to circumvent cpp pollution from python: python put its
|
244 |
+
# config.h in the public namespace, so we have a clash for the common
|
245 |
+
# functions we test. We remove every function tested by python's
|
246 |
+
# autoconf, hoping their own test are correct
|
247 |
+
_macros = ["isnan", "isinf", "signbit", "isfinite"]
|
248 |
+
for f in _macros:
|
249 |
+
py_symbol = fname2def("decl_%s" % f)
|
250 |
+
already_declared = config.check_decl(py_symbol,
|
251 |
+
headers=["Python.h", "math.h"])
|
252 |
+
if already_declared:
|
253 |
+
if config.check_macro_true(py_symbol,
|
254 |
+
headers=["Python.h", "math.h"]):
|
255 |
+
pub.append('NPY_%s' % fname2def("decl_%s" % f))
|
256 |
+
else:
|
257 |
+
macros.append(f)
|
258 |
+
# Normally, isnan and isinf are macro (C99), but some platforms only have
|
259 |
+
# func, or both func and macro version. Check for macro only, and define
|
260 |
+
# replacement ones if not found.
|
261 |
+
# Note: including Python.h is necessary because it modifies some math.h
|
262 |
+
# definitions
|
263 |
+
for f in macros:
|
264 |
+
st = config.check_decl(f, headers = ["Python.h", "math.h"])
|
265 |
+
if st:
|
266 |
+
_add_decl(f)
|
267 |
+
|
268 |
+
return priv, pub
|
269 |
+
|
270 |
+
def check_types(config_cmd, ext, build_dir):
|
271 |
+
private_defines = []
|
272 |
+
public_defines = []
|
273 |
+
|
274 |
+
# Expected size (in number of bytes) for each type. This is an
|
275 |
+
# optimization: those are only hints, and an exhaustive search for the size
|
276 |
+
# is done if the hints are wrong.
|
277 |
+
expected = {}
|
278 |
+
expected['short'] = [2]
|
279 |
+
expected['int'] = [4]
|
280 |
+
expected['long'] = [8, 4]
|
281 |
+
expected['float'] = [4]
|
282 |
+
expected['double'] = [8]
|
283 |
+
expected['long double'] = [8, 12, 16]
|
284 |
+
expected['Py_intptr_t'] = [4, 8]
|
285 |
+
expected['PY_LONG_LONG'] = [8]
|
286 |
+
expected['long long'] = [8]
|
287 |
+
expected['off_t'] = [4, 8]
|
288 |
+
|
289 |
+
# Check we have the python header (-dev* packages on Linux)
|
290 |
+
result = config_cmd.check_header('Python.h')
|
291 |
+
if not result:
|
292 |
+
raise SystemError(
|
293 |
+
"Cannot compile 'Python.h'. Perhaps you need to "\
|
294 |
+
"install python-dev|python-devel.")
|
295 |
+
res = config_cmd.check_header("endian.h")
|
296 |
+
if res:
|
297 |
+
private_defines.append(('HAVE_ENDIAN_H', 1))
|
298 |
+
public_defines.append(('NPY_HAVE_ENDIAN_H', 1))
|
299 |
+
|
300 |
+
# Check basic types sizes
|
301 |
+
for type in ('short', 'int', 'long'):
|
302 |
+
res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"])
|
303 |
+
if res:
|
304 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type)))
|
305 |
+
else:
|
306 |
+
res = config_cmd.check_type_size(type, expected=expected[type])
|
307 |
+
if res >= 0:
|
308 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
|
309 |
+
else:
|
310 |
+
raise SystemError("Checking sizeof (%s) failed !" % type)
|
311 |
+
|
312 |
+
for type in ('float', 'double', 'long double'):
|
313 |
+
already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type),
|
314 |
+
headers = ["Python.h"])
|
315 |
+
res = config_cmd.check_type_size(type, expected=expected[type])
|
316 |
+
if res >= 0:
|
317 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
|
318 |
+
if not already_declared and not type == 'long double':
|
319 |
+
private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
|
320 |
+
else:
|
321 |
+
raise SystemError("Checking sizeof (%s) failed !" % type)
|
322 |
+
|
323 |
+
# Compute size of corresponding complex type: used to check that our
|
324 |
+
# definition is binary compatible with C99 complex type (check done at
|
325 |
+
# build time in npy_common.h)
|
326 |
+
complex_def = "struct {%s __x; %s __y;}" % (type, type)
|
327 |
+
res = config_cmd.check_type_size(complex_def, expected=2*expected[type])
|
328 |
+
if res >= 0:
|
329 |
+
public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res))
|
330 |
+
else:
|
331 |
+
raise SystemError("Checking sizeof (%s) failed !" % complex_def)
|
332 |
+
|
333 |
+
|
334 |
+
for type in ('Py_intptr_t', 'off_t'):
|
335 |
+
res = config_cmd.check_type_size(type, headers=["Python.h"],
|
336 |
+
library_dirs=[pythonlib_dir()],
|
337 |
+
expected=expected[type])
|
338 |
+
|
339 |
+
if res >= 0:
|
340 |
+
private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res))
|
341 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res))
|
342 |
+
else:
|
343 |
+
raise SystemError("Checking sizeof (%s) failed !" % type)
|
344 |
+
|
345 |
+
# We check declaration AND type because that's how distutils does it.
|
346 |
+
if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']):
|
347 |
+
res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'],
|
348 |
+
library_dirs=[pythonlib_dir()],
|
349 |
+
expected=expected['PY_LONG_LONG'])
|
350 |
+
if res >= 0:
|
351 |
+
private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
|
352 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res))
|
353 |
+
else:
|
354 |
+
raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG')
|
355 |
+
|
356 |
+
res = config_cmd.check_type_size('long long',
|
357 |
+
expected=expected['long long'])
|
358 |
+
if res >= 0:
|
359 |
+
#private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res))
|
360 |
+
public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res))
|
361 |
+
else:
|
362 |
+
raise SystemError("Checking sizeof (%s) failed !" % 'long long')
|
363 |
+
|
364 |
+
if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']):
|
365 |
+
raise RuntimeError(
|
366 |
+
"Config wo CHAR_BIT is not supported"\
|
367 |
+
", please contact the maintainers")
|
368 |
+
|
369 |
+
return private_defines, public_defines
|
370 |
+
|
371 |
+
def check_mathlib(config_cmd):
|
372 |
+
# Testing the C math library
|
373 |
+
mathlibs = []
|
374 |
+
mathlibs_choices = [[], ['m'], ['cpml']]
|
375 |
+
mathlib = os.environ.get('MATHLIB')
|
376 |
+
if mathlib:
|
377 |
+
mathlibs_choices.insert(0, mathlib.split(','))
|
378 |
+
for libs in mathlibs_choices:
|
379 |
+
if config_cmd.check_func("exp", libraries=libs, decl=True, call=True):
|
380 |
+
mathlibs = libs
|
381 |
+
break
|
382 |
+
else:
|
383 |
+
raise EnvironmentError("math library missing; rerun "
|
384 |
+
"setup.py after setting the "
|
385 |
+
"MATHLIB env variable")
|
386 |
+
return mathlibs
|
387 |
+
|
388 |
+
def visibility_define(config):
|
389 |
+
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
|
390 |
+
string)."""
|
391 |
+
if config.check_compiler_gcc4():
|
392 |
+
return '__attribute__((visibility("hidden")))'
|
393 |
+
else:
|
394 |
+
return ''
|
395 |
+
|
396 |
+
def configuration(parent_package='',top_path=None):
|
397 |
+
from numpy.distutils.misc_util import Configuration, dot_join
|
398 |
+
from numpy.distutils.system_info import get_info, default_lib_dirs
|
399 |
+
|
400 |
+
config = Configuration('core', parent_package, top_path)
|
401 |
+
local_dir = config.local_path
|
402 |
+
codegen_dir = join(local_dir, 'code_generators')
|
403 |
+
|
404 |
+
if is_released(config):
|
405 |
+
warnings.simplefilter('error', MismatchCAPIWarning)
|
406 |
+
|
407 |
+
# Check whether we have a mismatch between the set C API VERSION and the
|
408 |
+
# actual C API VERSION
|
409 |
+
check_api_version(C_API_VERSION, codegen_dir)
|
410 |
+
|
411 |
+
generate_umath_py = join(codegen_dir, 'generate_umath.py')
|
412 |
+
n = dot_join(config.name, 'generate_umath')
|
413 |
+
generate_umath = imp.load_module('_'.join(n.split('.')),
|
414 |
+
open(generate_umath_py, 'U'), generate_umath_py,
|
415 |
+
('.py', 'U', 1))
|
416 |
+
|
417 |
+
header_dir = 'include/numpy' # this is relative to config.path_in_package
|
418 |
+
|
419 |
+
cocache = CallOnceOnly()
|
420 |
+
|
421 |
+
def generate_config_h(ext, build_dir):
|
422 |
+
target = join(build_dir, header_dir, 'config.h')
|
423 |
+
d = os.path.dirname(target)
|
424 |
+
if not os.path.exists(d):
|
425 |
+
os.makedirs(d)
|
426 |
+
|
427 |
+
if newer(__file__, target):
|
428 |
+
config_cmd = config.get_config_cmd()
|
429 |
+
log.info('Generating %s', target)
|
430 |
+
|
431 |
+
# Check sizeof
|
432 |
+
moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir)
|
433 |
+
|
434 |
+
# Check math library and C99 math funcs availability
|
435 |
+
mathlibs = check_mathlib(config_cmd)
|
436 |
+
moredefs.append(('MATHLIB', ','.join(mathlibs)))
|
437 |
+
|
438 |
+
check_math_capabilities(config_cmd, moredefs, mathlibs)
|
439 |
+
moredefs.extend(cocache.check_ieee_macros(config_cmd)[0])
|
440 |
+
moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0])
|
441 |
+
|
442 |
+
# Signal check
|
443 |
+
if is_npy_no_signal():
|
444 |
+
moredefs.append('__NPY_PRIVATE_NO_SIGNAL')
|
445 |
+
|
446 |
+
# Windows checks
|
447 |
+
if sys.platform=='win32' or os.name=='nt':
|
448 |
+
win32_checks(moredefs)
|
449 |
+
|
450 |
+
# Inline check
|
451 |
+
inline = config_cmd.check_inline()
|
452 |
+
|
453 |
+
# Check whether we need our own wide character support
|
454 |
+
if not config_cmd.check_decl('Py_UNICODE_WIDE', headers=['Python.h']):
|
455 |
+
PYTHON_HAS_UNICODE_WIDE = True
|
456 |
+
else:
|
457 |
+
PYTHON_HAS_UNICODE_WIDE = False
|
458 |
+
|
459 |
+
if ENABLE_SEPARATE_COMPILATION:
|
460 |
+
moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1))
|
461 |
+
|
462 |
+
if NPY_RELAXED_STRIDES_CHECKING:
|
463 |
+
moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
|
464 |
+
|
465 |
+
# Get long double representation
|
466 |
+
if sys.platform != 'darwin':
|
467 |
+
rep = check_long_double_representation(config_cmd)
|
468 |
+
if rep in ['INTEL_EXTENDED_12_BYTES_LE',
|
469 |
+
'INTEL_EXTENDED_16_BYTES_LE',
|
470 |
+
'MOTOROLA_EXTENDED_12_BYTES_BE',
|
471 |
+
'IEEE_QUAD_LE', 'IEEE_QUAD_BE',
|
472 |
+
'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE',
|
473 |
+
'DOUBLE_DOUBLE_BE', 'DOUBLE_DOUBLE_LE']:
|
474 |
+
moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1))
|
475 |
+
else:
|
476 |
+
raise ValueError("Unrecognized long double format: %s" % rep)
|
477 |
+
|
478 |
+
# Py3K check
|
479 |
+
if sys.version_info[0] == 3:
|
480 |
+
moredefs.append(('NPY_PY3K', 1))
|
481 |
+
|
482 |
+
# Generate the config.h file from moredefs
|
483 |
+
target_f = open(target, 'w')
|
484 |
+
for d in moredefs:
|
485 |
+
if isinstance(d, str):
|
486 |
+
target_f.write('#define %s\n' % (d))
|
487 |
+
else:
|
488 |
+
target_f.write('#define %s %s\n' % (d[0], d[1]))
|
489 |
+
|
490 |
+
# define inline to our keyword, or nothing
|
491 |
+
target_f.write('#ifndef __cplusplus\n')
|
492 |
+
if inline == 'inline':
|
493 |
+
target_f.write('/* #undef inline */\n')
|
494 |
+
else:
|
495 |
+
target_f.write('#define inline %s\n' % inline)
|
496 |
+
target_f.write('#endif\n')
|
497 |
+
|
498 |
+
# add the guard to make sure config.h is never included directly,
|
499 |
+
# but always through npy_config.h
|
500 |
+
target_f.write("""
|
501 |
+
#ifndef _NPY_NPY_CONFIG_H_
|
502 |
+
#error config.h should never be included directly, include npy_config.h instead
|
503 |
+
#endif
|
504 |
+
""")
|
505 |
+
|
506 |
+
target_f.close()
|
507 |
+
print('File:', target)
|
508 |
+
target_f = open(target)
|
509 |
+
print(target_f.read())
|
510 |
+
target_f.close()
|
511 |
+
print('EOF')
|
512 |
+
else:
|
513 |
+
mathlibs = []
|
514 |
+
target_f = open(target)
|
515 |
+
for line in target_f:
|
516 |
+
s = '#define MATHLIB'
|
517 |
+
if line.startswith(s):
|
518 |
+
value = line[len(s):].strip()
|
519 |
+
if value:
|
520 |
+
mathlibs.extend(value.split(','))
|
521 |
+
target_f.close()
|
522 |
+
|
523 |
+
# Ugly: this can be called within a library and not an extension,
|
524 |
+
# in which case there is no libraries attributes (and none is
|
525 |
+
# needed).
|
526 |
+
if hasattr(ext, 'libraries'):
|
527 |
+
ext.libraries.extend(mathlibs)
|
528 |
+
|
529 |
+
incl_dir = os.path.dirname(target)
|
530 |
+
if incl_dir not in config.numpy_include_dirs:
|
531 |
+
config.numpy_include_dirs.append(incl_dir)
|
532 |
+
|
533 |
+
return target
|
534 |
+
|
535 |
+
def generate_numpyconfig_h(ext, build_dir):
|
536 |
+
"""Depends on config.h: generate_config_h has to be called before !"""
|
537 |
+
# put private include directory in build_dir on search path
|
538 |
+
# allows using code generation in headers headers
|
539 |
+
config.add_include_dirs(join(build_dir, "src", "private"))
|
540 |
+
|
541 |
+
target = join(build_dir, header_dir, '_numpyconfig.h')
|
542 |
+
d = os.path.dirname(target)
|
543 |
+
if not os.path.exists(d):
|
544 |
+
os.makedirs(d)
|
545 |
+
if newer(__file__, target):
|
546 |
+
config_cmd = config.get_config_cmd()
|
547 |
+
log.info('Generating %s', target)
|
548 |
+
|
549 |
+
# Check sizeof
|
550 |
+
ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir)
|
551 |
+
|
552 |
+
if is_npy_no_signal():
|
553 |
+
moredefs.append(('NPY_NO_SIGNAL', 1))
|
554 |
+
|
555 |
+
if is_npy_no_smp():
|
556 |
+
moredefs.append(('NPY_NO_SMP', 1))
|
557 |
+
else:
|
558 |
+
moredefs.append(('NPY_NO_SMP', 0))
|
559 |
+
|
560 |
+
mathlibs = check_mathlib(config_cmd)
|
561 |
+
moredefs.extend(cocache.check_ieee_macros(config_cmd)[1])
|
562 |
+
moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1])
|
563 |
+
|
564 |
+
if ENABLE_SEPARATE_COMPILATION:
|
565 |
+
moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1))
|
566 |
+
|
567 |
+
if NPY_RELAXED_STRIDES_CHECKING:
|
568 |
+
moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1))
|
569 |
+
|
570 |
+
# Check wether we can use inttypes (C99) formats
|
571 |
+
if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']):
|
572 |
+
moredefs.append(('NPY_USE_C99_FORMATS', 1))
|
573 |
+
|
574 |
+
# visibility check
|
575 |
+
hidden_visibility = visibility_define(config_cmd)
|
576 |
+
moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility))
|
577 |
+
|
578 |
+
# Add the C API/ABI versions
|
579 |
+
moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION))
|
580 |
+
moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION))
|
581 |
+
|
582 |
+
# Add moredefs to header
|
583 |
+
target_f = open(target, 'w')
|
584 |
+
for d in moredefs:
|
585 |
+
if isinstance(d, str):
|
586 |
+
target_f.write('#define %s\n' % (d))
|
587 |
+
else:
|
588 |
+
target_f.write('#define %s %s\n' % (d[0], d[1]))
|
589 |
+
|
590 |
+
# Define __STDC_FORMAT_MACROS
|
591 |
+
target_f.write("""
|
592 |
+
#ifndef __STDC_FORMAT_MACROS
|
593 |
+
#define __STDC_FORMAT_MACROS 1
|
594 |
+
#endif
|
595 |
+
""")
|
596 |
+
target_f.close()
|
597 |
+
|
598 |
+
# Dump the numpyconfig.h header to stdout
|
599 |
+
print('File: %s' % target)
|
600 |
+
target_f = open(target)
|
601 |
+
print(target_f.read())
|
602 |
+
target_f.close()
|
603 |
+
print('EOF')
|
604 |
+
config.add_data_files((header_dir, target))
|
605 |
+
return target
|
606 |
+
|
607 |
+
def generate_api_func(module_name):
|
608 |
+
def generate_api(ext, build_dir):
|
609 |
+
script = join(codegen_dir, module_name + '.py')
|
610 |
+
sys.path.insert(0, codegen_dir)
|
611 |
+
try:
|
612 |
+
m = __import__(module_name)
|
613 |
+
log.info('executing %s', script)
|
614 |
+
h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir))
|
615 |
+
finally:
|
616 |
+
del sys.path[0]
|
617 |
+
config.add_data_files((header_dir, h_file),
|
618 |
+
(header_dir, doc_file))
|
619 |
+
return (h_file,)
|
620 |
+
return generate_api
|
621 |
+
|
622 |
+
generate_numpy_api = generate_api_func('generate_numpy_api')
|
623 |
+
generate_ufunc_api = generate_api_func('generate_ufunc_api')
|
624 |
+
|
625 |
+
config.add_include_dirs(join(local_dir, "src", "private"))
|
626 |
+
config.add_include_dirs(join(local_dir, "src"))
|
627 |
+
config.add_include_dirs(join(local_dir))
|
628 |
+
|
629 |
+
config.add_data_files('include/numpy/*.h')
|
630 |
+
config.add_include_dirs(join('src', 'npymath'))
|
631 |
+
config.add_include_dirs(join('src', 'multiarray'))
|
632 |
+
config.add_include_dirs(join('src', 'umath'))
|
633 |
+
config.add_include_dirs(join('src', 'npysort'))
|
634 |
+
|
635 |
+
config.add_define_macros([("HAVE_NPY_CONFIG_H", "1")])
|
636 |
+
config.add_define_macros([("_FILE_OFFSET_BITS", "64")])
|
637 |
+
config.add_define_macros([('_LARGEFILE_SOURCE', '1')])
|
638 |
+
config.add_define_macros([('_LARGEFILE64_SOURCE', '1')])
|
639 |
+
|
640 |
+
config.numpy_include_dirs.extend(config.paths('include'))
|
641 |
+
|
642 |
+
deps = [join('src', 'npymath', '_signbit.c'),
|
643 |
+
join('include', 'numpy', '*object.h'),
|
644 |
+
'include/numpy/fenv/fenv.c',
|
645 |
+
'include/numpy/fenv/fenv.h',
|
646 |
+
join(codegen_dir, 'genapi.py'),
|
647 |
+
]
|
648 |
+
|
649 |
+
# Don't install fenv unless we need them.
|
650 |
+
if sys.platform == 'cygwin':
|
651 |
+
config.add_data_dir('include/numpy/fenv')
|
652 |
+
|
653 |
+
#######################################################################
|
654 |
+
# dummy module #
|
655 |
+
#######################################################################
|
656 |
+
|
657 |
+
# npymath needs the config.h and numpyconfig.h files to be generated, but
|
658 |
+
# build_clib cannot handle generate_config_h and generate_numpyconfig_h
|
659 |
+
# (don't ask). Because clib are generated before extensions, we have to
|
660 |
+
# explicitly add an extension which has generate_config_h and
|
661 |
+
# generate_numpyconfig_h as sources *before* adding npymath.
|
662 |
+
|
663 |
+
config.add_extension('_dummy',
|
664 |
+
sources = [join('src', 'dummymodule.c'),
|
665 |
+
generate_config_h,
|
666 |
+
generate_numpyconfig_h,
|
667 |
+
generate_numpy_api]
|
668 |
+
)
|
669 |
+
|
670 |
+
#######################################################################
|
671 |
+
# npymath library #
|
672 |
+
#######################################################################
|
673 |
+
|
674 |
+
subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")])
|
675 |
+
def get_mathlib_info(*args):
|
676 |
+
# Another ugly hack: the mathlib info is known once build_src is run,
|
677 |
+
# but we cannot use add_installed_pkg_config here either, so we only
|
678 |
+
# update the substition dictionary during npymath build
|
679 |
+
config_cmd = config.get_config_cmd()
|
680 |
+
|
681 |
+
# Check that the toolchain works, to fail early if it doesn't
|
682 |
+
# (avoid late errors with MATHLIB which are confusing if the
|
683 |
+
# compiler does not work).
|
684 |
+
st = config_cmd.try_link('int main(void) { return 0;}')
|
685 |
+
if not st:
|
686 |
+
raise RuntimeError("Broken toolchain: cannot link a simple C program")
|
687 |
+
mlibs = check_mathlib(config_cmd)
|
688 |
+
|
689 |
+
posix_mlib = ' '.join(['-l%s' % l for l in mlibs])
|
690 |
+
msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs])
|
691 |
+
subst_dict["posix_mathlib"] = posix_mlib
|
692 |
+
subst_dict["msvc_mathlib"] = msvc_mlib
|
693 |
+
|
694 |
+
npymath_sources = [join('src', 'npymath', 'npy_math.c.src'),
|
695 |
+
join('src', 'npymath', 'ieee754.c.src'),
|
696 |
+
join('src', 'npymath', 'npy_math_complex.c.src'),
|
697 |
+
join('src', 'npymath', 'halffloat.c')]
|
698 |
+
config.add_installed_library('npymath',
|
699 |
+
sources=npymath_sources + [get_mathlib_info],
|
700 |
+
install_dir='lib')
|
701 |
+
config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config",
|
702 |
+
subst_dict)
|
703 |
+
config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config",
|
704 |
+
subst_dict)
|
705 |
+
|
706 |
+
#######################################################################
|
707 |
+
# npysort library #
|
708 |
+
#######################################################################
|
709 |
+
|
710 |
+
# This library is created for the build but it is not installed
|
711 |
+
npysort_sources=[join('src', 'npysort', 'quicksort.c.src'),
|
712 |
+
join('src', 'npysort', 'mergesort.c.src'),
|
713 |
+
join('src', 'npysort', 'heapsort.c.src'),
|
714 |
+
join('src', 'private', 'npy_partition.h.src'),
|
715 |
+
join('src', 'npysort', 'selection.c.src'),
|
716 |
+
join('src', 'private', 'npy_binsearch.h.src'),
|
717 |
+
join('src', 'npysort', 'binsearch.c.src'),
|
718 |
+
]
|
719 |
+
config.add_library('npysort',
|
720 |
+
sources=npysort_sources,
|
721 |
+
include_dirs=[])
|
722 |
+
|
723 |
+
|
724 |
+
#######################################################################
|
725 |
+
# multiarray module #
|
726 |
+
#######################################################################
|
727 |
+
|
728 |
+
# Multiarray version: this function is needed to build foo.c from foo.c.src
|
729 |
+
# when foo.c is included in another file and as such not in the src
|
730 |
+
# argument of build_ext command
|
731 |
+
def generate_multiarray_templated_sources(ext, build_dir):
|
732 |
+
from numpy.distutils.misc_util import get_cmd
|
733 |
+
|
734 |
+
subpath = join('src', 'multiarray')
|
735 |
+
sources = [join(local_dir, subpath, 'scalartypes.c.src'),
|
736 |
+
join(local_dir, subpath, 'arraytypes.c.src'),
|
737 |
+
join(local_dir, subpath, 'nditer_templ.c.src'),
|
738 |
+
join(local_dir, subpath, 'lowlevel_strided_loops.c.src'),
|
739 |
+
join(local_dir, subpath, 'einsum.c.src')]
|
740 |
+
|
741 |
+
# numpy.distutils generate .c from .c.src in weird directories, we have
|
742 |
+
# to add them there as they depend on the build_dir
|
743 |
+
config.add_include_dirs(join(build_dir, subpath))
|
744 |
+
cmd = get_cmd('build_src')
|
745 |
+
cmd.ensure_finalized()
|
746 |
+
cmd.template_sources(sources, ext)
|
747 |
+
|
748 |
+
multiarray_deps = [
|
749 |
+
join('src', 'multiarray', 'arrayobject.h'),
|
750 |
+
join('src', 'multiarray', 'arraytypes.h'),
|
751 |
+
join('src', 'multiarray', 'array_assign.h'),
|
752 |
+
join('src', 'multiarray', 'buffer.h'),
|
753 |
+
join('src', 'multiarray', 'calculation.h'),
|
754 |
+
join('src', 'multiarray', 'common.h'),
|
755 |
+
join('src', 'multiarray', 'convert_datatype.h'),
|
756 |
+
join('src', 'multiarray', 'convert.h'),
|
757 |
+
join('src', 'multiarray', 'conversion_utils.h'),
|
758 |
+
join('src', 'multiarray', 'ctors.h'),
|
759 |
+
join('src', 'multiarray', 'descriptor.h'),
|
760 |
+
join('src', 'multiarray', 'getset.h'),
|
761 |
+
join('src', 'multiarray', 'hashdescr.h'),
|
762 |
+
join('src', 'multiarray', 'iterators.h'),
|
763 |
+
join('src', 'multiarray', 'mapping.h'),
|
764 |
+
join('src', 'multiarray', 'methods.h'),
|
765 |
+
join('src', 'multiarray', 'multiarraymodule.h'),
|
766 |
+
join('src', 'multiarray', 'nditer_impl.h'),
|
767 |
+
join('src', 'multiarray', 'numpymemoryview.h'),
|
768 |
+
join('src', 'multiarray', 'number.h'),
|
769 |
+
join('src', 'multiarray', 'numpyos.h'),
|
770 |
+
join('src', 'multiarray', 'refcount.h'),
|
771 |
+
join('src', 'multiarray', 'scalartypes.h'),
|
772 |
+
join('src', 'multiarray', 'sequence.h'),
|
773 |
+
join('src', 'multiarray', 'shape.h'),
|
774 |
+
join('src', 'multiarray', 'ucsnarrow.h'),
|
775 |
+
join('src', 'multiarray', 'usertypes.h'),
|
776 |
+
join('src', 'private', 'lowlevel_strided_loops.h'),
|
777 |
+
join('include', 'numpy', 'arrayobject.h'),
|
778 |
+
join('include', 'numpy', '_neighborhood_iterator_imp.h'),
|
779 |
+
join('include', 'numpy', 'npy_endian.h'),
|
780 |
+
join('include', 'numpy', 'arrayscalars.h'),
|
781 |
+
join('include', 'numpy', 'noprefix.h'),
|
782 |
+
join('include', 'numpy', 'npy_interrupt.h'),
|
783 |
+
join('include', 'numpy', 'npy_3kcompat.h'),
|
784 |
+
join('include', 'numpy', 'npy_math.h'),
|
785 |
+
join('include', 'numpy', 'halffloat.h'),
|
786 |
+
join('include', 'numpy', 'npy_common.h'),
|
787 |
+
join('include', 'numpy', 'npy_os.h'),
|
788 |
+
join('include', 'numpy', 'utils.h'),
|
789 |
+
join('include', 'numpy', 'ndarrayobject.h'),
|
790 |
+
join('include', 'numpy', 'npy_cpu.h'),
|
791 |
+
join('include', 'numpy', 'numpyconfig.h'),
|
792 |
+
join('include', 'numpy', 'ndarraytypes.h'),
|
793 |
+
join('include', 'numpy', 'npy_1_7_deprecated_api.h'),
|
794 |
+
join('include', 'numpy', '_numpyconfig.h.in'),
|
795 |
+
# add library sources as distuils does not consider libraries
|
796 |
+
# dependencies
|
797 |
+
] + npysort_sources + npymath_sources
|
798 |
+
|
799 |
+
multiarray_src = [
|
800 |
+
join('src', 'multiarray', 'alloc.c'),
|
801 |
+
join('src', 'multiarray', 'arrayobject.c'),
|
802 |
+
join('src', 'multiarray', 'arraytypes.c.src'),
|
803 |
+
join('src', 'multiarray', 'array_assign.c'),
|
804 |
+
join('src', 'multiarray', 'array_assign_scalar.c'),
|
805 |
+
join('src', 'multiarray', 'array_assign_array.c'),
|
806 |
+
join('src', 'multiarray', 'buffer.c'),
|
807 |
+
join('src', 'multiarray', 'calculation.c'),
|
808 |
+
join('src', 'multiarray', 'common.c'),
|
809 |
+
join('src', 'multiarray', 'convert.c'),
|
810 |
+
join('src', 'multiarray', 'convert_datatype.c'),
|
811 |
+
join('src', 'multiarray', 'conversion_utils.c'),
|
812 |
+
join('src', 'multiarray', 'ctors.c'),
|
813 |
+
join('src', 'multiarray', 'datetime.c'),
|
814 |
+
join('src', 'multiarray', 'datetime_strings.c'),
|
815 |
+
join('src', 'multiarray', 'datetime_busday.c'),
|
816 |
+
join('src', 'multiarray', 'datetime_busdaycal.c'),
|
817 |
+
join('src', 'multiarray', 'descriptor.c'),
|
818 |
+
join('src', 'multiarray', 'dtype_transfer.c'),
|
819 |
+
join('src', 'multiarray', 'einsum.c.src'),
|
820 |
+
join('src', 'multiarray', 'flagsobject.c'),
|
821 |
+
join('src', 'multiarray', 'getset.c'),
|
822 |
+
join('src', 'multiarray', 'hashdescr.c'),
|
823 |
+
join('src', 'multiarray', 'item_selection.c'),
|
824 |
+
join('src', 'multiarray', 'iterators.c'),
|
825 |
+
join('src', 'multiarray', 'lowlevel_strided_loops.c.src'),
|
826 |
+
join('src', 'multiarray', 'mapping.c'),
|
827 |
+
join('src', 'multiarray', 'methods.c'),
|
828 |
+
join('src', 'multiarray', 'multiarraymodule.c'),
|
829 |
+
join('src', 'multiarray', 'nditer_templ.c.src'),
|
830 |
+
join('src', 'multiarray', 'nditer_api.c'),
|
831 |
+
join('src', 'multiarray', 'nditer_constr.c'),
|
832 |
+
join('src', 'multiarray', 'nditer_pywrap.c'),
|
833 |
+
join('src', 'multiarray', 'number.c'),
|
834 |
+
join('src', 'multiarray', 'numpymemoryview.c'),
|
835 |
+
join('src', 'multiarray', 'numpyos.c'),
|
836 |
+
join('src', 'multiarray', 'refcount.c'),
|
837 |
+
join('src', 'multiarray', 'sequence.c'),
|
838 |
+
join('src', 'multiarray', 'shape.c'),
|
839 |
+
join('src', 'multiarray', 'scalarapi.c'),
|
840 |
+
join('src', 'multiarray', 'scalartypes.c.src'),
|
841 |
+
join('src', 'multiarray', 'usertypes.c'),
|
842 |
+
join('src', 'multiarray', 'ucsnarrow.c')]
|
843 |
+
|
844 |
+
|
845 |
+
if not ENABLE_SEPARATE_COMPILATION:
|
846 |
+
multiarray_deps.extend(multiarray_src)
|
847 |
+
multiarray_src = [join('src', 'multiarray', 'multiarraymodule_onefile.c')]
|
848 |
+
multiarray_src.append(generate_multiarray_templated_sources)
|
849 |
+
|
850 |
+
config.add_extension('multiarray',
|
851 |
+
sources = multiarray_src +
|
852 |
+
[generate_config_h,
|
853 |
+
generate_numpyconfig_h,
|
854 |
+
generate_numpy_api,
|
855 |
+
join(codegen_dir, 'generate_numpy_api.py'),
|
856 |
+
join('*.py')],
|
857 |
+
depends = deps + multiarray_deps,
|
858 |
+
libraries = ['npymath', 'npysort'])
|
859 |
+
|
860 |
+
#######################################################################
|
861 |
+
# umath module #
|
862 |
+
#######################################################################
|
863 |
+
|
864 |
+
# umath version: this function is needed to build foo.c from foo.c.src
|
865 |
+
# when foo.c is included in another file and as such not in the src
|
866 |
+
# argument of build_ext command
|
867 |
+
def generate_umath_templated_sources(ext, build_dir):
|
868 |
+
from numpy.distutils.misc_util import get_cmd
|
869 |
+
|
870 |
+
subpath = join('src', 'umath')
|
871 |
+
sources = [
|
872 |
+
join(local_dir, subpath, 'loops.h.src'),
|
873 |
+
join(local_dir, subpath, 'loops.c.src'),
|
874 |
+
join(local_dir, subpath, 'simd.inc.src')]
|
875 |
+
|
876 |
+
# numpy.distutils generate .c from .c.src in weird directories, we have
|
877 |
+
# to add them there as they depend on the build_dir
|
878 |
+
config.add_include_dirs(join(build_dir, subpath))
|
879 |
+
cmd = get_cmd('build_src')
|
880 |
+
cmd.ensure_finalized()
|
881 |
+
cmd.template_sources(sources, ext)
|
882 |
+
|
883 |
+
|
884 |
+
def generate_umath_c(ext, build_dir):
|
885 |
+
target = join(build_dir, header_dir, '__umath_generated.c')
|
886 |
+
dir = os.path.dirname(target)
|
887 |
+
if not os.path.exists(dir):
|
888 |
+
os.makedirs(dir)
|
889 |
+
script = generate_umath_py
|
890 |
+
if newer(script, target):
|
891 |
+
f = open(target, 'w')
|
892 |
+
f.write(generate_umath.make_code(generate_umath.defdict,
|
893 |
+
generate_umath.__file__))
|
894 |
+
f.close()
|
895 |
+
return []
|
896 |
+
|
897 |
+
umath_src = [
|
898 |
+
join('src', 'umath', 'umathmodule.c'),
|
899 |
+
join('src', 'umath', 'reduction.c'),
|
900 |
+
join('src', 'umath', 'funcs.inc.src'),
|
901 |
+
join('src', 'umath', 'simd.inc.src'),
|
902 |
+
join('src', 'umath', 'loops.h.src'),
|
903 |
+
join('src', 'umath', 'loops.c.src'),
|
904 |
+
join('src', 'umath', 'ufunc_object.c'),
|
905 |
+
join('src', 'umath', 'ufunc_type_resolution.c')]
|
906 |
+
|
907 |
+
umath_deps = [
|
908 |
+
generate_umath_py,
|
909 |
+
join('src', 'multiarray', 'common.h'),
|
910 |
+
join('src', 'umath', 'simd.inc.src'),
|
911 |
+
join(codegen_dir, 'generate_ufunc_api.py'),
|
912 |
+
join('src', 'private', 'ufunc_override.h')] + npymath_sources
|
913 |
+
|
914 |
+
if not ENABLE_SEPARATE_COMPILATION:
|
915 |
+
umath_deps.extend(umath_src)
|
916 |
+
umath_src = [join('src', 'umath', 'umathmodule_onefile.c')]
|
917 |
+
umath_src.append(generate_umath_templated_sources)
|
918 |
+
umath_src.append(join('src', 'umath', 'funcs.inc.src'))
|
919 |
+
umath_src.append(join('src', 'umath', 'simd.inc.src'))
|
920 |
+
|
921 |
+
config.add_extension('umath',
|
922 |
+
sources = umath_src +
|
923 |
+
[generate_config_h,
|
924 |
+
generate_numpyconfig_h,
|
925 |
+
generate_umath_c,
|
926 |
+
generate_ufunc_api],
|
927 |
+
depends = deps + umath_deps,
|
928 |
+
libraries = ['npymath'],
|
929 |
+
)
|
930 |
+
|
931 |
+
#######################################################################
|
932 |
+
# scalarmath module #
|
933 |
+
#######################################################################
|
934 |
+
|
935 |
+
config.add_extension('scalarmath',
|
936 |
+
sources = [join('src', 'scalarmathmodule.c.src'),
|
937 |
+
join('src', 'private', 'scalarmathmodule.h.src'),
|
938 |
+
generate_config_h,
|
939 |
+
generate_numpyconfig_h,
|
940 |
+
generate_numpy_api,
|
941 |
+
generate_ufunc_api],
|
942 |
+
depends = deps + npymath_sources,
|
943 |
+
libraries = ['npymath'],
|
944 |
+
)
|
945 |
+
|
946 |
+
#######################################################################
|
947 |
+
# _dotblas module #
|
948 |
+
#######################################################################
|
949 |
+
|
950 |
+
# Configure blasdot
|
951 |
+
blas_info = get_info('blas_opt', 0)
|
952 |
+
#blas_info = {}
|
953 |
+
def get_dotblas_sources(ext, build_dir):
|
954 |
+
if blas_info:
|
955 |
+
if ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', []):
|
956 |
+
return None # dotblas needs ATLAS, Fortran compiled blas will not be sufficient.
|
957 |
+
return ext.depends[:1]
|
958 |
+
return None # no extension module will be built
|
959 |
+
|
960 |
+
config.add_extension('_dotblas',
|
961 |
+
sources = [get_dotblas_sources],
|
962 |
+
depends = [join('blasdot', '_dotblas.c'),
|
963 |
+
join('blasdot', 'cblas.h'),
|
964 |
+
],
|
965 |
+
include_dirs = ['blasdot'],
|
966 |
+
extra_info = blas_info
|
967 |
+
)
|
968 |
+
|
969 |
+
#######################################################################
|
970 |
+
# umath_tests module #
|
971 |
+
#######################################################################
|
972 |
+
|
973 |
+
config.add_extension('umath_tests',
|
974 |
+
sources = [join('src', 'umath', 'umath_tests.c.src')])
|
975 |
+
|
976 |
+
#######################################################################
|
977 |
+
# custom rational dtype module #
|
978 |
+
#######################################################################
|
979 |
+
|
980 |
+
config.add_extension('test_rational',
|
981 |
+
sources = [join('src', 'umath', 'test_rational.c.src')])
|
982 |
+
|
983 |
+
#######################################################################
|
984 |
+
# struct_ufunc_test module #
|
985 |
+
#######################################################################
|
986 |
+
|
987 |
+
config.add_extension('struct_ufunc_test',
|
988 |
+
sources = [join('src', 'umath', 'struct_ufunc_test.c.src')])
|
989 |
+
|
990 |
+
#######################################################################
|
991 |
+
# multiarray_tests module #
|
992 |
+
#######################################################################
|
993 |
+
|
994 |
+
config.add_extension('multiarray_tests',
|
995 |
+
sources = [join('src', 'multiarray', 'multiarray_tests.c.src')])
|
996 |
+
|
997 |
+
#######################################################################
|
998 |
+
# operand_flag_tests module #
|
999 |
+
#######################################################################
|
1000 |
+
|
1001 |
+
config.add_extension('operand_flag_tests',
|
1002 |
+
sources = [join('src', 'umath', 'operand_flag_tests.c.src')])
|
1003 |
+
|
1004 |
+
config.add_data_dir('tests')
|
1005 |
+
config.add_data_dir('tests/data')
|
1006 |
+
|
1007 |
+
config.make_svn_version_py()
|
1008 |
+
|
1009 |
+
return config
|
1010 |
+
|
1011 |
+
if __name__=='__main__':
|
1012 |
+
from numpy.distutils.core import setup
|
1013 |
+
setup(configuration=configuration)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/setup_common.py
ADDED
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
# Code common to build tools
|
4 |
+
import sys
|
5 |
+
from os.path import join
|
6 |
+
import warnings
|
7 |
+
import copy
|
8 |
+
import binascii
|
9 |
+
|
10 |
+
from distutils.ccompiler import CompileError
|
11 |
+
|
12 |
+
#-------------------
|
13 |
+
# Versioning support
|
14 |
+
#-------------------
|
15 |
+
# How to change C_API_VERSION ?
|
16 |
+
# - increase C_API_VERSION value
|
17 |
+
# - record the hash for the new C API with the script cversions.py
|
18 |
+
# and add the hash to cversions.txt
|
19 |
+
# The hash values are used to remind developers when the C API number was not
|
20 |
+
# updated - generates a MismatchCAPIWarning warning which is turned into an
|
21 |
+
# exception for released version.
|
22 |
+
|
23 |
+
# Binary compatibility version number. This number is increased whenever the
|
24 |
+
# C-API is changed such that binary compatibility is broken, i.e. whenever a
|
25 |
+
# recompile of extension modules is needed.
|
26 |
+
C_ABI_VERSION = 0x01000009
|
27 |
+
|
28 |
+
# Minor API version. This number is increased whenever a change is made to the
|
29 |
+
# C-API -- whether it breaks binary compatibility or not. Some changes, such
|
30 |
+
# as adding a function pointer to the end of the function table, can be made
|
31 |
+
# without breaking binary compatibility. In this case, only the C_API_VERSION
|
32 |
+
# (*not* C_ABI_VERSION) would be increased. Whenever binary compatibility is
|
33 |
+
# broken, both C_API_VERSION and C_ABI_VERSION should be increased.
|
34 |
+
#
|
35 |
+
# 0x00000008 - 1.7.x
|
36 |
+
# 0x00000009 - 1.8.x
|
37 |
+
# 0x00000009 - 1.9.x
|
38 |
+
C_API_VERSION = 0x00000009
|
39 |
+
|
40 |
+
class MismatchCAPIWarning(Warning):
|
41 |
+
pass
|
42 |
+
|
43 |
+
def is_released(config):
|
44 |
+
"""Return True if a released version of numpy is detected."""
|
45 |
+
from distutils.version import LooseVersion
|
46 |
+
|
47 |
+
v = config.get_version('../version.py')
|
48 |
+
if v is None:
|
49 |
+
raise ValueError("Could not get version")
|
50 |
+
pv = LooseVersion(vstring=v).version
|
51 |
+
if len(pv) > 3:
|
52 |
+
return False
|
53 |
+
return True
|
54 |
+
|
55 |
+
def get_api_versions(apiversion, codegen_dir):
|
56 |
+
"""Return current C API checksum and the recorded checksum for the given
|
57 |
+
version of the C API version."""
|
58 |
+
api_files = [join(codegen_dir, 'numpy_api_order.txt'),
|
59 |
+
join(codegen_dir, 'ufunc_api_order.txt')]
|
60 |
+
|
61 |
+
# Compute the hash of the current API as defined in the .txt files in
|
62 |
+
# code_generators
|
63 |
+
sys.path.insert(0, codegen_dir)
|
64 |
+
try:
|
65 |
+
m = __import__('genapi')
|
66 |
+
numpy_api = __import__('numpy_api')
|
67 |
+
curapi_hash = m.fullapi_hash(numpy_api.full_api)
|
68 |
+
apis_hash = m.get_versions_hash()
|
69 |
+
finally:
|
70 |
+
del sys.path[0]
|
71 |
+
|
72 |
+
return curapi_hash, apis_hash[apiversion]
|
73 |
+
|
74 |
+
def check_api_version(apiversion, codegen_dir):
|
75 |
+
"""Emits a MismacthCAPIWarning if the C API version needs updating."""
|
76 |
+
curapi_hash, api_hash = get_api_versions(apiversion, codegen_dir)
|
77 |
+
|
78 |
+
# If different hash, it means that the api .txt files in
|
79 |
+
# codegen_dir have been updated without the API version being
|
80 |
+
# updated. Any modification in those .txt files should be reflected
|
81 |
+
# in the api and eventually abi versions.
|
82 |
+
# To compute the checksum of the current API, use
|
83 |
+
# code_generators/cversions.py script
|
84 |
+
if not curapi_hash == api_hash:
|
85 |
+
msg = "API mismatch detected, the C API version " \
|
86 |
+
"numbers have to be updated. Current C api version is %d, " \
|
87 |
+
"with checksum %s, but recorded checksum for C API version %d in " \
|
88 |
+
"codegen_dir/cversions.txt is %s. If functions were added in the " \
|
89 |
+
"C API, you have to update C_API_VERSION in %s."
|
90 |
+
warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash,
|
91 |
+
__file__),
|
92 |
+
MismatchCAPIWarning)
|
93 |
+
# Mandatory functions: if not found, fail the build
|
94 |
+
MANDATORY_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs",
|
95 |
+
"floor", "ceil", "sqrt", "log10", "log", "exp", "asin",
|
96 |
+
"acos", "atan", "fmod", 'modf', 'frexp', 'ldexp']
|
97 |
+
|
98 |
+
# Standard functions which may not be available and for which we have a
|
99 |
+
# replacement implementation. Note that some of these are C99 functions.
|
100 |
+
OPTIONAL_STDFUNCS = ["expm1", "log1p", "acosh", "asinh", "atanh",
|
101 |
+
"rint", "trunc", "exp2", "log2", "hypot", "atan2", "pow",
|
102 |
+
"copysign", "nextafter", "ftello", "fseeko",
|
103 |
+
"strtoll", "strtoull"]
|
104 |
+
|
105 |
+
|
106 |
+
OPTIONAL_HEADERS = [
|
107 |
+
# sse headers only enabled automatically on amd64/x32 builds
|
108 |
+
"xmmintrin.h", # SSE
|
109 |
+
"emmintrin.h", # SSE2
|
110 |
+
]
|
111 |
+
|
112 |
+
# optional gcc compiler builtins and their call arguments and optional a
|
113 |
+
# required header
|
114 |
+
# call arguments are required as the compiler will do strict signature checking
|
115 |
+
OPTIONAL_INTRINSICS = [("__builtin_isnan", '5.'),
|
116 |
+
("__builtin_isinf", '5.'),
|
117 |
+
("__builtin_isfinite", '5.'),
|
118 |
+
("__builtin_bswap32", '5u'),
|
119 |
+
("__builtin_bswap64", '5u'),
|
120 |
+
("__builtin_expect", '5, 0'),
|
121 |
+
("_mm_load_ps", '(float*)0', "xmmintrin.h"), # SSE
|
122 |
+
("_mm_load_pd", '(double*)0', "emmintrin.h"), # SSE2
|
123 |
+
]
|
124 |
+
|
125 |
+
# function attributes
|
126 |
+
# tested via "int %s %s(void *);" % (attribute, name)
|
127 |
+
# function name will be converted to HAVE_<upper-case-name> preprocessor macro
|
128 |
+
OPTIONAL_FUNCTION_ATTRIBUTES = [('__attribute__((optimize("unroll-loops")))',
|
129 |
+
'attribute_optimize_unroll_loops'),
|
130 |
+
('__attribute__((optimize("O3")))',
|
131 |
+
'attribute_optimize_opt_3'),
|
132 |
+
('__attribute__((nonnull (1)))',
|
133 |
+
'attribute_nonnull'),
|
134 |
+
]
|
135 |
+
|
136 |
+
# variable attributes tested via "int %s a" % attribute
|
137 |
+
OPTIONAL_VARIABLE_ATTRIBUTES = ["__thread", "__declspec(thread)"]
|
138 |
+
|
139 |
+
# Subset of OPTIONAL_STDFUNCS which may alreay have HAVE_* defined by Python.h
|
140 |
+
OPTIONAL_STDFUNCS_MAYBE = ["expm1", "log1p", "acosh", "atanh", "asinh", "hypot",
|
141 |
+
"copysign", "ftello", "fseeko"]
|
142 |
+
|
143 |
+
# C99 functions: float and long double versions
|
144 |
+
C99_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor",
|
145 |
+
"ceil", "rint", "trunc", "sqrt", "log10", "log", "log1p", "exp",
|
146 |
+
"expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh",
|
147 |
+
"hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp',
|
148 |
+
"exp2", "log2", "copysign", "nextafter"]
|
149 |
+
|
150 |
+
C99_FUNCS_SINGLE = [f + 'f' for f in C99_FUNCS]
|
151 |
+
C99_FUNCS_EXTENDED = [f + 'l' for f in C99_FUNCS]
|
152 |
+
|
153 |
+
C99_COMPLEX_TYPES = ['complex double', 'complex float', 'complex long double']
|
154 |
+
|
155 |
+
C99_COMPLEX_FUNCS = ['creal', 'cimag', 'cabs', 'carg', 'cexp', 'csqrt', 'clog',
|
156 |
+
'ccos', 'csin', 'cpow']
|
157 |
+
|
158 |
+
def fname2def(name):
|
159 |
+
return "HAVE_%s" % name.upper()
|
160 |
+
|
161 |
+
def sym2def(symbol):
|
162 |
+
define = symbol.replace(' ', '')
|
163 |
+
return define.upper()
|
164 |
+
|
165 |
+
def type2def(symbol):
|
166 |
+
define = symbol.replace(' ', '_')
|
167 |
+
return define.upper()
|
168 |
+
|
169 |
+
# Code to detect long double representation taken from MPFR m4 macro
|
170 |
+
def check_long_double_representation(cmd):
|
171 |
+
cmd._check_compiler()
|
172 |
+
body = LONG_DOUBLE_REPRESENTATION_SRC % {'type': 'long double'}
|
173 |
+
|
174 |
+
# We need to use _compile because we need the object filename
|
175 |
+
src, object = cmd._compile(body, None, None, 'c')
|
176 |
+
try:
|
177 |
+
type = long_double_representation(pyod(object))
|
178 |
+
return type
|
179 |
+
finally:
|
180 |
+
cmd._clean()
|
181 |
+
|
182 |
+
LONG_DOUBLE_REPRESENTATION_SRC = r"""
|
183 |
+
/* "before" is 16 bytes to ensure there's no padding between it and "x".
|
184 |
+
* We're not expecting any "long double" bigger than 16 bytes or with
|
185 |
+
* alignment requirements stricter than 16 bytes. */
|
186 |
+
typedef %(type)s test_type;
|
187 |
+
|
188 |
+
struct {
|
189 |
+
char before[16];
|
190 |
+
test_type x;
|
191 |
+
char after[8];
|
192 |
+
} foo = {
|
193 |
+
{ '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0',
|
194 |
+
'\001', '\043', '\105', '\147', '\211', '\253', '\315', '\357' },
|
195 |
+
-123456789.0,
|
196 |
+
{ '\376', '\334', '\272', '\230', '\166', '\124', '\062', '\020' }
|
197 |
+
};
|
198 |
+
"""
|
199 |
+
|
200 |
+
def pyod(filename):
|
201 |
+
"""Python implementation of the od UNIX utility (od -b, more exactly).
|
202 |
+
|
203 |
+
Parameters
|
204 |
+
----------
|
205 |
+
filename : str
|
206 |
+
name of the file to get the dump from.
|
207 |
+
|
208 |
+
Returns
|
209 |
+
-------
|
210 |
+
out : seq
|
211 |
+
list of lines of od output
|
212 |
+
|
213 |
+
Note
|
214 |
+
----
|
215 |
+
We only implement enough to get the necessary information for long double
|
216 |
+
representation, this is not intended as a compatible replacement for od.
|
217 |
+
"""
|
218 |
+
def _pyod2():
|
219 |
+
out = []
|
220 |
+
|
221 |
+
fid = open(filename, 'rb')
|
222 |
+
try:
|
223 |
+
yo = [int(oct(int(binascii.b2a_hex(o), 16))) for o in fid.read()]
|
224 |
+
for i in range(0, len(yo), 16):
|
225 |
+
line = ['%07d' % int(oct(i))]
|
226 |
+
line.extend(['%03d' % c for c in yo[i:i+16]])
|
227 |
+
out.append(" ".join(line))
|
228 |
+
return out
|
229 |
+
finally:
|
230 |
+
fid.close()
|
231 |
+
|
232 |
+
def _pyod3():
|
233 |
+
out = []
|
234 |
+
|
235 |
+
fid = open(filename, 'rb')
|
236 |
+
try:
|
237 |
+
yo2 = [oct(o)[2:] for o in fid.read()]
|
238 |
+
for i in range(0, len(yo2), 16):
|
239 |
+
line = ['%07d' % int(oct(i)[2:])]
|
240 |
+
line.extend(['%03d' % int(c) for c in yo2[i:i+16]])
|
241 |
+
out.append(" ".join(line))
|
242 |
+
return out
|
243 |
+
finally:
|
244 |
+
fid.close()
|
245 |
+
|
246 |
+
if sys.version_info[0] < 3:
|
247 |
+
return _pyod2()
|
248 |
+
else:
|
249 |
+
return _pyod3()
|
250 |
+
|
251 |
+
_BEFORE_SEQ = ['000', '000', '000', '000', '000', '000', '000', '000',
|
252 |
+
'001', '043', '105', '147', '211', '253', '315', '357']
|
253 |
+
_AFTER_SEQ = ['376', '334', '272', '230', '166', '124', '062', '020']
|
254 |
+
|
255 |
+
_IEEE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000']
|
256 |
+
_IEEE_DOUBLE_LE = _IEEE_DOUBLE_BE[::-1]
|
257 |
+
_INTEL_EXTENDED_12B = ['000', '000', '000', '000', '240', '242', '171', '353',
|
258 |
+
'031', '300', '000', '000']
|
259 |
+
_INTEL_EXTENDED_16B = ['000', '000', '000', '000', '240', '242', '171', '353',
|
260 |
+
'031', '300', '000', '000', '000', '000', '000', '000']
|
261 |
+
_MOTOROLA_EXTENDED_12B = ['300', '031', '000', '000', '353', '171',
|
262 |
+
'242', '240', '000', '000', '000', '000']
|
263 |
+
_IEEE_QUAD_PREC_BE = ['300', '031', '326', '363', '105', '100', '000', '000',
|
264 |
+
'000', '000', '000', '000', '000', '000', '000', '000']
|
265 |
+
_IEEE_QUAD_PREC_LE = _IEEE_QUAD_PREC_BE[::-1]
|
266 |
+
_DOUBLE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000'] + \
|
267 |
+
['000'] * 8
|
268 |
+
_DOUBLE_DOUBLE_LE = ['000', '000', '000', '124', '064', '157', '235', '301'] + \
|
269 |
+
['000'] * 8
|
270 |
+
|
271 |
+
def long_double_representation(lines):
|
272 |
+
"""Given a binary dump as given by GNU od -b, look for long double
|
273 |
+
representation."""
|
274 |
+
|
275 |
+
# Read contains a list of 32 items, each item is a byte (in octal
|
276 |
+
# representation, as a string). We 'slide' over the output until read is of
|
277 |
+
# the form before_seq + content + after_sequence, where content is the long double
|
278 |
+
# representation:
|
279 |
+
# - content is 12 bytes: 80 bits Intel representation
|
280 |
+
# - content is 16 bytes: 80 bits Intel representation (64 bits) or quad precision
|
281 |
+
# - content is 8 bytes: same as double (not implemented yet)
|
282 |
+
read = [''] * 32
|
283 |
+
saw = None
|
284 |
+
for line in lines:
|
285 |
+
# we skip the first word, as od -b output an index at the beginning of
|
286 |
+
# each line
|
287 |
+
for w in line.split()[1:]:
|
288 |
+
read.pop(0)
|
289 |
+
read.append(w)
|
290 |
+
|
291 |
+
# If the end of read is equal to the after_sequence, read contains
|
292 |
+
# the long double
|
293 |
+
if read[-8:] == _AFTER_SEQ:
|
294 |
+
saw = copy.copy(read)
|
295 |
+
if read[:12] == _BEFORE_SEQ[4:]:
|
296 |
+
if read[12:-8] == _INTEL_EXTENDED_12B:
|
297 |
+
return 'INTEL_EXTENDED_12_BYTES_LE'
|
298 |
+
if read[12:-8] == _MOTOROLA_EXTENDED_12B:
|
299 |
+
return 'MOTOROLA_EXTENDED_12_BYTES_BE'
|
300 |
+
elif read[:8] == _BEFORE_SEQ[8:]:
|
301 |
+
if read[8:-8] == _INTEL_EXTENDED_16B:
|
302 |
+
return 'INTEL_EXTENDED_16_BYTES_LE'
|
303 |
+
elif read[8:-8] == _IEEE_QUAD_PREC_BE:
|
304 |
+
return 'IEEE_QUAD_BE'
|
305 |
+
elif read[8:-8] == _IEEE_QUAD_PREC_LE:
|
306 |
+
return 'IEEE_QUAD_LE'
|
307 |
+
elif read[8:-8] == _DOUBLE_DOUBLE_BE:
|
308 |
+
return 'DOUBLE_DOUBLE_BE'
|
309 |
+
elif read[8:-8] == _DOUBLE_DOUBLE_LE:
|
310 |
+
return 'DOUBLE_DOUBLE_LE'
|
311 |
+
elif read[:16] == _BEFORE_SEQ:
|
312 |
+
if read[16:-8] == _IEEE_DOUBLE_LE:
|
313 |
+
return 'IEEE_DOUBLE_LE'
|
314 |
+
elif read[16:-8] == _IEEE_DOUBLE_BE:
|
315 |
+
return 'IEEE_DOUBLE_BE'
|
316 |
+
|
317 |
+
if saw is not None:
|
318 |
+
raise ValueError("Unrecognized format (%s)" % saw)
|
319 |
+
else:
|
320 |
+
# We never detected the after_sequence
|
321 |
+
raise ValueError("Could not lock sequences (%s)" % saw)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/core/shape_base.py
ADDED
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'vstack', 'hstack']
|
4 |
+
|
5 |
+
from . import numeric as _nx
|
6 |
+
from .numeric import array, asanyarray, newaxis
|
7 |
+
|
8 |
+
def atleast_1d(*arys):
|
9 |
+
"""
|
10 |
+
Convert inputs to arrays with at least one dimension.
|
11 |
+
|
12 |
+
Scalar inputs are converted to 1-dimensional arrays, whilst
|
13 |
+
higher-dimensional inputs are preserved.
|
14 |
+
|
15 |
+
Parameters
|
16 |
+
----------
|
17 |
+
arys1, arys2, ... : array_like
|
18 |
+
One or more input arrays.
|
19 |
+
|
20 |
+
Returns
|
21 |
+
-------
|
22 |
+
ret : ndarray
|
23 |
+
An array, or sequence of arrays, each with ``a.ndim >= 1``.
|
24 |
+
Copies are made only if necessary.
|
25 |
+
|
26 |
+
See Also
|
27 |
+
--------
|
28 |
+
atleast_2d, atleast_3d
|
29 |
+
|
30 |
+
Examples
|
31 |
+
--------
|
32 |
+
>>> np.atleast_1d(1.0)
|
33 |
+
array([ 1.])
|
34 |
+
|
35 |
+
>>> x = np.arange(9.0).reshape(3,3)
|
36 |
+
>>> np.atleast_1d(x)
|
37 |
+
array([[ 0., 1., 2.],
|
38 |
+
[ 3., 4., 5.],
|
39 |
+
[ 6., 7., 8.]])
|
40 |
+
>>> np.atleast_1d(x) is x
|
41 |
+
True
|
42 |
+
|
43 |
+
>>> np.atleast_1d(1, [3, 4])
|
44 |
+
[array([1]), array([3, 4])]
|
45 |
+
|
46 |
+
"""
|
47 |
+
res = []
|
48 |
+
for ary in arys:
|
49 |
+
ary = asanyarray(ary)
|
50 |
+
if len(ary.shape) == 0 :
|
51 |
+
result = ary.reshape(1)
|
52 |
+
else :
|
53 |
+
result = ary
|
54 |
+
res.append(result)
|
55 |
+
if len(res) == 1:
|
56 |
+
return res[0]
|
57 |
+
else:
|
58 |
+
return res
|
59 |
+
|
60 |
+
def atleast_2d(*arys):
|
61 |
+
"""
|
62 |
+
View inputs as arrays with at least two dimensions.
|
63 |
+
|
64 |
+
Parameters
|
65 |
+
----------
|
66 |
+
arys1, arys2, ... : array_like
|
67 |
+
One or more array-like sequences. Non-array inputs are converted
|
68 |
+
to arrays. Arrays that already have two or more dimensions are
|
69 |
+
preserved.
|
70 |
+
|
71 |
+
Returns
|
72 |
+
-------
|
73 |
+
res, res2, ... : ndarray
|
74 |
+
An array, or tuple of arrays, each with ``a.ndim >= 2``.
|
75 |
+
Copies are avoided where possible, and views with two or more
|
76 |
+
dimensions are returned.
|
77 |
+
|
78 |
+
See Also
|
79 |
+
--------
|
80 |
+
atleast_1d, atleast_3d
|
81 |
+
|
82 |
+
Examples
|
83 |
+
--------
|
84 |
+
>>> np.atleast_2d(3.0)
|
85 |
+
array([[ 3.]])
|
86 |
+
|
87 |
+
>>> x = np.arange(3.0)
|
88 |
+
>>> np.atleast_2d(x)
|
89 |
+
array([[ 0., 1., 2.]])
|
90 |
+
>>> np.atleast_2d(x).base is x
|
91 |
+
True
|
92 |
+
|
93 |
+
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
|
94 |
+
[array([[1]]), array([[1, 2]]), array([[1, 2]])]
|
95 |
+
|
96 |
+
"""
|
97 |
+
res = []
|
98 |
+
for ary in arys:
|
99 |
+
ary = asanyarray(ary)
|
100 |
+
if len(ary.shape) == 0 :
|
101 |
+
result = ary.reshape(1, 1)
|
102 |
+
elif len(ary.shape) == 1 :
|
103 |
+
result = ary[newaxis,:]
|
104 |
+
else :
|
105 |
+
result = ary
|
106 |
+
res.append(result)
|
107 |
+
if len(res) == 1:
|
108 |
+
return res[0]
|
109 |
+
else:
|
110 |
+
return res
|
111 |
+
|
112 |
+
def atleast_3d(*arys):
|
113 |
+
"""
|
114 |
+
View inputs as arrays with at least three dimensions.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
----------
|
118 |
+
arys1, arys2, ... : array_like
|
119 |
+
One or more array-like sequences. Non-array inputs are converted to
|
120 |
+
arrays. Arrays that already have three or more dimensions are
|
121 |
+
preserved.
|
122 |
+
|
123 |
+
Returns
|
124 |
+
-------
|
125 |
+
res1, res2, ... : ndarray
|
126 |
+
An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
|
127 |
+
avoided where possible, and views with three or more dimensions are
|
128 |
+
returned. For example, a 1-D array of shape ``(N,)`` becomes a view
|
129 |
+
of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
|
130 |
+
view of shape ``(M, N, 1)``.
|
131 |
+
|
132 |
+
See Also
|
133 |
+
--------
|
134 |
+
atleast_1d, atleast_2d
|
135 |
+
|
136 |
+
Examples
|
137 |
+
--------
|
138 |
+
>>> np.atleast_3d(3.0)
|
139 |
+
array([[[ 3.]]])
|
140 |
+
|
141 |
+
>>> x = np.arange(3.0)
|
142 |
+
>>> np.atleast_3d(x).shape
|
143 |
+
(1, 3, 1)
|
144 |
+
|
145 |
+
>>> x = np.arange(12.0).reshape(4,3)
|
146 |
+
>>> np.atleast_3d(x).shape
|
147 |
+
(4, 3, 1)
|
148 |
+
>>> np.atleast_3d(x).base is x
|
149 |
+
True
|
150 |
+
|
151 |
+
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
|
152 |
+
... print arr, arr.shape
|
153 |
+
...
|
154 |
+
[[[1]
|
155 |
+
[2]]] (1, 2, 1)
|
156 |
+
[[[1]
|
157 |
+
[2]]] (1, 2, 1)
|
158 |
+
[[[1 2]]] (1, 1, 2)
|
159 |
+
|
160 |
+
"""
|
161 |
+
res = []
|
162 |
+
for ary in arys:
|
163 |
+
ary = asanyarray(ary)
|
164 |
+
if len(ary.shape) == 0:
|
165 |
+
result = ary.reshape(1, 1, 1)
|
166 |
+
elif len(ary.shape) == 1:
|
167 |
+
result = ary[newaxis,:, newaxis]
|
168 |
+
elif len(ary.shape) == 2:
|
169 |
+
result = ary[:,:, newaxis]
|
170 |
+
else:
|
171 |
+
result = ary
|
172 |
+
res.append(result)
|
173 |
+
if len(res) == 1:
|
174 |
+
return res[0]
|
175 |
+
else:
|
176 |
+
return res
|
177 |
+
|
178 |
+
|
179 |
+
def vstack(tup):
|
180 |
+
"""
|
181 |
+
Stack arrays in sequence vertically (row wise).
|
182 |
+
|
183 |
+
Take a sequence of arrays and stack them vertically to make a single
|
184 |
+
array. Rebuild arrays divided by `vsplit`.
|
185 |
+
|
186 |
+
Parameters
|
187 |
+
----------
|
188 |
+
tup : sequence of ndarrays
|
189 |
+
Tuple containing arrays to be stacked. The arrays must have the same
|
190 |
+
shape along all but the first axis.
|
191 |
+
|
192 |
+
Returns
|
193 |
+
-------
|
194 |
+
stacked : ndarray
|
195 |
+
The array formed by stacking the given arrays.
|
196 |
+
|
197 |
+
See Also
|
198 |
+
--------
|
199 |
+
hstack : Stack arrays in sequence horizontally (column wise).
|
200 |
+
dstack : Stack arrays in sequence depth wise (along third dimension).
|
201 |
+
concatenate : Join a sequence of arrays together.
|
202 |
+
vsplit : Split array into a list of multiple sub-arrays vertically.
|
203 |
+
|
204 |
+
Notes
|
205 |
+
-----
|
206 |
+
Equivalent to ``np.concatenate(tup, axis=0)`` if `tup` contains arrays that
|
207 |
+
are at least 2-dimensional.
|
208 |
+
|
209 |
+
Examples
|
210 |
+
--------
|
211 |
+
>>> a = np.array([1, 2, 3])
|
212 |
+
>>> b = np.array([2, 3, 4])
|
213 |
+
>>> np.vstack((a,b))
|
214 |
+
array([[1, 2, 3],
|
215 |
+
[2, 3, 4]])
|
216 |
+
|
217 |
+
>>> a = np.array([[1], [2], [3]])
|
218 |
+
>>> b = np.array([[2], [3], [4]])
|
219 |
+
>>> np.vstack((a,b))
|
220 |
+
array([[1],
|
221 |
+
[2],
|
222 |
+
[3],
|
223 |
+
[2],
|
224 |
+
[3],
|
225 |
+
[4]])
|
226 |
+
|
227 |
+
"""
|
228 |
+
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
|
229 |
+
|
230 |
+
def hstack(tup):
|
231 |
+
"""
|
232 |
+
Stack arrays in sequence horizontally (column wise).
|
233 |
+
|
234 |
+
Take a sequence of arrays and stack them horizontally to make
|
235 |
+
a single array. Rebuild arrays divided by `hsplit`.
|
236 |
+
|
237 |
+
Parameters
|
238 |
+
----------
|
239 |
+
tup : sequence of ndarrays
|
240 |
+
All arrays must have the same shape along all but the second axis.
|
241 |
+
|
242 |
+
Returns
|
243 |
+
-------
|
244 |
+
stacked : ndarray
|
245 |
+
The array formed by stacking the given arrays.
|
246 |
+
|
247 |
+
See Also
|
248 |
+
--------
|
249 |
+
vstack : Stack arrays in sequence vertically (row wise).
|
250 |
+
dstack : Stack arrays in sequence depth wise (along third axis).
|
251 |
+
concatenate : Join a sequence of arrays together.
|
252 |
+
hsplit : Split array along second axis.
|
253 |
+
|
254 |
+
Notes
|
255 |
+
-----
|
256 |
+
Equivalent to ``np.concatenate(tup, axis=1)``
|
257 |
+
|
258 |
+
Examples
|
259 |
+
--------
|
260 |
+
>>> a = np.array((1,2,3))
|
261 |
+
>>> b = np.array((2,3,4))
|
262 |
+
>>> np.hstack((a,b))
|
263 |
+
array([1, 2, 3, 2, 3, 4])
|
264 |
+
>>> a = np.array([[1],[2],[3]])
|
265 |
+
>>> b = np.array([[2],[3],[4]])
|
266 |
+
>>> np.hstack((a,b))
|
267 |
+
array([[1, 2],
|
268 |
+
[2, 3],
|
269 |
+
[3, 4]])
|
270 |
+
|
271 |
+
"""
|
272 |
+
arrs = [atleast_1d(_m) for _m in tup]
|
273 |
+
# As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
|
274 |
+
if arrs[0].ndim == 1:
|
275 |
+
return _nx.concatenate(arrs, 0)
|
276 |
+
else:
|
277 |
+
return _nx.concatenate(arrs, 1)
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/ctypeslib.py
ADDED
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
============================
|
3 |
+
``ctypes`` Utility Functions
|
4 |
+
============================
|
5 |
+
|
6 |
+
See Also
|
7 |
+
---------
|
8 |
+
load_library : Load a C library.
|
9 |
+
ndpointer : Array restype/argtype with verification.
|
10 |
+
as_ctypes : Create a ctypes array from an ndarray.
|
11 |
+
as_array : Create an ndarray from a ctypes array.
|
12 |
+
|
13 |
+
References
|
14 |
+
----------
|
15 |
+
.. [1] "SciPy Cookbook: ctypes", http://www.scipy.org/Cookbook/Ctypes
|
16 |
+
|
17 |
+
Examples
|
18 |
+
--------
|
19 |
+
Load the C library:
|
20 |
+
|
21 |
+
>>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP
|
22 |
+
|
23 |
+
Our result type, an ndarray that must be of type double, be 1-dimensional
|
24 |
+
and is C-contiguous in memory:
|
25 |
+
|
26 |
+
>>> array_1d_double = np.ctypeslib.ndpointer(
|
27 |
+
... dtype=np.double,
|
28 |
+
... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP
|
29 |
+
|
30 |
+
Our C-function typically takes an array and updates its values
|
31 |
+
in-place. For example::
|
32 |
+
|
33 |
+
void foo_func(double* x, int length)
|
34 |
+
{
|
35 |
+
int i;
|
36 |
+
for (i = 0; i < length; i++) {
|
37 |
+
x[i] = i*i;
|
38 |
+
}
|
39 |
+
}
|
40 |
+
|
41 |
+
We wrap it using:
|
42 |
+
|
43 |
+
>>> _lib.foo_func.restype = None #doctest: +SKIP
|
44 |
+
>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
|
45 |
+
|
46 |
+
Then, we're ready to call ``foo_func``:
|
47 |
+
|
48 |
+
>>> out = np.empty(15, dtype=np.double)
|
49 |
+
>>> _lib.foo_func(out, len(out)) #doctest: +SKIP
|
50 |
+
|
51 |
+
"""
|
52 |
+
from __future__ import division, absolute_import, print_function
|
53 |
+
|
54 |
+
__all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library',
|
55 |
+
'c_intp', 'as_ctypes', 'as_array']
|
56 |
+
|
57 |
+
import sys, os
|
58 |
+
from numpy import integer, ndarray, dtype as _dtype, deprecate, array
|
59 |
+
from numpy.core.multiarray import _flagdict, flagsobj
|
60 |
+
|
61 |
+
try:
|
62 |
+
import ctypes
|
63 |
+
except ImportError:
|
64 |
+
ctypes = None
|
65 |
+
|
66 |
+
if ctypes is None:
|
67 |
+
def _dummy(*args, **kwds):
|
68 |
+
"""
|
69 |
+
Dummy object that raises an ImportError if ctypes is not available.
|
70 |
+
|
71 |
+
Raises
|
72 |
+
------
|
73 |
+
ImportError
|
74 |
+
If ctypes is not available.
|
75 |
+
|
76 |
+
"""
|
77 |
+
raise ImportError("ctypes is not available.")
|
78 |
+
ctypes_load_library = _dummy
|
79 |
+
load_library = _dummy
|
80 |
+
as_ctypes = _dummy
|
81 |
+
as_array = _dummy
|
82 |
+
from numpy import intp as c_intp
|
83 |
+
_ndptr_base = object
|
84 |
+
else:
|
85 |
+
import numpy.core._internal as nic
|
86 |
+
c_intp = nic._getintp_ctype()
|
87 |
+
del nic
|
88 |
+
_ndptr_base = ctypes.c_void_p
|
89 |
+
|
90 |
+
# Adapted from Albert Strasheim
|
91 |
+
def load_library(libname, loader_path):
|
92 |
+
if ctypes.__version__ < '1.0.1':
|
93 |
+
import warnings
|
94 |
+
warnings.warn("All features of ctypes interface may not work " \
|
95 |
+
"with ctypes < 1.0.1")
|
96 |
+
|
97 |
+
ext = os.path.splitext(libname)[1]
|
98 |
+
if not ext:
|
99 |
+
# Try to load library with platform-specific name, otherwise
|
100 |
+
# default to libname.[so|pyd]. Sometimes, these files are built
|
101 |
+
# erroneously on non-linux platforms.
|
102 |
+
from numpy.distutils.misc_util import get_shared_lib_extension
|
103 |
+
so_ext = get_shared_lib_extension()
|
104 |
+
libname_ext = [libname + so_ext]
|
105 |
+
# mac, windows and linux >= py3.2 shared library and loadable
|
106 |
+
# module have different extensions so try both
|
107 |
+
so_ext2 = get_shared_lib_extension(is_python_ext=True)
|
108 |
+
if not so_ext2 == so_ext:
|
109 |
+
libname_ext.insert(0, libname + so_ext2)
|
110 |
+
else:
|
111 |
+
libname_ext = [libname]
|
112 |
+
|
113 |
+
loader_path = os.path.abspath(loader_path)
|
114 |
+
if not os.path.isdir(loader_path):
|
115 |
+
libdir = os.path.dirname(loader_path)
|
116 |
+
else:
|
117 |
+
libdir = loader_path
|
118 |
+
|
119 |
+
for ln in libname_ext:
|
120 |
+
libpath = os.path.join(libdir, ln)
|
121 |
+
if os.path.exists(libpath):
|
122 |
+
try:
|
123 |
+
return ctypes.cdll[libpath]
|
124 |
+
except OSError:
|
125 |
+
## defective lib file
|
126 |
+
raise
|
127 |
+
## if no successful return in the libname_ext loop:
|
128 |
+
raise OSError("no file with expected extension")
|
129 |
+
|
130 |
+
ctypes_load_library = deprecate(load_library, 'ctypes_load_library',
|
131 |
+
'load_library')
|
132 |
+
|
133 |
+
def _num_fromflags(flaglist):
|
134 |
+
num = 0
|
135 |
+
for val in flaglist:
|
136 |
+
num += _flagdict[val]
|
137 |
+
return num
|
138 |
+
|
139 |
+
_flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE',
|
140 |
+
'OWNDATA', 'UPDATEIFCOPY']
|
141 |
+
def _flags_fromnum(num):
|
142 |
+
res = []
|
143 |
+
for key in _flagnames:
|
144 |
+
value = _flagdict[key]
|
145 |
+
if (num & value):
|
146 |
+
res.append(key)
|
147 |
+
return res
|
148 |
+
|
149 |
+
|
150 |
+
class _ndptr(_ndptr_base):
|
151 |
+
|
152 |
+
def _check_retval_(self):
|
153 |
+
"""This method is called when this class is used as the .restype
|
154 |
+
asttribute for a shared-library function. It constructs a numpy
|
155 |
+
array from a void pointer."""
|
156 |
+
return array(self)
|
157 |
+
|
158 |
+
@property
|
159 |
+
def __array_interface__(self):
|
160 |
+
return {'descr': self._dtype_.descr,
|
161 |
+
'__ref': self,
|
162 |
+
'strides': None,
|
163 |
+
'shape': self._shape_,
|
164 |
+
'version': 3,
|
165 |
+
'typestr': self._dtype_.descr[0][1],
|
166 |
+
'data': (self.value, False),
|
167 |
+
}
|
168 |
+
|
169 |
+
@classmethod
|
170 |
+
def from_param(cls, obj):
|
171 |
+
if not isinstance(obj, ndarray):
|
172 |
+
raise TypeError("argument must be an ndarray")
|
173 |
+
if cls._dtype_ is not None \
|
174 |
+
and obj.dtype != cls._dtype_:
|
175 |
+
raise TypeError("array must have data type %s" % cls._dtype_)
|
176 |
+
if cls._ndim_ is not None \
|
177 |
+
and obj.ndim != cls._ndim_:
|
178 |
+
raise TypeError("array must have %d dimension(s)" % cls._ndim_)
|
179 |
+
if cls._shape_ is not None \
|
180 |
+
and obj.shape != cls._shape_:
|
181 |
+
raise TypeError("array must have shape %s" % str(cls._shape_))
|
182 |
+
if cls._flags_ is not None \
|
183 |
+
and ((obj.flags.num & cls._flags_) != cls._flags_):
|
184 |
+
raise TypeError("array must have flags %s" %
|
185 |
+
_flags_fromnum(cls._flags_))
|
186 |
+
return obj.ctypes
|
187 |
+
|
188 |
+
|
189 |
+
# Factory for an array-checking class with from_param defined for
|
190 |
+
# use with ctypes argtypes mechanism
|
191 |
+
_pointer_type_cache = {}
|
192 |
+
def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
|
193 |
+
"""
|
194 |
+
Array-checking restype/argtypes.
|
195 |
+
|
196 |
+
An ndpointer instance is used to describe an ndarray in restypes
|
197 |
+
and argtypes specifications. This approach is more flexible than
|
198 |
+
using, for example, ``POINTER(c_double)``, since several restrictions
|
199 |
+
can be specified, which are verified upon calling the ctypes function.
|
200 |
+
These include data type, number of dimensions, shape and flags. If a
|
201 |
+
given array does not satisfy the specified restrictions,
|
202 |
+
a ``TypeError`` is raised.
|
203 |
+
|
204 |
+
Parameters
|
205 |
+
----------
|
206 |
+
dtype : data-type, optional
|
207 |
+
Array data-type.
|
208 |
+
ndim : int, optional
|
209 |
+
Number of array dimensions.
|
210 |
+
shape : tuple of ints, optional
|
211 |
+
Array shape.
|
212 |
+
flags : str or tuple of str
|
213 |
+
Array flags; may be one or more of:
|
214 |
+
|
215 |
+
- C_CONTIGUOUS / C / CONTIGUOUS
|
216 |
+
- F_CONTIGUOUS / F / FORTRAN
|
217 |
+
- OWNDATA / O
|
218 |
+
- WRITEABLE / W
|
219 |
+
- ALIGNED / A
|
220 |
+
- UPDATEIFCOPY / U
|
221 |
+
|
222 |
+
Returns
|
223 |
+
-------
|
224 |
+
klass : ndpointer type object
|
225 |
+
A type object, which is an ``_ndtpr`` instance containing
|
226 |
+
dtype, ndim, shape and flags information.
|
227 |
+
|
228 |
+
Raises
|
229 |
+
------
|
230 |
+
TypeError
|
231 |
+
If a given array does not satisfy the specified restrictions.
|
232 |
+
|
233 |
+
Examples
|
234 |
+
--------
|
235 |
+
>>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
|
236 |
+
... ndim=1,
|
237 |
+
... flags='C_CONTIGUOUS')]
|
238 |
+
... #doctest: +SKIP
|
239 |
+
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
|
240 |
+
... #doctest: +SKIP
|
241 |
+
|
242 |
+
"""
|
243 |
+
|
244 |
+
if dtype is not None:
|
245 |
+
dtype = _dtype(dtype)
|
246 |
+
num = None
|
247 |
+
if flags is not None:
|
248 |
+
if isinstance(flags, str):
|
249 |
+
flags = flags.split(',')
|
250 |
+
elif isinstance(flags, (int, integer)):
|
251 |
+
num = flags
|
252 |
+
flags = _flags_fromnum(num)
|
253 |
+
elif isinstance(flags, flagsobj):
|
254 |
+
num = flags.num
|
255 |
+
flags = _flags_fromnum(num)
|
256 |
+
if num is None:
|
257 |
+
try:
|
258 |
+
flags = [x.strip().upper() for x in flags]
|
259 |
+
except:
|
260 |
+
raise TypeError("invalid flags specification")
|
261 |
+
num = _num_fromflags(flags)
|
262 |
+
try:
|
263 |
+
return _pointer_type_cache[(dtype, ndim, shape, num)]
|
264 |
+
except KeyError:
|
265 |
+
pass
|
266 |
+
if dtype is None:
|
267 |
+
name = 'any'
|
268 |
+
elif dtype.names:
|
269 |
+
name = str(id(dtype))
|
270 |
+
else:
|
271 |
+
name = dtype.str
|
272 |
+
if ndim is not None:
|
273 |
+
name += "_%dd" % ndim
|
274 |
+
if shape is not None:
|
275 |
+
try:
|
276 |
+
strshape = [str(x) for x in shape]
|
277 |
+
except TypeError:
|
278 |
+
strshape = [str(shape)]
|
279 |
+
shape = (shape,)
|
280 |
+
shape = tuple(shape)
|
281 |
+
name += "_"+"x".join(strshape)
|
282 |
+
if flags is not None:
|
283 |
+
name += "_"+"_".join(flags)
|
284 |
+
else:
|
285 |
+
flags = []
|
286 |
+
klass = type("ndpointer_%s"%name, (_ndptr,),
|
287 |
+
{"_dtype_": dtype,
|
288 |
+
"_shape_" : shape,
|
289 |
+
"_ndim_" : ndim,
|
290 |
+
"_flags_" : num})
|
291 |
+
_pointer_type_cache[dtype] = klass
|
292 |
+
return klass
|
293 |
+
|
294 |
+
if ctypes is not None:
|
295 |
+
ct = ctypes
|
296 |
+
################################################################
|
297 |
+
# simple types
|
298 |
+
|
299 |
+
# maps the numpy typecodes like '<f8' to simple ctypes types like
|
300 |
+
# c_double. Filled in by prep_simple.
|
301 |
+
_typecodes = {}
|
302 |
+
|
303 |
+
def prep_simple(simple_type, dtype):
|
304 |
+
"""Given a ctypes simple type, construct and attach an
|
305 |
+
__array_interface__ property to it if it does not yet have one.
|
306 |
+
"""
|
307 |
+
try: simple_type.__array_interface__
|
308 |
+
except AttributeError: pass
|
309 |
+
else: return
|
310 |
+
|
311 |
+
typestr = _dtype(dtype).str
|
312 |
+
_typecodes[typestr] = simple_type
|
313 |
+
|
314 |
+
def __array_interface__(self):
|
315 |
+
return {'descr': [('', typestr)],
|
316 |
+
'__ref': self,
|
317 |
+
'strides': None,
|
318 |
+
'shape': (),
|
319 |
+
'version': 3,
|
320 |
+
'typestr': typestr,
|
321 |
+
'data': (ct.addressof(self), False),
|
322 |
+
}
|
323 |
+
|
324 |
+
simple_type.__array_interface__ = property(__array_interface__)
|
325 |
+
|
326 |
+
simple_types = [
|
327 |
+
((ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong), "i"),
|
328 |
+
((ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong), "u"),
|
329 |
+
((ct.c_float, ct.c_double), "f"),
|
330 |
+
]
|
331 |
+
|
332 |
+
# Prep that numerical ctypes types:
|
333 |
+
for types, code in simple_types:
|
334 |
+
for tp in types:
|
335 |
+
prep_simple(tp, "%c%d" % (code, ct.sizeof(tp)))
|
336 |
+
|
337 |
+
################################################################
|
338 |
+
# array types
|
339 |
+
|
340 |
+
_ARRAY_TYPE = type(ct.c_int * 1)
|
341 |
+
|
342 |
+
def prep_array(array_type):
|
343 |
+
"""Given a ctypes array type, construct and attach an
|
344 |
+
__array_interface__ property to it if it does not yet have one.
|
345 |
+
"""
|
346 |
+
try: array_type.__array_interface__
|
347 |
+
except AttributeError: pass
|
348 |
+
else: return
|
349 |
+
|
350 |
+
shape = []
|
351 |
+
ob = array_type
|
352 |
+
while type(ob) is _ARRAY_TYPE:
|
353 |
+
shape.append(ob._length_)
|
354 |
+
ob = ob._type_
|
355 |
+
shape = tuple(shape)
|
356 |
+
ai = ob().__array_interface__
|
357 |
+
descr = ai['descr']
|
358 |
+
typestr = ai['typestr']
|
359 |
+
|
360 |
+
def __array_interface__(self):
|
361 |
+
return {'descr': descr,
|
362 |
+
'__ref': self,
|
363 |
+
'strides': None,
|
364 |
+
'shape': shape,
|
365 |
+
'version': 3,
|
366 |
+
'typestr': typestr,
|
367 |
+
'data': (ct.addressof(self), False),
|
368 |
+
}
|
369 |
+
|
370 |
+
array_type.__array_interface__ = property(__array_interface__)
|
371 |
+
|
372 |
+
def prep_pointer(pointer_obj, shape):
|
373 |
+
"""Given a ctypes pointer object, construct and
|
374 |
+
attach an __array_interface__ property to it if it does not
|
375 |
+
yet have one.
|
376 |
+
"""
|
377 |
+
try: pointer_obj.__array_interface__
|
378 |
+
except AttributeError: pass
|
379 |
+
else: return
|
380 |
+
|
381 |
+
contents = pointer_obj.contents
|
382 |
+
dtype = _dtype(type(contents))
|
383 |
+
|
384 |
+
inter = {'version': 3,
|
385 |
+
'typestr': dtype.str,
|
386 |
+
'data': (ct.addressof(contents), False),
|
387 |
+
'shape': shape}
|
388 |
+
|
389 |
+
pointer_obj.__array_interface__ = inter
|
390 |
+
|
391 |
+
################################################################
|
392 |
+
# public functions
|
393 |
+
|
394 |
+
def as_array(obj, shape=None):
|
395 |
+
"""Create a numpy array from a ctypes array or a ctypes POINTER.
|
396 |
+
The numpy array shares the memory with the ctypes object.
|
397 |
+
|
398 |
+
The size parameter must be given if converting from a ctypes POINTER.
|
399 |
+
The size parameter is ignored if converting from a ctypes array
|
400 |
+
"""
|
401 |
+
tp = type(obj)
|
402 |
+
try: tp.__array_interface__
|
403 |
+
except AttributeError:
|
404 |
+
if hasattr(obj, 'contents'):
|
405 |
+
prep_pointer(obj, shape)
|
406 |
+
else:
|
407 |
+
prep_array(tp)
|
408 |
+
return array(obj, copy=False)
|
409 |
+
|
410 |
+
def as_ctypes(obj):
|
411 |
+
"""Create and return a ctypes object from a numpy array. Actually
|
412 |
+
anything that exposes the __array_interface__ is accepted."""
|
413 |
+
ai = obj.__array_interface__
|
414 |
+
if ai["strides"]:
|
415 |
+
raise TypeError("strided arrays not supported")
|
416 |
+
if ai["version"] != 3:
|
417 |
+
raise TypeError("only __array_interface__ version 3 supported")
|
418 |
+
addr, readonly = ai["data"]
|
419 |
+
if readonly:
|
420 |
+
raise TypeError("readonly arrays unsupported")
|
421 |
+
tp = _typecodes[ai["typestr"]]
|
422 |
+
for dim in ai["shape"][::-1]:
|
423 |
+
tp = tp * dim
|
424 |
+
result = tp.from_address(addr)
|
425 |
+
result.__keep = ai
|
426 |
+
return result
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__config__.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is generated by /tmp/pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/setup.py
|
2 |
+
# It contains system_info results at the time of building this package.
|
3 |
+
__all__ = ["get_info","show"]
|
4 |
+
|
5 |
+
blas_mkl_info={}
|
6 |
+
openblas_info={}
|
7 |
+
atlas_blas_threads_info={}
|
8 |
+
atlas_blas_info={}
|
9 |
+
blas_info={}
|
10 |
+
blas_src_info={}
|
11 |
+
blas_opt_info={}
|
12 |
+
openblas_lapack_info={}
|
13 |
+
mkl_info={}
|
14 |
+
lapack_mkl_info={}
|
15 |
+
atlas_threads_info={}
|
16 |
+
atlas_info={}
|
17 |
+
lapack_info={}
|
18 |
+
lapack_src_info={}
|
19 |
+
lapack_opt_info={}
|
20 |
+
|
21 |
+
def get_info(name):
|
22 |
+
g = globals()
|
23 |
+
return g.get(name, g.get(name + "_info", {}))
|
24 |
+
|
25 |
+
def show():
|
26 |
+
for name,info_dict in globals().items():
|
27 |
+
if name[0] == "_" or type(info_dict) is not type({}): continue
|
28 |
+
print(name + ":")
|
29 |
+
if not info_dict:
|
30 |
+
print(" NOT AVAILABLE")
|
31 |
+
for k,v in info_dict.items():
|
32 |
+
v = str(v)
|
33 |
+
if k == "sources" and len(v) > 200:
|
34 |
+
v = v[:60] + " ...\n... " + v[-60:]
|
35 |
+
print(" %s = %s" % (k,v))
|
36 |
+
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__init__.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
import sys
|
4 |
+
|
5 |
+
if sys.version_info[0] < 3:
|
6 |
+
from .__version__ import version as __version__
|
7 |
+
# Must import local ccompiler ASAP in order to get
|
8 |
+
# customized CCompiler.spawn effective.
|
9 |
+
from . import ccompiler
|
10 |
+
from . import unixccompiler
|
11 |
+
|
12 |
+
from .info import __doc__
|
13 |
+
from .npy_pkg_config import *
|
14 |
+
|
15 |
+
try:
|
16 |
+
import __config__
|
17 |
+
_INSTALLED = True
|
18 |
+
except ImportError:
|
19 |
+
_INSTALLED = False
|
20 |
+
else:
|
21 |
+
from numpy.distutils.__version__ import version as __version__
|
22 |
+
# Must import local ccompiler ASAP in order to get
|
23 |
+
# customized CCompiler.spawn effective.
|
24 |
+
import numpy.distutils.ccompiler
|
25 |
+
import numpy.distutils.unixccompiler
|
26 |
+
|
27 |
+
from numpy.distutils.info import __doc__
|
28 |
+
from numpy.distutils.npy_pkg_config import *
|
29 |
+
|
30 |
+
try:
|
31 |
+
import numpy.distutils.__config__
|
32 |
+
_INSTALLED = True
|
33 |
+
except ImportError:
|
34 |
+
_INSTALLED = False
|
35 |
+
|
36 |
+
if _INSTALLED:
|
37 |
+
from numpy.testing import Tester
|
38 |
+
test = Tester().test
|
39 |
+
bench = Tester().bench
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/__version__.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division, absolute_import, print_function
|
2 |
+
|
3 |
+
major = 0
|
4 |
+
minor = 4
|
5 |
+
micro = 0
|
6 |
+
version = '%(major)d.%(minor)d.%(micro)d' % (locals())
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/ccompiler.py
ADDED
@@ -0,0 +1,656 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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sys
|
6 |
+
import types
|
7 |
+
from copy import copy
|
8 |
+
|
9 |
+
from distutils.ccompiler import *
|
10 |
+
from distutils import ccompiler
|
11 |
+
from distutils.errors import DistutilsExecError, DistutilsModuleError, \
|
12 |
+
DistutilsPlatformError
|
13 |
+
from distutils.sysconfig import customize_compiler
|
14 |
+
from distutils.version import LooseVersion
|
15 |
+
|
16 |
+
from numpy.distutils import log
|
17 |
+
from numpy.distutils.exec_command import exec_command
|
18 |
+
from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \
|
19 |
+
quote_args
|
20 |
+
from numpy.distutils.compat import get_exception
|
21 |
+
|
22 |
+
|
23 |
+
def replace_method(klass, method_name, func):
|
24 |
+
if sys.version_info[0] < 3:
|
25 |
+
m = types.MethodType(func, None, klass)
|
26 |
+
else:
|
27 |
+
# Py3k does not have unbound method anymore, MethodType does not work
|
28 |
+
m = lambda self, *args, **kw: func(self, *args, **kw)
|
29 |
+
setattr(klass, method_name, m)
|
30 |
+
|
31 |
+
# Using customized CCompiler.spawn.
|
32 |
+
def CCompiler_spawn(self, cmd, display=None):
|
33 |
+
"""
|
34 |
+
Execute a command in a sub-process.
|
35 |
+
|
36 |
+
Parameters
|
37 |
+
----------
|
38 |
+
cmd : str
|
39 |
+
The command to execute.
|
40 |
+
display : str or sequence of str, optional
|
41 |
+
The text to add to the log file kept by `numpy.distutils`.
|
42 |
+
If not given, `display` is equal to `cmd`.
|
43 |
+
|
44 |
+
Returns
|
45 |
+
-------
|
46 |
+
None
|
47 |
+
|
48 |
+
Raises
|
49 |
+
------
|
50 |
+
DistutilsExecError
|
51 |
+
If the command failed, i.e. the exit status was not 0.
|
52 |
+
|
53 |
+
"""
|
54 |
+
if display is None:
|
55 |
+
display = cmd
|
56 |
+
if is_sequence(display):
|
57 |
+
display = ' '.join(list(display))
|
58 |
+
log.info(display)
|
59 |
+
s, o = exec_command(cmd)
|
60 |
+
if s:
|
61 |
+
if is_sequence(cmd):
|
62 |
+
cmd = ' '.join(list(cmd))
|
63 |
+
try:
|
64 |
+
print(o)
|
65 |
+
except UnicodeError:
|
66 |
+
# When installing through pip, `o` can contain non-ascii chars
|
67 |
+
pass
|
68 |
+
if re.search('Too many open files', o):
|
69 |
+
msg = '\nTry rerunning setup command until build succeeds.'
|
70 |
+
else:
|
71 |
+
msg = ''
|
72 |
+
raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg))
|
73 |
+
|
74 |
+
replace_method(CCompiler, 'spawn', CCompiler_spawn)
|
75 |
+
|
76 |
+
def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
|
77 |
+
"""
|
78 |
+
Return the name of the object files for the given source files.
|
79 |
+
|
80 |
+
Parameters
|
81 |
+
----------
|
82 |
+
source_filenames : list of str
|
83 |
+
The list of paths to source files. Paths can be either relative or
|
84 |
+
absolute, this is handled transparently.
|
85 |
+
strip_dir : bool, optional
|
86 |
+
Whether to strip the directory from the returned paths. If True,
|
87 |
+
the file name prepended by `output_dir` is returned. Default is False.
|
88 |
+
output_dir : str, optional
|
89 |
+
If given, this path is prepended to the returned paths to the
|
90 |
+
object files.
|
91 |
+
|
92 |
+
Returns
|
93 |
+
-------
|
94 |
+
obj_names : list of str
|
95 |
+
The list of paths to the object files corresponding to the source
|
96 |
+
files in `source_filenames`.
|
97 |
+
|
98 |
+
"""
|
99 |
+
if output_dir is None:
|
100 |
+
output_dir = ''
|
101 |
+
obj_names = []
|
102 |
+
for src_name in source_filenames:
|
103 |
+
base, ext = os.path.splitext(os.path.normpath(src_name))
|
104 |
+
base = os.path.splitdrive(base)[1] # Chop off the drive
|
105 |
+
base = base[os.path.isabs(base):] # If abs, chop off leading /
|
106 |
+
if base.startswith('..'):
|
107 |
+
# Resolve starting relative path components, middle ones
|
108 |
+
# (if any) have been handled by os.path.normpath above.
|
109 |
+
i = base.rfind('..')+2
|
110 |
+
d = base[:i]
|
111 |
+
d = os.path.basename(os.path.abspath(d))
|
112 |
+
base = d + base[i:]
|
113 |
+
if ext not in self.src_extensions:
|
114 |
+
raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))
|
115 |
+
if strip_dir:
|
116 |
+
base = os.path.basename(base)
|
117 |
+
obj_name = os.path.join(output_dir, base + self.obj_extension)
|
118 |
+
obj_names.append(obj_name)
|
119 |
+
return obj_names
|
120 |
+
|
121 |
+
replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames)
|
122 |
+
|
123 |
+
def CCompiler_compile(self, sources, output_dir=None, macros=None,
|
124 |
+
include_dirs=None, debug=0, extra_preargs=None,
|
125 |
+
extra_postargs=None, depends=None):
|
126 |
+
"""
|
127 |
+
Compile one or more source files.
|
128 |
+
|
129 |
+
Please refer to the Python distutils API reference for more details.
|
130 |
+
|
131 |
+
Parameters
|
132 |
+
----------
|
133 |
+
sources : list of str
|
134 |
+
A list of filenames
|
135 |
+
output_dir : str, optional
|
136 |
+
Path to the output directory.
|
137 |
+
macros : list of tuples
|
138 |
+
A list of macro definitions.
|
139 |
+
include_dirs : list of str, optional
|
140 |
+
The directories to add to the default include file search path for
|
141 |
+
this compilation only.
|
142 |
+
debug : bool, optional
|
143 |
+
Whether or not to output debug symbols in or alongside the object
|
144 |
+
file(s).
|
145 |
+
extra_preargs, extra_postargs : ?
|
146 |
+
Extra pre- and post-arguments.
|
147 |
+
depends : list of str, optional
|
148 |
+
A list of file names that all targets depend on.
|
149 |
+
|
150 |
+
Returns
|
151 |
+
-------
|
152 |
+
objects : list of str
|
153 |
+
A list of object file names, one per source file `sources`.
|
154 |
+
|
155 |
+
Raises
|
156 |
+
------
|
157 |
+
CompileError
|
158 |
+
If compilation fails.
|
159 |
+
|
160 |
+
"""
|
161 |
+
# This method is effective only with Python >=2.3 distutils.
|
162 |
+
# Any changes here should be applied also to fcompiler.compile
|
163 |
+
# method to support pre Python 2.3 distutils.
|
164 |
+
if not sources:
|
165 |
+
return []
|
166 |
+
# FIXME:RELATIVE_IMPORT
|
167 |
+
if sys.version_info[0] < 3:
|
168 |
+
from .fcompiler import FCompiler
|
169 |
+
else:
|
170 |
+
from numpy.distutils.fcompiler import FCompiler
|
171 |
+
if isinstance(self, FCompiler):
|
172 |
+
display = []
|
173 |
+
for fc in ['f77', 'f90', 'fix']:
|
174 |
+
fcomp = getattr(self, 'compiler_'+fc)
|
175 |
+
if fcomp is None:
|
176 |
+
continue
|
177 |
+
display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp)))
|
178 |
+
display = '\n'.join(display)
|
179 |
+
else:
|
180 |
+
ccomp = self.compiler_so
|
181 |
+
display = "C compiler: %s\n" % (' '.join(ccomp),)
|
182 |
+
log.info(display)
|
183 |
+
macros, objects, extra_postargs, pp_opts, build = \
|
184 |
+
self._setup_compile(output_dir, macros, include_dirs, sources,
|
185 |
+
depends, extra_postargs)
|
186 |
+
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
|
187 |
+
display = "compile options: '%s'" % (' '.join(cc_args))
|
188 |
+
if extra_postargs:
|
189 |
+
display += "\nextra options: '%s'" % (' '.join(extra_postargs))
|
190 |
+
log.info(display)
|
191 |
+
|
192 |
+
# build any sources in same order as they were originally specified
|
193 |
+
# especially important for fortran .f90 files using modules
|
194 |
+
if isinstance(self, FCompiler):
|
195 |
+
objects_to_build = list(build.keys())
|
196 |
+
for obj in objects:
|
197 |
+
if obj in objects_to_build:
|
198 |
+
src, ext = build[obj]
|
199 |
+
if self.compiler_type=='absoft':
|
200 |
+
obj = cyg2win32(obj)
|
201 |
+
src = cyg2win32(src)
|
202 |
+
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
|
203 |
+
else:
|
204 |
+
for obj, (src, ext) in build.items():
|
205 |
+
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
|
206 |
+
|
207 |
+
# Return *all* object filenames, not just the ones we just built.
|
208 |
+
return objects
|
209 |
+
|
210 |
+
replace_method(CCompiler, 'compile', CCompiler_compile)
|
211 |
+
|
212 |
+
def CCompiler_customize_cmd(self, cmd, ignore=()):
|
213 |
+
"""
|
214 |
+
Customize compiler using distutils command.
|
215 |
+
|
216 |
+
Parameters
|
217 |
+
----------
|
218 |
+
cmd : class instance
|
219 |
+
An instance inheriting from `distutils.cmd.Command`.
|
220 |
+
ignore : sequence of str, optional
|
221 |
+
List of `CCompiler` commands (without ``'set_'``) that should not be
|
222 |
+
altered. Strings that are checked for are:
|
223 |
+
``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',
|
224 |
+
'rpath', 'link_objects')``.
|
225 |
+
|
226 |
+
Returns
|
227 |
+
-------
|
228 |
+
None
|
229 |
+
|
230 |
+
"""
|
231 |
+
log.info('customize %s using %s' % (self.__class__.__name__,
|
232 |
+
cmd.__class__.__name__))
|
233 |
+
def allow(attr):
|
234 |
+
return getattr(cmd, attr, None) is not None and attr not in ignore
|
235 |
+
|
236 |
+
if allow('include_dirs'):
|
237 |
+
self.set_include_dirs(cmd.include_dirs)
|
238 |
+
if allow('define'):
|
239 |
+
for (name, value) in cmd.define:
|
240 |
+
self.define_macro(name, value)
|
241 |
+
if allow('undef'):
|
242 |
+
for macro in cmd.undef:
|
243 |
+
self.undefine_macro(macro)
|
244 |
+
if allow('libraries'):
|
245 |
+
self.set_libraries(self.libraries + cmd.libraries)
|
246 |
+
if allow('library_dirs'):
|
247 |
+
self.set_library_dirs(self.library_dirs + cmd.library_dirs)
|
248 |
+
if allow('rpath'):
|
249 |
+
self.set_runtime_library_dirs(cmd.rpath)
|
250 |
+
if allow('link_objects'):
|
251 |
+
self.set_link_objects(cmd.link_objects)
|
252 |
+
|
253 |
+
replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd)
|
254 |
+
|
255 |
+
def _compiler_to_string(compiler):
|
256 |
+
props = []
|
257 |
+
mx = 0
|
258 |
+
keys = list(compiler.executables.keys())
|
259 |
+
for key in ['version', 'libraries', 'library_dirs',
|
260 |
+
'object_switch', 'compile_switch',
|
261 |
+
'include_dirs', 'define', 'undef', 'rpath', 'link_objects']:
|
262 |
+
if key not in keys:
|
263 |
+
keys.append(key)
|
264 |
+
for key in keys:
|
265 |
+
if hasattr(compiler, key):
|
266 |
+
v = getattr(compiler, key)
|
267 |
+
mx = max(mx, len(key))
|
268 |
+
props.append((key, repr(v)))
|
269 |
+
lines = []
|
270 |
+
format = '%-' + repr(mx+1) + 's = %s'
|
271 |
+
for prop in props:
|
272 |
+
lines.append(format % prop)
|
273 |
+
return '\n'.join(lines)
|
274 |
+
|
275 |
+
def CCompiler_show_customization(self):
|
276 |
+
"""
|
277 |
+
Print the compiler customizations to stdout.
|
278 |
+
|
279 |
+
Parameters
|
280 |
+
----------
|
281 |
+
None
|
282 |
+
|
283 |
+
Returns
|
284 |
+
-------
|
285 |
+
None
|
286 |
+
|
287 |
+
Notes
|
288 |
+
-----
|
289 |
+
Printing is only done if the distutils log threshold is < 2.
|
290 |
+
|
291 |
+
"""
|
292 |
+
if 0:
|
293 |
+
for attrname in ['include_dirs', 'define', 'undef',
|
294 |
+
'libraries', 'library_dirs',
|
295 |
+
'rpath', 'link_objects']:
|
296 |
+
attr = getattr(self, attrname, None)
|
297 |
+
if not attr:
|
298 |
+
continue
|
299 |
+
log.info("compiler '%s' is set to %s" % (attrname, attr))
|
300 |
+
try:
|
301 |
+
self.get_version()
|
302 |
+
except:
|
303 |
+
pass
|
304 |
+
if log._global_log.threshold<2:
|
305 |
+
print('*'*80)
|
306 |
+
print(self.__class__)
|
307 |
+
print(_compiler_to_string(self))
|
308 |
+
print('*'*80)
|
309 |
+
|
310 |
+
replace_method(CCompiler, 'show_customization', CCompiler_show_customization)
|
311 |
+
|
312 |
+
def CCompiler_customize(self, dist, need_cxx=0):
|
313 |
+
"""
|
314 |
+
Do any platform-specific customization of a compiler instance.
|
315 |
+
|
316 |
+
This method calls `distutils.sysconfig.customize_compiler` for
|
317 |
+
platform-specific customization, as well as optionally remove a flag
|
318 |
+
to suppress spurious warnings in case C++ code is being compiled.
|
319 |
+
|
320 |
+
Parameters
|
321 |
+
----------
|
322 |
+
dist : object
|
323 |
+
This parameter is not used for anything.
|
324 |
+
need_cxx : bool, optional
|
325 |
+
Whether or not C++ has to be compiled. If so (True), the
|
326 |
+
``"-Wstrict-prototypes"`` option is removed to prevent spurious
|
327 |
+
warnings. Default is False.
|
328 |
+
|
329 |
+
Returns
|
330 |
+
-------
|
331 |
+
None
|
332 |
+
|
333 |
+
Notes
|
334 |
+
-----
|
335 |
+
All the default options used by distutils can be extracted with::
|
336 |
+
|
337 |
+
from distutils import sysconfig
|
338 |
+
sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
|
339 |
+
'CCSHARED', 'LDSHARED', 'SO')
|
340 |
+
|
341 |
+
"""
|
342 |
+
# See FCompiler.customize for suggested usage.
|
343 |
+
log.info('customize %s' % (self.__class__.__name__))
|
344 |
+
customize_compiler(self)
|
345 |
+
if need_cxx:
|
346 |
+
# In general, distutils uses -Wstrict-prototypes, but this option is
|
347 |
+
# not valid for C++ code, only for C. Remove it if it's there to
|
348 |
+
# avoid a spurious warning on every compilation.
|
349 |
+
try:
|
350 |
+
self.compiler_so.remove('-Wstrict-prototypes')
|
351 |
+
except (AttributeError, ValueError):
|
352 |
+
pass
|
353 |
+
|
354 |
+
if hasattr(self, 'compiler') and 'cc' in self.compiler[0]:
|
355 |
+
if not self.compiler_cxx:
|
356 |
+
if self.compiler[0].startswith('gcc'):
|
357 |
+
a, b = 'gcc', 'g++'
|
358 |
+
else:
|
359 |
+
a, b = 'cc', 'c++'
|
360 |
+
self.compiler_cxx = [self.compiler[0].replace(a, b)]\
|
361 |
+
+ self.compiler[1:]
|
362 |
+
else:
|
363 |
+
if hasattr(self, 'compiler'):
|
364 |
+
log.warn("#### %s #######" % (self.compiler,))
|
365 |
+
log.warn('Missing compiler_cxx fix for '+self.__class__.__name__)
|
366 |
+
return
|
367 |
+
|
368 |
+
replace_method(CCompiler, 'customize', CCompiler_customize)
|
369 |
+
|
370 |
+
def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):
|
371 |
+
"""
|
372 |
+
Simple matching of version numbers, for use in CCompiler and FCompiler.
|
373 |
+
|
374 |
+
Parameters
|
375 |
+
----------
|
376 |
+
pat : str, optional
|
377 |
+
A regular expression matching version numbers.
|
378 |
+
Default is ``r'[-.\\d]+'``.
|
379 |
+
ignore : str, optional
|
380 |
+
A regular expression matching patterns to skip.
|
381 |
+
Default is ``''``, in which case nothing is skipped.
|
382 |
+
start : str, optional
|
383 |
+
A regular expression matching the start of where to start looking
|
384 |
+
for version numbers.
|
385 |
+
Default is ``''``, in which case searching is started at the
|
386 |
+
beginning of the version string given to `matcher`.
|
387 |
+
|
388 |
+
Returns
|
389 |
+
-------
|
390 |
+
matcher : callable
|
391 |
+
A function that is appropriate to use as the ``.version_match``
|
392 |
+
attribute of a `CCompiler` class. `matcher` takes a single parameter,
|
393 |
+
a version string.
|
394 |
+
|
395 |
+
"""
|
396 |
+
def matcher(self, version_string):
|
397 |
+
# version string may appear in the second line, so getting rid
|
398 |
+
# of new lines:
|
399 |
+
version_string = version_string.replace('\n', ' ')
|
400 |
+
pos = 0
|
401 |
+
if start:
|
402 |
+
m = re.match(start, version_string)
|
403 |
+
if not m:
|
404 |
+
return None
|
405 |
+
pos = m.end()
|
406 |
+
while True:
|
407 |
+
m = re.search(pat, version_string[pos:])
|
408 |
+
if not m:
|
409 |
+
return None
|
410 |
+
if ignore and re.match(ignore, m.group(0)):
|
411 |
+
pos = m.end()
|
412 |
+
continue
|
413 |
+
break
|
414 |
+
return m.group(0)
|
415 |
+
return matcher
|
416 |
+
|
417 |
+
def CCompiler_get_version(self, force=False, ok_status=[0]):
|
418 |
+
"""
|
419 |
+
Return compiler version, or None if compiler is not available.
|
420 |
+
|
421 |
+
Parameters
|
422 |
+
----------
|
423 |
+
force : bool, optional
|
424 |
+
If True, force a new determination of the version, even if the
|
425 |
+
compiler already has a version attribute. Default is False.
|
426 |
+
ok_status : list of int, optional
|
427 |
+
The list of status values returned by the version look-up process
|
428 |
+
for which a version string is returned. If the status value is not
|
429 |
+
in `ok_status`, None is returned. Default is ``[0]``.
|
430 |
+
|
431 |
+
Returns
|
432 |
+
-------
|
433 |
+
version : str or None
|
434 |
+
Version string, in the format of `distutils.version.LooseVersion`.
|
435 |
+
|
436 |
+
"""
|
437 |
+
if not force and hasattr(self, 'version'):
|
438 |
+
return self.version
|
439 |
+
self.find_executables()
|
440 |
+
try:
|
441 |
+
version_cmd = self.version_cmd
|
442 |
+
except AttributeError:
|
443 |
+
return None
|
444 |
+
if not version_cmd or not version_cmd[0]:
|
445 |
+
return None
|
446 |
+
try:
|
447 |
+
matcher = self.version_match
|
448 |
+
except AttributeError:
|
449 |
+
try:
|
450 |
+
pat = self.version_pattern
|
451 |
+
except AttributeError:
|
452 |
+
return None
|
453 |
+
def matcher(version_string):
|
454 |
+
m = re.match(pat, version_string)
|
455 |
+
if not m:
|
456 |
+
return None
|
457 |
+
version = m.group('version')
|
458 |
+
return version
|
459 |
+
|
460 |
+
status, output = exec_command(version_cmd, use_tee=0)
|
461 |
+
|
462 |
+
version = None
|
463 |
+
if status in ok_status:
|
464 |
+
version = matcher(output)
|
465 |
+
if version:
|
466 |
+
version = LooseVersion(version)
|
467 |
+
self.version = version
|
468 |
+
return version
|
469 |
+
|
470 |
+
replace_method(CCompiler, 'get_version', CCompiler_get_version)
|
471 |
+
|
472 |
+
def CCompiler_cxx_compiler(self):
|
473 |
+
"""
|
474 |
+
Return the C++ compiler.
|
475 |
+
|
476 |
+
Parameters
|
477 |
+
----------
|
478 |
+
None
|
479 |
+
|
480 |
+
Returns
|
481 |
+
-------
|
482 |
+
cxx : class instance
|
483 |
+
The C++ compiler, as a `CCompiler` instance.
|
484 |
+
|
485 |
+
"""
|
486 |
+
if self.compiler_type=='msvc': return self
|
487 |
+
cxx = copy(self)
|
488 |
+
cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:]
|
489 |
+
if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]:
|
490 |
+
# AIX needs the ld_so_aix script included with Python
|
491 |
+
cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \
|
492 |
+
+ cxx.linker_so[2:]
|
493 |
+
else:
|
494 |
+
cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]
|
495 |
+
return cxx
|
496 |
+
|
497 |
+
replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler)
|
498 |
+
|
499 |
+
compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler',
|
500 |
+
"Intel C Compiler for 32-bit applications")
|
501 |
+
compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler',
|
502 |
+
"Intel C Itanium Compiler for Itanium-based applications")
|
503 |
+
compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler',
|
504 |
+
"Intel C Compiler for 64-bit applications")
|
505 |
+
compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler',
|
506 |
+
"PathScale Compiler for SiCortex-based applications")
|
507 |
+
ccompiler._default_compilers += (('linux.*', 'intel'),
|
508 |
+
('linux.*', 'intele'),
|
509 |
+
('linux.*', 'intelem'),
|
510 |
+
('linux.*', 'pathcc'))
|
511 |
+
|
512 |
+
if sys.platform == 'win32':
|
513 |
+
compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler',
|
514 |
+
"Mingw32 port of GNU C Compiler for Win32"\
|
515 |
+
"(for MSC built Python)")
|
516 |
+
if mingw32():
|
517 |
+
# On windows platforms, we want to default to mingw32 (gcc)
|
518 |
+
# because msvc can't build blitz stuff.
|
519 |
+
log.info('Setting mingw32 as default compiler for nt.')
|
520 |
+
ccompiler._default_compilers = (('nt', 'mingw32'),) \
|
521 |
+
+ ccompiler._default_compilers
|
522 |
+
|
523 |
+
|
524 |
+
_distutils_new_compiler = new_compiler
|
525 |
+
def new_compiler (plat=None,
|
526 |
+
compiler=None,
|
527 |
+
verbose=0,
|
528 |
+
dry_run=0,
|
529 |
+
force=0):
|
530 |
+
# Try first C compilers from numpy.distutils.
|
531 |
+
if plat is None:
|
532 |
+
plat = os.name
|
533 |
+
try:
|
534 |
+
if compiler is None:
|
535 |
+
compiler = get_default_compiler(plat)
|
536 |
+
(module_name, class_name, long_description) = compiler_class[compiler]
|
537 |
+
except KeyError:
|
538 |
+
msg = "don't know how to compile C/C++ code on platform '%s'" % plat
|
539 |
+
if compiler is not None:
|
540 |
+
msg = msg + " with '%s' compiler" % compiler
|
541 |
+
raise DistutilsPlatformError(msg)
|
542 |
+
module_name = "numpy.distutils." + module_name
|
543 |
+
try:
|
544 |
+
__import__ (module_name)
|
545 |
+
except ImportError:
|
546 |
+
msg = str(get_exception())
|
547 |
+
log.info('%s in numpy.distutils; trying from distutils',
|
548 |
+
str(msg))
|
549 |
+
module_name = module_name[6:]
|
550 |
+
try:
|
551 |
+
__import__(module_name)
|
552 |
+
except ImportError:
|
553 |
+
msg = str(get_exception())
|
554 |
+
raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \
|
555 |
+
module_name)
|
556 |
+
try:
|
557 |
+
module = sys.modules[module_name]
|
558 |
+
klass = vars(module)[class_name]
|
559 |
+
except KeyError:
|
560 |
+
raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " +
|
561 |
+
"in module '%s'") % (class_name, module_name))
|
562 |
+
compiler = klass(None, dry_run, force)
|
563 |
+
log.debug('new_compiler returns %s' % (klass))
|
564 |
+
return compiler
|
565 |
+
|
566 |
+
ccompiler.new_compiler = new_compiler
|
567 |
+
|
568 |
+
_distutils_gen_lib_options = gen_lib_options
|
569 |
+
def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
|
570 |
+
library_dirs = quote_args(library_dirs)
|
571 |
+
runtime_library_dirs = quote_args(runtime_library_dirs)
|
572 |
+
r = _distutils_gen_lib_options(compiler, library_dirs,
|
573 |
+
runtime_library_dirs, libraries)
|
574 |
+
lib_opts = []
|
575 |
+
for i in r:
|
576 |
+
if is_sequence(i):
|
577 |
+
lib_opts.extend(list(i))
|
578 |
+
else:
|
579 |
+
lib_opts.append(i)
|
580 |
+
return lib_opts
|
581 |
+
ccompiler.gen_lib_options = gen_lib_options
|
582 |
+
|
583 |
+
# Also fix up the various compiler modules, which do
|
584 |
+
# from distutils.ccompiler import gen_lib_options
|
585 |
+
# Don't bother with mwerks, as we don't support Classic Mac.
|
586 |
+
for _cc in ['msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']:
|
587 |
+
_m = sys.modules.get('distutils.'+_cc+'compiler')
|
588 |
+
if _m is not None:
|
589 |
+
setattr(_m, 'gen_lib_options', gen_lib_options)
|
590 |
+
|
591 |
+
_distutils_gen_preprocess_options = gen_preprocess_options
|
592 |
+
def gen_preprocess_options (macros, include_dirs):
|
593 |
+
include_dirs = quote_args(include_dirs)
|
594 |
+
return _distutils_gen_preprocess_options(macros, include_dirs)
|
595 |
+
ccompiler.gen_preprocess_options = gen_preprocess_options
|
596 |
+
|
597 |
+
##Fix distutils.util.split_quoted:
|
598 |
+
# NOTE: I removed this fix in revision 4481 (see ticket #619), but it appears
|
599 |
+
# that removing this fix causes f2py problems on Windows XP (see ticket #723).
|
600 |
+
# Specifically, on WinXP when gfortran is installed in a directory path, which
|
601 |
+
# contains spaces, then f2py is unable to find it.
|
602 |
+
import re
|
603 |
+
import string
|
604 |
+
_wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
|
605 |
+
_squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
|
606 |
+
_dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
|
607 |
+
_has_white_re = re.compile(r'\s')
|
608 |
+
def split_quoted(s):
|
609 |
+
s = s.strip()
|
610 |
+
words = []
|
611 |
+
pos = 0
|
612 |
+
|
613 |
+
while s:
|
614 |
+
m = _wordchars_re.match(s, pos)
|
615 |
+
end = m.end()
|
616 |
+
if end == len(s):
|
617 |
+
words.append(s[:end])
|
618 |
+
break
|
619 |
+
|
620 |
+
if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
|
621 |
+
words.append(s[:end]) # we definitely have a word delimiter
|
622 |
+
s = s[end:].lstrip()
|
623 |
+
pos = 0
|
624 |
+
|
625 |
+
elif s[end] == '\\': # preserve whatever is being escaped;
|
626 |
+
# will become part of the current word
|
627 |
+
s = s[:end] + s[end+1:]
|
628 |
+
pos = end+1
|
629 |
+
|
630 |
+
else:
|
631 |
+
if s[end] == "'": # slurp singly-quoted string
|
632 |
+
m = _squote_re.match(s, end)
|
633 |
+
elif s[end] == '"': # slurp doubly-quoted string
|
634 |
+
m = _dquote_re.match(s, end)
|
635 |
+
else:
|
636 |
+
raise RuntimeError("this can't happen (bad char '%c')" % s[end])
|
637 |
+
|
638 |
+
if m is None:
|
639 |
+
raise ValueError("bad string (mismatched %s quotes?)" % s[end])
|
640 |
+
|
641 |
+
(beg, end) = m.span()
|
642 |
+
if _has_white_re.search(s[beg+1:end-1]):
|
643 |
+
s = s[:beg] + s[beg+1:end-1] + s[end:]
|
644 |
+
pos = m.end() - 2
|
645 |
+
else:
|
646 |
+
# Keeping quotes when a quoted word does not contain
|
647 |
+
# white-space. XXX: send a patch to distutils
|
648 |
+
pos = m.end()
|
649 |
+
|
650 |
+
if pos >= len(s):
|
651 |
+
words.append(s)
|
652 |
+
break
|
653 |
+
|
654 |
+
return words
|
655 |
+
ccompiler.split_quoted = split_quoted
|
656 |
+
##Fix distutils.util.split_quoted:
|
pip-install-ghxuqwgs/numpy_78e94bf2b6094bf9a1f3d92042f9bf46/build/lib.linux-x86_64-cpython-310/numpy/distutils/command/__init__.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""distutils.command
|
2 |
+
|
3 |
+
Package containing implementation of all the standard Distutils
|
4 |
+
commands.
|
5 |
+
|
6 |
+
"""
|
7 |
+
from __future__ import division, absolute_import, print_function
|
8 |
+
|
9 |
+
def test_na_writable_attributes_deletion():
|
10 |
+
a = np.NA(2)
|
11 |
+
attr = ['payload', 'dtype']
|
12 |
+
for s in attr:
|
13 |
+
assert_raises(AttributeError, delattr, a, s)
|
14 |
+
|
15 |
+
|
16 |
+
__revision__ = "$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $"
|
17 |
+
|
18 |
+
distutils_all = [ #'build_py',
|
19 |
+
'clean',
|
20 |
+
'install_clib',
|
21 |
+
'install_scripts',
|
22 |
+
'bdist',
|
23 |
+
'bdist_dumb',
|
24 |
+
'bdist_wininst',
|
25 |
+
]
|
26 |
+
|
27 |
+
__import__('distutils.command', globals(), locals(), distutils_all)
|
28 |
+
|
29 |
+
__all__ = ['build',
|
30 |
+
'config_compiler',
|
31 |
+
'config',
|
32 |
+
'build_src',
|
33 |
+
'build_py',
|
34 |
+
'build_ext',
|
35 |
+
'build_clib',
|
36 |
+
'build_scripts',
|
37 |
+
'install',
|
38 |
+
'install_data',
|
39 |
+
'install_headers',
|
40 |
+
'install_lib',
|
41 |
+
'bdist_rpm',
|
42 |
+
'sdist',
|
43 |
+
] + distutils_all
|