diff options
117 files changed, 4751 insertions, 1228 deletions
diff --git a/.gitattributes b/.gitattributes index f4b6c0dcf..8cdd176f0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -20,3 +20,4 @@ numpy/core/include/numpy/libdivide/* linguist-vendored numpy/linalg/lapack_lite/f2c_*.c linguist-generated numpy/linalg/lapack_lite/lapack_lite_names.h linguist-generated +numpy/_version.py export-subst diff --git a/.gitignore b/.gitignore index 18317b315..b0fa037a6 100644 --- a/.gitignore +++ b/.gitignore @@ -120,9 +120,7 @@ numpy/__config__.py numpy/core/include/numpy/__multiarray_api.h numpy/core/include/numpy/__ufunc_api.h numpy/core/include/numpy/_numpyconfig.h -numpy/version.py site.cfg -setup.cfg .tox numpy/core/include/numpy/__multiarray_api.c numpy/core/include/numpy/__ufunc_api.c diff --git a/MANIFEST.in b/MANIFEST.in index 35eb05a61..57496ec71 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -48,3 +48,5 @@ global-exclude *.pyc *.pyo *.pyd *.swp *.bak *~ # Exclude license file that we append to the main license when running # `python setup.py sdist` exclude LICENSES_bundled.txt +include versioneer.py +include numpy/_version.py diff --git a/azure-pipelines.yml b/azure-pipelines.yml index f8773dc36..5f7afdaaf 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -258,3 +258,28 @@ stages: failTaskOnFailedTests: true testRunTitle: 'Publish test results for gcc 4.8' + # Native build is based on gcc flag `-march=native` + - job: Linux_baseline_native + pool: + vmImage: 'ubuntu-20.04' + steps: + - script: | + if ! `gcc 2>/dev/null`; then + sudo apt install gcc + fi + sudo apt install python3 + sudo apt install python3-dev + # python3 has no setuptools, so install one to get us going + python3 -m pip install --user --upgrade pip 'setuptools<49.2.0' + python3 -m pip install --user -r test_requirements.txt + displayName: 'install python/requirements' + - script: | + python3 runtests.py --show-build-log --cpu-baseline=native --cpu-dispatch=none \ + --debug-info --mode=full -- -rsx --junitxml=junit/test-results.xml + displayName: 'Run native baseline Build / Tests' + - task: PublishTestResults@2 + condition: succeededOrFailed() + inputs: + testResultsFiles: '**/test-*.xml' + failTaskOnFailedTests: true + testRunTitle: 'Publish test results for baseline/native' diff --git a/benchmarks/asv_compare.conf.json.tpl b/benchmarks/asv_compare.conf.json.tpl index 1f339077c..03d13d985 100644 --- a/benchmarks/asv_compare.conf.json.tpl +++ b/benchmarks/asv_compare.conf.json.tpl @@ -78,7 +78,9 @@ "build_command" : [ "python setup.py build {numpy_build_options}", - "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}" + // pip ignores '--global-option' when pep517 is enabled, we also enabling pip verbose to + // be reached from asv `--verbose` so we can verify the build options. + "PIP_NO_BUILD_ISOLATION=false python {build_dir}/benchmarks/asv_pip_nopep517.py -v {numpy_global_options} --no-deps --no-index -w {build_cache_dir} {build_dir}" ], // The commits after which the regression search in `asv publish` // should start looking for regressions. Dictionary whose keys are diff --git a/benchmarks/asv_pip_nopep517.py b/benchmarks/asv_pip_nopep517.py new file mode 100644 index 000000000..9ba165493 --- /dev/null +++ b/benchmarks/asv_pip_nopep517.py @@ -0,0 +1,15 @@ +""" +This file is used by asv_compare.conf.json.tpl. +""" +import subprocess, sys +# pip ignores '--global-option' when pep517 is enabled therefore we disable it. +cmd = [sys.executable, '-mpip', 'wheel', '--no-use-pep517'] +try: + output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, universal_newlines=True) +except Exception as e: + output = str(e.output) +if "no such option" in output: + print("old version of pip, escape '--no-use-pep517'") + cmd.pop() + +subprocess.run(cmd + sys.argv[1:]) diff --git a/benchmarks/benchmarks/bench_core.py b/benchmarks/benchmarks/bench_core.py index 0c2a18c15..1c028542d 100644 --- a/benchmarks/benchmarks/bench_core.py +++ b/benchmarks/benchmarks/bench_core.py @@ -165,6 +165,9 @@ class PackBits(Benchmark): def time_packbits(self, dtype): np.packbits(self.d) + def time_packbits_little(self, dtype): + np.packbits(self.d, bitorder="little") + def time_packbits_axis0(self, dtype): np.packbits(self.d2, axis=0) diff --git a/doc/Makefile b/doc/Makefile index dd63702de..68d496389 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -49,7 +49,7 @@ help: @echo " show to show the html output in a browser" clean: - -rm -rf build/* + -rm -rf build/* find . -name generated -type d -prune -exec rm -rf "{}" ";" gitwash-update: @@ -66,7 +66,7 @@ gitwash-update: # Build the current numpy version, and extract docs from it. # We have to be careful of some issues: -# +# # - Everything must be done using the same Python version # - We must use eggs (otherwise they might override PYTHONPATH on import). # - Different versions of easy_install install to different directories (!) @@ -80,8 +80,7 @@ UPLOAD_DIR=/srv/docs_scipy_org/doc/numpy-$(RELEASE) DIST_VARS=SPHINXBUILD="LANG=C PYTHONPATH=$(INSTALL_PPH) python$(PYVER) `which sphinx-build`" PYTHON="PYTHONPATH=$(INSTALL_PPH) python$(PYVER)" NUMPYVER:=$(shell $(PYTHON) -c "import numpy; print(numpy.version.git_revision[:10])" 2>/dev/null) -GITVER ?= $(shell cd ..; $(PYTHON) -c "from setup import git_version; \ - print(git_version()[:10])") +GITVER ?= $(shell cd ..; $(PYTHON) -c "import versioneer as v; print(v.get_versions()['full-revisionid'][:10])") version-check: ifeq "$(GITVER)" "Unknown" @@ -163,7 +162,7 @@ endif @echo " <!-- insert here -->" @echo in build/merge/index.html, @echo then \"git commit\", \"git push\" - + #------------------------------------------------------------------------------ # Basic Sphinx generation rules for different formats diff --git a/doc/neps/nep-0013-ufunc-overrides.rst b/doc/neps/nep-0013-ufunc-overrides.rst index 698e45738..4a647e9d3 100644 --- a/doc/neps/nep-0013-ufunc-overrides.rst +++ b/doc/neps/nep-0013-ufunc-overrides.rst @@ -46,8 +46,8 @@ right behaviour, hence the change in name.) The ``__array_ufunc__`` as described below requires that any corresponding Python binary operations (``__mul__`` et al.) should be -implemented in a specific way and be compatible with Numpy's ndarray -semantics. Objects that do not satisfy this cannot override any Numpy +implemented in a specific way and be compatible with NumPy's ndarray +semantics. Objects that do not satisfy this cannot override any NumPy ufuncs. We do not specify a future-compatible path by which this requirement can be relaxed --- any changes here require corresponding changes in 3rd party code. @@ -132,7 +132,7 @@ However, this behavior is more confusing than useful, and having a :exc:`TypeError` would be preferable. This proposal will *not* resolve the issue with scipy.sparse matrices, -which have multiplication semantics incompatible with numpy arrays. +which have multiplication semantics incompatible with NumPy arrays. However, the aim is to enable writing other custom array types that have strictly ndarray compatible semantics. @@ -246,7 +246,7 @@ three groups: - *Incompatible*: neither above nor below A; types for which no (indirect) upcasting is possible. -Note that the legacy behaviour of numpy ufuncs is to try to convert +Note that the legacy behaviour of NumPy ufuncs is to try to convert unknown objects to :class:`ndarray` via :func:`np.asarray`. This is equivalent to placing :class:`ndarray` above these objects in the graph. Since we above defined :class:`ndarray` to return `NotImplemented` for @@ -454,7 +454,7 @@ implements the following behavior: A class wishing to modify the interaction with :class:`ndarray` in binary operations therefore has two options: -1. Implement ``__array_ufunc__`` and follow Numpy semantics for Python +1. Implement ``__array_ufunc__`` and follow NumPy semantics for Python binary operations (see below). 2. Set ``__array_ufunc__ = None``, and implement Python binary @@ -678,7 +678,7 @@ NA ``abs`` :func:`absolute` Future extensions to other functions ------------------------------------ -Some numpy functions could be implemented as (generalized) Ufunc, in +Some NumPy functions could be implemented as (generalized) Ufunc, in which case it would be possible for them to be overridden by the ``__array_ufunc__`` method. A prime candidate is :func:`~numpy.matmul`, which currently is not a Ufunc, but could be relatively easily be diff --git a/doc/neps/nep-0023-backwards-compatibility.rst b/doc/neps/nep-0023-backwards-compatibility.rst index 158f46273..c8bd7c180 100644 --- a/doc/neps/nep-0023-backwards-compatibility.rst +++ b/doc/neps/nep-0023-backwards-compatibility.rst @@ -156,7 +156,7 @@ Removing complete submodules This year there have been suggestions to consider removing some or all of ``numpy.distutils``, ``numpy.f2py``, ``numpy.linalg``, and ``numpy.random``. The motivation was that all these cost maintenance effort, and that they slow -down work on the core of Numpy (ndarrays, dtypes and ufuncs). +down work on the core of NumPy (ndarrays, dtypes and ufuncs). The impact on downstream libraries and users would be very large, and maintenance of these modules would still have to happen. Therefore this is diff --git a/doc/neps/nep-0025-missing-data-3.rst b/doc/neps/nep-0025-missing-data-3.rst index ffe208c98..81045652e 100644 --- a/doc/neps/nep-0025-missing-data-3.rst +++ b/doc/neps/nep-0025-missing-data-3.rst @@ -62,7 +62,7 @@ values, (4) it is compatible with the common practice of using NaN to indicate missingness when working with floating point numbers, (5) the dtype is already a place where "weird things can happen" -- there are a wide variety of dtypes that don't act like ordinary numbers (including structs, Python objects, -fixed-length strings, ...), so code that accepts arbitrary numpy arrays already +fixed-length strings, ...), so code that accepts arbitrary NumPy arrays already has to be prepared to handle these (even if only by checking for them and raising an error). Therefore adding yet more new dtypes has less impact on extension authors than if we change the ndarray object itself. @@ -96,7 +96,7 @@ for consistency. General strategy ================ -Numpy already has a general mechanism for defining new dtypes and slotting them +NumPy already has a general mechanism for defining new dtypes and slotting them in so that they're supported by ndarrays, by the casting machinery, by ufuncs, and so on. In principle, we could implement NA-dtypes just using these existing interfaces. But we don't want to do that, because defining all those new ufunc @@ -271,7 +271,7 @@ below. Casting ------- -FIXME: this really needs attention from an expert on numpy's casting rules. But +FIXME: this really needs attention from an expert on NumPy's casting rules. But I can't seem to find the docs that explain how casting loops are looked up and decided between (e.g., if you're casting from dtype A to dtype B, which dtype's loops are used?), so I can't go into details. But those details are tricky and @@ -338,7 +338,7 @@ Printing -------- FIXME: There should be some sort of mechanism by which values which are NA are -automatically repr'ed as NA, but I don't really understand how numpy printing +automatically repr'ed as NA, but I don't really understand how NumPy printing works, so I'll let someone else fill in this section. Indexing @@ -364,10 +364,10 @@ own global singleton.) So for now we stick to scalar indexing just returning Python API for generic NA support ================================= -NumPy will gain a global singleton called numpy.NA, similar to None, but with +NumPy will gain a global singleton called ``numpy.NA``, similar to None, but with semantics reflecting its status as a missing value. In particular, trying to treat it as a boolean will raise an exception, and comparisons with it will -produce numpy.NA instead of True or False. These basics are adopted from the +produce ``numpy.NA`` instead of True or False. These basics are adopted from the behavior of the NA value in the R project. To dig deeper into the ideas, http://en.wikipedia.org/wiki/Ternary_logic#Kleene_logic provides a starting point. @@ -453,8 +453,8 @@ The NEP also contains a proposal for a somewhat elaborate domain-specific-language for describing NA dtypes. I'm not sure how great an idea that is. (I have a bias against using strings as data structures, and find the already existing strings confusing enough as it is -- also, apparently the -NEP version of numpy uses strings like 'f8' when printing dtypes, while my -numpy uses object names like 'float64', so I'm not sure what's going on there. +NEP version of NumPy uses strings like 'f8' when printing dtypes, while my +NumPy uses object names like 'float64', so I'm not sure what's going on there. ``withNA(float64, arg1=value1)`` seems like a more pleasant way to print a dtype than "NA[f8,value1]", at least to me.) But if people want it, then cool. diff --git a/doc/neps/nep-0027-zero-rank-arrarys.rst b/doc/neps/nep-0027-zero-rank-arrarys.rst index 2d152234c..cb3972675 100644 --- a/doc/neps/nep-0027-zero-rank-arrarys.rst +++ b/doc/neps/nep-0027-zero-rank-arrarys.rst @@ -57,7 +57,7 @@ However there are some important differences: Motivation for Array Scalars ---------------------------- -Numpy's design decision to provide 0-d arrays and array scalars in addition to +NumPy's design decision to provide 0-d arrays and array scalars in addition to native python types goes against one of the fundamental python design principles that there should be only one obvious way to do it. In this section we will try to explain why it is necessary to have three different ways to @@ -109,7 +109,7 @@ arrays to scalars were summarized as follows: are something like Python lists (which except for Object arrays they are not). -Numpy implements a solution that is designed to have all the pros and none of the cons above. +NumPy implements a solution that is designed to have all the pros and none of the cons above. Create Python scalar types for all of the 21 types and also inherit from the three that already exist. Define equivalent diff --git a/doc/neps/nep-0029-deprecation_policy.rst b/doc/neps/nep-0029-deprecation_policy.rst index 957674ee6..a50afcb98 100644 --- a/doc/neps/nep-0029-deprecation_policy.rst +++ b/doc/neps/nep-0029-deprecation_policy.rst @@ -1,7 +1,7 @@ .. _NEP29: ================================================================================== -NEP 29 — Recommend Python and Numpy version support as a community policy standard +NEP 29 — Recommend Python and NumPy version support as a community policy standard ================================================================================== @@ -124,14 +124,14 @@ Drop Schedule :: On next release, drop support for Python 3.5 (initially released on Sep 13, 2015) - On Jan 07, 2020 drop support for Numpy 1.14 (initially released on Jan 06, 2018) + On Jan 07, 2020 drop support for NumPy 1.14 (initially released on Jan 06, 2018) On Jun 23, 2020 drop support for Python 3.6 (initially released on Dec 23, 2016) - On Jul 23, 2020 drop support for Numpy 1.15 (initially released on Jul 23, 2018) - On Jan 13, 2021 drop support for Numpy 1.16 (initially released on Jan 13, 2019) - On Jul 26, 2021 drop support for Numpy 1.17 (initially released on Jul 26, 2019) - On Dec 22, 2021 drop support for Numpy 1.18 (initially released on Dec 22, 2019) + On Jul 23, 2020 drop support for NumPy 1.15 (initially released on Jul 23, 2018) + On Jan 13, 2021 drop support for NumPy 1.16 (initially released on Jan 13, 2019) + On Jul 26, 2021 drop support for NumPy 1.17 (initially released on Jul 26, 2019) + On Dec 22, 2021 drop support for NumPy 1.18 (initially released on Dec 22, 2019) On Dec 26, 2021 drop support for Python 3.7 (initially released on Jun 27, 2018) - On Jun 21, 2022 drop support for Numpy 1.19 (initially released on Jun 20, 2020) + On Jun 21, 2022 drop support for NumPy 1.19 (initially released on Jun 20, 2020) On Apr 14, 2023 drop support for Python 3.8 (initially released on Oct 14, 2019) @@ -249,18 +249,18 @@ Code to generate support and drop schedule tables :: from datetime import datetime, timedelta - data = """Jan 15, 2017: Numpy 1.12 + data = """Jan 15, 2017: NumPy 1.12 Sep 13, 2015: Python 3.5 Dec 23, 2016: Python 3.6 Jun 27, 2018: Python 3.7 - Jun 07, 2017: Numpy 1.13 - Jan 06, 2018: Numpy 1.14 - Jul 23, 2018: Numpy 1.15 - Jan 13, 2019: Numpy 1.16 - Jul 26, 2019: Numpy 1.17 + Jun 07, 2017: NumPy 1.13 + Jan 06, 2018: NumPy 1.14 + Jul 23, 2018: NumPy 1.15 + Jan 13, 2019: NumPy 1.16 + Jul 26, 2019: NumPy 1.17 Oct 14, 2019: Python 3.8 - Dec 22, 2019: Numpy 1.18 - Jun 20, 2020: Numpy 1.19 + Dec 22, 2019: NumPy 1.18 + Jun 20, 2020: NumPy 1.19 """ releases = [] @@ -284,7 +284,7 @@ Code to generate support and drop schedule tables :: py_major,py_minor = sorted([int(x) for x in r[2].split('.')] for r in releases if r[1] == 'Python')[-1] minpy = f"{py_major}.{py_minor+1}+" - num_major,num_minor = sorted([int(x) for x in r[2].split('.')] for r in releases if r[1] == 'Numpy')[-1] + num_major,num_minor = sorted([int(x) for x in r[2].split('.')] for r in releases if r[1] == 'NumPy')[-1] minnum = f"{num_major}.{num_minor+1}+" toprint_drop_dates = [''] diff --git a/doc/neps/nep-0032-remove-financial-functions.rst b/doc/neps/nep-0032-remove-financial-functions.rst index 1c3722f46..bf98a7467 100644 --- a/doc/neps/nep-0032-remove-financial-functions.rst +++ b/doc/neps/nep-0032-remove-financial-functions.rst @@ -174,19 +174,19 @@ References and footnotes .. [1] Financial functions, https://numpy.org/doc/1.17/reference/routines.financial.html -.. [2] Numpy-discussion mailing list, "Simple financial functions for NumPy", +.. [2] NumPy-Discussion mailing list, "Simple financial functions for NumPy", https://mail.python.org/pipermail/numpy-discussion/2008-April/032353.html -.. [3] Numpy-discussion mailing list, "add xirr to numpy financial functions?", +.. [3] NumPy-Discussion mailing list, "add xirr to numpy financial functions?", https://mail.python.org/pipermail/numpy-discussion/2009-May/042645.html -.. [4] Numpy-discussion mailing list, "Definitions of pv, fv, nper, pmt, and rate", +.. [4] NumPy-Discussion mailing list, "Definitions of pv, fv, nper, pmt, and rate", https://mail.python.org/pipermail/numpy-discussion/2009-June/043188.html .. [5] Get financial functions out of main namespace, https://github.com/numpy/numpy/issues/2880 -.. [6] Numpy-discussion mailing list, "Deprecation of financial routines", +.. [6] NumPy-Discussion mailing list, "Deprecation of financial routines", https://mail.python.org/pipermail/numpy-discussion/2013-August/067409.html .. [7] ``component: numpy.lib.financial`` issues, @@ -198,7 +198,7 @@ References and footnotes .. [9] Quansight-Labs/python-api-inspect, https://github.com/Quansight-Labs/python-api-inspect/ -.. [10] Numpy-discussion mailing list, "NEP 32: Remove the financial functions +.. [10] NumPy-Discussion mailing list, "NEP 32: Remove the financial functions from NumPy" https://mail.python.org/pipermail/numpy-discussion/2019-September/079965.html @@ -206,7 +206,7 @@ References and footnotes remove the financial functions. https://mail.google.com/mail/u/0/h/1w0mjgixc4rpe/?&th=16d5c38be45f77c4&q=nep+32&v=c&s=q -.. [12] Numpy-discussion mailing list, "Proposal to accept NEP 32: Remove the +.. [12] NumPy-Discussion mailing list, "Proposal to accept NEP 32: Remove the financial functions from NumPy" https://mail.python.org/pipermail/numpy-discussion/2019-September/080074.html diff --git a/doc/neps/nep-0042-new-dtypes.rst b/doc/neps/nep-0042-new-dtypes.rst index 1a77b5718..1738bd1ab 100644 --- a/doc/neps/nep-0042-new-dtypes.rst +++ b/doc/neps/nep-0042-new-dtypes.rst @@ -8,10 +8,10 @@ NEP 42 — New and extensible DTypes :Author: Sebastian Berg :Author: Ben Nathanson :Author: Marten van Kerkwijk -:Status: Draft +:Status: Accepted :Type: Standard :Created: 2019-07-17 - +:Resolution: https://mail.python.org/pipermail/numpy-discussion/2020-October/081038.html .. note:: diff --git a/doc/release/upcoming_changes/17921.compatibility.rst b/doc/release/upcoming_changes/17921.compatibility.rst new file mode 100644 index 000000000..a1e2fb2d0 --- /dev/null +++ b/doc/release/upcoming_changes/17921.compatibility.rst @@ -0,0 +1,6 @@ +Validate input values in ``Generator.uniform`` +---------------------------------------------- +Checked that ``high - low >= 0`` in ``np.random.Generator.uniform``. Raises +``ValueError`` if ``low > high``. Previously out-of-order inputs were accepted +and silently swapped, so that if ``low > high``, the value generated was +``high + (low - high) * random()``. diff --git a/doc/source/_templates/autosummary/module.rst b/doc/source/_templates/autosummary/module.rst new file mode 100644 index 000000000..e1f428d65 --- /dev/null +++ b/doc/source/_templates/autosummary/module.rst @@ -0,0 +1,40 @@ +{% extends "!autosummary/module.rst" %} + +{# This file is almost the same as the default, but adds :toctree: to the autosummary directives. + The original can be found at `sphinx/ext/autosummary/templates/autosummary/module.rst`. #} + +{% block attributes %} +{% if attributes %} + .. rubric:: Module Attributes + + .. autosummary:: + :toctree: + {% for item in attributes %} + {{ item }} + {%- endfor %} +{% endif %} +{% endblock %} + +{% block functions %} +{% if functions %} + .. rubric:: Functions + + .. autosummary:: + :toctree: + {% for item in functions %} + {{ item }} + {%- endfor %} +{% endif %} +{% endblock %} + +{% block classes %} +{% if classes %} + .. rubric:: Classes + + .. autosummary:: + :toctree: + {% for item in classes %} + {{ item }} + {%- endfor %} +{% endif %} +{% endblock %} diff --git a/doc/source/conf.py b/doc/source/conf.py index 381a01612..e76f60063 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -4,7 +4,7 @@ import re import sys # Minimum version, enforced by sphinx -needs_sphinx = '2.2.0' +needs_sphinx = '3.2.0' # This is a nasty hack to use platform-agnostic names for types in the @@ -146,6 +146,14 @@ def setup(app): app.add_config_value('python_version_major', str(sys.version_info.major), 'env') app.add_lexer('NumPyC', NumPyLexer) +# While these objects do have type `module`, the names are aliases for modules +# elsewhere. Sphinx does not support referring to modules by an aliases name, +# so we make the alias look like a "real" module for it. +# If we deemed it desirable, we could in future make these real modules, which +# would make `from numpy.char import split` work. +sys.modules['numpy.char'] = numpy.char +sys.modules['numpy.testing.dec'] = numpy.testing.dec + # ----------------------------------------------------------------------------- # HTML output # ----------------------------------------------------------------------------- diff --git a/doc/source/reference/arrays.scalars.rst b/doc/source/reference/arrays.scalars.rst index 4b5da2e13..29438f70f 100644 --- a/doc/source/reference/arrays.scalars.rst +++ b/doc/source/reference/arrays.scalars.rst @@ -94,112 +94,141 @@ Python Boolean scalar. .. tip:: The default data type in NumPy is :class:`float_`. .. autoclass:: numpy.generic - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.number - :exclude-members: + :members: __init__ + :exclude-members: __init__ Integer types ~~~~~~~~~~~~~ .. autoclass:: numpy.integer - :exclude-members: + :members: __init__ + :exclude-members: __init__ Signed integer types ++++++++++++++++++++ .. autoclass:: numpy.signedinteger - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.byte - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.short - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.intc - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.int_ - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.longlong - :exclude-members: + :members: __init__ + :exclude-members: __init__ Unsigned integer types ++++++++++++++++++++++ .. autoclass:: numpy.unsignedinteger - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.ubyte - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.ushort - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.uintc - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.uint - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.ulonglong - :exclude-members: + :members: __init__ + :exclude-members: __init__ Inexact types ~~~~~~~~~~~~~ .. autoclass:: numpy.inexact - :exclude-members: + :members: __init__ + :exclude-members: __init__ Floating-point types ++++++++++++++++++++ .. autoclass:: numpy.floating - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.half - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.single - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.double - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.longdouble - :exclude-members: + :members: __init__ + :exclude-members: __init__ Complex floating-point types ++++++++++++++++++++++++++++ .. autoclass:: numpy.complexfloating - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.csingle - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.cdouble - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.clongdouble - :exclude-members: + :members: __init__ + :exclude-members: __init__ Other types ~~~~~~~~~~~ .. autoclass:: numpy.bool_ - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.datetime64 - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.timedelta64 - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.object_ - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. note:: @@ -222,16 +251,20 @@ arrays. (In the character codes ``#`` is an integer denoting how many elements the data type consists of.) .. autoclass:: numpy.flexible - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.bytes_ - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.str_ - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. autoclass:: numpy.void - :exclude-members: + :members: __init__ + :exclude-members: __init__ .. warning:: diff --git a/doc/source/reference/c-api/array.rst b/doc/source/reference/c-api/array.rst index 3aa541b79..1673f1d6b 100644 --- a/doc/source/reference/c-api/array.rst +++ b/doc/source/reference/c-api/array.rst @@ -22,8 +22,8 @@ Array structure and data access These macros access the :c:type:`PyArrayObject` structure members and are defined in ``ndarraytypes.h``. The input argument, *arr*, can be any -:c:type:`PyObject *<PyObject>` that is directly interpretable as a -:c:type:`PyArrayObject *` (any instance of the :c:data:`PyArray_Type` +:c:expr:`PyObject *` that is directly interpretable as a +:c:expr:`PyArrayObject *` (any instance of the :c:data:`PyArray_Type` and its sub-types). .. c:function:: int PyArray_NDIM(PyArrayObject *arr) @@ -825,7 +825,7 @@ General check of Python Type Evaluates true if *op* is an instance of (a subclass of) :c:data:`PyArray_Type` and has 0 dimensions. -.. c:function:: PyArray_IsScalar(op, cls) +.. c:macro:: PyArray_IsScalar(op, cls) Evaluates true if *op* is an instance of ``Py{cls}ArrType_Type``. @@ -864,8 +864,8 @@ Data-type checking For the typenum macros, the argument is an integer representing an enumerated array data type. For the array type checking macros the -argument must be a :c:type:`PyObject *<PyObject>` that can be directly interpreted as a -:c:type:`PyArrayObject *`. +argument must be a :c:expr:`PyObject *` that can be directly interpreted as a +:c:expr:`PyArrayObject *`. .. c:function:: int PyTypeNum_ISUNSIGNED(int num) @@ -1022,7 +1022,7 @@ argument must be a :c:type:`PyObject *<PyObject>` that can be directly interpret .. c:function:: int PyArray_EquivByteorders(int b1, int b2) - True if byteorder characters ( :c:data:`NPY_LITTLE`, + True if byteorder characters *b1* and *b2* ( :c:data:`NPY_LITTLE`, :c:data:`NPY_BIG`, :c:data:`NPY_NATIVE`, :c:data:`NPY_IGNORE` ) are either equal or equivalent as to their specification of a native byte order. Thus, on a little-endian machine :c:data:`NPY_LITTLE` @@ -2781,14 +2781,14 @@ Data-type descriptors Data-type objects must be reference counted so be aware of the action on the data-type reference of different C-API calls. The standard rule is that when a data-type object is returned it is a - new reference. Functions that take :c:type:`PyArray_Descr *` objects and + new reference. Functions that take :c:expr:`PyArray_Descr *` objects and return arrays steal references to the data-type their inputs unless otherwise noted. Therefore, you must own a reference to any data-type object used as input to such a function. .. c:function:: int PyArray_DescrCheck(PyObject* obj) - Evaluates as true if *obj* is a data-type object ( :c:type:`PyArray_Descr *` ). + Evaluates as true if *obj* is a data-type object ( :c:expr:`PyArray_Descr *` ). .. c:function:: PyArray_Descr* PyArray_DescrNew(PyArray_Descr* obj) @@ -3485,10 +3485,6 @@ Miscellaneous Macros Evaluates as True if arrays *a1* and *a2* have the same shape. -.. c:var:: a - -.. c:var:: b - .. c:macro:: PyArray_MAX(a,b) Returns the maximum of *a* and *b*. If (*a*) or (*b*) are @@ -3547,22 +3543,22 @@ Miscellaneous Macros Enumerated Types ^^^^^^^^^^^^^^^^ -.. c:type:: NPY_SORTKIND +.. c:enum:: NPY_SORTKIND A special variable-type which can take on different values to indicate the sorting algorithm being used. - .. c:var:: NPY_QUICKSORT + .. c:enumerator:: NPY_QUICKSORT - .. c:var:: NPY_HEAPSORT + .. c:enumerator:: NPY_HEAPSORT - .. c:var:: NPY_MERGESORT + .. c:enumerator:: NPY_MERGESORT - .. c:var:: NPY_STABLESORT + .. c:enumerator:: NPY_STABLESORT Used as an alias of :c:data:`NPY_MERGESORT` and vica versa. - .. c:var:: NPY_NSORTS + .. c:enumerator:: NPY_NSORTS Defined to be the number of sorts. It is fixed at three by the need for backwards compatibility, and consequently :c:data:`NPY_MERGESORT` and @@ -3570,90 +3566,90 @@ Enumerated Types of several stable sorting algorithms depending on the data type. -.. c:type:: NPY_SCALARKIND +.. c:enum:: NPY_SCALARKIND A special variable type indicating the number of "kinds" of scalars distinguished in determining scalar-coercion rules. This variable can take on the values: - .. c:var:: NPY_NOSCALAR + .. c:enumerator:: NPY_NOSCALAR - .. c:var:: NPY_BOOL_SCALAR + .. c:enumerator:: NPY_BOOL_SCALAR - .. c:var:: NPY_INTPOS_SCALAR + .. c:enumerator:: NPY_INTPOS_SCALAR - .. c:var:: NPY_INTNEG_SCALAR + .. c:enumerator:: NPY_INTNEG_SCALAR - .. c:var:: NPY_FLOAT_SCALAR + .. c:enumerator:: NPY_FLOAT_SCALAR - .. c:var:: NPY_COMPLEX_SCALAR + .. c:enumerator:: NPY_COMPLEX_SCALAR - .. c:var:: NPY_OBJECT_SCALAR + .. c:enumerator:: NPY_OBJECT_SCALAR - .. c:var:: NPY_NSCALARKINDS + .. c:enumerator:: NPY_NSCALARKINDS Defined to be the number of scalar kinds (not including :c:data:`NPY_NOSCALAR`). -.. c:type:: NPY_ORDER +.. c:enum:: NPY_ORDER An enumeration type indicating the element order that an array should be interpreted in. When a brand new array is created, generally only **NPY_CORDER** and **NPY_FORTRANORDER** are used, whereas when one or more inputs are provided, the order can be based on them. - .. c:var:: NPY_ANYORDER + .. c:enumerator:: NPY_ANYORDER Fortran order if all the inputs are Fortran, C otherwise. - .. c:var:: NPY_CORDER + .. c:enumerator:: NPY_CORDER C order. - .. c:var:: NPY_FORTRANORDER + .. c:enumerator:: NPY_FORTRANORDER Fortran order. - .. c:var:: NPY_KEEPORDER + .. c:enumerator:: NPY_KEEPORDER An order as close to the order of the inputs as possible, even if the input is in neither C nor Fortran order. -.. c:type:: NPY_CLIPMODE +.. c:enum:: NPY_CLIPMODE A variable type indicating the kind of clipping that should be applied in certain functions. - .. c:var:: NPY_RAISE + .. c:enumerator:: NPY_RAISE The default for most operations, raises an exception if an index is out of bounds. - .. c:var:: NPY_CLIP + .. c:enumerator:: NPY_CLIP Clips an index to the valid range if it is out of bounds. - .. c:var:: NPY_WRAP + .. c:enumerator:: NPY_WRAP Wraps an index to the valid range if it is out of bounds. -.. c:type:: NPY_SEARCHSIDE +.. c:enum:: NPY_SEARCHSIDE A variable type indicating whether the index returned should be that of the first suitable location (if :c:data:`NPY_SEARCHLEFT`) or of the last (if :c:data:`NPY_SEARCHRIGHT`). - .. c:var:: NPY_SEARCHLEFT + .. c:enumerator:: NPY_SEARCHLEFT - .. c:var:: NPY_SEARCHRIGHT + .. c:enumerator:: NPY_SEARCHRIGHT -.. c:type:: NPY_SELECTKIND +.. c:enum:: NPY_SELECTKIND A variable type indicating the selection algorithm being used. - .. c:var:: NPY_INTROSELECT + .. c:enumerator:: NPY_INTROSELECT -.. c:type:: NPY_CASTING +.. c:enum:: NPY_CASTING .. versionadded:: 1.6 @@ -3661,25 +3657,25 @@ Enumerated Types be. This is used by the iterator added in NumPy 1.6, and is intended to be used more broadly in a future version. - .. c:var:: NPY_NO_CASTING + .. c:enumerator:: NPY_NO_CASTING Only allow identical types. - .. c:var:: NPY_EQUIV_CASTING + .. c:enumerator:: NPY_EQUIV_CASTING Allow identical and casts involving byte swapping. - .. c:var:: NPY_SAFE_CASTING + .. c:enumerator:: NPY_SAFE_CASTING Only allow casts which will not cause values to be rounded, truncated, or otherwise changed. - .. c:var:: NPY_SAME_KIND_CASTING + .. c:enumerator:: NPY_SAME_KIND_CASTING Allow any safe casts, and casts between types of the same kind. For example, float64 -> float32 is permitted with this rule. - .. c:var:: NPY_UNSAFE_CASTING + .. c:enumerator:: NPY_UNSAFE_CASTING Allow any cast, no matter what kind of data loss may occur. diff --git a/doc/source/reference/c-api/coremath.rst b/doc/source/reference/c-api/coremath.rst index 338c584a1..cec83b150 100644 --- a/doc/source/reference/c-api/coremath.rst +++ b/doc/source/reference/c-api/coremath.rst @@ -46,30 +46,30 @@ Floating point classification corresponding single and extension precision macro are available with the suffix F and L. -.. c:function:: int npy_isnan(x) +.. c:macro:: npy_isnan(x) This is a macro, and is equivalent to C99 isnan: works for single, double and extended precision, and return a non 0 value is x is a NaN. -.. c:function:: int npy_isfinite(x) +.. c:macro:: npy_isfinite(x) This is a macro, and is equivalent to C99 isfinite: works for single, double and extended precision, and return a non 0 value is x is neither a NaN nor an infinity. -.. c:function:: int npy_isinf(x) +.. c:macro:: npy_isinf(x) This is a macro, and is equivalent to C99 isinf: works for single, double and extended precision, and return a non 0 value is x is infinite (positive and negative). -.. c:function:: int npy_signbit(x) +.. c:macro:: npy_signbit(x) This is a macro, and is equivalent to C99 signbit: works for single, double and extended precision, and return a non 0 value is x has the signbit set (that is the number is negative). -.. c:function:: double npy_copysign(double x, double y) +.. c:macro:: npy_copysign(x, y) This is a function equivalent to C99 copysign: return x with the same sign as y. Works for any value, including inf and nan. Single and extended diff --git a/doc/source/reference/c-api/dtype.rst b/doc/source/reference/c-api/dtype.rst index a1a53cdb6..382e45dc0 100644 --- a/doc/source/reference/c-api/dtype.rst +++ b/doc/source/reference/c-api/dtype.rst @@ -25,157 +25,157 @@ select the precision desired. Enumerated Types ---------------- -.. c:var:: NPY_TYPES +.. c:enumerator:: NPY_TYPES There is a list of enumerated types defined providing the basic 24 data types plus some useful generic names. Whenever the code requires a type number, one of these enumerated types is requested. The types are all called ``NPY_{NAME}``: -.. c:var:: NPY_BOOL +.. c:enumerator:: NPY_BOOL The enumeration value for the boolean type, stored as one byte. It may only be set to the values 0 and 1. -.. c:var:: NPY_BYTE -.. c:var:: NPY_INT8 +.. c:enumerator:: NPY_BYTE +.. c:enumerator:: NPY_INT8 The enumeration value for an 8-bit/1-byte signed integer. -.. c:var:: NPY_SHORT -.. c:var:: NPY_INT16 +.. c:enumerator:: NPY_SHORT +.. c:enumerator:: NPY_INT16 The enumeration value for a 16-bit/2-byte signed integer. -.. c:var:: NPY_INT -.. c:var:: NPY_INT32 +.. c:enumerator:: NPY_INT +.. c:enumerator:: NPY_INT32 The enumeration value for a 32-bit/4-byte signed integer. -.. c:var:: NPY_LONG +.. c:enumerator:: NPY_LONG Equivalent to either NPY_INT or NPY_LONGLONG, depending on the platform. -.. c:var:: NPY_LONGLONG -.. c:var:: NPY_INT64 +.. c:enumerator:: NPY_LONGLONG +.. c:enumerator:: NPY_INT64 The enumeration value for a 64-bit/8-byte signed integer. -.. c:var:: NPY_UBYTE -.. c:var:: NPY_UINT8 +.. c:enumerator:: NPY_UBYTE +.. c:enumerator:: NPY_UINT8 The enumeration value for an 8-bit/1-byte unsigned integer. -.. c:var:: NPY_USHORT -.. c:var:: NPY_UINT16 +.. c:enumerator:: NPY_USHORT +.. c:enumerator:: NPY_UINT16 The enumeration value for a 16-bit/2-byte unsigned integer. -.. c:var:: NPY_UINT -.. c:var:: NPY_UINT32 +.. c:enumerator:: NPY_UINT +.. c:enumerator:: NPY_UINT32 The enumeration value for a 32-bit/4-byte unsigned integer. -.. c:var:: NPY_ULONG +.. c:enumerator:: NPY_ULONG Equivalent to either NPY_UINT or NPY_ULONGLONG, depending on the platform. -.. c:var:: NPY_ULONGLONG -.. c:var:: NPY_UINT64 +.. c:enumerator:: NPY_ULONGLONG +.. c:enumerator:: NPY_UINT64 The enumeration value for a 64-bit/8-byte unsigned integer. -.. c:var:: NPY_HALF -.. c:var:: NPY_FLOAT16 +.. c:enumerator:: NPY_HALF +.. c:enumerator:: NPY_FLOAT16 The enumeration value for a 16-bit/2-byte IEEE 754-2008 compatible floating point type. -.. c:var:: NPY_FLOAT -.. c:var:: NPY_FLOAT32 +.. c:enumerator:: NPY_FLOAT +.. c:enumerator:: NPY_FLOAT32 The enumeration value for a 32-bit/4-byte IEEE 754 compatible floating point type. -.. c:var:: NPY_DOUBLE -.. c:var:: NPY_FLOAT64 +.. c:enumerator:: NPY_DOUBLE +.. c:enumerator:: NPY_FLOAT64 The enumeration value for a 64-bit/8-byte IEEE 754 compatible floating point type. -.. c:var:: NPY_LONGDOUBLE +.. c:enumerator:: NPY_LONGDOUBLE The enumeration value for a platform-specific floating point type which is at least as large as NPY_DOUBLE, but larger on many platforms. -.. c:var:: NPY_CFLOAT -.. c:var:: NPY_COMPLEX64 +.. c:enumerator:: NPY_CFLOAT +.. c:enumerator:: NPY_COMPLEX64 The enumeration value for a 64-bit/8-byte complex type made up of two NPY_FLOAT values. -.. c:var:: NPY_CDOUBLE -.. c:var:: NPY_COMPLEX128 +.. c:enumerator:: NPY_CDOUBLE +.. c:enumerator:: NPY_COMPLEX128 The enumeration value for a 128-bit/16-byte complex type made up of two NPY_DOUBLE values. -.. c:var:: NPY_CLONGDOUBLE +.. c:enumerator:: NPY_CLONGDOUBLE The enumeration value for a platform-specific complex floating point type which is made up of two NPY_LONGDOUBLE values. -.. c:var:: NPY_DATETIME +.. c:enumerator:: NPY_DATETIME The enumeration value for a data type which holds dates or datetimes with a precision based on selectable date or time units. -.. c:var:: NPY_TIMEDELTA +.. c:enumerator:: NPY_TIMEDELTA The enumeration value for a data type which holds lengths of times in integers of selectable date or time units. -.. c:var:: NPY_STRING +.. c:enumerator:: NPY_STRING The enumeration value for ASCII strings of a selectable size. The strings have a fixed maximum size within a given array. -.. c:var:: NPY_UNICODE +.. c:enumerator:: NPY_UNICODE The enumeration value for UCS4 strings of a selectable size. The strings have a fixed maximum size within a given array. -.. c:var:: NPY_OBJECT +.. c:enumerator:: NPY_OBJECT The enumeration value for references to arbitrary Python objects. -.. c:var:: NPY_VOID +.. c:enumerator:: NPY_VOID Primarily used to hold struct dtypes, but can contain arbitrary binary data. Some useful aliases of the above types are -.. c:var:: NPY_INTP +.. c:enumerator:: NPY_INTP The enumeration value for a signed integer type which is the same size as a (void \*) pointer. This is the type used by all arrays of indices. -.. c:var:: NPY_UINTP +.. c:enumerator:: NPY_UINTP The enumeration value for an unsigned integer type which is the same size as a (void \*) pointer. -.. c:var:: NPY_MASK +.. c:enumerator:: NPY_MASK The enumeration value of the type used for masks, such as with the :c:data:`NPY_ITER_ARRAYMASK` iterator flag. This is equivalent to :c:data:`NPY_UINT8`. -.. c:var:: NPY_DEFAULT_TYPE +.. c:enumerator:: NPY_DEFAULT_TYPE The default type to use when no dtype is explicitly specified, for example when calling np.zero(shape). This is equivalent to @@ -297,9 +297,13 @@ Boolean Unsigned versions of the integers can be defined by pre-pending a 'u' to the front of the integer name. -.. c:type:: npy_(u)byte +.. c:type:: npy_byte - (unsigned) char + char + +.. c:type:: npy_ubyte + + unsigned char .. c:type:: npy_short @@ -309,14 +313,14 @@ to the front of the integer name. unsigned short -.. c:type:: npy_uint - - unsigned int - .. c:type:: npy_int int +.. c:type:: npy_uint + + unsigned int + .. c:type:: npy_int16 16-bit integer @@ -341,13 +345,21 @@ to the front of the integer name. 64-bit unsigned integer -.. c:type:: npy_(u)long +.. c:type:: npy_long - (unsigned) long int + long int -.. c:type:: npy_(u)longlong +.. c:type:: npy_ulong - (unsigned long long int) + unsigned long int + +.. c:type:: npy_longlong + + long long int + +.. c:type:: npy_ulonglong + + unsigned long long int .. c:type:: npy_intp @@ -367,18 +379,30 @@ to the front of the integer name. 16-bit float -.. c:type:: npy_(c)float +.. c:type:: npy_float 32-bit float -.. c:type:: npy_(c)double +.. c:type:: npy_cfloat + + 32-bit complex float + +.. c:type:: npy_double 64-bit double -.. c:type:: npy_(c)longdouble +.. c:type:: npy_cdouble + + 64-bit complex double + +.. c:type:: npy_longdouble long double +.. c:type:: npy_clongdouble + + long complex double + complex types are structures with **.real** and **.imag** members (in that order). diff --git a/doc/source/reference/c-api/iterator.rst b/doc/source/reference/c-api/iterator.rst index ae96bb3fb..add96e3b4 100644 --- a/doc/source/reference/c-api/iterator.rst +++ b/doc/source/reference/c-api/iterator.rst @@ -370,7 +370,7 @@ Construction and Destruction arrays or structured arrays containing an object type) may be accepted and used in the iterator. If this flag is enabled, the caller must be sure to check whether - :c:func:`NpyIter_IterationNeedsAPI(iter)` is true, in which case + :c:expr:`NpyIter_IterationNeedsAPI(iter)` is true, in which case it may not release the GIL during iteration. .. c:macro:: NPY_ITER_ZEROSIZE_OK @@ -738,7 +738,7 @@ Construction and Destruction the iterator. Any cached functions or pointers from the iterator must be retrieved again! - After calling this function, :c:func:`NpyIter_HasMultiIndex(iter)` will + After calling this function, :c:expr:`NpyIter_HasMultiIndex(iter)` will return false. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. diff --git a/doc/source/reference/c-api/types-and-structures.rst b/doc/source/reference/c-api/types-and-structures.rst index 763f985a6..ab82fda87 100644 --- a/doc/source/reference/c-api/types-and-structures.rst +++ b/doc/source/reference/c-api/types-and-structures.rst @@ -7,7 +7,7 @@ Python Types and C-Structures Several new types are defined in the C-code. Most of these are accessible from Python, but a few are not exposed due to their limited -use. Every new Python type has an associated :c:type:`PyObject *<PyObject>` with an +use. Every new Python type has an associated :c:expr:`PyObject *` with an internal structure that includes a pointer to a "method table" that defines how the new object behaves in Python. When you receive a Python object into C code, you always get a pointer to a @@ -61,7 +61,7 @@ hierarchy of actual Python types. PyArray_Type and PyArrayObject ------------------------------ -.. c:var:: PyArray_Type +.. c:var:: PyTypeObject PyArray_Type The Python type of the ndarray is :c:data:`PyArray_Type`. In C, every ndarray is a pointer to a :c:type:`PyArrayObject` structure. The ob_type @@ -201,7 +201,7 @@ PyArray_Type and PyArrayObject PyArrayDescr_Type and PyArray_Descr ----------------------------------- -.. c:var:: PyArrayDescr_Type +.. c:var:: PyTypeObject PyArrayDescr_Type The :c:data:`PyArrayDescr_Type` is the built-in type of the data-type-descriptor objects used to describe how the bytes comprising @@ -636,7 +636,7 @@ PyArrayDescr_Type and PyArray_Descr Either ``NULL`` or a dictionary containing low-level casting functions for user- defined data-types. Each function is - wrapped in a :c:type:`PyCapsule *<PyCapsule>` and keyed by + wrapped in a :c:expr:`PyCapsule *` and keyed by the data-type number. .. c:member:: NPY_SCALARKIND scalarkind(PyArrayObject* arr) @@ -754,7 +754,7 @@ The :c:data:`PyArray_Type` can also be sub-typed. PyUFunc_Type and PyUFuncObject ------------------------------ -.. c:var:: PyUFunc_Type +.. c:var:: PyTypeObject PyUFunc_Type The ufunc object is implemented by creation of the :c:data:`PyUFunc_Type`. It is a very simple type that implements only @@ -1006,7 +1006,7 @@ PyUFunc_Type and PyUFuncObject PyArrayIter_Type and PyArrayIterObject -------------------------------------- -.. c:var:: PyArrayIter_Type +.. c:var:: PyTypeObject PyArrayIter_Type This is an iterator object that makes it easy to loop over an N-dimensional array. It is the object returned from the flat @@ -1110,13 +1110,13 @@ the internal structure of the iterator object, and merely interact with it through the use of the macros :c:func:`PyArray_ITER_NEXT` (it), :c:func:`PyArray_ITER_GOTO` (it, dest), or :c:func:`PyArray_ITER_GOTO1D` (it, index). All of these macros require the argument *it* to be a -:c:type:`PyArrayIterObject *`. +:c:expr:`PyArrayIterObject *`. PyArrayMultiIter_Type and PyArrayMultiIterObject ------------------------------------------------ -.. c:var:: PyArrayMultiIter_Type +.. c:var:: PyTypeObject PyArrayMultiIter_Type This type provides an iterator that encapsulates the concept of broadcasting. It allows :math:`N` arrays to be broadcast together @@ -1178,7 +1178,7 @@ PyArrayMultiIter_Type and PyArrayMultiIterObject PyArrayNeighborhoodIter_Type and PyArrayNeighborhoodIterObject -------------------------------------------------------------- -.. c:var:: PyArrayNeighborhoodIter_Type +.. c:var:: PyTypeObject PyArrayNeighborhoodIter_Type This is an iterator object that makes it easy to loop over an N-dimensional neighborhood. @@ -1217,7 +1217,7 @@ PyArrayNeighborhoodIter_Type and PyArrayNeighborhoodIterObject PyArrayFlags_Type and PyArrayFlagsObject ---------------------------------------- -.. c:var:: PyArrayFlags_Type +.. c:var:: PyTypeObject PyArrayFlags_Type When the flags attribute is retrieved from Python, a special builtin object of this type is constructed. This special type makes @@ -1466,7 +1466,7 @@ for completeness and assistance in understanding the code. to define a 1-d loop for a ufunc for every defined signature of a user-defined data-type. -.. c:var:: PyArrayMapIter_Type +.. c:var:: PyTypeObject PyArrayMapIter_Type Advanced indexing is handled with this Python type. It is simply a loose wrapper around the C-structure containing the variables diff --git a/doc/source/reference/random/bit_generators/index.rst b/doc/source/reference/random/bit_generators/index.rst index 315657172..6f8cf02ca 100644 --- a/doc/source/reference/random/bit_generators/index.rst +++ b/doc/source/reference/random/bit_generators/index.rst @@ -105,6 +105,44 @@ If you need to generate a good seed "offline", then ``SeedSequence().entropy`` or using ``secrets.randbits(128)`` from the standard library are both convenient ways. +If you need to run several stochastic simulations in parallel, best practice +is to construct a random generator instance for each simulation. +To make sure that the random streams have distinct initial states, you can use +the `spawn` method of `~SeedSequence`. For instance, here we construct a list +of 12 instances: + +.. code-block:: python + + from numpy.random import PCG64, SeedSequence + + # High quality initial entropy + entropy = 0x87351080e25cb0fad77a44a3be03b491 + base_seq = SeedSequence(entropy) + child_seqs = base_seq.spawn(12) # a list of 12 SeedSequences + generators = [PCG64(seq) for seq in child_seqs] + +.. end_block + + +An alternative way is to use the fact that a `~SeedSequence` can be initialized +by a tuple of elements. Here we use a base entropy value and an integer +``worker_id`` + +.. code-block:: python + + from numpy.random import PCG64, SeedSequence + + # High quality initial entropy + entropy = 0x87351080e25cb0fad77a44a3be03b491 + sequences = [SeedSequence((entropy, worker_id)) for worker_id in range(12)] + generators = [PCG64(seq) for seq in sequences] + +.. end_block + +Note that the sequences produced by the latter method will be distinct from +those constructed via `~SeedSequence.spawn`. + + .. autosummary:: :toctree: generated/ diff --git a/doc/source/reference/random/bit_generators/mt19937.rst b/doc/source/reference/random/bit_generators/mt19937.rst index 71875db4e..d05ea7c6f 100644 --- a/doc/source/reference/random/bit_generators/mt19937.rst +++ b/doc/source/reference/random/bit_generators/mt19937.rst @@ -4,7 +4,8 @@ Mersenne Twister (MT19937) .. currentmodule:: numpy.random .. autoclass:: MT19937 - :exclude-members: + :members: __init__ + :exclude-members: __init__ State ===== diff --git a/doc/source/reference/random/bit_generators/pcg64.rst b/doc/source/reference/random/bit_generators/pcg64.rst index edac4620b..889965f77 100644 --- a/doc/source/reference/random/bit_generators/pcg64.rst +++ b/doc/source/reference/random/bit_generators/pcg64.rst @@ -4,7 +4,8 @@ Permuted Congruential Generator (64-bit, PCG64) .. currentmodule:: numpy.random .. autoclass:: PCG64 - :exclude-members: + :members: __init__ + :exclude-members: __init__ State ===== diff --git a/doc/source/reference/random/bit_generators/philox.rst b/doc/source/reference/random/bit_generators/philox.rst index 8eba2d351..3c2fa4cc5 100644 --- a/doc/source/reference/random/bit_generators/philox.rst +++ b/doc/source/reference/random/bit_generators/philox.rst @@ -4,7 +4,8 @@ Philox Counter-based RNG .. currentmodule:: numpy.random .. autoclass:: Philox - :exclude-members: + :members: __init__ + :exclude-members: __init__ State ===== diff --git a/doc/source/reference/random/bit_generators/sfc64.rst b/doc/source/reference/random/bit_generators/sfc64.rst index d34124a33..8cb255bc1 100644 --- a/doc/source/reference/random/bit_generators/sfc64.rst +++ b/doc/source/reference/random/bit_generators/sfc64.rst @@ -4,7 +4,8 @@ SFC64 Small Fast Chaotic PRNG .. currentmodule:: numpy.random .. autoclass:: SFC64 - :exclude-members: + :members: __init__ + :exclude-members: __init__ State ===== diff --git a/doc/source/reference/random/generator.rst b/doc/source/reference/random/generator.rst index 8706e1de2..a359d2253 100644 --- a/doc/source/reference/random/generator.rst +++ b/doc/source/reference/random/generator.rst @@ -15,7 +15,8 @@ can be changed by passing an instantized BitGenerator to ``Generator``. .. autofunction:: default_rng .. autoclass:: Generator - :exclude-members: + :members: __init__ + :exclude-members: __init__ Accessing the BitGenerator ========================== diff --git a/doc/source/reference/random/legacy.rst b/doc/source/reference/random/legacy.rst index 6cf4775b8..42437dbb6 100644 --- a/doc/source/reference/random/legacy.rst +++ b/doc/source/reference/random/legacy.rst @@ -48,7 +48,8 @@ using the state of the `RandomState`: .. autoclass:: RandomState - :exclude-members: + :members: __init__ + :exclude-members: __init__ Seeding and State ================= diff --git a/doc/source/reference/routines.polynomials.rst b/doc/source/reference/routines.polynomials.rst index e74c5a683..da481ae4c 100644 --- a/doc/source/reference/routines.polynomials.rst +++ b/doc/source/reference/routines.polynomials.rst @@ -9,24 +9,165 @@ of the `numpy.polynomial` package, introduced in NumPy 1.4. Prior to NumPy 1.4, `numpy.poly1d` was the class of choice and it is still available in order to maintain backward compatibility. -However, the newer Polynomial package is more complete than `numpy.poly1d` -and its convenience classes are better behaved in the numpy environment. +However, the newer `polynomial package <numpy.polynomial>` is more complete +and its `convenience classes <routines.polynomials.classes>` provide a +more consistent, better-behaved interface for working with polynomial +expressions. Therefore :mod:`numpy.polynomial` is recommended for new coding. -Transition notice ------------------ -The various routines in the Polynomial package all deal with -series whose coefficients go from degree zero upward, -which is the *reverse order* of the Poly1d convention. -The easy way to remember this is that indexes -correspond to degree, i.e., coef[i] is the coefficient of the term of -degree i. +.. note:: **Terminology** + The term *polynomial module* refers to the old API defined in + `numpy.lib.polynomial`, which includes the :class:`numpy.poly1d` class and + the polynomial functions prefixed with *poly* accessible from the `numpy` + namespace (e.g. `numpy.polyadd`, `numpy.polyval`, `numpy.polyfit`, etc.). + + The term *polynomial package* refers to the new API definied in + `numpy.polynomial`, which includes the convenience classes for the + different kinds of polynomials (`numpy.polynomial.Polynomial`, + `numpy.polynomial.Chebyshev`, etc.). + +Transitioning from `numpy.poly1d` to `numpy.polynomial` +------------------------------------------------------- + +As noted above, the :class:`poly1d class <numpy.poly1d>` and associated +functions defined in ``numpy.lib.polynomial``, such as `numpy.polyfit` +and `numpy.poly`, are considered legacy and should **not** be used in new +code. +Since NumPy version 1.4, the `numpy.polynomial` package is preferred for +working with polynomials. + +Quick Reference +~~~~~~~~~~~~~~~ + +The following table highlights some of the main differences between the +legacy polynomial module and the polynomial package for common tasks. +The `~numpy.polynomial.polynomial.Polynomial` class is imported for brevity:: + + from numpy.polynomial import Polynomial + + ++------------------------+------------------------------+---------------------------------------+ +| **How to...** | Legacy (`numpy.poly1d`) | `numpy.polynomial` | ++------------------------+------------------------------+---------------------------------------+ +| Create a | ``p = np.poly1d([1, 2, 3])`` | ``p = Polynomial([3, 2, 1])`` | +| polynomial object | | | +| from coefficients [1]_ | | | ++------------------------+------------------------------+---------------------------------------+ +| Create a polynomial | ``r = np.poly([-1, 1])`` | ``p = Polynomial.fromroots([-1, 1])`` | +| object from roots | ``p = np.poly1d(r)`` | | ++------------------------+------------------------------+---------------------------------------+ +| Fit a polynomial of | | | +| degree ``deg`` to data | ``np.polyfit(x, y, deg)`` | ``Polynomial.fit(x, y, deg)`` | ++------------------------+------------------------------+---------------------------------------+ + + +.. [1] Note the reversed ordering of the coefficients + +Transition Guide +~~~~~~~~~~~~~~~~ + +There are significant differences between ``numpy.lib.polynomial`` and +`numpy.polynomial`. +The most significant difference is the ordering of the coefficients for the +polynomial expressions. +The various routines in `numpy.polynomial` all +deal with series whose coefficients go from degree zero upward, +which is the *reverse order* of the poly1d convention. +The easy way to remember this is that indices +correspond to degree, i.e., ``coef[i]`` is the coefficient of the term of +degree *i*. + +Though the difference in convention may be confusing, it is straightforward to +convert from the legacy polynomial API to the new. +For example, the following demonstrates how you would convert a `numpy.poly1d` +instance representing the expression :math:`x^{2} + 2x + 3` to a +`~numpy.polynomial.polynomial.Polynomial` instance representing the same +expression:: + + >>> p1d = np.poly1d([1, 2, 3]) + >>> p = np.polynomial.Polynomial(p1d.coef[::-1]) + +In addition to the ``coef`` attribute, polynomials from the polynomial +package also have ``domain`` and ``window`` attributes. +These attributes are most relevant when fitting +polynomials to data, though it should be noted that polynomials with +different ``domain`` and ``window`` attributes are not considered equal, and +can't be mixed in arithmetic:: + + >>> p1 = np.polynomial.Polynomial([1, 2, 3]) + >>> p1 + Polynomial([1., 2., 3.], domain=[-1, 1], window=[-1, 1]) + >>> p2 = np.polynomial.Polynomial([1, 2, 3], domain=[-2, 2]) + >>> p1 == p2 + False + >>> p1 + p2 + Traceback (most recent call last): + ... + TypeError: Domains differ + +See the documentation for the +`convenience classes <routines.polynomials.classes>`_ for further details on +the ``domain`` and ``window`` attributes. + +Another major difference bewteen the legacy polynomial module and the +polynomial package is polynomial fitting. In the old module, fitting was +done via the `~numpy.polyfit` function. In the polynomial package, the +`~numpy.polynomial.polynomial.Polynomial.fit` class method is preferred. For +example, consider a simple linear fit to the following data: + +.. ipython:: python + + rg = np.random.default_rng() + x = np.arange(10) + y = np.arange(10) + rg.standard_normal(10) + +With the legacy polynomial module, a linear fit (i.e. polynomial of degree 1) +could be applied to these data with `~numpy.polyfit`: + +.. ipython:: python + + np.polyfit(x, y, deg=1) + +With the new polynomial API, the `~numpy.polynomial.polynomial.Polynomial.fit` +class method is preferred: + +.. ipython:: python + + p_fitted = np.polynomial.Polynomial.fit(x, y, deg=1) + p_fitted + +Note that the coefficients are given *in the scaled domain* defined by the +linear mapping between the ``window`` and ``domain``. +`~numpy.polynomial.polynomial.Polynomial.convert` can be used to get the +coefficients in the unscaled data domain. + +.. ipython:: python + + p_fitted.convert() + +Documentation for the `~numpy.polynomial` Package +------------------------------------------------- + +In addition to standard power series polynomials, the polynomial package +provides several additional kinds of polynomials including Chebyshev, +Hermite (two subtypes), Laguerre, and Legendre polynomials. +Each of these has an associated +`convenience class <routines.polynomials.classes>` available from the +`numpy.polynomial` namespace that provides a consistent interface for working +with polynomials regardless of their type. .. toctree:: :maxdepth: 1 routines.polynomials.classes + +Documentation pertaining to specific functions defined for each kind of +polynomial individually can be found in the corresponding module documentation: + +.. toctree:: + :maxdepth: 1 + routines.polynomials.polynomial routines.polynomials.chebyshev routines.polynomials.hermite @@ -36,6 +177,9 @@ degree i. routines.polynomials.polyutils +Documentation for Legacy Polynomials +------------------------------------ + .. toctree:: :maxdepth: 2 diff --git a/doc/source/release/1.20.0-notes.rst b/doc/source/release/1.20.0-notes.rst index 9f46a3e80..e26aa0d40 100644 --- a/doc/source/release/1.20.0-notes.rst +++ b/doc/source/release/1.20.0-notes.rst @@ -184,6 +184,43 @@ Use ``next(it)`` instead of ``it.ndincr()``. (`gh-17233 <https://github.com/numpy/numpy/pull/17233>`__) +ArrayLike objects which do not define ``__len__`` and ``__getitem__`` +--------------------------------------------------------------------- +Objects which define one of the protocols ``__array__``, +``__array_interface__``, or ``__array_struct__`` but are not sequences +(usually defined by having a ``__len__`` and ``__getitem__``) will behave +differently during array-coercion in the future. + +When nested inside sequences, such as ``np.array([array_like])``, these +were handled as a single Python object rather than an array. +In the future they will behave identically to:: + + np.array([np.array(array_like)]) + +This change should only have an effect if ``np.array(array_like)`` is not 0-D. +The solution to this warning may depend on the object: + +* Some array-likes may expect the new behaviour, and users can ignore the + warning. The object can choose to expose the sequence protocol to opt-in + to the new behaviour. +* For example, ``shapely`` will allow conversion to an array-like using + ``line.coords`` rather than ``np.asarray(line)``. Users may work around + the warning, or use the new convention when it becomes available. + +Unfortunately, using the new behaviour can only be achieved by +calling ``np.array(array_like)``. + +If you wish to ensure that the old behaviour remains unchanged, please create +an object array and then fill it explicitly, for example:: + + arr = np.empty(3, dtype=object) + arr[:] = [array_like1, array_like2, array_like3] + +This will ensure NumPy knows to not enter the array-like and use it as +a object instead. + +(`gh-17973 <https://github.com/numpy/numpy/pull/17973>`__) + Future Changes ============== @@ -349,9 +386,15 @@ Things will now be more consistent with:: np.array([np.array(array_like1)]) -This could potentially subtly change output for badly defined array-likes. -We are not aware of any such case where the results were not clearly -incorrect previously. +This can subtly change output for some badly defined array-likes. +One example for this are array-like objects which are not also sequences +of matching shape. +In NumPy 1.20, a warning will be given when an array-like is not also a +sequence (but behaviour remains identical, see deprecations). +If an array like is also a sequence (defines ``__getitem__`` and ``__len__``) +NumPy will now only use the result given by ``__array__``, +``__array_interface__``, or ``__array_struct__``. This will result in +differences when the (nested) sequence describes a different shape. (`gh-16200 <https://github.com/numpy/numpy/pull/16200>`__) diff --git a/doc/source/user/basics.rst b/doc/source/user/basics.rst index e0fc0ece3..66f3f9ee9 100644 --- a/doc/source/user/basics.rst +++ b/doc/source/user/basics.rst @@ -1,14 +1,18 @@ -************ -NumPy basics -************ +****************** +NumPy fundamentals +****************** + +These documents clarify concepts, design decisions, and technical +constraints in NumPy. This is a great place to understand the +fundamental NumPy ideas and philosophy. .. toctree:: :maxdepth: 1 - basics.types basics.creation - basics.io basics.indexing + basics.io + basics.types basics.broadcasting basics.byteswapping basics.rec diff --git a/doc/source/user/c-info.beyond-basics.rst b/doc/source/user/c-info.beyond-basics.rst index 124162d6c..289a7951b 100644 --- a/doc/source/user/c-info.beyond-basics.rst +++ b/doc/source/user/c-info.beyond-basics.rst @@ -172,8 +172,8 @@ iterators so that all that needs to be done to advance to the next element in each array is for PyArray_ITER_NEXT to be called for each of the inputs. This incrementing is automatically performed by :c:func:`PyArray_MultiIter_NEXT` ( ``obj`` ) macro (which can handle a -multiterator ``obj`` as either a :c:type:`PyArrayMultiObject *` or a -:c:type:`PyObject *<PyObject>`). The data from input number ``i`` is available using +multiterator ``obj`` as either a :c:expr:`PyArrayMultiObject *` or a +:c:expr:`PyObject *`). The data from input number ``i`` is available using :c:func:`PyArray_MultiIter_DATA` ( ``obj``, ``i`` ) and the total (broadcasted) size as :c:func:`PyArray_MultiIter_SIZE` ( ``obj``). An example of using this feature follows. @@ -400,7 +400,7 @@ describe the desired behavior of the type. Typically, a new C-structure is also created to contain the instance-specific information needed for each object of the type as well. For example, :c:data:`&PyArray_Type<PyArray_Type>` is a pointer to the type-object table for the ndarray -while a :c:type:`PyArrayObject *` variable is a pointer to a particular instance +while a :c:expr:`PyArrayObject *` variable is a pointer to a particular instance of an ndarray (one of the members of the ndarray structure is, in turn, a pointer to the type- object table :c:data:`&PyArray_Type<PyArray_Type>`). Finally :c:func:`PyType_Ready` (<pointer_to_type_object>) must be called for diff --git a/doc/source/user/c-info.how-to-extend.rst b/doc/source/user/c-info.how-to-extend.rst index 845ce0a74..ebb4b7518 100644 --- a/doc/source/user/c-info.how-to-extend.rst +++ b/doc/source/user/c-info.how-to-extend.rst @@ -174,7 +174,7 @@ rule. There are several converter functions defined in the NumPy C-API that may be of use. In particular, the :c:func:`PyArray_DescrConverter` function is very useful to support arbitrary data-type specification. This function transforms any valid data-type Python object into a -:c:type:`PyArray_Descr *` object. Remember to pass in the address of the +:c:expr:`PyArray_Descr *` object. Remember to pass in the address of the C-variables that should be filled in. There are lots of examples of how to use :c:func:`PyArg_ParseTuple` @@ -192,7 +192,7 @@ It is important to keep in mind that you get a *borrowed* reference to the object when using the "O" format string. However, the converter functions usually require some form of memory handling. In this example, if the conversion is successful, *dtype* will hold a new -reference to a :c:type:`PyArray_Descr *` object, while *input* will hold a +reference to a :c:expr:`PyArray_Descr *` object, while *input* will hold a borrowed reference. Therefore, if this conversion were mixed with another conversion (say to an integer) and the data-type conversion was successful but the integer conversion failed, then you would need @@ -213,9 +213,9 @@ The :c:func:`Py_BuildValue` (format_string, c_variables...) function makes it easy to build tuples of Python objects from C variables. Pay special attention to the difference between 'N' and 'O' in the format string or you can easily create memory leaks. The 'O' format string -increments the reference count of the :c:type:`PyObject *<PyObject>` C-variable it +increments the reference count of the :c:expr:`PyObject *` C-variable it corresponds to, while the 'N' format string steals a reference to the -corresponding :c:type:`PyObject *<PyObject>` C-variable. You should use 'N' if you have +corresponding :c:expr:`PyObject *` C-variable. You should use 'N' if you have already created a reference for the object and just want to give that reference to the tuple. You should use 'O' if you only have a borrowed reference to an object and need to create one to provide for the @@ -510,7 +510,7 @@ by providing default values for common use cases. Getting at ndarray memory and accessing elements of the ndarray --------------------------------------------------------------- -If obj is an ndarray (:c:type:`PyArrayObject *`), then the data-area of the +If obj is an ndarray (:c:expr:`PyArrayObject *`), then the data-area of the ndarray is pointed to by the void* pointer :c:func:`PyArray_DATA` (obj) or the char* pointer :c:func:`PyArray_BYTES` (obj). Remember that (in general) this data-area may not be aligned according to the data-type, it may diff --git a/doc/source/user/quickstart.rst b/doc/source/user/quickstart.rst index 8fdc6ec36..ab5bb5318 100644 --- a/doc/source/user/quickstart.rst +++ b/doc/source/user/quickstart.rst @@ -53,8 +53,8 @@ axis has a length of 2, the second axis has a length of 3. :: - [[ 1., 0., 0.], - [ 0., 1., 2.]] + [[1., 0., 0.], + [0., 1., 2.]] NumPy's array class is called ``ndarray``. It is also known by the alias ``array``. Note that ``numpy.array`` is not the same as the Standard @@ -128,7 +128,7 @@ from the type of the elements in the sequences. :: >>> import numpy as np - >>> a = np.array([2,3,4]) + >>> a = np.array([2, 3, 4]) >>> a array([2, 3, 4]) >>> a.dtype @@ -142,11 +142,11 @@ rather than providing a single sequence as an argument. :: - >>> a = np.array(1,2,3,4) # WRONG + >>> a = np.array(1, 2, 3, 4) # WRONG Traceback (most recent call last): ... TypeError: array() takes from 1 to 2 positional arguments but 4 were given - >>> a = np.array([1,2,3,4]) # RIGHT + >>> a = np.array([1, 2, 3, 4]) # RIGHT ``array`` transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and @@ -154,7 +154,7 @@ so on. :: - >>> b = np.array([(1.5,2,3), (4,5,6)]) + >>> b = np.array([(1.5, 2, 3), (4, 5, 6)]) >>> b array([[1.5, 2. , 3. ], [4. , 5. , 6. ]]) @@ -163,7 +163,7 @@ The type of the array can also be explicitly specified at creation time: :: - >>> c = np.array( [ [1,2], [3,4] ], dtype=complex ) + >>> c = np.array([[1, 2], [3, 4]], dtype=complex) >>> c array([[1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j]]) @@ -177,7 +177,7 @@ The function ``zeros`` creates an array full of zeros, the function ``ones`` creates an array full of ones, and the function ``empty`` creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is -``float64``. +``float64``, but it can be specified via the key word argument ``dtype``. :: @@ -185,7 +185,7 @@ state of the memory. By default, the dtype of the created array is array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) - >>> np.ones( (2,3,4), dtype=np.int16 ) # dtype can also be specified + >>> np.ones((2, 3, 4), dtype=np.int16) array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], @@ -193,9 +193,9 @@ state of the memory. By default, the dtype of the created array is [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], dtype=int16) - >>> np.empty( (2,3) ) # uninitialized - array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], # may vary - [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]]) + >>> np.empty((2, 3)) + array([[3.73603959e-262, 6.02658058e-154, 6.55490914e-260], # may vary + [5.30498948e-313, 3.14673309e-307, 1.00000000e+000]]) To create sequences of numbers, NumPy provides the ``arange`` function which is analogous to the Python built-in ``range``, but returns an @@ -203,9 +203,9 @@ array. :: - >>> np.arange( 10, 30, 5 ) + >>> np.arange(10, 30, 5) array([10, 15, 20, 25]) - >>> np.arange( 0, 2, 0.3 ) # it accepts float arguments + >>> np.arange(0, 2, 0.3) # it accepts float arguments array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]) When ``arange`` is used with floating point arguments, it is generally @@ -215,9 +215,9 @@ to use the function ``linspace`` that receives as an argument the number of elements that we want, instead of the step:: >>> from numpy import pi - >>> np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2 + >>> np.linspace(0, 2, 9) # 9 numbers from 0 to 2 array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ]) - >>> x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points + >>> x = np.linspace(0, 2 * pi, 100) # useful to evaluate function at lots of points >>> f = np.sin(x) .. seealso:: @@ -251,18 +251,18 @@ matrices and tridimensionals as lists of matrices. :: - >>> a = np.arange(6) # 1d array + >>> a = np.arange(6) # 1d array >>> print(a) [0 1 2 3 4 5] - >>> - >>> b = np.arange(12).reshape(4,3) # 2d array + >>> + >>> b = np.arange(12).reshape(4, 3) # 2d array >>> print(b) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] - >>> - >>> c = np.arange(24).reshape(2,3,4) # 3d array + >>> + >>> c = np.arange(24).reshape(2, 3, 4) # 3d array >>> print(c) [[[ 0 1 2 3] [ 4 5 6 7] @@ -280,8 +280,8 @@ central part of the array and only prints the corners:: >>> print(np.arange(10000)) [ 0 1 2 ... 9997 9998 9999] - >>> - >>> print(np.arange(10000).reshape(100,100)) + >>> + >>> print(np.arange(10000).reshape(100, 100)) [[ 0 1 2 ... 97 98 99] [ 100 101 102 ... 197 198 199] [ 200 201 202 ... 297 298 299] @@ -295,7 +295,7 @@ can change the printing options using ``set_printoptions``. :: - >>> np.set_printoptions(threshold=sys.maxsize) # sys module should be imported + >>> np.set_printoptions(threshold=sys.maxsize) # sys module should be imported .. _quickstart.basic-operations: @@ -308,35 +308,35 @@ created and filled with the result. :: - >>> a = np.array( [20,30,40,50] ) - >>> b = np.arange( 4 ) + >>> a = np.array([20, 30, 40, 50]) + >>> b = np.arange(4) >>> b array([0, 1, 2, 3]) - >>> c = a-b + >>> c = a - b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) - >>> 10*np.sin(a) + >>> 10 * np.sin(a) array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854]) - >>> a<35 + >>> a < 35 array([ True, True, False, False]) Unlike in many matrix languages, the product operator ``*`` operates elementwise in NumPy arrays. The matrix product can be performed using the ``@`` operator (in python >=3.5) or the ``dot`` function or method:: - >>> A = np.array( [[1,1], - ... [0,1]] ) - >>> B = np.array( [[2,0], - ... [3,4]] ) - >>> A * B # elementwise product + >>> A = np.array([[1, 1], + ... [0, 1]]) + >>> B = np.array([[2, 0], + ... [3, 4]]) + >>> A * B # elementwise product array([[2, 0], [0, 4]]) - >>> A @ B # matrix product + >>> A @ B # matrix product array([[5, 4], [3, 4]]) - >>> A.dot(B) # another matrix product + >>> A.dot(B) # another matrix product array([[5, 4], [3, 4]]) @@ -345,9 +345,9 @@ existing array rather than create a new one. :: - >>> rg = np.random.default_rng(1) # create instance of default random number generator - >>> a = np.ones((2,3), dtype=int) - >>> b = rg.random((2,3)) + >>> rg = np.random.default_rng(1) # create instance of default random number generator + >>> a = np.ones((2, 3), dtype=int) + >>> b = rg.random((2, 3)) >>> a *= 3 >>> a array([[3, 3, 3], @@ -356,7 +356,7 @@ existing array rather than create a new one. >>> b array([[3.51182162, 3.9504637 , 3.14415961], [3.94864945, 3.31183145, 3.42332645]]) - >>> a += b # b is not automatically converted to integer type + >>> a += b # b is not automatically converted to integer type Traceback (most recent call last): ... numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind' @@ -368,15 +368,15 @@ as upcasting). :: >>> a = np.ones(3, dtype=np.int32) - >>> b = np.linspace(0,pi,3) + >>> b = np.linspace(0, pi, 3) >>> b.dtype.name 'float64' - >>> c = a+b + >>> c = a + b >>> c array([1. , 2.57079633, 4.14159265]) >>> c.dtype.name 'float64' - >>> d = np.exp(c*1j) + >>> d = np.exp(c * 1j) >>> d array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j, -0.54030231-0.84147098j]) @@ -388,7 +388,7 @@ the array, are implemented as methods of the ``ndarray`` class. :: - >>> a = rg.random((2,3)) + >>> a = rg.random((2, 3)) >>> a array([[0.82770259, 0.40919914, 0.54959369], [0.02755911, 0.75351311, 0.53814331]]) @@ -404,19 +404,19 @@ of numbers, regardless of its shape. However, by specifying the ``axis`` parameter you can apply an operation along the specified axis of an array:: - >>> b = np.arange(12).reshape(3,4) + >>> b = np.arange(12).reshape(3, 4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> - >>> b.sum(axis=0) # sum of each column + >>> b.sum(axis=0) # sum of each column array([12, 15, 18, 21]) >>> - >>> b.min(axis=1) # min of each row + >>> b.min(axis=1) # min of each row array([0, 4, 8]) >>> - >>> b.cumsum(axis=1) # cumulative sum along each row + >>> b.cumsum(axis=1) # cumulative sum along each row array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]]) @@ -427,7 +427,7 @@ Universal Functions NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called "universal -functions"(\ ``ufunc``). Within NumPy, these functions +functions" (\ ``ufunc``). Within NumPy, these functions operate elementwise on an array, producing an array as output. :: @@ -507,15 +507,15 @@ and other Python sequences. 8 >>> a[2:5] array([ 8, 27, 64]) - # equivalent to a[0:6:2] = 1000; - # from start to position 6, exclusive, set every 2nd element to 1000 + >>> # equivalent to a[0:6:2] = 1000; + >>> # from start to position 6, exclusive, set every 2nd element to 1000 >>> a[:6:2] = 1000 >>> a array([1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729]) - >>> a[ : :-1] # reversed a + >>> a[::-1] # reversed a array([ 729, 512, 343, 216, 125, 1000, 27, 1000, 1, 1000]) >>> for i in a: - ... print(i**(1/3.)) + ... print(i**(1 / 3.)) ... 9.999999999999998 1.0 @@ -532,23 +532,23 @@ and other Python sequences. **Multidimensional** arrays can have one index per axis. These indices are given in a tuple separated by commas:: - >>> def f(x,y): - ... return 10*x+y + >>> def f(x, y): + ... return 10 * x + y ... - >>> b = np.fromfunction(f,(5,4),dtype=int) + >>> b = np.fromfunction(f, (5, 4), dtype=int) >>> b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) - >>> b[2,3] + >>> b[2, 3] 23 - >>> b[0:5, 1] # each row in the second column of b + >>> b[0:5, 1] # each row in the second column of b array([ 1, 11, 21, 31, 41]) - >>> b[ : ,1] # equivalent to the previous example + >>> b[:, 1] # equivalent to the previous example array([ 1, 11, 21, 31, 41]) - >>> b[1:3, : ] # each column in the second and third row of b + >>> b[1:3, :] # each column in the second and third row of b array([[10, 11, 12, 13], [20, 21, 22, 23]]) @@ -557,34 +557,34 @@ indices are considered complete slices\ ``:`` :: - >>> b[-1] # the last row. Equivalent to b[-1,:] + >>> b[-1] # the last row. Equivalent to b[-1, :] array([40, 41, 42, 43]) The expression within brackets in ``b[i]`` is treated as an ``i`` followed by as many instances of ``:`` as needed to represent the remaining axes. NumPy also allows you to write this using dots as -``b[i,...]``. +``b[i, ...]``. The **dots** (``...``) represent as many colons as needed to produce a complete indexing tuple. For example, if ``x`` is an array with 5 axes, then -- ``x[1,2,...]`` is equivalent to ``x[1,2,:,:,:]``, -- ``x[...,3]`` to ``x[:,:,:,:,3]`` and -- ``x[4,...,5,:]`` to ``x[4,:,:,5,:]``. +- ``x[1, 2, ...]`` is equivalent to ``x[1, 2, :, :, :]``, +- ``x[..., 3]`` to ``x[:, :, :, :, 3]`` and +- ``x[4, ..., 5, :]`` to ``x[4, :, :, 5, :]``. :: - >>> c = np.array( [[[ 0, 1, 2], # a 3D array (two stacked 2D arrays) - ... [ 10, 12, 13]], - ... [[100,101,102], - ... [110,112,113]]]) + >>> c = np.array([[[ 0, 1, 2], # a 3D array (two stacked 2D arrays) + ... [ 10, 12, 13]], + ... [[100, 101, 102], + ... [110, 112, 113]]]) >>> c.shape (2, 2, 3) - >>> c[1,...] # same as c[1,:,:] or c[1] + >>> c[1, ...] # same as c[1, :, :] or c[1] array([[100, 101, 102], [110, 112, 113]]) - >>> c[...,2] # same as c[:,:,2] + >>> c[..., 2] # same as c[:, :, 2] array([[ 2, 13], [102, 113]]) @@ -647,7 +647,7 @@ Changing the shape of an array An array has a shape given by the number of elements along each axis:: - >>> a = np.floor(10*rg.random((3,4))) + >>> a = np.floor(10 * rg.random((3, 4))) >>> a array([[3., 7., 3., 4.], [1., 4., 2., 2.], @@ -661,7 +661,7 @@ the original array:: >>> a.ravel() # returns the array, flattened array([3., 7., 3., 4., 1., 4., 2., 2., 7., 2., 4., 9.]) - >>> a.reshape(6,2) # returns the array with a modified shape + >>> a.reshape(6, 2) # returns the array with a modified shape array([[3., 7.], [3., 4.], [1., 4.], @@ -678,14 +678,14 @@ the original array:: >>> a.shape (3, 4) -The order of the elements in the array resulting from ravel() is +The order of the elements in the array resulting from ``ravel`` is normally "C-style", that is, the rightmost index "changes the fastest", -so the element after a[0,0] is a[0,1]. If the array is reshaped to some +so the element after ``a[0, 0]`` is ``a[0, 1]``. If the array is reshaped to some other shape, again the array is treated as "C-style". NumPy normally -creates arrays stored in this order, so ravel() will usually not need to +creates arrays stored in this order, so ``ravel`` will usually not need to copy its argument, but if the array was made by taking slices of another array or created with unusual options, it may need to be copied. The -functions ravel() and reshape() can also be instructed, using an +functions ``ravel`` and ``reshape`` can also be instructed, using an optional argument, to use FORTRAN-style arrays, in which the leftmost index changes the fastest. @@ -698,15 +698,15 @@ itself:: array([[3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]) - >>> a.resize((2,6)) + >>> a.resize((2, 6)) >>> a array([[3., 7., 3., 4., 1., 4.], [2., 2., 7., 2., 4., 9.]]) -If a dimension is given as -1 in a reshaping operation, the other +If a dimension is given as ``-1`` in a reshaping operation, the other dimensions are automatically calculated:: - >>> a.reshape(3,-1) + >>> a.reshape(3, -1) array([[3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]) @@ -726,45 +726,44 @@ Stacking together different arrays Several arrays can be stacked together along different axes:: - >>> a = np.floor(10*rg.random((2,2))) + >>> a = np.floor(10 * rg.random((2, 2))) >>> a array([[9., 7.], [5., 2.]]) - >>> b = np.floor(10*rg.random((2,2))) + >>> b = np.floor(10 * rg.random((2, 2))) >>> b array([[1., 9.], [5., 1.]]) - >>> np.vstack((a,b)) + >>> np.vstack((a, b)) array([[9., 7.], [5., 2.], [1., 9.], [5., 1.]]) - >>> np.hstack((a,b)) + >>> np.hstack((a, b)) array([[9., 7., 1., 9.], [5., 2., 5., 1.]]) -The function `column_stack` -stacks 1D arrays as columns into a 2D array. It is equivalent to -`hstack` only for 2D arrays:: +The function `column_stack` stacks 1D arrays as columns into a 2D array. +It is equivalent to `hstack` only for 2D arrays:: >>> from numpy import newaxis - >>> np.column_stack((a,b)) # with 2D arrays + >>> np.column_stack((a, b)) # with 2D arrays array([[9., 7., 1., 9.], [5., 2., 5., 1.]]) - >>> a = np.array([4.,2.]) - >>> b = np.array([3.,8.]) - >>> np.column_stack((a,b)) # returns a 2D array + >>> a = np.array([4., 2.]) + >>> b = np.array([3., 8.]) + >>> np.column_stack((a, b)) # returns a 2D array array([[4., 3.], [2., 8.]]) - >>> np.hstack((a,b)) # the result is different + >>> np.hstack((a, b)) # the result is different array([4., 2., 3., 8.]) - >>> a[:,newaxis] # view `a` as a 2D column vector + >>> a[:, newaxis] # view `a` as a 2D column vector array([[4.], [2.]]) - >>> np.column_stack((a[:,newaxis],b[:,newaxis])) + >>> np.column_stack((a[:, newaxis], b[:, newaxis])) array([[4., 3.], [2., 8.]]) - >>> np.hstack((a[:,newaxis],b[:,newaxis])) # the result is the same + >>> np.hstack((a[:, newaxis], b[:, newaxis])) # the result is the same array([[4., 3.], [2., 8.]]) @@ -785,12 +784,10 @@ which the concatenation should happen. **Note** -In complex cases, `r_` and -`c_` are useful for creating arrays -by stacking numbers along one axis. They allow the use of range literals -(":") :: +In complex cases, `r_` and `c_` are useful for creating arrays by stacking +numbers along one axis. They allow the use of range literals ``:``. :: - >>> np.r_[1:4,0,4] + >>> np.r_[1:4, 0, 4] array([1, 2, 3, 0, 4]) When used with arrays as arguments, @@ -818,18 +815,18 @@ array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur:: - >>> a = np.floor(10*rg.random((2,12))) + >>> a = np.floor(10 * rg.random((2, 12))) >>> a array([[6., 7., 6., 9., 0., 5., 4., 0., 6., 8., 5., 2.], [8., 5., 5., 7., 1., 8., 6., 7., 1., 8., 1., 0.]]) - # Split a into 3 - >>> np.hsplit(a,3) + >>> # Split `a` into 3 + >>> np.hsplit(a, 3) [array([[6., 7., 6., 9.], [8., 5., 5., 7.]]), array([[0., 5., 4., 0.], [1., 8., 6., 7.]]), array([[6., 8., 5., 2.], [1., 8., 1., 0.]])] - # Split a after the third and the fourth column - >>> np.hsplit(a,(3,4)) + >>> # Split `a` after the third and the fourth column + >>> np.hsplit(a, (3, 4)) [array([[6., 7., 6.], [8., 5., 5.]]), array([[9.], [7.]]), array([[0., 5., 4., 0., 6., 8., 5., 2.], @@ -871,7 +868,7 @@ copy. >>> def f(x): ... print(id(x)) ... - >>> id(a) # id is a unique identifier of an object + >>> id(a) # id is a unique identifier of an object 148293216 # may vary >>> f(a) 148293216 # may vary @@ -887,15 +884,15 @@ creates a new array object that looks at the same data. >>> c = a.view() >>> c is a False - >>> c.base is a # c is a view of the data owned by a + >>> c.base is a # c is a view of the data owned by a True >>> c.flags.owndata False >>> - >>> c = c.reshape((2, 6)) # a's shape doesn't change + >>> c = c.reshape((2, 6)) # a's shape doesn't change >>> a.shape (3, 4) - >>> c[0, 4] = 1234 # a's data changes + >>> c[0, 4] = 1234 # a's data changes >>> a array([[ 0, 1, 2, 3], [1234, 5, 6, 7], @@ -903,8 +900,8 @@ creates a new array object that looks at the same data. Slicing an array returns a view of it:: - >>> s = a[ : , 1:3] # spaces added for clarity; could also be written "s = a[:, 1:3]" - >>> s[:] = 10 # s[:] is a view of s. Note the difference between s = 10 and s[:] = 10 + >>> s = a[:, 1:3] + >>> s[:] = 10 # s[:] is a view of s. Note the difference between s = 10 and s[:] = 10 >>> a array([[ 0, 10, 10, 3], [1234, 10, 10, 7], @@ -917,12 +914,12 @@ The ``copy`` method makes a complete copy of the array and its data. :: - >>> d = a.copy() # a new array object with new data is created + >>> d = a.copy() # a new array object with new data is created >>> d is a False - >>> d.base is a # d doesn't share anything with a + >>> d.base is a # d doesn't share anything with a False - >>> d[0,0] = 9999 + >>> d[0, 0] = 9999 >>> a array([[ 0, 10, 10, 3], [1234, 10, 10, 7], @@ -1068,13 +1065,13 @@ Indexing with Arrays of Indices :: - >>> a = np.arange(12)**2 # the first 12 square numbers - >>> i = np.array([1, 1, 3, 8, 5]) # an array of indices - >>> a[i] # the elements of a at the positions i + >>> a = np.arange(12)**2 # the first 12 square numbers + >>> i = np.array([1, 1, 3, 8, 5]) # an array of indices + >>> a[i] # the elements of `a` at the positions `i` array([ 1, 1, 9, 64, 25]) - >>> - >>> j = np.array([[3, 4], [9, 7]]) # a bidimensional array of indices - >>> a[j] # the same shape as j + >>> + >>> j = np.array([[3, 4], [9, 7]]) # a bidimensional array of indices + >>> a[j] # the same shape as `j` array([[ 9, 16], [81, 49]]) @@ -1090,9 +1087,9 @@ using a palette. ... [0, 255, 0], # green ... [0, 0, 255], # blue ... [255, 255, 255]]) # white - >>> image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette + >>> image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette ... [0, 3, 4, 0]]) - >>> palette[image] # the (2, 4, 3) color image + >>> palette[image] # the (2, 4, 3) color image array([[[ 0, 0, 0], [255, 0, 0], [ 0, 255, 0], @@ -1108,25 +1105,25 @@ indices for each dimension must have the same shape. :: - >>> a = np.arange(12).reshape(3,4) + >>> a = np.arange(12).reshape(3, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) - >>> i = np.array([[0, 1], # indices for the first dim of a + >>> i = np.array([[0, 1], # indices for the first dim of `a` ... [1, 2]]) - >>> j = np.array([[2, 1], # indices for the second dim + >>> j = np.array([[2, 1], # indices for the second dim ... [3, 3]]) - >>> - >>> a[i, j] # i and j must have equal shape + >>> + >>> a[i, j] # i and j must have equal shape array([[ 2, 5], [ 7, 11]]) - >>> + >>> >>> a[i, 2] array([[ 2, 6], [ 6, 10]]) - >>> - >>> a[:, j] # i.e., a[ : , j] + >>> + >>> a[:, j] array([[[ 2, 1], [ 3, 3]], <BLANKLINE> @@ -1142,26 +1139,24 @@ put ``i`` and ``j`` in a ``tuple`` and then do the indexing with that. :: >>> l = (i, j) - # equivalent to a[i, j] + >>> # equivalent to a[i, j] >>> a[l] array([[ 2, 5], [ 7, 11]]) However, we can not do this by putting ``i`` and ``j`` into an array, because this array will be interpreted as indexing the first dimension -of a. +of ``a``. :: >>> s = np.array([i, j]) - - # not what we want + >>> # not what we want >>> a[s] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index 3 is out of bounds for axis 0 with size 3 - - # same as a[i, j] + >>> # same as `a[i, j]` >>> a[tuple(s)] array([[ 2, 5], [ 7, 11]]) @@ -1169,8 +1164,8 @@ of a. Another common use of indexing with arrays is the search of the maximum value of time-dependent series:: - >>> time = np.linspace(20, 145, 5) # time scale - >>> data = np.sin(np.arange(20)).reshape(5,4) # 4 time-dependent series + >>> time = np.linspace(20, 145, 5) # time scale + >>> data = np.sin(np.arange(20)).reshape(5, 4) # 4 time-dependent series >>> time array([ 20. , 51.25, 82.5 , 113.75, 145. ]) >>> data @@ -1179,22 +1174,18 @@ value of time-dependent series:: [ 0.98935825, 0.41211849, -0.54402111, -0.99999021], [-0.53657292, 0.42016704, 0.99060736, 0.65028784], [-0.28790332, -0.96139749, -0.75098725, 0.14987721]]) - - # index of the maxima for each series + >>> # index of the maxima for each series >>> ind = data.argmax(axis=0) >>> ind array([2, 0, 3, 1]) - - # times corresponding to the maxima + >>> # times corresponding to the maxima >>> time_max = time[ind] - >>> - >>> data_max = data[ind, range(data.shape[1])] # => data[ind[0],0], data[ind[1],1]... - + >>> + >>> data_max = data[ind, range(data.shape[1])] # => data[ind[0], 0], data[ind[1], 1]... >>> time_max array([ 82.5 , 20. , 113.75, 51.25]) >>> data_max array([0.98935825, 0.84147098, 0.99060736, 0.6569866 ]) - >>> np.all(data_max == data.max(axis=0)) True @@ -1203,7 +1194,7 @@ You can also use indexing with arrays as a target to assign to:: >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) - >>> a[[1,3,4]] = 0 + >>> a[[1, 3, 4]] = 0 >>> a array([0, 0, 2, 0, 0]) @@ -1211,7 +1202,7 @@ However, when the list of indices contains repetitions, the assignment is done several times, leaving behind the last value:: >>> a = np.arange(5) - >>> a[[0,0,2]]=[1,2,3] + >>> a[[0, 0, 2]] = [1, 2, 3] >>> a array([2, 1, 3, 3, 4]) @@ -1219,13 +1210,13 @@ This is reasonable enough, but watch out if you want to use Python's ``+=`` construct, as it may not do what you expect:: >>> a = np.arange(5) - >>> a[[0,0,2]]+=1 + >>> a[[0, 0, 2]] += 1 >>> a array([1, 1, 3, 3, 4]) Even though 0 occurs twice in the list of indices, the 0th element is -only incremented once. This is because Python requires "a+=1" to be -equivalent to "a = a + 1". +only incremented once. This is because Python requires ``a += 1`` to be +equivalent to ``a = a + 1``. Indexing with Boolean Arrays ---------------------------- @@ -1238,18 +1229,18 @@ which ones we don't. The most natural way one can think of for boolean indexing is to use boolean arrays that have *the same shape* as the original array:: - >>> a = np.arange(12).reshape(3,4) + >>> a = np.arange(12).reshape(3, 4) >>> b = a > 4 - >>> b # b is a boolean with a's shape + >>> b # `b` is a boolean with `a`'s shape array([[False, False, False, False], [False, True, True, True], [ True, True, True, True]]) - >>> a[b] # 1d array with the selected elements + >>> a[b] # 1d array with the selected elements array([ 5, 6, 7, 8, 9, 10, 11]) This property can be very useful in assignments:: - >>> a[b] = 0 # All elements of 'a' higher than 4 become 0 + >>> a[b] = 0 # All elements of `a` higher than 4 become 0 >>> a array([[0, 1, 2, 3], [4, 0, 0, 0], @@ -1264,45 +1255,45 @@ set <https://en.wikipedia.org/wiki/Mandelbrot_set>`__: >>> import numpy as np >>> import matplotlib.pyplot as plt - >>> def mandelbrot( h,w, maxit=20 ): + >>> def mandelbrot(h, w, maxit=20): ... """Returns an image of the Mandelbrot fractal of size (h,w).""" - ... y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] - ... c = x+y*1j + ... y, x = np.ogrid[-1.4:1.4:h*1j, -2:0.8:w*1j] + ... c = x + y * 1j ... z = c ... divtime = maxit + np.zeros(z.shape, dtype=int) ... ... for i in range(maxit): ... z = z**2 + c - ... diverge = z*np.conj(z) > 2**2 # who is diverging - ... div_now = diverge & (divtime==maxit) # who is diverging now - ... divtime[div_now] = i # note when - ... z[diverge] = 2 # avoid diverging too much + ... diverge = z * np.conj(z) > 2**2 # who is diverging + ... div_now = diverge & (divtime == maxit) # who is diverging now + ... divtime[div_now] = i # note when + ... z[diverge] = 2 # avoid diverging too much ... ... return divtime - >>> plt.imshow(mandelbrot(400,400)) + >>> plt.imshow(mandelbrot(400, 400)) The second way of indexing with booleans is more similar to integer indexing; for each dimension of the array we give a 1D boolean array selecting the slices we want:: - >>> a = np.arange(12).reshape(3,4) - >>> b1 = np.array([False,True,True]) # first dim selection - >>> b2 = np.array([True,False,True,False]) # second dim selection - >>> - >>> a[b1,:] # selecting rows + >>> a = np.arange(12).reshape(3, 4) + >>> b1 = np.array([False, True, True]) # first dim selection + >>> b2 = np.array([True, False, True, False]) # second dim selection + >>> + >>> a[b1, :] # selecting rows array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]]) - >>> - >>> a[b1] # same thing + >>> + >>> a[b1] # same thing array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]]) - >>> - >>> a[:,b2] # selecting columns + >>> + >>> a[:, b2] # selecting columns array([[ 0, 2], [ 4, 6], [ 8, 10]]) - >>> - >>> a[b1,b2] # a weird thing to do + >>> + >>> a[b1, b2] # a weird thing to do array([ 4, 10]) Note that the length of the 1D boolean array must coincide with the @@ -1319,10 +1310,10 @@ obtain the result for each n-uplet. For example, if you want to compute all the a+b\*c for all the triplets taken from each of the vectors a, b and c:: - >>> a = np.array([2,3,4,5]) - >>> b = np.array([8,5,4]) - >>> c = np.array([5,4,6,8,3]) - >>> ax,bx,cx = np.ix_(a,b,c) + >>> a = np.array([2, 3, 4, 5]) + >>> b = np.array([8, 5, 4]) + >>> c = np.array([5, 4, 6, 8, 3]) + >>> ax, bx, cx = np.ix_(a, b, c) >>> ax array([[[2]], <BLANKLINE> @@ -1339,7 +1330,7 @@ and c:: array([[[5, 4, 6, 8, 3]]]) >>> ax.shape, bx.shape, cx.shape ((4, 1, 1), (1, 3, 1), (1, 1, 5)) - >>> result = ax+bx*cx + >>> result = ax + bx * cx >>> result array([[[42, 34, 50, 66, 26], [27, 22, 32, 42, 17], @@ -1356,9 +1347,9 @@ and c:: [[45, 37, 53, 69, 29], [30, 25, 35, 45, 20], [25, 21, 29, 37, 17]]]) - >>> result[3,2,4] + >>> result[3, 2, 4] 17 - >>> a[3]+b[2]*c[4] + >>> a[3] + b[2] * c[4] 17 You could also implement the reduce as follows:: @@ -1367,12 +1358,12 @@ You could also implement the reduce as follows:: ... vs = np.ix_(*vectors) ... r = ufct.identity ... for v in vs: - ... r = ufct(r,v) + ... r = ufct(r, v) ... return r and then use it as:: - >>> ufunc_reduce(np.add,a,b,c) + >>> ufunc_reduce(np.add, a, b, c) array([[[15, 14, 16, 18, 13], [12, 11, 13, 15, 10], [11, 10, 12, 14, 9]], @@ -1417,33 +1408,26 @@ See linalg.py in numpy folder for more. >>> print(a) [[1. 2.] [3. 4.]] - >>> a.transpose() array([[1., 3.], [2., 4.]]) - >>> np.linalg.inv(a) array([[-2. , 1. ], [ 1.5, -0.5]]) - - >>> u = np.eye(2) # unit 2x2 matrix; "eye" represents "I" + >>> u = np.eye(2) # unit 2x2 matrix; "eye" represents "I" >>> u array([[1., 0.], [0., 1.]]) >>> j = np.array([[0.0, -1.0], [1.0, 0.0]]) - - >>> j @ j # matrix product + >>> j @ j # matrix product array([[-1., 0.], [ 0., -1.]]) - >>> np.trace(u) # trace 2.0 - >>> y = np.array([[5.], [7.]]) >>> np.linalg.solve(a, y) array([[-3.], [ 4.]]) - >>> np.linalg.eig(j) (array([0.+1.j, 0.-1.j]), array([[0.70710678+0.j , 0.70710678-0.j ], [0. -0.70710678j, 0. +0.70710678j]])) @@ -1455,7 +1439,7 @@ See linalg.py in numpy folder for more. Returns The eigenvalues, each repeated according to its multiplicity. The normalized (unit "length") eigenvectors, such that the - column ``v[:,i]`` is the eigenvector corresponding to the + column ``v[:, i]`` is the eigenvector corresponding to the eigenvalue ``w[i]`` . Tricks and Tips @@ -1496,13 +1480,13 @@ functions ``column_stack``, ``dstack``, ``hstack`` and ``vstack``, depending on the dimension in which the stacking is to be done. For example:: - >>> x = np.arange(0,10,2) + >>> x = np.arange(0, 10, 2) >>> y = np.arange(5) - >>> m = np.vstack([x,y]) + >>> m = np.vstack([x, y]) >>> m array([[0, 2, 4, 6, 8], [0, 1, 2, 3, 4]]) - >>> xy = np.hstack([x,y]) + >>> xy = np.hstack([x, y]) >>> xy array([0, 2, 4, 6, 8, 0, 1, 2, 3, 4]) @@ -1530,12 +1514,12 @@ that ``pylab.hist`` plots the histogram automatically, while >>> import matplotlib.pyplot as plt >>> # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2 >>> mu, sigma = 2, 0.5 - >>> v = rg.normal(mu,sigma,10000) + >>> v = rg.normal(mu, sigma, 10000) >>> # Plot a normalized histogram with 50 bins >>> plt.hist(v, bins=50, density=1) # matplotlib version (plot) >>> # Compute the histogram with numpy and then plot it >>> (n, bins) = np.histogram(v, bins=50, density=True) # NumPy version (no plot) - >>> plt.plot(.5*(bins[1:]+bins[:-1]), n) + >>> plt.plot(.5 * (bins[1:] + bins[:-1]), n) Further reading diff --git a/doc/source/user/theory.broadcasting.rst b/doc/source/user/theory.broadcasting.rst index b37edeacc..a82d78e6c 100644 --- a/doc/source/user/theory.broadcasting.rst +++ b/doc/source/user/theory.broadcasting.rst @@ -69,7 +69,7 @@ numpy on Windows 2000 with one million element arrays. *Figure 1* *In the simplest example of broadcasting, the scalar ``b`` is - stretched to become an array of with the same shape as ``a`` so the shapes + stretched to become an array of same shape as ``a`` so the shapes are compatible for element-by-element multiplication.* diff --git a/doc_requirements.txt b/doc_requirements.txt index f69cc5dcb..0650e0a58 100644 --- a/doc_requirements.txt +++ b/doc_requirements.txt @@ -1,4 +1,4 @@ -sphinx>=2.2.0,<3.0 +sphinx>=3.2 numpydoc==1.1.0 ipython scipy diff --git a/numpy/__init__.py b/numpy/__init__.py index 3e5277318..a242bb7df 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -130,12 +130,16 @@ else: your python interpreter from there.""" raise ImportError(msg) from e - from .version import git_revision as __git_revision__ - from .version import version as __version__ - __all__ = ['ModuleDeprecationWarning', 'VisibleDeprecationWarning'] + # get the version using versioneer + from ._version import get_versions + vinfo = get_versions() + __version__ = vinfo.get("closest-tag", vinfo["version"]) + __git_version__ = vinfo.get("full-revisionid") + del get_versions, vinfo + # mapping of {name: (value, deprecation_msg)} __deprecated_attrs__ = {} @@ -384,3 +388,13 @@ else: # Note that this will currently only make a difference on Linux core.multiarray._set_madvise_hugepage(use_hugepage) + + # Give a warning if NumPy is reloaded or imported on a sub-interpreter + # We do this from python, since the C-module may not be reloaded and + # it is tidier organized. + core.multiarray._multiarray_umath._reload_guard() + +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions + diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 9f3ba3400..3165a6319 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -16,6 +16,7 @@ from numpy.typing import ( _IntLike, _FloatLike, _ComplexLike, + _TD64Like, _NumberLike, _SupportsDType, _VoidDTypeLike, @@ -173,6 +174,18 @@ from numpy.core._ufunc_config import ( _ErrDictOptional, ) +from numpy.core.arrayprint import ( + set_printoptions as set_printoptions, + get_printoptions as get_printoptions, + array2string as array2string, + format_float_scientific as format_float_scientific, + format_float_positional as format_float_positional, + array_repr as array_repr, + array_str as array_str, + set_string_function as set_string_function, + printoptions as printoptions, +) + from numpy.core.numeric import ( zeros_like as zeros_like, ones as ones, @@ -280,10 +293,7 @@ append: Any apply_along_axis: Any apply_over_axes: Any arange: Any -array2string: Any -array_repr: Any array_split: Any -array_str: Any asarray_chkfinite: Any asfarray: Any asmatrix: Any @@ -356,8 +366,6 @@ fliplr: Any flipud: Any float128: Any float_: Any -format_float_positional: Any -format_float_scientific: Any format_parser: Any frombuffer: Any fromfile: Any @@ -367,7 +375,6 @@ fromregex: Any fromstring: Any genfromtxt: Any get_include: Any -get_printoptions: Any geterrobj: Any gradient: Any half: Any @@ -468,7 +475,6 @@ polyint: Any polymul: Any polysub: Any polyval: Any -printoptions: Any product: Any promote_types: Any put_along_axis: Any @@ -494,8 +500,6 @@ savetxt: Any savez: Any savez_compressed: Any select: Any -set_printoptions: Any -set_string_function: Any setdiff1d: Any seterrobj: Any setxor1d: Any @@ -869,7 +873,7 @@ class dtype(Generic[_DTypeScalar]): @property def alignment(self) -> int: ... @property - def base(self) -> dtype: ... + def base(self: _DType) -> _DType: ... @property def byteorder(self) -> str: ... @property @@ -879,7 +883,7 @@ class dtype(Generic[_DTypeScalar]): @property def fields( self, - ) -> Optional[Mapping[str, Union[Tuple[dtype, int], Tuple[dtype, int, Any]]]]: ... + ) -> Optional[Mapping[str, Union[Tuple[dtype[Any], int], Tuple[dtype[Any], int, Any]]]]: ... @property def flags(self) -> int: ... @property @@ -905,14 +909,14 @@ class dtype(Generic[_DTypeScalar]): @property def ndim(self) -> int: ... @property - def subdtype(self) -> Optional[Tuple[dtype, _Shape]]: ... - def newbyteorder(self, __new_order: _ByteOrder = ...) -> dtype: ... + def subdtype(self: _DType) -> Optional[Tuple[_DType, _Shape]]: ... + def newbyteorder(self: _DType, __new_order: _ByteOrder = ...) -> _DType: ... # Leave str and type for end to avoid having to use `builtins.str` # everywhere. See https://github.com/python/mypy/issues/3775 @property def str(self) -> builtins.str: ... @property - def type(self) -> Type[generic]: ... + def type(self) -> Type[_DTypeScalar]: ... class _flagsobj: aligned: bool @@ -954,24 +958,30 @@ _ArrayLikeInt = Union[ _FlatIterSelf = TypeVar("_FlatIterSelf", bound=flatiter) -class flatiter(Generic[_ArraySelf]): +class flatiter(Generic[_NdArraySubClass]): @property - def base(self) -> _ArraySelf: ... + def base(self) -> _NdArraySubClass: ... @property def coords(self) -> _Shape: ... @property def index(self) -> int: ... - def copy(self) -> _ArraySelf: ... + def copy(self) -> _NdArraySubClass: ... def __iter__(self: _FlatIterSelf) -> _FlatIterSelf: ... - def __next__(self) -> generic: ... + def __next__(self: flatiter[ndarray[Any, dtype[_ScalarType]]]) -> _ScalarType: ... def __len__(self) -> int: ... @overload - def __getitem__(self, key: Union[int, integer]) -> generic: ... + def __getitem__( + self: flatiter[ndarray[Any, dtype[_ScalarType]]], + key: Union[int, integer], + ) -> _ScalarType: ... @overload def __getitem__( self, key: Union[_ArrayLikeInt, slice, ellipsis], - ) -> _ArraySelf: ... - def __array__(self, __dtype: DTypeLike = ...) -> ndarray: ... + ) -> _NdArraySubClass: ... + @overload + def __array__(self: flatiter[ndarray[Any, _DType]], __dtype: None = ...) -> ndarray[Any, _DType]: ... + @overload + def __array__(self, __dtype: DTypeLike) -> ndarray[Any, dtype[Any]]: ... _OrderKACF = Optional[Literal["K", "A", "C", "F"]] _OrderACF = Optional[Literal["A", "C", "F"]] @@ -985,10 +995,8 @@ _SortSide = Literal["left", "right"] _ArrayLikeBool = Union[_BoolLike, Sequence[_BoolLike], ndarray] _ArrayLikeIntOrBool = Union[ _IntLike, - _BoolLike, ndarray, Sequence[_IntLike], - Sequence[_BoolLike], Sequence[Sequence[Any]], # TODO: wait for support for recursive types ] @@ -1005,7 +1013,6 @@ class _ArrayOrScalarCommon: def itemsize(self) -> int: ... @property def nbytes(self) -> int: ... - def __array__(self, __dtype: DTypeLike = ...) -> ndarray: ... def __bool__(self) -> bool: ... def __bytes__(self) -> bytes: ... def __str__(self) -> str: ... @@ -1387,7 +1394,7 @@ class _ArrayOrScalarCommon: @overload def take( self, - indices: Union[_IntLike, _BoolLike], + indices: _IntLike, axis: Optional[int] = ..., out: None = ..., mode: _ModeKind = ..., @@ -1469,6 +1476,10 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeType, _DType]): strides: _ShapeLike = ..., order: _OrderKACF = ..., ) -> _ArraySelf: ... + @overload + def __array__(self, __dtype: None = ...) -> ndarray[Any, _DType]: ... + @overload + def __array__(self, __dtype: DTypeLike) -> ndarray[Any, dtype[Any]]: ... @property def ctypes(self) -> _ctypes: ... @property @@ -1482,7 +1493,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeType, _DType]): def byteswap(self: _ArraySelf, inplace: bool = ...) -> _ArraySelf: ... def fill(self, value: Any) -> None: ... @property - def flat(self: _ArraySelf) -> flatiter[_ArraySelf]: ... + def flat(self: _NdArraySubClass) -> flatiter[_NdArraySubClass]: ... @overload def item(self, *args: int) -> Any: ... @overload @@ -1647,6 +1658,10 @@ _NBit_co2 = TypeVar("_NBit_co2", covariant=True, bound=NBitBase) class generic(_ArrayOrScalarCommon): @abstractmethod def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @overload + def __array__(self: _ScalarType, __dtype: None = ...) -> ndarray[Any, dtype[_ScalarType]]: ... + @overload + def __array__(self, __dtype: DTypeLike) -> ndarray[Any, dtype[Any]]: ... @property def base(self) -> None: ... @property @@ -1659,7 +1674,7 @@ class generic(_ArrayOrScalarCommon): def strides(self) -> Tuple[()]: ... def byteswap(self: _ScalarType, inplace: Literal[False] = ...) -> _ScalarType: ... @property - def flat(self) -> flatiter[ndarray]: ... + def flat(self: _ScalarType) -> flatiter[ndarray[Any, dtype[_ScalarType]]]: ... def item( self: _ScalarType, __args: Union[Literal[0], Tuple[()], Tuple[Literal[0]]] = ..., @@ -1763,12 +1778,12 @@ class datetime64(generic): __value: int, __format: Union[_CharLike, Tuple[_CharLike, _IntLike]] ) -> None: ... - def __add__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> datetime64: ... - def __radd__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> datetime64: ... + def __add__(self, other: _TD64Like) -> datetime64: ... + def __radd__(self, other: _TD64Like) -> datetime64: ... @overload def __sub__(self, other: datetime64) -> timedelta64: ... @overload - def __sub__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> datetime64: ... + def __sub__(self, other: _TD64Like) -> datetime64: ... def __rsub__(self, other: datetime64) -> timedelta64: ... __lt__: _ComparisonOp[datetime64] __le__: _ComparisonOp[datetime64] @@ -1791,20 +1806,20 @@ class integer(number[_NBit_co]): # type: ignore def __index__(self) -> int: ... __truediv__: _IntTrueDiv[_NBit_co] __rtruediv__: _IntTrueDiv[_NBit_co] - def __mod__(self, value: Union[_IntLike, integer]) -> integer: ... - def __rmod__(self, value: Union[_IntLike, integer]) -> integer: ... + def __mod__(self, value: _IntLike) -> integer: ... + def __rmod__(self, value: _IntLike) -> integer: ... def __invert__(self: _IntType) -> _IntType: ... # Ensure that objects annotated as `integer` support bit-wise operations - def __lshift__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __rlshift__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __rshift__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __rrshift__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __and__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __rand__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __or__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __ror__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __xor__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... - def __rxor__(self, other: Union[_IntLike, _BoolLike]) -> integer: ... + def __lshift__(self, other: _IntLike) -> integer: ... + def __rlshift__(self, other: _IntLike) -> integer: ... + def __rshift__(self, other: _IntLike) -> integer: ... + def __rrshift__(self, other: _IntLike) -> integer: ... + def __and__(self, other: _IntLike) -> integer: ... + def __rand__(self, other: _IntLike) -> integer: ... + def __or__(self, other: _IntLike) -> integer: ... + def __ror__(self, other: _IntLike) -> integer: ... + def __xor__(self, other: _IntLike) -> integer: ... + def __rxor__(self, other: _IntLike) -> integer: ... class signedinteger(integer[_NBit_co]): def __init__(self, __value: _IntValue = ...) -> None: ... @@ -1850,12 +1865,12 @@ class timedelta64(generic): def __neg__(self: _ArraySelf) -> _ArraySelf: ... def __pos__(self: _ArraySelf) -> _ArraySelf: ... def __abs__(self: _ArraySelf) -> _ArraySelf: ... - def __add__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> timedelta64: ... - def __radd__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> timedelta64: ... - def __sub__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> timedelta64: ... - def __rsub__(self, other: Union[timedelta64, _IntLike, _BoolLike]) -> timedelta64: ... - def __mul__(self, other: Union[_FloatLike, _BoolLike]) -> timedelta64: ... - def __rmul__(self, other: Union[_FloatLike, _BoolLike]) -> timedelta64: ... + def __add__(self, other: _TD64Like) -> timedelta64: ... + def __radd__(self, other: _TD64Like) -> timedelta64: ... + def __sub__(self, other: _TD64Like) -> timedelta64: ... + def __rsub__(self, other: _TD64Like) -> timedelta64: ... + def __mul__(self, other: _FloatLike) -> timedelta64: ... + def __rmul__(self, other: _FloatLike) -> timedelta64: ... __truediv__: _TD64Div[float64] __floordiv__: _TD64Div[int64] def __rtruediv__(self, other: timedelta64) -> float64: ... @@ -1960,7 +1975,7 @@ complex128 = complexfloating[_64Bit, _64Bit] class flexible(generic): ... # type: ignore class void(flexible): - def __init__(self, __value: Union[_IntLike, _BoolLike, bytes]): ... + def __init__(self, __value: Union[_IntLike, bytes]): ... @property def real(self: _ArraySelf) -> _ArraySelf: ... @property diff --git a/numpy/_version.py b/numpy/_version.py new file mode 100644 index 000000000..6605bf4af --- /dev/null +++ b/numpy/_version.py @@ -0,0 +1,525 @@ + +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "$Format:%d$" + git_full = "$Format:%H$" + git_date = "$Format:%ci$" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "pep440" + cfg.tag_prefix = "v" + cfg.parentdir_prefix = "numpy-" + cfg.versionfile_source = "numpy/_version.py" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip().decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post0.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post0.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post0.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} diff --git a/numpy/core/_add_newdocs.py b/numpy/core/_add_newdocs.py index e2bf6c439..2cbfe52be 100644 --- a/numpy/core/_add_newdocs.py +++ b/numpy/core/_add_newdocs.py @@ -1147,13 +1147,13 @@ add_newdoc('numpy.core.multiarray', 'compare_chararrays', add_newdoc('numpy.core.multiarray', 'fromiter', """ - fromiter(iterable, dtype, count=-1, *, like=None) + fromiter(iter, dtype, count=-1, *, like=None) Create a new 1-dimensional array from an iterable object. Parameters ---------- - iterable : iterable object + iter : iterable object An iterable object providing data for the array. dtype : data-type The data-type of the returned array. diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index ad1530419..94ec8ed34 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -146,7 +146,6 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, - 'longcomplexfloat' : composed of two 128-bit floats - 'numpystr' : types `numpy.string_` and `numpy.unicode_` - 'object' : `np.object_` arrays - - 'str' : all other strings Other keys that can be used to set a group of types at once are: @@ -154,7 +153,7 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - - 'str_kind' : sets 'str' and 'numpystr' + - 'str_kind' : sets 'numpystr' floatmode : str, optional Controls the interpretation of the `precision` option for floating-point types. Can take the following values @@ -375,8 +374,7 @@ def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy, 'timedelta': lambda: TimedeltaFormat(data), 'object': lambda: _object_format, 'void': lambda: str_format, - 'numpystr': lambda: repr_format, - 'str': lambda: str} + 'numpystr': lambda: repr_format} # we need to wrap values in `formatter` in a lambda, so that the interface # is the same as the above values. @@ -398,8 +396,7 @@ def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy, for key in ['complexfloat', 'longcomplexfloat']: formatdict[key] = indirect(formatter['complex_kind']) if 'str_kind' in fkeys: - for key in ['numpystr', 'str']: - formatdict[key] = indirect(formatter['str_kind']) + formatdict['numpystr'] = indirect(formatter['str_kind']) for key in formatdict.keys(): if key in fkeys: formatdict[key] = indirect(formatter[key]) @@ -524,7 +521,7 @@ def array2string(a, max_line_width=None, precision=None, Parameters ---------- - a : array_like + a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. @@ -572,7 +569,6 @@ def array2string(a, max_line_width=None, precision=None, - 'longcomplexfloat' : composed of two 128-bit floats - 'void' : type `numpy.void` - 'numpystr' : types `numpy.string_` and `numpy.unicode_` - - 'str' : all other strings Other keys that can be used to set a group of types at once are: @@ -580,7 +576,7 @@ def array2string(a, max_line_width=None, precision=None, - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - - 'str_kind' : sets 'str' and 'numpystr' + - 'str_kind' : sets 'numpystr' threshold : int, optional Total number of array elements which trigger summarization rather than full repr. diff --git a/numpy/core/arrayprint.pyi b/numpy/core/arrayprint.pyi new file mode 100644 index 000000000..6aaae0320 --- /dev/null +++ b/numpy/core/arrayprint.pyi @@ -0,0 +1,145 @@ +import sys +from types import TracebackType +from typing import Any, Optional, Callable, Union, Type + +# Using a private class is by no means ideal, but it is simply a consquence +# of a `contextlib.context` returning an instance of aformentioned class +from contextlib import _GeneratorContextManager + +from numpy import ( + ndarray, + generic, + bool_, + integer, + timedelta64, + datetime64, + floating, + complexfloating, + void, + str_, + bytes_, + longdouble, + clongdouble, +) +from numpy.typing import ArrayLike, _CharLike, _FloatLike + +if sys.version_info > (3, 8): + from typing import Literal, TypedDict +else: + from typing_extensions import Literal, TypedDict + +_FloatMode = Literal["fixed", "unique", "maxprec", "maxprec_equal"] + +class _FormatDict(TypedDict, total=False): + bool: Callable[[bool_], str] + int: Callable[[integer[Any]], str] + timedelta: Callable[[timedelta64], str] + datetime: Callable[[datetime64], str] + float: Callable[[floating[Any]], str] + longfloat: Callable[[longdouble], str] + complexfloat: Callable[[complexfloating[Any, Any]], str] + longcomplexfloat: Callable[[clongdouble], str] + void: Callable[[void], str] + numpystr: Callable[[_CharLike], str] + object: Callable[[object], str] + all: Callable[[object], str] + int_kind: Callable[[integer[Any]], str] + float_kind: Callable[[floating[Any]], str] + complex_kind: Callable[[complexfloating[Any, Any]], str] + str_kind: Callable[[_CharLike], str] + +class _FormatOptions(TypedDict): + precision: int + threshold: int + edgeitems: int + linewidth: int + suppress: bool + nanstr: str + infstr: str + formatter: Optional[_FormatDict] + sign: Literal["-", "+", " "] + floatmode: _FloatMode + legacy: Literal[False, "1.13"] + +def set_printoptions( + precision: Optional[int] = ..., + threshold: Optional[int] = ..., + edgeitems: Optional[int] = ..., + linewidth: Optional[int] = ..., + suppress: Optional[bool] = ..., + nanstr: Optional[str] = ..., + infstr: Optional[str] = ..., + formatter: Optional[_FormatDict] = ..., + sign: Optional[Literal["-", "+", " "]] = ..., + floatmode: Optional[_FloatMode] = ..., + *, + legacy: Optional[Literal[False, "1.13"]] = ... +) -> None: ... +def get_printoptions() -> _FormatOptions: ... +def array2string( + a: ndarray[Any, Any], + max_line_width: Optional[int] = ..., + precision: Optional[int] = ..., + suppress_small: Optional[bool] = ..., + separator: str = ..., + prefix: str = ..., + # NOTE: With the `style` argument being deprecated, + # all arguments between `formatter` and `suffix` are de facto + # keyworld-only arguments + *, + formatter: Optional[_FormatDict] = ..., + threshold: Optional[int] = ..., + edgeitems: Optional[int] = ..., + sign: Optional[Literal["-", "+", " "]] = ..., + floatmode: Optional[_FloatMode] = ..., + suffix: str = ..., + legacy: Optional[Literal[False, "1.13"]] = ..., +) -> str: ... +def format_float_scientific( + x: _FloatLike, + precision: Optional[int] = ..., + unique: bool = ..., + trim: Literal["k", ".", "0", "-"] = ..., + sign: bool = ..., + pad_left: Optional[int] = ..., + exp_digits: Optional[int] = ..., +) -> str: ... +def format_float_positional( + x: _FloatLike, + precision: Optional[int] = ..., + unique: bool = ..., + fractional: bool = ..., + trim: Literal["k", ".", "0", "-"] = ..., + sign: bool = ..., + pad_left: Optional[int] = ..., + pad_right: Optional[int] = ..., +) -> str: ... +def array_repr( + arr: ndarray[Any, Any], + max_line_width: Optional[int] = ..., + precision: Optional[int] = ..., + suppress_small: Optional[bool] = ..., +) -> str: ... +def array_str( + a: ndarray[Any, Any], + max_line_width: Optional[int] = ..., + precision: Optional[int] = ..., + suppress_small: Optional[bool] = ..., +) -> str: ... +def set_string_function( + f: Optional[Callable[[ndarray[Any, Any]], str]], repr: bool = ... +) -> None: ... +def printoptions( + precision: Optional[int] = ..., + threshold: Optional[int] = ..., + edgeitems: Optional[int] = ..., + linewidth: Optional[int] = ..., + suppress: Optional[bool] = ..., + nanstr: Optional[str] = ..., + infstr: Optional[str] = ..., + formatter: Optional[_FormatDict] = ..., + sign: Optional[Literal["-", "+", " "]] = ..., + floatmode: Optional[_FloatMode] = ..., + *, + legacy: Optional[Literal[False, "1.13"]] = ... +) -> _GeneratorContextManager[_FormatOptions]: ... diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index b7edd2834..04181fbc2 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -185,7 +185,7 @@ add_newdoc('numpy.core.umath', 'arccos', Notes ----- `arccos` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `cos(z) = x`. The convention is to return + many numbers `z` such that ``cos(z) = x``. The convention is to return the angle `z` whose real part lies in `[0, pi]`. For real-valued input data types, `arccos` always returns real output. @@ -193,7 +193,7 @@ add_newdoc('numpy.core.umath', 'arccos', it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytic function that - has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from + has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse `cos` is also known as `acos` or cos^-1. @@ -245,7 +245,7 @@ add_newdoc('numpy.core.umath', 'arccosh', ----- `arccosh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `cosh(z) = x`. The convention is to return the - `z` whose imaginary part lies in `[-pi, pi]` and the real part in + `z` whose imaginary part lies in ``[-pi, pi]`` and the real part in ``[0, inf]``. For real-valued input data types, `arccosh` always returns real output. @@ -406,7 +406,7 @@ add_newdoc('numpy.core.umath', 'arctan', it yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arctan` is a complex analytic function that - has [`1j, infj`] and [`-1j, -infj`] as branch cuts, and is continuous + has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous from the left on the former and from the right on the latter. The inverse tangent is also known as `atan` or tan^{-1}. @@ -544,7 +544,7 @@ add_newdoc('numpy.core.umath', 'arctanh', Notes ----- `arctanh` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `tanh(z) = x`. The convention is to return + many numbers `z` such that ``tanh(z) = x``. The convention is to return the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arctanh` always returns real output. @@ -765,7 +765,7 @@ add_newdoc('numpy.core.umath', 'ceil', Return the ceiling of the input, element-wise. The ceil of the scalar `x` is the smallest integer `i`, such that - `i >= x`. It is often denoted as :math:`\\lceil x \\rceil`. + ``i >= x``. It is often denoted as :math:`\\lceil x \\rceil`. Parameters ---------- diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index 8a1fee99b..e940ac230 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -371,7 +371,7 @@ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0): 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j, 1.00000000e+00+0.00000000e+00j]) - Graphical illustration of ``endpoint`` parameter: + Graphical illustration of `endpoint` parameter: >>> import matplotlib.pyplot as plt >>> N = 10 diff --git a/numpy/core/include/numpy/npy_common.h b/numpy/core/include/numpy/npy_common.h index c8495db8e..d5a586c56 100644 --- a/numpy/core/include/numpy/npy_common.h +++ b/numpy/core/include/numpy/npy_common.h @@ -10,6 +10,14 @@ #include <npy_config.h> #endif +// int*, int64* should be propertly aligned on ARMv7 to avoid bus error +#if !defined(NPY_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64)) +#define NPY_STRONG_ALIGNMENT 1 +#endif +#if !defined(NPY_STRONG_ALIGNMENT) +#define NPY_STRONG_ALIGNMENT 0 +#endif + // compile time environment variables #ifndef NPY_RELAXED_STRIDES_CHECKING #define NPY_RELAXED_STRIDES_CHECKING 0 diff --git a/numpy/core/multiarray.py b/numpy/core/multiarray.py index f736973de..07179a627 100644 --- a/numpy/core/multiarray.py +++ b/numpy/core/multiarray.py @@ -259,12 +259,16 @@ def inner(a, b): Returns ------- out : ndarray - `out.shape = a.shape[:-1] + b.shape[:-1]` + If `a` and `b` are both + scalars or both 1-D arrays then a scalar is returned; otherwise + an array is returned. + ``out.shape = (*a.shape[:-1], *b.shape[:-1])`` Raises ------ ValueError - If the last dimension of `a` and `b` has different size. + If both `a` and `b` are nonscalar and their last dimensions have + different sizes. See Also -------- @@ -284,8 +288,8 @@ def inner(a, b): or explicitly:: - np.inner(a, b)[i0,...,ir-1,j0,...,js-1] - = sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:]) + np.inner(a, b)[i0,...,ir-2,j0,...,js-2] + = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:]) In addition `a` or `b` may be scalars, in which case:: @@ -300,14 +304,25 @@ def inner(a, b): >>> np.inner(a, b) 2 - A multidimensional example: + Some multidimensional examples: >>> a = np.arange(24).reshape((2,3,4)) >>> b = np.arange(4) - >>> np.inner(a, b) + >>> c = np.inner(a, b) + >>> c.shape + (2, 3) + >>> c array([[ 14, 38, 62], [ 86, 110, 134]]) + >>> a = np.arange(2).reshape((1,1,2)) + >>> b = np.arange(6).reshape((3,2)) + >>> c = np.inner(a, b) + >>> c.shape + (1, 1, 3) + >>> c + array([[[1, 3, 5]]]) + An example where `b` is a scalar: >>> np.inner(np.eye(2), 7) diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index ba3e215b3..2d85e0718 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -51,7 +51,7 @@ def is_released(config): """Return True if a released version of numpy is detected.""" from distutils.version import LooseVersion - v = config.get_version('../version.py') + v = config.get_version('../_version.py') if v is None: raise ValueError("Could not get version") pv = LooseVersion(vstring=v).version diff --git a/numpy/core/src/_simd/_simd.dispatch.c.src b/numpy/core/src/_simd/_simd.dispatch.c.src index 18c383871..e3dbcdece 100644 --- a/numpy/core/src/_simd/_simd.dispatch.c.src +++ b/numpy/core/src/_simd/_simd.dispatch.c.src @@ -9,9 +9,9 @@ #include "_simd_arg.inc" #include "_simd_easyintrin.inc" -/************************************************************************* - * Defining NPYV intrinsics as module functions - *************************************************************************/ +//######################################################################### +//## Defining NPYV intrinsics as module functions +//######################################################################### /**begin repeat * #sfx = u8, s8, u16, s16, u32, s32, u64, s64, f32, f64# * #bsfx = b8, b8, b16, b16, b32, b32, b64, b64, b32, b64# @@ -22,6 +22,7 @@ * #div_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# * #fused_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# * #sum_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# + * #rev64_sup = 1, 1, 1, 1, 1, 1, 0, 0, 1, 0# * #ncont_sup = 0, 0, 0, 0, 1, 1, 1, 1, 1, 1# * #shl_imm = 0, 0, 15, 15, 31, 31, 63, 63, 0, 0# * #shr_imm = 0, 0, 16, 16, 32, 32, 64, 64, 0, 0# @@ -227,7 +228,6 @@ err: /**end repeat1**/ #endif // @ncont_sup@ - /*************************** * Misc ***************************/ @@ -289,6 +289,10 @@ SIMD_IMPL_INTRIN_2(@intrin@_@sfx@, v@sfx@, v@sfx@, v@sfx@) SIMD_IMPL_INTRIN_2(@intrin@_@sfx@, v@sfx@x2, v@sfx@, v@sfx@) /**end repeat1**/ +#if @rev64_sup@ +SIMD_IMPL_INTRIN_1(rev64_@sfx@, v@sfx@, v@sfx@) +#endif + /*************************** * Operators ***************************/ @@ -370,14 +374,26 @@ SIMD_IMPL_INTRIN_1(@intrin@_@sfx@, v@sfx@, v@sfx@) #endif // simd_sup /**end repeat**/ -/*************************** +/************************************************************************* * Variant - ***************************/ + ************************************************************************/ SIMD_IMPL_INTRIN_0N(cleanup) - /************************************************************************* - * Attach module functions - *************************************************************************/ + * A special section for boolean intrinsics outside the main repeater + ************************************************************************/ +/*************************** + * Conversions + ***************************/ +// Convert mask vector to integer bitfield +/**begin repeat + * #bsfx = b8, b16, b32, b64# + */ +SIMD_IMPL_INTRIN_1(tobits_@bsfx@, u64, v@bsfx@) +/**end repeat**/ + +//######################################################################### +//## Attach module functions +//######################################################################### static PyMethodDef simd__intrinsics_methods[] = { /**begin repeat * #sfx = u8, s8, u16, s16, u32, s32, u64, s64, f32, f64# @@ -389,6 +405,7 @@ static PyMethodDef simd__intrinsics_methods[] = { * #div_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# * #fused_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# * #sum_sup = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1# + * #rev64_sup = 1, 1, 1, 1, 1, 1, 0, 0, 1, 0# * #ncont_sup = 0, 0, 0, 0, 1, 1, 1, 1, 1, 1# * #shl_imm = 0, 0, 15, 15, 31, 31, 63, 63, 0, 0# * #shr_imm = 0, 0, 16, 16, 32, 32, 64, 64, 0, 0# @@ -416,7 +433,6 @@ SIMD_INTRIN_DEF(@intrin@_@sfx@) /**end repeat1**/ #endif // ncont_sup - /*************************** * Misc ***************************/ @@ -444,8 +460,9 @@ SIMD_INTRIN_DEF(@intrin@_@sfx@) SIMD_INTRIN_DEF(@intrin@_@sfx@) /**end repeat1**/ -SIMD_INTRIN_DEF(cvt_@sfx@_@bsfx@) -SIMD_INTRIN_DEF(cvt_@bsfx@_@sfx@) +#if @rev64_sup@ +SIMD_INTRIN_DEF(rev64_@sfx@) +#endif /*************************** * Operators @@ -517,23 +534,35 @@ SIMD_INTRIN_DEF(sum_@sfx@) SIMD_INTRIN_DEF(@intrin@_@sfx@) /**end repeat1**/ #endif - #endif // simd_sup /**end repeat**/ +/************************************************************************* + * Variant + ************************************************************************/ +SIMD_INTRIN_DEF(cleanup) +/************************************************************************* + * A special section for boolean intrinsics outside the main repeater + ************************************************************************/ /*************************** - * Variant + * Conversions ***************************/ -SIMD_INTRIN_DEF(cleanup) -/***************************/ +// Convert mask vector to integer bitfield +/**begin repeat + * #bsfx = b8, b16, b32, b64# + */ +SIMD_INTRIN_DEF(tobits_@bsfx@) +/**end repeat**/ + +/************************************************************************/ {NULL, NULL, 0, NULL} }; // PyMethodDef #endif // NPY_SIMD -/************************************************************************* - * Defining a separate module for each target - *************************************************************************/ +//######################################################################### +//## Defining a separate module for each target +//######################################################################### NPY_VISIBILITY_HIDDEN PyObject * NPY_CPU_DISPATCH_CURFX(simd_create_module)(void) { diff --git a/numpy/core/src/common/simd/avx2/avx2.h b/numpy/core/src/common/simd/avx2/avx2.h index 6f0d3c0d9..c30c2233d 100644 --- a/numpy/core/src/common/simd/avx2/avx2.h +++ b/numpy/core/src/common/simd/avx2/avx2.h @@ -1,7 +1,6 @@ #ifndef _NPY_SIMD_H_ #error "Not a standalone header" #endif - #define NPY_SIMD 256 #define NPY_SIMD_WIDTH 32 #define NPY_SIMD_F64 1 diff --git a/numpy/core/src/common/simd/avx2/conversion.h b/numpy/core/src/common/simd/avx2/conversion.h index 9fd86016d..f72678b54 100644 --- a/numpy/core/src/common/simd/avx2/conversion.h +++ b/numpy/core/src/common/simd/avx2/conversion.h @@ -14,8 +14,8 @@ #define npyv_cvt_s32_b32(A) A #define npyv_cvt_u64_b64(A) A #define npyv_cvt_s64_b64(A) A -#define npyv_cvt_f32_b32(A) _mm256_castsi256_ps(A) -#define npyv_cvt_f64_b64(A) _mm256_castsi256_pd(A) +#define npyv_cvt_f32_b32 _mm256_castsi256_ps +#define npyv_cvt_f64_b64 _mm256_castsi256_pd // convert integer types to mask types #define npyv_cvt_b8_u8(BL) BL @@ -26,7 +26,21 @@ #define npyv_cvt_b32_s32(BL) BL #define npyv_cvt_b64_u64(BL) BL #define npyv_cvt_b64_s64(BL) BL -#define npyv_cvt_b32_f32(BL) _mm256_castps_si256(BL) -#define npyv_cvt_b64_f64(BL) _mm256_castpd_si256(BL) +#define npyv_cvt_b32_f32 _mm256_castps_si256 +#define npyv_cvt_b64_f64 _mm256_castpd_si256 + +// convert boolean vector to integer bitfield +NPY_FINLINE npy_uint64 npyv_tobits_b8(npyv_b8 a) +{ return (npy_uint32)_mm256_movemask_epi8(a); } + +NPY_FINLINE npy_uint64 npyv_tobits_b16(npyv_b16 a) +{ + __m128i pack = _mm_packs_epi16(_mm256_castsi256_si128(a), _mm256_extracti128_si256(a, 1)); + return (npy_uint16)_mm_movemask_epi8(pack); +} +NPY_FINLINE npy_uint64 npyv_tobits_b32(npyv_b32 a) +{ return (npy_uint8)_mm256_movemask_ps(_mm256_castsi256_ps(a)); } +NPY_FINLINE npy_uint64 npyv_tobits_b64(npyv_b64 a) +{ return (npy_uint8)_mm256_movemask_pd(_mm256_castsi256_pd(a)); } #endif // _NPY_SIMD_AVX2_CVT_H diff --git a/numpy/core/src/common/simd/avx2/reorder.h b/numpy/core/src/common/simd/avx2/reorder.h index 5a9e68e32..4d6ec8f75 100644 --- a/numpy/core/src/common/simd/avx2/reorder.h +++ b/numpy/core/src/common/simd/avx2/reorder.h @@ -94,4 +94,36 @@ NPY_FINLINE npyv_f64x2 npyv_zip_f64(__m256d a, __m256d b) return npyv_combine_f64(ab0, ab1); } +// Reverse elements of each 64-bit lane +NPY_FINLINE npyv_u8 npyv_rev64_u8(npyv_u8 a) +{ + const __m256i idx = _mm256_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8 + ); + return _mm256_shuffle_epi8(a, idx); +} +#define npyv_rev64_s8 npyv_rev64_u8 + +NPY_FINLINE npyv_u16 npyv_rev64_u16(npyv_u16 a) +{ + const __m256i idx = _mm256_setr_epi8( + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9, + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9 + ); + return _mm256_shuffle_epi8(a, idx); +} +#define npyv_rev64_s16 npyv_rev64_u16 + +NPY_FINLINE npyv_u32 npyv_rev64_u32(npyv_u32 a) +{ + return _mm256_shuffle_epi32(a, _MM_SHUFFLE(2, 3, 0, 1)); +} +#define npyv_rev64_s32 npyv_rev64_u32 + +NPY_FINLINE npyv_f32 npyv_rev64_f32(npyv_f32 a) +{ + return _mm256_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1)); +} + #endif // _NPY_SIMD_AVX2_REORDER_H diff --git a/numpy/core/src/common/simd/avx512/conversion.h b/numpy/core/src/common/simd/avx512/conversion.h index 0f7e27de3..6ad299dd5 100644 --- a/numpy/core/src/common/simd/avx512/conversion.h +++ b/numpy/core/src/common/simd/avx512/conversion.h @@ -51,4 +51,35 @@ #define npyv_cvt_b32_f32(A) npyv_cvt_b32_u32(_mm512_castps_si512(A)) #define npyv_cvt_b64_f64(A) npyv_cvt_b64_u64(_mm512_castpd_si512(A)) +// convert boolean vectors to integer bitfield +NPY_FINLINE npy_uint64 npyv_tobits_b8(npyv_b8 a) +{ +#ifdef NPY_HAVE_AVX512BW_MASK + return (npy_uint64)_cvtmask64_u64(a); +#elif defined(NPY_HAVE_AVX512BW) + return (npy_uint64)a; +#else + int mask_lo = _mm256_movemask_epi8(npyv512_lower_si256(a)); + int mask_hi = _mm256_movemask_epi8(npyv512_higher_si256(a)); + return (unsigned)mask_lo | ((npy_uint64)(unsigned)mask_hi << 32); +#endif +} +NPY_FINLINE npy_uint64 npyv_tobits_b16(npyv_b16 a) +{ +#ifdef NPY_HAVE_AVX512BW_MASK + return (npy_uint32)_cvtmask32_u32(a); +#elif defined(NPY_HAVE_AVX512BW) + return (npy_uint32)a; +#else + __m256i pack = _mm256_packs_epi16( + npyv512_lower_si256(a), npyv512_higher_si256(a) + ); + return (npy_uint32)_mm256_movemask_epi8(_mm256_permute4x64_epi64(pack, _MM_SHUFFLE(3, 1, 2, 0))); +#endif +} +NPY_FINLINE npy_uint64 npyv_tobits_b32(npyv_b32 a) +{ return (npy_uint16)a; } +NPY_FINLINE npy_uint64 npyv_tobits_b64(npyv_b64 a) +{ return (npy_uint8)a; } + #endif // _NPY_SIMD_AVX512_CVT_H diff --git a/numpy/core/src/common/simd/avx512/reorder.h b/numpy/core/src/common/simd/avx512/reorder.h index cdbae7aac..f043004ec 100644 --- a/numpy/core/src/common/simd/avx512/reorder.h +++ b/numpy/core/src/common/simd/avx512/reorder.h @@ -167,4 +167,60 @@ NPY_FINLINE npyv_f64x2 npyv_zip_f64(__m512d a, __m512d b) return r; } +// Reverse elements of each 64-bit lane +NPY_FINLINE npyv_u8 npyv_rev64_u8(npyv_u8 a) +{ +#ifdef NPY_HAVE_AVX512BW + const __m512i idx = npyv_set_u8( + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8 + ); + return _mm512_shuffle_epi8(a, idx); +#else + const __m256i idx = _mm256_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 + ); + __m256i lo = _mm256_shuffle_epi8(npyv512_lower_si256(a), idx); + __m256i hi = _mm256_shuffle_epi8(npyv512_higher_si256(a), idx); + return npyv512_combine_si256(lo, hi); +#endif +} +#define npyv_rev64_s8 npyv_rev64_u8 + +NPY_FINLINE npyv_u16 npyv_rev64_u16(npyv_u16 a) +{ +#ifdef NPY_HAVE_AVX512BW + const __m512i idx = npyv_set_u8( + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9, + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9, + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9, + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9 + ); + return _mm512_shuffle_epi8(a, idx); +#else + const __m256i idx = _mm256_setr_epi8( + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9, + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9 + ); + __m256i lo = _mm256_shuffle_epi8(npyv512_lower_si256(a), idx); + __m256i hi = _mm256_shuffle_epi8(npyv512_higher_si256(a), idx); + return npyv512_combine_si256(lo, hi); +#endif +} +#define npyv_rev64_s16 npyv_rev64_u16 + +NPY_FINLINE npyv_u32 npyv_rev64_u32(npyv_u32 a) +{ + return _mm512_shuffle_epi32(a, _MM_SHUFFLE(2, 3, 0, 1)); +} +#define npyv_rev64_s32 npyv_rev64_u32 + +NPY_FINLINE npyv_f32 npyv_rev64_f32(npyv_f32 a) +{ + return _mm512_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1)); +} + #endif // _NPY_SIMD_AVX512_REORDER_H diff --git a/numpy/core/src/common/simd/neon/conversion.h b/numpy/core/src/common/simd/neon/conversion.h index b286931d1..f9840b1cb 100644 --- a/numpy/core/src/common/simd/neon/conversion.h +++ b/numpy/core/src/common/simd/neon/conversion.h @@ -7,26 +7,68 @@ // convert boolean vectors to integer vectors #define npyv_cvt_u8_b8(A) A -#define npyv_cvt_s8_b8(A) vreinterpretq_s8_u8(A) +#define npyv_cvt_s8_b8 vreinterpretq_s8_u8 #define npyv_cvt_u16_b16(A) A -#define npyv_cvt_s16_b16(A) vreinterpretq_s16_u16(A) +#define npyv_cvt_s16_b16 vreinterpretq_s16_u16 #define npyv_cvt_u32_b32(A) A -#define npyv_cvt_s32_b32(A) vreinterpretq_s32_u32(A) +#define npyv_cvt_s32_b32 vreinterpretq_s32_u32 #define npyv_cvt_u64_b64(A) A -#define npyv_cvt_s64_b64(A) vreinterpretq_s64_u64(A) -#define npyv_cvt_f32_b32(A) vreinterpretq_f32_u32(A) -#define npyv_cvt_f64_b64(A) vreinterpretq_f64_u64(A) +#define npyv_cvt_s64_b64 vreinterpretq_s64_u64 +#define npyv_cvt_f32_b32 vreinterpretq_f32_u32 +#define npyv_cvt_f64_b64 vreinterpretq_f64_u64 // convert integer vectors to boolean vectors #define npyv_cvt_b8_u8(BL) BL -#define npyv_cvt_b8_s8(BL) vreinterpretq_u8_s8(BL) +#define npyv_cvt_b8_s8 vreinterpretq_u8_s8 #define npyv_cvt_b16_u16(BL) BL -#define npyv_cvt_b16_s16(BL) vreinterpretq_u16_s16(BL) +#define npyv_cvt_b16_s16 vreinterpretq_u16_s16 #define npyv_cvt_b32_u32(BL) BL -#define npyv_cvt_b32_s32(BL) vreinterpretq_u32_s32(BL) +#define npyv_cvt_b32_s32 vreinterpretq_u32_s32 #define npyv_cvt_b64_u64(BL) BL -#define npyv_cvt_b64_s64(BL) vreinterpretq_u64_s64(BL) -#define npyv_cvt_b32_f32(BL) vreinterpretq_u32_f32(BL) -#define npyv_cvt_b64_f64(BL) vreinterpretq_u64_f64(BL) +#define npyv_cvt_b64_s64 vreinterpretq_u64_s64 +#define npyv_cvt_b32_f32 vreinterpretq_u32_f32 +#define npyv_cvt_b64_f64 vreinterpretq_u64_f64 + +// convert boolean vector to integer bitfield +NPY_FINLINE npy_uint64 npyv_tobits_b8(npyv_b8 a) +{ + const npyv_u8 scale = npyv_set_u8(1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128); + npyv_u8 seq_scale = vandq_u8(a, scale); +#if NPY_SIMD_F64 + npy_uint8 sumlo = vaddv_u8(vget_low_u8(seq_scale)); + npy_uint8 sumhi = vaddv_u8(vget_high_u8(seq_scale)); + return sumlo + ((int)sumhi << 8); +#else + npyv_u64 sumh = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(seq_scale))); + return vgetq_lane_u64(sumh, 0) + ((int)vgetq_lane_u64(sumh, 1) << 8); +#endif +} +NPY_FINLINE npy_uint64 npyv_tobits_b16(npyv_b16 a) +{ + const npyv_u16 scale = npyv_set_u16(1, 2, 4, 8, 16, 32, 64, 128); + npyv_u16 seq_scale = vandq_u16(a, scale); +#if NPY_SIMD_F64 + return vaddvq_u16(seq_scale); +#else + npyv_u64 sumh = vpaddlq_u32(vpaddlq_u16(seq_scale)); + return vgetq_lane_u64(sumh, 0) + vgetq_lane_u64(sumh, 1); +#endif +} +NPY_FINLINE npy_uint64 npyv_tobits_b32(npyv_b32 a) +{ + const npyv_u32 scale = npyv_set_u32(1, 2, 4, 8); + npyv_u32 seq_scale = vandq_u32(a, scale); +#if NPY_SIMD_F64 + return vaddvq_u32(seq_scale); +#else + npyv_u64 sumh = vpaddlq_u32(seq_scale); + return vgetq_lane_u64(sumh, 0) + vgetq_lane_u64(sumh, 1); +#endif +} +NPY_FINLINE npy_uint64 npyv_tobits_b64(npyv_b64 a) +{ + npyv_u64 bit = vshrq_n_u64(a, 63); + return vgetq_lane_u64(bit, 0) | ((int)vgetq_lane_u64(bit, 1) << 1); +} #endif // _NPY_SIMD_NEON_CVT_H diff --git a/numpy/core/src/common/simd/neon/reorder.h b/numpy/core/src/common/simd/neon/reorder.h index 712a77982..50b06ed11 100644 --- a/numpy/core/src/common/simd/neon/reorder.h +++ b/numpy/core/src/common/simd/neon/reorder.h @@ -107,4 +107,13 @@ NPYV_IMPL_NEON_COMBINE(npyv_f64, f64) #define npyv_zip_u64 npyv_combine_u64 #define npyv_zip_s64 npyv_combine_s64 +// Reverse elements of each 64-bit lane +#define npyv_rev64_u8 vrev64q_u8 +#define npyv_rev64_s8 vrev64q_s8 +#define npyv_rev64_u16 vrev64q_u16 +#define npyv_rev64_s16 vrev64q_s16 +#define npyv_rev64_u32 vrev64q_u32 +#define npyv_rev64_s32 vrev64q_s32 +#define npyv_rev64_f32 vrev64q_f32 + #endif // _NPY_SIMD_NEON_REORDER_H diff --git a/numpy/core/src/common/simd/sse/conversion.h b/numpy/core/src/common/simd/sse/conversion.h index ea9660d13..ab4beea96 100644 --- a/numpy/core/src/common/simd/sse/conversion.h +++ b/numpy/core/src/common/simd/sse/conversion.h @@ -14,8 +14,8 @@ #define npyv_cvt_s32_b32(BL) BL #define npyv_cvt_u64_b64(BL) BL #define npyv_cvt_s64_b64(BL) BL -#define npyv_cvt_f32_b32(BL) _mm_castsi128_ps(BL) -#define npyv_cvt_f64_b64(BL) _mm_castsi128_pd(BL) +#define npyv_cvt_f32_b32 _mm_castsi128_ps +#define npyv_cvt_f64_b64 _mm_castsi128_pd // convert integer types to mask types #define npyv_cvt_b8_u8(A) A @@ -26,7 +26,20 @@ #define npyv_cvt_b32_s32(A) A #define npyv_cvt_b64_u64(A) A #define npyv_cvt_b64_s64(A) A -#define npyv_cvt_b32_f32(A) _mm_castps_si128(A) -#define npyv_cvt_b64_f64(A) _mm_castpd_si128(A) +#define npyv_cvt_b32_f32 _mm_castps_si128 +#define npyv_cvt_b64_f64 _mm_castpd_si128 + +// convert boolean vector to integer bitfield +NPY_FINLINE npy_uint64 npyv_tobits_b8(npyv_b8 a) +{ return (npy_uint16)_mm_movemask_epi8(a); } +NPY_FINLINE npy_uint64 npyv_tobits_b16(npyv_b16 a) +{ + __m128i pack = _mm_packs_epi16(a, a); + return (npy_uint8)_mm_movemask_epi8(pack); +} +NPY_FINLINE npy_uint64 npyv_tobits_b32(npyv_b32 a) +{ return (npy_uint8)_mm_movemask_ps(_mm_castsi128_ps(a)); } +NPY_FINLINE npy_uint64 npyv_tobits_b64(npyv_b64 a) +{ return (npy_uint8)_mm_movemask_pd(_mm_castsi128_pd(a)); } #endif // _NPY_SIMD_SSE_CVT_H diff --git a/numpy/core/src/common/simd/sse/reorder.h b/numpy/core/src/common/simd/sse/reorder.h index 3f68b4ad7..d96ab9c56 100644 --- a/numpy/core/src/common/simd/sse/reorder.h +++ b/numpy/core/src/common/simd/sse/reorder.h @@ -81,4 +81,45 @@ NPYV_IMPL_SSE_ZIP(npyv_s64, s64, epi64) NPYV_IMPL_SSE_ZIP(npyv_f32, f32, ps) NPYV_IMPL_SSE_ZIP(npyv_f64, f64, pd) +// Reverse elements of each 64-bit lane +NPY_FINLINE npyv_u16 npyv_rev64_u16(npyv_u16 a) +{ +#ifdef NPY_HAVE_SSSE3 + const __m128i idx = _mm_setr_epi8( + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9 + ); + return _mm_shuffle_epi8(a, idx); +#else + __m128i lo = _mm_shufflelo_epi16(a, _MM_SHUFFLE(0, 1, 2, 3)); + return _mm_shufflehi_epi16(lo, _MM_SHUFFLE(0, 1, 2, 3)); +#endif +} +#define npyv_rev64_s16 npyv_rev64_u16 + +NPY_FINLINE npyv_u8 npyv_rev64_u8(npyv_u8 a) +{ +#ifdef NPY_HAVE_SSSE3 + const __m128i idx = _mm_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8 + ); + return _mm_shuffle_epi8(a, idx); +#else + __m128i rev16 = npyv_rev64_u16(a); + // swap 8bit pairs + return _mm_or_si128(_mm_slli_epi16(rev16, 8), _mm_srli_epi16(rev16, 8)); +#endif +} +#define npyv_rev64_s8 npyv_rev64_u8 + +NPY_FINLINE npyv_u32 npyv_rev64_u32(npyv_u32 a) +{ + return _mm_shuffle_epi32(a, _MM_SHUFFLE(2, 3, 0, 1)); +} +#define npyv_rev64_s32 npyv_rev64_u32 + +NPY_FINLINE npyv_f32 npyv_rev64_f32(npyv_f32 a) +{ + return _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1)); +} + #endif // _NPY_SIMD_SSE_REORDER_H diff --git a/numpy/core/src/common/simd/vsx/conversion.h b/numpy/core/src/common/simd/vsx/conversion.h index 6ed135990..5803e1cdd 100644 --- a/numpy/core/src/common/simd/vsx/conversion.h +++ b/numpy/core/src/common/simd/vsx/conversion.h @@ -29,4 +29,26 @@ #define npyv_cvt_b32_f32(A) ((npyv_b32) A) #define npyv_cvt_b64_f64(A) ((npyv_b64) A) +// convert boolean vector to integer bitfield +NPY_FINLINE npy_uint64 npyv_tobits_b8(npyv_b8 a) +{ + const npyv_u8 qperm = npyv_set_u8(120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0); + return vec_extract((npyv_u32)vec_vbpermq((npyv_u8)a, qperm), 2); +} +NPY_FINLINE npy_uint64 npyv_tobits_b16(npyv_b16 a) +{ + const npyv_u8 qperm = npyv_setf_u8(128, 112, 96, 80, 64, 48, 32, 16, 0); + return vec_extract((npyv_u32)vec_vbpermq((npyv_u8)a, qperm), 2); +} +NPY_FINLINE npy_uint64 npyv_tobits_b32(npyv_b32 a) +{ + const npyv_u8 qperm = npyv_setf_u8(128, 96, 64, 32, 0); + return vec_extract((npyv_u32)vec_vbpermq((npyv_u8)a, qperm), 2); +} +NPY_FINLINE npy_uint64 npyv_tobits_b64(npyv_b64 a) +{ + npyv_u64 bit = npyv_shri_u64((npyv_u64)a, 63); + return vec_extract(bit, 0) | (int)vec_extract(bit, 1) << 1; +} + #endif // _NPY_SIMD_VSX_CVT_H diff --git a/numpy/core/src/common/simd/vsx/reorder.h b/numpy/core/src/common/simd/vsx/reorder.h index bfb9115fa..6533e5093 100644 --- a/numpy/core/src/common/simd/vsx/reorder.h +++ b/numpy/core/src/common/simd/vsx/reorder.h @@ -62,4 +62,45 @@ NPYV_IMPL_VSX_COMBINE_ZIP(npyv_s64, s64) NPYV_IMPL_VSX_COMBINE_ZIP(npyv_f32, f32) NPYV_IMPL_VSX_COMBINE_ZIP(npyv_f64, f64) +// Reverse elements of each 64-bit lane +NPY_FINLINE npyv_u8 npyv_rev64_u8(npyv_u8 a) +{ +#if defined(NPY_HAVE_VSX3) && ((defined(__GNUC__) && __GNUC__ > 7) || defined(__IBMC__)) + return (npyv_u8)vec_revb((npyv_u64)a); +#elif defined(NPY_HAVE_VSX3) && defined(NPY_HAVE_VSX_ASM) + npyv_u8 ret; + __asm__ ("xxbrd %x0,%x1" : "=wa" (ret) : "wa" (a)); + return ret; +#else + const npyv_u8 idx = npyv_set_u8( + 7, 6, 5, 4, 3, 2, 1, 0,/*64*/15, 14, 13, 12, 11, 10, 9, 8 + ); + return vec_perm(a, a, idx); +#endif +} +NPY_FINLINE npyv_s8 npyv_rev64_s8(npyv_s8 a) +{ return (npyv_s8)npyv_rev64_u8((npyv_u8)a); } + +NPY_FINLINE npyv_u16 npyv_rev64_u16(npyv_u16 a) +{ + const npyv_u8 idx = npyv_set_u8( + 6, 7, 4, 5, 2, 3, 0, 1,/*64*/14, 15, 12, 13, 10, 11, 8, 9 + ); + return vec_perm(a, a, idx); +} +NPY_FINLINE npyv_s16 npyv_rev64_s16(npyv_s16 a) +{ return (npyv_s16)npyv_rev64_u16((npyv_u16)a); } + +NPY_FINLINE npyv_u32 npyv_rev64_u32(npyv_u32 a) +{ + const npyv_u8 idx = npyv_set_u8( + 4, 5, 6, 7, 0, 1, 2, 3,/*64*/12, 13, 14, 15, 8, 9, 10, 11 + ); + return vec_perm(a, a, idx); +} +NPY_FINLINE npyv_s32 npyv_rev64_s32(npyv_s32 a) +{ return (npyv_s32)npyv_rev64_u32((npyv_u32)a); } +NPY_FINLINE npyv_f32 npyv_rev64_f32(npyv_f32 a) +{ return (npyv_f32)npyv_rev64_u32((npyv_u32)a); } + #endif // _NPY_SIMD_VSX_REORDER_H diff --git a/numpy/core/src/multiarray/array_coercion.c b/numpy/core/src/multiarray/array_coercion.c index 53d891049..1eac401bc 100644 --- a/numpy/core/src/multiarray/array_coercion.c +++ b/numpy/core/src/multiarray/array_coercion.c @@ -922,6 +922,53 @@ PyArray_DiscoverDTypeAndShape_Recursive( Py_DECREF(arr); arr = NULL; } + else if (curr_dims > 0 && curr_dims != max_dims) { + /* + * Deprecated 2020-12-09, NumPy 1.20 + * + * See https://github.com/numpy/numpy/issues/17965 + * Shapely had objects which are not sequences but did export + * the array-interface (and so are arguably array-like). + * Previously numpy would not use array-like information during + * shape discovery, so that it ended up acting as if this was + * an (unknown) scalar but with the specified dtype. + * Thus we ignore "scalars" here, as the value stored in the + * array should be acceptable. + */ + if (PyArray_NDIM(arr) > 0 && NPY_UNLIKELY(!PySequence_Check(obj))) { + if (PyErr_WarnFormat(PyExc_FutureWarning, 1, + "The input object of type '%s' is an array-like " + "implementing one of the corresponding protocols " + "(`__array__`, `__array_interface__` or " + "`__array_struct__`); but not a sequence (or 0-D). " + "In the future, this object will be coerced as if it " + "was first converted using `np.array(obj)`. " + "To retain the old behaviour, you have to either " + "modify the type '%s', or assign to an empty array " + "created with `np.empty(correct_shape, dtype=object)`.", + Py_TYPE(obj)->tp_name, Py_TYPE(obj)->tp_name) < 0) { + Py_DECREF(arr); + return -1; + } + /* + * Strangely enough, even though we threw away the result here, + * we did use it during descriptor discovery, so promote it: + */ + if (update_shape(curr_dims, &max_dims, out_shape, + 0, NULL, NPY_FALSE, flags) < 0) { + *flags |= FOUND_RAGGED_ARRAY; + Py_DECREF(arr); + return max_dims; + } + if (!(*flags & DESCRIPTOR_WAS_SET) && handle_promotion( + out_descr, PyArray_DESCR(arr), fixed_DType, flags) < 0) { + Py_DECREF(arr); + return -1; + } + Py_DECREF(arr); + return max_dims; + } + } } if (arr != NULL) { /* @@ -979,14 +1026,28 @@ PyArray_DiscoverDTypeAndShape_Recursive( * and to handle it recursively. That is, unless we have hit the * dimension limit. */ - npy_bool is_sequence = (PySequence_Check(obj) && PySequence_Size(obj) >= 0); + npy_bool is_sequence = PySequence_Check(obj); + if (is_sequence) { + is_sequence = PySequence_Size(obj) >= 0; + if (NPY_UNLIKELY(!is_sequence)) { + /* NOTE: This should likely just raise all errors */ + if (PyErr_ExceptionMatches(PyExc_RecursionError) || + PyErr_ExceptionMatches(PyExc_MemoryError)) { + /* + * Consider these unrecoverable errors, continuing execution + * might crash the interpreter. + */ + return -1; + } + PyErr_Clear(); + } + } if (NPY_UNLIKELY(*flags & DISCOVER_TUPLES_AS_ELEMENTS) && PyTuple_Check(obj)) { is_sequence = NPY_FALSE; } if (curr_dims == max_dims || !is_sequence) { /* Clear any PySequence_Size error which would corrupts further calls */ - PyErr_Clear(); max_dims = handle_scalar( obj, curr_dims, &max_dims, out_descr, out_shape, fixed_DType, flags, NULL); diff --git a/numpy/core/src/multiarray/compiled_base.c b/numpy/core/src/multiarray/compiled_base.c index da857071b..6ae4dda6b 100644 --- a/numpy/core/src/multiarray/compiled_base.c +++ b/numpy/core/src/multiarray/compiled_base.c @@ -13,7 +13,12 @@ #include "alloc.h" #include "ctors.h" #include "common.h" +#include "simd/simd.h" +typedef enum { + PACK_ORDER_LITTLE = 0, + PACK_ORDER_BIG +} PACK_ORDER; /* * Returns -1 if the array is monotonic decreasing, @@ -1465,27 +1470,12 @@ arr_add_docstring(PyObject *NPY_UNUSED(dummy), PyObject *args) Py_RETURN_NONE; } -#if defined NPY_HAVE_SSE2_INTRINSICS -#include <emmintrin.h> -#endif - -#ifdef NPY_HAVE_NEON - typedef npy_uint64 uint64_unaligned __attribute__((aligned(16))); - static NPY_INLINE int32_t - sign_mask(uint8x16_t input) - { - int8x8_t m0 = vcreate_s8(0x0706050403020100ULL); - uint8x16_t v0 = vshlq_u8(vshrq_n_u8(input, 7), vcombine_s8(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); - } -#endif /* * This function packs boolean values in the input array into the bits of a * byte array. Truth values are determined as usual: 0 is false, everything * else is true. */ -static NPY_INLINE void +static NPY_GCC_OPT_3 NPY_INLINE void pack_inner(const char *inptr, npy_intp element_size, /* in bytes */ npy_intp n_in, @@ -1493,7 +1483,7 @@ pack_inner(const char *inptr, char *outptr, npy_intp n_out, npy_intp out_stride, - char order) + PACK_ORDER order) { /* * Loop through the elements of inptr. @@ -1505,62 +1495,64 @@ pack_inner(const char *inptr, npy_intp index = 0; int remain = n_in % 8; /* uneven bits */ -#if defined NPY_HAVE_SSE2_INTRINSICS && defined HAVE__M_FROM_INT64 +#if NPY_SIMD if (in_stride == 1 && element_size == 1 && n_out > 2) { - __m128i zero = _mm_setzero_si128(); + npyv_u8 v_zero = npyv_zero_u8(); /* don't handle non-full 8-byte remainder */ npy_intp vn_out = n_out - (remain ? 1 : 0); - vn_out -= (vn_out & 1); - for (index = 0; index < vn_out; index += 2) { - unsigned int r; - npy_uint64 a = *(npy_uint64*)inptr; - npy_uint64 b = *(npy_uint64*)(inptr + 8); - if (order == 'b') { - a = npy_bswap8(a); - b = npy_bswap8(b); + const int vstep = npyv_nlanes_u64; + const int vstepx4 = vstep * 4; + const int isAligned = npy_is_aligned(outptr, sizeof(npy_uint64)); + vn_out -= (vn_out & (vstep - 1)); + for (; index <= vn_out - vstepx4; index += vstepx4, inptr += npyv_nlanes_u8 * 4) { + npyv_u8 v0 = npyv_load_u8((const npy_uint8*)inptr); + npyv_u8 v1 = npyv_load_u8((const npy_uint8*)inptr + npyv_nlanes_u8 * 1); + npyv_u8 v2 = npyv_load_u8((const npy_uint8*)inptr + npyv_nlanes_u8 * 2); + npyv_u8 v3 = npyv_load_u8((const npy_uint8*)inptr + npyv_nlanes_u8 * 3); + if (order == PACK_ORDER_BIG) { + v0 = npyv_rev64_u8(v0); + v1 = npyv_rev64_u8(v1); + v2 = npyv_rev64_u8(v2); + v3 = npyv_rev64_u8(v3); } - - /* note x86 can load unaligned */ - __m128i v = _mm_set_epi64(_m_from_int64(b), _m_from_int64(a)); - /* false -> 0x00 and true -> 0xFF (there is no cmpneq) */ - v = _mm_cmpeq_epi8(v, zero); - v = _mm_cmpeq_epi8(v, zero); - /* extract msb of 16 bytes and pack it into 16 bit */ - r = _mm_movemask_epi8(v); - /* store result */ - memcpy(outptr, &r, 1); - outptr += out_stride; - memcpy(outptr, (char*)&r + 1, 1); - outptr += out_stride; - inptr += 16; - } - } -#elif defined NPY_HAVE_NEON - if (in_stride == 1 && element_size == 1 && n_out > 2) { - /* don't handle non-full 8-byte remainder */ - npy_intp vn_out = n_out - (remain ? 1 : 0); - vn_out -= (vn_out & 1); - for (index = 0; index < vn_out; index += 2) { - unsigned int r; - npy_uint64 a = *((uint64_unaligned*)inptr); - npy_uint64 b = *((uint64_unaligned*)(inptr + 8)); - if (order == 'b') { - a = npy_bswap8(a); - b = npy_bswap8(b); + npy_uint64 bb[4]; + bb[0] = npyv_tobits_b8(npyv_cmpneq_u8(v0, v_zero)); + bb[1] = npyv_tobits_b8(npyv_cmpneq_u8(v1, v_zero)); + bb[2] = npyv_tobits_b8(npyv_cmpneq_u8(v2, v_zero)); + bb[3] = npyv_tobits_b8(npyv_cmpneq_u8(v3, v_zero)); + if(out_stride == 1 && + (!NPY_STRONG_ALIGNMENT || isAligned)) { + npy_uint64 *ptr64 = (npy_uint64*)outptr; + #if NPY_SIMD_WIDTH == 16 + npy_uint64 bcomp = bb[0] | (bb[1] << 16) | (bb[2] << 32) | (bb[3] << 48); + ptr64[0] = bcomp; + #elif NPY_SIMD_WIDTH == 32 + ptr64[0] = bb[0] | (bb[1] << 32); + ptr64[1] = bb[2] | (bb[3] << 32); + #else + ptr64[0] = bb[0]; ptr64[1] = bb[1]; + ptr64[2] = bb[2]; ptr64[3] = bb[3]; + #endif + outptr += vstepx4; + } else { + for(int i = 0; i < 4; i++) { + for (int j = 0; j < vstep; j++) { + memcpy(outptr, (char*)&bb[i] + j, 1); + outptr += out_stride; + } + } + } + } + for (; index < vn_out; index += vstep, inptr += npyv_nlanes_u8) { + npyv_u8 va = npyv_load_u8((const npy_uint8*)inptr); + if (order == PACK_ORDER_BIG) { + va = npyv_rev64_u8(va); + } + npy_uint64 bb = npyv_tobits_b8(npyv_cmpneq_u8(va, v_zero)); + for (int i = 0; i < vstep; ++i) { + memcpy(outptr, (char*)&bb + i, 1); + outptr += out_stride; } - uint64x2_t v = vcombine_u64(vcreate_u64(a), vcreate_u64(b)); - uint64x2_t zero = vdupq_n_u64(0); - /* false -> 0x00 and true -> 0xFF */ - v = vreinterpretq_u64_u8(vmvnq_u8(vceqq_u8(vreinterpretq_u8_u64(v), vreinterpretq_u8_u64(zero)))); - /* extract msb of 16 bytes and pack it into 16 bit */ - uint8x16_t input = vreinterpretq_u8_u64(v); - r = sign_mask(input); - /* store result */ - memcpy(outptr, &r, 1); - outptr += out_stride; - memcpy(outptr, (char*)&r + 1, 1); - outptr += out_stride; - inptr += 16; } } #endif @@ -1571,14 +1563,11 @@ pack_inner(const char *inptr, /* Don't reset index. Just handle remainder of above block */ for (; index < n_out; index++) { unsigned char build = 0; - int i, maxi; - npy_intp j; - - maxi = (index == n_out - 1) ? remain : 8; - if (order == 'b') { - for (i = 0; i < maxi; i++) { + int maxi = (index == n_out - 1) ? remain : 8; + if (order == PACK_ORDER_BIG) { + for (int i = 0; i < maxi; i++) { build <<= 1; - for (j = 0; j < element_size; j++) { + for (npy_intp j = 0; j < element_size; j++) { build |= (inptr[j] != 0); } inptr += in_stride; @@ -1589,9 +1578,9 @@ pack_inner(const char *inptr, } else { - for (i = 0; i < maxi; i++) { + for (int i = 0; i < maxi; i++) { build >>= 1; - for (j = 0; j < element_size; j++) { + for (npy_intp j = 0; j < element_size; j++) { build |= (inptr[j] != 0) ? 128 : 0; } inptr += in_stride; @@ -1685,13 +1674,13 @@ pack_bits(PyObject *input, int axis, char order) Py_XDECREF(ot); goto fail; } - + const PACK_ORDER ordere = order == 'b' ? PACK_ORDER_BIG : PACK_ORDER_LITTLE; NPY_BEGIN_THREADS_THRESHOLDED(PyArray_DIM(out, axis)); while (PyArray_ITER_NOTDONE(it)) { pack_inner(PyArray_ITER_DATA(it), PyArray_ITEMSIZE(new), PyArray_DIM(new, axis), PyArray_STRIDE(new, axis), PyArray_ITER_DATA(ot), PyArray_DIM(out, axis), - PyArray_STRIDE(out, axis), order); + PyArray_STRIDE(out, axis), ordere); PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(ot); } diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index f6031e370..58571b678 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -2124,7 +2124,7 @@ PyArray_FromInterface(PyObject *origin) if (iface == NULL) { if (PyErr_Occurred()) { - PyErr_Clear(); /* TODO[gh-14801]: propagate crashes during attribute access? */ + return NULL; } return Py_NotImplemented; } @@ -2392,7 +2392,7 @@ PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context) array_meth = PyArray_LookupSpecial_OnInstance(op, "__array__"); if (array_meth == NULL) { if (PyErr_Occurred()) { - PyErr_Clear(); /* TODO[gh-14801]: propagate crashes during attribute access? */ + return NULL; } return Py_NotImplemented; } diff --git a/numpy/core/src/multiarray/einsum_sumprod.c.src b/numpy/core/src/multiarray/einsum_sumprod.c.src index c58e74287..86d5b82fc 100644 --- a/numpy/core/src/multiarray/einsum_sumprod.c.src +++ b/numpy/core/src/multiarray/einsum_sumprod.c.src @@ -17,7 +17,8 @@ #include "einsum_sumprod.h" #include "einsum_debug.h" - +#include "simd/simd.h" +#include "common.h" #ifdef NPY_HAVE_SSE_INTRINSICS #define EINSUM_USE_SSE1 1 @@ -41,6 +42,13 @@ #define EINSUM_IS_SSE_ALIGNED(x) ((((npy_intp)x)&0xf) == 0) +// ARM/Neon don't have instructions for aligned memory access +#ifdef NPY_HAVE_NEON + #define EINSUM_IS_ALIGNED(x) 0 +#else + #define EINSUM_IS_ALIGNED(x) npy_is_aligned(x, NPY_SIMD_WIDTH) +#endif + /**********************************************/ /**begin repeat @@ -56,6 +64,10 @@ * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_float, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble# + * #sfx = s8, s16, s32, long, s64, + * u8, u16, u32, ulong, u64, + * half, f32, f64, longdouble, + * f32, f64, clongdouble# * #to = ,,,,, * ,,,,, * npy_float_to_half,,,, @@ -76,6 +88,10 @@ * 0*5, * 0,0,1,0, * 0*3# + * #NPYV_CHK = 0*5, + * 0*5, + * 0, NPY_SIMD, NPY_SIMD_F64, 0, + * 0*3# */ /**begin repeat1 @@ -250,115 +266,80 @@ static void @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @type@ *data_out = (@type@ *)dataptr[2]; - -#if EINSUM_USE_SSE1 && @float32@ - __m128 a, b; -#elif EINSUM_USE_SSE2 && @float64@ - __m128d a, b; -#endif - NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_two (%d)\n", (int)count); - -/* This is placed before the main loop to make small counts faster */ -finish_after_unrolled_loop: - switch (count) { -/**begin repeat2 - * #i = 6, 5, 4, 3, 2, 1, 0# - */ - case @i@+1: - data_out[@i@] = @to@(@from@(data0[@i@]) * - @from@(data1[@i@]) + - @from@(data_out[@i@])); -/**end repeat2**/ - case 0: - return; - } - -#if EINSUM_USE_SSE1 && @float32@ + // NPYV check for @type@ +#if @NPYV_CHK@ /* Use aligned instructions if possible */ - if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1) && - EINSUM_IS_SSE_ALIGNED(data_out)) { - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - -/**begin repeat2 - * #i = 0, 4# - */ - a = _mm_mul_ps(_mm_load_ps(data0+@i@), _mm_load_ps(data1+@i@)); - b = _mm_add_ps(a, _mm_load_ps(data_out+@i@)); - _mm_store_ps(data_out+@i@, b); -/**end repeat2**/ - data0 += 8; - data1 += 8; - data_out += 8; + const int is_aligned = EINSUM_IS_ALIGNED(data0) && EINSUM_IS_ALIGNED(data1) && + EINSUM_IS_ALIGNED(data_out); + const int vstep = npyv_nlanes_@sfx@; + + /**begin repeat2 + * #cond = if(is_aligned), else# + * #ld = loada, load# + * #st = storea, store# + */ + @cond@ { + const npy_intp vstepx4 = vstep * 4; + for (; count >= vstepx4; count -= vstepx4, data0 += vstepx4, data1 += vstepx4, data_out += vstepx4) { + /**begin repeat3 + * #i = 0, 1, 2, 3# + */ + npyv_@sfx@ a@i@ = npyv_@ld@_@sfx@(data0 + vstep * @i@); + npyv_@sfx@ b@i@ = npyv_@ld@_@sfx@(data1 + vstep * @i@); + npyv_@sfx@ c@i@ = npyv_@ld@_@sfx@(data_out + vstep * @i@); + /**end repeat3**/ + /**begin repeat3 + * #i = 0, 1, 2, 3# + */ + npyv_@sfx@ abc@i@ = npyv_muladd_@sfx@(a@i@, b@i@, c@i@); + /**end repeat3**/ + /**begin repeat3 + * #i = 0, 1, 2, 3# + */ + npyv_@st@_@sfx@(data_out + vstep * @i@, abc@i@); + /**end repeat3**/ } - - /* Finish off the loop */ - goto finish_after_unrolled_loop; } -#elif EINSUM_USE_SSE2 && @float64@ - /* Use aligned instructions if possible */ - if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1) && - EINSUM_IS_SSE_ALIGNED(data_out)) { - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - -/**begin repeat2 - * #i = 0, 2, 4, 6# - */ - a = _mm_mul_pd(_mm_load_pd(data0+@i@), _mm_load_pd(data1+@i@)); - b = _mm_add_pd(a, _mm_load_pd(data_out+@i@)); - _mm_store_pd(data_out+@i@, b); -/**end repeat2**/ - data0 += 8; - data1 += 8; - data_out += 8; - } - - /* Finish off the loop */ - goto finish_after_unrolled_loop; + /**end repeat2**/ + for (; count > 0; count -= vstep, data0 += vstep, data1 += vstep, data_out += vstep) { + npyv_@sfx@ a = npyv_load_tillz_@sfx@(data0, count); + npyv_@sfx@ b = npyv_load_tillz_@sfx@(data1, count); + npyv_@sfx@ c = npyv_load_tillz_@sfx@(data_out, count); + npyv_store_till_@sfx@(data_out, count, npyv_muladd_@sfx@(a, b, c)); } -#endif - - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - -#if EINSUM_USE_SSE1 && @float32@ -/**begin repeat2 - * #i = 0, 4# - */ - a = _mm_mul_ps(_mm_loadu_ps(data0+@i@), _mm_loadu_ps(data1+@i@)); - b = _mm_add_ps(a, _mm_loadu_ps(data_out+@i@)); - _mm_storeu_ps(data_out+@i@, b); -/**end repeat2**/ -#elif EINSUM_USE_SSE2 && @float64@ -/**begin repeat2 - * #i = 0, 2, 4, 6# - */ - a = _mm_mul_pd(_mm_loadu_pd(data0+@i@), _mm_loadu_pd(data1+@i@)); - b = _mm_add_pd(a, _mm_loadu_pd(data_out+@i@)); - _mm_storeu_pd(data_out+@i@, b); -/**end repeat2**/ + npyv_cleanup(); #else -/**begin repeat2 - * #i = 0, 1, 2, 3, 4, 5, 6, 7# - */ - data_out[@i@] = @to@(@from@(data0[@i@]) * - @from@(data1[@i@]) + - @from@(data_out[@i@])); -/**end repeat2**/ -#endif - data0 += 8; - data1 += 8; - data_out += 8; +#ifndef NPY_DISABLE_OPTIMIZATION + for (; count >= 4; count -= 4, data0 += 4, data1 += 4, data_out += 4) { + /**begin repeat2 + * #i = 0, 1, 2, 3# + */ + const @type@ a@i@ = @from@(data0[@i@]); + const @type@ b@i@ = @from@(data1[@i@]); + const @type@ c@i@ = @from@(data_out[@i@]); + /**end repeat2**/ + /**begin repeat2 + * #i = 0, 1, 2, 3# + */ + const @type@ abc@i@ = a@i@ * b@i@ + c@i@; + /**end repeat2**/ + /**begin repeat2 + * #i = 0, 1, 2, 3# + */ + data_out[@i@] = @to@(abc@i@); + /**end repeat2**/ } +#endif // !NPY_DISABLE_OPTIMIZATION + for (; count > 0; --count, ++data0, ++data1, ++data_out) { + const @type@ a = @from@(*data0); + const @type@ b = @from@(*data1); + const @type@ c = @from@(*data_out); + *data_out = @to@(a * b + c); + } +#endif // NPYV check for @type@ - /* Finish off the loop */ - goto finish_after_unrolled_loop; } /* Some extra specializations for the two operand case */ @@ -608,7 +589,7 @@ finish_after_unrolled_loop: goto finish_after_unrolled_loop; } -static void +static NPY_GCC_OPT_3 void @name@_sum_of_products_contig_contig_outstride0_two(int nop, char **dataptr, npy_intp const *NPY_UNUSED(strides), npy_intp count) { @@ -616,156 +597,60 @@ static void @type@ *data1 = (@type@ *)dataptr[1]; @temptype@ accum = 0; -#if EINSUM_USE_SSE1 && @float32@ - __m128 a, accum_sse = _mm_setzero_ps(); -#elif EINSUM_USE_SSE2 && @float64@ - __m128d a, accum_sse = _mm_setzero_pd(); -#endif - NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_contig_outstride0_two (%d)\n", (int)count); - -/* This is placed before the main loop to make small counts faster */ -finish_after_unrolled_loop: - switch (count) { -/**begin repeat2 - * #i = 6, 5, 4, 3, 2, 1, 0# - */ - case @i@+1: - accum += @from@(data0[@i@]) * @from@(data1[@i@]); -/**end repeat2**/ - case 0: - *(@type@ *)dataptr[2] = @to@(@from@(*(@type@ *)dataptr[2]) + accum); - return; - } - -#if EINSUM_USE_SSE1 && @float32@ +#if @NPYV_CHK@ // NPYV check for @type@ /* Use aligned instructions if possible */ - if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1)) { - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - - _mm_prefetch(data0 + 512, _MM_HINT_T0); - _mm_prefetch(data1 + 512, _MM_HINT_T0); - -/**begin repeat2 - * #i = 0, 4# - */ - /* - * NOTE: This accumulation changes the order, so will likely - * produce slightly different results. + const int is_aligned = EINSUM_IS_ALIGNED(data0) && EINSUM_IS_ALIGNED(data1); + const int vstep = npyv_nlanes_@sfx@; + npyv_@sfx@ vaccum = npyv_zero_@sfx@(); + + /**begin repeat2 + * #cond = if(is_aligned), else# + * #ld = loada, load# + * #st = storea, store# + */ + @cond@ { + const npy_intp vstepx4 = vstep * 4; + for (; count >= vstepx4; count -= vstepx4, data0 += vstepx4, data1 += vstepx4) { + /**begin repeat3 + * #i = 0, 1, 2, 3# */ - a = _mm_mul_ps(_mm_load_ps(data0+@i@), _mm_load_ps(data1+@i@)); - accum_sse = _mm_add_ps(accum_sse, a); -/**end repeat2**/ - data0 += 8; - data1 += 8; + npyv_@sfx@ a@i@ = npyv_@ld@_@sfx@(data0 + vstep * @i@); + npyv_@sfx@ b@i@ = npyv_@ld@_@sfx@(data1 + vstep * @i@); + /**end repeat3**/ + npyv_@sfx@ ab3 = npyv_muladd_@sfx@(a3, b3, vaccum); + npyv_@sfx@ ab2 = npyv_muladd_@sfx@(a2, b2, ab3); + npyv_@sfx@ ab1 = npyv_muladd_@sfx@(a1, b1, ab2); + vaccum = npyv_muladd_@sfx@(a0, b0, ab1); } - - /* Add the four SSE values and put in accum */ - a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); - accum_sse = _mm_add_ps(a, accum_sse); - a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); - accum_sse = _mm_add_ps(a, accum_sse); - _mm_store_ss(&accum, accum_sse); - - /* Finish off the loop */ - goto finish_after_unrolled_loop; } -#elif EINSUM_USE_SSE2 && @float64@ - /* Use aligned instructions if possible */ - if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1)) { - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - - _mm_prefetch(data0 + 512, _MM_HINT_T0); - _mm_prefetch(data1 + 512, _MM_HINT_T0); - -/**begin repeat2 - * #i = 0, 2, 4, 6# - */ - /* - * NOTE: This accumulation changes the order, so will likely - * produce slightly different results. - */ - a = _mm_mul_pd(_mm_load_pd(data0+@i@), _mm_load_pd(data1+@i@)); - accum_sse = _mm_add_pd(accum_sse, a); -/**end repeat2**/ - data0 += 8; - data1 += 8; - } - - /* Add the two SSE2 values and put in accum */ - a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); - accum_sse = _mm_add_pd(a, accum_sse); - _mm_store_sd(&accum, accum_sse); - - /* Finish off the loop */ - goto finish_after_unrolled_loop; + /**end repeat2**/ + for (; count > 0; count -= vstep, data0 += vstep, data1 += vstep) { + npyv_@sfx@ a = npyv_load_tillz_@sfx@(data0, count); + npyv_@sfx@ b = npyv_load_tillz_@sfx@(data1, count); + vaccum = npyv_muladd_@sfx@(a, b, vaccum); } -#endif - - /* Unroll the loop by 8 */ - while (count >= 8) { - count -= 8; - -#if EINSUM_USE_SSE1 && @float32@ - _mm_prefetch(data0 + 512, _MM_HINT_T0); - _mm_prefetch(data1 + 512, _MM_HINT_T0); - -/**begin repeat2 - * #i = 0, 4# - */ - /* - * NOTE: This accumulation changes the order, so will likely - * produce slightly different results. - */ - a = _mm_mul_ps(_mm_loadu_ps(data0+@i@), _mm_loadu_ps(data1+@i@)); - accum_sse = _mm_add_ps(accum_sse, a); -/**end repeat2**/ -#elif EINSUM_USE_SSE2 && @float64@ - _mm_prefetch(data0 + 512, _MM_HINT_T0); - _mm_prefetch(data1 + 512, _MM_HINT_T0); - -/**begin repeat2 - * #i = 0, 2, 4, 6# - */ - /* - * NOTE: This accumulation changes the order, so will likely - * produce slightly different results. - */ - a = _mm_mul_pd(_mm_loadu_pd(data0+@i@), _mm_loadu_pd(data1+@i@)); - accum_sse = _mm_add_pd(accum_sse, a); -/**end repeat2**/ + accum = npyv_sum_@sfx@(vaccum); + npyv_cleanup(); #else -/**begin repeat2 - * #i = 0, 1, 2, 3, 4, 5, 6, 7# - */ - accum += @from@(data0[@i@]) * @from@(data1[@i@]); -/**end repeat2**/ -#endif - data0 += 8; - data1 += 8; +#ifndef NPY_DISABLE_OPTIMIZATION + for (; count >= 4; count -= 4, data0 += 4, data1 += 4) { + /**begin repeat2 + * #i = 0, 1, 2, 3# + */ + const @type@ ab@i@ = @from@(data0[@i@]) * @from@(data1[@i@]); + /**end repeat2**/ + accum += ab0 + ab1 + ab2 + ab3; } - -#if EINSUM_USE_SSE1 && @float32@ - /* Add the four SSE values and put in accum */ - a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); - accum_sse = _mm_add_ps(a, accum_sse); - a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); - accum_sse = _mm_add_ps(a, accum_sse); - _mm_store_ss(&accum, accum_sse); -#elif EINSUM_USE_SSE2 && @float64@ - /* Add the two SSE2 values and put in accum */ - a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); - accum_sse = _mm_add_pd(a, accum_sse); - _mm_store_sd(&accum, accum_sse); -#endif - - /* Finish off the loop */ - goto finish_after_unrolled_loop; +#endif // !NPY_DISABLE_OPTIMIZATION + for (; count > 0; --count, ++data0, ++data1) { + const @type@ a = @from@(*data0); + const @type@ b = @from@(*data1); + accum += a * b; + } +#endif // NPYV check for @type@ + *(@type@ *)dataptr[2] = @to@(@from@(*(@type@ *)dataptr[2]) + accum); } static void diff --git a/numpy/core/src/multiarray/multiarraymodule.c b/numpy/core/src/multiarray/multiarraymodule.c index 79956863a..870b633ed 100644 --- a/numpy/core/src/multiarray/multiarraymodule.c +++ b/numpy/core/src/multiarray/multiarraymodule.c @@ -2892,6 +2892,7 @@ array_arange(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kws) { if (args == NULL || PyTuple_GET_SIZE(args) == 0){ PyErr_SetString(PyExc_TypeError, "arange() requires stop to be specified."); + Py_XDECREF(typecode); return NULL; } } @@ -4084,6 +4085,42 @@ normalize_axis_index(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) } +static PyObject * +_reload_guard(PyObject *NPY_UNUSED(self)) { + static int initialized = 0; + +#if !defined(PYPY_VERSION) + if (PyThreadState_Get()->interp != PyInterpreterState_Main()) { + if (PyErr_WarnEx(PyExc_UserWarning, + "NumPy was imported from a Python sub-interpreter but " + "NumPy does not properly support sub-interpreters. " + "This will likely work for most users but might cause hard to " + "track down issues or subtle bugs. " + "A common user of the rare sub-interpreter feature is wsgi " + "which also allows single-interpreter mode.\n" + "Improvements in the case of bugs are welcome, but is not " + "on the NumPy roadmap, and full support may require " + "significant effort to achieve.", 2) < 0) { + return NULL; + } + /* No need to give the other warning in a sub-interpreter as well... */ + initialized = 1; + Py_RETURN_NONE; + } +#endif + if (initialized) { + if (PyErr_WarnEx(PyExc_UserWarning, + "The NumPy module was reloaded (imported a second time). " + "This can in some cases result in small but subtle issues " + "and is discouraged.", 2) < 0) { + return NULL; + } + } + initialized = 1; + Py_RETURN_NONE; +} + + static struct PyMethodDef array_module_methods[] = { {"_get_implementing_args", (PyCFunction)array__get_implementing_args, @@ -4275,6 +4312,9 @@ static struct PyMethodDef array_module_methods[] = { METH_VARARGS, NULL}, {"_set_madvise_hugepage", (PyCFunction)_set_madvise_hugepage, METH_O, NULL}, + {"_reload_guard", (PyCFunction)_reload_guard, + METH_NOARGS, + "Give a warning on reload and big warning in sub-interpreters."}, {NULL, NULL, 0, NULL} /* sentinel */ }; diff --git a/numpy/core/src/umath/simd.inc.src b/numpy/core/src/umath/simd.inc.src index 53bb4e059..3d4e6de87 100644 --- a/numpy/core/src/umath/simd.inc.src +++ b/numpy/core/src/umath/simd.inc.src @@ -1002,7 +1002,11 @@ fma_get_exponent(__m256 x) __m256 denormal_mask = _mm256_cmp_ps(x, _mm256_set1_ps(FLT_MIN), _CMP_LT_OQ); __m256 normal_mask = _mm256_cmp_ps(x, _mm256_set1_ps(FLT_MIN), _CMP_GE_OQ); - __m256 temp1 = _mm256_blendv_ps(x, _mm256_set1_ps(0.0f), normal_mask); + /* + * It is necessary for temp1 to be volatile, a bug in clang optimizes it out which leads + * to an overflow warning in some cases. See https://github.com/numpy/numpy/issues/18005 + */ + volatile __m256 temp1 = _mm256_blendv_ps(x, _mm256_set1_ps(0.0f), normal_mask); __m256 temp = _mm256_mul_ps(temp1, two_power_100); x = _mm256_blendv_ps(x, temp, denormal_mask); @@ -1029,7 +1033,11 @@ fma_get_mantissa(__m256 x) __m256 denormal_mask = _mm256_cmp_ps(x, _mm256_set1_ps(FLT_MIN), _CMP_LT_OQ); __m256 normal_mask = _mm256_cmp_ps(x, _mm256_set1_ps(FLT_MIN), _CMP_GE_OQ); - __m256 temp1 = _mm256_blendv_ps(x, _mm256_set1_ps(0.0f), normal_mask); + /* + * It is necessary for temp1 to be volatile, a bug in clang optimizes it out which leads + * to an overflow warning in some cases. See https://github.com/numpy/numpy/issues/18005 + */ + volatile __m256 temp1 = _mm256_blendv_ps(x, _mm256_set1_ps(0.0f), normal_mask); __m256 temp = _mm256_mul_ps(temp1, two_power_100); x = _mm256_blendv_ps(x, temp, denormal_mask); diff --git a/numpy/core/tests/test_array_coercion.py b/numpy/core/tests/test_array_coercion.py index 78def9360..08b32dfcc 100644 --- a/numpy/core/tests/test_array_coercion.py +++ b/numpy/core/tests/test_array_coercion.py @@ -38,8 +38,18 @@ def arraylikes(): yield subclass + class _SequenceLike(): + # We are giving a warning that array-like's were also expected to be + # sequence-like in `np.array([array_like])`, this can be removed + # when the deprecation exired (started NumPy 1.20) + def __len__(self): + raise TypeError + + def __getitem__(self): + raise TypeError + # Array-interface - class ArrayDunder: + class ArrayDunder(_SequenceLike): def __init__(self, a): self.a = a @@ -52,7 +62,7 @@ def arraylikes(): yield param(memoryview, id="memoryview") # Array-interface - class ArrayInterface: + class ArrayInterface(_SequenceLike): def __init__(self, a): self.a = a # need to hold on to keep interface valid self.__array_interface__ = a.__array_interface__ @@ -60,7 +70,7 @@ def arraylikes(): yield param(ArrayInterface, id="__array_interface__") # Array-Struct - class ArrayStruct: + class ArrayStruct(_SequenceLike): def __init__(self, a): self.a = a # need to hold on to keep struct valid self.__array_struct__ = a.__array_struct__ @@ -689,3 +699,33 @@ class TestArrayLikes: np.array(arr) with pytest.raises(MemoryError): np.array([arr]) + + @pytest.mark.parametrize("attribute", + ["__array_interface__", "__array__", "__array_struct__"]) + def test_bad_array_like_attributes(self, attribute): + # Check that errors during attribute retrieval are raised unless + # they are Attribute errors. + + class BadInterface: + def __getattr__(self, attr): + if attr == attribute: + raise RuntimeError + super().__getattr__(attr) + + with pytest.raises(RuntimeError): + np.array(BadInterface()) + + @pytest.mark.parametrize("error", [RecursionError, MemoryError]) + def test_bad_array_like_bad_length(self, error): + # RecursionError and MemoryError are considered "critical" in + # sequences. We could expand this more generally though. (NumPy 1.20) + class BadSequence: + def __len__(self): + raise error + def __getitem__(self): + # must have getitem to be a Sequence + return 1 + + with pytest.raises(error): + np.array(BadSequence()) + diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index a67fe62c3..ed238da9f 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -773,6 +773,92 @@ class TestDeprecateSubarrayDTypeDuringArrayCoercion(_DeprecationTestCase): self.assert_deprecated(check) +class TestFutureWarningArrayLikeNotIterable(_DeprecationTestCase): + # Deprecated 2020-12-09, NumPy 1.20 + warning_cls = FutureWarning + message = "The input object of type.*but not a sequence" + + @pytest.mark.parametrize("protocol", + ["__array__", "__array_interface__", "__array_struct__"]) + def test_deprecated(self, protocol): + """Test that these objects give a warning since they are not 0-D, + not coerced at the top level `np.array(obj)`, but nested, and do + *not* define the sequence protocol. + + NOTE: Tests for the versions including __len__ and __getitem__ exist + in `test_array_coercion.py` and they can be modified or ammended + when this deprecation expired. + """ + blueprint = np.arange(10) + MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)}) + self.assert_deprecated(lambda: np.array([MyArr()], dtype=object)) + + @pytest.mark.parametrize("protocol", + ["__array__", "__array_interface__", "__array_struct__"]) + def test_0d_not_deprecated(self, protocol): + # 0-D always worked (albeit it would use __float__ or similar for the + # conversion, which may not happen anymore) + blueprint = np.array(1.) + MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)}) + myarr = MyArr() + + self.assert_not_deprecated(lambda: np.array([myarr], dtype=object)) + res = np.array([myarr], dtype=object) + expected = np.empty(1, dtype=object) + expected[0] = myarr + assert_array_equal(res, expected) + + @pytest.mark.parametrize("protocol", + ["__array__", "__array_interface__", "__array_struct__"]) + def test_unnested_not_deprecated(self, protocol): + blueprint = np.arange(10) + MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol)}) + myarr = MyArr() + + self.assert_not_deprecated(lambda: np.array(myarr)) + res = np.array(myarr) + assert_array_equal(res, blueprint) + + @pytest.mark.parametrize("protocol", + ["__array__", "__array_interface__", "__array_struct__"]) + def test_strange_dtype_handling(self, protocol): + """The old code would actually use the dtype from the array, but + then end up not using the array (for dimension discovery) + """ + blueprint = np.arange(10).astype("f4") + MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol), + "__float__": lambda _: 0.5}) + myarr = MyArr() + + # Make sure we warn (and capture the FutureWarning) + with pytest.warns(FutureWarning, match=self.message): + res = np.array([[myarr]]) + + assert res.shape == (1, 1) + assert res.dtype == "f4" + assert res[0, 0] == 0.5 + + @pytest.mark.parametrize("protocol", + ["__array__", "__array_interface__", "__array_struct__"]) + def test_assignment_not_deprecated(self, protocol): + # If the result is dtype=object we do not unpack a nested array or + # array-like, if it is nested at exactly the right depth. + # NOTE: We actually do still call __array__, etc. but ignore the result + # in the end. For `dtype=object` we could optimize that away. + blueprint = np.arange(10).astype("f4") + MyArr = type("MyArr", (), {protocol: getattr(blueprint, protocol), + "__float__": lambda _: 0.5}) + myarr = MyArr() + + res = np.empty(3, dtype=object) + def set(): + res[:] = [myarr, myarr, myarr] + self.assert_not_deprecated(set) + assert res[0] is myarr + assert res[1] is myarr + assert res[2] is myarr + + class TestDeprecatedUnpickleObjectScalar(_DeprecationTestCase): # Deprecated 2020-11-24, NumPy 1.20 """ diff --git a/numpy/core/tests/test_overrides.py b/numpy/core/tests/test_overrides.py index df0ea330c..6862fca03 100644 --- a/numpy/core/tests/test_overrides.py +++ b/numpy/core/tests/test_overrides.py @@ -430,25 +430,27 @@ class TestNumPyFunctions: class TestArrayLike: + def setup(self): + class MyArray(): + def __init__(self, function=None): + self.function = function - class MyArray(): - - def __init__(self, function=None): - self.function = function + def __array_function__(self, func, types, args, kwargs): + try: + my_func = getattr(self, func.__name__) + except AttributeError: + return NotImplemented + return my_func(*args, **kwargs) - def __array_function__(self, func, types, args, kwargs): - try: - my_func = getattr(TestArrayLike.MyArray, func.__name__) - except AttributeError: - return NotImplemented - return my_func(*args, **kwargs) + self.MyArray = MyArray - class MyNoArrayFunctionArray(): + class MyNoArrayFunctionArray(): + def __init__(self, function=None): + self.function = function - def __init__(self, function=None): - self.function = function + self.MyNoArrayFunctionArray = MyNoArrayFunctionArray - def add_method(name, arr_class, enable_value_error=False): + def add_method(self, name, arr_class, enable_value_error=False): def _definition(*args, **kwargs): # Check that `like=` isn't propagated downstream assert 'like' not in kwargs @@ -464,9 +466,9 @@ class TestArrayLike: @requires_array_function def test_array_like_not_implemented(self): - TestArrayLike.add_method('array', TestArrayLike.MyArray) + self.add_method('array', self.MyArray) - ref = TestArrayLike.MyArray.array() + ref = self.MyArray.array() with assert_raises_regex(TypeError, 'no implementation found'): array_like = np.asarray(1, like=ref) @@ -497,15 +499,15 @@ class TestArrayLike: @pytest.mark.parametrize('numpy_ref', [True, False]) @requires_array_function def test_array_like(self, function, args, kwargs, numpy_ref): - TestArrayLike.add_method('array', TestArrayLike.MyArray) - TestArrayLike.add_method(function, TestArrayLike.MyArray) + self.add_method('array', self.MyArray) + self.add_method(function, self.MyArray) np_func = getattr(np, function) - my_func = getattr(TestArrayLike.MyArray, function) + my_func = getattr(self.MyArray, function) if numpy_ref is True: ref = np.array(1) else: - ref = TestArrayLike.MyArray.array() + ref = self.MyArray.array() like_args = tuple(a() if callable(a) else a for a in args) array_like = np_func(*like_args, **kwargs, like=ref) @@ -523,20 +525,20 @@ class TestArrayLike: assert_equal(array_like, np_arr) else: - assert type(array_like) is TestArrayLike.MyArray + assert type(array_like) is self.MyArray assert array_like.function is my_func @pytest.mark.parametrize('function, args, kwargs', _array_tests) - @pytest.mark.parametrize('ref', [1, [1], MyNoArrayFunctionArray]) + @pytest.mark.parametrize('ref', [1, [1], "MyNoArrayFunctionArray"]) @requires_array_function def test_no_array_function_like(self, function, args, kwargs, ref): - TestArrayLike.add_method('array', TestArrayLike.MyNoArrayFunctionArray) - TestArrayLike.add_method(function, TestArrayLike.MyNoArrayFunctionArray) + self.add_method('array', self.MyNoArrayFunctionArray) + self.add_method(function, self.MyNoArrayFunctionArray) np_func = getattr(np, function) # Instantiate ref if it's the MyNoArrayFunctionArray class - if ref is TestArrayLike.MyNoArrayFunctionArray: - ref = ref.array() + if ref == "MyNoArrayFunctionArray": + ref = self.MyNoArrayFunctionArray.array() like_args = tuple(a() if callable(a) else a for a in args) @@ -546,13 +548,13 @@ class TestArrayLike: @pytest.mark.parametrize('numpy_ref', [True, False]) def test_array_like_fromfile(self, numpy_ref): - TestArrayLike.add_method('array', TestArrayLike.MyArray) - TestArrayLike.add_method("fromfile", TestArrayLike.MyArray) + self.add_method('array', self.MyArray) + self.add_method("fromfile", self.MyArray) if numpy_ref is True: ref = np.array(1) else: - ref = TestArrayLike.MyArray.array() + ref = self.MyArray.array() data = np.random.random(5) @@ -566,18 +568,14 @@ class TestArrayLike: assert_equal(np_res, data) assert_equal(array_like, np_res) else: - assert type(array_like) is TestArrayLike.MyArray - assert array_like.function is TestArrayLike.MyArray.fromfile + assert type(array_like) is self.MyArray + assert array_like.function is self.MyArray.fromfile @requires_array_function def test_exception_handling(self): - TestArrayLike.add_method( - 'array', - TestArrayLike.MyArray, - enable_value_error=True, - ) + self.add_method('array', self.MyArray, enable_value_error=True) - ref = TestArrayLike.MyArray.array() + ref = self.MyArray.array() with assert_raises(ValueError): np.array(1, value_error=True, like=ref) diff --git a/numpy/core/tests/test_simd.py b/numpy/core/tests/test_simd.py index 13e8d5ede..196003cdd 100644 --- a/numpy/core/tests/test_simd.py +++ b/numpy/core/tests/test_simd.py @@ -92,6 +92,32 @@ class _Test_Utility: v = self.npyv.setall_u32(0x7fc00000) return self.npyv.reinterpret_f32_u32(v)[0] +class _SIMD_BOOL(_Test_Utility): + """ + To test all boolean vector types at once + """ + def _data(self, start=None, count=None, reverse=False): + nlanes = getattr(self.npyv, "nlanes_u" + self.sfx[1:]) + true_mask = self._true_mask() + rng = range(nlanes) + if reverse: + rng = reversed(rng) + return [true_mask if x % 2 else 0 for x in rng] + + def _load_b(self, data): + len_str = self.sfx[1:] + load = getattr(self.npyv, "load_u" + len_str) + cvt = getattr(self.npyv, f"cvt_b{len_str}_u{len_str}") + return cvt(load(data)) + + def test_tobits(self): + data2bits = lambda data: sum([int(x != 0) << i for i, x in enumerate(data, 0)]) + for data in (self._data(), self._data(reverse=True)): + vdata = self._load_b(data) + data_bits = data2bits(data) + tobits = bin(self.tobits(vdata)) + assert tobits == bin(data_bits) + class _SIMD_INT(_Test_Utility): """ To test all integer vector types at once @@ -459,6 +485,18 @@ class _SIMD_ALL(_Test_Utility): vzip = self.zip(vdata_a, vdata_b) assert vzip == (data_zipl, data_ziph) + def test_reorder_rev64(self): + # Reverse elements of each 64-bit lane + ssize = self._scalar_size() + if ssize == 64: + return + data_rev64 = [ + y for x in range(0, self.nlanes, 64//ssize) + for y in reversed(range(x, x + 64//ssize)) + ] + rev64 = self.rev64(self.load(range(self.nlanes))) + assert rev64 == data_rev64 + def test_operators_comparison(self): if self._is_fp(): data_a = self._data() @@ -594,10 +632,12 @@ class _SIMD_ALL(_Test_Utility): vsum = self.sum(vdata) assert vsum == data_sum +bool_sfx = ("b8", "b16", "b32", "b64") int_sfx = ("u8", "s8", "u16", "s16", "u32", "s32", "u64", "s64") fp_sfx = ("f32", "f64") all_sfx = int_sfx + fp_sfx tests_registry = { + bool_sfx: _SIMD_BOOL, int_sfx : _SIMD_INT, fp_sfx : _SIMD_FP, all_sfx : _SIMD_ALL diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 8162e52bd..bc72aa862 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -926,6 +926,11 @@ class TestSpecialFloats: assert_raises(FloatingPointError, np.log, np.float32(-np.inf)) assert_raises(FloatingPointError, np.log, np.float32(-1.0)) + # See https://github.com/numpy/numpy/issues/18005 + with assert_no_warnings(): + a = np.array(1e9, dtype='float32') + np.log(a) + def test_sincos_values(self): with np.errstate(all='ignore'): x = [np.nan, np.nan, np.nan, np.nan] diff --git a/numpy/distutils/ccompiler_opt.py b/numpy/distutils/ccompiler_opt.py index 3eba6e32a..20dbb5c00 100644 --- a/numpy/distutils/ccompiler_opt.py +++ b/numpy/distutils/ccompiler_opt.py @@ -276,7 +276,7 @@ class _Config: ), # IBM/Power ## Power7/ISA 2.06 - VSX = dict(interest=1, headers="altivec.h"), + VSX = dict(interest=1, headers="altivec.h", extra_checks="VSX_ASM"), ## Power8/ISA 2.07 VSX2 = dict(interest=2, implies="VSX", implies_detect=False), ## Power9/ISA 3.00 diff --git a/numpy/distutils/checks/extra_vsx_asm.c b/numpy/distutils/checks/extra_vsx_asm.c new file mode 100644 index 000000000..b73a6f438 --- /dev/null +++ b/numpy/distutils/checks/extra_vsx_asm.c @@ -0,0 +1,36 @@ +/** + * Testing ASM VSX register number fixer '%x<n>' + * + * old versions of CLANG doesn't support %x<n> in the inline asm template + * which fixes register number when using any of the register constraints wa, wd, wf. + * + * xref: + * - https://bugs.llvm.org/show_bug.cgi?id=31837 + * - https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html + */ +#ifndef __VSX__ + #error "VSX is not supported" +#endif +#include <altivec.h> + +#if (defined(__GNUC__) && !defined(vec_xl)) || (defined(__clang__) && !defined(__IBMC__)) + #define vsx_ld vec_vsx_ld + #define vsx_st vec_vsx_st +#else + #define vsx_ld vec_xl + #define vsx_st vec_xst +#endif + +int main(void) +{ + float z4[] = {0, 0, 0, 0}; + signed int zout[] = {0, 0, 0, 0}; + + __vector float vz4 = vsx_ld(0, z4); + __vector signed int asm_ret = vsx_ld(0, zout); + + __asm__ ("xvcvspsxws %x0,%x1" : "=wa" (vz4) : "wa" (asm_ret)); + + vsx_st(asm_ret, 0, zout); + return zout[0]; +} diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index 0d9d769c2..68d1501ee 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -126,7 +126,7 @@ class GnuFCompiler(FCompiler): target = '10.9' s = f'Env. variable MACOSX_DEPLOYMENT_TARGET set to {target}' warnings.warn(s, stacklevel=2) - os.environ['MACOSX_DEPLOYMENT_TARGET'] = target + os.environ['MACOSX_DEPLOYMENT_TARGET'] = str(target) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append("-shared") diff --git a/numpy/distutils/fcompiler/nag.py b/numpy/distutils/fcompiler/nag.py index 908e724e6..7df8ffe2c 100644 --- a/numpy/distutils/fcompiler/nag.py +++ b/numpy/distutils/fcompiler/nag.py @@ -19,7 +19,7 @@ class BaseNAGFCompiler(FCompiler): def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): - return [''] + return [] class NAGFCompiler(BaseNAGFCompiler): diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index a8e19d52c..d3073ab2d 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -1968,6 +1968,13 @@ class Configuration: version = getattr(version_module, a, None) if version is not None: break + + # Try if versioneer module + try: + version = version_module.get_versions()['version'] + except AttributeError: + version = None + if version is not None: break diff --git a/numpy/fft/_pocketfft.py b/numpy/fft/_pocketfft.py index 83ac86036..bf0e60b6d 100644 --- a/numpy/fft/_pocketfft.py +++ b/numpy/fft/_pocketfft.py @@ -160,7 +160,7 @@ def fft(a, n=None, axis=-1, norm=None): Raises ------ IndexError - if `axes` is larger than the last axis of `a`. + If `axis` is not a valid axis of `a`. See Also -------- @@ -272,7 +272,7 @@ def ifft(a, n=None, axis=-1, norm=None): Raises ------ IndexError - If `axes` is larger than the last axis of `a`. + If `axis` is not a valid axis of `a`. See Also -------- @@ -358,7 +358,7 @@ def rfft(a, n=None, axis=-1, norm=None): Raises ------ IndexError - If `axis` is larger than the last axis of `a`. + If `axis` is not a valid axis of `a`. See Also -------- @@ -461,7 +461,7 @@ def irfft(a, n=None, axis=-1, norm=None): Raises ------ IndexError - If `axis` is larger than the last axis of `a`. + If `axis` is not a valid axis of `a`. See Also -------- @@ -556,7 +556,7 @@ def hfft(a, n=None, axis=-1, norm=None): Raises ------ IndexError - If `axis` is larger than the last axis of `a`. + If `axis` is not a valid axis of `a`. See also -------- @@ -1242,6 +1242,15 @@ def rfft2(a, s=None, axes=(-2, -1), norm=None): This is really just `rfftn` with different default behavior. For more details see `rfftn`. + Examples + -------- + >>> a = np.mgrid[:5, :5][0] + >>> np.fft.rfft2(a) + array([[ 50. +0.j , 0. +0.j , 0. +0.j ], + [-12.5+17.20477401j, 0. +0.j , 0. +0.j ], + [-12.5 +4.0614962j , 0. +0.j , 0. +0.j ], + [-12.5 -4.0614962j , 0. +0.j , 0. +0.j ], + [-12.5-17.20477401j, 0. +0.j , 0. +0.j ]]) """ return rfftn(a, s, axes, norm) @@ -1399,5 +1408,15 @@ def irfft2(a, s=None, axes=(-2, -1), norm=None): This is really `irfftn` with different defaults. For more details see `irfftn`. + Examples + -------- + >>> a = np.mgrid[:5, :5][0] + >>> A = np.fft.rfft2(a) + >>> np.fft.irfft2(A, s=a.shape) + array([[0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1.], + [2., 2., 2., 2., 2.], + [3., 3., 3., 3., 3.], + [4., 4., 4., 4., 4.]]) """ return irfftn(a, s, axes, norm) diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index af8e28e42..efebb5fb7 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -539,10 +539,11 @@ def _savez_dispatcher(file, *args, **kwds): def savez(file, *args, **kwds): """Save several arrays into a single file in uncompressed ``.npz`` format. - If arguments are passed in with no keywords, the corresponding variable - names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword - arguments are given, the corresponding variable names, in the ``.npz`` - file will match the keyword names. + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., ``savez(fn, + x, y)``, their names will be `arr_0`, `arr_1`, etc. Parameters ---------- @@ -552,13 +553,12 @@ def savez(file, *args, **kwds): ``.npz`` extension will be appended to the filename if it is not already there. args : Arguments, optional - Arrays to save to the file. Since it is not possible for Python to - know the names of the arrays outside `savez`, the arrays will be saved - with names "arr_0", "arr_1", and so on. These arguments can be any - expression. + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. kwds : Keyword arguments, optional - Arrays to save to the file. Arrays will be saved in the file with the - keyword names. + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. Returns ------- @@ -613,6 +613,7 @@ def savez(file, *args, **kwds): ['x', 'y'] >>> npzfile['x'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + """ _savez(file, args, kwds, False) @@ -627,9 +628,11 @@ def savez_compressed(file, *args, **kwds): """ Save several arrays into a single file in compressed ``.npz`` format. - If keyword arguments are given, then filenames are taken from the keywords. - If arguments are passed in with no keywords, then stored filenames are - arr_0, arr_1, etc. + Provide arrays as keyword arguments to store them under the + corresponding name in the output file: ``savez(fn, x=x, y=y)``. + + If arrays are specified as positional arguments, i.e., ``savez(fn, + x, y)``, their names will be `arr_0`, `arr_1`, etc. Parameters ---------- @@ -639,13 +642,12 @@ def savez_compressed(file, *args, **kwds): ``.npz`` extension will be appended to the filename if it is not already there. args : Arguments, optional - Arrays to save to the file. Since it is not possible for Python to - know the names of the arrays outside `savez`, the arrays will be saved - with names "arr_0", "arr_1", and so on. These arguments can be any - expression. + Arrays to save to the file. Please use keyword arguments (see + `kwds` below) to assign names to arrays. Arrays specified as + args will be named "arr_0", "arr_1", and so on. kwds : Keyword arguments, optional - Arrays to save to the file. Arrays will be saved in the file with the - keyword names. + Arrays to save to the file. Each array will be saved to the + output file with its corresponding keyword name. Returns ------- diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 0fd9bbd79..ea966ffa3 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -708,8 +708,8 @@ def polyval(p, x): ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]`` - If `x` is a sequence, then `p(x)` is returned for each element of `x`. - If `x` is another polynomial then the composite polynomial `p(x(t))` + If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``. + If `x` is another polynomial then the composite polynomial ``p(x(t))`` is returned. Parameters diff --git a/numpy/lib/scimath.py b/numpy/lib/scimath.py index 2b0d38c37..ed9ffd295 100644 --- a/numpy/lib/scimath.py +++ b/numpy/lib/scimath.py @@ -572,10 +572,10 @@ def arctanh(x): Compute the inverse hyperbolic tangent of `x`. Return the "principal value" (for a description of this, see - `numpy.arctanh`) of `arctanh(x)`. For real `x` such that - `abs(x) < 1`, this is a real number. If `abs(x) > 1`, or if `x` is + `numpy.arctanh`) of ``arctanh(x)``. For real `x` such that + ``abs(x) < 1``, this is a real number. If `abs(x) > 1`, or if `x` is complex, the result is complex. Finally, `x = 1` returns``inf`` and - `x=-1` returns ``-inf``. + ``x=-1`` returns ``-inf``. Parameters ---------- @@ -597,7 +597,7 @@ def arctanh(x): ----- For an arctanh() that returns ``NAN`` when real `x` is not in the interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does - return +/-inf for `x = +/-1`). + return +/-inf for ``x = +/-1``). Examples -------- diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index cbc4641d8..f0596444e 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1088,8 +1088,8 @@ def kron(a, b): ----- The function assumes that the number of dimensions of `a` and `b` are the same, if necessary prepending the smallest with ones. - If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`, - the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`. + If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``, + the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``. The elements are products of elements from `a` and `b`, organized explicitly by:: diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 33951b92a..8a877ae69 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -4,7 +4,7 @@ import pytest from numpy.core import arange from numpy.testing import assert_, assert_equal, assert_raises_regex -from numpy.lib import deprecate +from numpy.lib import deprecate, deprecate_with_doc import numpy.lib.utils as utils from io import StringIO @@ -60,6 +60,11 @@ def old_func6(self, x): new_func6 = deprecate(old_func6) +@deprecate_with_doc(msg="Rather use new_func7") +def old_func7(self,x): + return x + + def test_deprecate_decorator(): assert_('deprecated' in old_func.__doc__) @@ -73,6 +78,10 @@ def test_deprecate_fn(): assert_('new_func3' in new_func3.__doc__) +def test_deprecate_with_doc_decorator_message(): + assert_('Rather use new_func7' in old_func7.__doc__) + + @pytest.mark.skipif(sys.flags.optimize == 2, reason="-OO discards docstrings") @pytest.mark.parametrize('old_func, new_func', [ (old_func4, new_func4), diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 5447608bf..f7e176cf3 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -193,7 +193,32 @@ def deprecate(*args, **kwargs): else: return _Deprecate(*args, **kwargs) -deprecate_with_doc = lambda msg: _Deprecate(message=msg) + +def deprecate_with_doc(msg): + """ + Deprecates a function and includes the deprecation in its docstring. + + This function is used as a decorator. It returns an object that can be + used to issue a DeprecationWarning, by passing the to-be decorated + function as argument, this adds warning to the to-be decorated function's + docstring and returns the new function object. + + See Also + -------- + deprecate : Decorate a function such that it issues a `DeprecationWarning` + + Parameters + ---------- + msg : str + Additional explanation of the deprecation. Displayed in the + docstring after the warning. + + Returns + ------- + obj : object + + """ + return _Deprecate(message=msg) #-------------------------------------------- diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 4fb7d8c28..d6af22337 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -5439,7 +5439,7 @@ class MaskedArray(ndarray): When the array contains unmasked values at the same extremes of the datatype, the ordering of these values and the masked values is undefined. - fill_value : {var}, optional + fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. @@ -5497,7 +5497,7 @@ class MaskedArray(ndarray): axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis - fill_value : {var}, optional + fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. out : {None, array}, optional @@ -5543,7 +5543,7 @@ class MaskedArray(ndarray): axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis - fill_value : {var}, optional + fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional @@ -5594,7 +5594,7 @@ class MaskedArray(ndarray): When the array contains unmasked values sorting at the same extremes of the datatype, the ordering of these values and the masked values is undefined. - fill_value : {var}, optional + fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. @@ -5665,7 +5665,7 @@ class MaskedArray(ndarray): out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. - fill_value : {var}, optional + fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of `minimum_fill_value`. keepdims : bool, optional @@ -5799,7 +5799,7 @@ class MaskedArray(ndarray): out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. - fill_value : {var}, optional + fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of maximum_fill_value(). keepdims : bool, optional @@ -5876,7 +5876,7 @@ class MaskedArray(ndarray): Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. - fill_value : {var}, optional + fill_value : scalar or None, optional Value used to fill in the masked values. keepdims : bool, optional If this is set to True, the axes which are reduced are left diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py index aff72f79b..9eb1a23cd 100644 --- a/numpy/ma/timer_comparison.py +++ b/numpy/ma/timer_comparison.py @@ -7,12 +7,9 @@ import numpy.core.fromnumeric as fromnumeric from numpy.testing import build_err_msg -# Fixme: this does not look right. -np.seterr(all='ignore') pi = np.pi - class ModuleTester: def __init__(self, module): self.module = module @@ -111,6 +108,7 @@ class ModuleTester: self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal') + @np.errstate(all='ignore') def test_0(self): """ Tests creation @@ -121,6 +119,7 @@ class ModuleTester: xm = self.masked_array(x, mask=m) xm[0] + @np.errstate(all='ignore') def test_1(self): """ Tests creation @@ -148,6 +147,7 @@ class ModuleTester: xf.shape = s assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) + @np.errstate(all='ignore') def test_2(self): """ Tests conversions and indexing. @@ -190,6 +190,7 @@ class ModuleTester: m3 = self.make_mask(m, copy=1) assert(m is not m3) + @np.errstate(all='ignore') def test_3(self): """ Tests resize/repeat @@ -209,6 +210,7 @@ class ModuleTester: y8 = x4.repeat(2, 0) assert self.allequal(y5, y8) + @np.errstate(all='ignore') def test_4(self): """ Test of take, transpose, inner, outer products. @@ -232,6 +234,7 @@ class ModuleTester: assert t[1] == 2 assert t[2] == 3 + @np.errstate(all='ignore') def test_5(self): """ Tests inplace w/ scalar @@ -284,6 +287,7 @@ class ModuleTester: x += 1. assert self.allequal(x, y + 1.) + @np.errstate(all='ignore') def test_6(self): """ Tests inplace w/ array @@ -335,6 +339,7 @@ class ModuleTester: x /= a xm /= a + @np.errstate(all='ignore') def test_7(self): "Tests ufunc" d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6), @@ -369,6 +374,7 @@ class ModuleTester: self.assert_array_equal(ur.filled(0), mr.filled(0), f) self.assert_array_equal(ur._mask, mr._mask) + @np.errstate(all='ignore') def test_99(self): # test average ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) @@ -414,6 +420,7 @@ class ModuleTester: self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) + @np.errstate(all='ignore') def test_A(self): x = self.arange(24) x[5:6] = self.masked diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 1baa7d870..44784023b 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -156,7 +156,7 @@ def polyfromroots(roots): .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), - where the `r_n` are the roots specified in `roots`. If a zero has + where the ``r_n`` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear @@ -192,11 +192,11 @@ def polyfromroots(roots): Notes ----- The coefficients are determined by multiplying together linear factors - of the form `(x - r_i)`, i.e. + of the form ``(x - r_i)``, i.e. .. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n) - where ``n == len(roots) - 1``; note that this implies that `1` is always + where ``n == len(roots) - 1``; note that this implies that ``1`` is always returned for :math:`a_n`. Examples diff --git a/numpy/random/_generator.pyx b/numpy/random/_generator.pyx index 7ffa36775..e00bc4d98 100644 --- a/numpy/random/_generator.pyx +++ b/numpy/random/_generator.pyx @@ -859,7 +859,8 @@ cdef class Generator: greater than or equal to low. The default value is 0. high : float or array_like of floats Upper boundary of the output interval. All values generated will be - less than high. The default value is 1.0. + less than high. high - low must be non-negative. The default value + is 1.0. size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. If size is ``None`` (default), @@ -885,10 +886,6 @@ cdef class Generator: anywhere within the interval ``[a, b)``, and zero elsewhere. When ``high`` == ``low``, values of ``low`` will be returned. - If ``high`` < ``low``, the results are officially undefined - and may eventually raise an error, i.e. do not rely on this - function to behave when passed arguments satisfying that - inequality condition. Examples -------- @@ -914,7 +911,7 @@ cdef class Generator: """ cdef bint is_scalar = True cdef np.ndarray alow, ahigh, arange - cdef double _low, _high, range + cdef double _low, _high, rng cdef object temp alow = <np.ndarray>np.PyArray_FROM_OTF(low, np.NPY_DOUBLE, np.NPY_ALIGNED) @@ -923,13 +920,13 @@ cdef class Generator: if np.PyArray_NDIM(alow) == np.PyArray_NDIM(ahigh) == 0: _low = PyFloat_AsDouble(low) _high = PyFloat_AsDouble(high) - range = _high - _low - if not np.isfinite(range): - raise OverflowError('Range exceeds valid bounds') + rng = _high - _low + if not np.isfinite(rng): + raise OverflowError('high - low range exceeds valid bounds') return cont(&random_uniform, &self._bitgen, size, self.lock, 2, _low, '', CONS_NONE, - range, '', CONS_NONE, + rng, 'high - low', CONS_NON_NEGATIVE, 0.0, '', CONS_NONE, None) @@ -943,7 +940,7 @@ cdef class Generator: raise OverflowError('Range exceeds valid bounds') return cont(&random_uniform, &self._bitgen, size, self.lock, 2, alow, '', CONS_NONE, - arange, '', CONS_NONE, + arange, 'high - low', CONS_NON_NEGATIVE, 0.0, '', CONS_NONE, None) diff --git a/numpy/random/tests/test_generator_mt19937.py b/numpy/random/tests/test_generator_mt19937.py index b69cd38d4..c4fb5883c 100644 --- a/numpy/random/tests/test_generator_mt19937.py +++ b/numpy/random/tests/test_generator_mt19937.py @@ -1666,6 +1666,21 @@ class TestRandomDist: # DBL_MAX by increasing fmin a bit random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17) + def test_uniform_zero_range(self): + func = random.uniform + result = func(1.5, 1.5) + assert_allclose(result, 1.5) + result = func([0.0, np.pi], [0.0, np.pi]) + assert_allclose(result, [0.0, np.pi]) + result = func([[2145.12], [2145.12]], [2145.12, 2145.12]) + assert_allclose(result, 2145.12 + np.zeros((2, 2))) + + def test_uniform_neg_range(self): + func = random.uniform + assert_raises(ValueError, func, 2, 1) + assert_raises(ValueError, func, [1, 2], [1, 1]) + assert_raises(ValueError, func, [[0, 1],[2, 3]], 2) + def test_scalar_exception_propagation(self): # Tests that exceptions are correctly propagated in distributions # when called with objects that throw exceptions when converted to diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py index e974bbd09..b4d42728e 100644 --- a/numpy/testing/_private/utils.py +++ b/numpy/testing/_private/utils.py @@ -481,7 +481,7 @@ def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): instead of this function for more consistent floating point comparisons. - The test verifies that the elements of ``actual`` and ``desired`` satisfy. + The test verifies that the elements of `actual` and `desired` satisfy. ``abs(desired-actual) < 1.5 * 10**(-decimal)`` diff --git a/numpy/tests/test_numpy_version.py b/numpy/tests/test_numpy_version.py index 916ab9383..7fd566815 100644 --- a/numpy/tests/test_numpy_version.py +++ b/numpy/tests/test_numpy_version.py @@ -8,7 +8,7 @@ def test_valid_numpy_version(): # Verify that the numpy version is a valid one (no .post suffix or other # nonsense). See gh-6431 for an issue caused by an invalid version. version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(|a[0-9]|b[0-9]|rc[0-9])" - dev_suffix = r"(\.dev0\+([0-9a-f]{7}|Unknown))" + dev_suffix = r"\.dev0\+[0-9]*\.g[0-9a-f]+" if np.version.release: res = re.match(version_pattern, np.__version__) else: diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index 1382e1c4b..7b2a590c3 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -40,7 +40,7 @@ def test_numpy_namespace(): 'byte_bounds': 'numpy.lib.utils.byte_bounds', 'compare_chararrays': 'numpy.core._multiarray_umath.compare_chararrays', 'deprecate': 'numpy.lib.utils.deprecate', - 'deprecate_with_doc': 'numpy.lib.utils.<lambda>', + 'deprecate_with_doc': 'numpy.lib.utils.deprecate_with_doc', 'disp': 'numpy.lib.function_base.disp', 'fastCopyAndTranspose': 'numpy.core._multiarray_umath._fastCopyAndTranspose', 'get_array_wrap': 'numpy.lib.shape_base.get_array_wrap', diff --git a/numpy/tests/test_reloading.py b/numpy/tests/test_reloading.py index 61ae91b00..5c4309f4a 100644 --- a/numpy/tests/test_reloading.py +++ b/numpy/tests/test_reloading.py @@ -1,4 +1,4 @@ -from numpy.testing import assert_raises, assert_, assert_equal +from numpy.testing import assert_raises, assert_warns, assert_, assert_equal from numpy.compat import pickle import sys @@ -16,13 +16,15 @@ def test_numpy_reloading(): VisibleDeprecationWarning = np.VisibleDeprecationWarning ModuleDeprecationWarning = np.ModuleDeprecationWarning - reload(np) + with assert_warns(UserWarning): + reload(np) assert_(_NoValue is np._NoValue) assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning) assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning) assert_raises(RuntimeError, reload, numpy._globals) - reload(np) + with assert_warns(UserWarning): + reload(np) assert_(_NoValue is np._NoValue) assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning) assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning) @@ -45,13 +47,15 @@ def test_full_reimport(): # This is generally unsafe, especially, since we also reload the C-modules. code = textwrap.dedent(r""" import sys + from pytest import warns import numpy as np for k in list(sys.modules.keys()): if "numpy" in k: del sys.modules[k] - import numpy as np + with warns(UserWarning): + import numpy as np """) p = subprocess.run([sys.executable, '-c', code]) - assert p.returncode == 0 + diff --git a/numpy/typing/__init__.py b/numpy/typing/__init__.py index e72e8fb4d..d9d9557bf 100644 --- a/numpy/typing/__init__.py +++ b/numpy/typing/__init__.py @@ -210,9 +210,11 @@ del TYPE_CHECKING, final, List from ._scalars import ( _CharLike, _BoolLike, + _UIntLike, _IntLike, _FloatLike, _ComplexLike, + _TD64Like, _NumberLike, _ScalarLike, _VoidLike, diff --git a/numpy/typing/_array_like.py b/numpy/typing/_array_like.py index a1a604239..63b67b33a 100644 --- a/numpy/typing/_array_like.py +++ b/numpy/typing/_array_like.py @@ -1,7 +1,9 @@ +from __future__ import annotations + import sys -from typing import Any, overload, Sequence, TYPE_CHECKING, Union +from typing import Any, overload, Sequence, TYPE_CHECKING, Union, TypeVar -from numpy import ndarray +from numpy import ndarray, dtype from ._scalars import _ScalarLike from ._dtype_like import DTypeLike @@ -16,12 +18,15 @@ else: else: HAVE_PROTOCOL = True +_DType = TypeVar("_DType", bound="dtype[Any]") + if TYPE_CHECKING or HAVE_PROTOCOL: - class _SupportsArray(Protocol): - @overload - def __array__(self, __dtype: DTypeLike = ...) -> ndarray: ... - @overload - def __array__(self, dtype: DTypeLike = ...) -> ndarray: ... + # The `_SupportsArray` protocol only cares about the default dtype + # (i.e. `dtype=None`) of the to-be returned array. + # Concrete implementations of the protocol are responsible for adding + # any and all remaining overloads + class _SupportsArray(Protocol[_DType]): + def __array__(self, dtype: None = ...) -> ndarray[Any, _DType]: ... else: _SupportsArray = Any @@ -36,5 +41,5 @@ ArrayLike = Union[ _ScalarLike, Sequence[_ScalarLike], Sequence[Sequence[Any]], # TODO: Wait for support for recursive types - _SupportsArray, + "_SupportsArray[Any]", ] diff --git a/numpy/typing/_callable.py b/numpy/typing/_callable.py index c703df28a..831921fd7 100644 --- a/numpy/typing/_callable.py +++ b/numpy/typing/_callable.py @@ -103,7 +103,7 @@ if TYPE_CHECKING or HAVE_PROTOCOL: class _BoolTrueDiv(Protocol): @overload - def __call__(self, __other: Union[float, _IntLike, _BoolLike]) -> float64: ... + def __call__(self, __other: Union[float, _IntLike]) -> float64: ... @overload def __call__(self, __other: complex) -> complex128: ... @overload diff --git a/numpy/typing/_scalars.py b/numpy/typing/_scalars.py index e4fc28b07..90b2eff7b 100644 --- a/numpy/typing/_scalars.py +++ b/numpy/typing/_scalars.py @@ -7,12 +7,16 @@ import numpy as np _CharLike = Union[str, bytes] +# The 6 `<X>Like` type-aliases below represent all scalars that can be +# coerced into `<X>` (with the casting rule `same_kind`) _BoolLike = Union[bool, np.bool_] -_IntLike = Union[int, np.integer] +_UIntLike = Union[_BoolLike, np.unsignedinteger] +_IntLike = Union[_BoolLike, int, np.integer] _FloatLike = Union[_IntLike, float, np.floating] _ComplexLike = Union[_FloatLike, complex, np.complexfloating] -_NumberLike = Union[int, float, complex, np.number, np.bool_] +_TD64Like = Union[_IntLike, np.timedelta64] +_NumberLike = Union[int, float, complex, np.number, np.bool_] _ScalarLike = Union[ int, float, diff --git a/numpy/typing/tests/data/fail/array_like.py b/numpy/typing/tests/data/fail/array_like.py index a97e72dc7..3bbd29061 100644 --- a/numpy/typing/tests/data/fail/array_like.py +++ b/numpy/typing/tests/data/fail/array_like.py @@ -11,6 +11,6 @@ x2: ArrayLike = A() # E: Incompatible types in assignment x3: ArrayLike = {1: "foo", 2: "bar"} # E: Incompatible types in assignment scalar = np.int64(1) -scalar.__array__(dtype=np.float64) # E: Unexpected keyword argument +scalar.__array__(dtype=np.float64) # E: No overload variant array = np.array([1]) -array.__array__(dtype=np.float64) # E: Unexpected keyword argument +array.__array__(dtype=np.float64) # E: No overload variant diff --git a/numpy/typing/tests/data/fail/arrayprint.py b/numpy/typing/tests/data/fail/arrayprint.py new file mode 100644 index 000000000..86297a0b2 --- /dev/null +++ b/numpy/typing/tests/data/fail/arrayprint.py @@ -0,0 +1,13 @@ +from typing import Callable, Any +import numpy as np + +AR: np.ndarray +func1: Callable[[Any], str] +func2: Callable[[np.integer[Any]], str] + +np.array2string(AR, style=None) # E: Unexpected keyword argument +np.array2string(AR, legacy="1.14") # E: incompatible type +np.array2string(AR, sign="*") # E: incompatible type +np.array2string(AR, floatmode="default") # E: incompatible type +np.array2string(AR, formatter={"A": func1}) # E: incompatible type +np.array2string(AR, formatter={"float": func2}) # E: Incompatible types diff --git a/numpy/typing/tests/data/pass/array_like.py b/numpy/typing/tests/data/pass/array_like.py index f85724267..563fc08c7 100644 --- a/numpy/typing/tests/data/pass/array_like.py +++ b/numpy/typing/tests/data/pass/array_like.py @@ -25,13 +25,13 @@ class A: x13: ArrayLike = A() scalar: _SupportsArray = np.int64(1) -scalar.__array__(np.float64) +scalar.__array__(None) array: _SupportsArray = np.array(1) -array.__array__(np.float64) +array.__array__(None) a: _SupportsArray = A() -a.__array__(np.int64) -a.__array__(dtype=np.int64) +a.__array__(None) +a.__array__(dtype=None) # Escape hatch for when you mean to make something like an object # array. diff --git a/numpy/typing/tests/data/pass/arrayprint.py b/numpy/typing/tests/data/pass/arrayprint.py new file mode 100644 index 000000000..6c704c755 --- /dev/null +++ b/numpy/typing/tests/data/pass/arrayprint.py @@ -0,0 +1,37 @@ +import numpy as np + +AR = np.arange(10) +AR.setflags(write=False) + +with np.printoptions(): + np.set_printoptions( + precision=1, + threshold=2, + edgeitems=3, + linewidth=4, + suppress=False, + nanstr="Bob", + infstr="Bill", + formatter={}, + sign="+", + floatmode="unique", + ) + np.get_printoptions() + str(AR) + + np.array2string( + AR, + max_line_width=5, + precision=2, + suppress_small=True, + separator=";", + prefix="test", + threshold=5, + floatmode="fixed", + suffix="?", + legacy="1.13", + ) + np.format_float_scientific(1, precision=5) + np.format_float_positional(1, trim="k") + np.array_repr(AR) + np.array_str(AR) diff --git a/numpy/typing/tests/data/pass/dtype.py b/numpy/typing/tests/data/pass/dtype.py index cbae8c078..a97edc302 100644 --- a/numpy/typing/tests/data/pass/dtype.py +++ b/numpy/typing/tests/data/pass/dtype.py @@ -1,5 +1,7 @@ import numpy as np +dtype_obj = np.dtype(np.str_) + np.dtype(dtype=np.int64) np.dtype(int) np.dtype("int") @@ -33,3 +35,9 @@ class Test: np.dtype(Test()) + +# Methods and attributes +dtype_obj.base +dtype_obj.subdtype +dtype_obj.newbyteorder() +dtype_obj.type diff --git a/numpy/typing/tests/data/pass/flatiter.py b/numpy/typing/tests/data/pass/flatiter.py index c0219eb2b..4fdf25299 100644 --- a/numpy/typing/tests/data/pass/flatiter.py +++ b/numpy/typing/tests/data/pass/flatiter.py @@ -12,3 +12,5 @@ a[0] a[[0, 1, 2]] a[...] a[:] +a.__array__() +a.__array__(np.float64) diff --git a/numpy/typing/tests/data/reveal/arrayprint.py b/numpy/typing/tests/data/reveal/arrayprint.py new file mode 100644 index 000000000..e797097eb --- /dev/null +++ b/numpy/typing/tests/data/reveal/arrayprint.py @@ -0,0 +1,19 @@ +from typing import Any, Callable +import numpy as np + +AR: np.ndarray[Any, Any] +func_float: Callable[[np.floating[Any]], str] +func_int: Callable[[np.integer[Any]], str] + +reveal_type(np.get_printoptions()) # E: TypedDict +reveal_type(np.array2string( # E: str + AR, formatter={'float_kind': func_float, 'int_kind': func_int} +)) +reveal_type(np.format_float_scientific(1.0)) # E: str +reveal_type(np.format_float_positional(1)) # E: str +reveal_type(np.array_repr(AR)) # E: str +reveal_type(np.array_str(AR)) # E: str + +reveal_type(np.printoptions()) # E: contextlib._GeneratorContextManager +with np.printoptions() as dct: + reveal_type(dct) # E: TypedDict diff --git a/numpy/typing/tests/data/reveal/dtype.py b/numpy/typing/tests/data/reveal/dtype.py index d414f2c49..626a15270 100644 --- a/numpy/typing/tests/data/reveal/dtype.py +++ b/numpy/typing/tests/data/reveal/dtype.py @@ -1,5 +1,7 @@ import numpy as np +dtype_obj: np.dtype[np.str_] + reveal_type(np.dtype(np.float64)) # E: numpy.dtype[numpy.floating[numpy.typing._64Bit]] reveal_type(np.dtype(np.int64)) # E: numpy.dtype[numpy.signedinteger[numpy.typing._64Bit]] @@ -31,3 +33,9 @@ reveal_type(np.dtype("S8")) # E: numpy.dtype # Void reveal_type(np.dtype(("U", 10))) # E: numpy.dtype[numpy.void] + +# Methods and attributes +reveal_type(dtype_obj.base) # E: numpy.dtype[numpy.str_] +reveal_type(dtype_obj.subdtype) # E: Union[Tuple[numpy.dtype[numpy.str_], builtins.tuple[builtins.int]], None] +reveal_type(dtype_obj.newbyteorder()) # E: numpy.dtype[numpy.str_] +reveal_type(dtype_obj.type) # E: Type[numpy.str_] diff --git a/numpy/typing/tests/data/reveal/flatiter.py b/numpy/typing/tests/data/reveal/flatiter.py index 56cdc7a0e..221101ebb 100644 --- a/numpy/typing/tests/data/reveal/flatiter.py +++ b/numpy/typing/tests/data/reveal/flatiter.py @@ -1,14 +1,17 @@ +from typing import Any import numpy as np -a: "np.flatiter[np.ndarray]" +a: np.flatiter[np.ndarray[Any, np.dtype[np.str_]]] -reveal_type(a.base) # E: numpy.ndarray* -reveal_type(a.copy()) # E: numpy.ndarray* +reveal_type(a.base) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] +reveal_type(a.copy()) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] reveal_type(a.coords) # E: tuple[builtins.int] reveal_type(a.index) # E: int -reveal_type(iter(a)) # E: Iterator[numpy.generic*] -reveal_type(next(a)) # E: numpy.generic -reveal_type(a[0]) # E: numpy.generic -reveal_type(a[[0, 1, 2]]) # E: numpy.ndarray* -reveal_type(a[...]) # E: numpy.ndarray* -reveal_type(a[:]) # E: numpy.ndarray* +reveal_type(iter(a)) # E: Iterator[numpy.str_] +reveal_type(next(a)) # E: numpy.str_ +reveal_type(a[0]) # E: numpy.str_ +reveal_type(a[[0, 1, 2]]) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] +reveal_type(a[...]) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] +reveal_type(a[:]) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] +reveal_type(a.__array__()) # E: numpy.ndarray[Any, numpy.dtype[numpy.str_]] +reveal_type(a.__array__(np.float64)) # E: numpy.ndarray[Any, numpy.dtype[Any]] diff --git a/numpy/version.py b/numpy/version.py new file mode 100644 index 000000000..8a1d05aa4 --- /dev/null +++ b/numpy/version.py @@ -0,0 +1,11 @@ +from ._version import get_versions + +__ALL__ = ['version', 'full_version', 'git_revision', 'release'] + +vinfo = get_versions() +version: str = vinfo["version"] +full_version: str = vinfo['version'] +git_revision: str = vinfo['full-revisionid'] +release = 'dev0' not in version + +del get_versions, vinfo diff --git a/pytest.ini b/pytest.ini index 149af04b8..dfad538c2 100644 --- a/pytest.ini +++ b/pytest.ini @@ -14,4 +14,5 @@ filterwarnings = # Matrix PendingDeprecationWarning. ignore:the matrix subclass is not ignore:Importing from numpy.matlib is - +# pytest warning when using PYTHONOPTIMIZE + ignore:assertions not in test modules or plugins:pytest.PytestConfigWarning diff --git a/release_requirements.txt b/release_requirements.txt index c24e39c78..805ce9a8a 100644 --- a/release_requirements.txt +++ b/release_requirements.txt @@ -14,4 +14,4 @@ twine # building and notes Paver -towncrier +git+https://github.com/hawkowl/towncrier.git@master diff --git a/runtests.py b/runtests.py index 87e26768b..4c9493a35 100755 --- a/runtests.py +++ b/runtests.py @@ -432,8 +432,6 @@ def build_project(args): cmd += ["build"] if args.parallel > 1: cmd += ["-j", str(args.parallel)] - if args.debug_info: - cmd += ["build_src", "--verbose-cfg"] if args.warn_error: cmd += ["--warn-error"] if args.cpu_baseline: @@ -444,6 +442,8 @@ def build_project(args): cmd += ["--disable-optimization"] if args.simd_test is not None: cmd += ["--simd-test", args.simd_test] + if args.debug_info: + cmd += ["build_src", "--verbose-cfg"] # Install; avoid producing eggs so numpy can be imported from dst_dir. cmd += ['install', '--prefix=' + dst_dir, '--single-version-externally-managed', @@ -524,6 +524,7 @@ def asv_compare_config(bench_path, args, h_commits): is_cached = asv_substitute_config(conf_path, nconf_path, numpy_build_options = ' '.join([f'\\"{v}\\"' for v in build]), + numpy_global_options= ' '.join([f'--global-option=\\"{v}\\"' for v in ["build"] + build]) ) if not is_cached: asv_clear_cache(bench_path, h_commits) @@ -538,7 +539,7 @@ def asv_clear_cache(bench_path, h_commits, env_dir="env"): for asv_build_cache in glob.glob(asv_build_pattern, recursive=True): for c in h_commits: try: shutil.rmtree(os.path.join(asv_build_cache, c)) - except OSError: pass + except OSError: pass def asv_substitute_config(in_config, out_config, **custom_vars): """ diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 000000000..5bca14ba0 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,11 @@ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +VCS = git +style = pep440 +versionfile_source = numpy/_version.py +versionfile_build = numpy/_version.py +tag_prefix = v +parentdir_prefix = numpy- @@ -24,13 +24,51 @@ import sys import subprocess import textwrap import warnings +import versioneer +import builtins + +# This is a bit hackish: we are setting a global variable so that the main +# numpy __init__ can detect if it is being loaded by the setup routine, to +# avoid attempting to load components that aren't built yet. While ugly, it's +# a lot more robust than what was previously being used. +builtins.__NUMPY_SETUP__ = True +# Needed for backwards code compatibility below and in some CI scripts. +# The version components are changed from ints to strings, but only VERSION +# seems to matter outside of this module and it was already a str. +FULLVERSION = versioneer.get_version() +ISRELEASED = 'dev' not in FULLVERSION +MAJOR, MINOR, MICRO = FULLVERSION.split('.')[:3] +VERSION = '{}.{}.{}'.format(MAJOR, MINOR, MICRO) +# Python supported version checks if sys.version_info[:2] < (3, 7): raise RuntimeError("Python version >= 3.7 required.") -import builtins +# The first version not in the `Programming Language :: Python :: ...` classifiers above +if sys.version_info >= (3, 10): + fmt = "NumPy {} may not yet support Python {}.{}." + warnings.warn( + fmt.format(VERSION, *sys.version_info[:2]), + RuntimeWarning) + del fmt +# BEFORE importing setuptools, remove MANIFEST. Otherwise it may not be +# properly updated when the contents of directories change (true for distutils, +# not sure about setuptools). +if os.path.exists('MANIFEST'): + os.remove('MANIFEST') + +# We need to import setuptools here in order for it to persist in sys.modules. +# Its presence/absence is used in subclassing setup in numpy/distutils/core.py. +# However, we need to run the distutils version of sdist, so import that first +# so that it is in sys.modules +import numpy.distutils.command.sdist +import setuptools + +# Initialize cmdclass from versioneer +from numpy.distutils.core import numpy_cmdclass +cmdclass = versioneer.get_cmdclass(numpy_cmdclass) CLASSIFIERS = """\ Development Status :: 5 - Production/Stable @@ -54,114 +92,6 @@ Operating System :: Unix Operating System :: MacOS """ -MAJOR = 1 -MINOR = 21 -MICRO = 0 -ISRELEASED = False -VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) - -# The first version not in the `Programming Language :: Python :: ...` classifiers above -if sys.version_info >= (3, 10): - warnings.warn( - f"NumPy {VERSION} may not yet support Python " - f"{sys.version_info.major}.{sys.version_info.minor}.", - RuntimeWarning, - ) - - -# Return the git revision as a string -def git_version(): - def _minimal_ext_cmd(cmd): - # construct minimal environment - env = {} - for k in ['SYSTEMROOT', 'PATH', 'HOME']: - v = os.environ.get(k) - if v is not None: - env[k] = v - # LANGUAGE is used on win32 - env['LANGUAGE'] = 'C' - env['LANG'] = 'C' - env['LC_ALL'] = 'C' - out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env) - return out - - try: - out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) - GIT_REVISION = out.strip().decode('ascii') - except (subprocess.SubprocessError, OSError): - GIT_REVISION = "Unknown" - - if not GIT_REVISION: - # this shouldn't happen but apparently can (see gh-8512) - GIT_REVISION = "Unknown" - - return GIT_REVISION - - -# BEFORE importing setuptools, remove MANIFEST. Otherwise it may not be -# properly updated when the contents of directories change (true for distutils, -# not sure about setuptools). -if os.path.exists('MANIFEST'): - os.remove('MANIFEST') - -# This is a bit hackish: we are setting a global variable so that the main -# numpy __init__ can detect if it is being loaded by the setup routine, to -# avoid attempting to load components that aren't built yet. While ugly, it's -# a lot more robust than what was previously being used. -builtins.__NUMPY_SETUP__ = True - - -def get_version_info(): - # Adding the git rev number needs to be done inside write_version_py(), - # otherwise the import of numpy.version messes up the build under Python 3. - FULLVERSION = VERSION - if os.path.exists('.git'): - GIT_REVISION = git_version() - elif os.path.exists('numpy/version.py'): - # must be a source distribution, use existing version file - try: - from numpy.version import git_revision as GIT_REVISION - except ImportError: - raise ImportError("Unable to import git_revision. Try removing " - "numpy/version.py and the build directory " - "before building.") - else: - GIT_REVISION = "Unknown" - - if not ISRELEASED: - import time - - time_stamp = time.strftime("%Y%m%d%H%M%S", time.localtime()) - FULLVERSION += f'.dev0+{time_stamp}_{GIT_REVISION[:7]}' - - return FULLVERSION, GIT_REVISION - - -def write_version_py(filename='numpy/version.py'): - cnt = """ -# THIS FILE IS GENERATED FROM NUMPY SETUP.PY -# -# To compare versions robustly, use `numpy.lib.NumpyVersion` -short_version: str = '%(version)s' -version: str = '%(version)s' -full_version: str = '%(full_version)s' -git_revision: str = '%(git_revision)s' -release: bool = %(isrelease)s - -if not release: - version = full_version -""" - FULLVERSION, GIT_REVISION = get_version_info() - - a = open(filename, 'w') - try: - a.write(cnt % {'version': VERSION, - 'full_version': FULLVERSION, - 'git_revision': GIT_REVISION, - 'isrelease': str(ISRELEASED)}) - finally: - a.close() - def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration @@ -230,13 +160,14 @@ class concat_license_files(): f.write(self.bsd_text) -from distutils.command.sdist import sdist -class sdist_checked(sdist): +# Need to inherit from versioneer version of sdist to get the encoded +# version information. +class sdist_checked(cmdclass['sdist']): """ check submodules on sdist to prevent incomplete tarballs """ def run(self): check_submodules() with concat_license_files(): - sdist.run(self) + super().run() def get_build_overrides(): @@ -320,7 +251,8 @@ def parse_setuppy_commands(): # below and not standalone. Hence they're not added to good_commands. good_commands = ('develop', 'sdist', 'build', 'build_ext', 'build_py', 'build_clib', 'build_scripts', 'bdist_wheel', 'bdist_rpm', - 'bdist_wininst', 'bdist_msi', 'bdist_mpkg', 'build_src') + 'bdist_wininst', 'bdist_msi', 'bdist_mpkg', 'build_src', + 'version') for command in good_commands: if command in args: @@ -422,7 +354,7 @@ def parse_setuppy_commands(): def get_docs_url(): - if not ISRELEASED: + if 'dev' in VERSION: return "https://numpy.org/devdocs" else: # For releases, this URL ends up on pypi. @@ -437,9 +369,6 @@ def setup_package(): os.chdir(src_path) sys.path.insert(0, src_path) - # Rewrite the version file every time - write_version_py() - # The f2py scripts that will be installed if sys.platform == 'win32': f2py_cmds = [ @@ -452,7 +381,7 @@ def setup_package(): 'f2py%s.%s = numpy.f2py.f2py2e:main' % sys.version_info[:2], ] - cmdclass = {"sdist": sdist_checked, } + cmdclass["sdist"] = sdist_checked metadata = dict( name='numpy', maintainer="NumPy Developers", @@ -471,6 +400,7 @@ def setup_package(): classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], platforms=["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], test_suite='pytest', + version=versioneer.get_version(), cmdclass=cmdclass, python_requires='>=3.7', zip_safe=False, @@ -486,10 +416,11 @@ def setup_package(): # Raise errors for unsupported commands, improve help output, etc. run_build = parse_setuppy_commands() - if run_build: + if run_build and 'version' not in sys.argv: # patches distutils, even though we don't use it - import setuptools # noqa: F401 + #from setuptools import setup from numpy.distutils.core import setup + if 'sdist' not in sys.argv: # Generate Cython sources, unless we're generating an sdist generate_cython() @@ -498,10 +429,8 @@ def setup_package(): # Customize extension building cmdclass['build_clib'], cmdclass['build_ext'] = get_build_overrides() else: + #from numpy.distutils.core import setup from setuptools import setup - # Version number is added to metadata inside configuration() if build - # is run. - metadata['version'] = get_version_info()[0] try: setup(**metadata) diff --git a/test_requirements.txt b/test_requirements.txt index 1b7b696d3..e3fc9ccc6 100644 --- a/test_requirements.txt +++ b/test_requirements.txt @@ -1,8 +1,8 @@ cython==0.29.21 -wheel +wheel<0.36.3 setuptools<49.2.0 -hypothesis==5.41.5 -pytest==6.0.2 +hypothesis==5.43.3 +pytest==6.2.0 pytz==2020.4 pytest-cov==2.10.1 pickle5; python_version == '3.7' and platform_python_implementation != 'PyPy' diff --git a/tools/openblas_support.py b/tools/openblas_support.py index 50837177b..dff19274e 100644 --- a/tools/openblas_support.py +++ b/tools/openblas_support.py @@ -12,81 +12,12 @@ from tempfile import mkstemp, gettempdir from urllib.request import urlopen, Request from urllib.error import HTTPError -OPENBLAS_V = '0.3.12' -# Temporary build of OpenBLAS to test a fix for dynamic detection of CPU -OPENBLAS_LONG = 'v0.3.12-buffersize20' +OPENBLAS_V = '0.3.13' +OPENBLAS_LONG = 'v0.3.13' BASE_LOC = 'https://anaconda.org/multibuild-wheels-staging/openblas-libs' BASEURL = f'{BASE_LOC}/{OPENBLAS_LONG}/download' ARCHITECTURES = ['', 'windows', 'darwin', 'aarch64', 'x86_64', 'i686', 'ppc64le', 's390x'] -sha256_vals = { - "openblas-v0.3.7-527-g79fd006c-win_amd64-gcc_7_1_0.zip": - "7249d68c02e6b6339e06edfeab1fecddf29ee1e67a3afaa77917c320c43de840", - "openblas64_-v0.3.7-527-g79fd006c-win_amd64-gcc_7_1_0.zip": - "6488e0961a5926e47242f63b63b41cfdd661e6f1d267e8e313e397cde4775c17", - "openblas-v0.3.7-527-g79fd006c-win32-gcc_7_1_0.zip": - "5fb0867ca70b1d0fdbf68dd387c0211f26903d74631420e4aabb49e94aa3930d", - "openblas-v0.3.7-527-g79fd006c-macosx_10_9_x86_64-gf_1becaaa.tar.gz": - "69434bd626bbc495da9ce8c36b005d140c75e3c47f94e88c764a199e820f9259", - "openblas64_-v0.3.7-527-g79fd006c-macosx_10_9_x86_64-gf_1becaaa.tar.gz": - "093f6d953e3fa76a86809be67bd1f0b27656671b5a55b233169cfaa43fd63e22", - "openblas-v0.3.7-527-g79fd006c-manylinux2014_aarch64.tar.gz": - "42676c69dc48cd6e412251b39da6b955a5a0e00323ddd77f9137f7c259d35319", - "openblas64_-v0.3.7-527-g79fd006c-manylinux2014_aarch64.tar.gz": - "5aec167af4052cf5e9e3e416c522d9794efabf03a2aea78b9bb3adc94f0b73d8", - "openblas-v0.3.7-527-g79fd006c-manylinux2010_x86_64.tar.gz": - "fa67c6cc29d4cc5c70a147c80526243239a6f95fc3feadcf83a78176cd9c526b", - "openblas64_-v0.3.7-527-g79fd006c-manylinux2010_x86_64.tar.gz": - "9ad34e89a5307dcf5823bf5c020580d0559a0c155fe85b44fc219752e61852b0", - "openblas-v0.3.7-527-g79fd006c-manylinux2010_i686.tar.gz": - "0b8595d316c8b7be84ab1f1d5a0c89c1b35f7c987cdaf61d441bcba7ab4c7439", - "openblas-v0.3.7-527-g79fd006c-manylinux2014_ppc64le.tar.gz": - "3e1c7d6472c34e7210e3605be4bac9ddd32f613d44297dc50cf2d067e720c4a9", - "openblas64_-v0.3.7-527-g79fd006c-manylinux2014_ppc64le.tar.gz": - "a0885873298e21297a04be6cb7355a585df4fa4873e436b4c16c0a18fc9073ea", - "openblas-v0.3.7-527-g79fd006c-manylinux2014_s390x.tar.gz": - "79b454320817574e20499d58f05259ed35213bea0158953992b910607b17f240", - "openblas64_-v0.3.7-527-g79fd006c-manylinux2014_s390x.tar.gz": - "9fddbebf5301518fc4a5d2022a61886544a0566868c8c014359a1ee6b17f2814", - "openblas-v0.3.7-527-g79fd006c-manylinux1_i686.tar.gz": - "24fb92684ec4676185fff5c9340f50c3db6075948bcef760e9c715a8974e4680", - "openblas-v0.3.7-527-g79fd006c-manylinux1_x86_64.tar.gz": - "ebb8236b57a1b4075fd5cdc3e9246d2900c133a42482e5e714d1e67af5d00e62", - "openblas-v0.3.10-win_amd64-gcc_7_1_0.zip": - "e5356a2aa4aa7ed9233b2ca199fdd445f55ba227f004ebc63071dfa2426e9b09", - "openblas64_-v0.3.10-win_amd64-gcc_7_1_0.zip": - "aea3f9c8bdfe0b837f0d2739a6c755b12b6838f6c983e4ede71b4e1b576e6e77", - "openblas-v0.3.10-win32-gcc_7_1_0.zip": - "af1ad3172b23f7c6ef2234151a71d3be4d92010dad4dfb25d07cf5a20f009202", - "openblas64_-v0.3.10-macosx_10_9_x86_64-gf_1becaaa.tar.gz": - "38b61c58d63048731d6884fea7b63f8cbd610e85b138c6bac0e39fd77cd4699b", - "openblas-v0.3.10-manylinux2014_aarch64.tar.gz": - "c4444b9836ec26f7772fae02851961bf73177ff2aa436470e56fab8a1ef8d405", - "openblas-v0.3.10-manylinux2010_x86_64.tar.gz": - "cb7988c4a015aece9c49b1169f51c4ac2287fb9aab8114c8ab67792138ffc85e", - "openblas-v0.3.10-manylinux2010_i686.tar.gz": - "dc637801dd80ebd6394ea8b4a97f8858e4224870ea9214de08bebbdddd8e206e", - "openblas-v0.3.10-manylinux1_x86_64.tar.gz": - "ec1f9e9b2a62d5cb9e2634b88ee2da7cb6b07702d5a0e8b190d680a31adfa23a", - "openblas-v0.3.10-manylinux1_i686.tar.gz": - "b13d9d14e6bd452c0fbadb5cd5fda05b98b1e14043edb13ead90694d4cc07f0e", - "openblas-v0.3.10-manylinux2014_ppc64le.tar.gz": - "1cbc8176986099cf0cbb8f64968d5a14880d602d4b3c59a91d75b69b8760cde3", - "openblas-v0.3.10-manylinux2014_s390x.tar.gz": - "fa6722f0b12507ab0a65f38501ed8435b573df0adc0b979f47cdc4c9e9599475", - "openblas-v0.3.10-macosx_10_9_x86_64-gf_1becaaa.tar.gz": - "c6940b5133e687ae7a4f9c7c794f6a6d92b619cf41e591e5db07aab5da118199", - "openblas64_-v0.3.10-manylinux2014_s390x.tar.gz": - "e0347dd6f3f3a27d2f5e76d382e8a4a68e2e92f5f6a10e54ef65c7b14b44d0e8", - "openblas64_-v0.3.10-manylinux2014_ppc64le.tar.gz": - "4b96a51ac767ec0aabb821c61bcd3420e82e987fc93f7e1f85aebb2a845694eb", - "openblas64_-v0.3.10-manylinux2010_x86_64.tar.gz": - "f68fea21fbc73d06b7566057cad2ed8c7c0eb71fabf9ed8a609f86e5bc60ce5e", - "openblas64_-v0.3.10-manylinux2014_aarch64.tar.gz": - "15e6eed8cb0df8b88e52baa136ffe1769c517e9de7bcdfd81ec56420ae1069e9", -} - - IS_32BIT = sys.maxsize < 2**32 @@ -162,15 +93,6 @@ def download_openblas(target, arch, ilp64, is_32bit): data = response.read() # Verify hash key = os.path.basename(filename) - sha256_returned = hashlib.sha256(data).hexdigest() - if 0: - if key not in sha256_vals: - raise ValueError( - f'\nkey "{key}" with hash "{sha256_returned}" not in sha256_vals\n') - sha256_expected = sha256_vals[key] - if sha256_returned != sha256_expected: - # print(f'\nkey "{key}" with hash "{sha256_returned}" mismatch\n') - raise ValueError(f'sha256 hash mismatch for filename {filename}') print("Saving to file", file=sys.stderr) with open(target, 'wb') as fid: fid.write(data) diff --git a/tools/refguide_check.py b/tools/refguide_check.py index 138e0ece7..f0f6461b7 100644 --- a/tools/refguide_check.py +++ b/tools/refguide_check.py @@ -19,11 +19,12 @@ another function, or deprecated, or ...) Another use of this helper script is to check validity of code samples in docstrings:: - $ python refguide_check.py --doctests ma + $ python tools/refguide_check.py --doctests ma or in RST-based documentations:: - $ python refguide_check.py --rst docs + $ python tools/refguide_check.py --rst doc/source + """ import copy import doctest diff --git a/versioneer.py b/versioneer.py new file mode 100644 index 000000000..7a77c5ef7 --- /dev/null +++ b/versioneer.py @@ -0,0 +1,1855 @@ + +# Version: 0.19 + +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/python-versioneer/python-versioneer +* Brian Warner +* License: Public Domain +* Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3 +* [![Latest Version][pypi-image]][pypi-url] +* [![Build Status][travis-image]][travis-url] + +This is a tool for managing a recorded version number in distutils-based +python projects. The goal is to remove the tedious and error-prone "update +the embedded version string" step from your release process. Making a new +release should be as easy as recording a new tag in your version-control +system, and maybe making new tarballs. + + +## Quick Install + +* `pip install versioneer` to somewhere in your $PATH +* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) +* run `versioneer install` in your source tree, commit the results +* Verify version information with `python setup.py version` + +## Version Identifiers + +Source trees come from a variety of places: + +* a version-control system checkout (mostly used by developers) +* a nightly tarball, produced by build automation +* a snapshot tarball, produced by a web-based VCS browser, like github's + "tarball from tag" feature +* a release tarball, produced by "setup.py sdist", distributed through PyPI + +Within each source tree, the version identifier (either a string or a number, +this tool is format-agnostic) can come from a variety of places: + +* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows + about recent "tags" and an absolute revision-id +* the name of the directory into which the tarball was unpacked +* an expanded VCS keyword ($Id$, etc) +* a `_version.py` created by some earlier build step + +For released software, the version identifier is closely related to a VCS +tag. Some projects use tag names that include more than just the version +string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool +needs to strip the tag prefix to extract the version identifier. For +unreleased software (between tags), the version identifier should provide +enough information to help developers recreate the same tree, while also +giving them an idea of roughly how old the tree is (after version 1.2, before +version 1.3). Many VCS systems can report a description that captures this, +for example `git describe --tags --dirty --always` reports things like +"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the +0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has +uncommitted changes). + +The version identifier is used for multiple purposes: + +* to allow the module to self-identify its version: `myproject.__version__` +* to choose a name and prefix for a 'setup.py sdist' tarball + +## Theory of Operation + +Versioneer works by adding a special `_version.py` file into your source +tree, where your `__init__.py` can import it. This `_version.py` knows how to +dynamically ask the VCS tool for version information at import time. + +`_version.py` also contains `$Revision$` markers, and the installation +process marks `_version.py` to have this marker rewritten with a tag name +during the `git archive` command. As a result, generated tarballs will +contain enough information to get the proper version. + +To allow `setup.py` to compute a version too, a `versioneer.py` is added to +the top level of your source tree, next to `setup.py` and the `setup.cfg` +that configures it. This overrides several distutils/setuptools commands to +compute the version when invoked, and changes `setup.py build` and `setup.py +sdist` to replace `_version.py` with a small static file that contains just +the generated version data. + +## Installation + +See [INSTALL.md](./INSTALL.md) for detailed installation instructions. + +## Version-String Flavors + +Code which uses Versioneer can learn about its version string at runtime by +importing `_version` from your main `__init__.py` file and running the +`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can +import the top-level `versioneer.py` and run `get_versions()`. + +Both functions return a dictionary with different flavors of version +information: + +* `['version']`: A condensed version string, rendered using the selected + style. This is the most commonly used value for the project's version + string. The default "pep440" style yields strings like `0.11`, + `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section + below for alternative styles. + +* `['full-revisionid']`: detailed revision identifier. For Git, this is the + full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". + +* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the + commit date in ISO 8601 format. This will be None if the date is not + available. + +* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that + this is only accurate if run in a VCS checkout, otherwise it is likely to + be False or None + +* `['error']`: if the version string could not be computed, this will be set + to a string describing the problem, otherwise it will be None. It may be + useful to throw an exception in setup.py if this is set, to avoid e.g. + creating tarballs with a version string of "unknown". + +Some variants are more useful than others. Including `full-revisionid` in a +bug report should allow developers to reconstruct the exact code being tested +(or indicate the presence of local changes that should be shared with the +developers). `version` is suitable for display in an "about" box or a CLI +`--version` output: it can be easily compared against release notes and lists +of bugs fixed in various releases. + +The installer adds the following text to your `__init__.py` to place a basic +version in `YOURPROJECT.__version__`: + + from ._version import get_versions + __version__ = get_versions()['version'] + del get_versions + +## Styles + +The setup.cfg `style=` configuration controls how the VCS information is +rendered into a version string. + +The default style, "pep440", produces a PEP440-compliant string, equal to the +un-prefixed tag name for actual releases, and containing an additional "local +version" section with more detail for in-between builds. For Git, this is +TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags +--dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the +tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and +that this commit is two revisions ("+2") beyond the "0.11" tag. For released +software (exactly equal to a known tag), the identifier will only contain the +stripped tag, e.g. "0.11". + +Other styles are available. See [details.md](details.md) in the Versioneer +source tree for descriptions. + +## Debugging + +Versioneer tries to avoid fatal errors: if something goes wrong, it will tend +to return a version of "0+unknown". To investigate the problem, run `setup.py +version`, which will run the version-lookup code in a verbose mode, and will +display the full contents of `get_versions()` (including the `error` string, +which may help identify what went wrong). + +## Known Limitations + +Some situations are known to cause problems for Versioneer. This details the +most significant ones. More can be found on Github +[issues page](https://github.com/python-versioneer/python-versioneer/issues). + +### Subprojects + +Versioneer has limited support for source trees in which `setup.py` is not in +the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are +two common reasons why `setup.py` might not be in the root: + +* Source trees which contain multiple subprojects, such as + [Buildbot](https://github.com/buildbot/buildbot), which contains both + "master" and "slave" subprojects, each with their own `setup.py`, + `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI + distributions (and upload multiple independently-installable tarballs). +* Source trees whose main purpose is to contain a C library, but which also + provide bindings to Python (and perhaps other languages) in subdirectories. + +Versioneer will look for `.git` in parent directories, and most operations +should get the right version string. However `pip` and `setuptools` have bugs +and implementation details which frequently cause `pip install .` from a +subproject directory to fail to find a correct version string (so it usually +defaults to `0+unknown`). + +`pip install --editable .` should work correctly. `setup.py install` might +work too. + +Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in +some later version. + +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking +this issue. The discussion in +[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the +issue from the Versioneer side in more detail. +[pip PR#3176](https://github.com/pypa/pip/pull/3176) and +[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve +pip to let Versioneer work correctly. + +Versioneer-0.16 and earlier only looked for a `.git` directory next to the +`setup.cfg`, so subprojects were completely unsupported with those releases. + +### Editable installs with setuptools <= 18.5 + +`setup.py develop` and `pip install --editable .` allow you to install a +project into a virtualenv once, then continue editing the source code (and +test) without re-installing after every change. + +"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a +convenient way to specify executable scripts that should be installed along +with the python package. + +These both work as expected when using modern setuptools. When using +setuptools-18.5 or earlier, however, certain operations will cause +`pkg_resources.DistributionNotFound` errors when running the entrypoint +script, which must be resolved by re-installing the package. This happens +when the install happens with one version, then the egg_info data is +regenerated while a different version is checked out. Many setup.py commands +cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into +a different virtualenv), so this can be surprising. + +[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes +this one, but upgrading to a newer version of setuptools should probably +resolve it. + + +## Updating Versioneer + +To upgrade your project to a new release of Versioneer, do the following: + +* install the new Versioneer (`pip install -U versioneer` or equivalent) +* edit `setup.cfg`, if necessary, to include any new configuration settings + indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install` in your source tree, to replace + `SRC/_version.py` +* commit any changed files + +## Future Directions + +This tool is designed to make it easily extended to other version-control +systems: all VCS-specific components are in separate directories like +src/git/ . The top-level `versioneer.py` script is assembled from these +components by running make-versioneer.py . In the future, make-versioneer.py +will take a VCS name as an argument, and will construct a version of +`versioneer.py` that is specific to the given VCS. It might also take the +configuration arguments that are currently provided manually during +installation by editing setup.py . Alternatively, it might go the other +direction and include code from all supported VCS systems, reducing the +number of intermediate scripts. + +## Similar projects + +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time + dependency +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of + versioneer + +## License + +To make Versioneer easier to embed, all its code is dedicated to the public +domain. The `_version.py` that it creates is also in the public domain. +Specifically, both are released under the Creative Commons "Public Domain +Dedication" license (CC0-1.0), as described in +https://creativecommons.org/publicdomain/zero/1.0/ . + +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg +[pypi-url]: https://pypi.python.org/pypi/versioneer/ +[travis-image]: +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer + +""" + +import configparser +import errno +import json +import os +import re +import subprocess +import sys + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_root(): + """Get the project root directory. + + We require that all commands are run from the project root, i.e. the + directory that contains setup.py, setup.cfg, and versioneer.py . + """ + root = os.path.realpath(os.path.abspath(os.getcwd())) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + # allow 'python path/to/setup.py COMMAND' + root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) + setup_py = os.path.join(root, "setup.py") + versioneer_py = os.path.join(root, "versioneer.py") + if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + err = ("Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND').") + raise VersioneerBadRootError(err) + try: + # Certain runtime workflows (setup.py install/develop in a setuptools + # tree) execute all dependencies in a single python process, so + # "versioneer" may be imported multiple times, and python's shared + # module-import table will cache the first one. So we can't use + # os.path.dirname(__file__), as that will find whichever + # versioneer.py was first imported, even in later projects. + me = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(me)[0]) + vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) + if me_dir != vsr_dir: + print("Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py)) + except NameError: + pass + return root + + +def get_config_from_root(root): + """Read the project setup.cfg file to determine Versioneer config.""" + # This might raise EnvironmentError (if setup.cfg is missing), or + # configparser.NoSectionError (if it lacks a [versioneer] section), or + # configparser.NoOptionError (if it lacks "VCS="). See the docstring at + # the top of versioneer.py for instructions on writing your setup.cfg . + setup_cfg = os.path.join(root, "setup.cfg") + parser = configparser.ConfigParser() + with open(setup_cfg, "r") as f: + parser.read_file(f) + VCS = parser.get("versioneer", "VCS") # mandatory + + def get(parser, name): + if parser.has_option("versioneer", name): + return parser.get("versioneer", name) + return None + cfg = VersioneerConfig() + cfg.VCS = VCS + cfg.style = get(parser, "style") or "" + cfg.versionfile_source = get(parser, "versionfile_source") + cfg.versionfile_build = get(parser, "versionfile_build") + cfg.tag_prefix = get(parser, "tag_prefix") + if cfg.tag_prefix in ("''", '""'): + cfg.tag_prefix = "" + cfg.parentdir_prefix = get(parser, "parentdir_prefix") + cfg.verbose = get(parser, "verbose") + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +# these dictionaries contain VCS-specific tools +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None, None + stdout = p.communicate()[0].strip().decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % dispcmd) + print("stdout was %s" % stdout) + return None, p.returncode + return stdout, p.returncode + + +LONG_VERSION_PY['git'] = r''' +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (built by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) + +"""Git implementation of _version.py.""" + +import errno +import os +import re +import subprocess +import sys + + +def get_keywords(): + """Get the keywords needed to look up the version information.""" + # these strings will be replaced by git during git-archive. + # setup.py/versioneer.py will grep for the variable names, so they must + # each be defined on a line of their own. _version.py will just call + # get_keywords(). + git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" + git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" + git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" + keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} + return keywords + + +class VersioneerConfig: + """Container for Versioneer configuration parameters.""" + + +def get_config(): + """Create, populate and return the VersioneerConfig() object.""" + # these strings are filled in when 'setup.py versioneer' creates + # _version.py + cfg = VersioneerConfig() + cfg.VCS = "git" + cfg.style = "%(STYLE)s" + cfg.tag_prefix = "%(TAG_PREFIX)s" + cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" + cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" + cfg.verbose = False + return cfg + + +class NotThisMethod(Exception): + """Exception raised if a method is not valid for the current scenario.""" + + +LONG_VERSION_PY = {} +HANDLERS = {} + + +def register_vcs_handler(vcs, method): # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f): + """Store f in HANDLERS[vcs][method].""" + if vcs not in HANDLERS: + HANDLERS[vcs] = {} + HANDLERS[vcs][method] = f + return f + return decorate + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, + env=None): + """Call the given command(s).""" + assert isinstance(commands, list) + p = None + for c in commands: + try: + dispcmd = str([c] + args) + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %%s" %% dispcmd) + print(e) + return None, None + else: + if verbose: + print("unable to find command, tried %%s" %% (commands,)) + return None, None + stdout = p.communicate()[0].strip().decode() + if p.returncode != 0: + if verbose: + print("unable to run %%s (error)" %% dispcmd) + print("stdout was %%s" %% stdout) + return None, p.returncode + return stdout, p.returncode + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %%s but none started with prefix %%s" %% + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %%d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%%s', no digits" %% ",".join(refs - tags)) + if verbose: + print("likely tags: %%s" %% ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %%s" %% r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %%s not under git control" %% root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", + "--always", "--long", + "--match", "%%s*" %% tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%%s'" + %% describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%%s' doesn't start with prefix '%%s'" + print(fmt %% (full_tag, tag_prefix)) + pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" + %% (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], + cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post0.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post0.dev%%d" %% pieces["distance"] + else: + # exception #1 + rendered = "0.post0.dev%%d" %% pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%%s'" %% style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +def get_versions(): + """Get version information or return default if unable to do so.""" + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded keywords. + + cfg = get_config() + verbose = cfg.verbose + + try: + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, + verbose) + except NotThisMethod: + pass + + try: + root = os.path.realpath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in cfg.versionfile_source.split('/'): + root = os.path.dirname(root) + except NameError: + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None} + + try: + pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) + return render(pieces, cfg.style) + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + except NotThisMethod: + pass + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", "date": None} +''' + + +@register_vcs_handler("git", "get_keywords") +def git_get_keywords(versionfile_abs): + """Extract version information from the given file.""" + # the code embedded in _version.py can just fetch the value of these + # keywords. When used from setup.py, we don't want to import _version.py, + # so we do it with a regexp instead. This function is not used from + # _version.py. + keywords = {} + try: + f = open(versionfile_abs, "r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return keywords + + +@register_vcs_handler("git", "keywords") +def git_versions_from_keywords(keywords, tag_prefix, verbose): + """Get version information from git keywords.""" + if not keywords: + raise NotThisMethod("no keywords at all, weird") + date = keywords.get("date") + if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant + # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 + # -like" string, which we must then edit to make compliant), because + # it's been around since git-1.5.3, and it's too difficult to + # discover which version we're using, or to work around using an + # older one. + date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + refnames = keywords["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("keywords are unexpanded, not using") + raise NotThisMethod("unexpanded keywords, not a git-archive tarball") + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs - tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return {"version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": None, + "date": date} + # no suitable tags, so version is "0+unknown", but full hex is still there + if verbose: + print("no suitable tags, using unknown + full revision id") + return {"version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, "error": "no suitable tags", "date": None} + + +@register_vcs_handler("git", "pieces_from_vcs") +def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): + """Get version from 'git describe' in the root of the source tree. + + This only gets called if the git-archive 'subst' keywords were *not* + expanded, and _version.py hasn't already been rewritten with a short + version string, meaning we're inside a checked out source tree. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=True) + if rc != 0: + if verbose: + print("Directory %s not under git control" % root) + raise NotThisMethod("'git rev-parse --git-dir' returned error") + + # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] + # if there isn't one, this yields HEX[-dirty] (no NUM) + describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty=", + "--always", "--long", + "--match", "%s*" % tag_prefix], + cwd=root) + # --long was added in git-1.5.5 + if describe_out is None: + raise NotThisMethod("'git describe' failed") + describe_out = describe_out.strip() + full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if full_out is None: + raise NotThisMethod("'git rev-parse' failed") + full_out = full_out.strip() + + pieces = {} + pieces["long"] = full_out + pieces["short"] = full_out[:7] # maybe improved later + pieces["error"] = None + + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] + # TAG might have hyphens. + git_describe = describe_out + + # look for -dirty suffix + dirty = git_describe.endswith("-dirty") + pieces["dirty"] = dirty + if dirty: + git_describe = git_describe[:git_describe.rindex("-dirty")] + + # now we have TAG-NUM-gHEX or HEX + + if "-" in git_describe: + # TAG-NUM-gHEX + mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + if not mo: + # unparseable. Maybe git-describe is misbehaving? + pieces["error"] = ("unable to parse git-describe output: '%s'" + % describe_out) + return pieces + + # tag + full_tag = mo.group(1) + if not full_tag.startswith(tag_prefix): + if verbose: + fmt = "tag '%s' doesn't start with prefix '%s'" + print(fmt % (full_tag, tag_prefix)) + pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" + % (full_tag, tag_prefix)) + return pieces + pieces["closest-tag"] = full_tag[len(tag_prefix):] + + # distance: number of commits since tag + pieces["distance"] = int(mo.group(2)) + + # commit: short hex revision ID + pieces["short"] = mo.group(3) + + else: + # HEX: no tags + pieces["closest-tag"] = None + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], + cwd=root) + pieces["distance"] = int(count_out) # total number of commits + + # commit date: see ISO-8601 comment in git_versions_from_keywords() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], + cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) + + return pieces + + +def do_vcs_install(manifest_in, versionfile_source, ipy): + """Git-specific installation logic for Versioneer. + + For Git, this means creating/changing .gitattributes to mark _version.py + for export-subst keyword substitution. + """ + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + files = [manifest_in, versionfile_source] + if ipy: + files.append(ipy) + try: + me = __file__ + if me.endswith(".pyc") or me.endswith(".pyo"): + me = os.path.splitext(me)[0] + ".py" + versioneer_file = os.path.relpath(me) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) + present = False + try: + f = open(".gitattributes", "r") + for line in f.readlines(): + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + f.close() + except EnvironmentError: + pass + if not present: + f = open(".gitattributes", "a+") + f.write("%s export-subst\n" % versionfile_source) + f.close() + files.append(".gitattributes") + run_command(GITS, ["add", "--"] + files) + + +def versions_from_parentdir(parentdir_prefix, root, verbose): + """Try to determine the version from the parent directory name. + + Source tarballs conventionally unpack into a directory that includes both + the project name and a version string. We will also support searching up + two directory levels for an appropriately named parent directory + """ + rootdirs = [] + + for i in range(3): + dirname = os.path.basename(root) + if dirname.startswith(parentdir_prefix): + return {"version": dirname[len(parentdir_prefix):], + "full-revisionid": None, + "dirty": False, "error": None, "date": None} + else: + rootdirs.append(root) + root = os.path.dirname(root) # up a level + + if verbose: + print("Tried directories %s but none started with prefix %s" % + (str(rootdirs), parentdir_prefix)) + raise NotThisMethod("rootdir doesn't start with parentdir_prefix") + + +SHORT_VERSION_PY = """ +# This file was generated by 'versioneer.py' (0.19) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +%s +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) +""" + + +def versions_from_file(filename): + """Try to determine the version from _version.py if present.""" + try: + with open(filename) as f: + contents = f.read() + except EnvironmentError: + raise NotThisMethod("unable to read _version.py") + mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", + contents, re.M | re.S) + if not mo: + raise NotThisMethod("no version_json in _version.py") + return json.loads(mo.group(1)) + + +def write_to_version_file(filename, versions): + """Write the given version number to the given _version.py file.""" + os.unlink(filename) + contents = json.dumps(versions, sort_keys=True, + indent=1, separators=(",", ": ")) + with open(filename, "w") as f: + f.write(SHORT_VERSION_PY % contents) + + print("set %s to '%s'" % (filename, versions["version"])) + + +def plus_or_dot(pieces): + """Return a + if we don't already have one, else return a .""" + if "+" in pieces.get("closest-tag", ""): + return "." + return "+" + + +def render_pep440(pieces): + """Build up version string, with post-release "local version identifier". + + Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you + get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty + + Exceptions: + 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_pre(pieces): + """TAG[.post0.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += ".post0.dev%d" % pieces["distance"] + else: + # exception #1 + rendered = "0.post0.dev%d" % pieces["distance"] + return rendered + + +def render_pep440_post(pieces): + """TAG[.postDISTANCE[.dev0]+gHEX] . + + The ".dev0" means dirty. Note that .dev0 sorts backwards + (a dirty tree will appear "older" than the corresponding clean one), + but you shouldn't be releasing software with -dirty anyways. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + +def render_pep440_old(pieces): + """TAG[.postDISTANCE[.dev0]] . + + The ".dev0" means dirty. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + return rendered + + +def render_git_describe(pieces): + """TAG[-DISTANCE-gHEX][-dirty]. + + Like 'git describe --tags --dirty --always'. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"]: + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render_git_describe_long(pieces): + """TAG-DISTANCE-gHEX[-dirty]. + + Like 'git describe --tags --dirty --always -long'. + The distance/hash is unconditional. + + Exceptions: + 1: no tags. HEX[-dirty] (note: no 'g' prefix) + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) + else: + # exception #1 + rendered = pieces["short"] + if pieces["dirty"]: + rendered += "-dirty" + return rendered + + +def render(pieces, style): + """Render the given version pieces into the requested style.""" + if pieces["error"]: + return {"version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None} + + if not style or style == "default": + style = "pep440" # the default + + if style == "pep440": + rendered = render_pep440(pieces) + elif style == "pep440-pre": + rendered = render_pep440_pre(pieces) + elif style == "pep440-post": + rendered = render_pep440_post(pieces) + elif style == "pep440-old": + rendered = render_pep440_old(pieces) + elif style == "git-describe": + rendered = render_git_describe(pieces) + elif style == "git-describe-long": + rendered = render_git_describe_long(pieces) + else: + raise ValueError("unknown style '%s'" % style) + + return {"version": rendered, "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], "error": None, + "date": pieces.get("date")} + + +class VersioneerBadRootError(Exception): + """The project root directory is unknown or missing key files.""" + + +def get_versions(verbose=False): + """Get the project version from whatever source is available. + + Returns dict with two keys: 'version' and 'full'. + """ + if "versioneer" in sys.modules: + # see the discussion in cmdclass.py:get_cmdclass() + del sys.modules["versioneer"] + + root = get_root() + cfg = get_config_from_root(root) + + assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" + handlers = HANDLERS.get(cfg.VCS) + assert handlers, "unrecognized VCS '%s'" % cfg.VCS + verbose = verbose or cfg.verbose + assert cfg.versionfile_source is not None, \ + "please set versioneer.versionfile_source" + assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" + + versionfile_abs = os.path.join(root, cfg.versionfile_source) + + # extract version from first of: _version.py, VCS command (e.g. 'git + # describe'), parentdir. This is meant to work for developers using a + # source checkout, for users of a tarball created by 'setup.py sdist', + # and for users of a tarball/zipball created by 'git archive' or github's + # download-from-tag feature or the equivalent in other VCSes. + + get_keywords_f = handlers.get("get_keywords") + from_keywords_f = handlers.get("keywords") + if get_keywords_f and from_keywords_f: + try: + keywords = get_keywords_f(versionfile_abs) + ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) + if verbose: + print("got version from expanded keyword %s" % ver) + return ver + except NotThisMethod: + pass + + try: + ver = versions_from_file(versionfile_abs) + if verbose: + print("got version from file %s %s" % (versionfile_abs, ver)) + return ver + except NotThisMethod: + pass + + from_vcs_f = handlers.get("pieces_from_vcs") + if from_vcs_f: + try: + pieces = from_vcs_f(cfg.tag_prefix, root, verbose) + ver = render(pieces, cfg.style) + if verbose: + print("got version from VCS %s" % ver) + return ver + except NotThisMethod: + pass + + try: + if cfg.parentdir_prefix: + ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) + if verbose: + print("got version from parentdir %s" % ver) + return ver + except NotThisMethod: + pass + + if verbose: + print("unable to compute version") + + return {"version": "0+unknown", "full-revisionid": None, + "dirty": None, "error": "unable to compute version", + "date": None} + + +def get_version(): + """Get the short version string for this project.""" + return get_versions()["version"] + + +def get_cmdclass(cmdclass=None): + """Get the custom setuptools/distutils subclasses used by Versioneer. + + If the package uses a different cmdclass (e.g. one from numpy), it + should be provide as an argument. + """ + if "versioneer" in sys.modules: + del sys.modules["versioneer"] + # this fixes the "python setup.py develop" case (also 'install' and + # 'easy_install .'), in which subdependencies of the main project are + # built (using setup.py bdist_egg) in the same python process. Assume + # a main project A and a dependency B, which use different versions + # of Versioneer. A's setup.py imports A's Versioneer, leaving it in + # sys.modules by the time B's setup.py is executed, causing B to run + # with the wrong versioneer. Setuptools wraps the sub-dep builds in a + # sandbox that restores sys.modules to it's pre-build state, so the + # parent is protected against the child's "import versioneer". By + # removing ourselves from sys.modules here, before the child build + # happens, we protect the child from the parent's versioneer too. + # Also see https://github.com/python-versioneer/python-versioneer/issues/52 + + cmds = {} if cmdclass is None else cmdclass.copy() + + # we add "version" to both distutils and setuptools + from distutils.core import Command + + class cmd_version(Command): + description = "report generated version string" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + vers = get_versions(verbose=True) + print("Version: %s" % vers["version"]) + print(" full-revisionid: %s" % vers.get("full-revisionid")) + print(" dirty: %s" % vers.get("dirty")) + print(" date: %s" % vers.get("date")) + if vers["error"]: + print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version + + # we override "build_py" in both distutils and setuptools + # + # most invocation pathways end up running build_py: + # distutils/build -> build_py + # distutils/install -> distutils/build ->.. + # setuptools/bdist_wheel -> distutils/install ->.. + # setuptools/bdist_egg -> distutils/install_lib -> build_py + # setuptools/install -> bdist_egg ->.. + # setuptools/develop -> ? + # pip install: + # copies source tree to a tempdir before running egg_info/etc + # if .git isn't copied too, 'git describe' will fail + # then does setup.py bdist_wheel, or sometimes setup.py install + # setup.py egg_info -> ? + + # we override different "build_py" commands for both environments + if 'build_py' in cmds: + _build_py = cmds['build_py'] + elif "setuptools" in sys.modules: + from setuptools.command.build_py import build_py as _build_py + else: + from distutils.command.build_py import build_py as _build_py + + class cmd_build_py(_build_py): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_py.run(self) + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if cfg.versionfile_build: + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py + + if "setuptools" in sys.modules: + from setuptools.command.build_ext import build_ext as _build_ext + else: + from distutils.command.build_ext import build_ext as _build_ext + + class cmd_build_ext(_build_ext): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_ext.run(self) + if self.inplace: + # build_ext --inplace will only build extensions in + # build/lib<..> dir with no _version.py to write to. + # As in place builds will already have a _version.py + # in the module dir, we do not need to write one. + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_ext"] = cmd_build_ext + + if "cx_Freeze" in sys.modules: # cx_freeze enabled? + from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string + # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. + # setup(console=[{ + # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION + # "product_version": versioneer.get_version(), + # ... + + class cmd_build_exe(_build_exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _build_exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["build_exe"] = cmd_build_exe + del cmds["build_py"] + + if 'py2exe' in sys.modules: # py2exe enabled? + from py2exe.distutils_buildexe import py2exe as _py2exe + + class cmd_py2exe(_py2exe): + def run(self): + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + target_versionfile = cfg.versionfile_source + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + + _py2exe.run(self) + os.unlink(target_versionfile) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % + {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + cmds["py2exe"] = cmd_py2exe + + # we override different "sdist" commands for both environments + if 'sdist' in cmds: + _sdist = cmds['sdist'] + elif "setuptools" in sys.modules: + from setuptools.command.sdist import sdist as _sdist + else: + from distutils.command.sdist import sdist as _sdist + + class cmd_sdist(_sdist): + def run(self): + versions = get_versions() + self._versioneer_generated_versions = versions + # unless we update this, the command will keep using the old + # version + self.distribution.metadata.version = versions["version"] + return _sdist.run(self) + + def make_release_tree(self, base_dir, files): + root = get_root() + cfg = get_config_from_root(root) + _sdist.make_release_tree(self, base_dir, files) + # now locate _version.py in the new base_dir directory + # (remembering that it may be a hardlink) and replace it with an + # updated value + target_versionfile = os.path.join(base_dir, cfg.versionfile_source) + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, + self._versioneer_generated_versions) + cmds["sdist"] = cmd_sdist + + return cmds + + +CONFIG_ERROR = """ +setup.cfg is missing the necessary Versioneer configuration. You need +a section like: + + [versioneer] + VCS = git + style = pep440 + versionfile_source = src/myproject/_version.py + versionfile_build = myproject/_version.py + tag_prefix = + parentdir_prefix = myproject- + +You will also need to edit your setup.py to use the results: + + import versioneer + setup(version=versioneer.get_version(), + cmdclass=versioneer.get_cmdclass(), ...) + +Please read the docstring in ./versioneer.py for configuration instructions, +edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. +""" + +SAMPLE_CONFIG = """ +# See the docstring in versioneer.py for instructions. Note that you must +# re-run 'versioneer.py setup' after changing this section, and commit the +# resulting files. + +[versioneer] +#VCS = git +#style = pep440 +#versionfile_source = +#versionfile_build = +#tag_prefix = +#parentdir_prefix = + +""" + +INIT_PY_SNIPPET = """ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions +""" + + +def do_setup(): + """Do main VCS-independent setup function for installing Versioneer.""" + root = get_root() + try: + cfg = get_config_from_root(root) + except (EnvironmentError, configparser.NoSectionError, + configparser.NoOptionError) as e: + if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + print("Adding sample versioneer config to setup.cfg", + file=sys.stderr) + with open(os.path.join(root, "setup.cfg"), "a") as f: + f.write(SAMPLE_CONFIG) + print(CONFIG_ERROR, file=sys.stderr) + return 1 + + print(" creating %s" % cfg.versionfile_source) + with open(cfg.versionfile_source, "w") as f: + LONG = LONG_VERSION_PY[cfg.VCS] + f.write(LONG % {"DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + }) + + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), + "__init__.py") + if os.path.exists(ipy): + try: + with open(ipy, "r") as f: + old = f.read() + except EnvironmentError: + old = "" + if INIT_PY_SNIPPET not in old: + print(" appending to %s" % ipy) + with open(ipy, "a") as f: + f.write(INIT_PY_SNIPPET) + else: + print(" %s unmodified" % ipy) + else: + print(" %s doesn't exist, ok" % ipy) + ipy = None + + # Make sure both the top-level "versioneer.py" and versionfile_source + # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so + # they'll be copied into source distributions. Pip won't be able to + # install the package without this. + manifest_in = os.path.join(root, "MANIFEST.in") + simple_includes = set() + try: + with open(manifest_in, "r") as f: + for line in f: + if line.startswith("include "): + for include in line.split()[1:]: + simple_includes.add(include) + except EnvironmentError: + pass + # That doesn't cover everything MANIFEST.in can do + # (http://docs.python.org/2/distutils/sourcedist.html#commands), so + # it might give some false negatives. Appending redundant 'include' + # lines is safe, though. + if "versioneer.py" not in simple_includes: + print(" appending 'versioneer.py' to MANIFEST.in") + with open(manifest_in, "a") as f: + f.write("include versioneer.py\n") + else: + print(" 'versioneer.py' already in MANIFEST.in") + if cfg.versionfile_source not in simple_includes: + print(" appending versionfile_source ('%s') to MANIFEST.in" % + cfg.versionfile_source) + with open(manifest_in, "a") as f: + f.write("include %s\n" % cfg.versionfile_source) + else: + print(" versionfile_source already in MANIFEST.in") + + # Make VCS-specific changes. For git, this means creating/changing + # .gitattributes to mark _version.py for export-subst keyword + # substitution. + do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + return 0 + + +def scan_setup_py(): + """Validate the contents of setup.py against Versioneer's expectations.""" + found = set() + setters = False + errors = 0 + with open("setup.py", "r") as f: + for line in f.readlines(): + if "import versioneer" in line: + found.add("import") + if "versioneer.get_cmdclass()" in line: + found.add("cmdclass") + if "versioneer.get_version()" in line: + found.add("get_version") + if "versioneer.VCS" in line: + setters = True + if "versioneer.versionfile_source" in line: + setters = True + if len(found) != 3: + print("") + print("Your setup.py appears to be missing some important items") + print("(but I might be wrong). Please make sure it has something") + print("roughly like the following:") + print("") + print(" import versioneer") + print(" setup( version=versioneer.get_version(),") + print(" cmdclass=versioneer.get_cmdclass(), ...)") + print("") + errors += 1 + if setters: + print("You should remove lines like 'versioneer.VCS = ' and") + print("'versioneer.versionfile_source = ' . This configuration") + print("now lives in setup.cfg, and should be removed from setup.py") + print("") + errors += 1 + return errors + + +if __name__ == "__main__": + cmd = sys.argv[1] + if cmd == "setup": + errors = do_setup() + errors += scan_setup_py() + if errors: + sys.exit(1) |