### Offset into a memmap example Source: https://numpy.org/doc/stable/reference/generated/numpy.memmap.html Demonstrates creating a memmap object that starts at a specific byte offset within the file. ```python >>> fpo = np.memmap(filename, dtype=np.float32, mode='r', offset=16) >>> fpo memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32) ``` -------------------------------- ### Cython Extension Module Setup Source: https://numpy.org/doc/stable/user/c-info.python-as-glue.html Example of setting up a Python project with a Cython extension module using Meson and Meson-Python. This includes the Cython file, Python init file, Meson build configuration, and pyproject.toml. ```cython cimport numpy as np def say_hello(): print("Hello!") ``` ```python from .my_extension import say_hello ``` ```meson project( 'module_with_extension', 'c', 'cython', version: '0.0.1', license: 'MIT', ) cython = find_program('cython') py = import('python').find_installation(pure: false) numpy_nodepr_api = ['-DNPY_NO_DEPRECATED_API=NPY_2_0_API_VERSION'] np_dep = declare_dependency(dependencies: dependency('numpy'), compile_args: numpy_nodepr_api) py.extension_module( 'my_extension', 'my_extension.pyx', dependencies: [np_dep], install: true, subdir: 'my_module_with_extension', ) py.install_sources( '__init__.py', subdir: 'my_module_with_extension', ) ``` ```toml [build-system] build-backend = "mesonpy" requires = [ "meson-python", "Cython>=3.0.0", "numpy", ] [project] name = "my_module_with_extension" version = "0.0.1" license = "MIT" dependencies = ["numpy"] ``` -------------------------------- ### Install scipy-doctest Source: https://numpy.org/doc/stable/reference/testing.html Install the `scipy-doctest` package using pip to enable the verification of documentation examples (doctests). ```bash $ pip install scipy-doctest ``` -------------------------------- ### Old distutils Workflow: Install from Source Source: https://numpy.org/doc/stable/building/distutils_equivalents.html Installs NumPy from the current directory, typically after building a wheel. ```bash pip install dist/numpy*.whl ``` -------------------------------- ### Import NumPy and SciPy Modules Source: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html These imports are assumed for the examples in this document. Ensure these libraries are installed. ```python import numpy as np from scipy import io, integrate, linalg, signal from scipy.sparse.linalg import cg, eigs ``` -------------------------------- ### Install Airspeed Velocity Source: https://numpy.org/doc/stable/benchmarking.html Install the Airspeed Velocity benchmarking tool and its dependency for virtual environments. ```bash pip install asv pip install virtualenv ``` -------------------------------- ### Meson.build Example for f2py Extension Source: https://numpy.org/doc/stable/f2py/usage.html A minimal meson.build file to compile a Fortran extension using f2py. It defines sources, invokes f2py via a custom target, and handles installation. ```meson project('f2py_examples', 'fortran') py = import('python').find_installation() # List your Fortran source files sources = files('add.pyf', 'add.f') # Build the extension by invoking f2py via a custom target add_mod = custom_target( 'add_extension', input: sources, output: ['add' + py.extension_suffix()], command: [ py.full_path(), '-m', 'numpy.f2py', '-c', 'add.pyf', 'add.f', '-m', 'add' ], build_by_default: true ) # Install into site-packages under the f2py_examples package install_subdir('.', install_dir: join_paths(py.site_packages_dir(), 'f2py_examples'), strip_directory: false, exclude_files: ['meson.build']) # Also install the built extension (place it beside __init__.py) install_data(add_mod, install_dir: join_paths(py.site_packages_dir(), 'f2py_examples')) ``` -------------------------------- ### String Slicing with Start, Stop, and Step Source: https://numpy.org/doc/stable/reference/generated/numpy.strings.slice.html Illustrates string slicing with start, stop, and step parameters. ```python import numpy as np a = np.array(['hello', 'world']) np.strings.slice(a, 1, 5, 2) ``` -------------------------------- ### Basic Polynomial Fit with numpy.ma.polyfit Source: https://numpy.org/doc/stable/reference/generated/numpy.ma.polyfit.html Demonstrates a basic polynomial fit using numpy.ma.polyfit. This example shows how to get the coefficients of a polynomial that best fits a given set of data points. ```python import numpy as np import warnings x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) z = np.polyfit(x, y, 3) z ``` -------------------------------- ### Meson Install Stage Source: https://numpy.org/doc/stable/building/understanding_meson.html Installs NumPy into the specified prefix directory. The installation path is typically within a site-packages directory. ```bash meson install -C build ``` -------------------------------- ### Install Scoop Source: https://numpy.org/doc/stable/f2py/windows/conda.html Installs Scoop, a command-line installer for Windows, which is used to install Miniconda. ```powershell Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh') ``` -------------------------------- ### String Slicing with Start and Stop Source: https://numpy.org/doc/stable/reference/generated/numpy.strings.slice.html Shows how to slice strings using both start and stop parameters. ```python import numpy as np a = np.array(['hello', 'world']) np.strings.slice(a, 2, None) ``` -------------------------------- ### Old distutils Workflow: Pip Install Source: https://numpy.org/doc/stable/building/distutils_equivalents.html Installs NumPy from source using pip, building in an isolated environment. Use with caution for development. ```bash pip install . ``` -------------------------------- ### Get NumPy Include Directory Source: https://numpy.org/doc/stable/reference/generated/numpy.get_include.html This example shows the typical output of `np.get_include()` in an interactive Python session, indicating the path where NumPy header files are located. The exact path may vary depending on the installation. ```python >>> np.get_include() '.../site-packages/numpy/core/include' # may vary ``` -------------------------------- ### Migrating Nested setup.py to Setuptools Source: https://numpy.org/doc/stable/reference/distutils_status_migration.html Example demonstrating how to aggregate content from multiple setup.py files into a single setup.py for setuptools. This approach involves dropping Configuration instances and using Extension instead. ```python from distutils.core import setup from distutils.extension import Extension setup(name='foobar', version='1.0', ext_modules=[ Extension('foopkg.foo', ['foo.c']), Extension('barpkg.bar', ['bar.c']), ], ) ``` -------------------------------- ### NumPy and SciPy Startup Script Example Source: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html This example shows how to set up a Python startup script to import NumPy as 'np', SciPy linear algebra functions, and define a custom 'hermitian' function with a shortcut. ```python # Make all numpy available via shorter 'np' prefix import numpy as np # # Make the SciPy linear algebra functions available as linalg.func() # e.g. linalg.lu, linalg.eig (for general l*B@u==A@u solution) from scipy import linalg # # Define a Hermitian function def hermitian(A, **kwargs): return np.conj(A,**kwargs).T # Make a shortcut for hermitian: # hermitian(A) --> H(A) H = hermitian ``` -------------------------------- ### Setuptools Build Configuration Source: https://numpy.org/doc/stable/user/c-info.ufunc-tutorial.html This `pyproject.toml` and `setup.py` setup uses `setuptools` as the build backend to compile the C extension module. ```toml [project] name = "spam" version = "0.1" [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" ``` ```python from setuptools import setup, Extension spammodule = Extension('spam', sources=['spammodule.c']) setup(name='spam', version='1.0', ext_modules=[spammodule]) ``` -------------------------------- ### Get NumPy Version Information Source: https://numpy.org/doc/stable/reference/routines.version.html Accesses the full and short version strings of the installed NumPy package. The output may vary depending on your installation. ```python >>> import numpy as np >>> np.__version__ '2.1.0.dev0+git20240319.2ea7ce0' # may vary >>> np.version.short_version '2.1.0.dev0' # may vary ``` -------------------------------- ### Get data type descriptions Source: https://numpy.org/doc/stable/reference/generated/numpy.typename.html This example demonstrates how to use numpy.typename to get descriptions for various data type codes. Note that this function is deprecated. ```python import numpy as np typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q', 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q'] for typechar in typechars: print(typechar, ' : ', np.typename(typechar)) ``` -------------------------------- ### Reading NumPy Example Code Source: https://numpy.org/doc/stable/user/absolute_beginners.html This example demonstrates how to interpret code snippets in the NumPy documentation. Lines starting with '>>>' or '...' are input code, and the rest is the output. ```python >>> a = np.array([[1, ... [4, 5, 6]]) >>> a.shape (2, 3) ``` -------------------------------- ### Cloning NumPy and Setting Up Environment Source: https://numpy.org/doc/stable/building/understanding_meson.html This snippet shows the initial steps to clone the NumPy repository, update submodules, and create/activate a development environment using mamba. ```bash git clone git@github.com:numpy/numpy.git git submodule update --init mamba env create -f environment.yml mamba activate numpy-dev ``` -------------------------------- ### Example Configuration Statement for Dispatchable Source Source: https://numpy.org/doc/stable/reference/simd/how-it-works.html This example shows the format of a configuration statement at the top of a dispatchable C source file. It specifies the target instruction sets for optimization. ```c /*@targets avx2 avx512f vsx2 vsx3 asimd asimdhp */ // C code ``` -------------------------------- ### numpy.modf Example Source: https://numpy.org/doc/stable/reference/generated/numpy.modf.html Demonstrates how to use numpy.modf to get the fractional and integral parts of array elements and a single negative number. ```python import numpy as np np.modf([0, 3.5]) ``` ```python np.modf(-0.5) ``` -------------------------------- ### Meson Build Commands Source: https://numpy.org/doc/stable/f2py/buildtools/meson.html Commands to set up and compile the project using Meson. ```bash meson setup builddir meson compile -C builddir ``` -------------------------------- ### Get Iterator Index Range Source: https://numpy.org/doc/stable/reference/c-api/iterator.html Retrieves the start and end indices (`istart`, `iend`) that define the current iteration range for the iterator. ```c void NpyIter_GetIterIndexRange(NpyIter *iter, npy_intp *istart, npy_intp *iend); ``` -------------------------------- ### Old distutils Workflow: Build Wheel Source: https://numpy.org/doc/stable/building/distutils_equivalents.html Builds a wheel distribution in the current environment for installation. ```bash python setup.py bdist_wheel ``` -------------------------------- ### Baseline Fibonacci Fortran Subroutine Source: https://numpy.org/doc/stable/f2py/buildtools/distutils-to-meson.html A basic Fortran subroutine to generate a Fibonacci series. This serves as a starting point for migration examples. ```fortran subroutine fib(a, n) use iso_c_binding integer(c_int), intent(in) :: n integer(c_int), intent(out) :: a(n) do i = 1, n if (i .eq. 1) then a(i) = 0.0d0 elseif (i .eq. 2) then a(i) = 1.0d0 else a(i) = a(i - 1) + a(i - 2) end if end do end ``` -------------------------------- ### Import numpy and set print options Source: https://numpy.org/doc/stable/reference/generated/numpy.emath.arcsin.html Imports the numpy library and sets the print options for floating-point precision. This is a common setup for numerical examples. ```python import numpy as np np.set_printoptions(precision=4) ``` -------------------------------- ### Building and Running Cython Extension Source: https://numpy.org/doc/stable/user/c-info.python-as-glue.html Command-line instructions to build, install, and execute a function from a Cython extension module. Demonstrates the integration of the compiled extension into a Python environment. ```bash $ pip install . $ python -c "from my_module_with_extension import say_hello; say_hello()" "Hello!" ``` -------------------------------- ### Return Indices of Intersection Source: https://numpy.org/doc/stable/reference/generated/numpy.intersect1d.html This example shows how to use the return_indices=True argument in numpy.intersect1d to get the indices of the common elements in the original arrays, along with the intersected values themselves. ```python x = np.array([1, 1, 2, 3, 4]) y = np.array([2, 1, 4, 6]) xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True) x_ind, y_ind (array([0, 2, 4]), array([1, 0, 2])) xy, x[x_ind], y[y_ind] (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4])) ``` -------------------------------- ### Implementing Setup and Teardown Methods Source: https://numpy.org/doc/stable/reference/testing.html Define `setup` and `teardown` methods within a test class to manage resources and state before and after each test. This approach is thread-safe and recommended for explicit control. ```python class TestMe: def setup(self): print('doing setup') return 1 def teardown(self): print('doing teardown') def test_xyz(self): x = self.setup() assert x == 1 self.teardown() ``` -------------------------------- ### Get Number of Elements Along a Specific Axis Source: https://numpy.org/doc/stable/reference/generated/numpy.size.html Specify the 'axis' argument to count elements along that particular dimension. For example, axis=1 counts elements in each row. ```python >>> np.size(a,axis=1) 3 ``` -------------------------------- ### Example Build Report for x86_64/gcc Source: https://numpy.org/doc/stable/reference/simd/build-options.html This is an example of a build report log on x86_64 with gcc, showing the enabled CPU features for baseline and dispatch optimizations, and the generated multi-targets for various dispatch headers. ```text Test features "X86_V2" : Supported Test features "X86_V3" : Supported Test features "X86_V4" : Supported Test features "AVX512_ICL" : Supported Test features "AVX512_SPR" : Supported Configuring npy_cpu_dispatch_config.h using configuration Message: CPU Optimization Options baseline: Requested : min Enabled : X86_V2 dispatch: Requested : max Enabled : X86_V3 X86_V4 AVX512_ICL AVX512_SPR Generating multi-targets for "_umath_tests.dispatch.h" Enabled targets: X86_V3, baseline Generating multi-targets for "argfunc.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "x86_simd_argsort.dispatch.h" Enabled targets: X86_V4, X86_V3 Generating multi-targets for "x86_simd_qsort.dispatch.h" Enabled targets: X86_V4, X86_V3 Generating multi-targets for "x86_simd_qsort_16bit.dispatch.h" Enabled targets: AVX512_SPR, AVX512_ICL Generating multi-targets for "highway_qsort.dispatch.h" Enabled targets: Generating multi-targets for "highway_qsort_16bit.dispatch.h" Enabled targets: Generating multi-targets for "loops_arithm_fp.dispatch.h" Enabled targets: X86_V3, baseline Generating multi-targets for "loops_arithmetic.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_comparison.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_exponent_log.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_hyperbolic.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_logical.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_minmax.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_modulo.dispatch.h" Enabled targets: baseline Generating multi-targets for "loops_trigonometric.dispatch.h" Enabled targets: X86_V4, X86_V3, baseline Generating multi-targets for "loops_umath_fp.dispatch.h" Enabled targets: X86_V4, baseline Generating multi-targets for "loops_unary.dispatch.h" Enabled targets: X86_V4, baseline Generating multi-targets for "loops_unary_fp.dispatch.h" Enabled targets: baseline Generating multi-targets for "loops_unary_fp_le.dispatch.h" Enabled targets: baseline Generating multi-targets for "loops_unary_complex.dispatch.h" Enabled targets: X86_V3, baseline Generating multi-targets for "loops_autovec.dispatch.h" Enabled targets: X86_V3, baseline Generating multi-targets for "loops_half.dispatch.h" Enabled targets: AVX512_SPR, X86_V4, baseline WARNING: Project targets '>=1.5.2' but uses feature deprecated since '1.3.0': Source file src/umath/svml/linux/avx512/svml_z0_acos_d_la.s in the 'objects' kwarg is not an object.. Generating multi-targets for "_simd.dispatch.h" Enabled targets: X86_V3, X86_V4, baseline ``` -------------------------------- ### Get indices of non-zero elements ignoring masked values Source: https://numpy.org/doc/stable/reference/generated/numpy.ma.MaskedArray.nonzero.html This example shows how `nonzero` ignores masked elements. When an element is masked, it is not included in the returned indices, even if it is non-zero. ```python x[1, 1] = ma.masked x.nonzero() ``` -------------------------------- ### Dispatchable Source Example Source: https://numpy.org/doc/stable/reference/simd/how-it-works.html An example of a dispatchable C source file (`hello.dispatch.c`) that uses macros for CPU target identification and conditional compilation. It includes definitions for `CURRENT_TARGET` and `NPY__CPU_TARGET_CURRENT` to handle baseline and optimized builds. ```c // hello.dispatch.c /*@targets baseline sse42 avx512f */ #include #include "numpy/utils.h" // NPY_CAT, NPY_TOSTR #ifndef NPY__CPU_TARGET_CURRENT // wrapping the dispatch-able source only happens to the additional optimizations // but if the keyword 'baseline' provided within the configuration statements, // the infrastructure will add extra compiling for the dispatch-able source by // passing it as-is to the compiler without any changes. #define CURRENT_TARGET(X) X #define NPY__CPU_TARGET_CURRENT baseline // for printing only #else // since we reach to this point, that's mean we're dealing with // the additional optimizations, so it could be SSE42 or AVX512F #define CURRENT_TARGET(X) NPY_CAT(NPY_CAT(X, _), NPY__CPU_TARGET_CURRENT) #endif // Macro 'CURRENT_TARGET' adding the current target as suffix to the exported symbols, // to avoid linking duplications, NumPy already has a macro called // 'NPY_CPU_DISPATCH_CURFX' similar to it, located at // numpy/numpy/_core/src/common/npy_cpu_dispatch.h // NOTE: we tend to not adding suffixes to the baseline exported symbols void CURRENT_TARGET(simd_whoami)(const char *extra_info) { printf("I'm " NPY_TOSTR(NPY__CPU_TARGET_CURRENT) ", %s\n", extra_info); } ``` -------------------------------- ### Importing and Instantiating Polynomial Source: https://numpy.org/doc/stable/reference/routines.polynomials.classes.html Demonstrates how to import the Polynomial class and create an instance with given coefficients. Shows the default representation including coefficients, domain, and window. ```python >>> from numpy.polynomial import Polynomial as P >>> p = P([1,2,3]) >>> p Polynomial([1., 2., 3.], domain=[-1., 1.], window=[-1., 1.], symbol='x') ``` -------------------------------- ### Create a NumPy array view from a PyTorch tensor Source: https://numpy.org/doc/stable/reference/generated/numpy.from_dlpack.html This example demonstrates how to create a NumPy array that views the memory of a PyTorch tensor using `numpy.from_dlpack`. Ensure PyTorch is installed and imported. ```python import torch import numpy as np x = torch.arange(10) # create a view of the torch tensor "x" in NumPy y = np.from_dlpack(x) ``` -------------------------------- ### Editable Install with Meson-Python Source: https://numpy.org/doc/stable/f2py/buildtools/meson-python.html Use this command for an editable install during development. It requires meson-python, meson, ninja, and numpy to be pre-installed and reuses the current environment. ```bash pip install --no-build-isolation --editable . ``` -------------------------------- ### Get indices of non-zero elements in a flattened array Source: https://numpy.org/doc/stable/reference/generated/numpy.flatnonzero.html This example demonstrates how to use numpy.flatnonzero to find the indices of non-zero elements in a flattened array. The function returns a 1-D array of these indices. ```python import numpy as np x = np.arange(-2, 3) x array([-2, -1, 0, 1, 2]) np.flatnonzero(x) array([0, 1, 3, 4]) ``` -------------------------------- ### numpy.pad Examples Source: https://numpy.org/doc/stable/reference/generated/numpy.pad.html Demonstrates various ways to use numpy.pad with different padding types and configurations. ```APIDOC ## numpy.pad ### Description Pads an array with values. This function supports various padding modes including constant, edge, mean, median, minimum, maximum, reflect, symmetric, and wrap. It also allows for custom padding functions. ### Parameters * **array** (array_like) - The input array to pad. * **pad_width** (int, tuple of ints, or dict) - Number of padded values to add before and after each axis. * **mode** (str, optional) - The padding mode. Defaults to 'constant'. * ****kwargs - Additional keyword arguments for specific padding modes. ### Examples #### Constant Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'constant', constant_values=(0, 0)) array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0]) ``` #### Mean Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2,), 'mean') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) ``` #### Median Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2,), 'median') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) ``` #### Minimum Padding ```python >>> a = [[1, 2], [3, 4]] >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') array([[1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [3, 3, 3, 4, 3, 3, 3], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1]]) ``` #### Reflect Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect') array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) ``` #### Reflect Padding with Odd Type ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) ``` #### Symmetric Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'symmetric') array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) ``` #### Symmetric Padding with Odd Type ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) ``` #### Wrap Padding ```python >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'wrap') array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) ``` #### Custom Padding Function ```python def pad_with(vector, pad_width, iaxis, kwargs): pad_value = kwargs.get('padder', 10) vector[:pad_width[0]] = pad_value vector[-pad_width[1]:] = pad_value >>> a = np.arange(6) >>> a = a.reshape((2, 3)) >>> np.pad(a, 2, pad_with) array([[10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 0, 1, 2, 10, 10], [10, 10, 3, 4, 5, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10]]) >>> np.pad(a, 2, pad_with, padder=100) array([[100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 0, 1, 2, 100, 100], [100, 100, 3, 4, 5, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100]]) ``` #### Dictionary-based Padding ```python >>> a = np.arange(1, 7).reshape(2, 3) >>> np.pad(a, {1: (1, 2)}) array([[0, 1, 2, 3, 0, 0], [0, 4, 5, 6, 0, 0]]) >>> np.pad(a, {-1: 2}) array([[0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0]]) >>> np.pad(a, {0: (3, 0)}) array([[0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3], [4, 5, 6]]) >>> np.pad(a, {0: (3, 0), 1: 2}) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0]]) ``` ``` -------------------------------- ### Build Wheel with Meson Native File Source: https://numpy.org/doc/stable/f2py/buildtools/meson-python.html Builds a wheel distribution using a specified Meson native file for compiler configuration. The native file path is passed via setup-args. ```bash python -m build --wheel -Csetup-args="--native-file=native.ini" ``` -------------------------------- ### Setuptools Build Configuration for NumPy ufunc Source: https://numpy.org/doc/stable/user/c-info.ufunc-tutorial.html This configuration uses Setuptools to build a NumPy extension module. It lists the C source file and includes NumPy's header directory for compilation. ```toml [project] name = "npufunc" dependencies = ["numpy"] version = "0.1" [build-system] requires = ["setuptools", "numpy"] build-backend = "setuptools.build_meta" ``` ```python from setuptools import setup, Extension from numpy import get_include npufunc = Extension('npufunc', sources=['single_type_logit.c'], include_dirs=[get_include()]) setup(name='npufunc', version='1.0', ext_modules=[npufunc]) ``` -------------------------------- ### Using k parameter with numpy.triu_indices_from Source: https://numpy.org/doc/stable/reference/generated/numpy.triu_indices_from.html Illustrates how to use the 'k' parameter with numpy.triu_indices_from to get indices for the upper triangular array starting from a specific diagonal (k=1 in this case). The code then extracts these elements. ```python a = np.arange(16).reshape(4, 4) triuim1 = np.triu_indices_from(a, k=1) print(a[triuim1]) ``` -------------------------------- ### Check for prefix within a specific range Source: https://numpy.org/doc/stable/reference/generated/numpy.strings.startswith.html This example demonstrates using `numpy.strings.startswith` with `start` and `end` parameters to check for a prefix within a specified slice of each string. This allows for more granular string matching. ```python import numpy as np s = np.array(['foo', 'bar']) np.strings.startswith(s, 'o', start=1, end=2) array([ True, False]) ``` -------------------------------- ### Create a pkg-config File for Nonstandard Libraries Source: https://numpy.org/doc/stable/building/blas_lapack.html Craft a pkg-config file to help Meson discover BLAS/LAPACK libraries located in nonstandard paths. This involves defining library directories, include paths, and linker flags. ```ini libdir=/path/to/library-dir # e.g., /a/random/path/lib includedir=/path/to/include-dir # e.g., /a/random/path/include version=1.2.3 # set to actual version extralib=-lm -lpthread -lgfortran # if needed, the flags to link in dependencies Name: armpl_lp64 Description: ArmPL - Arm Performance Libraries Version: ${version} Libs: -L${libdir} -larmpl_lp64 # linker flags Libs.private: ${extralib} Cflags: -I${includedir} ``` -------------------------------- ### Apply numpy.positive to an array Source: https://numpy.org/doc/stable/reference/generated/numpy.positive.html This example demonstrates how to use `np.positive` to get the element-wise positive of an array. It shows that `np.positive` returns the same values for positive and negative numbers, effectively returning the original values. ```python import numpy as np x1 = np.array(([1., -1.])) np.positive(x1) ``` -------------------------------- ### Meson Configure Stage Source: https://numpy.org/doc/stable/building/understanding_meson.html Configures the build by detecting compilers and dependencies, creating a build directory, and generating the build.ninja file. The build artifacts are placed in 'build/' and a local install under 'build-install/'. ```bash meson setup build --prefix=$PWD/build-install ``` -------------------------------- ### Get item size of NumPy array elements Source: https://numpy.org/doc/stable/reference/generated/numpy.matrix.itemsize.html Demonstrates how to use the `itemsize` attribute to find the size in bytes of elements in a NumPy array. Shows examples with float64 and complex128 data types. ```python import numpy as np x = np.array([1,2,3], dtype=np.float64) x.itemsize ``` ```python x = np.array([1,2,3], dtype=np.complex128) x.itemsize ``` -------------------------------- ### Generated Configuration Header Example Source: https://numpy.org/doc/stable/reference/simd/how-it-works.html An example of a generated configuration header (`hello.dispatch.h`) that defines macros for CPU feature checking and dispatching. It includes definitions for `NPY__CPU_DISPATCH_EXPAND_`, `NPY__CPU_DISPATCH_BASELINE_CALL`, and `NPY__CPU_DISPATCH_CALL`. ```c #ifndef NPY__CPU_DISPATCH_EXPAND_ // To expand the macro calls in this header #define NPY__CPU_DISPATCH_EXPAND_(X) X #endif // Undefining the following macros, due to the possibility of including config headers // multiple times within the same source and since each config header represents // different required optimizations according to the specified configuration // statements in the dispatch-able source that derived from it. #undef NPY__CPU_DISPATCH_BASELINE_CALL #undef NPY__CPU_DISPATCH_CALL // nothing strange here, just a normal preprocessor callback // enabled only if 'baseline' specified within the configuration statements #define NPY__CPU_DISPATCH_BASELINE_CALL(CB, ...) \ NPY__CPU_DISPATCH_EXPAND_(CB(__VA_ARGS__)) // 'NPY__CPU_DISPATCH_CALL' is an abstract macro is used for dispatching // the required optimizations that specified within the configuration statements. // // @param CHK, Expected a macro that can be used to detect CPU features // in runtime, which takes a CPU feature name without string quotes and // returns the testing result in a shape of boolean value. // NumPy already has macro called "NPY_CPU_HAVE", which fits this requirement. // // @param CB, a callback macro that expected to be called multiple times depending // on the required optimizations, the callback should receive the following arguments: // 1- The pending calls of @param CHK filled up with the required CPU features, // that need to be tested first in runtime before executing call belong to // the compiled object. // 2- The required optimization name, same as in 'NPY__CPU_TARGET_CURRENT' // 3- Extra arguments in the macro itself // // By default the callback calls are sorted depending on the highest interest // unless the policy "$keep_sort" was in place within the configuration statements // see "Dive into the CPU dispatcher" for more clarification. #define NPY__CPU_DISPATCH_CALL(CHK, CB, ...) \ NPY__CPU_DISPATCH_EXPAND_(CB((CHK(AVX512F)), AVX512F, __VA_ARGS__)) \ NPY__CPU_DISPATCH_EXPAND_(CB((CHK(SSE)&&CHK(SSE2)&&CHK(SSE3)&&CHK(SSSE3)&&CHK(SSE41)), SSE41, __VA_ARGS__)) ``` -------------------------------- ### Create and Plot Band-Limited Image Source: https://numpy.org/doc/stable/reference/generated/numpy.fft.ifftn.html This example demonstrates creating an image with band-limited frequency content and visualizing it. It involves creating a complex array, applying `ifftn` to get the real part of the image, and then plotting it. ```python import matplotlib.pyplot as plt n = np.zeros((200,200), dtype=np.complex128) n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) im = np.fft.ifftn(n).real plt.imshow(im) plt.show() ``` -------------------------------- ### Prepend and append values to differences Source: https://numpy.org/doc/stable/reference/generated/numpy.ediff1d.html This example shows how to use the `to_begin` and `to_end` parameters of numpy.ediff1d to add specific values at the start and end of the difference array. This is useful for boundary conditions or specific calculations. ```python import numpy as np x = np.array([1, 2, 4, 7, 0]) np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) ``` -------------------------------- ### Build and Execute Fortran Extension Source: https://numpy.org/doc/stable/f2py/buildtools/skbuild.html Builds a Fortran extension module in-place and demonstrates its usage with NumPy. ```bash ls . # CMakeLists.txt fib1.f pyproject.toml setup.py python setup.py build_ext --inplace python -c "import numpy as np; import fibby.fibby; a = np.zeros(9); fibby.fibby.fib(a); print (a)" # [ 0. 1. 1. 2. 3. 5. 8. 13. 21.] ``` -------------------------------- ### Get Indices of Unique Elements Source: https://numpy.org/doc/stable/reference/generated/numpy.unique.html This example demonstrates how to retrieve the indices of the first occurrences of unique elements in an array using `return_index=True`. The returned indices can be used to access these unique elements directly from the original array. ```python import numpy as np a = np.array(['a', 'b', 'b', 'c', 'a']) u, indices = np.unique(a, return_index=True) print(u) print(indices) print(a[indices]) ``` -------------------------------- ### Partitioning a string array Source: https://numpy.org/doc/stable/reference/generated/numpy.char.partition.html Demonstrates how to use numpy.char.partition to split strings in an array by a space. ```python import numpy as np x = np.array(["Numpy is nice!"]) np.char.partition(x, " ") ``` -------------------------------- ### Count occurrences of a substring in a NumPy array Source: https://numpy.org/doc/stable/reference/generated/numpy.char.count.html This example demonstrates how to count occurrences of a substring within a NumPy array of strings. It shows counting a single character and a multi-character substring. The `start` and `end` parameters can be used to specify a range for the search. ```python import numpy as np c = np.array(['aAaAaA', ' aA ', 'abBABba']) c np.strings.count(c, 'A') np.strings.count(c, 'aA') np.strings.count(c, 'A', start=1, end=4) np.strings.count(c, 'A', start=1, end=3) ``` -------------------------------- ### Build C Library for Numba/CFFI (Windows) Source: https://numpy.org/doc/stable/reference/random/examples/numba_cffi.html Builds a DLL 'distributions.dll' from 'distributions.c' on Windows. Requires specific environment variables for Python home and version, and links against the Python library. ```batch rem PYTHON_HOME and PYTHON_VERSION are setup dependent, this is an example set PYTHON_HOME=c:\Anaconda set PYTHON_VERSION=38 cl.exe /LD .\distributions.c -DDLL_EXPORT \ -I%PYTHON_HOME%\lib\site-packages\numpy\_core\include \ -I%PYTHON_HOME%\include %PYTHON_HOME%\libs\python%PYTHON_VERSION%.lib move distributions.dll ../../_examples/numba/ ``` -------------------------------- ### Using numpy.get_include in setup.py Source: https://numpy.org/doc/stable/reference/generated/numpy.get_include.html This snippet shows how to use numpy.get_include() within a setuptools setup.py file to specify the include directory for NumPy header files when building an extension module. ```python import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ... ``` -------------------------------- ### Create and Copy a NumPy Array Source: https://numpy.org/doc/stable/reference/generated/numpy.char.chararray.copy.html Demonstrates creating a NumPy array with Fortran-order and then creating a copy of it. The original array is then filled with zeros to show that the copy remains unaffected. ```python import numpy as np x = np.array([[1,2,3],[4,5,6]], order='F') ``` ```python y = x.copy() ``` ```python x.fill(0) ``` ```python print(x) ``` ```python print(y) ``` ```python print(y.flags['C_CONTIGUOUS']) ``` -------------------------------- ### Create an array with specified start, stop, and step Source: https://numpy.org/doc/stable/reference/generated/numpy.arange.html Generates an array with values starting from 'start' up to (but not including) 'stop', with a specified interval 'step'. ```python np.arange(3,7,2) ``` -------------------------------- ### show_runtime Source: https://numpy.org/doc/stable/reference/routines.other.html Prints information about system resources and NumPy's runtime environment. ```APIDOC ## show_runtime ### Description Print information about various resources in the system including available intrinsic support and BLAS/LAPACK library in use. ### Method Not applicable (Python function) ### Parameters None ### Request Example ```python numpy.show_runtime() ``` ### Response #### Success Response Prints runtime information to the console. #### Response Example ``` System information: OS: Linux CPU: x86_64 ... (more information) BLAS/LAPACK: Built with: OpenBLAS ... (more information) ``` ``` -------------------------------- ### Create an array with specified start and stop Source: https://numpy.org/doc/stable/reference/generated/numpy.arange.html Generates an array with values starting from 'start' up to (but not including) 'stop', using a default step of 1. ```python np.arange(3,7) ``` -------------------------------- ### Install Apple Developer Tools on macOS Source: https://numpy.org/doc/stable/building/index.html Installs essential development tools for macOS, including Git and Clang compilers, by running the xcode-select --install command. ```bash xcode-select --install ```