repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
numpy | doc/source/conf.py | .py | import importlib
import os
import re
import sys
import sysconfig
from datetime import datetime
from docutils import nodes
from docutils.parsers.rst import Directive
# Minimum version, enforced by sphinx
needs_sphinx = '4.3'
# This is a nasty hack to use platform-agnostic names for types in the
# documentation.
# m... | 644 | 20,963 |
numpy | doc/source/reference/random/performance.py | .py | from timeit import repeat
import pandas as pd
import numpy as np
from numpy.random import MT19937, PCG64, PCG64DXSM, SFC64, Philox
PRNGS = [MT19937, PCG64, PCG64DXSM, Philox, SFC64]
funcs = {}
integers = 'integers(0, 2**{bits},size=1000000, dtype="uint{bits}")'
funcs['32-bit Unsigned Ints'] = integers.format(bits=3... | 85 | 2,570 |
numpy | doc/source/f2py/code/setup_skbuild.py | .py | from skbuild import setup
setup(
name="fibby",
version="0.0.1",
description="a minimal example package (fortran version)",
license="MIT",
packages=['fibby'],
python_requires=">=3.7",
)
| 11 | 210 |
numpy | doc/source/user/plots/meshgrid_plot.py | .py | import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([0, 1, 2, 3, 4, 5])
xx, yy = np.meshgrid(x, y)
plt.plot(xx, yy, marker='o', color='k', linestyle='none')
| 9 | 198 |
numpy | doc/source/user/plots/matplotlib2.py | .py | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 20)
y = np.linspace(0, 10, 20)
plt.plot(x, y, 'purple') # line
plt.plot(x, y, 'o') # dots
plt.show()
| 10 | 182 |
numpy | doc/source/user/plots/matplotlib1.py | .py | import matplotlib.pyplot as plt
import numpy as np
a = np.array([2, 1, 5, 7, 4, 6, 8, 14, 10, 9, 18, 20, 22])
plt.plot(a)
plt.show()
| 9 | 136 |
numpy | doc/source/user/plots/matplotlib3.py | .py | import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
X = np.arange(-5, 5, 0.15)
Y = np.arange(-5, 5, 0.15)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis')
plt.show()
| 16 | 304 |
numpy | doc/neps/nep-0016-benchmark.py | .py | import abc
import perf
import numpy as np
class NotArray:
pass
class AttrArray:
__array_implementer__ = True
class ArrayBase(abc.ABC): # noqa: B024
pass
class ABCArray1(ArrayBase):
pass
class ABCArray2:
pass
ArrayBase.register(ABCArray2)
not_array = NotArray()
attr_array = AttrArray()
ab... | 53 | 1,053 |
numpy | doc/neps/tools/build_index.py | .py | """
Scan the directory of nep files and extract their metadata. The
metadata is passed to Jinja for filling out the toctrees for various NEP
categories.
"""
import glob
import os
import re
import jinja2
def render(tpl_path, context):
path, filename = os.path.split(tpl_path)
return jinja2.Environment(
... | 127 | 4,261 |
numpy | numpy/exceptions.py | .py | """
Exceptions and Warnings
=======================
General exceptions used by NumPy. Note that some exceptions may be module
specific, such as linear algebra errors.
.. versionadded:: NumPy 1.25
The exceptions module is new in NumPy 1.25.
.. currentmodule:: numpy.exceptions
Warnings
--------
.. autosummary::... | 247 | 7,709 |
numpy | numpy/_configtool.py | .py | import argparse
import sys
from pathlib import Path
from .lib._utils_impl import get_include
from .version import __version__
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--version",
action="version",
version=__version__,
help="Print the version... | 40 | 1,007 |
numpy | numpy/_expired_attrs_2_0.py | .py | """
Dict of expired attributes that are discontinued since 2.0 release.
Each item is associated with a migration note.
"""
__expired_attributes__ = {
"geterrobj": "Use the np.errstate context manager instead.",
"seterrobj": "Use the np.errstate context manager instead.",
"cast": "Use `np.asarray(arr, dtype... | 79 | 3,775 |
numpy | numpy/__init__.py | .py | """
NumPy
=====
Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation
How to use the documentation
----------------------------
Documentation is available in two forms: docstrings provided
with the c... | 928 | 25,235 |
numpy | numpy/matlib.py | .py | import warnings
# 2018-05-29, PendingDeprecationWarning added to matrix.__new__
# 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning
warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. "
"The matrix subclass is not the recommended way to represent "
"matrices or deal with ... | 381 | 10,637 |
numpy | numpy/_array_api_info.py | .py | """
Array API Inspection namespace
This is the namespace for inspection functions as defined by the array API
standard. See
https://data-apis.org/array-api/latest/API_specification/inspection.html for
more details.
"""
from numpy._core import (
bool,
complex64,
complex128,
dtype,
float32,
floa... | 350 | 10,515 |
numpy | numpy/dtypes.py | .py | """
This module is home to specific dtypes related functionality and their classes.
For more general information about dtypes, also see `numpy.dtype` and
:ref:`arrays.dtypes`.
Similar to the builtin ``types`` module, this submodule defines types (classes)
that are not widely used directly.
.. versionadded:: NumPy 1.2... | 87 | 2,909 |
numpy | numpy/_globals.py | .py | """
Module defining global singleton classes.
This module raises a RuntimeError if an attempt to reload it is made. In that
way the identities of the classes defined here are fixed and will remain so
even if numpy itself is reloaded. In particular, a function like the following
will still work correctly after numpy is... | 122 | 4,156 |
numpy | numpy/_distributor_init.py | .py | """ Distributor init file
Distributors: you can add custom code here to support particular distributions
of numpy.
For example, this is a good place to put any BLAS/LAPACK initialization code.
The numpy standard source distribution will not put code in this file, so you
can safely replace this file with your own ver... | 16 | 421 |
numpy | numpy/_pytesttester.py | .py | """
Pytest test running.
This module implements the ``test()`` function for NumPy modules. The usual
boiler plate for doing that is to put the following in the module
``__init__.py`` file::
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
Warnings filtering and... | 187 | 5,658 |
numpy | numpy/conftest.py | .py | """
Pytest configuration and fixtures for the Numpy test suite.
"""
import os
import sys
import tempfile
import warnings
from contextlib import contextmanager
from pathlib import Path
import pytest
try:
import hypothesis
except ImportError:
# hypothesis is an optional test dependency (see
# requirements/h... | 259 | 9,180 |
numpy | numpy/testing/print_coercion_tables.py | .py | #!/usr/bin/env python3
"""Prints type-coercion tables for the built-in NumPy types
"""
from collections import namedtuple
import numpy as np
from numpy._core.numerictypes import obj2sctype
# Generic object that can be added, but doesn't do anything else
class GenericObject:
def __init__(self, v):
self.v... | 208 | 6,286 |
numpy | numpy/testing/__init__.py | .py | """Common test support for all numpy test scripts.
This single module should provide all the common functionality for numpy tests
in a single location, so that test scripts can just import it and work right
away.
"""
from unittest import TestCase
from . import _private, overrides
from ._private import extbuild
from ... | 23 | 581 |
numpy | numpy/testing/overrides.py | .py | """Tools for testing implementations of __array_function__ and ufunc overrides
"""
import numpy._core.umath as _umath
from numpy import ufunc as _ufunc
from numpy._core.overrides import ARRAY_FUNCTIONS as _array_functions
def get_overridable_numpy_ufuncs():
"""List all numpy ufuncs overridable via `__array_ufu... | 85 | 2,134 |
numpy | numpy/testing/tests/test_utils.py | .py | import itertools
import os
import re
import sys
import warnings
import weakref
import pytest
import numpy as np
import numpy._core._multiarray_umath as ncu
from numpy.testing import (
HAS_REFCOUNT,
assert_,
assert_allclose,
assert_almost_equal,
assert_approx_equal,
assert_array_almost_equal,
... | 2,160 | 81,973 |
numpy | numpy/testing/_private/utils.py | .py | """
Utility function to facilitate testing.
"""
import concurrent.futures
import contextlib
import gc
import importlib.metadata
import importlib.util
import operator
import os
import pathlib
import platform
import pprint
import re
import shutil
import subprocess
import sys
import sysconfig
import threading
import warn... | 2,921 | 102,124 |
numpy | numpy/testing/_private/extbuild.py | .py | """
Build a c-extension module on-the-fly in tests.
See build_and_import_extensions for usage hints
"""
import os
import pathlib
import sys
import sysconfig
import textwrap
from .utils import run_subprocess
__all__ = ['build_and_import_extension', 'compile_extension_module']
def build_and_import_extension(
... | 248 | 7,510 |
numpy | numpy/testing/_private/hypothesis_helpers.py | .py | """Shims that let the NumPy test suite import, collect, and run cleanly when the
*optional* ``hypothesis`` dependency is not installed.
``hypothesis`` is a supplement to the deterministic pytest suite (property-based
fuzzing). It recently grew a Rust extension, which makes it hard to install on
platforms without a pr... | 70 | 2,576 |
numpy | numpy/linalg/__init__.py | .py | """
``numpy.linalg``
================
The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
low level implementations of standard linear algebra algorithms. Those
libraries may be provided by NumPy itself using C versions of a subset of their
reference implementations but, when possible, high... | 96 | 2,076 |
numpy | numpy/linalg/_linalg.py | .py | """Lite version of scipy.linalg.
Notes
-----
This module is a lite version of the linalg.py module in SciPy which
contains high-level Python interface to the LAPACK library. The lite
version only accesses the following LAPACK functions: dgesv, zgesv,
dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetr... | 3,625 | 113,432 |
numpy | numpy/linalg/tests/test_regression.py | .py | """ Test functions for linalg module
"""
import pytest
import numpy as np
from numpy import arange, array, dot, float64, linalg, transpose
from numpy.testing import (
assert_,
assert_almost_equal,
assert_array_almost_equal,
assert_array_equal,
assert_array_less,
assert_equal,
assert_raises... | 192 | 7,069 |
numpy | numpy/linalg/tests/test_deprecations.py | .py | """Test deprecation and future warnings.
"""
import pytest
import numpy as np
def test_qr_mode_full_removed():
"""Check mode='full' and mode='economic' raise ValueError."""
a = np.eye(2)
with pytest.raises(ValueError, match="deprecated in NumPy 1.8"):
np.linalg.qr(a, mode='full')
with pytest... | 20 | 621 |
numpy | numpy/linalg/tests/test_linalg.py | .py | """ Test functions for linalg module
"""
import itertools
import os
import sys
import textwrap
import threading
import traceback
import warnings
import pytest
import numpy as np
from numpy import (
array,
asarray,
atleast_2d,
cdouble,
csingle,
dot,
double,
identity,
inf,
linal... | 2,497 | 86,750 |
numpy | numpy/linalg/lapack_lite/fortran.py | .py | # WARNING! This a Python 2 script. Read README.rst for rationale.
import itertools
import re
def isBlank(line):
return not line
def isLabel(line):
return line[0].isdigit()
def isComment(line):
return line[0] != ' '
def isContinuation(line):
return line[5] != ' '
COMMENT, STATEMENT, CONTINUATION = 0,... | 125 | 3,472 |
numpy | numpy/linalg/lapack_lite/make_lite.py | .py | #!/usr/bin/env python2.7
# WARNING! This a Python 2 script. Read README.rst for rationale.
"""
Usage: make_lite.py <wrapped_routines_file> <lapack_dir>
Typical invocation:
make_lite.py wrapped_routines /tmp/lapack-3.x.x
Requires the following to be on the path:
* f2c
* patch
"""
import os
import re
import shu... | 393 | 12,111 |
numpy | numpy/linalg/lapack_lite/clapack_scrub.py | .py | #!/usr/bin/env python2.7
# WARNING! This a Python 2 script. Read README.rst for rationale.
import os
import re
import sys
from plex import IGNORE, TEXT, AnyChar, Bol, Lexicon, Opt, Scanner, State, Str
from plex.traditional import re as Re
try:
from io import BytesIO as UStringIO # Python 2
except ImportError:
... | 320 | 9,217 |
numpy | numpy/_core/getlimits.py | .py | """Machine limits for Float32 and Float64 and (long double) if available...
"""
__all__ = ['finfo', 'iinfo']
import math
import types
from functools import cached_property
from numpy._utils import set_module
from . import numeric, numerictypes as ntypes
from ._multiarray_umath import _finfo_get_realdtype, _populate... | 450 | 14,614 |
numpy | numpy/_core/function_base.py | .py | import functools
import inspect
import operator
import types
import warnings
import numpy as np
from numpy._core import overrides
from numpy._core._multiarray_umath import _array_converter
from numpy._core.multiarray import add_docstring
from . import numeric as _nx
from .numeric import asanyarray, nan, result_type
... | 576 | 21,080 |
numpy | numpy/_core/strings.py | .py | """
This module contains a set of functions for vectorized string
operations.
"""
import functools
import sys
import numpy as np
from numpy import (
add,
equal,
greater,
greater_equal,
less,
less_equal,
multiply as _multiply_ufunc,
not_equal,
)
from numpy._core.multiarray import _vec_s... | 1,826 | 51,204 |
numpy | numpy/_core/einsumfunc.py | .py | """
Implementation of optimized einsum.
"""
import functools
import itertools
import operator
from numpy._core.multiarray import c_einsum, matmul
from numpy._core.numeric import asanyarray, reshape
from numpy._core.overrides import array_function_dispatch
from numpy._core.umath import multiply
__all__ = ['einsum', '... | 1,660 | 58,476 |
numpy | numpy/_core/printoptions.py | .py | """
Stores and defines the low-level format_options context variable.
This is defined in its own file outside of the arrayprint module
so we can import it from C while initializing the multiarray
C module during import without introducing circular dependencies.
"""
import sys
from contextvars import ContextVar
__all... | 33 | 1,056 |
numpy | numpy/_core/numeric.py | .py | import builtins
import functools
import itertools
import math
import numbers
import operator
import sys
import warnings
import numpy as np
from numpy.exceptions import AxisError
from . import multiarray, numerictypes, numerictypes as nt, overrides, shape_base, umath
from ._ufunc_config import errstate
from .multiarra... | 2,712 | 80,673 |
numpy | numpy/_core/_add_newdocs_scalars.py | .py | """
This file is separate from ``_add_newdocs.py`` so that it can be mocked out by
our sphinx ``conf.py`` during doc builds, where we want to avoid showing
platform-dependent information.
"""
import os
import sys
from numpy._core import dtype, numerictypes as _numerictypes
from numpy._core.function_base import add_new... | 382 | 12,933 |
numpy | numpy/_core/records.py | .py | """
This module contains a set of functions for record arrays.
"""
import os
import warnings
from collections import Counter
from contextlib import nullcontext
from numpy._utils import set_module
from . import numeric as sb, numerictypes as nt
from .arrayprint import _get_legacy_print_mode
# All of the functions all... | 1,102 | 37,264 |
numpy | numpy/_core/defchararray.py | .py | """
This module contains a set of functions for vectorized string
operations and methods.
.. note::
The `chararray` class exists for backwards compatibility with
Numarray, it is not recommended for new development. Starting from numpy
1.4, if one needs arrays of strings, it is recommended to use arrays of
... | 1,430 | 38,241 |
numpy | numpy/_core/__init__.py | .py | """
Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
Please note that this module is private. All functions and objects
are available in the main ``numpy`` namespace - use that instead.
"""
import os
from numpy.version import version as __version__
# disables OpenBLAS affinity setting of the main thread ... | 204 | 6,657 |
numpy | numpy/_core/overrides.py | .py | """Implementation of __array_function__ overrides from NEP-18."""
import collections
import enum
import functools
import inspect
from numpy._core._multiarray_umath import (
_ArrayFunctionDispatcher,
_get_implementing_args,
add_docstring,
)
from numpy._utils import set_module # noqa: F401
from numpy._utils... | 204 | 8,078 |
numpy | numpy/_core/_exceptions.py | .py | """
Various richly-typed exceptions, that also help us deal with string formatting
in python where it's easier.
By putting the formatting in `__str__`, we also avoid paying the cost for
users who silence the exceptions.
"""
def _unpack_tuple(tup):
if len(tup) == 1:
return tup[0]
else:
return t... | 163 | 5,159 |
numpy | numpy/_core/_internal.py | .py | """
A place for internal code
Some things are more easily handled Python.
"""
import ast
import math
import re
import sys
import warnings
from numpy import _NoValue
from numpy.exceptions import DTypePromotionError
from ._multiarray_umath import _is_view_safe_cast
from .multiarray import StringDType, array, dtype, p... | 965 | 29,401 |
numpy | numpy/_core/_type_aliases.py | .py | """
Due to compatibility, numpy has a very large number of different naming
conventions for the scalar types (those subclassing from `numpy.generic`).
This file produces a convoluted set of dictionaries mapping names to types,
and sometimes other mappings too.
.. data:: allTypes
A dictionary of names to types that... | 131 | 3,797 |
numpy | numpy/_core/_add_newdocs.py | .py | """
This is only meant to add docs to objects defined in C-extension modules.
The purpose is to allow easier editing of the docstrings without
requiring a re-compile.
NOTE: Many of the methods of ndarray have corresponding functions.
If you update these docstrings, please keep also the ones in
_core/fromnu... | 7,177 | 217,587 |
numpy | numpy/_core/umath.py | .py | """
Create the numpy._core.umath namespace for backward compatibility. In v1.16
the multiarray and umath c-extension modules were merged into a single
_multiarray_umath extension module. So we replicate the old namespace
by importing from the extension module.
"""
import numpy
from . import _multiarray_umath
from ._... | 61 | 2,130 |
numpy | numpy/_core/_ufunc_config.py | .py | """
Functions for changing global ufunc configuration
This provides helpers which wrap `_get_extobj_dict` and `_make_extobj`, and
`_extobj_contextvar` from umath.
"""
import functools
from numpy._utils import set_module
from .umath import _extobj_contextvar, _get_extobj_dict, _make_extobj
__all__ = [
"seterr", ... | 516 | 15,611 |
numpy | numpy/_core/shape_base.py | .py | __all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'block', 'hstack',
'stack', 'unstack', 'vstack']
import functools
import itertools
import operator
from . import fromnumeric as _from_nx, numeric as _nx, overrides
from .multiarray import array, asanyarray, normalize_axis_index
array_function_dispatch =... | 995 | 32,616 |
numpy | numpy/_core/arrayprint.py | .py | """Array printing function
$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
"""
__all__ = ["array2string", "array_str", "array_repr",
"set_printoptions", "get_printoptions", "printoptions",
"format_float_positional", "format_float_scientific"]
__docformat__ = 'restructuredtext'
#
#... | 1,789 | 65,695 |
numpy | numpy/_core/_asarray.py | .py | """
Functions in the ``as*array`` family that promote array-likes into arrays.
`require` fits this category despite its name not matching this pattern.
"""
from .multiarray import array, asanyarray
from .overrides import array_function_dispatch, finalize_array_function_like, set_module
__all__ = ["require"]
POSSIBL... | 131 | 3,894 |
numpy | numpy/_core/_string_helpers.py | .py | """
String-handling utilities to avoid locale-dependence.
Used primarily to generate type name aliases.
"""
# "import string" is costly to import!
# Construct the translation tables directly
# "A" = chr(65), "a" = chr(97)
_all_chars = tuple(map(chr, range(256)))
_ascii_upper = _all_chars[65:65 + 26]
_ascii_lower = _... | 101 | 2,845 |
numpy | numpy/_core/numerictypes.py | .py | """
numerictypes: Define the numeric type objects
This module is designed so "from numerictypes import \\*" is safe.
Exported symbols include:
Dictionary with all registered number types (including aliases):
sctypeDict
Type objects (not all will be available, depends on platform):
see variable sctypes ... | 577 | 14,816 |
numpy | numpy/_core/_dtype.py | .py | """
A place for code to be called from the implementation of np.dtype
String handling is much easier to do correctly in python.
"""
import numpy as np
_kind_to_stem = {
'u': 'uint',
'i': 'int',
'c': 'complex',
'f': 'float',
'b': 'bool',
'V': 'void',
'O': 'object',
'M': 'datetime',
... | 363 | 10,374 |
numpy | numpy/_core/cversions.py | .py | """Simple script to compute the api hash of the current API.
The API has is defined by numpy_api_order and ufunc_api_order.
"""
from os.path import dirname
from code_generators.genapi import fullapi_hash
from code_generators.numpy_api import full_api
if __name__ == '__main__':
curdir = dirname(__file__)
pri... | 14 | 347 |
numpy | numpy/_core/_methods.py | .py | """
Array methods which are called by both the C-code for the method
and the Python code for the NumPy-namespace function
"""
import os
import pickle
import warnings
from contextlib import nullcontext
import numpy as np
from numpy._core import multiarray as mu, numerictypes as nt, umath as um
from numpy._core.multiar... | 253 | 9,393 |
numpy | numpy/_core/fromnumeric.py | .py | """Module containing non-deprecated functions borrowed from Numeric.
"""
import functools
import math
import types
import numpy as np
from numpy._utils import set_module
from . import _methods, multiarray as mu, numerictypes as nt, overrides, umath as um
from ._multiarray_umath import _wrapfunc, _wrapit
from .multia... | 4,416 | 149,237 |
numpy | numpy/_core/_dtype_ctypes.py | .py | """
Conversion from ctypes to dtype.
In an ideal world, we could achieve this through the PEP3118 buffer protocol,
something like::
def dtype_from_ctypes_type(t):
# needed to ensure that the shape of `t` is within memoryview.format
class DummyStruct(ctypes.Structure):
_fields_ = [('a',... | 121 | 3,726 |
numpy | numpy/_core/multiarray.py | .py | """
Create the numpy._core.multiarray namespace for backward compatibility.
In v1.16 the multiarray and umath c-extension modules were merged into
a single _multiarray_umath extension module. So we replicate the old
namespace by importing from the extension module.
"""
import functools
from . import _multiarray_umat... | 1,744 | 56,885 |
numpy | numpy/_core/memmap.py | .py | import operator
from contextlib import nullcontext
import numpy as np
from numpy._utils import set_module
from .numeric import dtype, ndarray, uint8
__all__ = ['memmap']
dtypedescr = dtype
valid_filemodes = ["r", "c", "r+", "w+"]
writeable_filemodes = ["r+", "w+"]
mode_equivalents = {
"readonly": "r",
"cop... | 363 | 12,638 |
numpy | numpy/_core/code_generators/verify_c_api_version.py | .py | #!/usr/bin/env python3
import argparse
import os
import sys
class MismatchCAPIError(ValueError):
pass
def get_api_versions(apiversion):
"""
Return current C API checksum and the recorded checksum.
Return current C API checksum and the recorded checksum for the given
version of the C API version... | 67 | 2,074 |
numpy | numpy/_core/code_generators/generate_umath.py | .py | """
Generate the code to build all the internal ufuncs. At the base is the defdict:
a dictionary ofUfunc classes. This is fed to make_code to generate
__umath_generated.c
"""
import argparse
import os
import re
import textwrap
# identity objects
Zero = "PyLong_FromLong(0)"
One = "PyLong_FromLong(1)"
True_ = "(Py_INCRE... | 1,701 | 55,236 |
numpy | numpy/_core/code_generators/generate_numpy_api.py | .py | #!/usr/bin/env python3
import argparse
import os
from . import genapi, numpy_api
from .genapi import BoolValuesApi, FunctionApi, GlobalVarApi, TypeApi
# use annotated api when running under cpychecker
h_template = r"""
#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE)
typed... | 331 | 9,868 |
numpy | numpy/_core/code_generators/generate_umath_doc.py | .py | import argparse
import os
import textwrap
from . import ufunc_docstrings as docstrings
def normalize_doc(docstring):
docstring = textwrap.dedent(docstring).strip()
docstring = docstring.encode('unicode-escape').decode('ascii')
docstring = docstring.replace(r'"', r'\"')
docstring = docstring.replace(r... | 48 | 1,447 |
numpy | numpy/_core/code_generators/genapi.py | .py | """
Get API information encoded in C files.
See ``find_function`` for how functions should be formatted, and
``read_order`` for how the order of the functions should be
specified.
"""
import hashlib
import importlib.util
import io
import os
import re
import sys
import textwrap
from os.path import join
def get_proce... | 560 | 18,728 |
numpy | numpy/_core/code_generators/ufunc_docstrings.py | .py | """
Docstrings for generated ufuncs
The syntax is designed to look like the function add_newdoc is being
called from numpy.lib, but in this file add_newdoc puts the docstrings
in a dictionary. This dictionary is used in
numpy/_core/code_generators/generate_umath_doc.py to generate the docstrings
as a C #definitions f... | 5,583 | 143,760 |
numpy | numpy/_core/code_generators/generate_ufunc_api.py | .py | import argparse
import os
from . import genapi, numpy_api
from .genapi import FunctionApi, TypeApi
h_template = r"""
#ifdef _UMATHMODULE
extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type;
%s
#else
#if defined(PY_UFUNC_UNIQUE_SYMBOL)
#define PyUFunc_API PY_UFUNC_UNIQUE_SYMBOL
#endif
/* By default do not export API i... | 219 | 5,459 |
numpy | numpy/_core/code_generators/numpy_api.py | .py | """Here we define the exported functions, types, etc... which need to be
exported through a global C pointer.
Each dictionary contains name -> index pair.
Whenever you change one index, you break the ABI (and the ABI version number
should be incremented). Whenever you add an item to one of the dict, the API
needs to ... | 501 | 24,562 |
numpy | numpy/_core/tests/test_numerictypes.py | .py | import itertools
import sys
import pytest
import numpy as np
import numpy._core.numerictypes as nt
from numpy._core.numerictypes import issctype, sctype2char, sctypes
from numpy.testing import assert_, assert_equal, assert_raises, assert_raises_regex
# This is the structure of the table used for plain objects:
#
# +... | 641 | 24,065 |
numpy | numpy/_core/tests/test_stringdtype.py | .py | import bisect
import copy
import itertools
import operator
import os
import pickle
import string
import sys
import tempfile
import pytest
import numpy as np
from numpy._core.tests._natype import pd_NA
from numpy.dtypes import StringDType
from numpy.testing import assert_array_equal
def random_unicode_string_list():... | 2,982 | 100,576 |
numpy | numpy/_core/tests/test_api.py | .py | import sys
import pytest
import numpy as np
import numpy._core.umath as ncu
from numpy._core._rational_tests import rational, rational2
from numpy.lib import stride_tricks
from numpy.testing import (
HAS_REFCOUNT,
assert_,
assert_array_equal,
assert_equal,
assert_raises,
)
def test_array_array()... | 684 | 25,246 |
numpy | numpy/_core/tests/test_memmap.py | .py | import mmap
import os
import sys
import warnings
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryFile
import pytest
from numpy import (
add,
allclose,
arange,
asarray,
average,
isscalar,
memmap,
multiply,
ndarray,
prod,
subtract,
sum,
)
from n... | 287 | 10,142 |
numpy | numpy/_core/tests/test_mem_overlap.py | .py | import itertools
import pytest
import numpy as np
from numpy._core import _umath_tests
from numpy._core._multiarray_tests import internal_overlap, solve_diophantine
from numpy.lib.stride_tricks import as_strided
from numpy.testing import assert_, assert_array_equal, assert_equal, assert_raises
ndims = 2
size = 10
sh... | 934 | 29,317 |
numpy | numpy/_core/tests/test_numeric.py | .py | import inspect
import itertools
import math
import platform
import sys
import warnings
from decimal import Decimal
import pytest
import numpy as np
from numpy import ma
from numpy._core import sctypes
from numpy._core._rational_tests import rational, rational2
from numpy._core.numerictypes import obj2sctype
from nump... | 4,319 | 161,399 |
numpy | numpy/_core/tests/test_overrides.py | .py | import inspect
import os
import pickle
import sys
import tempfile
from io import StringIO
from unittest import mock
import pytest
import numpy as np
from numpy._core._multiarray_umath import _ArrayFunctionDispatcher
from numpy._core.overrides import (
_get_implementing_args,
_ReductionKind,
array_function... | 891 | 31,220 |
numpy | numpy/_core/tests/test_umath_complex.py | .py | import platform
import sys
import pytest
import numpy as np
# import the c-extension module directly since _arg is not exported via umath
import numpy._core._multiarray_umath as ncu
from numpy.testing import (
assert_almost_equal,
assert_array_equal,
assert_array_max_ulp,
assert_equal,
assert_rai... | 632 | 23,562 |
numpy | numpy/_core/tests/test_custom_dtypes.py | .py | from tempfile import NamedTemporaryFile
import pytest
import numpy as np
from numpy._core._multiarray_umath import (
_discover_array_parameters as discover_array_params,
_get_sfloat_dtype,
)
from numpy.testing import assert_array_equal
SF = _get_sfloat_dtype()
class TestSFloat:
def _get_array(self, sca... | 618 | 24,240 |
numpy | numpy/_core/tests/test_limited_api.py | .py | import importlib
import os
import shutil
import subprocess
import sys
import sysconfig
import pytest
import numpy as np
from numpy.testing import HAS_SUBPROCESSES, IS_EDITABLE, NOGIL_BUILD
from numpy.testing._private.utils import run_subprocess
# This import is copied from random.tests.test_extending
try:
import... | 255 | 9,312 |
numpy | numpy/_core/tests/test_casting_floatingpoint_errors.py | .py | import pytest
from pytest import param
import numpy as np
from numpy.testing import IS_WASM
from numpy.testing._private.utils import longdouble_fpe_mark
def values_and_dtypes():
"""
Generate value+dtype pairs that generate floating point errors during
casts. The invalid casts to integers will generate "... | 167 | 5,416 |
numpy | numpy/_core/tests/test_nep50_promotions.py | .py | """
This file adds basic tests to test the NEP 50 style promotion compatibility
mode. Most of these test are likely to be simply deleted again once NEP 50
is adopted in the main test suite. A few may be moved elsewhere.
"""
import operator
import pytest
import numpy as np
from numpy.testing import assert_array_equ... | 359 | 12,499 |
numpy | numpy/_core/tests/test_umath_accuracy.py | .py | import os
import sys
from ctypes import POINTER, c_double, c_float, c_int, c_longlong, cast, pointer
from os import path
import pytest
import numpy as np
from numpy._core._multiarray_umath import __cpu_features__
from numpy.testing import assert_array_max_ulp
from numpy.testing._private.utils import _glibc_older_than... | 93 | 4,379 |
numpy | numpy/_core/tests/test_array_api_info.py | .py | import pytest
import numpy as np
info = np.__array_namespace_info__()
def test_capabilities():
caps = info.capabilities()
assert caps["boolean indexing"] is True
assert caps["data-dependent shapes"] is True
# This will be added in the 2024.12 release of the array API standard.
# assert caps["m... | 114 | 3,064 |
numpy | numpy/_core/tests/test_indexing.py | .py | import functools
import inspect
import operator
import sys
import warnings
from itertools import product
import pytest
import numpy as np
from numpy._core._multiarray_tests import array_indexing
from numpy.exceptions import ComplexWarning, VisibleDeprecationWarning
from numpy.testing import (
HAS_REFCOUNT,
as... | 1,718 | 65,735 |
numpy | numpy/_core/tests/test_dtype.py | .py | import contextlib
import ctypes
import inspect
import operator
import os
import pickle
import sys
import types
import warnings
from itertools import permutations
from typing import Any
import pytest
import numpy as np
import numpy.dtypes
from numpy._core._multiarray_tests import create_custom_field_dtype
from numpy._... | 2,132 | 83,330 |
numpy | numpy/_core/tests/test_scalarinherit.py | .py | """ Test printing of scalar types.
"""
import pytest
import numpy as np
from numpy.testing import assert_, assert_raises
class A:
pass
class B(A, np.float64):
pass
class C(B):
pass
class D(C, B):
pass
class B0(np.float64, A):
pass
class C0(B0):
pass
class HasNew:
def __new__(cls, *arg... | 106 | 2,587 |
numpy | numpy/_core/tests/test_indexerrors.py | .py | import numpy as np
from numpy.testing import assert_raises, assert_raises_regex
class TestIndexErrors:
'''Tests to exercise indexerrors not covered by other tests.'''
def test_arraytypes_fasttake(self):
'take from a 0-length dimension'
x = np.empty((2, 3, 0, 4))
assert_raises(IndexErr... | 123 | 4,713 |
numpy | numpy/_core/tests/test_nditer.py | .py | import inspect
import subprocess
import sys
import textwrap
import warnings
import pytest
import numpy as np
import numpy._core._multiarray_tests as _multiarray_tests
import numpy._core.umath as ncu
from numpy import all, arange, array, nditer
from numpy.testing import (
HAS_REFCOUNT,
HAS_SUBPROCESSES,
IS... | 3,710 | 140,111 |
numpy | numpy/_core/tests/test_datetime.py | .py | import datetime
import pickle
import warnings
from typing import Final
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import pytest
import numpy
import numpy as np
from numpy.testing import (
assert_,
assert_array_equal,
assert_equal,
assert_raises,
assert_raises_regex,
)
try:
Recursion... | 3,299 | 146,725 |
numpy | numpy/_core/tests/test_cpu_features.py | .py | import os
import pathlib
import platform
import re
import subprocess
import sys
import pytest
from numpy._core._multiarray_umath import (
__cpu_baseline__,
__cpu_dispatch__,
__cpu_features__,
)
from numpy.testing import HAS_SUBPROCESSES
def assert_features_equal(actual, desired, fname):
__tracebackh... | 529 | 18,369 |
numpy | numpy/_core/tests/test_shape_base.py | .py | import sys
import pytest
import numpy as np
from numpy._core import (
arange,
array,
atleast_1d,
atleast_2d,
atleast_3d,
block,
concatenate,
hstack,
newaxis,
stack,
vstack,
)
from numpy._core.shape_base import (
_block_concatenate,
_block_dispatcher,
_block_setu... | 900 | 31,733 |
numpy | numpy/_core/tests/test_protocols.py | .py | import warnings
import pytest
import numpy as np
@pytest.mark.filterwarnings("error")
def test_getattr_warning():
# issue gh-14735: make sure we clear only getattr errors, and let warnings
# through
class Wrapper:
def __init__(self, array):
self.array = array
def __len__(sel... | 47 | 1,173 |
numpy | numpy/_core/tests/_locales.py | .py | """Provide class for testing in French locale
"""
import locale
import sys
import pytest
__ALL__ = ['CommaDecimalPointLocale']
def find_comma_decimal_point_locale():
"""See if platform has a decimal point as comma locale.
Find a locale that uses a comma instead of a period as the
decimal point.
R... | 73 | 2,176 |
numpy | numpy/_core/tests/test_scalarprint.py | .py | """ Test printing of scalar types.
"""
import pytest
import numpy as np
from numpy.testing import IS_MUSL, assert_, assert_equal, assert_raises
from numpy.testing._private.utils import LONG_DOUBLE_IS_IBM_DOUBLE_DOUBLE
class TestRealScalars:
def test_str(self):
svals = [0.0, -0.0, 1, -1, np.inf, -np.inf... | 404 | 19,762 |
numpy | numpy/_core/tests/test_arrayobject.py | .py | import sys
import pytest
import numpy as np
from numpy._core._rational_tests import rational, rational2
from numpy.testing import HAS_REFCOUNT, assert_array_equal
def test_matrix_transpose_raises_error_for_1d():
msg = "matrix transpose with ndim < 2 is undefined"
arr = np.arange(48)
with pytest.raises(V... | 199 | 6,837 |
numpy | numpy/_core/tests/test_multiprocessing.py | .py | import multiprocessing
import pytest
import numpy as np
from numpy.testing import IS_IOS, IS_WASM
pytestmark = pytest.mark.thread_unsafe(
reason="tests in this module are explicitly multi-processed"
)
def bool_array_writer(shm_name, n):
# writer routine for test_read_write_bool_array
import time
fro... | 56 | 2,012 |
numpy | numpy/_core/tests/test_cpu_dispatcher.py | .py | from numpy._core import _umath_tests
from numpy._core._multiarray_umath import (
__cpu_baseline__,
__cpu_dispatch__,
__cpu_features__,
)
from numpy.testing import assert_equal
def test_dispatcher():
"""
Testing the utilities of the CPU dispatcher
"""
targets = (
"X86_V2", "X86_V3",... | 49 | 1,570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.