numpy 2.4.1__pp311-pypy311_pp73-macosx_14_0_arm64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- numpy/__config__.py +170 -0
- numpy/__config__.pyi +108 -0
- numpy/__init__.cython-30.pxd +1242 -0
- numpy/__init__.pxd +1155 -0
- numpy/__init__.py +942 -0
- numpy/__init__.pyi +6202 -0
- numpy/_array_api_info.py +346 -0
- numpy/_array_api_info.pyi +206 -0
- numpy/_configtool.py +39 -0
- numpy/_configtool.pyi +1 -0
- numpy/_core/__init__.py +201 -0
- numpy/_core/__init__.pyi +666 -0
- numpy/_core/_add_newdocs.py +7151 -0
- numpy/_core/_add_newdocs.pyi +2 -0
- numpy/_core/_add_newdocs_scalars.py +381 -0
- numpy/_core/_add_newdocs_scalars.pyi +16 -0
- numpy/_core/_asarray.py +130 -0
- numpy/_core/_asarray.pyi +43 -0
- numpy/_core/_dtype.py +366 -0
- numpy/_core/_dtype.pyi +56 -0
- numpy/_core/_dtype_ctypes.py +120 -0
- numpy/_core/_dtype_ctypes.pyi +83 -0
- numpy/_core/_exceptions.py +162 -0
- numpy/_core/_exceptions.pyi +54 -0
- numpy/_core/_internal.py +968 -0
- numpy/_core/_internal.pyi +61 -0
- numpy/_core/_methods.py +252 -0
- numpy/_core/_methods.pyi +22 -0
- numpy/_core/_multiarray_tests.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_multiarray_umath.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_operand_flag_tests.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_rational_tests.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_simd.pyi +35 -0
- numpy/_core/_simd.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_string_helpers.py +100 -0
- numpy/_core/_string_helpers.pyi +12 -0
- numpy/_core/_struct_ufunc_tests.pypy311-pp73-darwin.so +0 -0
- numpy/_core/_type_aliases.py +131 -0
- numpy/_core/_type_aliases.pyi +86 -0
- numpy/_core/_ufunc_config.py +515 -0
- numpy/_core/_ufunc_config.pyi +69 -0
- numpy/_core/_umath_tests.pyi +47 -0
- numpy/_core/_umath_tests.pypy311-pp73-darwin.so +0 -0
- numpy/_core/arrayprint.py +1779 -0
- numpy/_core/arrayprint.pyi +158 -0
- numpy/_core/cversions.py +13 -0
- numpy/_core/defchararray.py +1414 -0
- numpy/_core/defchararray.pyi +1150 -0
- numpy/_core/einsumfunc.py +1650 -0
- numpy/_core/einsumfunc.pyi +184 -0
- numpy/_core/fromnumeric.py +4233 -0
- numpy/_core/fromnumeric.pyi +1735 -0
- numpy/_core/function_base.py +547 -0
- numpy/_core/function_base.pyi +276 -0
- numpy/_core/getlimits.py +462 -0
- numpy/_core/getlimits.pyi +124 -0
- numpy/_core/include/numpy/__multiarray_api.c +376 -0
- numpy/_core/include/numpy/__multiarray_api.h +1628 -0
- numpy/_core/include/numpy/__ufunc_api.c +55 -0
- numpy/_core/include/numpy/__ufunc_api.h +349 -0
- numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
- numpy/_core/include/numpy/_numpyconfig.h +33 -0
- numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
- numpy/_core/include/numpy/arrayobject.h +7 -0
- numpy/_core/include/numpy/arrayscalars.h +198 -0
- numpy/_core/include/numpy/dtype_api.h +547 -0
- numpy/_core/include/numpy/halffloat.h +70 -0
- numpy/_core/include/numpy/ndarrayobject.h +304 -0
- numpy/_core/include/numpy/ndarraytypes.h +1982 -0
- numpy/_core/include/numpy/npy_2_compat.h +249 -0
- numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
- numpy/_core/include/numpy/npy_3kcompat.h +374 -0
- numpy/_core/include/numpy/npy_common.h +989 -0
- numpy/_core/include/numpy/npy_cpu.h +126 -0
- numpy/_core/include/numpy/npy_endian.h +79 -0
- numpy/_core/include/numpy/npy_math.h +602 -0
- numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
- numpy/_core/include/numpy/npy_os.h +42 -0
- numpy/_core/include/numpy/numpyconfig.h +185 -0
- numpy/_core/include/numpy/random/LICENSE.txt +21 -0
- numpy/_core/include/numpy/random/bitgen.h +20 -0
- numpy/_core/include/numpy/random/distributions.h +209 -0
- numpy/_core/include/numpy/random/libdivide.h +2079 -0
- numpy/_core/include/numpy/ufuncobject.h +343 -0
- numpy/_core/include/numpy/utils.h +37 -0
- numpy/_core/lib/libnpymath.a +0 -0
- numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
- numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
- numpy/_core/lib/pkgconfig/numpy.pc +7 -0
- numpy/_core/memmap.py +363 -0
- numpy/_core/memmap.pyi +3 -0
- numpy/_core/multiarray.py +1740 -0
- numpy/_core/multiarray.pyi +1316 -0
- numpy/_core/numeric.py +2758 -0
- numpy/_core/numeric.pyi +1276 -0
- numpy/_core/numerictypes.py +633 -0
- numpy/_core/numerictypes.pyi +196 -0
- numpy/_core/overrides.py +188 -0
- numpy/_core/overrides.pyi +47 -0
- numpy/_core/printoptions.py +32 -0
- numpy/_core/printoptions.pyi +28 -0
- numpy/_core/records.py +1088 -0
- numpy/_core/records.pyi +340 -0
- numpy/_core/shape_base.py +996 -0
- numpy/_core/shape_base.pyi +182 -0
- numpy/_core/strings.py +1813 -0
- numpy/_core/strings.pyi +536 -0
- numpy/_core/tests/_locales.py +72 -0
- numpy/_core/tests/_natype.py +144 -0
- numpy/_core/tests/data/astype_copy.pkl +0 -0
- numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
- numpy/_core/tests/data/recarray_from_file.fits +0 -0
- numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
- numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
- numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
- numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
- numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
- numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
- numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
- numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
- numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
- numpy/_core/tests/examples/cython/checks.pyx +373 -0
- numpy/_core/tests/examples/cython/meson.build +43 -0
- numpy/_core/tests/examples/cython/setup.py +39 -0
- numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
- numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
- numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
- numpy/_core/tests/examples/limited_api/meson.build +59 -0
- numpy/_core/tests/examples/limited_api/setup.py +24 -0
- numpy/_core/tests/test__exceptions.py +90 -0
- numpy/_core/tests/test_abc.py +54 -0
- numpy/_core/tests/test_api.py +655 -0
- numpy/_core/tests/test_argparse.py +90 -0
- numpy/_core/tests/test_array_api_info.py +113 -0
- numpy/_core/tests/test_array_coercion.py +928 -0
- numpy/_core/tests/test_array_interface.py +222 -0
- numpy/_core/tests/test_arraymethod.py +84 -0
- numpy/_core/tests/test_arrayobject.py +75 -0
- numpy/_core/tests/test_arrayprint.py +1324 -0
- numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
- numpy/_core/tests/test_casting_unittests.py +955 -0
- numpy/_core/tests/test_conversion_utils.py +209 -0
- numpy/_core/tests/test_cpu_dispatcher.py +48 -0
- numpy/_core/tests/test_cpu_features.py +450 -0
- numpy/_core/tests/test_custom_dtypes.py +393 -0
- numpy/_core/tests/test_cython.py +352 -0
- numpy/_core/tests/test_datetime.py +2792 -0
- numpy/_core/tests/test_defchararray.py +858 -0
- numpy/_core/tests/test_deprecations.py +460 -0
- numpy/_core/tests/test_dlpack.py +190 -0
- numpy/_core/tests/test_dtype.py +2110 -0
- numpy/_core/tests/test_einsum.py +1351 -0
- numpy/_core/tests/test_errstate.py +131 -0
- numpy/_core/tests/test_extint128.py +217 -0
- numpy/_core/tests/test_finfo.py +86 -0
- numpy/_core/tests/test_function_base.py +504 -0
- numpy/_core/tests/test_getlimits.py +171 -0
- numpy/_core/tests/test_half.py +593 -0
- numpy/_core/tests/test_hashtable.py +36 -0
- numpy/_core/tests/test_indexerrors.py +122 -0
- numpy/_core/tests/test_indexing.py +1692 -0
- numpy/_core/tests/test_item_selection.py +167 -0
- numpy/_core/tests/test_limited_api.py +102 -0
- numpy/_core/tests/test_longdouble.py +370 -0
- numpy/_core/tests/test_mem_overlap.py +933 -0
- numpy/_core/tests/test_mem_policy.py +453 -0
- numpy/_core/tests/test_memmap.py +248 -0
- numpy/_core/tests/test_multiarray.py +11008 -0
- numpy/_core/tests/test_multiprocessing.py +55 -0
- numpy/_core/tests/test_multithreading.py +377 -0
- numpy/_core/tests/test_nditer.py +3533 -0
- numpy/_core/tests/test_nep50_promotions.py +287 -0
- numpy/_core/tests/test_numeric.py +4295 -0
- numpy/_core/tests/test_numerictypes.py +650 -0
- numpy/_core/tests/test_overrides.py +800 -0
- numpy/_core/tests/test_print.py +202 -0
- numpy/_core/tests/test_protocols.py +46 -0
- numpy/_core/tests/test_records.py +544 -0
- numpy/_core/tests/test_regression.py +2677 -0
- numpy/_core/tests/test_scalar_ctors.py +203 -0
- numpy/_core/tests/test_scalar_methods.py +328 -0
- numpy/_core/tests/test_scalarbuffer.py +153 -0
- numpy/_core/tests/test_scalarinherit.py +105 -0
- numpy/_core/tests/test_scalarmath.py +1168 -0
- numpy/_core/tests/test_scalarprint.py +403 -0
- numpy/_core/tests/test_shape_base.py +904 -0
- numpy/_core/tests/test_simd.py +1345 -0
- numpy/_core/tests/test_simd_module.py +105 -0
- numpy/_core/tests/test_stringdtype.py +1855 -0
- numpy/_core/tests/test_strings.py +1523 -0
- numpy/_core/tests/test_ufunc.py +3405 -0
- numpy/_core/tests/test_umath.py +4962 -0
- numpy/_core/tests/test_umath_accuracy.py +132 -0
- numpy/_core/tests/test_umath_complex.py +631 -0
- numpy/_core/tests/test_unicode.py +369 -0
- numpy/_core/umath.py +60 -0
- numpy/_core/umath.pyi +232 -0
- numpy/_distributor_init.py +15 -0
- numpy/_distributor_init.pyi +1 -0
- numpy/_expired_attrs_2_0.py +78 -0
- numpy/_expired_attrs_2_0.pyi +61 -0
- numpy/_globals.py +121 -0
- numpy/_globals.pyi +17 -0
- numpy/_pyinstaller/__init__.py +0 -0
- numpy/_pyinstaller/__init__.pyi +0 -0
- numpy/_pyinstaller/hook-numpy.py +36 -0
- numpy/_pyinstaller/hook-numpy.pyi +6 -0
- numpy/_pyinstaller/tests/__init__.py +16 -0
- numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
- numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
- numpy/_pytesttester.py +201 -0
- numpy/_pytesttester.pyi +18 -0
- numpy/_typing/__init__.py +173 -0
- numpy/_typing/_add_docstring.py +153 -0
- numpy/_typing/_array_like.py +106 -0
- numpy/_typing/_char_codes.py +213 -0
- numpy/_typing/_dtype_like.py +114 -0
- numpy/_typing/_extended_precision.py +15 -0
- numpy/_typing/_nbit.py +19 -0
- numpy/_typing/_nbit_base.py +94 -0
- numpy/_typing/_nbit_base.pyi +39 -0
- numpy/_typing/_nested_sequence.py +79 -0
- numpy/_typing/_scalars.py +20 -0
- numpy/_typing/_shape.py +8 -0
- numpy/_typing/_ufunc.py +7 -0
- numpy/_typing/_ufunc.pyi +975 -0
- numpy/_utils/__init__.py +95 -0
- numpy/_utils/__init__.pyi +28 -0
- numpy/_utils/_convertions.py +18 -0
- numpy/_utils/_convertions.pyi +4 -0
- numpy/_utils/_inspect.py +192 -0
- numpy/_utils/_inspect.pyi +70 -0
- numpy/_utils/_pep440.py +486 -0
- numpy/_utils/_pep440.pyi +118 -0
- numpy/char/__init__.py +2 -0
- numpy/char/__init__.pyi +111 -0
- numpy/conftest.py +248 -0
- numpy/core/__init__.py +33 -0
- numpy/core/__init__.pyi +0 -0
- numpy/core/_dtype.py +10 -0
- numpy/core/_dtype.pyi +0 -0
- numpy/core/_dtype_ctypes.py +10 -0
- numpy/core/_dtype_ctypes.pyi +0 -0
- numpy/core/_internal.py +27 -0
- numpy/core/_multiarray_umath.py +57 -0
- numpy/core/_utils.py +21 -0
- numpy/core/arrayprint.py +10 -0
- numpy/core/defchararray.py +10 -0
- numpy/core/einsumfunc.py +10 -0
- numpy/core/fromnumeric.py +10 -0
- numpy/core/function_base.py +10 -0
- numpy/core/getlimits.py +10 -0
- numpy/core/multiarray.py +25 -0
- numpy/core/numeric.py +12 -0
- numpy/core/numerictypes.py +10 -0
- numpy/core/overrides.py +10 -0
- numpy/core/overrides.pyi +7 -0
- numpy/core/records.py +10 -0
- numpy/core/shape_base.py +10 -0
- numpy/core/umath.py +10 -0
- numpy/ctypeslib/__init__.py +13 -0
- numpy/ctypeslib/__init__.pyi +15 -0
- numpy/ctypeslib/_ctypeslib.py +603 -0
- numpy/ctypeslib/_ctypeslib.pyi +236 -0
- numpy/distutils/__init__.py +64 -0
- numpy/distutils/__init__.pyi +4 -0
- numpy/distutils/__pycache__/conv_template.pypy311.pyc +0 -0
- numpy/distutils/_shell_utils.py +87 -0
- numpy/distutils/armccompiler.py +26 -0
- numpy/distutils/ccompiler.py +826 -0
- numpy/distutils/ccompiler_opt.py +2668 -0
- numpy/distutils/checks/cpu_asimd.c +27 -0
- numpy/distutils/checks/cpu_asimddp.c +16 -0
- numpy/distutils/checks/cpu_asimdfhm.c +19 -0
- numpy/distutils/checks/cpu_asimdhp.c +15 -0
- numpy/distutils/checks/cpu_avx.c +20 -0
- numpy/distutils/checks/cpu_avx2.c +20 -0
- numpy/distutils/checks/cpu_avx512_clx.c +22 -0
- numpy/distutils/checks/cpu_avx512_cnl.c +24 -0
- numpy/distutils/checks/cpu_avx512_icl.c +26 -0
- numpy/distutils/checks/cpu_avx512_knl.c +25 -0
- numpy/distutils/checks/cpu_avx512_knm.c +30 -0
- numpy/distutils/checks/cpu_avx512_skx.c +26 -0
- numpy/distutils/checks/cpu_avx512_spr.c +26 -0
- numpy/distutils/checks/cpu_avx512cd.c +20 -0
- numpy/distutils/checks/cpu_avx512f.c +20 -0
- numpy/distutils/checks/cpu_f16c.c +22 -0
- numpy/distutils/checks/cpu_fma3.c +22 -0
- numpy/distutils/checks/cpu_fma4.c +13 -0
- numpy/distutils/checks/cpu_lsx.c +11 -0
- numpy/distutils/checks/cpu_neon.c +19 -0
- numpy/distutils/checks/cpu_neon_fp16.c +11 -0
- numpy/distutils/checks/cpu_neon_vfpv4.c +21 -0
- numpy/distutils/checks/cpu_popcnt.c +32 -0
- numpy/distutils/checks/cpu_rvv.c +13 -0
- numpy/distutils/checks/cpu_sse.c +20 -0
- numpy/distutils/checks/cpu_sse2.c +20 -0
- numpy/distutils/checks/cpu_sse3.c +20 -0
- numpy/distutils/checks/cpu_sse41.c +20 -0
- numpy/distutils/checks/cpu_sse42.c +20 -0
- numpy/distutils/checks/cpu_ssse3.c +20 -0
- numpy/distutils/checks/cpu_sve.c +14 -0
- numpy/distutils/checks/cpu_vsx.c +21 -0
- numpy/distutils/checks/cpu_vsx2.c +13 -0
- numpy/distutils/checks/cpu_vsx3.c +13 -0
- numpy/distutils/checks/cpu_vsx4.c +14 -0
- numpy/distutils/checks/cpu_vx.c +16 -0
- numpy/distutils/checks/cpu_vxe.c +25 -0
- numpy/distutils/checks/cpu_vxe2.c +21 -0
- numpy/distutils/checks/cpu_xop.c +12 -0
- numpy/distutils/checks/extra_avx512bw_mask.c +18 -0
- numpy/distutils/checks/extra_avx512dq_mask.c +16 -0
- numpy/distutils/checks/extra_avx512f_reduce.c +41 -0
- numpy/distutils/checks/extra_vsx3_half_double.c +12 -0
- numpy/distutils/checks/extra_vsx4_mma.c +21 -0
- numpy/distutils/checks/extra_vsx_asm.c +36 -0
- numpy/distutils/checks/test_flags.c +1 -0
- numpy/distutils/command/__init__.py +41 -0
- numpy/distutils/command/autodist.py +148 -0
- numpy/distutils/command/bdist_rpm.py +22 -0
- numpy/distutils/command/build.py +62 -0
- numpy/distutils/command/build_clib.py +469 -0
- numpy/distutils/command/build_ext.py +752 -0
- numpy/distutils/command/build_py.py +31 -0
- numpy/distutils/command/build_scripts.py +49 -0
- numpy/distutils/command/build_src.py +773 -0
- numpy/distutils/command/config.py +516 -0
- numpy/distutils/command/config_compiler.py +126 -0
- numpy/distutils/command/develop.py +15 -0
- numpy/distutils/command/egg_info.py +25 -0
- numpy/distutils/command/install.py +79 -0
- numpy/distutils/command/install_clib.py +40 -0
- numpy/distutils/command/install_data.py +24 -0
- numpy/distutils/command/install_headers.py +25 -0
- numpy/distutils/command/sdist.py +27 -0
- numpy/distutils/conv_template.py +329 -0
- numpy/distutils/core.py +215 -0
- numpy/distutils/cpuinfo.py +683 -0
- numpy/distutils/exec_command.py +315 -0
- numpy/distutils/extension.py +101 -0
- numpy/distutils/fcompiler/__init__.py +1035 -0
- numpy/distutils/fcompiler/absoft.py +158 -0
- numpy/distutils/fcompiler/arm.py +71 -0
- numpy/distutils/fcompiler/compaq.py +120 -0
- numpy/distutils/fcompiler/environment.py +88 -0
- numpy/distutils/fcompiler/fujitsu.py +46 -0
- numpy/distutils/fcompiler/g95.py +42 -0
- numpy/distutils/fcompiler/gnu.py +555 -0
- numpy/distutils/fcompiler/hpux.py +41 -0
- numpy/distutils/fcompiler/ibm.py +97 -0
- numpy/distutils/fcompiler/intel.py +211 -0
- numpy/distutils/fcompiler/lahey.py +45 -0
- numpy/distutils/fcompiler/mips.py +54 -0
- numpy/distutils/fcompiler/nag.py +87 -0
- numpy/distutils/fcompiler/none.py +28 -0
- numpy/distutils/fcompiler/nv.py +53 -0
- numpy/distutils/fcompiler/pathf95.py +33 -0
- numpy/distutils/fcompiler/pg.py +128 -0
- numpy/distutils/fcompiler/sun.py +51 -0
- numpy/distutils/fcompiler/vast.py +52 -0
- numpy/distutils/from_template.py +261 -0
- numpy/distutils/fujitsuccompiler.py +28 -0
- numpy/distutils/intelccompiler.py +106 -0
- numpy/distutils/lib2def.py +116 -0
- numpy/distutils/line_endings.py +77 -0
- numpy/distutils/log.py +111 -0
- numpy/distutils/mingw/gfortran_vs2003_hack.c +6 -0
- numpy/distutils/mingw32ccompiler.py +620 -0
- numpy/distutils/misc_util.py +2484 -0
- numpy/distutils/msvc9compiler.py +63 -0
- numpy/distutils/msvccompiler.py +76 -0
- numpy/distutils/npy_pkg_config.py +441 -0
- numpy/distutils/numpy_distribution.py +17 -0
- numpy/distutils/pathccompiler.py +21 -0
- numpy/distutils/system_info.py +3267 -0
- numpy/distutils/tests/__init__.py +0 -0
- numpy/distutils/tests/test_build_ext.py +74 -0
- numpy/distutils/tests/test_ccompiler_opt.py +808 -0
- numpy/distutils/tests/test_ccompiler_opt_conf.py +176 -0
- numpy/distutils/tests/test_exec_command.py +217 -0
- numpy/distutils/tests/test_fcompiler.py +43 -0
- numpy/distutils/tests/test_fcompiler_gnu.py +55 -0
- numpy/distutils/tests/test_fcompiler_intel.py +30 -0
- numpy/distutils/tests/test_fcompiler_nagfor.py +22 -0
- numpy/distutils/tests/test_from_template.py +44 -0
- numpy/distutils/tests/test_log.py +34 -0
- numpy/distutils/tests/test_mingw32ccompiler.py +47 -0
- numpy/distutils/tests/test_misc_util.py +88 -0
- numpy/distutils/tests/test_npy_pkg_config.py +84 -0
- numpy/distutils/tests/test_shell_utils.py +79 -0
- numpy/distutils/tests/test_system_info.py +334 -0
- numpy/distutils/tests/utilities.py +90 -0
- numpy/distutils/unixccompiler.py +141 -0
- numpy/doc/ufuncs.py +138 -0
- numpy/dtypes.py +41 -0
- numpy/dtypes.pyi +630 -0
- numpy/exceptions.py +246 -0
- numpy/exceptions.pyi +27 -0
- numpy/f2py/__init__.py +86 -0
- numpy/f2py/__init__.pyi +5 -0
- numpy/f2py/__main__.py +5 -0
- numpy/f2py/__version__.py +1 -0
- numpy/f2py/__version__.pyi +1 -0
- numpy/f2py/_backends/__init__.py +9 -0
- numpy/f2py/_backends/__init__.pyi +5 -0
- numpy/f2py/_backends/_backend.py +44 -0
- numpy/f2py/_backends/_backend.pyi +46 -0
- numpy/f2py/_backends/_distutils.py +76 -0
- numpy/f2py/_backends/_distutils.pyi +13 -0
- numpy/f2py/_backends/_meson.py +244 -0
- numpy/f2py/_backends/_meson.pyi +62 -0
- numpy/f2py/_backends/meson.build.template +58 -0
- numpy/f2py/_isocbind.py +62 -0
- numpy/f2py/_isocbind.pyi +13 -0
- numpy/f2py/_src_pyf.py +247 -0
- numpy/f2py/_src_pyf.pyi +28 -0
- numpy/f2py/auxfuncs.py +1004 -0
- numpy/f2py/auxfuncs.pyi +262 -0
- numpy/f2py/capi_maps.py +811 -0
- numpy/f2py/capi_maps.pyi +33 -0
- numpy/f2py/cb_rules.py +665 -0
- numpy/f2py/cb_rules.pyi +17 -0
- numpy/f2py/cfuncs.py +1563 -0
- numpy/f2py/cfuncs.pyi +31 -0
- numpy/f2py/common_rules.py +143 -0
- numpy/f2py/common_rules.pyi +9 -0
- numpy/f2py/crackfortran.py +3725 -0
- numpy/f2py/crackfortran.pyi +266 -0
- numpy/f2py/diagnose.py +149 -0
- numpy/f2py/diagnose.pyi +1 -0
- numpy/f2py/f2py2e.py +788 -0
- numpy/f2py/f2py2e.pyi +74 -0
- numpy/f2py/f90mod_rules.py +269 -0
- numpy/f2py/f90mod_rules.pyi +16 -0
- numpy/f2py/func2subr.py +329 -0
- numpy/f2py/func2subr.pyi +7 -0
- numpy/f2py/rules.py +1629 -0
- numpy/f2py/rules.pyi +41 -0
- numpy/f2py/setup.cfg +3 -0
- numpy/f2py/src/fortranobject.c +1436 -0
- numpy/f2py/src/fortranobject.h +173 -0
- numpy/f2py/symbolic.py +1518 -0
- numpy/f2py/symbolic.pyi +219 -0
- numpy/f2py/tests/__init__.py +16 -0
- numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
- numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
- numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
- numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
- numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
- numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
- numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
- numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
- numpy/f2py/tests/src/block_docstring/foo.f +6 -0
- numpy/f2py/tests/src/callback/foo.f +62 -0
- numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
- numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
- numpy/f2py/tests/src/callback/gh25211.f +10 -0
- numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
- numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
- numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
- numpy/f2py/tests/src/cli/hi77.f +3 -0
- numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
- numpy/f2py/tests/src/common/block.f +11 -0
- numpy/f2py/tests/src/common/gh19161.f90 +10 -0
- numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
- numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
- numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
- numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
- numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
- numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
- numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
- numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
- numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
- numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
- numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
- numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
- numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
- numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
- numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
- numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
- numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
- numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
- numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
- numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
- numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
- numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
- numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
- numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
- numpy/f2py/tests/src/kind/foo.f90 +20 -0
- numpy/f2py/tests/src/mixed/foo.f +5 -0
- numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
- numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
- numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
- numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
- numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
- numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
- numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
- numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
- numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
- numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
- numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
- numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
- numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
- numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
- numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
- numpy/f2py/tests/src/quoted_character/foo.f +14 -0
- numpy/f2py/tests/src/regression/AB.inc +1 -0
- numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
- numpy/f2py/tests/src/regression/datonly.f90 +17 -0
- numpy/f2py/tests/src/regression/f77comments.f +26 -0
- numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
- numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
- numpy/f2py/tests/src/regression/incfile.f90 +5 -0
- numpy/f2py/tests/src/regression/inout.f90 +9 -0
- numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
- numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
- numpy/f2py/tests/src/return_character/foo77.f +45 -0
- numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
- numpy/f2py/tests/src/return_complex/foo77.f +45 -0
- numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
- numpy/f2py/tests/src/return_integer/foo77.f +56 -0
- numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
- numpy/f2py/tests/src/return_logical/foo77.f +56 -0
- numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
- numpy/f2py/tests/src/return_real/foo77.f +45 -0
- numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
- numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
- numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
- numpy/f2py/tests/src/routines/subrout.f +4 -0
- numpy/f2py/tests/src/routines/subrout.pyf +10 -0
- numpy/f2py/tests/src/size/foo.f90 +44 -0
- numpy/f2py/tests/src/string/char.f90 +29 -0
- numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
- numpy/f2py/tests/src/string/gh24008.f +8 -0
- numpy/f2py/tests/src/string/gh24662.f90 +7 -0
- numpy/f2py/tests/src/string/gh25286.f90 +14 -0
- numpy/f2py/tests/src/string/gh25286.pyf +12 -0
- numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
- numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
- numpy/f2py/tests/src/string/string.f +12 -0
- numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
- numpy/f2py/tests/test_abstract_interface.py +26 -0
- numpy/f2py/tests/test_array_from_pyobj.py +678 -0
- numpy/f2py/tests/test_assumed_shape.py +50 -0
- numpy/f2py/tests/test_block_docstring.py +20 -0
- numpy/f2py/tests/test_callback.py +263 -0
- numpy/f2py/tests/test_character.py +641 -0
- numpy/f2py/tests/test_common.py +23 -0
- numpy/f2py/tests/test_crackfortran.py +421 -0
- numpy/f2py/tests/test_data.py +71 -0
- numpy/f2py/tests/test_docs.py +66 -0
- numpy/f2py/tests/test_f2cmap.py +17 -0
- numpy/f2py/tests/test_f2py2e.py +983 -0
- numpy/f2py/tests/test_isoc.py +56 -0
- numpy/f2py/tests/test_kind.py +52 -0
- numpy/f2py/tests/test_mixed.py +35 -0
- numpy/f2py/tests/test_modules.py +83 -0
- numpy/f2py/tests/test_parameter.py +129 -0
- numpy/f2py/tests/test_pyf_src.py +43 -0
- numpy/f2py/tests/test_quoted_character.py +18 -0
- numpy/f2py/tests/test_regression.py +187 -0
- numpy/f2py/tests/test_return_character.py +48 -0
- numpy/f2py/tests/test_return_complex.py +67 -0
- numpy/f2py/tests/test_return_integer.py +55 -0
- numpy/f2py/tests/test_return_logical.py +65 -0
- numpy/f2py/tests/test_return_real.py +109 -0
- numpy/f2py/tests/test_routines.py +29 -0
- numpy/f2py/tests/test_semicolon_split.py +75 -0
- numpy/f2py/tests/test_size.py +45 -0
- numpy/f2py/tests/test_string.py +100 -0
- numpy/f2py/tests/test_symbolic.py +500 -0
- numpy/f2py/tests/test_value_attrspec.py +15 -0
- numpy/f2py/tests/util.py +442 -0
- numpy/f2py/use_rules.py +99 -0
- numpy/f2py/use_rules.pyi +9 -0
- numpy/fft/__init__.py +213 -0
- numpy/fft/__init__.pyi +38 -0
- numpy/fft/_helper.py +235 -0
- numpy/fft/_helper.pyi +44 -0
- numpy/fft/_pocketfft.py +1693 -0
- numpy/fft/_pocketfft.pyi +137 -0
- numpy/fft/_pocketfft_umath.pypy311-pp73-darwin.so +0 -0
- numpy/fft/tests/__init__.py +0 -0
- numpy/fft/tests/test_helper.py +167 -0
- numpy/fft/tests/test_pocketfft.py +589 -0
- numpy/lib/__init__.py +97 -0
- numpy/lib/__init__.pyi +52 -0
- numpy/lib/_array_utils_impl.py +62 -0
- numpy/lib/_array_utils_impl.pyi +10 -0
- numpy/lib/_arraypad_impl.py +926 -0
- numpy/lib/_arraypad_impl.pyi +88 -0
- numpy/lib/_arraysetops_impl.py +1158 -0
- numpy/lib/_arraysetops_impl.pyi +462 -0
- numpy/lib/_arrayterator_impl.py +224 -0
- numpy/lib/_arrayterator_impl.pyi +45 -0
- numpy/lib/_datasource.py +700 -0
- numpy/lib/_datasource.pyi +30 -0
- numpy/lib/_format_impl.py +1036 -0
- numpy/lib/_format_impl.pyi +56 -0
- numpy/lib/_function_base_impl.py +5760 -0
- numpy/lib/_function_base_impl.pyi +2324 -0
- numpy/lib/_histograms_impl.py +1085 -0
- numpy/lib/_histograms_impl.pyi +40 -0
- numpy/lib/_index_tricks_impl.py +1048 -0
- numpy/lib/_index_tricks_impl.pyi +267 -0
- numpy/lib/_iotools.py +900 -0
- numpy/lib/_iotools.pyi +116 -0
- numpy/lib/_nanfunctions_impl.py +2006 -0
- numpy/lib/_nanfunctions_impl.pyi +48 -0
- numpy/lib/_npyio_impl.py +2583 -0
- numpy/lib/_npyio_impl.pyi +299 -0
- numpy/lib/_polynomial_impl.py +1465 -0
- numpy/lib/_polynomial_impl.pyi +338 -0
- numpy/lib/_scimath_impl.py +642 -0
- numpy/lib/_scimath_impl.pyi +93 -0
- numpy/lib/_shape_base_impl.py +1289 -0
- numpy/lib/_shape_base_impl.pyi +236 -0
- numpy/lib/_stride_tricks_impl.py +582 -0
- numpy/lib/_stride_tricks_impl.pyi +73 -0
- numpy/lib/_twodim_base_impl.py +1201 -0
- numpy/lib/_twodim_base_impl.pyi +408 -0
- numpy/lib/_type_check_impl.py +710 -0
- numpy/lib/_type_check_impl.pyi +348 -0
- numpy/lib/_ufunclike_impl.py +199 -0
- numpy/lib/_ufunclike_impl.pyi +60 -0
- numpy/lib/_user_array_impl.py +310 -0
- numpy/lib/_user_array_impl.pyi +226 -0
- numpy/lib/_utils_impl.py +784 -0
- numpy/lib/_utils_impl.pyi +22 -0
- numpy/lib/_version.py +153 -0
- numpy/lib/_version.pyi +17 -0
- numpy/lib/array_utils.py +7 -0
- numpy/lib/array_utils.pyi +6 -0
- numpy/lib/format.py +24 -0
- numpy/lib/format.pyi +24 -0
- numpy/lib/introspect.py +94 -0
- numpy/lib/introspect.pyi +3 -0
- numpy/lib/mixins.py +180 -0
- numpy/lib/mixins.pyi +78 -0
- numpy/lib/npyio.py +1 -0
- numpy/lib/npyio.pyi +5 -0
- numpy/lib/recfunctions.py +1681 -0
- numpy/lib/recfunctions.pyi +444 -0
- numpy/lib/scimath.py +13 -0
- numpy/lib/scimath.pyi +12 -0
- numpy/lib/stride_tricks.py +1 -0
- numpy/lib/stride_tricks.pyi +4 -0
- numpy/lib/tests/__init__.py +0 -0
- numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
- numpy/lib/tests/data/py2-objarr.npy +0 -0
- numpy/lib/tests/data/py2-objarr.npz +0 -0
- numpy/lib/tests/data/py3-objarr.npy +0 -0
- numpy/lib/tests/data/py3-objarr.npz +0 -0
- numpy/lib/tests/data/python3.npy +0 -0
- numpy/lib/tests/data/win64python2.npy +0 -0
- numpy/lib/tests/test__datasource.py +328 -0
- numpy/lib/tests/test__iotools.py +358 -0
- numpy/lib/tests/test__version.py +64 -0
- numpy/lib/tests/test_array_utils.py +32 -0
- numpy/lib/tests/test_arraypad.py +1427 -0
- numpy/lib/tests/test_arraysetops.py +1302 -0
- numpy/lib/tests/test_arrayterator.py +45 -0
- numpy/lib/tests/test_format.py +1054 -0
- numpy/lib/tests/test_function_base.py +4750 -0
- numpy/lib/tests/test_histograms.py +855 -0
- numpy/lib/tests/test_index_tricks.py +693 -0
- numpy/lib/tests/test_io.py +2857 -0
- numpy/lib/tests/test_loadtxt.py +1099 -0
- numpy/lib/tests/test_mixins.py +215 -0
- numpy/lib/tests/test_nanfunctions.py +1438 -0
- numpy/lib/tests/test_packbits.py +376 -0
- numpy/lib/tests/test_polynomial.py +325 -0
- numpy/lib/tests/test_recfunctions.py +1042 -0
- numpy/lib/tests/test_regression.py +231 -0
- numpy/lib/tests/test_shape_base.py +813 -0
- numpy/lib/tests/test_stride_tricks.py +655 -0
- numpy/lib/tests/test_twodim_base.py +559 -0
- numpy/lib/tests/test_type_check.py +473 -0
- numpy/lib/tests/test_ufunclike.py +97 -0
- numpy/lib/tests/test_utils.py +80 -0
- numpy/lib/user_array.py +1 -0
- numpy/lib/user_array.pyi +1 -0
- numpy/linalg/__init__.py +95 -0
- numpy/linalg/__init__.pyi +71 -0
- numpy/linalg/_linalg.py +3657 -0
- numpy/linalg/_linalg.pyi +548 -0
- numpy/linalg/_umath_linalg.pyi +60 -0
- numpy/linalg/_umath_linalg.pypy311-pp73-darwin.so +0 -0
- numpy/linalg/lapack_lite.pyi +143 -0
- numpy/linalg/lapack_lite.pypy311-pp73-darwin.so +0 -0
- numpy/linalg/tests/__init__.py +0 -0
- numpy/linalg/tests/test_deprecations.py +21 -0
- numpy/linalg/tests/test_linalg.py +2442 -0
- numpy/linalg/tests/test_regression.py +182 -0
- numpy/ma/API_CHANGES.txt +135 -0
- numpy/ma/LICENSE +24 -0
- numpy/ma/README.rst +236 -0
- numpy/ma/__init__.py +53 -0
- numpy/ma/__init__.pyi +458 -0
- numpy/ma/core.py +8929 -0
- numpy/ma/core.pyi +3720 -0
- numpy/ma/extras.py +2266 -0
- numpy/ma/extras.pyi +297 -0
- numpy/ma/mrecords.py +762 -0
- numpy/ma/mrecords.pyi +96 -0
- numpy/ma/tests/__init__.py +0 -0
- numpy/ma/tests/test_arrayobject.py +40 -0
- numpy/ma/tests/test_core.py +6008 -0
- numpy/ma/tests/test_deprecations.py +65 -0
- numpy/ma/tests/test_extras.py +1945 -0
- numpy/ma/tests/test_mrecords.py +495 -0
- numpy/ma/tests/test_old_ma.py +939 -0
- numpy/ma/tests/test_regression.py +83 -0
- numpy/ma/tests/test_subclassing.py +469 -0
- numpy/ma/testutils.py +294 -0
- numpy/ma/testutils.pyi +69 -0
- numpy/matlib.py +380 -0
- numpy/matlib.pyi +580 -0
- numpy/matrixlib/__init__.py +12 -0
- numpy/matrixlib/__init__.pyi +3 -0
- numpy/matrixlib/defmatrix.py +1119 -0
- numpy/matrixlib/defmatrix.pyi +218 -0
- numpy/matrixlib/tests/__init__.py +0 -0
- numpy/matrixlib/tests/test_defmatrix.py +455 -0
- numpy/matrixlib/tests/test_interaction.py +360 -0
- numpy/matrixlib/tests/test_masked_matrix.py +240 -0
- numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
- numpy/matrixlib/tests/test_multiarray.py +17 -0
- numpy/matrixlib/tests/test_numeric.py +18 -0
- numpy/matrixlib/tests/test_regression.py +31 -0
- numpy/polynomial/__init__.py +187 -0
- numpy/polynomial/__init__.pyi +31 -0
- numpy/polynomial/_polybase.py +1191 -0
- numpy/polynomial/_polybase.pyi +262 -0
- numpy/polynomial/_polytypes.pyi +501 -0
- numpy/polynomial/chebyshev.py +2001 -0
- numpy/polynomial/chebyshev.pyi +180 -0
- numpy/polynomial/hermite.py +1738 -0
- numpy/polynomial/hermite.pyi +106 -0
- numpy/polynomial/hermite_e.py +1640 -0
- numpy/polynomial/hermite_e.pyi +106 -0
- numpy/polynomial/laguerre.py +1673 -0
- numpy/polynomial/laguerre.pyi +100 -0
- numpy/polynomial/legendre.py +1603 -0
- numpy/polynomial/legendre.pyi +100 -0
- numpy/polynomial/polynomial.py +1625 -0
- numpy/polynomial/polynomial.pyi +109 -0
- numpy/polynomial/polyutils.py +759 -0
- numpy/polynomial/polyutils.pyi +307 -0
- numpy/polynomial/tests/__init__.py +0 -0
- numpy/polynomial/tests/test_chebyshev.py +618 -0
- numpy/polynomial/tests/test_classes.py +613 -0
- numpy/polynomial/tests/test_hermite.py +553 -0
- numpy/polynomial/tests/test_hermite_e.py +554 -0
- numpy/polynomial/tests/test_laguerre.py +535 -0
- numpy/polynomial/tests/test_legendre.py +566 -0
- numpy/polynomial/tests/test_polynomial.py +691 -0
- numpy/polynomial/tests/test_polyutils.py +123 -0
- numpy/polynomial/tests/test_printing.py +557 -0
- numpy/polynomial/tests/test_symbol.py +217 -0
- numpy/py.typed +0 -0
- numpy/random/LICENSE.md +71 -0
- numpy/random/__init__.pxd +14 -0
- numpy/random/__init__.py +213 -0
- numpy/random/__init__.pyi +124 -0
- numpy/random/_bounded_integers.pxd +29 -0
- numpy/random/_bounded_integers.pyi +1 -0
- numpy/random/_bounded_integers.pypy311-pp73-darwin.so +0 -0
- numpy/random/_common.pxd +110 -0
- numpy/random/_common.pyi +16 -0
- numpy/random/_common.pypy311-pp73-darwin.so +0 -0
- numpy/random/_examples/cffi/extending.py +44 -0
- numpy/random/_examples/cffi/parse.py +53 -0
- numpy/random/_examples/cython/extending.pyx +77 -0
- numpy/random/_examples/cython/extending_distributions.pyx +117 -0
- numpy/random/_examples/cython/meson.build +53 -0
- numpy/random/_examples/numba/extending.py +86 -0
- numpy/random/_examples/numba/extending_distributions.py +67 -0
- numpy/random/_generator.pyi +862 -0
- numpy/random/_generator.pypy311-pp73-darwin.so +0 -0
- numpy/random/_mt19937.pyi +27 -0
- numpy/random/_mt19937.pypy311-pp73-darwin.so +0 -0
- numpy/random/_pcg64.pyi +41 -0
- numpy/random/_pcg64.pypy311-pp73-darwin.so +0 -0
- numpy/random/_philox.pyi +36 -0
- numpy/random/_philox.pypy311-pp73-darwin.so +0 -0
- numpy/random/_pickle.py +88 -0
- numpy/random/_pickle.pyi +43 -0
- numpy/random/_sfc64.pyi +25 -0
- numpy/random/_sfc64.pypy311-pp73-darwin.so +0 -0
- numpy/random/bit_generator.pxd +40 -0
- numpy/random/bit_generator.pyi +123 -0
- numpy/random/bit_generator.pypy311-pp73-darwin.so +0 -0
- numpy/random/c_distributions.pxd +119 -0
- numpy/random/lib/libnpyrandom.a +0 -0
- numpy/random/mtrand.pyi +759 -0
- numpy/random/mtrand.pypy311-pp73-darwin.so +0 -0
- numpy/random/tests/__init__.py +0 -0
- numpy/random/tests/data/__init__.py +0 -0
- numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
- numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
- numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
- numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
- numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
- numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
- numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
- numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
- numpy/random/tests/data/philox-testset-1.csv +1001 -0
- numpy/random/tests/data/philox-testset-2.csv +1001 -0
- numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
- numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
- numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
- numpy/random/tests/test_direct.py +595 -0
- numpy/random/tests/test_extending.py +131 -0
- numpy/random/tests/test_generator_mt19937.py +2825 -0
- numpy/random/tests/test_generator_mt19937_regressions.py +221 -0
- numpy/random/tests/test_random.py +1724 -0
- numpy/random/tests/test_randomstate.py +2099 -0
- numpy/random/tests/test_randomstate_regression.py +213 -0
- numpy/random/tests/test_regression.py +175 -0
- numpy/random/tests/test_seed_sequence.py +79 -0
- numpy/random/tests/test_smoke.py +882 -0
- numpy/rec/__init__.py +2 -0
- numpy/rec/__init__.pyi +23 -0
- numpy/strings/__init__.py +2 -0
- numpy/strings/__init__.pyi +97 -0
- numpy/testing/__init__.py +22 -0
- numpy/testing/__init__.pyi +107 -0
- numpy/testing/_private/__init__.py +0 -0
- numpy/testing/_private/__init__.pyi +0 -0
- numpy/testing/_private/extbuild.py +250 -0
- numpy/testing/_private/extbuild.pyi +25 -0
- numpy/testing/_private/utils.py +2830 -0
- numpy/testing/_private/utils.pyi +505 -0
- numpy/testing/overrides.py +84 -0
- numpy/testing/overrides.pyi +10 -0
- numpy/testing/print_coercion_tables.py +207 -0
- numpy/testing/print_coercion_tables.pyi +26 -0
- numpy/testing/tests/__init__.py +0 -0
- numpy/testing/tests/test_utils.py +2123 -0
- numpy/tests/__init__.py +0 -0
- numpy/tests/test__all__.py +10 -0
- numpy/tests/test_configtool.py +51 -0
- numpy/tests/test_ctypeslib.py +383 -0
- numpy/tests/test_lazyloading.py +42 -0
- numpy/tests/test_matlib.py +59 -0
- numpy/tests/test_numpy_config.py +47 -0
- numpy/tests/test_numpy_version.py +54 -0
- numpy/tests/test_public_api.py +807 -0
- numpy/tests/test_reloading.py +76 -0
- numpy/tests/test_scripts.py +48 -0
- numpy/tests/test_warnings.py +79 -0
- numpy/typing/__init__.py +233 -0
- numpy/typing/__init__.pyi +3 -0
- numpy/typing/mypy_plugin.py +200 -0
- numpy/typing/tests/__init__.py +0 -0
- numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
- numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
- numpy/typing/tests/data/fail/array_like.pyi +15 -0
- numpy/typing/tests/data/fail/array_pad.pyi +6 -0
- numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
- numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
- numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
- numpy/typing/tests/data/fail/char.pyi +63 -0
- numpy/typing/tests/data/fail/chararray.pyi +61 -0
- numpy/typing/tests/data/fail/comparisons.pyi +27 -0
- numpy/typing/tests/data/fail/constants.pyi +3 -0
- numpy/typing/tests/data/fail/datasource.pyi +16 -0
- numpy/typing/tests/data/fail/dtype.pyi +17 -0
- numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
- numpy/typing/tests/data/fail/flatiter.pyi +38 -0
- numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
- numpy/typing/tests/data/fail/histograms.pyi +12 -0
- numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
- numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
- numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
- numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
- numpy/typing/tests/data/fail/lib_version.pyi +6 -0
- numpy/typing/tests/data/fail/linalg.pyi +52 -0
- numpy/typing/tests/data/fail/ma.pyi +155 -0
- numpy/typing/tests/data/fail/memmap.pyi +5 -0
- numpy/typing/tests/data/fail/modules.pyi +17 -0
- numpy/typing/tests/data/fail/multiarray.pyi +52 -0
- numpy/typing/tests/data/fail/ndarray.pyi +11 -0
- numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
- numpy/typing/tests/data/fail/nditer.pyi +8 -0
- numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
- numpy/typing/tests/data/fail/npyio.pyi +24 -0
- numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
- numpy/typing/tests/data/fail/random.pyi +62 -0
- numpy/typing/tests/data/fail/rec.pyi +17 -0
- numpy/typing/tests/data/fail/scalars.pyi +86 -0
- numpy/typing/tests/data/fail/shape.pyi +7 -0
- numpy/typing/tests/data/fail/shape_base.pyi +8 -0
- numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
- numpy/typing/tests/data/fail/strings.pyi +52 -0
- numpy/typing/tests/data/fail/testing.pyi +28 -0
- numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
- numpy/typing/tests/data/fail/type_check.pyi +12 -0
- numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
- numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
- numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
- numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
- numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
- numpy/typing/tests/data/mypy.ini +8 -0
- numpy/typing/tests/data/pass/arithmetic.py +614 -0
- numpy/typing/tests/data/pass/array_constructors.py +138 -0
- numpy/typing/tests/data/pass/array_like.py +43 -0
- numpy/typing/tests/data/pass/arrayprint.py +37 -0
- numpy/typing/tests/data/pass/arrayterator.py +28 -0
- numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
- numpy/typing/tests/data/pass/comparisons.py +316 -0
- numpy/typing/tests/data/pass/dtype.py +57 -0
- numpy/typing/tests/data/pass/einsumfunc.py +36 -0
- numpy/typing/tests/data/pass/flatiter.py +26 -0
- numpy/typing/tests/data/pass/fromnumeric.py +272 -0
- numpy/typing/tests/data/pass/index_tricks.py +62 -0
- numpy/typing/tests/data/pass/lib_user_array.py +22 -0
- numpy/typing/tests/data/pass/lib_utils.py +19 -0
- numpy/typing/tests/data/pass/lib_version.py +18 -0
- numpy/typing/tests/data/pass/literal.py +52 -0
- numpy/typing/tests/data/pass/ma.py +199 -0
- numpy/typing/tests/data/pass/mod.py +149 -0
- numpy/typing/tests/data/pass/modules.py +45 -0
- numpy/typing/tests/data/pass/multiarray.py +77 -0
- numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
- numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
- numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
- numpy/typing/tests/data/pass/nditer.py +4 -0
- numpy/typing/tests/data/pass/numeric.py +90 -0
- numpy/typing/tests/data/pass/numerictypes.py +17 -0
- numpy/typing/tests/data/pass/random.py +1498 -0
- numpy/typing/tests/data/pass/recfunctions.py +164 -0
- numpy/typing/tests/data/pass/scalars.py +249 -0
- numpy/typing/tests/data/pass/shape.py +19 -0
- numpy/typing/tests/data/pass/simple.py +170 -0
- numpy/typing/tests/data/pass/ufunc_config.py +64 -0
- numpy/typing/tests/data/pass/ufunclike.py +52 -0
- numpy/typing/tests/data/pass/ufuncs.py +16 -0
- numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
- numpy/typing/tests/data/reveal/arithmetic.pyi +719 -0
- numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
- numpy/typing/tests/data/reveal/array_constructors.pyi +277 -0
- numpy/typing/tests/data/reveal/arraypad.pyi +27 -0
- numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
- numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
- numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
- numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
- numpy/typing/tests/data/reveal/char.pyi +225 -0
- numpy/typing/tests/data/reveal/chararray.pyi +138 -0
- numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
- numpy/typing/tests/data/reveal/constants.pyi +14 -0
- numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
- numpy/typing/tests/data/reveal/datasource.pyi +23 -0
- numpy/typing/tests/data/reveal/dtype.pyi +132 -0
- numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
- numpy/typing/tests/data/reveal/emath.pyi +54 -0
- numpy/typing/tests/data/reveal/fft.pyi +37 -0
- numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
- numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
- numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
- numpy/typing/tests/data/reveal/histograms.pyi +25 -0
- numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
- numpy/typing/tests/data/reveal/lib_function_base.pyi +409 -0
- numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
- numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
- numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
- numpy/typing/tests/data/reveal/linalg.pyi +154 -0
- numpy/typing/tests/data/reveal/ma.pyi +1098 -0
- numpy/typing/tests/data/reveal/matrix.pyi +73 -0
- numpy/typing/tests/data/reveal/memmap.pyi +19 -0
- numpy/typing/tests/data/reveal/mod.pyi +178 -0
- numpy/typing/tests/data/reveal/modules.pyi +51 -0
- numpy/typing/tests/data/reveal/multiarray.pyi +197 -0
- numpy/typing/tests/data/reveal/nbit_base_example.pyi +20 -0
- numpy/typing/tests/data/reveal/ndarray_assignability.pyi +82 -0
- numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
- numpy/typing/tests/data/reveal/ndarray_misc.pyi +246 -0
- numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
- numpy/typing/tests/data/reveal/nditer.pyi +49 -0
- numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
- numpy/typing/tests/data/reveal/npyio.pyi +83 -0
- numpy/typing/tests/data/reveal/numeric.pyi +170 -0
- numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
- numpy/typing/tests/data/reveal/polynomial_polybase.pyi +217 -0
- numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
- numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
- numpy/typing/tests/data/reveal/random.pyi +1546 -0
- numpy/typing/tests/data/reveal/rec.pyi +171 -0
- numpy/typing/tests/data/reveal/scalars.pyi +191 -0
- numpy/typing/tests/data/reveal/shape.pyi +13 -0
- numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
- numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
- numpy/typing/tests/data/reveal/strings.pyi +196 -0
- numpy/typing/tests/data/reveal/testing.pyi +198 -0
- numpy/typing/tests/data/reveal/twodim_base.pyi +225 -0
- numpy/typing/tests/data/reveal/type_check.pyi +67 -0
- numpy/typing/tests/data/reveal/ufunc_config.pyi +29 -0
- numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
- numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
- numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
- numpy/typing/tests/test_isfile.py +38 -0
- numpy/typing/tests/test_runtime.py +110 -0
- numpy/typing/tests/test_typing.py +205 -0
- numpy/version.py +11 -0
- numpy/version.pyi +9 -0
- numpy-2.4.1.dist-info/METADATA +139 -0
- numpy-2.4.1.dist-info/RECORD +1039 -0
- numpy-2.4.1.dist-info/WHEEL +6 -0
- numpy-2.4.1.dist-info/entry_points.txt +13 -0
- numpy-2.4.1.dist-info/licenses/LICENSE.txt +935 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
- numpy-2.4.1.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
- numpy-2.4.1.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
- numpy-2.4.1.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
- numpy-2.4.1.dist-info/licenses/numpy/ma/LICENSE +24 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/LICENSE.md +71 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
- numpy-2.4.1.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
numpy/linalg/_linalg.py
ADDED
|
@@ -0,0 +1,3657 @@
|
|
|
1
|
+
"""Lite version of scipy.linalg.
|
|
2
|
+
|
|
3
|
+
Notes
|
|
4
|
+
-----
|
|
5
|
+
This module is a lite version of the linalg.py module in SciPy which
|
|
6
|
+
contains high-level Python interface to the LAPACK library. The lite
|
|
7
|
+
version only accesses the following LAPACK functions: dgesv, zgesv,
|
|
8
|
+
dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
|
|
9
|
+
zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
|
|
13
|
+
'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',
|
|
14
|
+
'svd', 'svdvals', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond',
|
|
15
|
+
'matrix_rank', 'LinAlgError', 'multi_dot', 'trace', 'diagonal',
|
|
16
|
+
'cross', 'outer', 'tensordot', 'matmul', 'matrix_transpose',
|
|
17
|
+
'matrix_norm', 'vector_norm', 'vecdot']
|
|
18
|
+
|
|
19
|
+
import functools
|
|
20
|
+
import operator
|
|
21
|
+
import warnings
|
|
22
|
+
from typing import Any, NamedTuple
|
|
23
|
+
|
|
24
|
+
from numpy._core import (
|
|
25
|
+
abs,
|
|
26
|
+
add,
|
|
27
|
+
all,
|
|
28
|
+
amax,
|
|
29
|
+
amin,
|
|
30
|
+
argsort,
|
|
31
|
+
array,
|
|
32
|
+
asanyarray,
|
|
33
|
+
asarray,
|
|
34
|
+
atleast_2d,
|
|
35
|
+
cdouble,
|
|
36
|
+
complexfloating,
|
|
37
|
+
count_nonzero,
|
|
38
|
+
cross as _core_cross,
|
|
39
|
+
csingle,
|
|
40
|
+
diagonal as _core_diagonal,
|
|
41
|
+
divide,
|
|
42
|
+
dot,
|
|
43
|
+
double,
|
|
44
|
+
empty,
|
|
45
|
+
empty_like,
|
|
46
|
+
errstate,
|
|
47
|
+
finfo,
|
|
48
|
+
inexact,
|
|
49
|
+
inf,
|
|
50
|
+
intc,
|
|
51
|
+
intp,
|
|
52
|
+
isfinite,
|
|
53
|
+
isnan,
|
|
54
|
+
matmul as _core_matmul,
|
|
55
|
+
matrix_transpose as _core_matrix_transpose,
|
|
56
|
+
moveaxis,
|
|
57
|
+
multiply,
|
|
58
|
+
newaxis,
|
|
59
|
+
object_,
|
|
60
|
+
outer as _core_outer,
|
|
61
|
+
overrides,
|
|
62
|
+
prod,
|
|
63
|
+
reciprocal,
|
|
64
|
+
sign,
|
|
65
|
+
single,
|
|
66
|
+
sort,
|
|
67
|
+
sqrt,
|
|
68
|
+
sum,
|
|
69
|
+
swapaxes,
|
|
70
|
+
tensordot as _core_tensordot,
|
|
71
|
+
trace as _core_trace,
|
|
72
|
+
transpose as _core_transpose,
|
|
73
|
+
vecdot as _core_vecdot,
|
|
74
|
+
zeros,
|
|
75
|
+
)
|
|
76
|
+
from numpy._globals import _NoValue
|
|
77
|
+
from numpy._typing import NDArray
|
|
78
|
+
from numpy._utils import set_module
|
|
79
|
+
from numpy.lib._twodim_base_impl import eye, triu
|
|
80
|
+
from numpy.lib.array_utils import normalize_axis_index, normalize_axis_tuple
|
|
81
|
+
from numpy.linalg import _umath_linalg
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class EigResult(NamedTuple):
|
|
85
|
+
eigenvalues: NDArray[Any]
|
|
86
|
+
eigenvectors: NDArray[Any]
|
|
87
|
+
|
|
88
|
+
class EighResult(NamedTuple):
|
|
89
|
+
eigenvalues: NDArray[Any]
|
|
90
|
+
eigenvectors: NDArray[Any]
|
|
91
|
+
|
|
92
|
+
class QRResult(NamedTuple):
|
|
93
|
+
Q: NDArray[Any]
|
|
94
|
+
R: NDArray[Any]
|
|
95
|
+
|
|
96
|
+
class SlogdetResult(NamedTuple):
|
|
97
|
+
sign: NDArray[Any]
|
|
98
|
+
logabsdet: NDArray[Any]
|
|
99
|
+
|
|
100
|
+
class SVDResult(NamedTuple):
|
|
101
|
+
U: NDArray[Any]
|
|
102
|
+
S: NDArray[Any]
|
|
103
|
+
Vh: NDArray[Any]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
array_function_dispatch = functools.partial(
|
|
107
|
+
overrides.array_function_dispatch, module='numpy.linalg'
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
fortran_int = intc
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@set_module('numpy.linalg')
|
|
115
|
+
class LinAlgError(ValueError):
|
|
116
|
+
"""
|
|
117
|
+
Generic Python-exception-derived object raised by linalg functions.
|
|
118
|
+
|
|
119
|
+
General purpose exception class, derived from Python's ValueError
|
|
120
|
+
class, programmatically raised in linalg functions when a Linear
|
|
121
|
+
Algebra-related condition would prevent further correct execution of the
|
|
122
|
+
function.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
None
|
|
127
|
+
|
|
128
|
+
Examples
|
|
129
|
+
--------
|
|
130
|
+
>>> from numpy import linalg as LA
|
|
131
|
+
>>> LA.inv(np.zeros((2,2)))
|
|
132
|
+
Traceback (most recent call last):
|
|
133
|
+
File "<stdin>", line 1, in <module>
|
|
134
|
+
File "...linalg.py", line 350,
|
|
135
|
+
in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
|
|
136
|
+
File "...linalg.py", line 249,
|
|
137
|
+
in solve
|
|
138
|
+
raise LinAlgError('Singular matrix')
|
|
139
|
+
numpy.linalg.LinAlgError: Singular matrix
|
|
140
|
+
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _raise_linalgerror_singular(err, flag):
|
|
145
|
+
raise LinAlgError("Singular matrix")
|
|
146
|
+
|
|
147
|
+
def _raise_linalgerror_nonposdef(err, flag):
|
|
148
|
+
raise LinAlgError("Matrix is not positive definite")
|
|
149
|
+
|
|
150
|
+
def _raise_linalgerror_eigenvalues_nonconvergence(err, flag):
|
|
151
|
+
raise LinAlgError("Eigenvalues did not converge")
|
|
152
|
+
|
|
153
|
+
def _raise_linalgerror_svd_nonconvergence(err, flag):
|
|
154
|
+
raise LinAlgError("SVD did not converge")
|
|
155
|
+
|
|
156
|
+
def _raise_linalgerror_lstsq(err, flag):
|
|
157
|
+
raise LinAlgError("SVD did not converge in Linear Least Squares")
|
|
158
|
+
|
|
159
|
+
def _raise_linalgerror_qr(err, flag):
|
|
160
|
+
raise LinAlgError("Incorrect argument found while performing "
|
|
161
|
+
"QR factorization")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _makearray(a):
|
|
165
|
+
new = asarray(a)
|
|
166
|
+
wrap = getattr(a, "__array_wrap__", new.__array_wrap__)
|
|
167
|
+
return new, wrap
|
|
168
|
+
|
|
169
|
+
def isComplexType(t):
|
|
170
|
+
return issubclass(t, complexfloating)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
_real_types_map = {single: single,
|
|
174
|
+
double: double,
|
|
175
|
+
csingle: single,
|
|
176
|
+
cdouble: double}
|
|
177
|
+
|
|
178
|
+
_complex_types_map = {single: csingle,
|
|
179
|
+
double: cdouble,
|
|
180
|
+
csingle: csingle,
|
|
181
|
+
cdouble: cdouble}
|
|
182
|
+
|
|
183
|
+
def _realType(t, default=double):
|
|
184
|
+
return _real_types_map.get(t, default)
|
|
185
|
+
|
|
186
|
+
def _complexType(t, default=cdouble):
|
|
187
|
+
return _complex_types_map.get(t, default)
|
|
188
|
+
|
|
189
|
+
def _commonType(*arrays):
|
|
190
|
+
# in lite version, use higher precision (always double or cdouble)
|
|
191
|
+
result_type = single
|
|
192
|
+
is_complex = False
|
|
193
|
+
for a in arrays:
|
|
194
|
+
type_ = a.dtype.type
|
|
195
|
+
if issubclass(type_, inexact):
|
|
196
|
+
if isComplexType(type_):
|
|
197
|
+
is_complex = True
|
|
198
|
+
rt = _realType(type_, default=None)
|
|
199
|
+
if rt is double:
|
|
200
|
+
result_type = double
|
|
201
|
+
elif rt is None:
|
|
202
|
+
# unsupported inexact scalar
|
|
203
|
+
raise TypeError(f"array type {a.dtype.name} is unsupported in linalg")
|
|
204
|
+
else:
|
|
205
|
+
result_type = double
|
|
206
|
+
if is_complex:
|
|
207
|
+
result_type = _complex_types_map[result_type]
|
|
208
|
+
return cdouble, result_type
|
|
209
|
+
else:
|
|
210
|
+
return double, result_type
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _to_native_byte_order(*arrays):
|
|
214
|
+
ret = []
|
|
215
|
+
for arr in arrays:
|
|
216
|
+
if arr.dtype.byteorder not in ('=', '|'):
|
|
217
|
+
ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('=')))
|
|
218
|
+
else:
|
|
219
|
+
ret.append(arr)
|
|
220
|
+
if len(ret) == 1:
|
|
221
|
+
return ret[0]
|
|
222
|
+
else:
|
|
223
|
+
return ret
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _assert_2d(*arrays):
|
|
227
|
+
for a in arrays:
|
|
228
|
+
if a.ndim != 2:
|
|
229
|
+
raise LinAlgError('%d-dimensional array given. Array must be '
|
|
230
|
+
'two-dimensional' % a.ndim)
|
|
231
|
+
|
|
232
|
+
def _assert_stacked_2d(*arrays):
|
|
233
|
+
for a in arrays:
|
|
234
|
+
if a.ndim < 2:
|
|
235
|
+
raise LinAlgError('%d-dimensional array given. Array must be '
|
|
236
|
+
'at least two-dimensional' % a.ndim)
|
|
237
|
+
|
|
238
|
+
def _assert_stacked_square(*arrays):
|
|
239
|
+
for a in arrays:
|
|
240
|
+
try:
|
|
241
|
+
m, n = a.shape[-2:]
|
|
242
|
+
except ValueError:
|
|
243
|
+
raise LinAlgError('%d-dimensional array given. Array must be '
|
|
244
|
+
'at least two-dimensional' % a.ndim)
|
|
245
|
+
if m != n:
|
|
246
|
+
raise LinAlgError('Last 2 dimensions of the array must be square')
|
|
247
|
+
|
|
248
|
+
def _assert_finite(*arrays):
|
|
249
|
+
for a in arrays:
|
|
250
|
+
if not isfinite(a).all():
|
|
251
|
+
raise LinAlgError("Array must not contain infs or NaNs")
|
|
252
|
+
|
|
253
|
+
def _is_empty_2d(arr):
|
|
254
|
+
# check size first for efficiency
|
|
255
|
+
return arr.size == 0 and prod(arr.shape[-2:]) == 0
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def transpose(a):
|
|
259
|
+
"""
|
|
260
|
+
Transpose each matrix in a stack of matrices.
|
|
261
|
+
|
|
262
|
+
Unlike np.transpose, this only swaps the last two axes, rather than all of
|
|
263
|
+
them
|
|
264
|
+
|
|
265
|
+
Parameters
|
|
266
|
+
----------
|
|
267
|
+
a : (...,M,N) array_like
|
|
268
|
+
|
|
269
|
+
Returns
|
|
270
|
+
-------
|
|
271
|
+
aT : (...,N,M) ndarray
|
|
272
|
+
"""
|
|
273
|
+
return swapaxes(a, -1, -2)
|
|
274
|
+
|
|
275
|
+
# Linear equations
|
|
276
|
+
|
|
277
|
+
def _tensorsolve_dispatcher(a, b, axes=None):
|
|
278
|
+
return (a, b)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
@array_function_dispatch(_tensorsolve_dispatcher)
|
|
282
|
+
def tensorsolve(a, b, axes=None):
|
|
283
|
+
"""
|
|
284
|
+
Solve the tensor equation ``a x = b`` for x.
|
|
285
|
+
|
|
286
|
+
It is assumed that all indices of `x` are summed over in the product,
|
|
287
|
+
together with the rightmost indices of `a`, as is done in, for example,
|
|
288
|
+
``tensordot(a, x, axes=x.ndim)``.
|
|
289
|
+
|
|
290
|
+
Parameters
|
|
291
|
+
----------
|
|
292
|
+
a : array_like
|
|
293
|
+
Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
|
|
294
|
+
the shape of that sub-tensor of `a` consisting of the appropriate
|
|
295
|
+
number of its rightmost indices, and must be such that
|
|
296
|
+
``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
|
|
297
|
+
'square').
|
|
298
|
+
b : array_like
|
|
299
|
+
Right-hand tensor, which can be of any shape.
|
|
300
|
+
axes : tuple of ints, optional
|
|
301
|
+
Axes in `a` to reorder to the right, before inversion.
|
|
302
|
+
If None (default), no reordering is done.
|
|
303
|
+
|
|
304
|
+
Returns
|
|
305
|
+
-------
|
|
306
|
+
x : ndarray, shape Q
|
|
307
|
+
|
|
308
|
+
Raises
|
|
309
|
+
------
|
|
310
|
+
LinAlgError
|
|
311
|
+
If `a` is singular or not 'square' (in the above sense).
|
|
312
|
+
|
|
313
|
+
See Also
|
|
314
|
+
--------
|
|
315
|
+
numpy.tensordot, tensorinv, numpy.einsum
|
|
316
|
+
|
|
317
|
+
Examples
|
|
318
|
+
--------
|
|
319
|
+
>>> import numpy as np
|
|
320
|
+
>>> a = np.eye(2*3*4).reshape((2*3, 4, 2, 3, 4))
|
|
321
|
+
>>> rng = np.random.default_rng()
|
|
322
|
+
>>> b = rng.normal(size=(2*3, 4))
|
|
323
|
+
>>> x = np.linalg.tensorsolve(a, b)
|
|
324
|
+
>>> x.shape
|
|
325
|
+
(2, 3, 4)
|
|
326
|
+
>>> np.allclose(np.tensordot(a, x, axes=3), b)
|
|
327
|
+
True
|
|
328
|
+
|
|
329
|
+
"""
|
|
330
|
+
a, wrap = _makearray(a)
|
|
331
|
+
b = asarray(b)
|
|
332
|
+
an = a.ndim
|
|
333
|
+
|
|
334
|
+
if axes is not None:
|
|
335
|
+
allaxes = list(range(an))
|
|
336
|
+
for k in axes:
|
|
337
|
+
allaxes.remove(k)
|
|
338
|
+
allaxes.insert(an, k)
|
|
339
|
+
a = a.transpose(allaxes)
|
|
340
|
+
|
|
341
|
+
oldshape = a.shape[-(an - b.ndim):]
|
|
342
|
+
prod = 1
|
|
343
|
+
for k in oldshape:
|
|
344
|
+
prod *= k
|
|
345
|
+
|
|
346
|
+
if a.size != prod ** 2:
|
|
347
|
+
raise LinAlgError(
|
|
348
|
+
"Input arrays must satisfy the requirement \
|
|
349
|
+
prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])"
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
a = a.reshape(prod, prod)
|
|
353
|
+
b = b.ravel()
|
|
354
|
+
res = wrap(solve(a, b))
|
|
355
|
+
res.shape = oldshape
|
|
356
|
+
return res
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _solve_dispatcher(a, b):
|
|
360
|
+
return (a, b)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
@array_function_dispatch(_solve_dispatcher)
|
|
364
|
+
def solve(a, b):
|
|
365
|
+
"""
|
|
366
|
+
Solve a linear matrix equation, or system of linear scalar equations.
|
|
367
|
+
|
|
368
|
+
Computes the "exact" solution, `x`, of the well-determined, i.e., full
|
|
369
|
+
rank, linear matrix equation `ax = b`.
|
|
370
|
+
|
|
371
|
+
Parameters
|
|
372
|
+
----------
|
|
373
|
+
a : (..., M, M) array_like
|
|
374
|
+
Coefficient matrix.
|
|
375
|
+
b : {(M,), (..., M, K)}, array_like
|
|
376
|
+
Ordinate or "dependent variable" values.
|
|
377
|
+
|
|
378
|
+
Returns
|
|
379
|
+
-------
|
|
380
|
+
x : {(..., M,), (..., M, K)} ndarray
|
|
381
|
+
Solution to the system a x = b. Returned shape is (..., M) if b is
|
|
382
|
+
shape (M,) and (..., M, K) if b is (..., M, K), where the "..." part is
|
|
383
|
+
broadcasted between a and b.
|
|
384
|
+
|
|
385
|
+
Raises
|
|
386
|
+
------
|
|
387
|
+
LinAlgError
|
|
388
|
+
If `a` is singular or not square.
|
|
389
|
+
|
|
390
|
+
See Also
|
|
391
|
+
--------
|
|
392
|
+
scipy.linalg.solve : Similar function in SciPy.
|
|
393
|
+
|
|
394
|
+
Notes
|
|
395
|
+
-----
|
|
396
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
397
|
+
details.
|
|
398
|
+
|
|
399
|
+
The solutions are computed using LAPACK routine ``_gesv``.
|
|
400
|
+
|
|
401
|
+
`a` must be square and of full-rank, i.e., all rows (or, equivalently,
|
|
402
|
+
columns) must be linearly independent; if either is not true, use
|
|
403
|
+
`lstsq` for the least-squares best "solution" of the
|
|
404
|
+
system/equation.
|
|
405
|
+
|
|
406
|
+
.. versionchanged:: 2.0
|
|
407
|
+
|
|
408
|
+
The b array is only treated as a shape (M,) column vector if it is
|
|
409
|
+
exactly 1-dimensional. In all other instances it is treated as a stack
|
|
410
|
+
of (M, K) matrices. Previously b would be treated as a stack of (M,)
|
|
411
|
+
vectors if b.ndim was equal to a.ndim - 1.
|
|
412
|
+
|
|
413
|
+
References
|
|
414
|
+
----------
|
|
415
|
+
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
|
|
416
|
+
FL, Academic Press, Inc., 1980, pg. 22.
|
|
417
|
+
|
|
418
|
+
Examples
|
|
419
|
+
--------
|
|
420
|
+
Solve the system of equations:
|
|
421
|
+
``x0 + 2 * x1 = 1`` and
|
|
422
|
+
``3 * x0 + 5 * x1 = 2``:
|
|
423
|
+
|
|
424
|
+
>>> import numpy as np
|
|
425
|
+
>>> a = np.array([[1, 2], [3, 5]])
|
|
426
|
+
>>> b = np.array([1, 2])
|
|
427
|
+
>>> x = np.linalg.solve(a, b)
|
|
428
|
+
>>> x
|
|
429
|
+
array([-1., 1.])
|
|
430
|
+
|
|
431
|
+
Check that the solution is correct:
|
|
432
|
+
|
|
433
|
+
>>> np.allclose(np.dot(a, x), b)
|
|
434
|
+
True
|
|
435
|
+
|
|
436
|
+
"""
|
|
437
|
+
a, _ = _makearray(a)
|
|
438
|
+
_assert_stacked_square(a)
|
|
439
|
+
b, wrap = _makearray(b)
|
|
440
|
+
t, result_t = _commonType(a, b)
|
|
441
|
+
|
|
442
|
+
# We use the b = (..., M,) logic, only if the number of extra dimensions
|
|
443
|
+
# match exactly
|
|
444
|
+
if b.ndim == 1:
|
|
445
|
+
gufunc = _umath_linalg.solve1
|
|
446
|
+
else:
|
|
447
|
+
gufunc = _umath_linalg.solve
|
|
448
|
+
|
|
449
|
+
signature = 'DD->D' if isComplexType(t) else 'dd->d'
|
|
450
|
+
with errstate(call=_raise_linalgerror_singular, invalid='call',
|
|
451
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
452
|
+
r = gufunc(a, b, signature=signature)
|
|
453
|
+
|
|
454
|
+
return wrap(r.astype(result_t, copy=False))
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _tensorinv_dispatcher(a, ind=None):
|
|
458
|
+
return (a,)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@array_function_dispatch(_tensorinv_dispatcher)
|
|
462
|
+
def tensorinv(a, ind=2):
|
|
463
|
+
"""
|
|
464
|
+
Compute the 'inverse' of an N-dimensional array.
|
|
465
|
+
|
|
466
|
+
The result is an inverse for `a` relative to the tensordot operation
|
|
467
|
+
``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
|
|
468
|
+
``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
|
|
469
|
+
tensordot operation.
|
|
470
|
+
|
|
471
|
+
Parameters
|
|
472
|
+
----------
|
|
473
|
+
a : array_like
|
|
474
|
+
Tensor to 'invert'. Its shape must be 'square', i. e.,
|
|
475
|
+
``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
|
|
476
|
+
ind : int, optional
|
|
477
|
+
Number of first indices that are involved in the inverse sum.
|
|
478
|
+
Must be a positive integer, default is 2.
|
|
479
|
+
|
|
480
|
+
Returns
|
|
481
|
+
-------
|
|
482
|
+
b : ndarray
|
|
483
|
+
`a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
|
|
484
|
+
|
|
485
|
+
Raises
|
|
486
|
+
------
|
|
487
|
+
LinAlgError
|
|
488
|
+
If `a` is singular or not 'square' (in the above sense).
|
|
489
|
+
|
|
490
|
+
See Also
|
|
491
|
+
--------
|
|
492
|
+
numpy.tensordot, tensorsolve
|
|
493
|
+
|
|
494
|
+
Examples
|
|
495
|
+
--------
|
|
496
|
+
>>> import numpy as np
|
|
497
|
+
>>> a = np.eye(4*6).reshape((4, 6, 8, 3))
|
|
498
|
+
>>> ainv = np.linalg.tensorinv(a, ind=2)
|
|
499
|
+
>>> ainv.shape
|
|
500
|
+
(8, 3, 4, 6)
|
|
501
|
+
>>> rng = np.random.default_rng()
|
|
502
|
+
>>> b = rng.normal(size=(4, 6))
|
|
503
|
+
>>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
|
|
504
|
+
True
|
|
505
|
+
|
|
506
|
+
>>> a = np.eye(4*6).reshape((24, 8, 3))
|
|
507
|
+
>>> ainv = np.linalg.tensorinv(a, ind=1)
|
|
508
|
+
>>> ainv.shape
|
|
509
|
+
(8, 3, 24)
|
|
510
|
+
>>> rng = np.random.default_rng()
|
|
511
|
+
>>> b = rng.normal(size=24)
|
|
512
|
+
>>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
|
|
513
|
+
True
|
|
514
|
+
|
|
515
|
+
"""
|
|
516
|
+
a = asarray(a)
|
|
517
|
+
oldshape = a.shape
|
|
518
|
+
prod = 1
|
|
519
|
+
if ind > 0:
|
|
520
|
+
invshape = oldshape[ind:] + oldshape[:ind]
|
|
521
|
+
for k in oldshape[ind:]:
|
|
522
|
+
prod *= k
|
|
523
|
+
else:
|
|
524
|
+
raise ValueError("Invalid ind argument.")
|
|
525
|
+
a = a.reshape(prod, -1)
|
|
526
|
+
ia = inv(a)
|
|
527
|
+
return ia.reshape(*invshape)
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
# Matrix inversion
|
|
531
|
+
|
|
532
|
+
def _unary_dispatcher(a):
|
|
533
|
+
return (a,)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
@array_function_dispatch(_unary_dispatcher)
|
|
537
|
+
def inv(a):
|
|
538
|
+
"""
|
|
539
|
+
Compute the inverse of a matrix.
|
|
540
|
+
|
|
541
|
+
Given a square matrix `a`, return the matrix `ainv` satisfying
|
|
542
|
+
``a @ ainv = ainv @ a = eye(a.shape[0])``.
|
|
543
|
+
|
|
544
|
+
Parameters
|
|
545
|
+
----------
|
|
546
|
+
a : (..., M, M) array_like
|
|
547
|
+
Matrix to be inverted.
|
|
548
|
+
|
|
549
|
+
Returns
|
|
550
|
+
-------
|
|
551
|
+
ainv : (..., M, M) ndarray or matrix
|
|
552
|
+
Inverse of the matrix `a`.
|
|
553
|
+
|
|
554
|
+
Raises
|
|
555
|
+
------
|
|
556
|
+
LinAlgError
|
|
557
|
+
If `a` is not square or inversion fails.
|
|
558
|
+
|
|
559
|
+
See Also
|
|
560
|
+
--------
|
|
561
|
+
scipy.linalg.inv : Similar function in SciPy.
|
|
562
|
+
numpy.linalg.cond : Compute the condition number of a matrix.
|
|
563
|
+
numpy.linalg.svd : Compute the singular value decomposition of a matrix.
|
|
564
|
+
|
|
565
|
+
Notes
|
|
566
|
+
-----
|
|
567
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
568
|
+
details.
|
|
569
|
+
|
|
570
|
+
If `a` is detected to be singular, a `LinAlgError` is raised. If `a` is
|
|
571
|
+
ill-conditioned, a `LinAlgError` may or may not be raised, and results may
|
|
572
|
+
be inaccurate due to floating-point errors.
|
|
573
|
+
|
|
574
|
+
References
|
|
575
|
+
----------
|
|
576
|
+
.. [1] Wikipedia, "Condition number",
|
|
577
|
+
https://en.wikipedia.org/wiki/Condition_number
|
|
578
|
+
|
|
579
|
+
Examples
|
|
580
|
+
--------
|
|
581
|
+
>>> import numpy as np
|
|
582
|
+
>>> from numpy.linalg import inv
|
|
583
|
+
>>> a = np.array([[1., 2.], [3., 4.]])
|
|
584
|
+
>>> ainv = inv(a)
|
|
585
|
+
>>> np.allclose(a @ ainv, np.eye(2))
|
|
586
|
+
True
|
|
587
|
+
>>> np.allclose(ainv @ a, np.eye(2))
|
|
588
|
+
True
|
|
589
|
+
|
|
590
|
+
If a is a matrix object, then the return value is a matrix as well:
|
|
591
|
+
|
|
592
|
+
>>> ainv = inv(np.matrix(a))
|
|
593
|
+
>>> ainv
|
|
594
|
+
matrix([[-2. , 1. ],
|
|
595
|
+
[ 1.5, -0.5]])
|
|
596
|
+
|
|
597
|
+
Inverses of several matrices can be computed at once:
|
|
598
|
+
|
|
599
|
+
>>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
|
|
600
|
+
>>> inv(a)
|
|
601
|
+
array([[[-2. , 1. ],
|
|
602
|
+
[ 1.5 , -0.5 ]],
|
|
603
|
+
[[-1.25, 0.75],
|
|
604
|
+
[ 0.75, -0.25]]])
|
|
605
|
+
|
|
606
|
+
If a matrix is close to singular, the computed inverse may not satisfy
|
|
607
|
+
``a @ ainv = ainv @ a = eye(a.shape[0])`` even if a `LinAlgError`
|
|
608
|
+
is not raised:
|
|
609
|
+
|
|
610
|
+
>>> a = np.array([[2,4,6],[2,0,2],[6,8,14]])
|
|
611
|
+
>>> inv(a) # No errors raised
|
|
612
|
+
array([[-1.12589991e+15, -5.62949953e+14, 5.62949953e+14],
|
|
613
|
+
[-1.12589991e+15, -5.62949953e+14, 5.62949953e+14],
|
|
614
|
+
[ 1.12589991e+15, 5.62949953e+14, -5.62949953e+14]])
|
|
615
|
+
>>> a @ inv(a)
|
|
616
|
+
array([[ 0. , -0.5 , 0. ], # may vary
|
|
617
|
+
[-0.5 , 0.625, 0.25 ],
|
|
618
|
+
[ 0. , 0. , 1. ]])
|
|
619
|
+
|
|
620
|
+
To detect ill-conditioned matrices, you can use `numpy.linalg.cond` to
|
|
621
|
+
compute its *condition number* [1]_. The larger the condition number, the
|
|
622
|
+
more ill-conditioned the matrix is. As a rule of thumb, if the condition
|
|
623
|
+
number ``cond(a) = 10**k``, then you may lose up to ``k`` digits of
|
|
624
|
+
accuracy on top of what would be lost to the numerical method due to loss
|
|
625
|
+
of precision from arithmetic methods.
|
|
626
|
+
|
|
627
|
+
>>> from numpy.linalg import cond
|
|
628
|
+
>>> cond(a)
|
|
629
|
+
np.float64(8.659885634118668e+17) # may vary
|
|
630
|
+
|
|
631
|
+
It is also possible to detect ill-conditioning by inspecting the matrix's
|
|
632
|
+
singular values directly. The ratio between the largest and the smallest
|
|
633
|
+
singular value is the condition number:
|
|
634
|
+
|
|
635
|
+
>>> from numpy.linalg import svd
|
|
636
|
+
>>> sigma = svd(a, compute_uv=False) # Do not compute singular vectors
|
|
637
|
+
>>> sigma.max()/sigma.min()
|
|
638
|
+
8.659885634118668e+17 # may vary
|
|
639
|
+
|
|
640
|
+
"""
|
|
641
|
+
a, wrap = _makearray(a)
|
|
642
|
+
_assert_stacked_square(a)
|
|
643
|
+
t, result_t = _commonType(a)
|
|
644
|
+
|
|
645
|
+
signature = 'D->D' if isComplexType(t) else 'd->d'
|
|
646
|
+
with errstate(call=_raise_linalgerror_singular, invalid='call',
|
|
647
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
648
|
+
ainv = _umath_linalg.inv(a, signature=signature)
|
|
649
|
+
return wrap(ainv.astype(result_t, copy=False))
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _matrix_power_dispatcher(a, n):
|
|
653
|
+
return (a,)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
@array_function_dispatch(_matrix_power_dispatcher)
|
|
657
|
+
def matrix_power(a, n):
|
|
658
|
+
"""
|
|
659
|
+
Raise a square matrix to the (integer) power `n`.
|
|
660
|
+
|
|
661
|
+
For positive integers `n`, the power is computed by repeated matrix
|
|
662
|
+
squarings and matrix multiplications. If ``n == 0``, the identity matrix
|
|
663
|
+
of the same shape as M is returned. If ``n < 0``, the inverse
|
|
664
|
+
is computed and then raised to the ``abs(n)``.
|
|
665
|
+
|
|
666
|
+
.. note:: Stacks of object matrices are not currently supported.
|
|
667
|
+
|
|
668
|
+
Parameters
|
|
669
|
+
----------
|
|
670
|
+
a : (..., M, M) array_like
|
|
671
|
+
Matrix to be "powered".
|
|
672
|
+
n : int
|
|
673
|
+
The exponent can be any integer or long integer, positive,
|
|
674
|
+
negative, or zero.
|
|
675
|
+
|
|
676
|
+
Returns
|
|
677
|
+
-------
|
|
678
|
+
a**n : (..., M, M) ndarray or matrix object
|
|
679
|
+
The return value is the same shape and type as `M`;
|
|
680
|
+
if the exponent is positive or zero then the type of the
|
|
681
|
+
elements is the same as those of `M`. If the exponent is
|
|
682
|
+
negative the elements are floating-point.
|
|
683
|
+
|
|
684
|
+
Raises
|
|
685
|
+
------
|
|
686
|
+
LinAlgError
|
|
687
|
+
For matrices that are not square or that (for negative powers) cannot
|
|
688
|
+
be inverted numerically.
|
|
689
|
+
|
|
690
|
+
Examples
|
|
691
|
+
--------
|
|
692
|
+
>>> import numpy as np
|
|
693
|
+
>>> from numpy.linalg import matrix_power
|
|
694
|
+
>>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
|
|
695
|
+
>>> matrix_power(i, 3) # should = -i
|
|
696
|
+
array([[ 0, -1],
|
|
697
|
+
[ 1, 0]])
|
|
698
|
+
>>> matrix_power(i, 0)
|
|
699
|
+
array([[1, 0],
|
|
700
|
+
[0, 1]])
|
|
701
|
+
>>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
|
|
702
|
+
array([[ 0., 1.],
|
|
703
|
+
[-1., 0.]])
|
|
704
|
+
|
|
705
|
+
Somewhat more sophisticated example
|
|
706
|
+
|
|
707
|
+
>>> q = np.zeros((4, 4))
|
|
708
|
+
>>> q[0:2, 0:2] = -i
|
|
709
|
+
>>> q[2:4, 2:4] = i
|
|
710
|
+
>>> q # one of the three quaternion units not equal to 1
|
|
711
|
+
array([[ 0., -1., 0., 0.],
|
|
712
|
+
[ 1., 0., 0., 0.],
|
|
713
|
+
[ 0., 0., 0., 1.],
|
|
714
|
+
[ 0., 0., -1., 0.]])
|
|
715
|
+
>>> matrix_power(q, 2) # = -np.eye(4)
|
|
716
|
+
array([[-1., 0., 0., 0.],
|
|
717
|
+
[ 0., -1., 0., 0.],
|
|
718
|
+
[ 0., 0., -1., 0.],
|
|
719
|
+
[ 0., 0., 0., -1.]])
|
|
720
|
+
|
|
721
|
+
"""
|
|
722
|
+
a = asanyarray(a)
|
|
723
|
+
_assert_stacked_square(a)
|
|
724
|
+
|
|
725
|
+
try:
|
|
726
|
+
n = operator.index(n)
|
|
727
|
+
except TypeError as e:
|
|
728
|
+
raise TypeError("exponent must be an integer") from e
|
|
729
|
+
|
|
730
|
+
# Fall back on dot for object arrays. Object arrays are not supported by
|
|
731
|
+
# the current implementation of matmul using einsum
|
|
732
|
+
if a.dtype != object:
|
|
733
|
+
fmatmul = matmul
|
|
734
|
+
elif a.ndim == 2:
|
|
735
|
+
fmatmul = dot
|
|
736
|
+
else:
|
|
737
|
+
raise NotImplementedError(
|
|
738
|
+
"matrix_power not supported for stacks of object arrays")
|
|
739
|
+
|
|
740
|
+
if n == 0:
|
|
741
|
+
a = empty_like(a)
|
|
742
|
+
a[...] = eye(a.shape[-2], dtype=a.dtype)
|
|
743
|
+
return a
|
|
744
|
+
|
|
745
|
+
elif n < 0:
|
|
746
|
+
a = inv(a)
|
|
747
|
+
n = abs(n)
|
|
748
|
+
|
|
749
|
+
# short-cuts.
|
|
750
|
+
if n == 1:
|
|
751
|
+
return a
|
|
752
|
+
|
|
753
|
+
elif n == 2:
|
|
754
|
+
return fmatmul(a, a)
|
|
755
|
+
|
|
756
|
+
elif n == 3:
|
|
757
|
+
return fmatmul(fmatmul(a, a), a)
|
|
758
|
+
|
|
759
|
+
# Use binary decomposition to reduce the number of matrix multiplications.
|
|
760
|
+
# Here, we iterate over the bits of n, from LSB to MSB, raise `a` to
|
|
761
|
+
# increasing powers of 2, and multiply into the result as needed.
|
|
762
|
+
z = result = None
|
|
763
|
+
while n > 0:
|
|
764
|
+
z = a if z is None else fmatmul(z, z)
|
|
765
|
+
n, bit = divmod(n, 2)
|
|
766
|
+
if bit:
|
|
767
|
+
result = z if result is None else fmatmul(result, z)
|
|
768
|
+
|
|
769
|
+
return result
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
# Cholesky decomposition
|
|
773
|
+
|
|
774
|
+
def _cholesky_dispatcher(a, /, *, upper=None):
|
|
775
|
+
return (a,)
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
@array_function_dispatch(_cholesky_dispatcher)
|
|
779
|
+
def cholesky(a, /, *, upper=False):
|
|
780
|
+
"""
|
|
781
|
+
Cholesky decomposition.
|
|
782
|
+
|
|
783
|
+
Return the lower or upper Cholesky decomposition, ``L * L.H`` or
|
|
784
|
+
``U.H * U``, of the square matrix ``a``, where ``L`` is lower-triangular,
|
|
785
|
+
``U`` is upper-triangular, and ``.H`` is the conjugate transpose operator
|
|
786
|
+
(which is the ordinary transpose if ``a`` is real-valued). ``a`` must be
|
|
787
|
+
Hermitian (symmetric if real-valued) and positive-definite. No checking is
|
|
788
|
+
performed to verify whether ``a`` is Hermitian or not. In addition, only
|
|
789
|
+
the lower or upper-triangular and diagonal elements of ``a`` are used.
|
|
790
|
+
Only ``L`` or ``U`` is actually returned.
|
|
791
|
+
|
|
792
|
+
Parameters
|
|
793
|
+
----------
|
|
794
|
+
a : (..., M, M) array_like
|
|
795
|
+
Hermitian (symmetric if all elements are real), positive-definite
|
|
796
|
+
input matrix.
|
|
797
|
+
upper : bool
|
|
798
|
+
If ``True``, the result must be the upper-triangular Cholesky factor.
|
|
799
|
+
If ``False``, the result must be the lower-triangular Cholesky factor.
|
|
800
|
+
Default: ``False``.
|
|
801
|
+
|
|
802
|
+
Returns
|
|
803
|
+
-------
|
|
804
|
+
L : (..., M, M) array_like
|
|
805
|
+
Lower or upper-triangular Cholesky factor of `a`. Returns a matrix
|
|
806
|
+
object if `a` is a matrix object.
|
|
807
|
+
|
|
808
|
+
Raises
|
|
809
|
+
------
|
|
810
|
+
LinAlgError
|
|
811
|
+
If the decomposition fails, for example, if `a` is not
|
|
812
|
+
positive-definite.
|
|
813
|
+
|
|
814
|
+
See Also
|
|
815
|
+
--------
|
|
816
|
+
scipy.linalg.cholesky : Similar function in SciPy.
|
|
817
|
+
scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
|
|
818
|
+
positive-definite matrix.
|
|
819
|
+
scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
|
|
820
|
+
`scipy.linalg.cho_solve`.
|
|
821
|
+
|
|
822
|
+
Notes
|
|
823
|
+
-----
|
|
824
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
825
|
+
details.
|
|
826
|
+
|
|
827
|
+
The Cholesky decomposition is often used as a fast way of solving
|
|
828
|
+
|
|
829
|
+
.. math:: A \\mathbf{x} = \\mathbf{b}
|
|
830
|
+
|
|
831
|
+
(when `A` is both Hermitian/symmetric and positive-definite).
|
|
832
|
+
|
|
833
|
+
First, we solve for :math:`\\mathbf{y}` in
|
|
834
|
+
|
|
835
|
+
.. math:: L \\mathbf{y} = \\mathbf{b},
|
|
836
|
+
|
|
837
|
+
and then for :math:`\\mathbf{x}` in
|
|
838
|
+
|
|
839
|
+
.. math:: L^{H} \\mathbf{x} = \\mathbf{y}.
|
|
840
|
+
|
|
841
|
+
Examples
|
|
842
|
+
--------
|
|
843
|
+
>>> import numpy as np
|
|
844
|
+
>>> A = np.array([[1,-2j],[2j,5]])
|
|
845
|
+
>>> A
|
|
846
|
+
array([[ 1.+0.j, -0.-2.j],
|
|
847
|
+
[ 0.+2.j, 5.+0.j]])
|
|
848
|
+
>>> L = np.linalg.cholesky(A)
|
|
849
|
+
>>> L
|
|
850
|
+
array([[1.+0.j, 0.+0.j],
|
|
851
|
+
[0.+2.j, 1.+0.j]])
|
|
852
|
+
>>> np.dot(L, L.T.conj()) # verify that L * L.H = A
|
|
853
|
+
array([[1.+0.j, 0.-2.j],
|
|
854
|
+
[0.+2.j, 5.+0.j]])
|
|
855
|
+
>>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
|
|
856
|
+
>>> np.linalg.cholesky(A) # an ndarray object is returned
|
|
857
|
+
array([[1.+0.j, 0.+0.j],
|
|
858
|
+
[0.+2.j, 1.+0.j]])
|
|
859
|
+
>>> # But a matrix object is returned if A is a matrix object
|
|
860
|
+
>>> np.linalg.cholesky(np.matrix(A))
|
|
861
|
+
matrix([[ 1.+0.j, 0.+0.j],
|
|
862
|
+
[ 0.+2.j, 1.+0.j]])
|
|
863
|
+
>>> # The upper-triangular Cholesky factor can also be obtained.
|
|
864
|
+
>>> np.linalg.cholesky(A, upper=True)
|
|
865
|
+
array([[1.-0.j, 0.-2.j],
|
|
866
|
+
[0.-0.j, 1.-0.j]])
|
|
867
|
+
|
|
868
|
+
"""
|
|
869
|
+
gufunc = _umath_linalg.cholesky_up if upper else _umath_linalg.cholesky_lo
|
|
870
|
+
a, wrap = _makearray(a)
|
|
871
|
+
_assert_stacked_square(a)
|
|
872
|
+
t, result_t = _commonType(a)
|
|
873
|
+
signature = 'D->D' if isComplexType(t) else 'd->d'
|
|
874
|
+
with errstate(call=_raise_linalgerror_nonposdef, invalid='call',
|
|
875
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
876
|
+
r = gufunc(a, signature=signature)
|
|
877
|
+
return wrap(r.astype(result_t, copy=False))
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
# outer product
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def _outer_dispatcher(x1, x2):
|
|
884
|
+
return (x1, x2)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
@array_function_dispatch(_outer_dispatcher)
|
|
888
|
+
def outer(x1, x2, /):
|
|
889
|
+
"""
|
|
890
|
+
Compute the outer product of two vectors.
|
|
891
|
+
|
|
892
|
+
This function is Array API compatible. Compared to ``np.outer``
|
|
893
|
+
it accepts 1-dimensional inputs only.
|
|
894
|
+
|
|
895
|
+
Parameters
|
|
896
|
+
----------
|
|
897
|
+
x1 : (M,) array_like
|
|
898
|
+
One-dimensional input array of size ``N``.
|
|
899
|
+
Must have a numeric data type.
|
|
900
|
+
x2 : (N,) array_like
|
|
901
|
+
One-dimensional input array of size ``M``.
|
|
902
|
+
Must have a numeric data type.
|
|
903
|
+
|
|
904
|
+
Returns
|
|
905
|
+
-------
|
|
906
|
+
out : (M, N) ndarray
|
|
907
|
+
``out[i, j] = a[i] * b[j]``
|
|
908
|
+
|
|
909
|
+
See also
|
|
910
|
+
--------
|
|
911
|
+
outer
|
|
912
|
+
|
|
913
|
+
Examples
|
|
914
|
+
--------
|
|
915
|
+
Make a (*very* coarse) grid for computing a Mandelbrot set:
|
|
916
|
+
|
|
917
|
+
>>> rl = np.linalg.outer(np.ones((5,)), np.linspace(-2, 2, 5))
|
|
918
|
+
>>> rl
|
|
919
|
+
array([[-2., -1., 0., 1., 2.],
|
|
920
|
+
[-2., -1., 0., 1., 2.],
|
|
921
|
+
[-2., -1., 0., 1., 2.],
|
|
922
|
+
[-2., -1., 0., 1., 2.],
|
|
923
|
+
[-2., -1., 0., 1., 2.]])
|
|
924
|
+
>>> im = np.linalg.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
|
|
925
|
+
>>> im
|
|
926
|
+
array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
|
|
927
|
+
[0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
|
|
928
|
+
[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
|
|
929
|
+
[0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
|
|
930
|
+
[0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
|
|
931
|
+
>>> grid = rl + im
|
|
932
|
+
>>> grid
|
|
933
|
+
array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
|
|
934
|
+
[-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
|
|
935
|
+
[-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
|
|
936
|
+
[-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
|
|
937
|
+
[-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
|
|
938
|
+
|
|
939
|
+
An example using a "vector" of letters:
|
|
940
|
+
|
|
941
|
+
>>> x = np.array(['a', 'b', 'c'], dtype=object)
|
|
942
|
+
>>> np.linalg.outer(x, [1, 2, 3])
|
|
943
|
+
array([['a', 'aa', 'aaa'],
|
|
944
|
+
['b', 'bb', 'bbb'],
|
|
945
|
+
['c', 'cc', 'ccc']], dtype=object)
|
|
946
|
+
|
|
947
|
+
"""
|
|
948
|
+
x1 = asanyarray(x1)
|
|
949
|
+
x2 = asanyarray(x2)
|
|
950
|
+
if x1.ndim != 1 or x2.ndim != 1:
|
|
951
|
+
raise ValueError(
|
|
952
|
+
"Input arrays must be one-dimensional, but they are "
|
|
953
|
+
f"{x1.ndim=} and {x2.ndim=}."
|
|
954
|
+
)
|
|
955
|
+
return _core_outer(x1, x2, out=None)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
# QR decomposition
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def _qr_dispatcher(a, mode=None):
|
|
962
|
+
return (a,)
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
@array_function_dispatch(_qr_dispatcher)
|
|
966
|
+
def qr(a, mode='reduced'):
|
|
967
|
+
"""
|
|
968
|
+
Compute the qr factorization of a matrix.
|
|
969
|
+
|
|
970
|
+
Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
|
|
971
|
+
upper-triangular.
|
|
972
|
+
|
|
973
|
+
Parameters
|
|
974
|
+
----------
|
|
975
|
+
a : array_like, shape (..., M, N)
|
|
976
|
+
An array-like object with the dimensionality of at least 2.
|
|
977
|
+
mode : {'reduced', 'complete', 'r', 'raw'}, optional, default: 'reduced'
|
|
978
|
+
If K = min(M, N), then
|
|
979
|
+
|
|
980
|
+
* 'reduced' : returns Q, R with dimensions (..., M, K), (..., K, N)
|
|
981
|
+
* 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
|
|
982
|
+
* 'r' : returns R only with dimensions (..., K, N)
|
|
983
|
+
* 'raw' : returns h, tau with dimensions (..., N, M), (..., K,)
|
|
984
|
+
|
|
985
|
+
The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
|
|
986
|
+
see the notes for more information. The default is 'reduced', and to
|
|
987
|
+
maintain backward compatibility with earlier versions of numpy both
|
|
988
|
+
it and the old default 'full' can be omitted. Note that array h
|
|
989
|
+
returned in 'raw' mode is transposed for calling Fortran. The
|
|
990
|
+
'economic' mode is deprecated. The modes 'full' and 'economic' may
|
|
991
|
+
be passed using only the first letter for backwards compatibility,
|
|
992
|
+
but all others must be spelled out. See the Notes for more
|
|
993
|
+
explanation.
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
Returns
|
|
997
|
+
-------
|
|
998
|
+
Q : ndarray of float or complex, optional
|
|
999
|
+
A matrix with orthonormal columns. When mode = 'complete' the
|
|
1000
|
+
result is an orthogonal/unitary matrix depending on whether or not
|
|
1001
|
+
a is real/complex. The determinant may be either +/- 1 in that
|
|
1002
|
+
case. In case the number of dimensions in the input array is
|
|
1003
|
+
greater than 2 then a stack of the matrices with above properties
|
|
1004
|
+
is returned.
|
|
1005
|
+
R : ndarray of float or complex, optional
|
|
1006
|
+
The upper-triangular matrix or a stack of upper-triangular
|
|
1007
|
+
matrices if the number of dimensions in the input array is greater
|
|
1008
|
+
than 2.
|
|
1009
|
+
(h, tau) : ndarrays of np.double or np.cdouble, optional
|
|
1010
|
+
The array h contains the Householder reflectors that generate q
|
|
1011
|
+
along with r. The tau array contains scaling factors for the
|
|
1012
|
+
reflectors. In the deprecated 'economic' mode only h is returned.
|
|
1013
|
+
|
|
1014
|
+
Raises
|
|
1015
|
+
------
|
|
1016
|
+
LinAlgError
|
|
1017
|
+
If factoring fails.
|
|
1018
|
+
|
|
1019
|
+
See Also
|
|
1020
|
+
--------
|
|
1021
|
+
scipy.linalg.qr : Similar function in SciPy.
|
|
1022
|
+
scipy.linalg.rq : Compute RQ decomposition of a matrix.
|
|
1023
|
+
|
|
1024
|
+
Notes
|
|
1025
|
+
-----
|
|
1026
|
+
When mode is 'reduced' or 'complete', the result will be a namedtuple with
|
|
1027
|
+
the attributes ``Q`` and ``R``.
|
|
1028
|
+
|
|
1029
|
+
This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
|
|
1030
|
+
``dorgqr``, and ``zungqr``.
|
|
1031
|
+
|
|
1032
|
+
For more information on the qr factorization, see for example:
|
|
1033
|
+
https://en.wikipedia.org/wiki/QR_factorization
|
|
1034
|
+
|
|
1035
|
+
Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
|
|
1036
|
+
`a` is of type `matrix`, all the return values will be matrices too.
|
|
1037
|
+
|
|
1038
|
+
New 'reduced', 'complete', and 'raw' options for mode were added in
|
|
1039
|
+
NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In
|
|
1040
|
+
addition the options 'full' and 'economic' were deprecated. Because
|
|
1041
|
+
'full' was the previous default and 'reduced' is the new default,
|
|
1042
|
+
backward compatibility can be maintained by letting `mode` default.
|
|
1043
|
+
The 'raw' option was added so that LAPACK routines that can multiply
|
|
1044
|
+
arrays by q using the Householder reflectors can be used. Note that in
|
|
1045
|
+
this case the returned arrays are of type np.double or np.cdouble and
|
|
1046
|
+
the h array is transposed to be FORTRAN compatible. No routines using
|
|
1047
|
+
the 'raw' return are currently exposed by numpy, but some are available
|
|
1048
|
+
in lapack_lite and just await the necessary work.
|
|
1049
|
+
|
|
1050
|
+
Examples
|
|
1051
|
+
--------
|
|
1052
|
+
>>> import numpy as np
|
|
1053
|
+
>>> rng = np.random.default_rng()
|
|
1054
|
+
>>> a = rng.normal(size=(9, 6))
|
|
1055
|
+
>>> Q, R = np.linalg.qr(a)
|
|
1056
|
+
>>> np.allclose(a, np.dot(Q, R)) # a does equal QR
|
|
1057
|
+
True
|
|
1058
|
+
>>> R2 = np.linalg.qr(a, mode='r')
|
|
1059
|
+
>>> np.allclose(R, R2) # mode='r' returns the same R as mode='full'
|
|
1060
|
+
True
|
|
1061
|
+
>>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
|
|
1062
|
+
>>> Q, R = np.linalg.qr(a)
|
|
1063
|
+
>>> Q.shape
|
|
1064
|
+
(3, 2, 2)
|
|
1065
|
+
>>> R.shape
|
|
1066
|
+
(3, 2, 2)
|
|
1067
|
+
>>> np.allclose(a, np.matmul(Q, R))
|
|
1068
|
+
True
|
|
1069
|
+
|
|
1070
|
+
Example illustrating a common use of `qr`: solving of least squares
|
|
1071
|
+
problems
|
|
1072
|
+
|
|
1073
|
+
What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
|
|
1074
|
+
the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
|
|
1075
|
+
and you'll see that it should be y0 = 0, m = 1.) The answer is provided
|
|
1076
|
+
by solving the over-determined matrix equation ``Ax = b``, where::
|
|
1077
|
+
|
|
1078
|
+
A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
|
|
1079
|
+
x = array([[y0], [m]])
|
|
1080
|
+
b = array([[1], [0], [2], [1]])
|
|
1081
|
+
|
|
1082
|
+
If A = QR such that Q is orthonormal (which is always possible via
|
|
1083
|
+
Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``. (In numpy practice,
|
|
1084
|
+
however, we simply use `lstsq`.)
|
|
1085
|
+
|
|
1086
|
+
>>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
|
|
1087
|
+
>>> A
|
|
1088
|
+
array([[0, 1],
|
|
1089
|
+
[1, 1],
|
|
1090
|
+
[1, 1],
|
|
1091
|
+
[2, 1]])
|
|
1092
|
+
>>> b = np.array([1, 2, 2, 3])
|
|
1093
|
+
>>> Q, R = np.linalg.qr(A)
|
|
1094
|
+
>>> p = np.dot(Q.T, b)
|
|
1095
|
+
>>> np.dot(np.linalg.inv(R), p)
|
|
1096
|
+
array([ 1., 1.])
|
|
1097
|
+
|
|
1098
|
+
"""
|
|
1099
|
+
if mode not in ('reduced', 'complete', 'r', 'raw'):
|
|
1100
|
+
if mode in ('f', 'full'):
|
|
1101
|
+
# 2013-04-01, 1.8
|
|
1102
|
+
msg = (
|
|
1103
|
+
"The 'full' option is deprecated in favor of 'reduced'.\n"
|
|
1104
|
+
"For backward compatibility let mode default."
|
|
1105
|
+
)
|
|
1106
|
+
warnings.warn(msg, DeprecationWarning, stacklevel=2)
|
|
1107
|
+
mode = 'reduced'
|
|
1108
|
+
elif mode in ('e', 'economic'):
|
|
1109
|
+
# 2013-04-01, 1.8
|
|
1110
|
+
msg = "The 'economic' option is deprecated."
|
|
1111
|
+
warnings.warn(msg, DeprecationWarning, stacklevel=2)
|
|
1112
|
+
mode = 'economic'
|
|
1113
|
+
else:
|
|
1114
|
+
raise ValueError(f"Unrecognized mode '{mode}'")
|
|
1115
|
+
|
|
1116
|
+
a, wrap = _makearray(a)
|
|
1117
|
+
_assert_stacked_2d(a)
|
|
1118
|
+
m, n = a.shape[-2:]
|
|
1119
|
+
t, result_t = _commonType(a)
|
|
1120
|
+
a = a.astype(t, copy=True)
|
|
1121
|
+
a = _to_native_byte_order(a)
|
|
1122
|
+
mn = min(m, n)
|
|
1123
|
+
|
|
1124
|
+
signature = 'D->D' if isComplexType(t) else 'd->d'
|
|
1125
|
+
with errstate(call=_raise_linalgerror_qr, invalid='call',
|
|
1126
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
1127
|
+
tau = _umath_linalg.qr_r_raw(a, signature=signature)
|
|
1128
|
+
|
|
1129
|
+
# handle modes that don't return q
|
|
1130
|
+
if mode == 'r':
|
|
1131
|
+
r = triu(a[..., :mn, :])
|
|
1132
|
+
r = r.astype(result_t, copy=False)
|
|
1133
|
+
return wrap(r)
|
|
1134
|
+
|
|
1135
|
+
if mode == 'raw':
|
|
1136
|
+
q = transpose(a)
|
|
1137
|
+
q = q.astype(result_t, copy=False)
|
|
1138
|
+
tau = tau.astype(result_t, copy=False)
|
|
1139
|
+
return wrap(q), tau
|
|
1140
|
+
|
|
1141
|
+
if mode == 'economic':
|
|
1142
|
+
a = a.astype(result_t, copy=False)
|
|
1143
|
+
return wrap(a)
|
|
1144
|
+
|
|
1145
|
+
# mc is the number of columns in the resulting q
|
|
1146
|
+
# matrix. If the mode is complete then it is
|
|
1147
|
+
# same as number of rows, and if the mode is reduced,
|
|
1148
|
+
# then it is the minimum of number of rows and columns.
|
|
1149
|
+
if mode == 'complete' and m > n:
|
|
1150
|
+
mc = m
|
|
1151
|
+
gufunc = _umath_linalg.qr_complete
|
|
1152
|
+
else:
|
|
1153
|
+
mc = mn
|
|
1154
|
+
gufunc = _umath_linalg.qr_reduced
|
|
1155
|
+
|
|
1156
|
+
signature = 'DD->D' if isComplexType(t) else 'dd->d'
|
|
1157
|
+
with errstate(call=_raise_linalgerror_qr, invalid='call',
|
|
1158
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
1159
|
+
q = gufunc(a, tau, signature=signature)
|
|
1160
|
+
r = triu(a[..., :mc, :])
|
|
1161
|
+
|
|
1162
|
+
q = q.astype(result_t, copy=False)
|
|
1163
|
+
r = r.astype(result_t, copy=False)
|
|
1164
|
+
|
|
1165
|
+
return QRResult(wrap(q), wrap(r))
|
|
1166
|
+
|
|
1167
|
+
# Eigenvalues
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
@array_function_dispatch(_unary_dispatcher)
|
|
1171
|
+
def eigvals(a):
|
|
1172
|
+
"""
|
|
1173
|
+
Compute the eigenvalues of a general matrix.
|
|
1174
|
+
|
|
1175
|
+
Main difference between `eigvals` and `eig`: the eigenvectors aren't
|
|
1176
|
+
returned.
|
|
1177
|
+
|
|
1178
|
+
Parameters
|
|
1179
|
+
----------
|
|
1180
|
+
a : (..., M, M) array_like
|
|
1181
|
+
A complex- or real-valued matrix whose eigenvalues will be computed.
|
|
1182
|
+
|
|
1183
|
+
Returns
|
|
1184
|
+
-------
|
|
1185
|
+
w : (..., M,) ndarray
|
|
1186
|
+
The eigenvalues, each repeated according to its multiplicity.
|
|
1187
|
+
They are not necessarily ordered, nor are they necessarily
|
|
1188
|
+
real for real matrices.
|
|
1189
|
+
|
|
1190
|
+
Raises
|
|
1191
|
+
------
|
|
1192
|
+
LinAlgError
|
|
1193
|
+
If the eigenvalue computation does not converge.
|
|
1194
|
+
|
|
1195
|
+
See Also
|
|
1196
|
+
--------
|
|
1197
|
+
eig : eigenvalues and right eigenvectors of general arrays
|
|
1198
|
+
eigvalsh : eigenvalues of real symmetric or complex Hermitian
|
|
1199
|
+
(conjugate symmetric) arrays.
|
|
1200
|
+
eigh : eigenvalues and eigenvectors of real symmetric or complex
|
|
1201
|
+
Hermitian (conjugate symmetric) arrays.
|
|
1202
|
+
scipy.linalg.eigvals : Similar function in SciPy.
|
|
1203
|
+
|
|
1204
|
+
Notes
|
|
1205
|
+
-----
|
|
1206
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
1207
|
+
details.
|
|
1208
|
+
|
|
1209
|
+
This is implemented using the ``_geev`` LAPACK routines which compute
|
|
1210
|
+
the eigenvalues and eigenvectors of general square arrays.
|
|
1211
|
+
|
|
1212
|
+
Examples
|
|
1213
|
+
--------
|
|
1214
|
+
Illustration, using the fact that the eigenvalues of a diagonal matrix
|
|
1215
|
+
are its diagonal elements, that multiplying a matrix on the left
|
|
1216
|
+
by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
|
|
1217
|
+
of `Q`), preserves the eigenvalues of the "middle" matrix. In other words,
|
|
1218
|
+
if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
|
|
1219
|
+
``A``:
|
|
1220
|
+
|
|
1221
|
+
>>> import numpy as np
|
|
1222
|
+
>>> from numpy import linalg as LA
|
|
1223
|
+
>>> x = np.random.random()
|
|
1224
|
+
>>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
|
|
1225
|
+
>>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
|
|
1226
|
+
(1.0, 1.0, 0.0)
|
|
1227
|
+
|
|
1228
|
+
Now multiply a diagonal matrix by ``Q`` on one side and
|
|
1229
|
+
by ``Q.T`` on the other:
|
|
1230
|
+
|
|
1231
|
+
>>> D = np.diag((-1,1))
|
|
1232
|
+
>>> LA.eigvals(D)
|
|
1233
|
+
array([-1., 1.])
|
|
1234
|
+
>>> A = np.dot(Q, D)
|
|
1235
|
+
>>> A = np.dot(A, Q.T)
|
|
1236
|
+
>>> LA.eigvals(A)
|
|
1237
|
+
array([ 1., -1.]) # random
|
|
1238
|
+
|
|
1239
|
+
"""
|
|
1240
|
+
a, wrap = _makearray(a)
|
|
1241
|
+
_assert_stacked_square(a)
|
|
1242
|
+
_assert_finite(a)
|
|
1243
|
+
t, result_t = _commonType(a)
|
|
1244
|
+
|
|
1245
|
+
signature = 'D->D' if isComplexType(t) else 'd->D'
|
|
1246
|
+
with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence,
|
|
1247
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1248
|
+
under='ignore'):
|
|
1249
|
+
w = _umath_linalg.eigvals(a, signature=signature)
|
|
1250
|
+
|
|
1251
|
+
if not isComplexType(t):
|
|
1252
|
+
if all(w.imag == 0):
|
|
1253
|
+
w = w.real
|
|
1254
|
+
result_t = _realType(result_t)
|
|
1255
|
+
else:
|
|
1256
|
+
result_t = _complexType(result_t)
|
|
1257
|
+
|
|
1258
|
+
return w.astype(result_t, copy=False)
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
def _eigvalsh_dispatcher(a, UPLO=None):
|
|
1262
|
+
return (a,)
|
|
1263
|
+
|
|
1264
|
+
|
|
1265
|
+
@array_function_dispatch(_eigvalsh_dispatcher)
|
|
1266
|
+
def eigvalsh(a, UPLO='L'):
|
|
1267
|
+
"""
|
|
1268
|
+
Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
|
|
1269
|
+
|
|
1270
|
+
Main difference from eigh: the eigenvectors are not computed.
|
|
1271
|
+
|
|
1272
|
+
Parameters
|
|
1273
|
+
----------
|
|
1274
|
+
a : (..., M, M) array_like
|
|
1275
|
+
A complex- or real-valued matrix whose eigenvalues are to be
|
|
1276
|
+
computed.
|
|
1277
|
+
UPLO : {'L', 'U'}, optional
|
|
1278
|
+
Specifies whether the calculation is done with the lower triangular
|
|
1279
|
+
part of `a` ('L', default) or the upper triangular part ('U').
|
|
1280
|
+
Irrespective of this value only the real parts of the diagonal will
|
|
1281
|
+
be considered in the computation to preserve the notion of a Hermitian
|
|
1282
|
+
matrix. It therefore follows that the imaginary part of the diagonal
|
|
1283
|
+
will always be treated as zero.
|
|
1284
|
+
|
|
1285
|
+
Returns
|
|
1286
|
+
-------
|
|
1287
|
+
w : (..., M,) ndarray
|
|
1288
|
+
The eigenvalues in ascending order, each repeated according to
|
|
1289
|
+
its multiplicity.
|
|
1290
|
+
|
|
1291
|
+
Raises
|
|
1292
|
+
------
|
|
1293
|
+
LinAlgError
|
|
1294
|
+
If the eigenvalue computation does not converge.
|
|
1295
|
+
|
|
1296
|
+
See Also
|
|
1297
|
+
--------
|
|
1298
|
+
eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
|
|
1299
|
+
(conjugate symmetric) arrays.
|
|
1300
|
+
eigvals : eigenvalues of general real or complex arrays.
|
|
1301
|
+
eig : eigenvalues and right eigenvectors of general real or complex
|
|
1302
|
+
arrays.
|
|
1303
|
+
scipy.linalg.eigvalsh : Similar function in SciPy.
|
|
1304
|
+
|
|
1305
|
+
Notes
|
|
1306
|
+
-----
|
|
1307
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
1308
|
+
details.
|
|
1309
|
+
|
|
1310
|
+
The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
|
|
1311
|
+
|
|
1312
|
+
Examples
|
|
1313
|
+
--------
|
|
1314
|
+
>>> import numpy as np
|
|
1315
|
+
>>> from numpy import linalg as LA
|
|
1316
|
+
>>> a = np.array([[1, -2j], [2j, 5]])
|
|
1317
|
+
>>> LA.eigvalsh(a)
|
|
1318
|
+
array([ 0.17157288, 5.82842712]) # may vary
|
|
1319
|
+
|
|
1320
|
+
>>> # demonstrate the treatment of the imaginary part of the diagonal
|
|
1321
|
+
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
|
|
1322
|
+
>>> a
|
|
1323
|
+
array([[5.+2.j, 9.-2.j],
|
|
1324
|
+
[0.+2.j, 2.-1.j]])
|
|
1325
|
+
>>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
|
|
1326
|
+
>>> # with:
|
|
1327
|
+
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
|
|
1328
|
+
>>> b
|
|
1329
|
+
array([[5.+0.j, 0.-2.j],
|
|
1330
|
+
[0.+2.j, 2.+0.j]])
|
|
1331
|
+
>>> wa = LA.eigvalsh(a)
|
|
1332
|
+
>>> wb = LA.eigvals(b)
|
|
1333
|
+
>>> wa
|
|
1334
|
+
array([1., 6.])
|
|
1335
|
+
>>> wb
|
|
1336
|
+
array([6.+0.j, 1.+0.j])
|
|
1337
|
+
|
|
1338
|
+
"""
|
|
1339
|
+
UPLO = UPLO.upper()
|
|
1340
|
+
if UPLO not in ('L', 'U'):
|
|
1341
|
+
raise ValueError("UPLO argument must be 'L' or 'U'")
|
|
1342
|
+
|
|
1343
|
+
if UPLO == 'L':
|
|
1344
|
+
gufunc = _umath_linalg.eigvalsh_lo
|
|
1345
|
+
else:
|
|
1346
|
+
gufunc = _umath_linalg.eigvalsh_up
|
|
1347
|
+
|
|
1348
|
+
a, wrap = _makearray(a)
|
|
1349
|
+
_assert_stacked_square(a)
|
|
1350
|
+
t, result_t = _commonType(a)
|
|
1351
|
+
signature = 'D->d' if isComplexType(t) else 'd->d'
|
|
1352
|
+
with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence,
|
|
1353
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1354
|
+
under='ignore'):
|
|
1355
|
+
w = gufunc(a, signature=signature)
|
|
1356
|
+
return w.astype(_realType(result_t), copy=False)
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
# Eigenvectors
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
@array_function_dispatch(_unary_dispatcher)
|
|
1363
|
+
def eig(a):
|
|
1364
|
+
"""
|
|
1365
|
+
Compute the eigenvalues and right eigenvectors of a square array.
|
|
1366
|
+
|
|
1367
|
+
Parameters
|
|
1368
|
+
----------
|
|
1369
|
+
a : (..., M, M) array
|
|
1370
|
+
Matrices for which the eigenvalues and right eigenvectors will
|
|
1371
|
+
be computed
|
|
1372
|
+
|
|
1373
|
+
Returns
|
|
1374
|
+
-------
|
|
1375
|
+
A namedtuple with the following attributes:
|
|
1376
|
+
|
|
1377
|
+
eigenvalues : (..., M) array
|
|
1378
|
+
The eigenvalues, each repeated according to its multiplicity.
|
|
1379
|
+
The eigenvalues are not necessarily ordered. The resulting
|
|
1380
|
+
array will be of complex type, unless the imaginary part is
|
|
1381
|
+
zero in which case it will be cast to a real type. When `a`
|
|
1382
|
+
is real the resulting eigenvalues will be real (0 imaginary
|
|
1383
|
+
part) or occur in conjugate pairs
|
|
1384
|
+
|
|
1385
|
+
eigenvectors : (..., M, M) array
|
|
1386
|
+
The normalized (unit "length") eigenvectors, such that the
|
|
1387
|
+
column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
|
|
1388
|
+
eigenvalue ``eigenvalues[i]``.
|
|
1389
|
+
|
|
1390
|
+
Raises
|
|
1391
|
+
------
|
|
1392
|
+
LinAlgError
|
|
1393
|
+
If the eigenvalue computation does not converge.
|
|
1394
|
+
|
|
1395
|
+
See Also
|
|
1396
|
+
--------
|
|
1397
|
+
eigvals : eigenvalues of a non-symmetric array.
|
|
1398
|
+
eigh : eigenvalues and eigenvectors of a real symmetric or complex
|
|
1399
|
+
Hermitian (conjugate symmetric) array.
|
|
1400
|
+
eigvalsh : eigenvalues of a real symmetric or complex Hermitian
|
|
1401
|
+
(conjugate symmetric) array.
|
|
1402
|
+
scipy.linalg.eig : Similar function in SciPy that also solves the
|
|
1403
|
+
generalized eigenvalue problem.
|
|
1404
|
+
scipy.linalg.schur : Best choice for unitary and other non-Hermitian
|
|
1405
|
+
normal matrices.
|
|
1406
|
+
|
|
1407
|
+
Notes
|
|
1408
|
+
-----
|
|
1409
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
1410
|
+
details.
|
|
1411
|
+
|
|
1412
|
+
This is implemented using the ``_geev`` LAPACK routines which compute
|
|
1413
|
+
the eigenvalues and eigenvectors of general square arrays.
|
|
1414
|
+
|
|
1415
|
+
The number `w` is an eigenvalue of `a` if there exists a vector `v` such
|
|
1416
|
+
that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
|
|
1417
|
+
`eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
|
|
1418
|
+
eigenvalues[i] * eigenvectors[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`.
|
|
1419
|
+
|
|
1420
|
+
The array `eigenvectors` may not be of maximum rank, that is, some of the
|
|
1421
|
+
columns may be linearly dependent, although round-off error may obscure
|
|
1422
|
+
that fact. If the eigenvalues are all different, then theoretically the
|
|
1423
|
+
eigenvectors are linearly independent and `a` can be diagonalized by a
|
|
1424
|
+
similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
|
|
1425
|
+
a @ eigenvectors`` is diagonal.
|
|
1426
|
+
|
|
1427
|
+
For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
|
|
1428
|
+
is preferred because the matrix `eigenvectors` is guaranteed to be
|
|
1429
|
+
unitary, which is not the case when using `eig`. The Schur factorization
|
|
1430
|
+
produces an upper triangular matrix rather than a diagonal matrix, but for
|
|
1431
|
+
normal matrices only the diagonal of the upper triangular matrix is
|
|
1432
|
+
needed, the rest is roundoff error.
|
|
1433
|
+
|
|
1434
|
+
Finally, it is emphasized that `eigenvectors` consists of the *right* (as
|
|
1435
|
+
in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
|
|
1436
|
+
= z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
|
|
1437
|
+
and, in general, the left and right eigenvectors of a matrix are not
|
|
1438
|
+
necessarily the (perhaps conjugate) transposes of each other.
|
|
1439
|
+
|
|
1440
|
+
References
|
|
1441
|
+
----------
|
|
1442
|
+
G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
|
|
1443
|
+
Academic Press, Inc., 1980, Various pp.
|
|
1444
|
+
|
|
1445
|
+
Examples
|
|
1446
|
+
--------
|
|
1447
|
+
>>> import numpy as np
|
|
1448
|
+
>>> from numpy import linalg as LA
|
|
1449
|
+
|
|
1450
|
+
(Almost) trivial example with real eigenvalues and eigenvectors.
|
|
1451
|
+
|
|
1452
|
+
>>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
|
|
1453
|
+
>>> eigenvalues
|
|
1454
|
+
array([1., 2., 3.])
|
|
1455
|
+
>>> eigenvectors
|
|
1456
|
+
array([[1., 0., 0.],
|
|
1457
|
+
[0., 1., 0.],
|
|
1458
|
+
[0., 0., 1.]])
|
|
1459
|
+
|
|
1460
|
+
Real matrix possessing complex eigenvalues and eigenvectors;
|
|
1461
|
+
note that the eigenvalues are complex conjugates of each other.
|
|
1462
|
+
|
|
1463
|
+
>>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
|
|
1464
|
+
>>> eigenvalues
|
|
1465
|
+
array([1.+1.j, 1.-1.j])
|
|
1466
|
+
>>> eigenvectors
|
|
1467
|
+
array([[0.70710678+0.j , 0.70710678-0.j ],
|
|
1468
|
+
[0. -0.70710678j, 0. +0.70710678j]])
|
|
1469
|
+
|
|
1470
|
+
Complex-valued matrix with real eigenvalues (but complex-valued
|
|
1471
|
+
eigenvectors); note that ``a.conj().T == a``, i.e., `a` is Hermitian.
|
|
1472
|
+
|
|
1473
|
+
>>> a = np.array([[1, 1j], [-1j, 1]])
|
|
1474
|
+
>>> eigenvalues, eigenvectors = LA.eig(a)
|
|
1475
|
+
>>> eigenvalues
|
|
1476
|
+
array([2.+0.j, 0.+0.j])
|
|
1477
|
+
>>> eigenvectors
|
|
1478
|
+
array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary
|
|
1479
|
+
[ 0.70710678+0.j , -0. +0.70710678j]])
|
|
1480
|
+
|
|
1481
|
+
Be careful about round-off error!
|
|
1482
|
+
|
|
1483
|
+
>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
|
|
1484
|
+
>>> # Theor. eigenvalues are 1 +/- 1e-9
|
|
1485
|
+
>>> eigenvalues, eigenvectors = LA.eig(a)
|
|
1486
|
+
>>> eigenvalues
|
|
1487
|
+
array([1., 1.])
|
|
1488
|
+
>>> eigenvectors
|
|
1489
|
+
array([[1., 0.],
|
|
1490
|
+
[0., 1.]])
|
|
1491
|
+
|
|
1492
|
+
"""
|
|
1493
|
+
a, wrap = _makearray(a)
|
|
1494
|
+
_assert_stacked_square(a)
|
|
1495
|
+
_assert_finite(a)
|
|
1496
|
+
t, result_t = _commonType(a)
|
|
1497
|
+
|
|
1498
|
+
signature = 'D->DD' if isComplexType(t) else 'd->DD'
|
|
1499
|
+
with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence,
|
|
1500
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1501
|
+
under='ignore'):
|
|
1502
|
+
w, vt = _umath_linalg.eig(a, signature=signature)
|
|
1503
|
+
|
|
1504
|
+
if not isComplexType(t) and all(w.imag == 0.0):
|
|
1505
|
+
w = w.real
|
|
1506
|
+
vt = vt.real
|
|
1507
|
+
result_t = _realType(result_t)
|
|
1508
|
+
else:
|
|
1509
|
+
result_t = _complexType(result_t)
|
|
1510
|
+
|
|
1511
|
+
vt = vt.astype(result_t, copy=False)
|
|
1512
|
+
return EigResult(w.astype(result_t, copy=False), wrap(vt))
|
|
1513
|
+
|
|
1514
|
+
|
|
1515
|
+
@array_function_dispatch(_eigvalsh_dispatcher)
|
|
1516
|
+
def eigh(a, UPLO='L'):
|
|
1517
|
+
"""
|
|
1518
|
+
Return the eigenvalues and eigenvectors of a complex Hermitian
|
|
1519
|
+
(conjugate symmetric) or a real symmetric matrix.
|
|
1520
|
+
|
|
1521
|
+
Returns two objects, a 1-D array containing the eigenvalues of `a`, and
|
|
1522
|
+
a 2-D square array or matrix (depending on the input type) of the
|
|
1523
|
+
corresponding eigenvectors (in columns).
|
|
1524
|
+
|
|
1525
|
+
Parameters
|
|
1526
|
+
----------
|
|
1527
|
+
a : (..., M, M) array
|
|
1528
|
+
Hermitian or real symmetric matrices whose eigenvalues and
|
|
1529
|
+
eigenvectors are to be computed.
|
|
1530
|
+
UPLO : {'L', 'U'}, optional
|
|
1531
|
+
Specifies whether the calculation is done with the lower triangular
|
|
1532
|
+
part of `a` ('L', default) or the upper triangular part ('U').
|
|
1533
|
+
Irrespective of this value only the real parts of the diagonal will
|
|
1534
|
+
be considered in the computation to preserve the notion of a Hermitian
|
|
1535
|
+
matrix. It therefore follows that the imaginary part of the diagonal
|
|
1536
|
+
will always be treated as zero.
|
|
1537
|
+
|
|
1538
|
+
Returns
|
|
1539
|
+
-------
|
|
1540
|
+
A namedtuple with the following attributes:
|
|
1541
|
+
|
|
1542
|
+
eigenvalues : (..., M) ndarray
|
|
1543
|
+
The eigenvalues in ascending order, each repeated according to
|
|
1544
|
+
its multiplicity.
|
|
1545
|
+
eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
|
|
1546
|
+
The column ``eigenvectors[:, i]`` is the normalized eigenvector
|
|
1547
|
+
corresponding to the eigenvalue ``eigenvalues[i]``. Will return a
|
|
1548
|
+
matrix object if `a` is a matrix object.
|
|
1549
|
+
|
|
1550
|
+
Raises
|
|
1551
|
+
------
|
|
1552
|
+
LinAlgError
|
|
1553
|
+
If the eigenvalue computation does not converge.
|
|
1554
|
+
|
|
1555
|
+
See Also
|
|
1556
|
+
--------
|
|
1557
|
+
eigvalsh : eigenvalues of real symmetric or complex Hermitian
|
|
1558
|
+
(conjugate symmetric) arrays.
|
|
1559
|
+
eig : eigenvalues and right eigenvectors for non-symmetric arrays.
|
|
1560
|
+
eigvals : eigenvalues of non-symmetric arrays.
|
|
1561
|
+
scipy.linalg.eigh : Similar function in SciPy (but also solves the
|
|
1562
|
+
generalized eigenvalue problem).
|
|
1563
|
+
|
|
1564
|
+
Notes
|
|
1565
|
+
-----
|
|
1566
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
1567
|
+
details.
|
|
1568
|
+
|
|
1569
|
+
The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
|
|
1570
|
+
``_heevd``.
|
|
1571
|
+
|
|
1572
|
+
The eigenvalues of real symmetric or complex Hermitian matrices are always
|
|
1573
|
+
real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
|
|
1574
|
+
`a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
|
|
1575
|
+
eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.
|
|
1576
|
+
|
|
1577
|
+
References
|
|
1578
|
+
----------
|
|
1579
|
+
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
|
|
1580
|
+
FL, Academic Press, Inc., 1980, pg. 222.
|
|
1581
|
+
|
|
1582
|
+
Examples
|
|
1583
|
+
--------
|
|
1584
|
+
>>> import numpy as np
|
|
1585
|
+
>>> from numpy import linalg as LA
|
|
1586
|
+
>>> a = np.array([[1, -2j], [2j, 5]])
|
|
1587
|
+
>>> a
|
|
1588
|
+
array([[ 1.+0.j, -0.-2.j],
|
|
1589
|
+
[ 0.+2.j, 5.+0.j]])
|
|
1590
|
+
>>> eigenvalues, eigenvectors = LA.eigh(a)
|
|
1591
|
+
>>> eigenvalues
|
|
1592
|
+
array([0.17157288, 5.82842712])
|
|
1593
|
+
>>> eigenvectors
|
|
1594
|
+
array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
|
|
1595
|
+
[ 0. +0.38268343j, 0. -0.92387953j]])
|
|
1596
|
+
|
|
1597
|
+
>>> (np.dot(a, eigenvectors[:, 0]) -
|
|
1598
|
+
... eigenvalues[0] * eigenvectors[:, 0]) # verify 1st eigenval/vec pair
|
|
1599
|
+
array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
|
|
1600
|
+
>>> (np.dot(a, eigenvectors[:, 1]) -
|
|
1601
|
+
... eigenvalues[1] * eigenvectors[:, 1]) # verify 2nd eigenval/vec pair
|
|
1602
|
+
array([0.+0.j, 0.+0.j])
|
|
1603
|
+
|
|
1604
|
+
>>> A = np.matrix(a) # what happens if input is a matrix object
|
|
1605
|
+
>>> A
|
|
1606
|
+
matrix([[ 1.+0.j, -0.-2.j],
|
|
1607
|
+
[ 0.+2.j, 5.+0.j]])
|
|
1608
|
+
>>> eigenvalues, eigenvectors = LA.eigh(A)
|
|
1609
|
+
>>> eigenvalues
|
|
1610
|
+
array([0.17157288, 5.82842712])
|
|
1611
|
+
>>> eigenvectors
|
|
1612
|
+
matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
|
|
1613
|
+
[ 0. +0.38268343j, 0. -0.92387953j]])
|
|
1614
|
+
|
|
1615
|
+
>>> # demonstrate the treatment of the imaginary part of the diagonal
|
|
1616
|
+
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
|
|
1617
|
+
>>> a
|
|
1618
|
+
array([[5.+2.j, 9.-2.j],
|
|
1619
|
+
[0.+2.j, 2.-1.j]])
|
|
1620
|
+
>>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
|
|
1621
|
+
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
|
|
1622
|
+
>>> b
|
|
1623
|
+
array([[5.+0.j, 0.-2.j],
|
|
1624
|
+
[0.+2.j, 2.+0.j]])
|
|
1625
|
+
>>> wa, va = LA.eigh(a)
|
|
1626
|
+
>>> wb, vb = LA.eig(b)
|
|
1627
|
+
>>> wa
|
|
1628
|
+
array([1., 6.])
|
|
1629
|
+
>>> wb
|
|
1630
|
+
array([6.+0.j, 1.+0.j])
|
|
1631
|
+
>>> va
|
|
1632
|
+
array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary
|
|
1633
|
+
[ 0. +0.89442719j, 0. -0.4472136j ]])
|
|
1634
|
+
>>> vb
|
|
1635
|
+
array([[ 0.89442719+0.j , -0. +0.4472136j],
|
|
1636
|
+
[-0. +0.4472136j, 0.89442719+0.j ]])
|
|
1637
|
+
|
|
1638
|
+
"""
|
|
1639
|
+
UPLO = UPLO.upper()
|
|
1640
|
+
if UPLO not in ('L', 'U'):
|
|
1641
|
+
raise ValueError("UPLO argument must be 'L' or 'U'")
|
|
1642
|
+
|
|
1643
|
+
a, wrap = _makearray(a)
|
|
1644
|
+
_assert_stacked_square(a)
|
|
1645
|
+
t, result_t = _commonType(a)
|
|
1646
|
+
|
|
1647
|
+
if UPLO == 'L':
|
|
1648
|
+
gufunc = _umath_linalg.eigh_lo
|
|
1649
|
+
else:
|
|
1650
|
+
gufunc = _umath_linalg.eigh_up
|
|
1651
|
+
|
|
1652
|
+
signature = 'D->dD' if isComplexType(t) else 'd->dd'
|
|
1653
|
+
with errstate(call=_raise_linalgerror_eigenvalues_nonconvergence,
|
|
1654
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1655
|
+
under='ignore'):
|
|
1656
|
+
w, vt = gufunc(a, signature=signature)
|
|
1657
|
+
w = w.astype(_realType(result_t), copy=False)
|
|
1658
|
+
vt = vt.astype(result_t, copy=False)
|
|
1659
|
+
return EighResult(w, wrap(vt))
|
|
1660
|
+
|
|
1661
|
+
|
|
1662
|
+
# Singular value decomposition
|
|
1663
|
+
|
|
1664
|
+
def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None):
|
|
1665
|
+
return (a,)
|
|
1666
|
+
|
|
1667
|
+
|
|
1668
|
+
@array_function_dispatch(_svd_dispatcher)
|
|
1669
|
+
def svd(a, full_matrices=True, compute_uv=True, hermitian=False):
|
|
1670
|
+
"""
|
|
1671
|
+
Singular Value Decomposition.
|
|
1672
|
+
|
|
1673
|
+
When `a` is a 2D array, and ``full_matrices=False``, then it is
|
|
1674
|
+
factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
|
|
1675
|
+
`u` and the Hermitian transpose of `vh` are 2D arrays with
|
|
1676
|
+
orthonormal columns and `s` is a 1D array of `a`'s singular
|
|
1677
|
+
values. When `a` is higher-dimensional, SVD is applied in
|
|
1678
|
+
stacked mode as explained below.
|
|
1679
|
+
|
|
1680
|
+
Parameters
|
|
1681
|
+
----------
|
|
1682
|
+
a : (..., M, N) array_like
|
|
1683
|
+
A real or complex array with ``a.ndim >= 2``.
|
|
1684
|
+
full_matrices : bool, optional
|
|
1685
|
+
If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
|
|
1686
|
+
``(..., N, N)``, respectively. Otherwise, the shapes are
|
|
1687
|
+
``(..., M, K)`` and ``(..., K, N)``, respectively, where
|
|
1688
|
+
``K = min(M, N)``.
|
|
1689
|
+
compute_uv : bool, optional
|
|
1690
|
+
Whether or not to compute `u` and `vh` in addition to `s`. True
|
|
1691
|
+
by default.
|
|
1692
|
+
hermitian : bool, optional
|
|
1693
|
+
If True, `a` is assumed to be Hermitian (symmetric if real-valued),
|
|
1694
|
+
enabling a more efficient method for finding singular values.
|
|
1695
|
+
Defaults to False.
|
|
1696
|
+
|
|
1697
|
+
Returns
|
|
1698
|
+
-------
|
|
1699
|
+
U : { (..., M, M), (..., M, K) } array
|
|
1700
|
+
Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
|
|
1701
|
+
size as those of the input `a`. The size of the last two dimensions
|
|
1702
|
+
depends on the value of `full_matrices`. Only returned when
|
|
1703
|
+
`compute_uv` is True.
|
|
1704
|
+
S : (..., K) array
|
|
1705
|
+
Vector(s) with the singular values, within each vector sorted in
|
|
1706
|
+
descending order. The first ``a.ndim - 2`` dimensions have the same
|
|
1707
|
+
size as those of the input `a`.
|
|
1708
|
+
Vh : { (..., N, N), (..., K, N) } array
|
|
1709
|
+
Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
|
|
1710
|
+
size as those of the input `a`. The size of the last two dimensions
|
|
1711
|
+
depends on the value of `full_matrices`. Only returned when
|
|
1712
|
+
`compute_uv` is True.
|
|
1713
|
+
|
|
1714
|
+
Raises
|
|
1715
|
+
------
|
|
1716
|
+
LinAlgError
|
|
1717
|
+
If SVD computation does not converge.
|
|
1718
|
+
|
|
1719
|
+
See Also
|
|
1720
|
+
--------
|
|
1721
|
+
scipy.linalg.svd : Similar function in SciPy.
|
|
1722
|
+
scipy.linalg.svdvals : Compute singular values of a matrix.
|
|
1723
|
+
|
|
1724
|
+
Notes
|
|
1725
|
+
-----
|
|
1726
|
+
When `compute_uv` is True, the result is a namedtuple with the following
|
|
1727
|
+
attribute names: `U`, `S`, and `Vh`.
|
|
1728
|
+
|
|
1729
|
+
The decomposition is performed using LAPACK routine ``_gesdd``.
|
|
1730
|
+
|
|
1731
|
+
SVD is usually described for the factorization of a 2D matrix :math:`A`.
|
|
1732
|
+
The higher-dimensional case will be discussed below. In the 2D case, SVD is
|
|
1733
|
+
written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
|
|
1734
|
+
:math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
|
|
1735
|
+
contains the singular values of `a` and `u` and `vh` are unitary. The rows
|
|
1736
|
+
of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
|
|
1737
|
+
the eigenvectors of :math:`A A^H`. In both cases the corresponding
|
|
1738
|
+
(possibly non-zero) eigenvalues are given by ``s**2``.
|
|
1739
|
+
|
|
1740
|
+
If `a` has more than two dimensions, then broadcasting rules apply, as
|
|
1741
|
+
explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
|
|
1742
|
+
working in "stacked" mode: it iterates over all indices of the first
|
|
1743
|
+
``a.ndim - 2`` dimensions and for each combination SVD is applied to the
|
|
1744
|
+
last two indices. The matrix `a` can be reconstructed from the
|
|
1745
|
+
decomposition with either ``(u * s[..., None, :]) @ vh`` or
|
|
1746
|
+
``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
|
|
1747
|
+
function ``np.matmul`` for python versions below 3.5.)
|
|
1748
|
+
|
|
1749
|
+
If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
|
|
1750
|
+
all the return values.
|
|
1751
|
+
|
|
1752
|
+
Examples
|
|
1753
|
+
--------
|
|
1754
|
+
>>> import numpy as np
|
|
1755
|
+
>>> rng = np.random.default_rng()
|
|
1756
|
+
>>> a = rng.normal(size=(9, 6)) + 1j*rng.normal(size=(9, 6))
|
|
1757
|
+
>>> b = rng.normal(size=(2, 7, 8, 3)) + 1j*rng.normal(size=(2, 7, 8, 3))
|
|
1758
|
+
|
|
1759
|
+
|
|
1760
|
+
Reconstruction based on full SVD, 2D case:
|
|
1761
|
+
|
|
1762
|
+
>>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
|
|
1763
|
+
>>> U.shape, S.shape, Vh.shape
|
|
1764
|
+
((9, 9), (6,), (6, 6))
|
|
1765
|
+
>>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
|
|
1766
|
+
True
|
|
1767
|
+
>>> smat = np.zeros((9, 6), dtype=complex)
|
|
1768
|
+
>>> smat[:6, :6] = np.diag(S)
|
|
1769
|
+
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
|
|
1770
|
+
True
|
|
1771
|
+
|
|
1772
|
+
Reconstruction based on reduced SVD, 2D case:
|
|
1773
|
+
|
|
1774
|
+
>>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
|
|
1775
|
+
>>> U.shape, S.shape, Vh.shape
|
|
1776
|
+
((9, 6), (6,), (6, 6))
|
|
1777
|
+
>>> np.allclose(a, np.dot(U * S, Vh))
|
|
1778
|
+
True
|
|
1779
|
+
>>> smat = np.diag(S)
|
|
1780
|
+
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
|
|
1781
|
+
True
|
|
1782
|
+
|
|
1783
|
+
Reconstruction based on full SVD, 4D case:
|
|
1784
|
+
|
|
1785
|
+
>>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
|
|
1786
|
+
>>> U.shape, S.shape, Vh.shape
|
|
1787
|
+
((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
|
|
1788
|
+
>>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
|
|
1789
|
+
True
|
|
1790
|
+
>>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
|
|
1791
|
+
True
|
|
1792
|
+
|
|
1793
|
+
Reconstruction based on reduced SVD, 4D case:
|
|
1794
|
+
|
|
1795
|
+
>>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
|
|
1796
|
+
>>> U.shape, S.shape, Vh.shape
|
|
1797
|
+
((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
|
|
1798
|
+
>>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
|
|
1799
|
+
True
|
|
1800
|
+
>>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
|
|
1801
|
+
True
|
|
1802
|
+
|
|
1803
|
+
"""
|
|
1804
|
+
import numpy as np
|
|
1805
|
+
a, wrap = _makearray(a)
|
|
1806
|
+
|
|
1807
|
+
if hermitian:
|
|
1808
|
+
# note: lapack svd returns eigenvalues with s ** 2 sorted descending,
|
|
1809
|
+
# but eig returns s sorted ascending, so we re-order the eigenvalues
|
|
1810
|
+
# and related arrays to have the correct order
|
|
1811
|
+
if compute_uv:
|
|
1812
|
+
s, u = eigh(a)
|
|
1813
|
+
sgn = sign(s)
|
|
1814
|
+
s = abs(s)
|
|
1815
|
+
sidx = argsort(s)[..., ::-1]
|
|
1816
|
+
sgn = np.take_along_axis(sgn, sidx, axis=-1)
|
|
1817
|
+
s = np.take_along_axis(s, sidx, axis=-1)
|
|
1818
|
+
u = np.take_along_axis(u, sidx[..., None, :], axis=-1)
|
|
1819
|
+
# singular values are unsigned, move the sign into v
|
|
1820
|
+
vt = transpose(u * sgn[..., None, :]).conjugate()
|
|
1821
|
+
return SVDResult(wrap(u), s, wrap(vt))
|
|
1822
|
+
else:
|
|
1823
|
+
s = eigvalsh(a)
|
|
1824
|
+
s = abs(s)
|
|
1825
|
+
return sort(s)[..., ::-1]
|
|
1826
|
+
|
|
1827
|
+
_assert_stacked_2d(a)
|
|
1828
|
+
t, result_t = _commonType(a)
|
|
1829
|
+
|
|
1830
|
+
m, n = a.shape[-2:]
|
|
1831
|
+
if compute_uv:
|
|
1832
|
+
if full_matrices:
|
|
1833
|
+
gufunc = _umath_linalg.svd_f
|
|
1834
|
+
else:
|
|
1835
|
+
gufunc = _umath_linalg.svd_s
|
|
1836
|
+
|
|
1837
|
+
signature = 'D->DdD' if isComplexType(t) else 'd->ddd'
|
|
1838
|
+
with errstate(call=_raise_linalgerror_svd_nonconvergence,
|
|
1839
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1840
|
+
under='ignore'):
|
|
1841
|
+
u, s, vh = gufunc(a, signature=signature)
|
|
1842
|
+
u = u.astype(result_t, copy=False)
|
|
1843
|
+
s = s.astype(_realType(result_t), copy=False)
|
|
1844
|
+
vh = vh.astype(result_t, copy=False)
|
|
1845
|
+
return SVDResult(wrap(u), s, wrap(vh))
|
|
1846
|
+
else:
|
|
1847
|
+
signature = 'D->d' if isComplexType(t) else 'd->d'
|
|
1848
|
+
with errstate(call=_raise_linalgerror_svd_nonconvergence,
|
|
1849
|
+
invalid='call', over='ignore', divide='ignore',
|
|
1850
|
+
under='ignore'):
|
|
1851
|
+
s = _umath_linalg.svd(a, signature=signature)
|
|
1852
|
+
s = s.astype(_realType(result_t), copy=False)
|
|
1853
|
+
return s
|
|
1854
|
+
|
|
1855
|
+
|
|
1856
|
+
def _svdvals_dispatcher(x):
|
|
1857
|
+
return (x,)
|
|
1858
|
+
|
|
1859
|
+
|
|
1860
|
+
@array_function_dispatch(_svdvals_dispatcher)
|
|
1861
|
+
def svdvals(x, /):
|
|
1862
|
+
"""
|
|
1863
|
+
Returns the singular values of a matrix (or a stack of matrices) ``x``.
|
|
1864
|
+
When x is a stack of matrices, the function will compute the singular
|
|
1865
|
+
values for each matrix in the stack.
|
|
1866
|
+
|
|
1867
|
+
This function is Array API compatible.
|
|
1868
|
+
|
|
1869
|
+
Calling ``np.svdvals(x)`` to get singular values is the same as
|
|
1870
|
+
``np.svd(x, compute_uv=False, hermitian=False)``.
|
|
1871
|
+
|
|
1872
|
+
Parameters
|
|
1873
|
+
----------
|
|
1874
|
+
x : (..., M, N) array_like
|
|
1875
|
+
Input array having shape (..., M, N) and whose last two
|
|
1876
|
+
dimensions form matrices on which to perform singular value
|
|
1877
|
+
decomposition. Should have a floating-point data type.
|
|
1878
|
+
|
|
1879
|
+
Returns
|
|
1880
|
+
-------
|
|
1881
|
+
out : ndarray
|
|
1882
|
+
An array with shape (..., K) that contains the vector(s)
|
|
1883
|
+
of singular values of length K, where K = min(M, N).
|
|
1884
|
+
|
|
1885
|
+
See Also
|
|
1886
|
+
--------
|
|
1887
|
+
scipy.linalg.svdvals : Compute singular values of a matrix.
|
|
1888
|
+
|
|
1889
|
+
Examples
|
|
1890
|
+
--------
|
|
1891
|
+
|
|
1892
|
+
>>> np.linalg.svdvals([[1, 2, 3, 4, 5],
|
|
1893
|
+
... [1, 4, 9, 16, 25],
|
|
1894
|
+
... [1, 8, 27, 64, 125]])
|
|
1895
|
+
array([146.68862757, 5.57510612, 0.60393245])
|
|
1896
|
+
|
|
1897
|
+
Determine the rank of a matrix using singular values:
|
|
1898
|
+
|
|
1899
|
+
>>> s = np.linalg.svdvals([[1, 2, 3],
|
|
1900
|
+
... [2, 4, 6],
|
|
1901
|
+
... [-1, 1, -1]]); s
|
|
1902
|
+
array([8.38434191e+00, 1.64402274e+00, 2.31534378e-16])
|
|
1903
|
+
>>> np.count_nonzero(s > 1e-10) # Matrix of rank 2
|
|
1904
|
+
2
|
|
1905
|
+
|
|
1906
|
+
"""
|
|
1907
|
+
return svd(x, compute_uv=False, hermitian=False)
|
|
1908
|
+
|
|
1909
|
+
|
|
1910
|
+
def _cond_dispatcher(x, p=None):
|
|
1911
|
+
return (x,)
|
|
1912
|
+
|
|
1913
|
+
|
|
1914
|
+
@array_function_dispatch(_cond_dispatcher)
|
|
1915
|
+
def cond(x, p=None):
|
|
1916
|
+
"""
|
|
1917
|
+
Compute the condition number of a matrix.
|
|
1918
|
+
|
|
1919
|
+
This function is capable of returning the condition number using
|
|
1920
|
+
one of seven different norms, depending on the value of `p` (see
|
|
1921
|
+
Parameters below).
|
|
1922
|
+
|
|
1923
|
+
Parameters
|
|
1924
|
+
----------
|
|
1925
|
+
x : (..., M, N) array_like
|
|
1926
|
+
The matrix whose condition number is sought.
|
|
1927
|
+
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
|
|
1928
|
+
Order of the norm used in the condition number computation:
|
|
1929
|
+
|
|
1930
|
+
===== ============================
|
|
1931
|
+
p norm for matrices
|
|
1932
|
+
===== ============================
|
|
1933
|
+
None 2-norm, computed directly using the ``SVD``
|
|
1934
|
+
'fro' Frobenius norm
|
|
1935
|
+
inf max(sum(abs(x), axis=1))
|
|
1936
|
+
-inf min(sum(abs(x), axis=1))
|
|
1937
|
+
1 max(sum(abs(x), axis=0))
|
|
1938
|
+
-1 min(sum(abs(x), axis=0))
|
|
1939
|
+
2 2-norm (largest sing. value)
|
|
1940
|
+
-2 smallest singular value
|
|
1941
|
+
===== ============================
|
|
1942
|
+
|
|
1943
|
+
inf means the `numpy.inf` object, and the Frobenius norm is
|
|
1944
|
+
the root-of-sum-of-squares norm.
|
|
1945
|
+
|
|
1946
|
+
Returns
|
|
1947
|
+
-------
|
|
1948
|
+
c : {float, inf}
|
|
1949
|
+
The condition number of the matrix. May be infinite.
|
|
1950
|
+
|
|
1951
|
+
See Also
|
|
1952
|
+
--------
|
|
1953
|
+
numpy.linalg.norm
|
|
1954
|
+
|
|
1955
|
+
Notes
|
|
1956
|
+
-----
|
|
1957
|
+
The condition number of `x` is defined as the norm of `x` times the
|
|
1958
|
+
norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
|
|
1959
|
+
(root-of-sum-of-squares) or one of a number of other matrix norms.
|
|
1960
|
+
|
|
1961
|
+
References
|
|
1962
|
+
----------
|
|
1963
|
+
.. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
|
|
1964
|
+
Academic Press, Inc., 1980, pg. 285.
|
|
1965
|
+
|
|
1966
|
+
Examples
|
|
1967
|
+
--------
|
|
1968
|
+
>>> import numpy as np
|
|
1969
|
+
>>> from numpy import linalg as LA
|
|
1970
|
+
>>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
|
|
1971
|
+
>>> a
|
|
1972
|
+
array([[ 1, 0, -1],
|
|
1973
|
+
[ 0, 1, 0],
|
|
1974
|
+
[ 1, 0, 1]])
|
|
1975
|
+
>>> LA.cond(a)
|
|
1976
|
+
1.4142135623730951
|
|
1977
|
+
>>> LA.cond(a, 'fro')
|
|
1978
|
+
3.1622776601683795
|
|
1979
|
+
>>> LA.cond(a, np.inf)
|
|
1980
|
+
2.0
|
|
1981
|
+
>>> LA.cond(a, -np.inf)
|
|
1982
|
+
1.0
|
|
1983
|
+
>>> LA.cond(a, 1)
|
|
1984
|
+
2.0
|
|
1985
|
+
>>> LA.cond(a, -1)
|
|
1986
|
+
1.0
|
|
1987
|
+
>>> LA.cond(a, 2)
|
|
1988
|
+
1.4142135623730951
|
|
1989
|
+
>>> LA.cond(a, -2)
|
|
1990
|
+
0.70710678118654746 # may vary
|
|
1991
|
+
>>> (min(LA.svd(a, compute_uv=False)) *
|
|
1992
|
+
... min(LA.svd(LA.inv(a), compute_uv=False)))
|
|
1993
|
+
0.70710678118654746 # may vary
|
|
1994
|
+
|
|
1995
|
+
"""
|
|
1996
|
+
x = asarray(x) # in case we have a matrix
|
|
1997
|
+
if _is_empty_2d(x):
|
|
1998
|
+
raise LinAlgError("cond is not defined on empty arrays")
|
|
1999
|
+
if p is None or p in {2, -2}:
|
|
2000
|
+
s = svd(x, compute_uv=False)
|
|
2001
|
+
with errstate(all='ignore'):
|
|
2002
|
+
if p == -2:
|
|
2003
|
+
r = s[..., -1] / s[..., 0]
|
|
2004
|
+
else:
|
|
2005
|
+
r = s[..., 0] / s[..., -1]
|
|
2006
|
+
else:
|
|
2007
|
+
# Call inv(x) ignoring errors. The result array will
|
|
2008
|
+
# contain nans in the entries where inversion failed.
|
|
2009
|
+
_assert_stacked_square(x)
|
|
2010
|
+
t, result_t = _commonType(x)
|
|
2011
|
+
result_t = _realType(result_t) # condition number is always real
|
|
2012
|
+
signature = 'D->D' if isComplexType(t) else 'd->d'
|
|
2013
|
+
with errstate(all='ignore'):
|
|
2014
|
+
invx = _umath_linalg.inv(x, signature=signature)
|
|
2015
|
+
r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1))
|
|
2016
|
+
r = r.astype(result_t, copy=False)
|
|
2017
|
+
|
|
2018
|
+
# Convert nans to infs unless the original array had nan entries
|
|
2019
|
+
nan_mask = isnan(r)
|
|
2020
|
+
if nan_mask.any():
|
|
2021
|
+
nan_mask &= ~isnan(x).any(axis=(-2, -1))
|
|
2022
|
+
if r.ndim > 0:
|
|
2023
|
+
r[nan_mask] = inf
|
|
2024
|
+
elif nan_mask:
|
|
2025
|
+
# Convention is to return scalars instead of 0d arrays.
|
|
2026
|
+
r = r.dtype.type(inf)
|
|
2027
|
+
|
|
2028
|
+
return r
|
|
2029
|
+
|
|
2030
|
+
|
|
2031
|
+
def _matrix_rank_dispatcher(A, tol=None, hermitian=None, *, rtol=None):
|
|
2032
|
+
return (A,)
|
|
2033
|
+
|
|
2034
|
+
|
|
2035
|
+
@array_function_dispatch(_matrix_rank_dispatcher)
|
|
2036
|
+
def matrix_rank(A, tol=None, hermitian=False, *, rtol=None):
|
|
2037
|
+
"""
|
|
2038
|
+
Return matrix rank of array using SVD method
|
|
2039
|
+
|
|
2040
|
+
Rank of the array is the number of singular values of the array that are
|
|
2041
|
+
greater than `tol`.
|
|
2042
|
+
|
|
2043
|
+
Parameters
|
|
2044
|
+
----------
|
|
2045
|
+
A : {(M,), (..., M, N)} array_like
|
|
2046
|
+
Input vector or stack of matrices.
|
|
2047
|
+
tol : (...) array_like, float, optional
|
|
2048
|
+
Threshold below which SVD values are considered zero. If `tol` is
|
|
2049
|
+
None, and ``S`` is an array with singular values for `M`, and
|
|
2050
|
+
``eps`` is the epsilon value for datatype of ``S``, then `tol` is
|
|
2051
|
+
set to ``S.max() * max(M, N) * eps``.
|
|
2052
|
+
hermitian : bool, optional
|
|
2053
|
+
If True, `A` is assumed to be Hermitian (symmetric if real-valued),
|
|
2054
|
+
enabling a more efficient method for finding singular values.
|
|
2055
|
+
Defaults to False.
|
|
2056
|
+
rtol : (...) array_like, float, optional
|
|
2057
|
+
Parameter for the relative tolerance component. Only ``tol`` or
|
|
2058
|
+
``rtol`` can be set at a time. Defaults to ``max(M, N) * eps``.
|
|
2059
|
+
|
|
2060
|
+
.. versionadded:: 2.0.0
|
|
2061
|
+
|
|
2062
|
+
Returns
|
|
2063
|
+
-------
|
|
2064
|
+
rank : (...) array_like
|
|
2065
|
+
Rank of A.
|
|
2066
|
+
|
|
2067
|
+
Notes
|
|
2068
|
+
-----
|
|
2069
|
+
The default threshold to detect rank deficiency is a test on the magnitude
|
|
2070
|
+
of the singular values of `A`. By default, we identify singular values
|
|
2071
|
+
less than ``S.max() * max(M, N) * eps`` as indicating rank deficiency
|
|
2072
|
+
(with the symbols defined above). This is the algorithm MATLAB uses [1]_.
|
|
2073
|
+
It also appears in *Numerical recipes* in the discussion of SVD solutions
|
|
2074
|
+
for linear least squares [2]_.
|
|
2075
|
+
|
|
2076
|
+
This default threshold is designed to detect rank deficiency accounting
|
|
2077
|
+
for the numerical errors of the SVD computation. Imagine that there
|
|
2078
|
+
is a column in `A` that is an exact (in floating point) linear combination
|
|
2079
|
+
of other columns in `A`. Computing the SVD on `A` will not produce
|
|
2080
|
+
a singular value exactly equal to 0 in general: any difference of
|
|
2081
|
+
the smallest SVD value from 0 will be caused by numerical imprecision
|
|
2082
|
+
in the calculation of the SVD. Our threshold for small SVD values takes
|
|
2083
|
+
this numerical imprecision into account, and the default threshold will
|
|
2084
|
+
detect such numerical rank deficiency. The threshold may declare a matrix
|
|
2085
|
+
`A` rank deficient even if the linear combination of some columns of `A`
|
|
2086
|
+
is not exactly equal to another column of `A` but only numerically very
|
|
2087
|
+
close to another column of `A`.
|
|
2088
|
+
|
|
2089
|
+
We chose our default threshold because it is in wide use. Other thresholds
|
|
2090
|
+
are possible. For example, elsewhere in the 2007 edition of *Numerical
|
|
2091
|
+
recipes* there is an alternative threshold of ``S.max() *
|
|
2092
|
+
np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
|
|
2093
|
+
this threshold as being based on "expected roundoff error" (p 71).
|
|
2094
|
+
|
|
2095
|
+
The thresholds above deal with floating point roundoff error in the
|
|
2096
|
+
calculation of the SVD. However, you may have more information about
|
|
2097
|
+
the sources of error in `A` that would make you consider other tolerance
|
|
2098
|
+
values to detect *effective* rank deficiency. The most useful measure
|
|
2099
|
+
of the tolerance depends on the operations you intend to use on your
|
|
2100
|
+
matrix. For example, if your data come from uncertain measurements with
|
|
2101
|
+
uncertainties greater than floating point epsilon, choosing a tolerance
|
|
2102
|
+
near that uncertainty may be preferable. The tolerance may be absolute
|
|
2103
|
+
if the uncertainties are absolute rather than relative.
|
|
2104
|
+
|
|
2105
|
+
References
|
|
2106
|
+
----------
|
|
2107
|
+
.. [1] MATLAB reference documentation, "Rank"
|
|
2108
|
+
https://www.mathworks.com/help/techdoc/ref/rank.html
|
|
2109
|
+
.. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
|
|
2110
|
+
"Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
|
|
2111
|
+
page 795.
|
|
2112
|
+
|
|
2113
|
+
Examples
|
|
2114
|
+
--------
|
|
2115
|
+
>>> import numpy as np
|
|
2116
|
+
>>> from numpy.linalg import matrix_rank
|
|
2117
|
+
>>> matrix_rank(np.eye(4)) # Full rank matrix
|
|
2118
|
+
4
|
|
2119
|
+
>>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
|
|
2120
|
+
>>> matrix_rank(I)
|
|
2121
|
+
3
|
|
2122
|
+
>>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
|
|
2123
|
+
1
|
|
2124
|
+
>>> matrix_rank(np.zeros((4,)))
|
|
2125
|
+
0
|
|
2126
|
+
"""
|
|
2127
|
+
if rtol is not None and tol is not None:
|
|
2128
|
+
raise ValueError("`tol` and `rtol` can't be both set.")
|
|
2129
|
+
|
|
2130
|
+
A = asarray(A)
|
|
2131
|
+
if A.ndim < 2:
|
|
2132
|
+
return int(not all(A == 0))
|
|
2133
|
+
S = svd(A, compute_uv=False, hermitian=hermitian)
|
|
2134
|
+
|
|
2135
|
+
if tol is None:
|
|
2136
|
+
if rtol is None:
|
|
2137
|
+
rtol = max(A.shape[-2:]) * finfo(S.dtype).eps
|
|
2138
|
+
else:
|
|
2139
|
+
rtol = asarray(rtol)[..., newaxis]
|
|
2140
|
+
tol = S.max(axis=-1, keepdims=True) * rtol
|
|
2141
|
+
else:
|
|
2142
|
+
tol = asarray(tol)[..., newaxis]
|
|
2143
|
+
|
|
2144
|
+
return count_nonzero(S > tol, axis=-1)
|
|
2145
|
+
|
|
2146
|
+
|
|
2147
|
+
# Generalized inverse
|
|
2148
|
+
|
|
2149
|
+
def _pinv_dispatcher(a, rcond=None, hermitian=None, *, rtol=None):
|
|
2150
|
+
return (a,)
|
|
2151
|
+
|
|
2152
|
+
|
|
2153
|
+
@array_function_dispatch(_pinv_dispatcher)
|
|
2154
|
+
def pinv(a, rcond=None, hermitian=False, *, rtol=_NoValue):
|
|
2155
|
+
"""
|
|
2156
|
+
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
|
|
2157
|
+
|
|
2158
|
+
Calculate the generalized inverse of a matrix using its
|
|
2159
|
+
singular-value decomposition (SVD) and including all
|
|
2160
|
+
*large* singular values.
|
|
2161
|
+
|
|
2162
|
+
Parameters
|
|
2163
|
+
----------
|
|
2164
|
+
a : (..., M, N) array_like
|
|
2165
|
+
Matrix or stack of matrices to be pseudo-inverted.
|
|
2166
|
+
rcond : (...) array_like of float, optional
|
|
2167
|
+
Cutoff for small singular values.
|
|
2168
|
+
Singular values less than or equal to
|
|
2169
|
+
``rcond * largest_singular_value`` are set to zero.
|
|
2170
|
+
Broadcasts against the stack of matrices. Default: ``1e-15``.
|
|
2171
|
+
hermitian : bool, optional
|
|
2172
|
+
If True, `a` is assumed to be Hermitian (symmetric if real-valued),
|
|
2173
|
+
enabling a more efficient method for finding singular values.
|
|
2174
|
+
Defaults to False.
|
|
2175
|
+
rtol : (...) array_like of float, optional
|
|
2176
|
+
Same as `rcond`, but it's an Array API compatible parameter name.
|
|
2177
|
+
Only `rcond` or `rtol` can be set at a time. If none of them are
|
|
2178
|
+
provided then NumPy's ``1e-15`` default is used. If ``rtol=None``
|
|
2179
|
+
is passed then the API standard default is used.
|
|
2180
|
+
|
|
2181
|
+
.. versionadded:: 2.0.0
|
|
2182
|
+
|
|
2183
|
+
Returns
|
|
2184
|
+
-------
|
|
2185
|
+
B : (..., N, M) ndarray
|
|
2186
|
+
The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
|
|
2187
|
+
is `B`.
|
|
2188
|
+
|
|
2189
|
+
Raises
|
|
2190
|
+
------
|
|
2191
|
+
LinAlgError
|
|
2192
|
+
If the SVD computation does not converge.
|
|
2193
|
+
|
|
2194
|
+
See Also
|
|
2195
|
+
--------
|
|
2196
|
+
scipy.linalg.pinv : Similar function in SciPy.
|
|
2197
|
+
scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
|
|
2198
|
+
Hermitian matrix.
|
|
2199
|
+
|
|
2200
|
+
Notes
|
|
2201
|
+
-----
|
|
2202
|
+
The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
|
|
2203
|
+
defined as: "the matrix that 'solves' [the least-squares problem]
|
|
2204
|
+
:math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
|
|
2205
|
+
:math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
|
|
2206
|
+
|
|
2207
|
+
It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
|
|
2208
|
+
value decomposition of A, then
|
|
2209
|
+
:math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
|
|
2210
|
+
orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
|
|
2211
|
+
of A's so-called singular values, (followed, typically, by
|
|
2212
|
+
zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
|
|
2213
|
+
consisting of the reciprocals of A's singular values
|
|
2214
|
+
(again, followed by zeros). [1]_
|
|
2215
|
+
|
|
2216
|
+
References
|
|
2217
|
+
----------
|
|
2218
|
+
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
|
|
2219
|
+
FL, Academic Press, Inc., 1980, pp. 139-142.
|
|
2220
|
+
|
|
2221
|
+
Examples
|
|
2222
|
+
--------
|
|
2223
|
+
The following example checks that ``a * a+ * a == a`` and
|
|
2224
|
+
``a+ * a * a+ == a+``:
|
|
2225
|
+
|
|
2226
|
+
>>> import numpy as np
|
|
2227
|
+
>>> rng = np.random.default_rng()
|
|
2228
|
+
>>> a = rng.normal(size=(9, 6))
|
|
2229
|
+
>>> B = np.linalg.pinv(a)
|
|
2230
|
+
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
|
|
2231
|
+
True
|
|
2232
|
+
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
|
|
2233
|
+
True
|
|
2234
|
+
|
|
2235
|
+
"""
|
|
2236
|
+
a, wrap = _makearray(a)
|
|
2237
|
+
if rcond is None:
|
|
2238
|
+
if rtol is _NoValue:
|
|
2239
|
+
rcond = 1e-15
|
|
2240
|
+
elif rtol is None:
|
|
2241
|
+
rcond = max(a.shape[-2:]) * finfo(a.dtype).eps
|
|
2242
|
+
else:
|
|
2243
|
+
rcond = rtol
|
|
2244
|
+
elif rtol is not _NoValue:
|
|
2245
|
+
raise ValueError("`rtol` and `rcond` can't be both set.")
|
|
2246
|
+
else:
|
|
2247
|
+
# NOTE: Deprecate `rcond` in a few versions.
|
|
2248
|
+
pass
|
|
2249
|
+
|
|
2250
|
+
rcond = asarray(rcond)
|
|
2251
|
+
if _is_empty_2d(a):
|
|
2252
|
+
m, n = a.shape[-2:]
|
|
2253
|
+
res = empty(a.shape[:-2] + (n, m), dtype=a.dtype)
|
|
2254
|
+
return wrap(res)
|
|
2255
|
+
a = a.conjugate()
|
|
2256
|
+
u, s, vt = svd(a, full_matrices=False, hermitian=hermitian)
|
|
2257
|
+
|
|
2258
|
+
# discard small singular values
|
|
2259
|
+
cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True)
|
|
2260
|
+
large = s > cutoff
|
|
2261
|
+
s = divide(1, s, where=large, out=s)
|
|
2262
|
+
s[~large] = 0
|
|
2263
|
+
|
|
2264
|
+
res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u)))
|
|
2265
|
+
return wrap(res)
|
|
2266
|
+
|
|
2267
|
+
|
|
2268
|
+
# Determinant
|
|
2269
|
+
|
|
2270
|
+
|
|
2271
|
+
@array_function_dispatch(_unary_dispatcher)
|
|
2272
|
+
def slogdet(a):
|
|
2273
|
+
"""
|
|
2274
|
+
Compute the sign and (natural) logarithm of the determinant of an array.
|
|
2275
|
+
|
|
2276
|
+
If an array has a very small or very large determinant, then a call to
|
|
2277
|
+
`det` may overflow or underflow. This routine is more robust against such
|
|
2278
|
+
issues, because it computes the logarithm of the determinant rather than
|
|
2279
|
+
the determinant itself.
|
|
2280
|
+
|
|
2281
|
+
Parameters
|
|
2282
|
+
----------
|
|
2283
|
+
a : (..., M, M) array_like
|
|
2284
|
+
Input array, has to be a square 2-D array.
|
|
2285
|
+
|
|
2286
|
+
Returns
|
|
2287
|
+
-------
|
|
2288
|
+
A namedtuple with the following attributes:
|
|
2289
|
+
|
|
2290
|
+
sign : (...) array_like
|
|
2291
|
+
A number representing the sign of the determinant. For a real matrix,
|
|
2292
|
+
this is 1, 0, or -1. For a complex matrix, this is a complex number
|
|
2293
|
+
with absolute value 1 (i.e., it is on the unit circle), or else 0.
|
|
2294
|
+
logabsdet : (...) array_like
|
|
2295
|
+
The natural log of the absolute value of the determinant.
|
|
2296
|
+
|
|
2297
|
+
If the determinant is zero, then `sign` will be 0 and `logabsdet`
|
|
2298
|
+
will be -inf. In all cases, the determinant is equal to
|
|
2299
|
+
``sign * np.exp(logabsdet)``.
|
|
2300
|
+
|
|
2301
|
+
See Also
|
|
2302
|
+
--------
|
|
2303
|
+
det
|
|
2304
|
+
|
|
2305
|
+
Notes
|
|
2306
|
+
-----
|
|
2307
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
2308
|
+
details.
|
|
2309
|
+
|
|
2310
|
+
The determinant is computed via LU factorization using the LAPACK
|
|
2311
|
+
routine ``z/dgetrf``.
|
|
2312
|
+
|
|
2313
|
+
Examples
|
|
2314
|
+
--------
|
|
2315
|
+
The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
|
|
2316
|
+
|
|
2317
|
+
>>> import numpy as np
|
|
2318
|
+
>>> a = np.array([[1, 2], [3, 4]])
|
|
2319
|
+
>>> (sign, logabsdet) = np.linalg.slogdet(a)
|
|
2320
|
+
>>> (sign, logabsdet)
|
|
2321
|
+
(-1, 0.69314718055994529) # may vary
|
|
2322
|
+
>>> sign * np.exp(logabsdet)
|
|
2323
|
+
-2.0
|
|
2324
|
+
|
|
2325
|
+
Computing log-determinants for a stack of matrices:
|
|
2326
|
+
|
|
2327
|
+
>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
|
|
2328
|
+
>>> a.shape
|
|
2329
|
+
(3, 2, 2)
|
|
2330
|
+
>>> sign, logabsdet = np.linalg.slogdet(a)
|
|
2331
|
+
>>> (sign, logabsdet)
|
|
2332
|
+
(array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154]))
|
|
2333
|
+
>>> sign * np.exp(logabsdet)
|
|
2334
|
+
array([-2., -3., -8.])
|
|
2335
|
+
|
|
2336
|
+
This routine succeeds where ordinary `det` does not:
|
|
2337
|
+
|
|
2338
|
+
>>> np.linalg.det(np.eye(500) * 0.1)
|
|
2339
|
+
0.0
|
|
2340
|
+
>>> np.linalg.slogdet(np.eye(500) * 0.1)
|
|
2341
|
+
(1, -1151.2925464970228)
|
|
2342
|
+
|
|
2343
|
+
"""
|
|
2344
|
+
a = asarray(a)
|
|
2345
|
+
_assert_stacked_square(a)
|
|
2346
|
+
t, result_t = _commonType(a)
|
|
2347
|
+
real_t = _realType(result_t)
|
|
2348
|
+
signature = 'D->Dd' if isComplexType(t) else 'd->dd'
|
|
2349
|
+
sign, logdet = _umath_linalg.slogdet(a, signature=signature)
|
|
2350
|
+
sign = sign.astype(result_t, copy=False)
|
|
2351
|
+
logdet = logdet.astype(real_t, copy=False)
|
|
2352
|
+
return SlogdetResult(sign, logdet)
|
|
2353
|
+
|
|
2354
|
+
|
|
2355
|
+
@array_function_dispatch(_unary_dispatcher)
|
|
2356
|
+
def det(a):
|
|
2357
|
+
"""
|
|
2358
|
+
Compute the determinant of an array.
|
|
2359
|
+
|
|
2360
|
+
Parameters
|
|
2361
|
+
----------
|
|
2362
|
+
a : (..., M, M) array_like
|
|
2363
|
+
Input array to compute determinants for.
|
|
2364
|
+
|
|
2365
|
+
Returns
|
|
2366
|
+
-------
|
|
2367
|
+
det : (...) array_like
|
|
2368
|
+
Determinant of `a`.
|
|
2369
|
+
|
|
2370
|
+
See Also
|
|
2371
|
+
--------
|
|
2372
|
+
slogdet : Another way to represent the determinant, more suitable
|
|
2373
|
+
for large matrices where underflow/overflow may occur.
|
|
2374
|
+
scipy.linalg.det : Similar function in SciPy.
|
|
2375
|
+
|
|
2376
|
+
Notes
|
|
2377
|
+
-----
|
|
2378
|
+
Broadcasting rules apply, see the `numpy.linalg` documentation for
|
|
2379
|
+
details.
|
|
2380
|
+
|
|
2381
|
+
The determinant is computed via LU factorization using the LAPACK
|
|
2382
|
+
routine ``z/dgetrf``.
|
|
2383
|
+
|
|
2384
|
+
Examples
|
|
2385
|
+
--------
|
|
2386
|
+
The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
|
|
2387
|
+
|
|
2388
|
+
>>> import numpy as np
|
|
2389
|
+
>>> a = np.array([[1, 2], [3, 4]])
|
|
2390
|
+
>>> np.linalg.det(a)
|
|
2391
|
+
-2.0 # may vary
|
|
2392
|
+
|
|
2393
|
+
Computing determinants for a stack of matrices:
|
|
2394
|
+
|
|
2395
|
+
>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
|
|
2396
|
+
>>> a.shape
|
|
2397
|
+
(3, 2, 2)
|
|
2398
|
+
>>> np.linalg.det(a)
|
|
2399
|
+
array([-2., -3., -8.])
|
|
2400
|
+
|
|
2401
|
+
"""
|
|
2402
|
+
a = asarray(a)
|
|
2403
|
+
_assert_stacked_square(a)
|
|
2404
|
+
t, result_t = _commonType(a)
|
|
2405
|
+
signature = 'D->D' if isComplexType(t) else 'd->d'
|
|
2406
|
+
r = _umath_linalg.det(a, signature=signature)
|
|
2407
|
+
r = r.astype(result_t, copy=False)
|
|
2408
|
+
return r
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
# Linear Least Squares
|
|
2412
|
+
|
|
2413
|
+
def _lstsq_dispatcher(a, b, rcond=None):
|
|
2414
|
+
return (a, b)
|
|
2415
|
+
|
|
2416
|
+
|
|
2417
|
+
@array_function_dispatch(_lstsq_dispatcher)
|
|
2418
|
+
def lstsq(a, b, rcond=None):
|
|
2419
|
+
r"""
|
|
2420
|
+
Return the least-squares solution to a linear matrix equation.
|
|
2421
|
+
|
|
2422
|
+
Computes the vector `x` that approximately solves the equation
|
|
2423
|
+
``a @ x = b``. The equation may be under-, well-, or over-determined
|
|
2424
|
+
(i.e., the number of linearly independent rows of `a` can be less than,
|
|
2425
|
+
equal to, or greater than its number of linearly independent columns).
|
|
2426
|
+
If `a` is square and of full rank, then `x` (but for round-off error)
|
|
2427
|
+
is the "exact" solution of the equation. Else, `x` minimizes the
|
|
2428
|
+
Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
|
|
2429
|
+
solutions, the one with the smallest 2-norm :math:`||x||` is returned.
|
|
2430
|
+
|
|
2431
|
+
Parameters
|
|
2432
|
+
----------
|
|
2433
|
+
a : (M, N) array_like
|
|
2434
|
+
"Coefficient" matrix.
|
|
2435
|
+
b : {(M,), (M, K)} array_like
|
|
2436
|
+
Ordinate or "dependent variable" values. If `b` is two-dimensional,
|
|
2437
|
+
the least-squares solution is calculated for each of the `K` columns
|
|
2438
|
+
of `b`.
|
|
2439
|
+
rcond : float, optional
|
|
2440
|
+
Cut-off ratio for small singular values of `a`.
|
|
2441
|
+
For the purposes of rank determination, singular values are treated
|
|
2442
|
+
as zero if they are smaller than `rcond` times the largest singular
|
|
2443
|
+
value of `a`.
|
|
2444
|
+
The default uses the machine precision times ``max(M, N)``. Passing
|
|
2445
|
+
``-1`` will use machine precision.
|
|
2446
|
+
|
|
2447
|
+
.. versionchanged:: 2.0
|
|
2448
|
+
Previously, the default was ``-1``, but a warning was given that
|
|
2449
|
+
this would change.
|
|
2450
|
+
|
|
2451
|
+
Returns
|
|
2452
|
+
-------
|
|
2453
|
+
x : {(N,), (N, K)} ndarray
|
|
2454
|
+
Least-squares solution. If `b` is two-dimensional,
|
|
2455
|
+
the solutions are in the `K` columns of `x`.
|
|
2456
|
+
residuals : {(1,), (K,), (0,)} ndarray
|
|
2457
|
+
Sums of squared residuals: Squared Euclidean 2-norm for each column in
|
|
2458
|
+
``b - a @ x``.
|
|
2459
|
+
If the rank of `a` is < N or M <= N, this is an empty array.
|
|
2460
|
+
If `b` is 1-dimensional, this is a (1,) shape array.
|
|
2461
|
+
Otherwise the shape is (K,).
|
|
2462
|
+
rank : int
|
|
2463
|
+
Rank of matrix `a`.
|
|
2464
|
+
s : (min(M, N),) ndarray
|
|
2465
|
+
Singular values of `a`.
|
|
2466
|
+
|
|
2467
|
+
Raises
|
|
2468
|
+
------
|
|
2469
|
+
LinAlgError
|
|
2470
|
+
If computation does not converge.
|
|
2471
|
+
|
|
2472
|
+
See Also
|
|
2473
|
+
--------
|
|
2474
|
+
scipy.linalg.lstsq : Similar function in SciPy.
|
|
2475
|
+
|
|
2476
|
+
Notes
|
|
2477
|
+
-----
|
|
2478
|
+
If `b` is a matrix, then all array results are returned as matrices.
|
|
2479
|
+
|
|
2480
|
+
Examples
|
|
2481
|
+
--------
|
|
2482
|
+
Fit a line, ``y = mx + c``, through some noisy data-points:
|
|
2483
|
+
|
|
2484
|
+
>>> import numpy as np
|
|
2485
|
+
>>> x = np.array([0, 1, 2, 3])
|
|
2486
|
+
>>> y = np.array([-1, 0.2, 0.9, 2.1])
|
|
2487
|
+
|
|
2488
|
+
By examining the coefficients, we see that the line should have a
|
|
2489
|
+
gradient of roughly 1 and cut the y-axis at, more or less, -1.
|
|
2490
|
+
|
|
2491
|
+
We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
|
|
2492
|
+
and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
|
|
2493
|
+
|
|
2494
|
+
>>> A = np.vstack([x, np.ones(len(x))]).T
|
|
2495
|
+
>>> A
|
|
2496
|
+
array([[ 0., 1.],
|
|
2497
|
+
[ 1., 1.],
|
|
2498
|
+
[ 2., 1.],
|
|
2499
|
+
[ 3., 1.]])
|
|
2500
|
+
|
|
2501
|
+
>>> m, c = np.linalg.lstsq(A, y)[0]
|
|
2502
|
+
>>> m, c
|
|
2503
|
+
(1.0 -0.95) # may vary
|
|
2504
|
+
|
|
2505
|
+
Plot the data along with the fitted line:
|
|
2506
|
+
|
|
2507
|
+
>>> import matplotlib.pyplot as plt
|
|
2508
|
+
>>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
|
|
2509
|
+
>>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
|
|
2510
|
+
>>> _ = plt.legend()
|
|
2511
|
+
>>> plt.show()
|
|
2512
|
+
|
|
2513
|
+
"""
|
|
2514
|
+
a, _ = _makearray(a)
|
|
2515
|
+
b, wrap = _makearray(b)
|
|
2516
|
+
is_1d = b.ndim == 1
|
|
2517
|
+
if is_1d:
|
|
2518
|
+
b = b[:, newaxis]
|
|
2519
|
+
_assert_2d(a, b)
|
|
2520
|
+
m, n = a.shape[-2:]
|
|
2521
|
+
m2, n_rhs = b.shape[-2:]
|
|
2522
|
+
if m != m2:
|
|
2523
|
+
raise LinAlgError('Incompatible dimensions')
|
|
2524
|
+
|
|
2525
|
+
t, result_t = _commonType(a, b)
|
|
2526
|
+
result_real_t = _realType(result_t)
|
|
2527
|
+
|
|
2528
|
+
if rcond is None:
|
|
2529
|
+
rcond = finfo(t).eps * max(n, m)
|
|
2530
|
+
|
|
2531
|
+
signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid'
|
|
2532
|
+
if n_rhs == 0:
|
|
2533
|
+
# lapack can't handle n_rhs = 0 - so allocate
|
|
2534
|
+
# the array one larger in that axis
|
|
2535
|
+
b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype)
|
|
2536
|
+
|
|
2537
|
+
with errstate(call=_raise_linalgerror_lstsq, invalid='call',
|
|
2538
|
+
over='ignore', divide='ignore', under='ignore'):
|
|
2539
|
+
x, resids, rank, s = _umath_linalg.lstsq(a, b, rcond,
|
|
2540
|
+
signature=signature)
|
|
2541
|
+
if m == 0:
|
|
2542
|
+
x[...] = 0
|
|
2543
|
+
if n_rhs == 0:
|
|
2544
|
+
# remove the item we added
|
|
2545
|
+
x = x[..., :n_rhs]
|
|
2546
|
+
resids = resids[..., :n_rhs]
|
|
2547
|
+
|
|
2548
|
+
# remove the axis we added
|
|
2549
|
+
if is_1d:
|
|
2550
|
+
x = x.squeeze(axis=-1)
|
|
2551
|
+
# we probably should squeeze resids too, but we can't
|
|
2552
|
+
# without breaking compatibility.
|
|
2553
|
+
|
|
2554
|
+
# as documented
|
|
2555
|
+
if rank != n or m <= n:
|
|
2556
|
+
resids = array([], result_real_t)
|
|
2557
|
+
|
|
2558
|
+
# coerce output arrays
|
|
2559
|
+
s = s.astype(result_real_t, copy=False)
|
|
2560
|
+
resids = resids.astype(result_real_t, copy=False)
|
|
2561
|
+
# Copying lets the memory in r_parts be freed
|
|
2562
|
+
x = x.astype(result_t, copy=True)
|
|
2563
|
+
return wrap(x), wrap(resids), rank, s
|
|
2564
|
+
|
|
2565
|
+
|
|
2566
|
+
def _multi_svd_norm(x, row_axis, col_axis, op, initial=None):
|
|
2567
|
+
"""Compute a function of the singular values of the 2-D matrices in `x`.
|
|
2568
|
+
|
|
2569
|
+
This is a private utility function used by `numpy.linalg.norm()`.
|
|
2570
|
+
|
|
2571
|
+
Parameters
|
|
2572
|
+
----------
|
|
2573
|
+
x : ndarray
|
|
2574
|
+
row_axis, col_axis : int
|
|
2575
|
+
The axes of `x` that hold the 2-D matrices.
|
|
2576
|
+
op : callable
|
|
2577
|
+
This should be either numpy.amin or `numpy.amax` or `numpy.sum`.
|
|
2578
|
+
|
|
2579
|
+
Returns
|
|
2580
|
+
-------
|
|
2581
|
+
result : float or ndarray
|
|
2582
|
+
If `x` is 2-D, the return values is a float.
|
|
2583
|
+
Otherwise, it is an array with ``x.ndim - 2`` dimensions.
|
|
2584
|
+
The return values are either the minimum or maximum or sum of the
|
|
2585
|
+
singular values of the matrices, depending on whether `op`
|
|
2586
|
+
is `numpy.amin` or `numpy.amax` or `numpy.sum`.
|
|
2587
|
+
|
|
2588
|
+
"""
|
|
2589
|
+
y = moveaxis(x, (row_axis, col_axis), (-2, -1))
|
|
2590
|
+
result = op(svd(y, compute_uv=False), axis=-1, initial=initial)
|
|
2591
|
+
return result
|
|
2592
|
+
|
|
2593
|
+
|
|
2594
|
+
def _norm_dispatcher(x, ord=None, axis=None, keepdims=None):
|
|
2595
|
+
return (x,)
|
|
2596
|
+
|
|
2597
|
+
|
|
2598
|
+
@array_function_dispatch(_norm_dispatcher)
|
|
2599
|
+
def norm(x, ord=None, axis=None, keepdims=False):
|
|
2600
|
+
"""
|
|
2601
|
+
Matrix or vector norm.
|
|
2602
|
+
|
|
2603
|
+
This function is able to return one of eight different matrix norms,
|
|
2604
|
+
or one of an infinite number of vector norms (described below), depending
|
|
2605
|
+
on the value of the ``ord`` parameter.
|
|
2606
|
+
|
|
2607
|
+
Parameters
|
|
2608
|
+
----------
|
|
2609
|
+
x : array_like
|
|
2610
|
+
Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
|
|
2611
|
+
is None. If both `axis` and `ord` are None, the 2-norm of
|
|
2612
|
+
``x.ravel`` will be returned.
|
|
2613
|
+
ord : {int, float, inf, -inf, 'fro', 'nuc'}, optional
|
|
2614
|
+
Order of the norm (see table under ``Notes`` for what values are
|
|
2615
|
+
supported for matrices and vectors respectively). inf means numpy's
|
|
2616
|
+
`inf` object. The default is None.
|
|
2617
|
+
axis : {None, int, 2-tuple of ints}, optional.
|
|
2618
|
+
If `axis` is an integer, it specifies the axis of `x` along which to
|
|
2619
|
+
compute the vector norms. If `axis` is a 2-tuple, it specifies the
|
|
2620
|
+
axes that hold 2-D matrices, and the matrix norms of these matrices
|
|
2621
|
+
are computed. If `axis` is None then either a vector norm (when `x`
|
|
2622
|
+
is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
|
|
2623
|
+
is None.
|
|
2624
|
+
|
|
2625
|
+
keepdims : bool, optional
|
|
2626
|
+
If this is set to True, the axes which are normed over are left in the
|
|
2627
|
+
result as dimensions with size one. With this option the result will
|
|
2628
|
+
broadcast correctly against the original `x`.
|
|
2629
|
+
|
|
2630
|
+
Returns
|
|
2631
|
+
-------
|
|
2632
|
+
n : float or ndarray
|
|
2633
|
+
Norm of the matrix or vector(s).
|
|
2634
|
+
|
|
2635
|
+
See Also
|
|
2636
|
+
--------
|
|
2637
|
+
scipy.linalg.norm : Similar function in SciPy.
|
|
2638
|
+
|
|
2639
|
+
Notes
|
|
2640
|
+
-----
|
|
2641
|
+
For values of ``ord < 1``, the result is, strictly speaking, not a
|
|
2642
|
+
mathematical 'norm', but it may still be useful for various numerical
|
|
2643
|
+
purposes.
|
|
2644
|
+
|
|
2645
|
+
The following norms can be calculated:
|
|
2646
|
+
|
|
2647
|
+
===== ============================ ==========================
|
|
2648
|
+
ord norm for matrices norm for vectors
|
|
2649
|
+
===== ============================ ==========================
|
|
2650
|
+
None Frobenius norm 2-norm
|
|
2651
|
+
'fro' Frobenius norm --
|
|
2652
|
+
'nuc' nuclear norm --
|
|
2653
|
+
inf max(sum(abs(x), axis=1)) max(abs(x))
|
|
2654
|
+
-inf min(sum(abs(x), axis=1)) min(abs(x))
|
|
2655
|
+
0 -- sum(x != 0)
|
|
2656
|
+
1 max(sum(abs(x), axis=0)) as below
|
|
2657
|
+
-1 min(sum(abs(x), axis=0)) as below
|
|
2658
|
+
2 2-norm (largest sing. value) as below
|
|
2659
|
+
-2 smallest singular value as below
|
|
2660
|
+
other -- sum(abs(x)**ord)**(1./ord)
|
|
2661
|
+
===== ============================ ==========================
|
|
2662
|
+
|
|
2663
|
+
The Frobenius norm is given by [1]_:
|
|
2664
|
+
|
|
2665
|
+
:math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
|
|
2666
|
+
|
|
2667
|
+
The nuclear norm is the sum of the singular values.
|
|
2668
|
+
|
|
2669
|
+
Both the Frobenius and nuclear norm orders are only defined for
|
|
2670
|
+
matrices and raise a ValueError when ``x.ndim != 2``.
|
|
2671
|
+
|
|
2672
|
+
References
|
|
2673
|
+
----------
|
|
2674
|
+
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
|
|
2675
|
+
Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
|
|
2676
|
+
|
|
2677
|
+
Examples
|
|
2678
|
+
--------
|
|
2679
|
+
|
|
2680
|
+
>>> import numpy as np
|
|
2681
|
+
>>> from numpy import linalg as LA
|
|
2682
|
+
>>> a = np.arange(9) - 4
|
|
2683
|
+
>>> a
|
|
2684
|
+
array([-4, -3, -2, ..., 2, 3, 4])
|
|
2685
|
+
>>> b = a.reshape((3, 3))
|
|
2686
|
+
>>> b
|
|
2687
|
+
array([[-4, -3, -2],
|
|
2688
|
+
[-1, 0, 1],
|
|
2689
|
+
[ 2, 3, 4]])
|
|
2690
|
+
|
|
2691
|
+
>>> LA.norm(a)
|
|
2692
|
+
7.745966692414834
|
|
2693
|
+
>>> LA.norm(b)
|
|
2694
|
+
7.745966692414834
|
|
2695
|
+
>>> LA.norm(b, 'fro')
|
|
2696
|
+
7.745966692414834
|
|
2697
|
+
>>> LA.norm(a, np.inf)
|
|
2698
|
+
4.0
|
|
2699
|
+
>>> LA.norm(b, np.inf)
|
|
2700
|
+
9.0
|
|
2701
|
+
>>> LA.norm(a, -np.inf)
|
|
2702
|
+
0.0
|
|
2703
|
+
>>> LA.norm(b, -np.inf)
|
|
2704
|
+
2.0
|
|
2705
|
+
|
|
2706
|
+
>>> LA.norm(a, 1)
|
|
2707
|
+
20.0
|
|
2708
|
+
>>> LA.norm(b, 1)
|
|
2709
|
+
7.0
|
|
2710
|
+
>>> LA.norm(a, -1)
|
|
2711
|
+
-4.6566128774142013e-010
|
|
2712
|
+
>>> LA.norm(b, -1)
|
|
2713
|
+
6.0
|
|
2714
|
+
>>> LA.norm(a, 2)
|
|
2715
|
+
7.745966692414834
|
|
2716
|
+
>>> LA.norm(b, 2)
|
|
2717
|
+
7.3484692283495345
|
|
2718
|
+
|
|
2719
|
+
>>> LA.norm(a, -2)
|
|
2720
|
+
0.0
|
|
2721
|
+
>>> LA.norm(b, -2)
|
|
2722
|
+
1.8570331885190563e-016 # may vary
|
|
2723
|
+
>>> LA.norm(a, 3)
|
|
2724
|
+
5.8480354764257312 # may vary
|
|
2725
|
+
>>> LA.norm(a, -3)
|
|
2726
|
+
0.0
|
|
2727
|
+
|
|
2728
|
+
Using the `axis` argument to compute vector norms:
|
|
2729
|
+
|
|
2730
|
+
>>> c = np.array([[ 1, 2, 3],
|
|
2731
|
+
... [-1, 1, 4]])
|
|
2732
|
+
>>> LA.norm(c, axis=0)
|
|
2733
|
+
array([ 1.41421356, 2.23606798, 5. ])
|
|
2734
|
+
>>> LA.norm(c, axis=1)
|
|
2735
|
+
array([ 3.74165739, 4.24264069])
|
|
2736
|
+
>>> LA.norm(c, ord=1, axis=1)
|
|
2737
|
+
array([ 6., 6.])
|
|
2738
|
+
|
|
2739
|
+
Using the `axis` argument to compute matrix norms:
|
|
2740
|
+
|
|
2741
|
+
>>> m = np.arange(8).reshape(2,2,2)
|
|
2742
|
+
>>> LA.norm(m, axis=(1,2))
|
|
2743
|
+
array([ 3.74165739, 11.22497216])
|
|
2744
|
+
>>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
|
|
2745
|
+
(3.7416573867739413, 11.224972160321824)
|
|
2746
|
+
|
|
2747
|
+
"""
|
|
2748
|
+
x = asarray(x)
|
|
2749
|
+
|
|
2750
|
+
if not issubclass(x.dtype.type, (inexact, object_)):
|
|
2751
|
+
x = x.astype(float)
|
|
2752
|
+
|
|
2753
|
+
# Immediately handle some default, simple, fast, and common cases.
|
|
2754
|
+
if axis is None:
|
|
2755
|
+
ndim = x.ndim
|
|
2756
|
+
if (
|
|
2757
|
+
(ord is None) or
|
|
2758
|
+
(ord in ('f', 'fro') and ndim == 2) or
|
|
2759
|
+
(ord == 2 and ndim == 1)
|
|
2760
|
+
):
|
|
2761
|
+
x = x.ravel(order='K')
|
|
2762
|
+
if isComplexType(x.dtype.type):
|
|
2763
|
+
x_real = x.real
|
|
2764
|
+
x_imag = x.imag
|
|
2765
|
+
sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag)
|
|
2766
|
+
else:
|
|
2767
|
+
sqnorm = x.dot(x)
|
|
2768
|
+
ret = sqrt(sqnorm)
|
|
2769
|
+
if keepdims:
|
|
2770
|
+
ret = ret.reshape(ndim * [1])
|
|
2771
|
+
return ret
|
|
2772
|
+
|
|
2773
|
+
# Normalize the `axis` argument to a tuple.
|
|
2774
|
+
nd = x.ndim
|
|
2775
|
+
if axis is None:
|
|
2776
|
+
axis = tuple(range(nd))
|
|
2777
|
+
elif not isinstance(axis, tuple):
|
|
2778
|
+
try:
|
|
2779
|
+
axis = int(axis)
|
|
2780
|
+
except Exception as e:
|
|
2781
|
+
raise TypeError(
|
|
2782
|
+
"'axis' must be None, an integer or a tuple of integers"
|
|
2783
|
+
) from e
|
|
2784
|
+
axis = (axis,)
|
|
2785
|
+
|
|
2786
|
+
if len(axis) == 1:
|
|
2787
|
+
if ord == inf:
|
|
2788
|
+
return abs(x).max(axis=axis, keepdims=keepdims, initial=0)
|
|
2789
|
+
elif ord == -inf:
|
|
2790
|
+
return abs(x).min(axis=axis, keepdims=keepdims)
|
|
2791
|
+
elif ord == 0:
|
|
2792
|
+
# Zero norm
|
|
2793
|
+
return (
|
|
2794
|
+
(x != 0)
|
|
2795
|
+
.astype(x.real.dtype)
|
|
2796
|
+
.sum(axis=axis, keepdims=keepdims)
|
|
2797
|
+
)
|
|
2798
|
+
elif ord == 1:
|
|
2799
|
+
# special case for speedup
|
|
2800
|
+
return add.reduce(abs(x), axis=axis, keepdims=keepdims)
|
|
2801
|
+
elif ord is None or ord == 2:
|
|
2802
|
+
# special case for speedup
|
|
2803
|
+
s = (x.conj() * x).real
|
|
2804
|
+
return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
|
|
2805
|
+
# None of the str-type keywords for ord ('fro', 'nuc')
|
|
2806
|
+
# are valid for vectors
|
|
2807
|
+
elif isinstance(ord, str):
|
|
2808
|
+
raise ValueError(f"Invalid norm order '{ord}' for vectors")
|
|
2809
|
+
else:
|
|
2810
|
+
absx = abs(x)
|
|
2811
|
+
absx **= ord
|
|
2812
|
+
ret = add.reduce(absx, axis=axis, keepdims=keepdims)
|
|
2813
|
+
ret **= reciprocal(ord, dtype=ret.dtype)
|
|
2814
|
+
return ret
|
|
2815
|
+
elif len(axis) == 2:
|
|
2816
|
+
row_axis, col_axis = axis
|
|
2817
|
+
row_axis = normalize_axis_index(row_axis, nd)
|
|
2818
|
+
col_axis = normalize_axis_index(col_axis, nd)
|
|
2819
|
+
if row_axis == col_axis:
|
|
2820
|
+
raise ValueError('Duplicate axes given.')
|
|
2821
|
+
if ord == 2:
|
|
2822
|
+
ret = _multi_svd_norm(x, row_axis, col_axis, amax, 0)
|
|
2823
|
+
elif ord == -2:
|
|
2824
|
+
ret = _multi_svd_norm(x, row_axis, col_axis, amin)
|
|
2825
|
+
elif ord == 1:
|
|
2826
|
+
if col_axis > row_axis:
|
|
2827
|
+
col_axis -= 1
|
|
2828
|
+
ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis, initial=0)
|
|
2829
|
+
elif ord == inf:
|
|
2830
|
+
if row_axis > col_axis:
|
|
2831
|
+
row_axis -= 1
|
|
2832
|
+
ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis, initial=0)
|
|
2833
|
+
elif ord == -1:
|
|
2834
|
+
if col_axis > row_axis:
|
|
2835
|
+
col_axis -= 1
|
|
2836
|
+
ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis)
|
|
2837
|
+
elif ord == -inf:
|
|
2838
|
+
if row_axis > col_axis:
|
|
2839
|
+
row_axis -= 1
|
|
2840
|
+
ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis)
|
|
2841
|
+
elif ord in [None, 'fro', 'f']:
|
|
2842
|
+
ret = sqrt(add.reduce((x.conj() * x).real, axis=axis))
|
|
2843
|
+
elif ord == 'nuc':
|
|
2844
|
+
ret = _multi_svd_norm(x, row_axis, col_axis, sum, 0)
|
|
2845
|
+
else:
|
|
2846
|
+
raise ValueError("Invalid norm order for matrices.")
|
|
2847
|
+
if keepdims:
|
|
2848
|
+
ret_shape = list(x.shape)
|
|
2849
|
+
ret_shape[axis[0]] = 1
|
|
2850
|
+
ret_shape[axis[1]] = 1
|
|
2851
|
+
ret = ret.reshape(ret_shape)
|
|
2852
|
+
return ret
|
|
2853
|
+
else:
|
|
2854
|
+
raise ValueError("Improper number of dimensions to norm.")
|
|
2855
|
+
|
|
2856
|
+
|
|
2857
|
+
# multi_dot
|
|
2858
|
+
|
|
2859
|
+
def _multidot_dispatcher(arrays, *, out=None):
|
|
2860
|
+
yield from arrays
|
|
2861
|
+
yield out
|
|
2862
|
+
|
|
2863
|
+
|
|
2864
|
+
@array_function_dispatch(_multidot_dispatcher)
|
|
2865
|
+
def multi_dot(arrays, *, out=None):
|
|
2866
|
+
"""
|
|
2867
|
+
Compute the dot product of two or more arrays in a single function call,
|
|
2868
|
+
while automatically selecting the fastest evaluation order.
|
|
2869
|
+
|
|
2870
|
+
`multi_dot` chains `numpy.dot` and uses optimal parenthesization
|
|
2871
|
+
of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
|
|
2872
|
+
this can speed up the multiplication a lot.
|
|
2873
|
+
|
|
2874
|
+
If the first argument is 1-D it is treated as a row vector.
|
|
2875
|
+
If the last argument is 1-D it is treated as a column vector.
|
|
2876
|
+
The other arguments must be 2-D.
|
|
2877
|
+
|
|
2878
|
+
Think of `multi_dot` as::
|
|
2879
|
+
|
|
2880
|
+
def multi_dot(arrays): return functools.reduce(np.dot, arrays)
|
|
2881
|
+
|
|
2882
|
+
|
|
2883
|
+
Parameters
|
|
2884
|
+
----------
|
|
2885
|
+
arrays : sequence of array_like
|
|
2886
|
+
If the first argument is 1-D it is treated as row vector.
|
|
2887
|
+
If the last argument is 1-D it is treated as column vector.
|
|
2888
|
+
The other arguments must be 2-D.
|
|
2889
|
+
out : ndarray, optional
|
|
2890
|
+
Output argument. This must have the exact kind that would be returned
|
|
2891
|
+
if it was not used. In particular, it must have the right type, must be
|
|
2892
|
+
C-contiguous, and its dtype must be the dtype that would be returned
|
|
2893
|
+
for `dot(a, b)`. This is a performance feature. Therefore, if these
|
|
2894
|
+
conditions are not met, an exception is raised, instead of attempting
|
|
2895
|
+
to be flexible.
|
|
2896
|
+
|
|
2897
|
+
Returns
|
|
2898
|
+
-------
|
|
2899
|
+
output : ndarray
|
|
2900
|
+
Returns the dot product of the supplied arrays.
|
|
2901
|
+
|
|
2902
|
+
See Also
|
|
2903
|
+
--------
|
|
2904
|
+
numpy.dot : dot multiplication with two arguments.
|
|
2905
|
+
|
|
2906
|
+
References
|
|
2907
|
+
----------
|
|
2908
|
+
|
|
2909
|
+
.. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
|
|
2910
|
+
.. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
|
|
2911
|
+
|
|
2912
|
+
Examples
|
|
2913
|
+
--------
|
|
2914
|
+
`multi_dot` allows you to write::
|
|
2915
|
+
|
|
2916
|
+
>>> import numpy as np
|
|
2917
|
+
>>> from numpy.linalg import multi_dot
|
|
2918
|
+
>>> # Prepare some data
|
|
2919
|
+
>>> A = np.random.random((10000, 100))
|
|
2920
|
+
>>> B = np.random.random((100, 1000))
|
|
2921
|
+
>>> C = np.random.random((1000, 5))
|
|
2922
|
+
>>> D = np.random.random((5, 333))
|
|
2923
|
+
>>> # the actual dot multiplication
|
|
2924
|
+
>>> _ = multi_dot([A, B, C, D])
|
|
2925
|
+
|
|
2926
|
+
instead of::
|
|
2927
|
+
|
|
2928
|
+
>>> _ = np.dot(np.dot(np.dot(A, B), C), D)
|
|
2929
|
+
>>> # or
|
|
2930
|
+
>>> _ = A.dot(B).dot(C).dot(D)
|
|
2931
|
+
|
|
2932
|
+
Notes
|
|
2933
|
+
-----
|
|
2934
|
+
The cost for a matrix multiplication can be calculated with the
|
|
2935
|
+
following function::
|
|
2936
|
+
|
|
2937
|
+
def cost(A, B):
|
|
2938
|
+
return A.shape[0] * A.shape[1] * B.shape[1]
|
|
2939
|
+
|
|
2940
|
+
Assume we have three matrices
|
|
2941
|
+
:math:`A_{10 \\times 100}, B_{100 \\times 5}, C_{5 \\times 50}`.
|
|
2942
|
+
|
|
2943
|
+
The costs for the two different parenthesizations are as follows::
|
|
2944
|
+
|
|
2945
|
+
cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500
|
|
2946
|
+
cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
|
|
2947
|
+
|
|
2948
|
+
"""
|
|
2949
|
+
n = len(arrays)
|
|
2950
|
+
# optimization only makes sense for len(arrays) > 2
|
|
2951
|
+
if n < 2:
|
|
2952
|
+
raise ValueError("Expecting at least two arrays.")
|
|
2953
|
+
elif n == 2:
|
|
2954
|
+
return dot(arrays[0], arrays[1], out=out)
|
|
2955
|
+
|
|
2956
|
+
arrays = [asanyarray(a) for a in arrays]
|
|
2957
|
+
|
|
2958
|
+
# save original ndim to reshape the result array into the proper form later
|
|
2959
|
+
ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim
|
|
2960
|
+
# Explicitly convert vectors to 2D arrays to keep the logic of the internal
|
|
2961
|
+
# _multi_dot_* functions as simple as possible.
|
|
2962
|
+
if arrays[0].ndim == 1:
|
|
2963
|
+
arrays[0] = atleast_2d(arrays[0])
|
|
2964
|
+
if arrays[-1].ndim == 1:
|
|
2965
|
+
arrays[-1] = atleast_2d(arrays[-1]).T
|
|
2966
|
+
_assert_2d(*arrays)
|
|
2967
|
+
|
|
2968
|
+
# _multi_dot_three is much faster than _multi_dot_matrix_chain_order
|
|
2969
|
+
if n == 3:
|
|
2970
|
+
result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out)
|
|
2971
|
+
else:
|
|
2972
|
+
order = _multi_dot_matrix_chain_order(arrays)
|
|
2973
|
+
result = _multi_dot(arrays, order, 0, n - 1, out=out)
|
|
2974
|
+
|
|
2975
|
+
# return proper shape
|
|
2976
|
+
if ndim_first == 1 and ndim_last == 1:
|
|
2977
|
+
return result[0, 0] # scalar
|
|
2978
|
+
elif ndim_first == 1 or ndim_last == 1:
|
|
2979
|
+
return result.ravel() # 1-D
|
|
2980
|
+
else:
|
|
2981
|
+
return result
|
|
2982
|
+
|
|
2983
|
+
|
|
2984
|
+
def _multi_dot_three(A, B, C, out=None):
|
|
2985
|
+
"""
|
|
2986
|
+
Find the best order for three arrays and do the multiplication.
|
|
2987
|
+
|
|
2988
|
+
For three arguments `_multi_dot_three` is approximately 15 times faster
|
|
2989
|
+
than `_multi_dot_matrix_chain_order`
|
|
2990
|
+
|
|
2991
|
+
"""
|
|
2992
|
+
a0, a1b0 = A.shape
|
|
2993
|
+
b1c0, c1 = C.shape
|
|
2994
|
+
# cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1
|
|
2995
|
+
cost1 = a0 * b1c0 * (a1b0 + c1)
|
|
2996
|
+
# cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1
|
|
2997
|
+
cost2 = a1b0 * c1 * (a0 + b1c0)
|
|
2998
|
+
|
|
2999
|
+
if cost1 < cost2:
|
|
3000
|
+
return dot(dot(A, B), C, out=out)
|
|
3001
|
+
else:
|
|
3002
|
+
return dot(A, dot(B, C), out=out)
|
|
3003
|
+
|
|
3004
|
+
|
|
3005
|
+
def _multi_dot_matrix_chain_order(arrays, return_costs=False):
|
|
3006
|
+
"""
|
|
3007
|
+
Return a np.array that encodes the optimal order of multiplications.
|
|
3008
|
+
|
|
3009
|
+
The optimal order array is then used by `_multi_dot()` to do the
|
|
3010
|
+
multiplication.
|
|
3011
|
+
|
|
3012
|
+
Also return the cost matrix if `return_costs` is `True`
|
|
3013
|
+
|
|
3014
|
+
The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
|
|
3015
|
+
Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices.
|
|
3016
|
+
|
|
3017
|
+
cost[i, j] = min([
|
|
3018
|
+
cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
|
|
3019
|
+
for k in range(i, j)])
|
|
3020
|
+
|
|
3021
|
+
"""
|
|
3022
|
+
n = len(arrays)
|
|
3023
|
+
# p stores the dimensions of the matrices
|
|
3024
|
+
# Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]
|
|
3025
|
+
p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]]
|
|
3026
|
+
# m is a matrix of costs of the subproblems
|
|
3027
|
+
# m[i,j]: min number of scalar multiplications needed to compute A_{i..j}
|
|
3028
|
+
m = zeros((n, n), dtype=double)
|
|
3029
|
+
# s is the actual ordering
|
|
3030
|
+
# s[i, j] is the value of k at which we split the product A_i..A_j
|
|
3031
|
+
s = empty((n, n), dtype=intp)
|
|
3032
|
+
|
|
3033
|
+
for l in range(1, n):
|
|
3034
|
+
for i in range(n - l):
|
|
3035
|
+
j = i + l
|
|
3036
|
+
m[i, j] = inf
|
|
3037
|
+
for k in range(i, j):
|
|
3038
|
+
q = m[i, k] + m[k + 1, j] + p[i] * p[k + 1] * p[j + 1]
|
|
3039
|
+
if q < m[i, j]:
|
|
3040
|
+
m[i, j] = q
|
|
3041
|
+
s[i, j] = k # Note that Cormen uses 1-based index
|
|
3042
|
+
|
|
3043
|
+
return (s, m) if return_costs else s
|
|
3044
|
+
|
|
3045
|
+
|
|
3046
|
+
def _multi_dot(arrays, order, i, j, out=None):
|
|
3047
|
+
"""Actually do the multiplication with the given order."""
|
|
3048
|
+
if i == j:
|
|
3049
|
+
# the initial call with non-None out should never get here
|
|
3050
|
+
assert out is None
|
|
3051
|
+
|
|
3052
|
+
return arrays[i]
|
|
3053
|
+
else:
|
|
3054
|
+
return dot(_multi_dot(arrays, order, i, order[i, j]),
|
|
3055
|
+
_multi_dot(arrays, order, order[i, j] + 1, j),
|
|
3056
|
+
out=out)
|
|
3057
|
+
|
|
3058
|
+
|
|
3059
|
+
# diagonal
|
|
3060
|
+
|
|
3061
|
+
def _diagonal_dispatcher(x, /, *, offset=None):
|
|
3062
|
+
return (x,)
|
|
3063
|
+
|
|
3064
|
+
|
|
3065
|
+
@array_function_dispatch(_diagonal_dispatcher)
|
|
3066
|
+
def diagonal(x, /, *, offset=0):
|
|
3067
|
+
"""
|
|
3068
|
+
Returns specified diagonals of a matrix (or a stack of matrices) ``x``.
|
|
3069
|
+
|
|
3070
|
+
This function is Array API compatible, contrary to
|
|
3071
|
+
:py:func:`numpy.diagonal`, the matrix is assumed
|
|
3072
|
+
to be defined by the last two dimensions.
|
|
3073
|
+
|
|
3074
|
+
Parameters
|
|
3075
|
+
----------
|
|
3076
|
+
x : (...,M,N) array_like
|
|
3077
|
+
Input array having shape (..., M, N) and whose innermost two
|
|
3078
|
+
dimensions form MxN matrices.
|
|
3079
|
+
offset : int, optional
|
|
3080
|
+
Offset specifying the off-diagonal relative to the main diagonal,
|
|
3081
|
+
where::
|
|
3082
|
+
|
|
3083
|
+
* offset = 0: the main diagonal.
|
|
3084
|
+
* offset > 0: off-diagonal above the main diagonal.
|
|
3085
|
+
* offset < 0: off-diagonal below the main diagonal.
|
|
3086
|
+
|
|
3087
|
+
Returns
|
|
3088
|
+
-------
|
|
3089
|
+
out : (...,min(N,M)) ndarray
|
|
3090
|
+
An array containing the diagonals and whose shape is determined by
|
|
3091
|
+
removing the last two dimensions and appending a dimension equal to
|
|
3092
|
+
the size of the resulting diagonals. The returned array must have
|
|
3093
|
+
the same data type as ``x``.
|
|
3094
|
+
|
|
3095
|
+
See Also
|
|
3096
|
+
--------
|
|
3097
|
+
numpy.diagonal
|
|
3098
|
+
|
|
3099
|
+
Examples
|
|
3100
|
+
--------
|
|
3101
|
+
>>> a = np.arange(4).reshape(2, 2); a
|
|
3102
|
+
array([[0, 1],
|
|
3103
|
+
[2, 3]])
|
|
3104
|
+
>>> np.linalg.diagonal(a)
|
|
3105
|
+
array([0, 3])
|
|
3106
|
+
|
|
3107
|
+
A 3-D example:
|
|
3108
|
+
|
|
3109
|
+
>>> a = np.arange(8).reshape(2, 2, 2); a
|
|
3110
|
+
array([[[0, 1],
|
|
3111
|
+
[2, 3]],
|
|
3112
|
+
[[4, 5],
|
|
3113
|
+
[6, 7]]])
|
|
3114
|
+
>>> np.linalg.diagonal(a)
|
|
3115
|
+
array([[0, 3],
|
|
3116
|
+
[4, 7]])
|
|
3117
|
+
|
|
3118
|
+
Diagonals adjacent to the main diagonal can be obtained by using the
|
|
3119
|
+
`offset` argument:
|
|
3120
|
+
|
|
3121
|
+
>>> a = np.arange(9).reshape(3, 3)
|
|
3122
|
+
>>> a
|
|
3123
|
+
array([[0, 1, 2],
|
|
3124
|
+
[3, 4, 5],
|
|
3125
|
+
[6, 7, 8]])
|
|
3126
|
+
>>> np.linalg.diagonal(a, offset=1) # First superdiagonal
|
|
3127
|
+
array([1, 5])
|
|
3128
|
+
>>> np.linalg.diagonal(a, offset=2) # Second superdiagonal
|
|
3129
|
+
array([2])
|
|
3130
|
+
>>> np.linalg.diagonal(a, offset=-1) # First subdiagonal
|
|
3131
|
+
array([3, 7])
|
|
3132
|
+
>>> np.linalg.diagonal(a, offset=-2) # Second subdiagonal
|
|
3133
|
+
array([6])
|
|
3134
|
+
|
|
3135
|
+
The anti-diagonal can be obtained by reversing the order of elements
|
|
3136
|
+
using either `numpy.flipud` or `numpy.fliplr`.
|
|
3137
|
+
|
|
3138
|
+
>>> a = np.arange(9).reshape(3, 3)
|
|
3139
|
+
>>> a
|
|
3140
|
+
array([[0, 1, 2],
|
|
3141
|
+
[3, 4, 5],
|
|
3142
|
+
[6, 7, 8]])
|
|
3143
|
+
>>> np.linalg.diagonal(np.fliplr(a)) # Horizontal flip
|
|
3144
|
+
array([2, 4, 6])
|
|
3145
|
+
>>> np.linalg.diagonal(np.flipud(a)) # Vertical flip
|
|
3146
|
+
array([6, 4, 2])
|
|
3147
|
+
|
|
3148
|
+
Note that the order in which the diagonal is retrieved varies depending
|
|
3149
|
+
on the flip function.
|
|
3150
|
+
|
|
3151
|
+
"""
|
|
3152
|
+
return _core_diagonal(x, offset, axis1=-2, axis2=-1)
|
|
3153
|
+
|
|
3154
|
+
|
|
3155
|
+
# trace
|
|
3156
|
+
|
|
3157
|
+
def _trace_dispatcher(x, /, *, offset=None, dtype=None):
|
|
3158
|
+
return (x,)
|
|
3159
|
+
|
|
3160
|
+
|
|
3161
|
+
@array_function_dispatch(_trace_dispatcher)
|
|
3162
|
+
def trace(x, /, *, offset=0, dtype=None):
|
|
3163
|
+
"""
|
|
3164
|
+
Returns the sum along the specified diagonals of a matrix
|
|
3165
|
+
(or a stack of matrices) ``x``.
|
|
3166
|
+
|
|
3167
|
+
This function is Array API compatible, contrary to
|
|
3168
|
+
:py:func:`numpy.trace`.
|
|
3169
|
+
|
|
3170
|
+
Parameters
|
|
3171
|
+
----------
|
|
3172
|
+
x : (...,M,N) array_like
|
|
3173
|
+
Input array having shape (..., M, N) and whose innermost two
|
|
3174
|
+
dimensions form MxN matrices.
|
|
3175
|
+
offset : int, optional
|
|
3176
|
+
Offset specifying the off-diagonal relative to the main diagonal,
|
|
3177
|
+
where::
|
|
3178
|
+
|
|
3179
|
+
* offset = 0: the main diagonal.
|
|
3180
|
+
* offset > 0: off-diagonal above the main diagonal.
|
|
3181
|
+
* offset < 0: off-diagonal below the main diagonal.
|
|
3182
|
+
|
|
3183
|
+
dtype : dtype, optional
|
|
3184
|
+
Data type of the returned array.
|
|
3185
|
+
|
|
3186
|
+
Returns
|
|
3187
|
+
-------
|
|
3188
|
+
out : ndarray
|
|
3189
|
+
An array containing the traces and whose shape is determined by
|
|
3190
|
+
removing the last two dimensions and storing the traces in the last
|
|
3191
|
+
array dimension. For example, if x has rank k and shape:
|
|
3192
|
+
(I, J, K, ..., L, M, N), then an output array has rank k-2 and shape:
|
|
3193
|
+
(I, J, K, ..., L) where::
|
|
3194
|
+
|
|
3195
|
+
out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
|
|
3196
|
+
|
|
3197
|
+
The returned array must have a data type as described by the dtype
|
|
3198
|
+
parameter above.
|
|
3199
|
+
|
|
3200
|
+
See Also
|
|
3201
|
+
--------
|
|
3202
|
+
numpy.trace
|
|
3203
|
+
|
|
3204
|
+
Examples
|
|
3205
|
+
--------
|
|
3206
|
+
>>> np.linalg.trace(np.eye(3))
|
|
3207
|
+
3.0
|
|
3208
|
+
>>> a = np.arange(8).reshape((2, 2, 2))
|
|
3209
|
+
>>> np.linalg.trace(a)
|
|
3210
|
+
array([3, 11])
|
|
3211
|
+
|
|
3212
|
+
Trace is computed with the last two axes as the 2-d sub-arrays.
|
|
3213
|
+
This behavior differs from :py:func:`numpy.trace` which uses the first two
|
|
3214
|
+
axes by default.
|
|
3215
|
+
|
|
3216
|
+
>>> a = np.arange(24).reshape((3, 2, 2, 2))
|
|
3217
|
+
>>> np.linalg.trace(a).shape
|
|
3218
|
+
(3, 2)
|
|
3219
|
+
|
|
3220
|
+
Traces adjacent to the main diagonal can be obtained by using the
|
|
3221
|
+
`offset` argument:
|
|
3222
|
+
|
|
3223
|
+
>>> a = np.arange(9).reshape((3, 3)); a
|
|
3224
|
+
array([[0, 1, 2],
|
|
3225
|
+
[3, 4, 5],
|
|
3226
|
+
[6, 7, 8]])
|
|
3227
|
+
>>> np.linalg.trace(a, offset=1) # First superdiagonal
|
|
3228
|
+
6
|
|
3229
|
+
>>> np.linalg.trace(a, offset=2) # Second superdiagonal
|
|
3230
|
+
2
|
|
3231
|
+
>>> np.linalg.trace(a, offset=-1) # First subdiagonal
|
|
3232
|
+
10
|
|
3233
|
+
>>> np.linalg.trace(a, offset=-2) # Second subdiagonal
|
|
3234
|
+
6
|
|
3235
|
+
|
|
3236
|
+
"""
|
|
3237
|
+
return _core_trace(x, offset, axis1=-2, axis2=-1, dtype=dtype)
|
|
3238
|
+
|
|
3239
|
+
|
|
3240
|
+
# cross
|
|
3241
|
+
|
|
3242
|
+
def _cross_dispatcher(x1, x2, /, *, axis=None):
|
|
3243
|
+
return (x1, x2,)
|
|
3244
|
+
|
|
3245
|
+
|
|
3246
|
+
@array_function_dispatch(_cross_dispatcher)
|
|
3247
|
+
def cross(x1, x2, /, *, axis=-1):
|
|
3248
|
+
"""
|
|
3249
|
+
Returns the cross product of 3-element vectors.
|
|
3250
|
+
|
|
3251
|
+
If ``x1`` and/or ``x2`` are multi-dimensional arrays, then
|
|
3252
|
+
the cross-product of each pair of corresponding 3-element vectors
|
|
3253
|
+
is independently computed.
|
|
3254
|
+
|
|
3255
|
+
This function is Array API compatible, contrary to
|
|
3256
|
+
:func:`numpy.cross`.
|
|
3257
|
+
|
|
3258
|
+
Parameters
|
|
3259
|
+
----------
|
|
3260
|
+
x1 : array_like
|
|
3261
|
+
The first input array.
|
|
3262
|
+
x2 : array_like
|
|
3263
|
+
The second input array. Must be compatible with ``x1`` for all
|
|
3264
|
+
non-compute axes. The size of the axis over which to compute
|
|
3265
|
+
the cross-product must be the same size as the respective axis
|
|
3266
|
+
in ``x1``.
|
|
3267
|
+
axis : int, optional
|
|
3268
|
+
The axis (dimension) of ``x1`` and ``x2`` containing the vectors for
|
|
3269
|
+
which to compute the cross-product. Default: ``-1``.
|
|
3270
|
+
|
|
3271
|
+
Returns
|
|
3272
|
+
-------
|
|
3273
|
+
out : ndarray
|
|
3274
|
+
An array containing the cross products.
|
|
3275
|
+
|
|
3276
|
+
See Also
|
|
3277
|
+
--------
|
|
3278
|
+
numpy.cross
|
|
3279
|
+
|
|
3280
|
+
Examples
|
|
3281
|
+
--------
|
|
3282
|
+
Vector cross-product.
|
|
3283
|
+
|
|
3284
|
+
>>> x = np.array([1, 2, 3])
|
|
3285
|
+
>>> y = np.array([4, 5, 6])
|
|
3286
|
+
>>> np.linalg.cross(x, y)
|
|
3287
|
+
array([-3, 6, -3])
|
|
3288
|
+
|
|
3289
|
+
Multiple vector cross-products. Note that the direction of the cross
|
|
3290
|
+
product vector is defined by the *right-hand rule*.
|
|
3291
|
+
|
|
3292
|
+
>>> x = np.array([[1,2,3], [4,5,6]])
|
|
3293
|
+
>>> y = np.array([[4,5,6], [1,2,3]])
|
|
3294
|
+
>>> np.linalg.cross(x, y)
|
|
3295
|
+
array([[-3, 6, -3],
|
|
3296
|
+
[ 3, -6, 3]])
|
|
3297
|
+
|
|
3298
|
+
>>> x = np.array([[1, 2], [3, 4], [5, 6]])
|
|
3299
|
+
>>> y = np.array([[4, 5], [6, 1], [2, 3]])
|
|
3300
|
+
>>> np.linalg.cross(x, y, axis=0)
|
|
3301
|
+
array([[-24, 6],
|
|
3302
|
+
[ 18, 24],
|
|
3303
|
+
[-6, -18]])
|
|
3304
|
+
|
|
3305
|
+
"""
|
|
3306
|
+
x1 = asanyarray(x1)
|
|
3307
|
+
x2 = asanyarray(x2)
|
|
3308
|
+
|
|
3309
|
+
if x1.shape[axis] != 3 or x2.shape[axis] != 3:
|
|
3310
|
+
raise ValueError(
|
|
3311
|
+
"Both input arrays must be (arrays of) 3-dimensional vectors, "
|
|
3312
|
+
f"but they are {x1.shape[axis]} and {x2.shape[axis]} "
|
|
3313
|
+
"dimensional instead."
|
|
3314
|
+
)
|
|
3315
|
+
|
|
3316
|
+
return _core_cross(x1, x2, axis=axis)
|
|
3317
|
+
|
|
3318
|
+
|
|
3319
|
+
# matmul
|
|
3320
|
+
|
|
3321
|
+
def _matmul_dispatcher(x1, x2, /):
|
|
3322
|
+
return (x1, x2)
|
|
3323
|
+
|
|
3324
|
+
|
|
3325
|
+
@array_function_dispatch(_matmul_dispatcher)
|
|
3326
|
+
def matmul(x1, x2, /):
|
|
3327
|
+
"""
|
|
3328
|
+
Computes the matrix product.
|
|
3329
|
+
|
|
3330
|
+
This function is Array API compatible, contrary to
|
|
3331
|
+
:func:`numpy.matmul`.
|
|
3332
|
+
|
|
3333
|
+
Parameters
|
|
3334
|
+
----------
|
|
3335
|
+
x1 : array_like
|
|
3336
|
+
The first input array.
|
|
3337
|
+
x2 : array_like
|
|
3338
|
+
The second input array.
|
|
3339
|
+
|
|
3340
|
+
Returns
|
|
3341
|
+
-------
|
|
3342
|
+
out : ndarray
|
|
3343
|
+
The matrix product of the inputs.
|
|
3344
|
+
This is a scalar only when both ``x1``, ``x2`` are 1-d vectors.
|
|
3345
|
+
|
|
3346
|
+
Raises
|
|
3347
|
+
------
|
|
3348
|
+
ValueError
|
|
3349
|
+
If the last dimension of ``x1`` is not the same size as
|
|
3350
|
+
the second-to-last dimension of ``x2``.
|
|
3351
|
+
|
|
3352
|
+
If a scalar value is passed in.
|
|
3353
|
+
|
|
3354
|
+
See Also
|
|
3355
|
+
--------
|
|
3356
|
+
numpy.matmul
|
|
3357
|
+
|
|
3358
|
+
Examples
|
|
3359
|
+
--------
|
|
3360
|
+
For 2-D arrays it is the matrix product:
|
|
3361
|
+
|
|
3362
|
+
>>> a = np.array([[1, 0],
|
|
3363
|
+
... [0, 1]])
|
|
3364
|
+
>>> b = np.array([[4, 1],
|
|
3365
|
+
... [2, 2]])
|
|
3366
|
+
>>> np.linalg.matmul(a, b)
|
|
3367
|
+
array([[4, 1],
|
|
3368
|
+
[2, 2]])
|
|
3369
|
+
|
|
3370
|
+
For 2-D mixed with 1-D, the result is the usual.
|
|
3371
|
+
|
|
3372
|
+
>>> a = np.array([[1, 0],
|
|
3373
|
+
... [0, 1]])
|
|
3374
|
+
>>> b = np.array([1, 2])
|
|
3375
|
+
>>> np.linalg.matmul(a, b)
|
|
3376
|
+
array([1, 2])
|
|
3377
|
+
>>> np.linalg.matmul(b, a)
|
|
3378
|
+
array([1, 2])
|
|
3379
|
+
|
|
3380
|
+
|
|
3381
|
+
Broadcasting is conventional for stacks of arrays
|
|
3382
|
+
|
|
3383
|
+
>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
|
|
3384
|
+
>>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
|
|
3385
|
+
>>> np.linalg.matmul(a,b).shape
|
|
3386
|
+
(2, 2, 2)
|
|
3387
|
+
>>> np.linalg.matmul(a, b)[0, 1, 1]
|
|
3388
|
+
98
|
|
3389
|
+
>>> sum(a[0, 1, :] * b[0 , :, 1])
|
|
3390
|
+
98
|
|
3391
|
+
|
|
3392
|
+
Vector, vector returns the scalar inner product, but neither argument
|
|
3393
|
+
is complex-conjugated:
|
|
3394
|
+
|
|
3395
|
+
>>> np.linalg.matmul([2j, 3j], [2j, 3j])
|
|
3396
|
+
(-13+0j)
|
|
3397
|
+
|
|
3398
|
+
Scalar multiplication raises an error.
|
|
3399
|
+
|
|
3400
|
+
>>> np.linalg.matmul([1,2], 3)
|
|
3401
|
+
Traceback (most recent call last):
|
|
3402
|
+
...
|
|
3403
|
+
ValueError: matmul: Input operand 1 does not have enough dimensions ...
|
|
3404
|
+
|
|
3405
|
+
"""
|
|
3406
|
+
return _core_matmul(x1, x2)
|
|
3407
|
+
|
|
3408
|
+
|
|
3409
|
+
# tensordot
|
|
3410
|
+
|
|
3411
|
+
def _tensordot_dispatcher(x1, x2, /, *, axes=None):
|
|
3412
|
+
return (x1, x2)
|
|
3413
|
+
|
|
3414
|
+
|
|
3415
|
+
@array_function_dispatch(_tensordot_dispatcher)
|
|
3416
|
+
def tensordot(x1, x2, /, *, axes=2):
|
|
3417
|
+
return _core_tensordot(x1, x2, axes=axes)
|
|
3418
|
+
|
|
3419
|
+
|
|
3420
|
+
tensordot.__doc__ = _core_tensordot.__doc__
|
|
3421
|
+
|
|
3422
|
+
|
|
3423
|
+
# matrix_transpose
|
|
3424
|
+
|
|
3425
|
+
def _matrix_transpose_dispatcher(x):
|
|
3426
|
+
return (x,)
|
|
3427
|
+
|
|
3428
|
+
@array_function_dispatch(_matrix_transpose_dispatcher)
|
|
3429
|
+
def matrix_transpose(x, /):
|
|
3430
|
+
return _core_matrix_transpose(x)
|
|
3431
|
+
|
|
3432
|
+
|
|
3433
|
+
matrix_transpose.__doc__ = f"""{_core_matrix_transpose.__doc__}
|
|
3434
|
+
|
|
3435
|
+
Notes
|
|
3436
|
+
-----
|
|
3437
|
+
This function is an alias of `numpy.matrix_transpose`.
|
|
3438
|
+
"""
|
|
3439
|
+
|
|
3440
|
+
|
|
3441
|
+
# matrix_norm
|
|
3442
|
+
|
|
3443
|
+
def _matrix_norm_dispatcher(x, /, *, keepdims=None, ord=None):
|
|
3444
|
+
return (x,)
|
|
3445
|
+
|
|
3446
|
+
@array_function_dispatch(_matrix_norm_dispatcher)
|
|
3447
|
+
def matrix_norm(x, /, *, keepdims=False, ord="fro"):
|
|
3448
|
+
"""
|
|
3449
|
+
Computes the matrix norm of a matrix (or a stack of matrices) ``x``.
|
|
3450
|
+
|
|
3451
|
+
This function is Array API compatible.
|
|
3452
|
+
|
|
3453
|
+
Parameters
|
|
3454
|
+
----------
|
|
3455
|
+
x : array_like
|
|
3456
|
+
Input array having shape (..., M, N) and whose two innermost
|
|
3457
|
+
dimensions form ``MxN`` matrices.
|
|
3458
|
+
keepdims : bool, optional
|
|
3459
|
+
If this is set to True, the axes which are normed over are left in
|
|
3460
|
+
the result as dimensions with size one. Default: False.
|
|
3461
|
+
ord : {1, -1, 2, -2, inf, -inf, 'fro', 'nuc'}, optional
|
|
3462
|
+
The order of the norm. For details see the table under ``Notes``
|
|
3463
|
+
in `numpy.linalg.norm`.
|
|
3464
|
+
|
|
3465
|
+
See Also
|
|
3466
|
+
--------
|
|
3467
|
+
numpy.linalg.norm : Generic norm function
|
|
3468
|
+
|
|
3469
|
+
Examples
|
|
3470
|
+
--------
|
|
3471
|
+
>>> from numpy import linalg as LA
|
|
3472
|
+
>>> a = np.arange(9) - 4
|
|
3473
|
+
>>> a
|
|
3474
|
+
array([-4, -3, -2, ..., 2, 3, 4])
|
|
3475
|
+
>>> b = a.reshape((3, 3))
|
|
3476
|
+
>>> b
|
|
3477
|
+
array([[-4, -3, -2],
|
|
3478
|
+
[-1, 0, 1],
|
|
3479
|
+
[ 2, 3, 4]])
|
|
3480
|
+
|
|
3481
|
+
>>> LA.matrix_norm(b)
|
|
3482
|
+
7.745966692414834
|
|
3483
|
+
>>> LA.matrix_norm(b, ord='fro')
|
|
3484
|
+
7.745966692414834
|
|
3485
|
+
>>> LA.matrix_norm(b, ord=np.inf)
|
|
3486
|
+
9.0
|
|
3487
|
+
>>> LA.matrix_norm(b, ord=-np.inf)
|
|
3488
|
+
2.0
|
|
3489
|
+
|
|
3490
|
+
>>> LA.matrix_norm(b, ord=1)
|
|
3491
|
+
7.0
|
|
3492
|
+
>>> LA.matrix_norm(b, ord=-1)
|
|
3493
|
+
6.0
|
|
3494
|
+
>>> LA.matrix_norm(b, ord=2)
|
|
3495
|
+
7.3484692283495345
|
|
3496
|
+
>>> LA.matrix_norm(b, ord=-2)
|
|
3497
|
+
1.8570331885190563e-016 # may vary
|
|
3498
|
+
|
|
3499
|
+
"""
|
|
3500
|
+
x = asanyarray(x)
|
|
3501
|
+
return norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
|
|
3502
|
+
|
|
3503
|
+
|
|
3504
|
+
# vector_norm
|
|
3505
|
+
|
|
3506
|
+
def _vector_norm_dispatcher(x, /, *, axis=None, keepdims=None, ord=None):
|
|
3507
|
+
return (x,)
|
|
3508
|
+
|
|
3509
|
+
@array_function_dispatch(_vector_norm_dispatcher)
|
|
3510
|
+
def vector_norm(x, /, *, axis=None, keepdims=False, ord=2):
|
|
3511
|
+
"""
|
|
3512
|
+
Computes the vector norm of a vector (or batch of vectors) ``x``.
|
|
3513
|
+
|
|
3514
|
+
This function is Array API compatible.
|
|
3515
|
+
|
|
3516
|
+
Parameters
|
|
3517
|
+
----------
|
|
3518
|
+
x : array_like
|
|
3519
|
+
Input array.
|
|
3520
|
+
axis : {None, int, 2-tuple of ints}, optional
|
|
3521
|
+
If an integer, ``axis`` specifies the axis (dimension) along which
|
|
3522
|
+
to compute vector norms. If an n-tuple, ``axis`` specifies the axes
|
|
3523
|
+
(dimensions) along which to compute batched vector norms. If ``None``,
|
|
3524
|
+
the vector norm must be computed over all array values (i.e.,
|
|
3525
|
+
equivalent to computing the vector norm of a flattened array).
|
|
3526
|
+
Default: ``None``.
|
|
3527
|
+
keepdims : bool, optional
|
|
3528
|
+
If this is set to True, the axes which are normed over are left in
|
|
3529
|
+
the result as dimensions with size one. Default: False.
|
|
3530
|
+
ord : {int, float, inf, -inf}, optional
|
|
3531
|
+
The order of the norm. For details see the table under ``Notes``
|
|
3532
|
+
in `numpy.linalg.norm`.
|
|
3533
|
+
|
|
3534
|
+
See Also
|
|
3535
|
+
--------
|
|
3536
|
+
numpy.linalg.norm : Generic norm function
|
|
3537
|
+
|
|
3538
|
+
Examples
|
|
3539
|
+
--------
|
|
3540
|
+
>>> from numpy import linalg as LA
|
|
3541
|
+
>>> a = np.arange(9) + 1
|
|
3542
|
+
>>> a
|
|
3543
|
+
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
|
3544
|
+
>>> b = a.reshape((3, 3))
|
|
3545
|
+
>>> b
|
|
3546
|
+
array([[1, 2, 3],
|
|
3547
|
+
[4, 5, 6],
|
|
3548
|
+
[7, 8, 9]])
|
|
3549
|
+
|
|
3550
|
+
>>> LA.vector_norm(b)
|
|
3551
|
+
16.881943016134134
|
|
3552
|
+
>>> LA.vector_norm(b, ord=np.inf)
|
|
3553
|
+
9.0
|
|
3554
|
+
>>> LA.vector_norm(b, ord=-np.inf)
|
|
3555
|
+
1.0
|
|
3556
|
+
|
|
3557
|
+
>>> LA.vector_norm(b, ord=0)
|
|
3558
|
+
9.0
|
|
3559
|
+
>>> LA.vector_norm(b, ord=1)
|
|
3560
|
+
45.0
|
|
3561
|
+
>>> LA.vector_norm(b, ord=-1)
|
|
3562
|
+
0.3534857623790153
|
|
3563
|
+
>>> LA.vector_norm(b, ord=2)
|
|
3564
|
+
16.881943016134134
|
|
3565
|
+
>>> LA.vector_norm(b, ord=-2)
|
|
3566
|
+
0.8058837395885292
|
|
3567
|
+
|
|
3568
|
+
"""
|
|
3569
|
+
x = asanyarray(x)
|
|
3570
|
+
shape = list(x.shape)
|
|
3571
|
+
if axis is None:
|
|
3572
|
+
# Note: np.linalg.norm() doesn't handle 0-D arrays
|
|
3573
|
+
x = x.ravel()
|
|
3574
|
+
_axis = 0
|
|
3575
|
+
elif isinstance(axis, tuple):
|
|
3576
|
+
# Note: The axis argument supports any number of axes, whereas
|
|
3577
|
+
# np.linalg.norm() only supports a single axis for vector norm.
|
|
3578
|
+
normalized_axis = normalize_axis_tuple(axis, x.ndim)
|
|
3579
|
+
rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
|
|
3580
|
+
newshape = axis + rest
|
|
3581
|
+
x = _core_transpose(x, newshape).reshape(
|
|
3582
|
+
(
|
|
3583
|
+
prod([x.shape[i] for i in axis], dtype=int),
|
|
3584
|
+
*[x.shape[i] for i in rest]
|
|
3585
|
+
)
|
|
3586
|
+
)
|
|
3587
|
+
_axis = 0
|
|
3588
|
+
else:
|
|
3589
|
+
_axis = axis
|
|
3590
|
+
|
|
3591
|
+
res = norm(x, axis=_axis, ord=ord)
|
|
3592
|
+
|
|
3593
|
+
if keepdims:
|
|
3594
|
+
# We can't reuse np.linalg.norm(keepdims) because of the reshape hacks
|
|
3595
|
+
# above to avoid matrix norm logic.
|
|
3596
|
+
_axis = normalize_axis_tuple(
|
|
3597
|
+
range(len(shape)) if axis is None else axis, len(shape)
|
|
3598
|
+
)
|
|
3599
|
+
for i in _axis:
|
|
3600
|
+
shape[i] = 1
|
|
3601
|
+
res = res.reshape(tuple(shape))
|
|
3602
|
+
|
|
3603
|
+
return res
|
|
3604
|
+
|
|
3605
|
+
|
|
3606
|
+
# vecdot
|
|
3607
|
+
|
|
3608
|
+
def _vecdot_dispatcher(x1, x2, /, *, axis=None):
|
|
3609
|
+
return (x1, x2)
|
|
3610
|
+
|
|
3611
|
+
@array_function_dispatch(_vecdot_dispatcher)
|
|
3612
|
+
def vecdot(x1, x2, /, *, axis=-1):
|
|
3613
|
+
"""
|
|
3614
|
+
Computes the vector dot product.
|
|
3615
|
+
|
|
3616
|
+
This function is restricted to arguments compatible with the Array API,
|
|
3617
|
+
contrary to :func:`numpy.vecdot`.
|
|
3618
|
+
|
|
3619
|
+
Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be
|
|
3620
|
+
a corresponding vector in ``x2``. The dot product is defined as:
|
|
3621
|
+
|
|
3622
|
+
.. math::
|
|
3623
|
+
\\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i
|
|
3624
|
+
|
|
3625
|
+
over the dimension specified by ``axis`` and where :math:`\\overline{a_i}`
|
|
3626
|
+
denotes the complex conjugate if :math:`a_i` is complex and the identity
|
|
3627
|
+
otherwise.
|
|
3628
|
+
|
|
3629
|
+
Parameters
|
|
3630
|
+
----------
|
|
3631
|
+
x1 : array_like
|
|
3632
|
+
First input array.
|
|
3633
|
+
x2 : array_like
|
|
3634
|
+
Second input array.
|
|
3635
|
+
axis : int, optional
|
|
3636
|
+
Axis over which to compute the dot product. Default: ``-1``.
|
|
3637
|
+
|
|
3638
|
+
Returns
|
|
3639
|
+
-------
|
|
3640
|
+
output : ndarray
|
|
3641
|
+
The vector dot product of the input.
|
|
3642
|
+
|
|
3643
|
+
See Also
|
|
3644
|
+
--------
|
|
3645
|
+
numpy.vecdot
|
|
3646
|
+
|
|
3647
|
+
Examples
|
|
3648
|
+
--------
|
|
3649
|
+
Get the projected size along a given normal for an array of vectors.
|
|
3650
|
+
|
|
3651
|
+
>>> v = np.array([[0., 5., 0.], [0., 0., 10.], [0., 6., 8.]])
|
|
3652
|
+
>>> n = np.array([0., 0.6, 0.8])
|
|
3653
|
+
>>> np.linalg.vecdot(v, n)
|
|
3654
|
+
array([ 3., 8., 10.])
|
|
3655
|
+
|
|
3656
|
+
"""
|
|
3657
|
+
return _core_vecdot(x1, x2, axis=axis)
|