diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3239bf2cd8fbc1c0f74d4e10202ce7e056cc78c9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee77bf7753e0c8e5514a1ae03a208bd55b524cfa Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ContainerIO.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ContainerIO.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3055e343f48396f075d07e3b9e06e887eaea7519 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ContainerIO.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/CurImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/CurImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95d6ebb8bca71bef8841eb811640dade67d76c85 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/CurImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b21efd6a450532d99a27d7553199e875ebab2aae Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ExifTags.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ExifTags.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5c32048b0d9c572ad351071b53a6acb5b006f8b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ExifTags.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b316785e7c0b8bf4d4ba78a16962a777de3606b5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FontFile.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FontFile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66fa4ad0f1e9d98644cf018951d683a6c1ecc270 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/FontFile.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee55ea239980fa739b545101d09a0a97fb64a57b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ceb767ae0e4a06e6220f2a36efaa60acd25b527 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2e9cce603f76926c379f0c86b487f6d432059c2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageChops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageChops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6911b4fc48ae90ded0298f7f25ccee25e5144590 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageChops.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageCms.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageCms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a43a6fdd124e832eda98399b934a8964628d6936 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageCms.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageDraw.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageDraw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f5adbe74955e7bc827e0debb291619049689d8e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageDraw.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageGrab.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageGrab.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdbd28d7cb3ff7151f9ade19f1ebe317c19c441c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageGrab.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMath.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e718b31646e77cf56f549bdda28540275d61e176 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMath.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMode.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38cd686c331b666b5ac285557e29e478917fcde9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageMode.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageOps.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageOps.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c13103ecc6cccf1cb749449d725f28c73bea6dd8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageOps.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePalette.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePalette.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b03b69c4e7fb139fd15ac666b143a5f7303c95e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePalette.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePath.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..673f4a1c35f9d774b938d5dc27caa8d3cbe4f3dc Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImagePath.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageSequence.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageSequence.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67f80ffdd46fe141b62a9c28af7946caf4de05c0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageSequence.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageShow.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageShow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8c8a29027bc54fb9713d03552144f9666e7f4fd Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/ImageShow.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb415823d8eb7adf090a349f9a41be1e2d735cfa Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..763c9d851d0af3ff530755e50ee941ded5825c90 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/JpegPresets.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/JpegPresets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eb5b2cef511f86edc8461a06946883f5151f56b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/JpegPresets.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..010379009efea559dc160f6b96bad0842cdde031 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PSDraw.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PSDraw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be003ce8268b2a6b33eab6b4f9b6587e62436f14 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PSDraw.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec4be5468262f549a7febdbfc2cb28c263a0d8a7 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcfFontFile.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcfFontFile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac0083f6a869dabf0f4ef1773686d7989a4c235d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PcfFontFile.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..135224a30e3d6b73315b2df77a7ca3ce1621e52f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..438e13b952a8543f7718fc04fddd35ed11072a79 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/SunImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/SunImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75666fadc6acb3961af27337197ff4976b9f9a02 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/SunImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TarIO.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TarIO.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef94035b4f7454d99444bb433fa2b292d1b75ac5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TarIO.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef42e73668e49328995998b7d86b479340d3e74 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d18cb240248335cd114e1e2a4f8d5744cd3ed1d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..179fa9113a7648eb732fcd9bffe71b5c0bf52576 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..113c169289856ff27c12a7ea0d70b660227cca11 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d211e2b8dac143ed861008da833e42e2564dc80a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9713450169d7ad16b959c659792f5005882c839 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/__main__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_tkinter_finder.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_tkinter_finder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f8e1a5f77f126cda9a0846eb401ae0e4fd24d44 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_tkinter_finder.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_typing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0db7db185e76ed11fdd5c8a82e54769337e999a8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_typing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_util.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c042ce9b907f23b5eea95e0269172a61876ba3b3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_util.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d50436dc9e34684980d8541658138afafbfb93 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/_version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/features.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/features.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfa753735579dd68a1243a3c21a34aaeeedd7438 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/PIL/__pycache__/features.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS b/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..370a25d317c9063a3b87d59d0168570f4ee27cf2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS @@ -0,0 +1,8 @@ +This package has been mostly done by Armin Rigo with help from +Maciej FijaƂkowski. The idea is heavily based (although not directly +copied) from LuaJIT ffi by Mike Pall. + + +Other contributors: + + Google Inc. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a1dbfb017c2e0afcaac48ba6750d32539335e41 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,23 @@ + +Except when otherwise stated (look for LICENSE files in directories or +information at the beginning of each file) all software and +documentation is licensed as follows: + + MIT No Attribution + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the + Software is furnished to do so. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_cloud_bigquery_storage-2.38.0.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_cloud_bigquery_storage-2.38.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/google_cloud_bigquery_storage-2.38.0.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub-1.7.1.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub-1.7.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub-1.7.1.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46f4b2846fd708ecb81b2d665434ce6379aa1101 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 - 2023 Holger Krekel and others + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_checkpoint-4.1.1.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_checkpoint-4.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fc0602feecdd6748623c852ab534e1ca612673c7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_checkpoint-4.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 LangChain, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dd87ab2201b33081a3620c41804196c8ecd5ca0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_cache.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_cache.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a943a3cd279b282bffa59215623a08bcf54a7a02 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_cache.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_typing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..842612cef2872d4d1b3fdc78ea13fbc4f0372719 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/_typing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/beat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/beat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcde7201fce242987329b4db5c03e4938a10e86e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/beat.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/decompose.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/decompose.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..626946a1ceb8d2182bce395223d6063b4b2e64cf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/decompose.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/display.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/display.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e8d7452c3e4a47d76ea1e0553bed14af41d470f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/display.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/effects.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/effects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..900aff963cffbc652a068f34a21616c7b888bf5e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/effects.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/filters.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..098a8ad7f50a2387bc25c04a1f664d134fb4b31f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/filters.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/onset.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/onset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3458afb376c8570ce545e5b6f88096d57c70208e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/onset.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/segment.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/segment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2268a45af77d476dfa0ae7b413237e1d77be17a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/segment.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/sequence.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/sequence.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aa41e1ea73d1dd451b7d6c527291e212fab1723 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/sequence.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d9b2998806b368a573a7a86cf8f1b4d26240d9d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/__pycache__/version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7e20907aa2d9e90c9b4d8405e1b6bc55679aa0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Core IO and DSP functions""" + +import lazy_loader as lazy + +__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f992bddfff07ffc9b88c171be1f3fb49d94447be --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__init__.pyi @@ -0,0 +1,124 @@ +from .convert import ( + frames_to_samples as frames_to_samples, + frames_to_time as frames_to_time, + samples_to_frames as samples_to_frames, + samples_to_time as samples_to_time, + time_to_samples as time_to_samples, + time_to_frames as time_to_frames, + blocks_to_samples as blocks_to_samples, + blocks_to_frames as blocks_to_frames, + blocks_to_time as blocks_to_time, + note_to_hz as note_to_hz, + note_to_midi as note_to_midi, + midi_to_hz as midi_to_hz, + midi_to_note as midi_to_note, + hz_to_note as hz_to_note, + hz_to_midi as hz_to_midi, + hz_to_mel as hz_to_mel, + hz_to_octs as hz_to_octs, + hz_to_fjs as hz_to_fjs, + mel_to_hz as mel_to_hz, + octs_to_hz as octs_to_hz, + A4_to_tuning as A4_to_tuning, + tuning_to_A4 as tuning_to_A4, + fft_frequencies as fft_frequencies, + cqt_frequencies as cqt_frequencies, + mel_frequencies as mel_frequencies, + tempo_frequencies as tempo_frequencies, + fourier_tempo_frequencies as fourier_tempo_frequencies, + A_weighting as A_weighting, + B_weighting as B_weighting, + C_weighting as C_weighting, + D_weighting as D_weighting, + Z_weighting as Z_weighting, + frequency_weighting as frequency_weighting, + multi_frequency_weighting as multi_frequency_weighting, + samples_like as samples_like, + times_like as times_like, + midi_to_svara_h as midi_to_svara_h, + midi_to_svara_c as midi_to_svara_c, + note_to_svara_h as note_to_svara_h, + note_to_svara_c as note_to_svara_c, + hz_to_svara_h as hz_to_svara_h, + hz_to_svara_c as hz_to_svara_c, +) + +from .audio import ( + load as load, + stream as stream, + to_mono as to_mono, + resample as resample, + get_duration as get_duration, + get_samplerate as get_samplerate, + autocorrelate as autocorrelate, + lpc as lpc, + zero_crossings as zero_crossings, + clicks as clicks, + tone as tone, + chirp as chirp, + mu_compress as mu_compress, + mu_expand as mu_expand, +) + +from .spectrum import ( + stft as stft, + istft as istft, + magphase as magphase, + iirt as iirt, + reassigned_spectrogram as reassigned_spectrogram, + phase_vocoder as phase_vocoder, + perceptual_weighting as perceptual_weighting, + power_to_db as power_to_db, + db_to_power as db_to_power, + amplitude_to_db as amplitude_to_db, + db_to_amplitude as db_to_amplitude, + fmt as fmt, + pcen as pcen, + griffinlim as griffinlim, +) + +from .pitch import ( + estimate_tuning as estimate_tuning, + pitch_tuning as pitch_tuning, + piptrack as piptrack, + yin as yin, + pyin as pyin, +) + +from .constantq import ( + cqt as cqt, + hybrid_cqt as hybrid_cqt, + pseudo_cqt as pseudo_cqt, + icqt as icqt, + griffinlim_cqt as griffinlim_cqt, + vqt as vqt, +) + +from .harmonic import ( + salience as salience, + interp_harmonics as interp_harmonics, + f0_harmonics as f0_harmonics, +) + +from .fft import ( + get_fftlib as get_fftlib, + set_fftlib as set_fftlib, +) + +from .notation import ( + key_to_degrees as key_to_degrees, + key_to_notes as key_to_notes, + mela_to_degrees as mela_to_degrees, + mela_to_svara as mela_to_svara, + thaat_to_degrees as thaat_to_degrees, + list_mela as list_mela, + list_thaat as list_thaat, + fifths_to_note as fifths_to_note, + interval_to_fjs as interval_to_fjs, +) + +from .intervals import ( + interval_frequencies as interval_frequencies, + pythagorean_intervals as pythagorean_intervals, + plimit_intervals as plimit_intervals, +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afcce9a9ecf6615a4838de04410ea43ab703df4e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/audio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/audio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..388f2480569c161e6eae08ff34fc6f45bcd5cbc9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/audio.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/constantq.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/constantq.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa331ab06a2c434a8953525cff1e1159431d1feb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/constantq.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/convert.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/convert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee5ce6a57798e905cdb0eb95ea338c389bdc6056 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/convert.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/fft.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/fft.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48c7815b1941a33d65794b7778bc257268e9fb8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/fft.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/harmonic.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/harmonic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dccf8f94cf1d4e948886a620e640161b81d9420 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/harmonic.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/intervals.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/intervals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c88a35ef7167e53ca676dd0f24dd7319a2b47575 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/intervals.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/notation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/notation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b35c380ca27f760179f71261502d0e8266ddf629 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/notation.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/pitch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/pitch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3980bcb0bf401ee70a6d17d907269eacde1776af Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/__pycache__/pitch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/audio.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/audio.py new file mode 100644 index 0000000000000000000000000000000000000000..b5bb4ddb227a4d8824fe354644351c733b39a10c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/audio.py @@ -0,0 +1,1786 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Core IO, DSP and utility functions.""" +from __future__ import annotations + +import os +import pathlib +import warnings + +import soundfile as sf +import audioread +import numpy as np +import scipy +import scipy.signal +import soxr +import lazy_loader as lazy + +from numba import jit, stencil, guvectorize +from .fft import get_fftlib +from .convert import frames_to_samples, time_to_samples +from .._cache import cache +from .. import util +from ..util.exceptions import ParameterError +from ..util.decorators import deprecated +from ..util.deprecation import Deprecated, rename_kw +from .._typing import _FloatLike_co, _IntLike_co, _SequenceLike + +from typing import Any, BinaryIO, Callable, Generator, Optional, Tuple, Union +from numpy.typing import DTypeLike + +# Lazy-load optional dependencies +samplerate = lazy.load("samplerate") +resampy = lazy.load("resampy") + +__all__ = [ + "load", + "stream", + "to_mono", + "resample", + "get_duration", + "get_samplerate", + "autocorrelate", + "lpc", + "zero_crossings", + "clicks", + "tone", + "chirp", + "mu_compress", + "mu_expand", +] + + +# -- CORE ROUTINES --# +# Load should never be cached, since we cannot verify that the contents of +# 'path' are unchanged across calls. +def load( + path: Union[ + str, int, os.PathLike[Any], sf.SoundFile, audioread.AudioFile, BinaryIO + ], + *, + sr: Optional[float] = 22050, + mono: bool = True, + offset: float = 0.0, + duration: Optional[float] = None, + dtype: DTypeLike = np.float32, + res_type: str = "soxr_hq", +) -> Tuple[np.ndarray, Union[int, float]]: + """Load an audio file as a floating point time series. + + Audio will be automatically resampled to the given rate + (default ``sr=22050``). + + To preserve the native sampling rate of the file, use ``sr=None``. + + Parameters + ---------- + path : string, int, pathlib.Path, soundfile.SoundFile, audioread object, or file-like object + path to the input file. + + Any codec supported by `soundfile` or `audioread` will work. + + Any string file paths, or any object implementing Python's + file interface (e.g. `pathlib.Path`) are supported as `path`. + + If the codec is supported by `soundfile`, then `path` can also be + an open file descriptor (int) or an existing `soundfile.SoundFile` object. + + Pre-constructed audioread decoders are also supported here, see the example + below. This can be used, for example, to force a specific decoder rather + than relying upon audioread to select one for you. + + .. warning:: audioread support is deprecated as of version 0.10.0. + audioread support be removed in version 1.0. + + sr : number > 0 [scalar] + target sampling rate + + 'None' uses the native sampling rate + + mono : bool + convert signal to mono + + offset : float + start reading after this time (in seconds) + + duration : float + only load up to this much audio (in seconds) + + dtype : numeric type + data type of ``y`` + + res_type : str + resample type (see note) + + .. note:: + By default, this uses `soxr`'s high-quality mode ('HQ'). + + For alternative resampling modes, see `resample` + + .. note:: + `audioread` may truncate the precision of the audio data to 16 bits. + + See :ref:`ioformats` for alternate loading methods. + + Returns + ------- + y : np.ndarray [shape=(n,) or (..., n)] + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + + Examples + -------- + >>> # Load an ogg vorbis file + >>> filename = librosa.ex('trumpet') + >>> y, sr = librosa.load(filename) + >>> y + array([-1.407e-03, -4.461e-04, ..., -3.042e-05, 1.277e-05], + dtype=float32) + >>> sr + 22050 + + >>> # Load a file and resample to 11 KHz + >>> filename = librosa.ex('trumpet') + >>> y, sr = librosa.load(filename, sr=11025) + >>> y + array([-8.746e-04, -3.363e-04, ..., -1.301e-05, 0.000e+00], + dtype=float32) + >>> sr + 11025 + + >>> # Load 5 seconds of a file, starting 15 seconds in + >>> filename = librosa.ex('brahms') + >>> y, sr = librosa.load(filename, offset=15.0, duration=5.0) + >>> y + array([0.146, 0.144, ..., 0.128, 0.015], dtype=float32) + >>> sr + 22050 + + >>> # Load using an already open SoundFile object + >>> import soundfile + >>> sfo = soundfile.SoundFile(librosa.ex('brahms')) + >>> y, sr = librosa.load(sfo) + + >>> # Load using an already open audioread object + >>> import audioread.ffdec # Use ffmpeg decoder + >>> aro = audioread.ffdec.FFmpegAudioFile(librosa.ex('brahms')) + >>> y, sr = librosa.load(aro) + """ + if isinstance(path, tuple(audioread.available_backends())): + # Force the audioread loader if we have a reader object already + y, sr_native = __audioread_load(path, offset, duration, dtype) + else: + # Otherwise try soundfile first, and then fall back if necessary + try: + y, sr_native = __soundfile_load(path, offset, duration, dtype) + + except sf.SoundFileRuntimeError as exc: + # If soundfile failed, try audioread instead + if isinstance(path, (str, pathlib.PurePath)): + warnings.warn( + "PySoundFile failed. Trying audioread instead.", stacklevel=2 + ) + y, sr_native = __audioread_load(path, offset, duration, dtype) + else: + raise exc + + # Final cleanup for dtype and contiguity + if mono: + y = to_mono(y) + + if sr is not None: + y = resample(y, orig_sr=sr_native, target_sr=sr, res_type=res_type) + + else: + sr = sr_native + + return y, sr + + +def __soundfile_load(path, offset, duration, dtype): + """Load an audio buffer using soundfile.""" + if isinstance(path, sf.SoundFile): + # If the user passed an existing soundfile object, + # we can use it directly + context = path + else: + # Otherwise, create the soundfile object + context = sf.SoundFile(path) + + with context as sf_desc: + sr_native = sf_desc.samplerate + if offset: + # Seek to the start of the target read + sf_desc.seek(int(offset * sr_native)) + if duration is not None: + frame_duration = int(duration * sr_native) + else: + frame_duration = -1 + + # Load the target number of frames, and transpose to match librosa form + y = sf_desc.read(frames=frame_duration, dtype=dtype, always_2d=False).T + + return y, sr_native + + +@deprecated(version="0.10.0", version_removed="1.0") +def __audioread_load(path, offset, duration, dtype: DTypeLike): + """Load an audio buffer using audioread. + + This loads one block at a time, and then concatenates the results. + """ + buf = [] + + if isinstance(path, tuple(audioread.available_backends())): + # If we have an audioread object already, don't bother opening + reader = path + else: + # If the input was not an audioread object, try to open it + reader = audioread.audio_open(path) + + with reader as input_file: + sr_native = input_file.samplerate + n_channels = input_file.channels + + s_start = int(sr_native * offset) * n_channels + + if duration is None: + s_end = np.inf + else: + s_end = s_start + (int(sr_native * duration) * n_channels) + + n = 0 + + for frame in input_file: + frame = util.buf_to_float(frame, dtype=dtype) + n_prev = n + n = n + len(frame) + + if n < s_start: + # offset is after the current frame + # keep reading + continue + + if s_end < n_prev: + # we're off the end. stop reading + break + + if s_end < n: + # the end is in this frame. crop. + frame = frame[: int(s_end - n_prev)] # pragma: no cover + + if n_prev <= s_start <= n: + # beginning is in this frame + frame = frame[(s_start - n_prev) :] + + # tack on the current frame + buf.append(frame) + + if buf: + y = np.concatenate(buf) + if n_channels > 1: + y = y.reshape((-1, n_channels)).T + else: + y = np.empty(0, dtype=dtype) + + return y, sr_native + + +def stream( + path: Union[str, int, sf.SoundFile, BinaryIO], + *, + block_length: int, + frame_length: int, + hop_length: int, + mono: bool = True, + offset: float = 0.0, + duration: Optional[float] = None, + fill_value: Optional[float] = None, + dtype: DTypeLike = np.float32, +) -> Generator[np.ndarray, None, None]: + """Stream audio in fixed-length buffers. + + This is primarily useful for processing large files that won't + fit entirely in memory at once. + + Instead of loading the entire audio signal into memory (as + in `load`, this function produces *blocks* of audio spanning + a fixed number of frames at a specified frame length and hop + length. + + While this function strives for similar behavior to `load`, + there are a few caveats that users should be aware of: + + 1. This function does not return audio buffers directly. + It returns a generator, which you can iterate over + to produce blocks of audio. A *block*, in this context, + refers to a buffer of audio which spans a given number of + (potentially overlapping) frames. + 2. Automatic sample-rate conversion is not supported. + Audio will be streamed in its native sample rate, + so no default values are provided for ``frame_length`` + and ``hop_length``. It is recommended that you first + get the sampling rate for the file in question, using + `get_samplerate`, and set these parameters accordingly. + 3. Many analyses require access to the entire signal + to behave correctly, such as `resample`, `cqt`, or + `beat_track`, so these methods will not be appropriate + for streamed data. + 4. The ``block_length`` parameter specifies how many frames + of audio will be produced per block. Larger values will + consume more memory, but will be more efficient to process + down-stream. The best value will ultimately depend on your + application and other system constraints. + 5. By default, most librosa analyses (e.g., short-time Fourier + transform) assume centered frames, which requires padding the + signal at the beginning and end. This will not work correctly + when the signal is carved into blocks, because it would introduce + padding in the middle of the signal. To disable this feature, + use ``center=False`` in all frame-based analyses. + + See the examples below for proper usage of this function. + + Parameters + ---------- + path : string, int, sf.SoundFile, or file-like object + path to the input file to stream. + + Any codec supported by `soundfile` is permitted here. + + An existing `soundfile.SoundFile` object may also be provided. + + block_length : int > 0 + The number of frames to include in each block. + + Note that at the end of the file, there may not be enough + data to fill an entire block, resulting in a shorter block + by default. To pad the signal out so that blocks are always + full length, set ``fill_value`` (see below). + + frame_length : int > 0 + The number of samples per frame. + + hop_length : int > 0 + The number of samples to advance between frames. + + Note that by when ``hop_length < frame_length``, neighboring frames + will overlap. Similarly, the last frame of one *block* will overlap + with the first frame of the next *block*. + + mono : bool + Convert the signal to mono during streaming + + offset : float + Start reading after this time (in seconds) + + duration : float + Only load up to this much audio (in seconds) + + fill_value : float [optional] + If padding the signal to produce constant-length blocks, + this value will be used at the end of the signal. + + In most cases, ``fill_value=0`` (silence) is expected, but + you may specify any value here. + + dtype : numeric type + data type of audio buffers to be produced + + Yields + ------ + y : np.ndarray + An audio buffer of (at most) + ``(block_length-1) * hop_length + frame_length`` samples. + + See Also + -------- + load + get_samplerate + soundfile.blocks + + Examples + -------- + Apply a short-term Fourier transform to blocks of 256 frames + at a time. Note that streaming operation requires left-aligned + frames, so we must set ``center=False`` to avoid padding artifacts. + + >>> filename = librosa.ex('brahms') + >>> sr = librosa.get_samplerate(filename) + >>> stream = librosa.stream(filename, + ... block_length=256, + ... frame_length=4096, + ... hop_length=1024) + >>> for y_block in stream: + ... D_block = librosa.stft(y_block, center=False) + + Or compute a mel spectrogram over a stream, using a shorter frame + and non-overlapping windows + + >>> filename = librosa.ex('brahms') + >>> sr = librosa.get_samplerate(filename) + >>> stream = librosa.stream(filename, + ... block_length=256, + ... frame_length=2048, + ... hop_length=2048) + >>> for y_block in stream: + ... m_block = librosa.feature.melspectrogram(y=y_block, sr=sr, + ... n_fft=2048, + ... hop_length=2048, + ... center=False) + """ + if not util.is_positive_int(block_length): + raise ParameterError(f"block_length={block_length} must be a positive integer") + if not util.is_positive_int(frame_length): + raise ParameterError(f"frame_length={frame_length} must be a positive integer") + if not util.is_positive_int(hop_length): + raise ParameterError(f"hop_length={hop_length} must be a positive integer") + + if isinstance(path, sf.SoundFile): + sfo = path + else: + sfo = sf.SoundFile(path) + + # Get the sample rate from the file info + sr = sfo.samplerate + + # Construct the stream + if offset: + start = int(offset * sr) + else: + start = 0 + + if duration: + frames = int(duration * sr) + else: + frames = -1 + + # Seek the soundfile object to the starting frame + sfo.seek(start) + + blocks = sfo.blocks( + blocksize=frame_length + (block_length - 1) * hop_length, + overlap=frame_length - hop_length, + frames=frames, + dtype=dtype, + always_2d=False, + fill_value=fill_value, + ) + + for block in blocks: + if mono: + yield to_mono(block.T) + else: + yield block.T + + +@cache(level=20) +def to_mono(y: np.ndarray) -> np.ndarray: + """Convert an audio signal to mono by averaging samples across channels. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + Returns + ------- + y_mono : np.ndarray [shape=(n,)] + ``y`` as a monophonic time-series + + Notes + ----- + This function caches at level 20. + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet', hq=True), mono=False) + >>> y.shape + (2, 117601) + >>> y_mono = librosa.to_mono(y) + >>> y_mono.shape + (117601,) + """ + # Validate the buffer + util.valid_audio(y) + + if y.ndim > 1: + y = np.mean(y, axis=tuple(range(y.ndim - 1))) + + return y + + +@cache(level=20) +def resample( + y: np.ndarray, + *, + orig_sr: float, + target_sr: float, + res_type: str = "soxr_hq", + fix: bool = True, + scale: bool = False, + axis: int = -1, + **kwargs: Any, +) -> np.ndarray: + """Resample a time series from orig_sr to target_sr + + By default, this uses a high-quality method (`soxr_hq`) for band-limited sinc + interpolation. The alternate ``res_type`` values listed below offer different + trade-offs of speed and quality. + + Parameters + ---------- + y : np.ndarray [shape=(..., n, ...)] + audio time series, with `n` samples along the specified axis. + + orig_sr : number > 0 [scalar] + original sampling rate of ``y`` + + target_sr : number > 0 [scalar] + target sampling rate + + res_type : str (default: `soxr_hq`) + resample type + + 'soxr_vhq', 'soxr_hq', 'soxr_mq' or 'soxr_lq' + `soxr` Very high-, High-, Medium-, Low-quality FFT-based bandlimited interpolation. + ``'soxr_hq'`` is the default setting of `soxr`. + 'soxr_qq' + `soxr` Quick cubic interpolation (very fast, but not bandlimited) + 'kaiser_best' + `resampy` high-quality mode + 'kaiser_fast' + `resampy` faster method + 'fft' or 'scipy' + `scipy.signal.resample` Fourier method. + 'polyphase' + `scipy.signal.resample_poly` polyphase filtering. (fast) + 'linear' + `samplerate` linear interpolation. (very fast, but not bandlimited) + 'zero_order_hold' + `samplerate` repeat the last value between samples. (very fast, but not bandlimited) + 'sinc_best', 'sinc_medium' or 'sinc_fastest' + `samplerate` high-, medium-, and low-quality bandlimited sinc interpolation. + + .. note:: + Not all options yield a bandlimited interpolator. If you use `soxr_qq`, `polyphase`, + `linear`, or `zero_order_hold`, you need to be aware of possible aliasing effects. + + .. note:: + `samplerate` and `resampy` are not installed with `librosa`. + To use `samplerate` or `resampy`, they should be installed manually:: + + $ pip install samplerate + $ pip install resampy + + .. note:: + When using ``res_type='polyphase'``, only integer sampling rates are + supported. + + fix : bool + adjust the length of the resampled signal to be of size exactly + ``ceil(target_sr * len(y) / orig_sr)`` + + scale : bool + Scale the resampled signal so that ``y`` and ``y_hat`` have approximately + equal total energy. + + axis : int + The target axis along which to resample. Defaults to the trailing axis. + + **kwargs : additional keyword arguments + If ``fix==True``, additional keyword arguments to pass to + `librosa.util.fix_length`. + + Returns + ------- + y_hat : np.ndarray [shape=(..., n * target_sr / orig_sr, ...)] + ``y`` resampled from ``orig_sr`` to ``target_sr`` along the target axis + + Raises + ------ + ParameterError + If ``res_type='polyphase'`` and ``orig_sr`` or ``target_sr`` are not both + integer-valued. + + See Also + -------- + librosa.util.fix_length + scipy.signal.resample + resampy + samplerate.converters.resample + soxr.resample + + Notes + ----- + This function caches at level 20. + + Examples + -------- + Downsample from 22 KHz to 8 KHz + + >>> y, sr = librosa.load(librosa.ex('trumpet'), sr=22050) + >>> y_8k = librosa.resample(y, orig_sr=sr, target_sr=8000) + >>> y.shape, y_8k.shape + ((117601,), (42668,)) + """ + # First, validate the audio buffer + util.valid_audio(y) + + if orig_sr == target_sr: + return y + + ratio = float(target_sr) / orig_sr + + n_samples = int(np.ceil(y.shape[axis] * ratio)) + + if res_type in ("scipy", "fft"): + y_hat = scipy.signal.resample(y, n_samples, axis=axis) + elif res_type == "polyphase": + if int(orig_sr) != orig_sr or int(target_sr) != target_sr: + raise ParameterError( + "polyphase resampling is only supported for integer-valued sampling rates." + ) + + # For polyphase resampling, we need up- and down-sampling ratios + # We can get those from the greatest common divisor of the rates + # as long as the rates are integrable + orig_sr = int(orig_sr) + target_sr = int(target_sr) + gcd = np.gcd(orig_sr, target_sr) + y_hat = scipy.signal.resample_poly( + y, target_sr // gcd, orig_sr // gcd, axis=axis + ) + elif res_type in ( + "linear", + "zero_order_hold", + "sinc_best", + "sinc_fastest", + "sinc_medium", + ): + # Use numpy to vectorize the resampler along the target axis + # This is because samplerate does not support ndim>2 generally. + y_hat = np.apply_along_axis( + samplerate.resample, axis=axis, arr=y, ratio=ratio, converter_type=res_type + ) + elif res_type.startswith("soxr"): + # Use numpy to vectorize the resampler along the target axis + # This is because soxr does not support ndim>2 generally. + y_hat = np.apply_along_axis( + soxr.resample, + axis=axis, + arr=y, + in_rate=orig_sr, + out_rate=target_sr, + quality=res_type, + ) + else: + y_hat = resampy.resample(y, orig_sr, target_sr, filter=res_type, axis=axis) + + if fix: + y_hat = util.fix_length(y_hat, size=n_samples, axis=axis, **kwargs) + + if scale: + y_hat /= np.sqrt(ratio) + + # Match dtypes + return np.asarray(y_hat, dtype=y.dtype) + + +def get_duration( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + center: bool = True, + path: Optional[Union[str, os.PathLike[Any]]] = None, + filename: Optional[Union[str, os.PathLike[Any], Deprecated]] = Deprecated(), +) -> float: + """Compute the duration (in seconds) of an audio time series, + feature matrix, or filename. + + Examples + -------- + >>> # Load an example audio file + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.get_duration(y=y, sr=sr) + 5.333378684807256 + + >>> # Or directly from an audio file + >>> librosa.get_duration(filename=librosa.ex('trumpet')) + 5.333378684807256 + + >>> # Or compute duration from an STFT matrix + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = librosa.stft(y) + >>> librosa.get_duration(S=S, sr=sr) + 5.317369614512471 + + >>> # Or a non-centered STFT matrix + >>> S_left = librosa.stft(y, center=False) + >>> librosa.get_duration(S=S_left, sr=sr) + 5.224489795918367 + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + audio sampling rate of ``y`` + + S : np.ndarray [shape=(..., d, t)] or None + STFT matrix, or any STFT-derived matrix (e.g., chromagram + or mel spectrogram). + Durations calculated from spectrogram inputs are only accurate + up to the frame resolution. If high precision is required, + it is better to use the audio time series directly. + + n_fft : int > 0 [scalar] + FFT window size for ``S`` + + hop_length : int > 0 [ scalar] + number of audio samples between columns of ``S`` + + center : boolean + - If ``True``, ``S[:, t]`` is centered at ``y[t * hop_length]`` + - If ``False``, then ``S[:, t]`` begins at ``y[t * hop_length]`` + + path : str, path, or file-like + If provided, all other parameters are ignored, and the + duration is calculated directly from the audio file. + Note that this avoids loading the contents into memory, + and is therefore useful for querying the duration of + long files. + + As in ``load``, this can also be an integer or open file-handle + that can be processed by ``soundfile``. + + filename : Deprecated + Equivalent to ``path`` + + .. warning:: This parameter has been renamed to ``path`` in 0.10. + Support for ``filename=`` will be removed in 1.0. + + Returns + ------- + d : float >= 0 + Duration (in seconds) of the input time series or spectrogram. + + Raises + ------ + ParameterError + if none of ``y``, ``S``, or ``path`` are provided. + + Notes + ----- + `get_duration` can be applied to a file (``path``), a spectrogram (``S``), + or audio buffer (``y, sr``). Only one of these three options should be + provided. If you do provide multiple options (e.g., ``path`` and ``S``), + then ``path`` takes precedence over ``S``, and ``S`` takes precedence over + ``(y, sr)``. + """ + path = rename_kw( + old_name="filename", + old_value=filename, + new_name="path", + new_value=path, + version_deprecated="0.10.0", + version_removed="1.0", + ) + + if path is not None: + try: + return sf.info(path).duration # type: ignore + except sf.SoundFileRuntimeError: + warnings.warn( + "PySoundFile failed. Trying audioread instead." + "\n\tAudioread support is deprecated in librosa 0.10.0" + " and will be removed in version 1.0.", + stacklevel=2, + category=FutureWarning, + ) + with audioread.audio_open(path) as fdesc: + return fdesc.duration # type: ignore + + if y is None: + if S is None: + raise ParameterError("At least one of (y, sr), S, or path must be provided") + + n_frames = S.shape[-1] + n_samples = n_fft + hop_length * (n_frames - 1) + + # If centered, we lose half a window from each end of S + if center: + n_samples = n_samples - 2 * int(n_fft // 2) + + else: + n_samples = y.shape[-1] + + return float(n_samples) / sr + + +def get_samplerate(path: Union[str, int, sf.SoundFile, BinaryIO]) -> float: + """Get the sampling rate for a given file. + + Parameters + ---------- + path : string, int, soundfile.SoundFile, or file-like + The path to the file to be loaded + As in ``load``, this can also be an integer or open file-handle + that can be processed by `soundfile`. + An existing `soundfile.SoundFile` object can also be supplied. + + Returns + ------- + sr : number > 0 + The sampling rate of the given audio file + + Examples + -------- + Get the sampling rate for the included audio file + + >>> path = librosa.ex('trumpet') + >>> librosa.get_samplerate(path) + 22050 + """ + try: + if isinstance(path, sf.SoundFile): + return path.samplerate # type: ignore + + return sf.info(path).samplerate # type: ignore + except sf.SoundFileRuntimeError: + warnings.warn( + "PySoundFile failed. Trying audioread instead." + "\n\tAudioread support is deprecated in librosa 0.10.0" + " and will be removed in version 1.0.", + stacklevel=2, + category=FutureWarning, + ) + with audioread.audio_open(path) as fdesc: + return fdesc.samplerate # type: ignore + + +@cache(level=20) +def autocorrelate( + y: np.ndarray, *, max_size: Optional[int] = None, axis: int = -1 +) -> np.ndarray: + """Bounded-lag auto-correlation + + Parameters + ---------- + y : np.ndarray + array to autocorrelate + max_size : int > 0 or None + maximum correlation lag. + If unspecified, defaults to ``y.shape[axis]`` (unbounded) + axis : int + The axis along which to autocorrelate. + By default, the last axis (-1) is taken. + + Returns + ------- + z : np.ndarray + truncated autocorrelation ``y*y`` along the specified axis. + If ``max_size`` is specified, then ``z.shape[axis]`` is bounded + to ``max_size``. + + Notes + ----- + This function caches at level 20. + + Examples + -------- + Compute full autocorrelation of ``y`` + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.autocorrelate(y) + array([ 6.899e+02, 6.236e+02, ..., 3.710e-08, -1.796e-08]) + + Compute onset strength auto-correlation up to 4 seconds + + >>> import matplotlib.pyplot as plt + >>> odf = librosa.onset.onset_strength(y=y, sr=sr, hop_length=512) + >>> ac = librosa.autocorrelate(odf, max_size=4 * sr // 512) + >>> fig, ax = plt.subplots() + >>> ax.plot(ac) + >>> ax.set(title='Auto-correlation', xlabel='Lag (frames)') + """ + if max_size is None: + max_size = y.shape[axis] + + max_size = int(min(max_size, y.shape[axis])) + + fft = get_fftlib() + + real = not np.iscomplexobj(y) + + # Pad out the signal to support full-length auto-correlation + n_pad = scipy.fft.next_fast_len(2 * y.shape[axis] - 1, real=real) + + if real: + # Compute the power spectrum along the chosen axis + powspec = util.abs2(fft.rfft(y, n=n_pad, axis=axis)) + + # Convert back to time domain + autocorr = fft.irfft(powspec, n=n_pad, axis=axis) + else: + # Compute the power spectrum along the chosen axis + powspec = util.abs2(fft.fft(y, n=n_pad, axis=axis)) + + # Convert back to time domain + autocorr = fft.ifft(powspec, n=n_pad, axis=axis) + + # Slice down to max_size + subslice = [slice(None)] * autocorr.ndim + subslice[axis] = slice(max_size) + + autocorr_slice: np.ndarray = autocorr[tuple(subslice)] + + return autocorr_slice + + +def lpc(y: np.ndarray, *, order: int, axis: int = -1) -> np.ndarray: + """Linear Prediction Coefficients via Burg's method + + This function applies Burg's method to estimate coefficients of a linear + filter on ``y`` of order ``order``. Burg's method is an extension to the + Yule-Walker approach, which are both sometimes referred to as LPC parameter + estimation by autocorrelation. + + It follows the description and implementation approach described in the + introduction by Marple. [#]_ N.B. This paper describes a different method, which + is not implemented here, but has been chosen for its clear explanation of + Burg's technique in its introduction. + + .. [#] Larry Marple. + A New Autoregressive Spectrum Analysis Algorithm. + IEEE Transactions on Acoustics, Speech, and Signal Processing + vol 28, no. 4, 1980. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + Time series to fit. Multi-channel is supported.. + order : int > 0 + Order of the linear filter + axis : int + Axis along which to compute the coefficients + + Returns + ------- + a : np.ndarray [shape=(..., order + 1)] + LP prediction error coefficients, i.e. filter denominator polynomial. + Note that the length along the specified ``axis`` will be ``order+1``. + + Raises + ------ + ParameterError + - If ``y`` is not valid audio as per `librosa.util.valid_audio` + - If ``order < 1`` or not integer + FloatingPointError + - If ``y`` is ill-conditioned + + See Also + -------- + scipy.signal.lfilter + + Examples + -------- + Compute LP coefficients of y at order 16 on entire series + + >>> y, sr = librosa.load(librosa.ex('libri1')) + >>> librosa.lpc(y, order=16) + + Compute LP coefficients, and plot LP estimate of original series + + >>> import matplotlib.pyplot as plt + >>> import scipy + >>> y, sr = librosa.load(librosa.ex('libri1'), duration=0.020) + >>> a = librosa.lpc(y, order=2) + >>> b = np.hstack([[0], -1 * a[1:]]) + >>> y_hat = scipy.signal.lfilter(b, [1], y) + >>> fig, ax = plt.subplots() + >>> ax.plot(y) + >>> ax.plot(y_hat, linestyle='--') + >>> ax.legend(['y', 'y_hat']) + >>> ax.set_title('LP Model Forward Prediction') + + """ + if not util.is_positive_int(order): + raise ParameterError(f"order={order} must be an integer > 0") + + util.valid_audio(y) + + # Move the lpc axis around front, because numba is silly + y = y.swapaxes(axis, 0) + + dtype = y.dtype + + shape = list(y.shape) + shape[0] = order + 1 + + ar_coeffs = np.zeros(tuple(shape), dtype=dtype) + ar_coeffs[0] = 1 + + ar_coeffs_prev = ar_coeffs.copy() + + shape[0] = 1 + reflect_coeff = np.zeros(shape, dtype=dtype) + den = reflect_coeff.copy() + + epsilon = util.tiny(den) + + # Call the helper, and swap the results back to the target axis position + return np.swapaxes( + __lpc(y, order, ar_coeffs, ar_coeffs_prev, reflect_coeff, den, epsilon), 0, axis + ) + + +@jit(nopython=True, cache=True) # type: ignore +def __lpc( + y: np.ndarray, + order: int, + ar_coeffs: np.ndarray, + ar_coeffs_prev: np.ndarray, + reflect_coeff: np.ndarray, + den: np.ndarray, + epsilon: float, +) -> np.ndarray: + # This implementation follows the description of Burg's algorithm given in + # section III of Marple's paper referenced in the docstring. + # + # We use the Levinson-Durbin recursion to compute AR coefficients for each + # increasing model order by using those from the last. We maintain two + # arrays and then flip them each time we increase the model order so that + # we may use all the coefficients from the previous order while we compute + # those for the new one. These two arrays hold ar_coeffs for order M and + # order M-1. (Corresponding to a_{M,k} and a_{M-1,k} in eqn 5) + + # These two arrays hold the forward and backward prediction error. They + # correspond to f_{M-1,k} and b_{M-1,k} in eqns 10, 11, 13 and 14 of + # Marple. First they are used to compute the reflection coefficient at + # order M from M-1 then are used as f_{M,k} and b_{M,k} for each + # iteration of the below loop + fwd_pred_error = y[1:] + bwd_pred_error = y[:-1] + + # DEN_{M} from eqn 16 of Marple. + den[0] = np.sum(fwd_pred_error**2 + bwd_pred_error**2, axis=0) + + for i in range(order): + # can be removed if we keep the epsilon bias + # if np.any(den <= 0): + # raise FloatingPointError("numerical error, input ill-conditioned?") + + # Eqn 15 of Marple, with fwd_pred_error and bwd_pred_error + # corresponding to f_{M-1,k+1} and b{M-1,k} and the result as a_{M,M} + + reflect_coeff[0] = np.sum(bwd_pred_error * fwd_pred_error, axis=0) + reflect_coeff[0] *= -2 + reflect_coeff[0] /= den[0] + epsilon + + # Now we use the reflection coefficient and the AR coefficients from + # the last model order to compute all of the AR coefficients for the + # current one. This is the Levinson-Durbin recursion described in + # eqn 5. + # Note 1: We don't have to care about complex conjugates as our signals + # are all real-valued + # Note 2: j counts 1..order+1, i-j+1 counts order..0 + # Note 3: The first element of ar_coeffs* is always 1, which copies in + # the reflection coefficient at the end of the new AR coefficient array + # after the preceding coefficients + + ar_coeffs_prev, ar_coeffs = ar_coeffs, ar_coeffs_prev + for j in range(1, i + 2): + # reflection multiply should be broadcast + ar_coeffs[j] = ( + ar_coeffs_prev[j] + reflect_coeff[0] * ar_coeffs_prev[i - j + 1] + ) + + # Update the forward and backward prediction errors corresponding to + # eqns 13 and 14. We start with f_{M-1,k+1} and b_{M-1,k} and use them + # to compute f_{M,k} and b_{M,k} + fwd_pred_error_tmp = fwd_pred_error + fwd_pred_error = fwd_pred_error + reflect_coeff * bwd_pred_error + bwd_pred_error = bwd_pred_error + reflect_coeff * fwd_pred_error_tmp + + # SNIP - we are now done with order M and advance. M-1 <- M + + # Compute DEN_{M} using the recursion from eqn 17. + # + # reflect_coeff = a_{M-1,M-1} (we have advanced M) + # den = DEN_{M-1} (rhs) + # bwd_pred_error = b_{M-1,N-M+1} (we have advanced M) + # fwd_pred_error = f_{M-1,k} (we have advanced M) + # den <- DEN_{M} (lhs) + # + + q = 1.0 - reflect_coeff[0] ** 2 + den[0] = q * den[0] - bwd_pred_error[-1] ** 2 - fwd_pred_error[0] ** 2 + + # Shift up forward error. + # + # fwd_pred_error <- f_{M-1,k+1} + # bwd_pred_error <- b_{M-1,k} + # + # N.B. We do this after computing the denominator using eqn 17 but + # before using it in the numerator in eqn 15. + fwd_pred_error = fwd_pred_error[1:] + bwd_pred_error = bwd_pred_error[:-1] + + return ar_coeffs + + +@stencil # type: ignore +def _zc_stencil(x: np.ndarray, threshold: float, zero_pos: bool) -> np.ndarray: + """Stencil to compute zero crossings""" + x0 = x[0] + if -threshold <= x0 <= threshold: + x0 = 0 + + x1 = x[-1] + if -threshold <= x1 <= threshold: + x1 = 0 + + if zero_pos: + return np.signbit(x0) != np.signbit(x1) # type: ignore + else: + return np.sign(x0) != np.sign(x1) # type: ignore + + +@guvectorize( + [ + "void(float32[:], float32, bool_, bool_[:])", + "void(float64[:], float64, bool_, bool_[:])", + ], + "(n),(),()->(n)", + cache=True, + nopython=True, +) # type: ignore +def _zc_wrapper( + x: np.ndarray, + threshold: float, + zero_pos: bool, + y: np.ndarray, +) -> None: # pragma: no cover + """Vectorized wrapper for zero crossing stencil""" + y[:] = _zc_stencil(x, threshold, zero_pos) + + +@cache(level=20) +def zero_crossings( + y: np.ndarray, + *, + threshold: float = 1e-10, + ref_magnitude: Optional[Union[float, Callable]] = None, + pad: bool = True, + zero_pos: bool = True, + axis: int = -1, +) -> np.ndarray: + """Find the zero-crossings of a signal ``y``: indices ``i`` such that + ``sign(y[i]) != sign(y[j])``. + + If ``y`` is multi-dimensional, then zero-crossings are computed along + the specified ``axis``. + + Parameters + ---------- + y : np.ndarray + The input array + + threshold : float >= 0 + If non-zero, values where ``-threshold <= y <= threshold`` are + clipped to 0. + + ref_magnitude : float > 0 or callable + If numeric, the threshold is scaled relative to ``ref_magnitude``. + + If callable, the threshold is scaled relative to + ``ref_magnitude(np.abs(y))``. + + pad : boolean + If ``True``, then ``y[0]`` is considered a valid zero-crossing. + + zero_pos : boolean + If ``True`` then the value 0 is interpreted as having positive sign. + + If ``False``, then 0, -1, and +1 all have distinct signs. + + axis : int + Axis along which to compute zero-crossings. + + Returns + ------- + zero_crossings : np.ndarray [shape=y.shape, dtype=boolean] + Indicator array of zero-crossings in ``y`` along the selected axis. + + Notes + ----- + This function caches at level 20. + + Examples + -------- + >>> # Generate a time-series + >>> y = np.sin(np.linspace(0, 4 * 2 * np.pi, 20)) + >>> y + array([ 0.000e+00, 9.694e-01, 4.759e-01, -7.357e-01, + -8.372e-01, 3.247e-01, 9.966e-01, 1.646e-01, + -9.158e-01, -6.142e-01, 6.142e-01, 9.158e-01, + -1.646e-01, -9.966e-01, -3.247e-01, 8.372e-01, + 7.357e-01, -4.759e-01, -9.694e-01, -9.797e-16]) + >>> # Compute zero-crossings + >>> z = librosa.zero_crossings(y) + >>> z + array([ True, False, False, True, False, True, False, False, + True, False, True, False, True, False, False, True, + False, True, False, True], dtype=bool) + + >>> # Stack y against the zero-crossing indicator + >>> librosa.util.stack([y, z], axis=-1) + array([[ 0.000e+00, 1.000e+00], + [ 9.694e-01, 0.000e+00], + [ 4.759e-01, 0.000e+00], + [ -7.357e-01, 1.000e+00], + [ -8.372e-01, 0.000e+00], + [ 3.247e-01, 1.000e+00], + [ 9.966e-01, 0.000e+00], + [ 1.646e-01, 0.000e+00], + [ -9.158e-01, 1.000e+00], + [ -6.142e-01, 0.000e+00], + [ 6.142e-01, 1.000e+00], + [ 9.158e-01, 0.000e+00], + [ -1.646e-01, 1.000e+00], + [ -9.966e-01, 0.000e+00], + [ -3.247e-01, 0.000e+00], + [ 8.372e-01, 1.000e+00], + [ 7.357e-01, 0.000e+00], + [ -4.759e-01, 1.000e+00], + [ -9.694e-01, 0.000e+00], + [ -9.797e-16, 1.000e+00]]) + + >>> # Find the indices of zero-crossings + >>> np.nonzero(z) + (array([ 0, 3, 5, 8, 10, 12, 15, 17, 19]),) + """ + if callable(ref_magnitude): + threshold = threshold * ref_magnitude(np.abs(y)) + + elif ref_magnitude is not None: + threshold = threshold * ref_magnitude + + yi = y.swapaxes(-1, axis) + z = np.empty_like(y, dtype=bool) + zi = z.swapaxes(-1, axis) + + _zc_wrapper(yi, threshold, zero_pos, zi) + + zi[..., 0] = pad + + return z + + +def clicks( + *, + times: Optional[_SequenceLike[_FloatLike_co]] = None, + frames: Optional[_SequenceLike[_IntLike_co]] = None, + sr: float = 22050, + hop_length: int = 512, + click_freq: float = 1000.0, + click_duration: float = 0.1, + click: Optional[np.ndarray] = None, + length: Optional[int] = None, +) -> np.ndarray: + """Construct a "click track". + + This returns a signal with the signal ``click`` sound placed at + each specified time. + + Parameters + ---------- + times : np.ndarray or None + times to place clicks, in seconds + frames : np.ndarray or None + frame indices to place clicks + sr : number > 0 + desired sampling rate of the output signal + hop_length : int > 0 + if positions are specified by ``frames``, the number of samples between frames. + click_freq : float > 0 + frequency (in Hz) of the default click signal. Default is 1KHz. + click_duration : float > 0 + duration (in seconds) of the default click signal. Default is 100ms. + click : np.ndarray or None + (optional) click signal sample to use instead of the default click. + Multi-channel is supported. + length : int > 0 + desired number of samples in the output signal + + Returns + ------- + click_signal : np.ndarray + Synthesized click signal. + This will be monophonic by default, or match the number of channels to a provided ``click`` signal. + + Raises + ------ + ParameterError + - If neither ``times`` nor ``frames`` are provided. + - If any of ``click_freq``, ``click_duration``, or ``length`` are out of range. + + Examples + -------- + >>> # Sonify detected beat events + >>> y, sr = librosa.load(librosa.ex('choice'), duration=10) + >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr) + >>> y_beats = librosa.clicks(frames=beats, sr=sr) + + >>> # Or generate a signal of the same length as y + >>> y_beats = librosa.clicks(frames=beats, sr=sr, length=len(y)) + + >>> # Or use timing instead of frame indices + >>> times = librosa.frames_to_time(beats, sr=sr) + >>> y_beat_times = librosa.clicks(times=times, sr=sr) + + >>> # Or with a click frequency of 880Hz and a 500ms sample + >>> y_beat_times880 = librosa.clicks(times=times, sr=sr, + ... click_freq=880, click_duration=0.5) + + Display click waveform next to the spectrogram + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> S = librosa.feature.melspectrogram(y=y, sr=sr) + >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max), + ... x_axis='time', y_axis='mel', ax=ax[0]) + >>> librosa.display.waveshow(y_beat_times, sr=sr, label='Beat clicks', + ... ax=ax[1]) + >>> ax[1].legend() + >>> ax[0].label_outer() + >>> ax[0].set_title(None) + """ + # Compute sample positions from time or frames + positions: np.ndarray + if times is None: + if frames is None: + raise ParameterError('either "times" or "frames" must be provided') + + positions = frames_to_samples(frames, hop_length=hop_length) + else: + # Convert times to positions + positions = time_to_samples(times, sr=sr) + + if click is not None: + # Check that we have a well-formed audio buffer + util.valid_audio(click) + + else: + # Create default click signal + if click_duration <= 0: + raise ParameterError("click_duration must be strictly positive") + + if click_freq <= 0: + raise ParameterError("click_freq must be strictly positive") + + angular_freq = 2 * np.pi * click_freq / float(sr) + + click = np.logspace(0, -10, num=int(sr * click_duration), base=2.0) + + click *= np.sin(angular_freq * np.arange(len(click))) + + # Set default length + if length is None: + length = positions.max() + click.shape[-1] + else: + if length < 1: + raise ParameterError("length must be a positive integer") + + # Filter out any positions past the length boundary + positions = positions[positions < length] + + # Pre-allocate click signal + shape = list(click.shape) + shape[-1] = length + click_signal = np.zeros(shape, dtype=np.float32) + + # Place clicks + for start in positions: + # Compute the end-point of this click + end = start + click.shape[-1] + + if end >= length: + click_signal[..., start:] += click[..., : length - start] + else: + # Normally, just add a click here + click_signal[..., start:end] += click + + return click_signal + + +def tone( + frequency: _FloatLike_co, + *, + sr: float = 22050, + length: Optional[int] = None, + duration: Optional[float] = None, + phi: Optional[float] = None, +) -> np.ndarray: + """Construct a pure tone (cosine) signal at a given frequency. + + Parameters + ---------- + frequency : float > 0 + frequency + sr : number > 0 + desired sampling rate of the output signal + length : int > 0 + desired number of samples in the output signal. + When both ``duration`` and ``length`` are defined, + ``length`` takes priority. + duration : float > 0 + desired duration in seconds. + When both ``duration`` and ``length`` are defined, + ``length`` takes priority. + phi : float or None + phase offset, in radians. If unspecified, defaults to ``-np.pi * 0.5``. + + Returns + ------- + tone_signal : np.ndarray [shape=(length,), dtype=float64] + Synthesized pure sine tone signal + + Raises + ------ + ParameterError + - If ``frequency`` is not provided. + - If neither ``length`` nor ``duration`` are provided. + + Examples + -------- + Generate a pure sine tone A4 + + >>> tone = librosa.tone(440, duration=1, sr=22050) + + Or generate the same signal using `length` + + >>> tone = librosa.tone(440, sr=22050, length=22050) + + Display spectrogram + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> S = librosa.feature.melspectrogram(y=tone) + >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max), + ... x_axis='time', y_axis='mel', ax=ax) + """ + if frequency is None: + raise ParameterError('"frequency" must be provided') + + # Compute signal length + if length is None: + if duration is None: + raise ParameterError('either "length" or "duration" must be provided') + length = int(duration * sr) + + if phi is None: + phi = -np.pi * 0.5 + + y: np.ndarray = np.cos(2 * np.pi * frequency * np.arange(length) / sr + phi) + return y + + +def chirp( + *, + fmin: _FloatLike_co, + fmax: _FloatLike_co, + sr: float = 22050, + length: Optional[int] = None, + duration: Optional[float] = None, + linear: bool = False, + phi: Optional[float] = None, +) -> np.ndarray: + """Construct a "chirp" or "sine-sweep" signal. + + The chirp sweeps from frequency ``fmin`` to ``fmax`` (in Hz). + + Parameters + ---------- + fmin : float > 0 + initial frequency + + fmax : float > 0 + final frequency + + sr : number > 0 + desired sampling rate of the output signal + + length : int > 0 + desired number of samples in the output signal. + When both ``duration`` and ``length`` are defined, + ``length`` takes priority. + + duration : float > 0 + desired duration in seconds. + When both ``duration`` and ``length`` are defined, + ``length`` takes priority. + + linear : boolean + - If ``True``, use a linear sweep, i.e., frequency changes linearly with time + - If ``False``, use a exponential sweep. + + Default is ``False``. + + phi : float or None + phase offset, in radians. + If unspecified, defaults to ``-np.pi * 0.5``. + + Returns + ------- + chirp_signal : np.ndarray [shape=(length,), dtype=float64] + Synthesized chirp signal + + Raises + ------ + ParameterError + - If either ``fmin`` or ``fmax`` are not provided. + - If neither ``length`` nor ``duration`` are provided. + + See Also + -------- + scipy.signal.chirp + + Examples + -------- + Generate a exponential chirp from A2 to A8 + + >>> exponential_chirp = librosa.chirp(fmin=110, fmax=110*64, duration=1, sr=22050) + + Or generate the same signal using ``length`` + + >>> exponential_chirp = librosa.chirp(fmin=110, fmax=110*64, sr=22050, length=22050) + + Or generate a linear chirp instead + + >>> linear_chirp = librosa.chirp(fmin=110, fmax=110*64, duration=1, linear=True, sr=22050) + + Display spectrogram for both exponential and linear chirps. + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> S_exponential = np.abs(librosa.stft(y=exponential_chirp)) + >>> librosa.display.specshow(librosa.amplitude_to_db(S_exponential, ref=np.max), + ... x_axis='time', y_axis='linear', ax=ax[0]) + >>> ax[0].set(title='Exponential chirp', xlabel=None) + >>> ax[0].label_outer() + >>> S_linear = np.abs(librosa.stft(y=linear_chirp)) + >>> librosa.display.specshow(librosa.amplitude_to_db(S_linear, ref=np.max), + ... x_axis='time', y_axis='linear', ax=ax[1]) + >>> ax[1].set(title='Linear chirp') + """ + if fmin is None or fmax is None: + raise ParameterError('both "fmin" and "fmax" must be provided') + + # Compute signal duration + period = 1.0 / sr + if length is None: + if duration is None: + raise ParameterError('either "length" or "duration" must be provided') + else: + duration = period * length + + if phi is None: + phi = -np.pi * 0.5 + + method = "linear" if linear else "logarithmic" + y: np.ndarray = scipy.signal.chirp( + np.arange(int(duration * sr)) / sr, + fmin, + duration, + fmax, + method=method, + phi=phi / np.pi * 180, # scipy.signal.chirp uses degrees for phase offset + ) + return y + + +def mu_compress( + x: Union[np.ndarray, _FloatLike_co], *, mu: float = 255, quantize: bool = True +) -> np.ndarray: + """mu-law compression + + Given an input signal ``-1 <= x <= 1``, the mu-law compression + is calculated by:: + + sign(x) * ln(1 + mu * abs(x)) / ln(1 + mu) + + Parameters + ---------- + x : np.ndarray with values in [-1, +1] + The input signal to compress + + mu : positive number + The compression parameter. Values of the form ``2**n - 1`` + (e.g., 15, 31, 63, etc.) are most common. + + quantize : bool + If ``True``, quantize the compressed values into ``1 + mu`` + distinct integer values. + + If ``False``, mu-law compression is applied without quantization. + + Returns + ------- + x_compressed : np.ndarray + The compressed signal. + + Raises + ------ + ParameterError + If ``x`` has values outside the range [-1, +1] + If ``mu <= 0`` + + See Also + -------- + mu_expand + + Examples + -------- + Compression without quantization + + >>> x = np.linspace(-1, 1, num=16) + >>> x + array([-1. , -0.86666667, -0.73333333, -0.6 , -0.46666667, + -0.33333333, -0.2 , -0.06666667, 0.06666667, 0.2 , + 0.33333333, 0.46666667, 0.6 , 0.73333333, 0.86666667, + 1. ]) + >>> y = librosa.mu_compress(x, quantize=False) + >>> y + array([-1. , -0.97430198, -0.94432361, -0.90834832, -0.86336132, + -0.80328309, -0.71255496, -0.52124063, 0.52124063, 0.71255496, + 0.80328309, 0.86336132, 0.90834832, 0.94432361, 0.97430198, + 1. ]) + + Compression with quantization + + >>> y = librosa.mu_compress(x, quantize=True) + >>> y + array([-128, -124, -120, -116, -110, -102, -91, -66, 66, 91, 102, + 110, 116, 120, 124, 127]) + + Compression with quantization and a smaller range + + >>> y = librosa.mu_compress(x, mu=15, quantize=True) + >>> y + array([-8, -7, -7, -6, -6, -5, -4, -2, 2, 4, 5, 6, 6, 7, 7, 7]) + """ + if mu <= 0: + raise ParameterError( + f"mu-law compression parameter mu={mu} must be strictly positive." + ) + + if np.any(x < -1) or np.any(x > 1): + raise ParameterError(f"mu-law input x={x} must be in the range [-1, +1].") + + x_comp: np.ndarray = np.sign(x) * np.log1p(mu * np.abs(x)) / np.log1p(mu) + + if quantize: + y: np.ndarray = ( + np.digitize( + x_comp, np.linspace(-1, 1, num=int(1 + mu), endpoint=True), right=True + ) + - int(mu + 1) // 2 + ) + return y + + return x_comp + + +def mu_expand( + x: Union[np.ndarray, _FloatLike_co], *, mu: float = 255.0, quantize: bool = True +) -> np.ndarray: + """mu-law expansion + + This function is the inverse of ``mu_compress``. Given a mu-law compressed + signal ``-1 <= x <= 1``, the mu-law expansion is calculated by:: + + sign(x) * (1 / mu) * ((1 + mu)**abs(x) - 1) + + Parameters + ---------- + x : np.ndarray + The compressed signal. + If ``quantize=True``, values must be in the range [-1, +1]. + mu : positive number + The compression parameter. Values of the form ``2**n - 1`` + (e.g., 15, 31, 63, etc.) are most common. + quantize : boolean + If ``True``, the input is assumed to be quantized to + ``1 + mu`` distinct integer values. + + Returns + ------- + x_expanded : np.ndarray with values in the range [-1, +1] + The mu-law expanded signal. + + Raises + ------ + ParameterError + If ``x`` has values outside the range [-1, +1] and ``quantize=False`` + If ``mu <= 0`` + + See Also + -------- + mu_compress + + Examples + -------- + Compress and expand without quantization + + >>> x = np.linspace(-1, 1, num=16) + >>> x + array([-1. , -0.86666667, -0.73333333, -0.6 , -0.46666667, + -0.33333333, -0.2 , -0.06666667, 0.06666667, 0.2 , + 0.33333333, 0.46666667, 0.6 , 0.73333333, 0.86666667, + 1. ]) + >>> y = librosa.mu_compress(x, quantize=False) + >>> y + array([-1. , -0.97430198, -0.94432361, -0.90834832, -0.86336132, + -0.80328309, -0.71255496, -0.52124063, 0.52124063, 0.71255496, + 0.80328309, 0.86336132, 0.90834832, 0.94432361, 0.97430198, + 1. ]) + >>> z = librosa.mu_expand(y, quantize=False) + >>> z + array([-1. , -0.86666667, -0.73333333, -0.6 , -0.46666667, + -0.33333333, -0.2 , -0.06666667, 0.06666667, 0.2 , + 0.33333333, 0.46666667, 0.6 , 0.73333333, 0.86666667, + 1. ]) + + Compress and expand with quantization. Note that this necessarily + incurs quantization error, particularly for values near +-1. + + >>> y = librosa.mu_compress(x, quantize=True) + >>> y + array([-128, -124, -120, -116, -110, -102, -91, -66, 66, 91, 102, + 110, 116, 120, 124, 127]) + >>> z = librosa.mu_expand(y, quantize=True) + array([-1. , -0.84027248, -0.70595818, -0.59301377, -0.4563785 , + -0.32155973, -0.19817918, -0.06450245, 0.06450245, 0.19817918, + 0.32155973, 0.4563785 , 0.59301377, 0.70595818, 0.84027248, + 0.95743702]) + """ + if mu <= 0: + raise ParameterError( + f"Inverse mu-law compression parameter mu={mu} must be strictly positive." + ) + + if quantize: + x = x * 2.0 / (1 + mu) + + if np.any(x < -1) or np.any(x > 1): + raise ParameterError( + f"Inverse mu-law input x={x} must be in the range [-1, +1]." + ) + + return np.sign(x) / mu * (np.power(1 + mu, np.abs(x)) - 1) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/constantq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/constantq.py new file mode 100644 index 0000000000000000000000000000000000000000..da0f5e15ff0eaa9426f17a02b152a12386974cba --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/constantq.py @@ -0,0 +1,1500 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Constant-Q transforms""" +import warnings +import numpy as np +from numba import jit + +from . import audio +from .intervals import interval_frequencies +from .fft import get_fftlib +from .convert import cqt_frequencies, note_to_hz +from .spectrum import stft, istft +from .pitch import estimate_tuning +from .._cache import cache +from .. import filters +from .. import util +from ..util.exceptions import ParameterError +from numpy.typing import DTypeLike +from typing import Optional, Union, Collection, List +from .._typing import _WindowSpec, _PadMode, _FloatLike_co, _ensure_not_reachable + +__all__ = ["cqt", "hybrid_cqt", "pseudo_cqt", "icqt", "griffinlim_cqt", "vqt"] + +# TODO: ivqt, griffinlim_vqt + + +@cache(level=20) +def cqt( + y: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + n_bins: int = 84, + bins_per_octave: int = 12, + tuning: Optional[float] = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + pad_mode: _PadMode = "constant", + res_type: Optional[str] = "soxr_hq", + dtype: Optional[DTypeLike] = None, +) -> np.ndarray: + """Compute the constant-Q transform of an audio signal. + + This implementation is based on the recursive sub-sampling method + described by [#]_. + + .. [#] Schoerkhuber, Christian, and Anssi Klapuri. + "Constant-Q transform toolbox for music processing." + 7th Sound and Music Computing Conference, Barcelona, Spain. 2010. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + hop_length : int > 0 [scalar] + number of samples between successive CQT columns. + + fmin : float > 0 [scalar] + Minimum frequency. Defaults to `C1 ~= 32.70 Hz` + + n_bins : int > 0 [scalar] + Number of frequency bins, starting at ``fmin`` + + bins_per_octave : int > 0 [scalar] + Number of bins per octave + + tuning : None or float + Tuning offset in fractions of a bin. + + If ``None``, tuning will be automatically estimated from the signal. + + The minimum frequency of the resulting CQT will be modified to + ``fmin * 2**(tuning / bins_per_octave)``. + + filter_scale : float > 0 + Filter scale factor. Small values (<1) use shorter windows + for improved time resolution. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the CQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, number, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the CQT response by square-root the length of + each channel's filter. This is analogous to ``norm='ortho'`` in FFT. + + If ``False``, do not scale the CQT. This is analogous to + ``norm=None`` in FFT. + + pad_mode : string + Padding mode for centered frame analysis. + + See also: `librosa.stft` and `numpy.pad`. + + res_type : string + The resampling mode for recursive downsampling. + + dtype : np.dtype + The (complex) data type of the output array. By default, this is inferred to match + the numerical precision of the input signal. + + Returns + ------- + CQT : np.ndarray [shape=(..., n_bins, t)] + Constant-Q value each frequency at each time. + + See Also + -------- + vqt + librosa.resample + librosa.util.normalize + + Notes + ----- + This function caches at level 20. + + Examples + -------- + Generate and plot a constant-Q power spectrum + + >>> import matplotlib.pyplot as plt + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> C = np.abs(librosa.cqt(y, sr=sr)) + >>> fig, ax = plt.subplots() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max), + ... sr=sr, x_axis='time', y_axis='cqt_note', ax=ax) + >>> ax.set_title('Constant-Q power spectrum') + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + + Limit the frequency range + + >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'), + ... n_bins=60)) + >>> C + array([[6.830e-04, 6.361e-04, ..., 7.362e-09, 9.102e-09], + [5.366e-04, 4.818e-04, ..., 8.953e-09, 1.067e-08], + ..., + [4.288e-02, 4.580e-01, ..., 1.529e-05, 5.572e-06], + [2.965e-03, 1.508e-01, ..., 8.965e-06, 1.455e-05]]) + + Using a higher frequency resolution + + >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'), + ... n_bins=60 * 2, bins_per_octave=12 * 2)) + >>> C + array([[5.468e-04, 5.382e-04, ..., 5.911e-09, 6.105e-09], + [4.118e-04, 4.014e-04, ..., 7.788e-09, 8.160e-09], + ..., + [2.780e-03, 1.424e-01, ..., 4.225e-06, 2.388e-05], + [5.147e-02, 6.959e-02, ..., 1.694e-05, 5.811e-06]]) + """ + # CQT is the special case of VQT with gamma=0 + return vqt( + y=y, + sr=sr, + hop_length=hop_length, + fmin=fmin, + n_bins=n_bins, + intervals="equal", + gamma=0, + bins_per_octave=bins_per_octave, + tuning=tuning, + filter_scale=filter_scale, + norm=norm, + sparsity=sparsity, + window=window, + scale=scale, + pad_mode=pad_mode, + res_type=res_type, + dtype=dtype, + ) + + +@cache(level=20) +def hybrid_cqt( + y: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + n_bins: int = 84, + bins_per_octave: int = 12, + tuning: Optional[float] = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + pad_mode: _PadMode = "constant", + res_type: str = "soxr_hq", + dtype: Optional[DTypeLike] = None, +) -> np.ndarray: + """Compute the hybrid constant-Q transform of an audio signal. + + Here, the hybrid CQT uses the pseudo CQT for higher frequencies where + the hop_length is longer than half the filter length and the full CQT + for lower frequencies. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + hop_length : int > 0 [scalar] + number of samples between successive CQT columns. + + fmin : float > 0 [scalar] + Minimum frequency. Defaults to `C1 ~= 32.70 Hz` + + n_bins : int > 0 [scalar] + Number of frequency bins, starting at ``fmin`` + + bins_per_octave : int > 0 [scalar] + Number of bins per octave + + tuning : None or float + Tuning offset in fractions of a bin. + + If ``None``, tuning will be automatically estimated from the signal. + + The minimum frequency of the resulting CQT will be modified to + ``fmin * 2**(tuning / bins_per_octave)``. + + filter_scale : float > 0 + Filter filter_scale factor. Larger values use longer windows. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the CQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, number, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the CQT response by square-root the length of + each channel's filter. This is analogous to ``norm='ortho'`` in FFT. + + If ``False``, do not scale the CQT. This is analogous to + ``norm=None`` in FFT. + + pad_mode : string + Padding mode for centered frame analysis. + + See also: `librosa.stft` and `numpy.pad`. + + res_type : string + Resampling mode. See `librosa.cqt` for details. + + dtype : np.dtype, optional + The complex dtype to use for computing the CQT. + By default, this is inferred to match the precision of + the input signal. + + Returns + ------- + CQT : np.ndarray [shape=(..., n_bins, t), dtype=np.float] + Constant-Q energy for each frequency at each time. + + See Also + -------- + cqt + pseudo_cqt + + Notes + ----- + This function caches at level 20. + """ + if fmin is None: + # C1 by default + fmin = note_to_hz("C1") + + if tuning is None: + tuning = estimate_tuning(y=y, sr=sr, bins_per_octave=bins_per_octave) + + # Apply tuning correction + fmin = fmin * 2.0 ** (tuning / bins_per_octave) + + # Get all CQT frequencies + freqs = cqt_frequencies(n_bins, fmin=fmin, bins_per_octave=bins_per_octave) + + # Pre-compute alpha + if n_bins == 1: + alpha = __et_relative_bw(bins_per_octave) + else: + alpha = filters._relative_bandwidth(freqs=freqs) + + # Compute the length of each constant-Q basis function + lengths, _ = filters.wavelet_lengths( + freqs=freqs, sr=sr, filter_scale=filter_scale, window=window, alpha=alpha + ) + + # Determine which filters to use with Pseudo CQT + # These are the ones that fit within 2 hop lengths after padding + pseudo_filters = 2.0 ** np.ceil(np.log2(lengths)) < 2 * hop_length + + n_bins_pseudo = int(np.sum(pseudo_filters)) + + n_bins_full = n_bins - n_bins_pseudo + cqt_resp = [] + + if n_bins_pseudo > 0: + fmin_pseudo = np.min(freqs[pseudo_filters]) + + cqt_resp.append( + pseudo_cqt( + y, + sr=sr, + hop_length=hop_length, + fmin=fmin_pseudo, + n_bins=n_bins_pseudo, + bins_per_octave=bins_per_octave, + filter_scale=filter_scale, + norm=norm, + sparsity=sparsity, + window=window, + scale=scale, + pad_mode=pad_mode, + dtype=dtype, + ) + ) + + if n_bins_full > 0: + cqt_resp.append( + np.abs( + cqt( + y, + sr=sr, + hop_length=hop_length, + fmin=fmin, + n_bins=n_bins_full, + bins_per_octave=bins_per_octave, + filter_scale=filter_scale, + norm=norm, + sparsity=sparsity, + window=window, + scale=scale, + pad_mode=pad_mode, + res_type=res_type, + dtype=dtype, + ) + ) + ) + + # Propagate dtype from the last component + return __trim_stack(cqt_resp, n_bins, cqt_resp[-1].dtype) + + +@cache(level=20) +def pseudo_cqt( + y: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + n_bins: int = 84, + bins_per_octave: int = 12, + tuning: Optional[float] = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + pad_mode: _PadMode = "constant", + dtype: Optional[DTypeLike] = None, +) -> np.ndarray: + """Compute the pseudo constant-Q transform of an audio signal. + + This uses a single fft size that is the smallest power of 2 that is greater + than or equal to the max of: + + 1. The longest CQT filter + 2. 2x the hop_length + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + hop_length : int > 0 [scalar] + number of samples between successive CQT columns. + + fmin : float > 0 [scalar] + Minimum frequency. Defaults to `C1 ~= 32.70 Hz` + + n_bins : int > 0 [scalar] + Number of frequency bins, starting at ``fmin`` + + bins_per_octave : int > 0 [scalar] + Number of bins per octave + + tuning : None or float + Tuning offset in fractions of a bin. + + If ``None``, tuning will be automatically estimated from the signal. + + The minimum frequency of the resulting CQT will be modified to + ``fmin * 2**(tuning / bins_per_octave)``. + + filter_scale : float > 0 + Filter filter_scale factor. Larger values use longer windows. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the CQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, number, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the CQT response by square-root the length of + each channel's filter. This is analogous to ``norm='ortho'`` in FFT. + + If ``False``, do not scale the CQT. This is analogous to + ``norm=None`` in FFT. + + pad_mode : string + Padding mode for centered frame analysis. + + See also: `librosa.stft` and `numpy.pad`. + + dtype : np.dtype, optional + The complex data type for CQT calculations. + By default, this is inferred to match the precision of the input signal. + + Returns + ------- + CQT : np.ndarray [shape=(..., n_bins, t), dtype=np.float] + Pseudo Constant-Q energy for each frequency at each time. + + Notes + ----- + This function caches at level 20. + """ + if fmin is None: + # C1 by default + fmin = note_to_hz("C1") + + if tuning is None: + tuning = estimate_tuning(y=y, sr=sr, bins_per_octave=bins_per_octave) + + if dtype is None: + dtype = util.dtype_r2c(y.dtype) + + # Apply tuning correction + fmin = fmin * 2.0 ** (tuning / bins_per_octave) + + freqs = cqt_frequencies(fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave) + + if n_bins == 1: + alpha = __et_relative_bw(bins_per_octave) + else: + alpha = filters._relative_bandwidth(freqs=freqs) + + lengths, _ = filters.wavelet_lengths( + freqs=freqs, sr=sr, window=window, filter_scale=filter_scale, alpha=alpha + ) + + fft_basis, n_fft, _ = __vqt_filter_fft( + sr, + freqs, + filter_scale, + norm, + sparsity, + hop_length=hop_length, + window=window, + dtype=dtype, + alpha=alpha, + ) + + fft_basis = np.abs(fft_basis) + + # Compute the magnitude-only CQT response + C: np.ndarray = __cqt_response( + y, + n_fft, + hop_length, + fft_basis, + pad_mode, + window="hann", + dtype=dtype, + phase=False, + ) + + if scale: + C /= np.sqrt(n_fft) + else: + # reshape lengths to match dimension properly + lengths = util.expand_to(lengths, ndim=C.ndim, axes=-2) + + C *= np.sqrt(lengths / n_fft) + + return C + + +@cache(level=40) +def icqt( + C: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + bins_per_octave: int = 12, + tuning: float = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + length: Optional[int] = None, + res_type: str = "soxr_hq", + dtype: Optional[DTypeLike] = None, +) -> np.ndarray: + """Compute the inverse constant-Q transform. + + Given a constant-Q transform representation ``C`` of an audio signal ``y``, + this function produces an approximation ``y_hat``. + + Parameters + ---------- + C : np.ndarray, [shape=(..., n_bins, n_frames)] + Constant-Q representation as produced by `cqt` + + sr : number > 0 [scalar] + sampling rate of the signal + + hop_length : int > 0 [scalar] + number of samples between successive frames + + fmin : float > 0 [scalar] + Minimum frequency. Defaults to `C1 ~= 32.70 Hz` + + bins_per_octave : int > 0 [scalar] + Number of bins per octave + + tuning : float [scalar] + Tuning offset in fractions of a bin. + + The minimum frequency of the CQT will be modified to + ``fmin * 2**(tuning / bins_per_octave)``. + + filter_scale : float > 0 [scalar] + Filter scale factor. Small values (<1) use shorter windows + for improved time resolution. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the CQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, number, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the CQT response by square-root the length + of each channel's filter. This is analogous to ``norm='ortho'`` in FFT. + + If ``False``, do not scale the CQT. This is analogous to ``norm=None`` + in FFT. + + length : int > 0, optional + If provided, the output ``y`` is zero-padded or clipped to exactly + ``length`` samples. + + res_type : string + Resampling mode. + See `librosa.resample` for supported modes. + + dtype : numeric type + Real numeric type for ``y``. Default is inferred to match the numerical + precision of the input CQT. + + Returns + ------- + y : np.ndarray, [shape=(..., n_samples), dtype=np.float] + Audio time-series reconstructed from the CQT representation. + + See Also + -------- + cqt + librosa.resample + + Notes + ----- + This function caches at level 40. + + Examples + -------- + Using default parameters + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> C = librosa.cqt(y=y, sr=sr) + >>> y_hat = librosa.icqt(C=C, sr=sr) + + Or with a different hop length and frequency resolution: + + >>> hop_length = 256 + >>> bins_per_octave = 12 * 3 + >>> C = librosa.cqt(y=y, sr=sr, hop_length=256, n_bins=7*bins_per_octave, + ... bins_per_octave=bins_per_octave) + >>> y_hat = librosa.icqt(C=C, sr=sr, hop_length=hop_length, + ... bins_per_octave=bins_per_octave) + """ + if fmin is None: + fmin = note_to_hz("C1") + + # Apply tuning correction + fmin = fmin * 2.0 ** (tuning / bins_per_octave) + + # Get the top octave of frequencies + n_bins = C.shape[-2] + + n_octaves = int(np.ceil(float(n_bins) / bins_per_octave)) + + freqs = cqt_frequencies(fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave) + if n_bins == 1: + alpha = __et_relative_bw(bins_per_octave) + else: + alpha = filters._relative_bandwidth(freqs=freqs) + + lengths, f_cutoff = filters.wavelet_lengths( + freqs=freqs, sr=sr, window=window, filter_scale=filter_scale, alpha=alpha + ) + + # Trim the CQT to only what's necessary for reconstruction + if length is not None: + n_frames = int(np.ceil((length + max(lengths)) / hop_length)) + C = C[..., :n_frames] + + C_scale = np.sqrt(lengths) + + # This shape array will be used for broadcasting the basis scale + # we'll have to adapt this per octave within the loop + y: Optional[np.ndarray] = None + + # Assume the top octave is at the full rate + srs = [sr] + hops = [hop_length] + + for i in range(n_octaves - 1): + if hops[0] % 2 == 0: + # We can downsample: + srs.insert(0, srs[0] * 0.5) + hops.insert(0, hops[0] // 2) + else: + # We're out of downsamplings, carry forward + srs.insert(0, srs[0]) + hops.insert(0, hops[0]) + + for i, (my_sr, my_hop) in enumerate(zip(srs, hops)): + # How many filters are in this octave? + n_filters = min(bins_per_octave, n_bins - bins_per_octave * i) + + # Slice out the current octave + sl = slice(bins_per_octave * i, bins_per_octave * i + n_filters) + + fft_basis, n_fft, _ = __vqt_filter_fft( + my_sr, + freqs[sl], + filter_scale, + norm, + sparsity, + window=window, + alpha=alpha[sl], + ) + + # Transpose the basis + inv_basis = fft_basis.conjugate().T.todense() + + # Compute each filter's frequency-domain power + freq_power = 1 / np.sum(util.abs2(np.asarray(inv_basis)), axis=0) + + # Compensate for length normalization in the forward transform + freq_power *= n_fft / lengths[sl] + + # Inverse-project the basis for each octave + if scale: + # scale=True ==> re-scale by sqrt(lengths) + D_oct = np.einsum( + "fc,c,c,...ct->...ft", + inv_basis, + C_scale[sl], + freq_power, + C[..., sl, :], + optimize=True, + ) + else: + D_oct = np.einsum( + "fc,c,...ct->...ft", inv_basis, freq_power, C[..., sl, :], optimize=True + ) + + y_oct = istft(D_oct, window="ones", hop_length=my_hop, dtype=dtype) + + y_oct = audio.resample( + y_oct, + orig_sr=1, + target_sr=sr // my_sr, + res_type=res_type, + scale=False, + fix=False, + ) + + if y is None: + y = y_oct + else: + y[..., : y_oct.shape[-1]] += y_oct + # make mypy happy + assert y is not None + + if length: + y = util.fix_length(y, size=length) + + return y + + +@cache(level=20) +def vqt( + y: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + n_bins: int = 84, + intervals: Union[str, Collection[float]] = "equal", + gamma: Optional[float] = None, + bins_per_octave: int = 12, + tuning: Optional[float] = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + pad_mode: _PadMode = "constant", + res_type: Optional[str] = "soxr_hq", + dtype: Optional[DTypeLike] = None, +) -> np.ndarray: + """Compute the variable-Q transform of an audio signal. + + This implementation is based on the recursive sub-sampling method + described by [#]_. + + .. [#] Schörkhuber, Christian, Anssi Klapuri, Nicki Holighaus, and Monika Dörfler. + "A Matlab toolbox for efficient perfect reconstruction time-frequency + transforms with log-frequency resolution." + In Audio Engineering Society Conference: 53rd International Conference: Semantic Audio. + Audio Engineering Society, 2014. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + hop_length : int > 0 [scalar] + number of samples between successive VQT columns. + + fmin : float > 0 [scalar] + Minimum frequency. Defaults to `C1 ~= 32.70 Hz` + + n_bins : int > 0 [scalar] + Number of frequency bins, starting at ``fmin`` + + intervals : str or array of floats in [1, 2) + Either a string specification for an interval set, e.g., + `'equal'`, `'pythagorean'`, `'ji3'`, etc. or an array of + intervals expressed as numbers between 1 and 2. + .. see also:: librosa.interval_frequencies + + gamma : number > 0 [scalar] + Bandwidth offset for determining filter lengths. + + If ``gamma=0``, produces the constant-Q transform. + + If 'gamma=None', gamma will be calculated such that filter bandwidths are equal to a + constant fraction of the equivalent rectangular bandwidths (ERB). This is accomplished + by solving for the gamma which gives:: + + B_k = alpha * f_k + gamma = C * ERB(f_k), + + where ``B_k`` is the bandwidth of filter ``k`` with center frequency ``f_k``, alpha + is the inverse of what would be the constant Q-factor, and ``C = alpha / 0.108`` is the + constant fraction across all filters. + + Here we use ``ERB(f_k) = 24.7 + 0.108 * f_k``, the best-fit curve derived + from experimental data in [#]_. + + .. [#] Glasberg, Brian R., and Brian CJ Moore. + "Derivation of auditory filter shapes from notched-noise data." + Hearing research 47.1-2 (1990): 103-138. + + bins_per_octave : int > 0 [scalar] + Number of bins per octave + + tuning : None or float + Tuning offset in fractions of a bin. + + If ``None``, tuning will be automatically estimated from the signal. + + The minimum frequency of the resulting VQT will be modified to + ``fmin * 2**(tuning / bins_per_octave)``. + + filter_scale : float > 0 + Filter scale factor. Small values (<1) use shorter windows + for improved time resolution. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the VQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, number, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the VQT response by square-root the length of + each channel's filter. This is analogous to ``norm='ortho'`` in FFT. + + If ``False``, do not scale the VQT. This is analogous to + ``norm=None`` in FFT. + + pad_mode : string + Padding mode for centered frame analysis. + + See also: `librosa.stft` and `numpy.pad`. + + res_type : string + The resampling mode for recursive downsampling. + + dtype : np.dtype + The dtype of the output array. By default, this is inferred to match the + numerical precision of the input signal. + + Returns + ------- + VQT : np.ndarray [shape=(..., n_bins, t), dtype=np.complex] + Variable-Q value each frequency at each time. + + See Also + -------- + cqt + + Notes + ----- + This function caches at level 20. + + Examples + -------- + Generate and plot a variable-Q power spectrum + + >>> import matplotlib.pyplot as plt + >>> y, sr = librosa.load(librosa.ex('choice'), duration=5) + >>> C = np.abs(librosa.cqt(y, sr=sr)) + >>> V = np.abs(librosa.vqt(y, sr=sr)) + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max), + ... sr=sr, x_axis='time', y_axis='cqt_note', ax=ax[0]) + >>> ax[0].set(title='Constant-Q power spectrum', xlabel=None) + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(V, ref=np.max), + ... sr=sr, x_axis='time', y_axis='cqt_note', ax=ax[1]) + >>> ax[1].set_title('Variable-Q power spectrum') + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + """ + # If intervals are provided as an array, override BPO + if not isinstance(intervals, str): + bins_per_octave = len(intervals) + + # How many octaves are we dealing with? + n_octaves = int(np.ceil(float(n_bins) / bins_per_octave)) + n_filters = min(bins_per_octave, n_bins) + + if fmin is None: + # C1 by default + fmin = note_to_hz("C1") + + if tuning is None: + tuning = estimate_tuning(y=y, sr=sr, bins_per_octave=bins_per_octave) + + if dtype is None: + dtype = util.dtype_r2c(y.dtype) + + # Apply tuning correction + fmin = fmin * 2.0 ** (tuning / bins_per_octave) + + # First thing, get the freqs of the top octave + freqs = interval_frequencies( + n_bins=n_bins, + fmin=fmin, + intervals=intervals, + bins_per_octave=bins_per_octave, + sort=True, + ) + + freqs_top = freqs[-bins_per_octave:] + + fmax_t: float = np.max(freqs_top) + if n_bins == 1: + alpha = __et_relative_bw(bins_per_octave) + else: + alpha = filters._relative_bandwidth(freqs=freqs) + + lengths, filter_cutoff = filters.wavelet_lengths( + freqs=freqs, + sr=sr, + window=window, + filter_scale=filter_scale, + gamma=gamma, + alpha=alpha, + ) + + # Determine required resampling quality + nyquist = sr / 2.0 + + if filter_cutoff > nyquist: + raise ParameterError( + f"Wavelet basis with max frequency={fmax_t} would exceed the Nyquist frequency={nyquist}. " + "Try reducing the number of frequency bins." + ) + + if res_type is None: + warnings.warn( + "Support for VQT with res_type=None is deprecated in librosa 0.10\n" + "and will be removed in version 1.0.", + category=FutureWarning, + stacklevel=2, + ) + res_type = "soxr_hq" + + y, sr, hop_length = __early_downsample( + y, sr, hop_length, res_type, n_octaves, nyquist, filter_cutoff, scale + ) + + vqt_resp = [] + + # Iterate down the octaves + my_y, my_sr, my_hop = y, sr, hop_length + + for i in range(n_octaves): + # Slice out the current octave of filters + if i == 0: + sl = slice(-n_filters, None) + else: + sl = slice(-n_filters * (i + 1), -n_filters * i) + + # This may be incorrect with early downsampling + freqs_oct = freqs[sl] + alpha_oct = alpha[sl] + + fft_basis, n_fft, _ = __vqt_filter_fft( + my_sr, + freqs_oct, + filter_scale, + norm, + sparsity, + window=window, + gamma=gamma, + dtype=dtype, + alpha=alpha_oct, + ) + + # Re-scale the filters to compensate for downsampling + fft_basis[:] *= np.sqrt(sr / my_sr) + + # Compute the vqt filter response and append to the stack + vqt_resp.append( + __cqt_response(my_y, n_fft, my_hop, fft_basis, pad_mode, dtype=dtype) + ) + + if my_hop % 2 == 0: + my_hop //= 2 + my_sr /= 2.0 + my_y = audio.resample( + my_y, orig_sr=2, target_sr=1, res_type=res_type, scale=True + ) + + V = __trim_stack(vqt_resp, n_bins, dtype) + + if scale: + # Recompute lengths here because early downsampling may have changed + # our sampling rate + lengths, _ = filters.wavelet_lengths( + freqs=freqs, + sr=sr, + window=window, + filter_scale=filter_scale, + gamma=gamma, + alpha=alpha, + ) + + # reshape lengths to match V shape + lengths = util.expand_to(lengths, ndim=V.ndim, axes=-2) + V /= np.sqrt(lengths) + + return V + + +@cache(level=10) +def __vqt_filter_fft( + sr, + freqs, + filter_scale, + norm, + sparsity, + hop_length=None, + window="hann", + gamma=0.0, + dtype=np.complex64, + alpha=None, +): + """Generate the frequency domain variable-Q filter basis.""" + basis, lengths = filters.wavelet( + freqs=freqs, + sr=sr, + filter_scale=filter_scale, + norm=norm, + pad_fft=True, + window=window, + gamma=gamma, + alpha=alpha, + ) + + # Filters are padded up to the nearest integral power of 2 + n_fft = basis.shape[1] + + if hop_length is not None and n_fft < 2.0 ** (1 + np.ceil(np.log2(hop_length))): + n_fft = int(2.0 ** (1 + np.ceil(np.log2(hop_length)))) + + # re-normalize bases with respect to the FFT window length + basis *= lengths[:, np.newaxis] / float(n_fft) + + # FFT and retain only the non-negative frequencies + fft = get_fftlib() + fft_basis = fft.fft(basis, n=n_fft, axis=1)[:, : (n_fft // 2) + 1] + + # sparsify the basis + fft_basis = util.sparsify_rows(fft_basis, quantile=sparsity, dtype=dtype) + + return fft_basis, n_fft, lengths + + +def __trim_stack( + cqt_resp: List[np.ndarray], n_bins: int, dtype: DTypeLike +) -> np.ndarray: + """Trim and stack a collection of CQT responses""" + max_col = min(c_i.shape[-1] for c_i in cqt_resp) + # Grab any leading dimensions + shape = list(cqt_resp[0].shape) + shape[-2] = n_bins + shape[-1] = max_col + cqt_out = np.empty(shape, dtype=dtype, order="F") + + # Copy per-octave data into output array + end = n_bins + for c_i in cqt_resp: + # By default, take the whole octave + n_oct = c_i.shape[-2] + # If the whole octave is more than we can fit, + # take the highest bins from c_i + if end < n_oct: + cqt_out[..., :end, :] = c_i[..., -end:, :max_col] + else: + cqt_out[..., end - n_oct : end, :] = c_i[..., :max_col] + + end -= n_oct + + return cqt_out + + +def __cqt_response( + y, n_fft, hop_length, fft_basis, mode, window="ones", phase=True, dtype=None +): + """Compute the filter response with a target STFT hop.""" + # Compute the STFT matrix + D = stft( + y, n_fft=n_fft, hop_length=hop_length, window=window, pad_mode=mode, dtype=dtype + ) + + if not phase: + D = np.abs(D) + + # Reshape D to Dr + Dr = D.reshape((-1, D.shape[-2], D.shape[-1])) + output_flat = np.empty( + (Dr.shape[0], fft_basis.shape[0], Dr.shape[-1]), dtype=D.dtype + ) + + # iterate over channels + # project fft_basis.dot(Dr[i]) + for i in range(Dr.shape[0]): + output_flat[i] = fft_basis.dot(Dr[i]) + + # reshape Dr to match D's leading dimensions again + shape = list(D.shape) + shape[-2] = fft_basis.shape[0] + return output_flat.reshape(shape) + + +def __early_downsample_count(nyquist, filter_cutoff, hop_length, n_octaves): + """Compute the number of early downsampling operations""" + downsample_count1 = max(0, int(np.ceil(np.log2(nyquist / filter_cutoff)) - 1) - 1) + + num_twos = __num_two_factors(hop_length) + downsample_count2 = max(0, num_twos - n_octaves + 1) + + return min(downsample_count1, downsample_count2) + + +def __early_downsample( + y, sr, hop_length, res_type, n_octaves, nyquist, filter_cutoff, scale +): + """Perform early downsampling on an audio signal, if it applies.""" + downsample_count = __early_downsample_count( + nyquist, filter_cutoff, hop_length, n_octaves + ) + + if downsample_count > 0: + downsample_factor = 2 ** (downsample_count) + + hop_length //= downsample_factor + + if y.shape[-1] < downsample_factor: + raise ParameterError( + f"Input signal length={len(y):d} is too short for " + f"{n_octaves:d}-octave CQT" + ) + + new_sr = sr / float(downsample_factor) + y = audio.resample( + y, orig_sr=downsample_factor, target_sr=1, res_type=res_type, scale=True + ) + + # If we're not going to length-scale after CQT, we + # need to compensate for the downsampling factor here + if not scale: + y *= np.sqrt(downsample_factor) + + sr = new_sr + + return y, sr, hop_length + + +@jit(nopython=True, cache=True) +def __num_two_factors(x): + """Return how many times integer x can be evenly divided by 2. + + Returns 0 for non-positive integers. + """ + if x <= 0: + return 0 + num_twos = 0 + while x % 2 == 0: + num_twos += 1 + x //= 2 + + return num_twos + + +def griffinlim_cqt( + C: np.ndarray, + *, + n_iter: int = 32, + sr: float = 22050, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + bins_per_octave: int = 12, + tuning: float = 0.0, + filter_scale: float = 1, + norm: Optional[float] = 1, + sparsity: float = 0.01, + window: _WindowSpec = "hann", + scale: bool = True, + pad_mode: _PadMode = "constant", + res_type: str = "soxr_hq", + dtype: Optional[DTypeLike] = None, + length: Optional[int] = None, + momentum: float = 0.99, + init: Optional[str] = "random", + random_state: Optional[ + Union[int, np.random.RandomState, np.random.Generator] + ] = None, +) -> np.ndarray: + """Approximate constant-Q magnitude spectrogram inversion using the "fast" Griffin-Lim + algorithm. + + Given the magnitude of a constant-Q spectrogram (``C``), the algorithm randomly initializes + phase estimates, and then alternates forward- and inverse-CQT operations. [#]_ + + This implementation is based on the (fast) Griffin-Lim method for Short-time Fourier Transforms, [#]_ + but adapted for use with constant-Q spectrograms. + + .. [#] D. W. Griffin and J. S. Lim, + "Signal estimation from modified short-time Fourier transform," + IEEE Trans. ASSP, vol.32, no.2, pp.236–243, Apr. 1984. + + .. [#] Perraudin, N., Balazs, P., & SĂžndergaard, P. L. + "A fast Griffin-Lim algorithm," + IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (pp. 1-4), + Oct. 2013. + + Parameters + ---------- + C : np.ndarray [shape=(..., n_bins, n_frames)] + The constant-Q magnitude spectrogram + + n_iter : int > 0 + The number of iterations to run + + sr : number > 0 + Audio sampling rate + + hop_length : int > 0 + The hop length of the CQT + + fmin : number > 0 + Minimum frequency for the CQT. + + If not provided, it defaults to `C1`. + + bins_per_octave : int > 0 + Number of bins per octave + + tuning : float + Tuning deviation from A440, in fractions of a bin + + filter_scale : float > 0 + Filter scale factor. Small values (<1) use shorter windows + for improved time resolution. + + norm : {inf, -inf, 0, float > 0} + Type of norm to use for basis function normalization. + See `librosa.util.normalize`. + + sparsity : float in [0, 1) + Sparsify the CQT basis by discarding up to ``sparsity`` + fraction of the energy in each basis. + + Set ``sparsity=0`` to disable sparsification. + + window : str, tuple, or function + Window specification for the basis filters. + See `filters.get_window` for details. + + scale : bool + If ``True``, scale the CQT response by square-root the length + of each channel's filter. This is analogous to ``norm='ortho'`` + in FFT. + + If ``False``, do not scale the CQT. This is analogous to ``norm=None`` + in FFT. + + pad_mode : string + Padding mode for centered frame analysis. + + See also: `librosa.stft` and `numpy.pad`. + + res_type : string + The resampling mode for recursive downsampling. + + See ``librosa.resample`` for a list of available options. + + dtype : numeric type + Real numeric type for ``y``. Default is inferred to match the precision + of the input CQT. + + length : int > 0, optional + If provided, the output ``y`` is zero-padded or clipped to exactly + ``length`` samples. + + momentum : float > 0 + The momentum parameter for fast Griffin-Lim. + Setting this to 0 recovers the original Griffin-Lim method. + Values near 1 can lead to faster convergence, but above 1 may not converge. + + init : None or 'random' [default] + If 'random' (the default), then phase values are initialized randomly + according to ``random_state``. This is recommended when the input ``C`` is + a magnitude spectrogram with no initial phase estimates. + + If ``None``, then the phase is initialized from ``C``. This is useful when + an initial guess for phase can be provided, or when you want to resume + Griffin-Lim from a previous output. + + random_state : None, int, np.random.RandomState, or np.random.Generator + If int, random_state is the seed used by the random number generator + for phase initialization. + + If `np.random.RandomState` or `np.random.Generator` instance, the random number generator itself. + + If ``None``, defaults to the `np.random.default_rng()` object. + + Returns + ------- + y : np.ndarray [shape=(..., n)] + time-domain signal reconstructed from ``C`` + + See Also + -------- + cqt + icqt + griffinlim + filters.get_window + resample + + Examples + -------- + A basis CQT inverse example + + >>> y, sr = librosa.load(librosa.ex('trumpet', hq=True), sr=None) + >>> # Get the CQT magnitude, 7 octaves at 36 bins per octave + >>> C = np.abs(librosa.cqt(y=y, sr=sr, bins_per_octave=36, n_bins=7*36)) + >>> # Invert using Griffin-Lim + >>> y_inv = librosa.griffinlim_cqt(C, sr=sr, bins_per_octave=36) + >>> # And invert without estimating phase + >>> y_icqt = librosa.icqt(C, sr=sr, bins_per_octave=36) + + Wave-plot the results + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> librosa.display.waveshow(y, sr=sr, color='b', ax=ax[0]) + >>> ax[0].set(title='Original', xlabel=None) + >>> ax[0].label_outer() + >>> librosa.display.waveshow(y_inv, sr=sr, color='g', ax=ax[1]) + >>> ax[1].set(title='Griffin-Lim reconstruction', xlabel=None) + >>> ax[1].label_outer() + >>> librosa.display.waveshow(y_icqt, sr=sr, color='r', ax=ax[2]) + >>> ax[2].set(title='Magnitude-only icqt reconstruction') + """ + if fmin is None: + fmin = note_to_hz("C1") + + if random_state is None: + rng = np.random.default_rng() + elif isinstance(random_state, int): + rng = np.random.RandomState(seed=random_state) # type: ignore + elif isinstance(random_state, (np.random.RandomState, np.random.Generator)): + rng = random_state # type: ignore + else: + _ensure_not_reachable(random_state) + raise ParameterError(f"Unsupported random_state={random_state!r}") + + if momentum > 1: + warnings.warn( + f"Griffin-Lim with momentum={momentum} > 1 can be unstable. " + "Proceed with caution!", + stacklevel=2, + ) + elif momentum < 0: + raise ParameterError(f"griffinlim_cqt() called with momentum={momentum} < 0") + + # using complex64 will keep the result to minimal necessary precision + angles = np.empty(C.shape, dtype=np.complex64) + eps = util.tiny(angles) + + if init == "random": + # randomly initialize the phase + angles[:] = util.phasor(2 * np.pi * rng.random(size=C.shape)) + elif init is None: + # Initialize an all ones complex matrix + angles[:] = 1.0 + else: + raise ParameterError(f"init={init} must either None or 'random'") + + # And initialize the previous iterate to 0 + rebuilt: np.ndarray = np.array(0.0) + + for _ in range(n_iter): + # Store the previous iterate + tprev = rebuilt + + # Invert with our current estimate of the phases + inverse = icqt( + C * angles, + sr=sr, + hop_length=hop_length, + bins_per_octave=bins_per_octave, + fmin=fmin, + tuning=tuning, + filter_scale=filter_scale, + window=window, + length=length, + res_type=res_type, + norm=norm, + scale=scale, + sparsity=sparsity, + dtype=dtype, + ) + + # Rebuild the spectrogram + rebuilt = cqt( + inverse, + sr=sr, + bins_per_octave=bins_per_octave, + n_bins=C.shape[-2], + hop_length=hop_length, + fmin=fmin, + tuning=tuning, + filter_scale=filter_scale, + window=window, + norm=norm, + scale=scale, + sparsity=sparsity, + pad_mode=pad_mode, + res_type=res_type, + ) + + # Update our phase estimates + angles[:] = rebuilt - (momentum / (1 + momentum)) * tprev + angles[:] /= np.abs(angles) + eps + + # Return the final phase estimates + return icqt( + C * angles, + sr=sr, + hop_length=hop_length, + bins_per_octave=bins_per_octave, + tuning=tuning, + filter_scale=filter_scale, + fmin=fmin, + window=window, + length=length, + res_type=res_type, + norm=norm, + scale=scale, + sparsity=sparsity, + dtype=dtype, + ) + + +def __et_relative_bw(bins_per_octave: int) -> np.ndarray: + """Compute the relative bandwidth coefficient for equal + (geometric) freuqency spacing and a give number of bins + per octave. + + This is a special case of the more general `relative_bandwidth` + calculation that can be used when only a single basis frequency + is used. + + Parameters + ---------- + bins_per_octave : int + + Returns + ------- + alpha : np.ndarray > 0 + Value is cast up to a 1d array to allow slicing + """ + r = 2 ** (1 / bins_per_octave) + return np.atleast_1d((r**2 - 1) / (r**2 + 1)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/convert.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf7c5e1099d335990342c66e98174312772401c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/convert.py @@ -0,0 +1,3176 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Unit conversion utilities""" +from __future__ import annotations +import numpy as np +from . import notation +from ..util.exceptions import ParameterError +from ..util.decorators import vectorize +from typing import Any, Callable, Dict, Iterable, Optional, Sized, Union, overload +from .._typing import ( + _IterableLike, + _FloatLike_co, + _SequenceLike, + _ScalarOrSequence, + _IntLike_co, +) + +__all__ = [ + "frames_to_samples", + "frames_to_time", + "samples_to_frames", + "samples_to_time", + "time_to_samples", + "time_to_frames", + "blocks_to_samples", + "blocks_to_frames", + "blocks_to_time", + "note_to_hz", + "note_to_midi", + "midi_to_hz", + "midi_to_note", + "hz_to_note", + "hz_to_midi", + "hz_to_mel", + "hz_to_octs", + "hz_to_fjs", + "mel_to_hz", + "octs_to_hz", + "A4_to_tuning", + "tuning_to_A4", + "fft_frequencies", + "cqt_frequencies", + "mel_frequencies", + "tempo_frequencies", + "fourier_tempo_frequencies", + "A_weighting", + "B_weighting", + "C_weighting", + "D_weighting", + "Z_weighting", + "frequency_weighting", + "multi_frequency_weighting", + "samples_like", + "times_like", + "midi_to_svara_h", + "midi_to_svara_c", + "note_to_svara_h", + "note_to_svara_c", + "hz_to_svara_h", + "hz_to_svara_c", +] + + +@overload +def frames_to_samples( + frames: _IntLike_co, *, hop_length: int = 512, n_fft: Optional[int] = None +) -> np.integer[Any]: + ... + + +@overload +def frames_to_samples( + frames: _SequenceLike[_IntLike_co], + *, + hop_length: int = 512, + n_fft: Optional[int] = None, +) -> np.ndarray: + ... + + +def frames_to_samples( + frames: _ScalarOrSequence[_IntLike_co], + *, + hop_length: int = 512, + n_fft: Optional[int] = None, +) -> Union[np.integer[Any], np.ndarray]: + """Convert frame indices to audio sample indices. + + Parameters + ---------- + frames : number or np.ndarray [shape=(n,)] + frame index or vector of frame indices + hop_length : int > 0 [scalar] + number of samples between successive frames + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``n_fft // 2`` + to counteract windowing effects when using a non-centered STFT. + + Returns + ------- + times : number or np.ndarray + time (in samples) of each given frame number:: + + times[i] = frames[i] * hop_length + + See Also + -------- + frames_to_time : convert frame indices to time values + samples_to_frames : convert sample indices to frame indices + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('choice')) + >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr) + >>> beat_samples = librosa.frames_to_samples(beats, sr=sr) + """ + offset = 0 + if n_fft is not None: + offset = int(n_fft // 2) + + return (np.asanyarray(frames) * hop_length + offset).astype(int) + + +@overload +def samples_to_frames( + samples: _IntLike_co, *, hop_length: int = ..., n_fft: Optional[int] = ... +) -> np.integer[Any]: + ... + + +@overload +def samples_to_frames( + samples: _SequenceLike[_IntLike_co], + *, + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> np.ndarray: + ... + + +@overload +def samples_to_frames( + samples: _ScalarOrSequence[_IntLike_co], + *, + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> Union[np.integer[Any], np.ndarray]: + ... + + +def samples_to_frames( + samples: _ScalarOrSequence[_IntLike_co], + *, + hop_length: int = 512, + n_fft: Optional[int] = None, +) -> Union[np.integer[Any], np.ndarray]: + """Convert sample indices into STFT frames. + + Examples + -------- + >>> # Get the frame numbers for every 256 samples + >>> librosa.samples_to_frames(np.arange(0, 22050, 256)) + array([ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, + 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, + 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, + 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, + 42, 42, 43]) + + Parameters + ---------- + samples : int or np.ndarray [shape=(n,)] + sample index or vector of sample indices + + hop_length : int > 0 [scalar] + number of samples between successive frames + + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``- n_fft // 2`` + to counteract windowing effects in STFT. + + .. note:: This may result in negative frame indices. + + Returns + ------- + frames : int or np.ndarray [shape=(n,), dtype=int] + Frame numbers corresponding to the given times:: + + frames[i] = floor( samples[i] / hop_length ) + + See Also + -------- + samples_to_time : convert sample indices to time values + frames_to_samples : convert frame indices to sample indices + """ + offset = 0 + if n_fft is not None: + offset = int(n_fft // 2) + + samples = np.asanyarray(samples) + return np.asarray(np.floor((samples - offset) // hop_length), dtype=int) + + +@overload +def frames_to_time( + frames: _IntLike_co, + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> np.floating[Any]: + ... + + +@overload +def frames_to_time( + frames: _SequenceLike[_IntLike_co], + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> np.ndarray: + ... + + +@overload +def frames_to_time( + frames: _ScalarOrSequence[_IntLike_co], + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def frames_to_time( + frames: _ScalarOrSequence[_IntLike_co], + *, + sr: float = 22050, + hop_length: int = 512, + n_fft: Optional[int] = None, +) -> Union[np.floating[Any], np.ndarray]: + """Convert frame counts to time (seconds). + + Parameters + ---------- + frames : np.ndarray [shape=(n,)] + frame index or vector of frame indices + sr : number > 0 [scalar] + audio sampling rate + hop_length : int > 0 [scalar] + number of samples between successive frames + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``n_fft // 2`` + to counteract windowing effects when using a non-centered STFT. + + Returns + ------- + times : np.ndarray [shape=(n,)] + time (in seconds) of each given frame number:: + + times[i] = frames[i] * hop_length / sr + + See Also + -------- + time_to_frames : convert time values to frame indices + frames_to_samples : convert frame indices to sample indices + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('choice')) + >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr) + >>> beat_times = librosa.frames_to_time(beats, sr=sr) + """ + samples = frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft) + + return samples_to_time(samples, sr=sr) + + +@overload +def time_to_frames( + times: _FloatLike_co, + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> np.integer[Any]: + ... + + +@overload +def time_to_frames( + times: _SequenceLike[_FloatLike_co], + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> np.ndarray: + ... + + +@overload +def time_to_frames( + times: _ScalarOrSequence[_FloatLike_co], + *, + sr: float = ..., + hop_length: int = ..., + n_fft: Optional[int] = ..., +) -> Union[np.integer[Any], np.ndarray]: + ... + + +def time_to_frames( + times: _ScalarOrSequence[_FloatLike_co], + *, + sr: float = 22050, + hop_length: int = 512, + n_fft: Optional[int] = None, +) -> Union[np.integer[Any], np.ndarray]: + """Convert time stamps into STFT frames. + + Parameters + ---------- + times : np.ndarray [shape=(n,)] + time (in seconds) or vector of time values + + sr : number > 0 [scalar] + audio sampling rate + + hop_length : int > 0 [scalar] + number of samples between successive frames + + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``- n_fft // 2`` + to counteract windowing effects in STFT. + + .. note:: This may result in negative frame indices. + + Returns + ------- + frames : np.ndarray [shape=(n,), dtype=int] + Frame numbers corresponding to the given times:: + + frames[i] = floor( times[i] * sr / hop_length ) + + See Also + -------- + frames_to_time : convert frame indices to time values + time_to_samples : convert time values to sample indices + + Examples + -------- + Get the frame numbers for every 100ms + + >>> librosa.time_to_frames(np.arange(0, 1, 0.1), + ... sr=22050, hop_length=512) + array([ 0, 4, 8, 12, 17, 21, 25, 30, 34, 38]) + """ + samples = time_to_samples(times, sr=sr) + + return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft) + + +@overload +def time_to_samples(times: _FloatLike_co, *, sr: float = ...) -> np.integer[Any]: + ... + + +@overload +def time_to_samples( + times: _SequenceLike[_FloatLike_co], *, sr: float = ... +) -> np.ndarray: + ... + + +@overload +def time_to_samples( + times: _ScalarOrSequence[_FloatLike_co], *, sr: float = ... +) -> Union[np.integer[Any], np.ndarray]: + ... + + +def time_to_samples( + times: _ScalarOrSequence[_FloatLike_co], *, sr: float = 22050 +) -> Union[np.integer[Any], np.ndarray]: + """Convert timestamps (in seconds) to sample indices. + + Parameters + ---------- + times : number or np.ndarray + Time value or array of time values (in seconds) + sr : number > 0 + Sampling rate + + Returns + ------- + samples : int or np.ndarray [shape=times.shape, dtype=int] + Sample indices corresponding to values in ``times`` + + See Also + -------- + time_to_frames : convert time values to frame indices + samples_to_time : convert sample indices to time values + + Examples + -------- + >>> librosa.time_to_samples(np.arange(0, 1, 0.1), sr=22050) + array([ 0, 2205, 4410, 6615, 8820, 11025, 13230, 15435, + 17640, 19845]) + """ + return (np.asanyarray(times) * sr).astype(int) + + +@overload +def samples_to_time(samples: _IntLike_co, *, sr: float = ...) -> np.floating[Any]: + ... + + +@overload +def samples_to_time( + samples: _SequenceLike[_IntLike_co], *, sr: float = ... +) -> np.ndarray: + ... + + +@overload +def samples_to_time( + samples: _ScalarOrSequence[_IntLike_co], *, sr: float = ... +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def samples_to_time( + samples: _ScalarOrSequence[_IntLike_co], *, sr: float = 22050 +) -> Union[np.floating[Any], np.ndarray]: + """Convert sample indices to time (in seconds). + + Parameters + ---------- + samples : np.ndarray + Sample index or array of sample indices + sr : number > 0 + Sampling rate + + Returns + ------- + times : np.ndarray [shape=samples.shape] + Time values corresponding to ``samples`` (in seconds) + + See Also + -------- + samples_to_frames : convert sample indices to frame indices + time_to_samples : convert time values to sample indices + + Examples + -------- + Get timestamps corresponding to every 512 samples + + >>> librosa.samples_to_time(np.arange(0, 22050, 512), sr=22050) + array([ 0. , 0.023, 0.046, 0.07 , 0.093, 0.116, 0.139, + 0.163, 0.186, 0.209, 0.232, 0.255, 0.279, 0.302, + 0.325, 0.348, 0.372, 0.395, 0.418, 0.441, 0.464, + 0.488, 0.511, 0.534, 0.557, 0.58 , 0.604, 0.627, + 0.65 , 0.673, 0.697, 0.72 , 0.743, 0.766, 0.789, + 0.813, 0.836, 0.859, 0.882, 0.906, 0.929, 0.952, + 0.975, 0.998]) + """ + return np.asanyarray(samples) / float(sr) + + +@overload +def blocks_to_frames(blocks: _IntLike_co, *, block_length: int) -> np.integer[Any]: + ... + + +@overload +def blocks_to_frames( + blocks: _SequenceLike[_IntLike_co], *, block_length: int +) -> np.ndarray: + ... + + +@overload +def blocks_to_frames( + blocks: _ScalarOrSequence[_IntLike_co], *, block_length: int +) -> Union[np.integer[Any], np.ndarray]: + ... + + +def blocks_to_frames( + blocks: _ScalarOrSequence[_IntLike_co], *, block_length: int +) -> Union[np.integer[Any], np.ndarray]: + """Convert block indices to frame indices + + Parameters + ---------- + blocks : np.ndarray + Block index or array of block indices + block_length : int > 0 + The number of frames per block + + Returns + ------- + frames : np.ndarray [shape=samples.shape, dtype=int] + The index or indices of frames corresponding to the beginning + of each provided block. + + See Also + -------- + blocks_to_samples + blocks_to_time + + Examples + -------- + Get frame indices for each block in a stream + + >>> filename = librosa.ex('brahms') + >>> sr = librosa.get_samplerate(filename) + >>> stream = librosa.stream(filename, block_length=16, + ... frame_length=2048, hop_length=512) + >>> for n, y in enumerate(stream): + ... n_frame = librosa.blocks_to_frames(n, block_length=16) + + """ + return block_length * np.asanyarray(blocks) + + +@overload +def blocks_to_samples( + blocks: _IntLike_co, *, block_length: int, hop_length: int +) -> np.integer[Any]: + ... + + +@overload +def blocks_to_samples( + blocks: _SequenceLike[_IntLike_co], *, block_length: int, hop_length: int +) -> np.ndarray: + ... + + +@overload +def blocks_to_samples( + blocks: _ScalarOrSequence[_IntLike_co], *, block_length: int, hop_length: int +) -> Union[np.integer[Any], np.ndarray]: + ... + + +def blocks_to_samples( + blocks: _ScalarOrSequence[_IntLike_co], *, block_length: int, hop_length: int +) -> Union[np.integer[Any], np.ndarray]: + """Convert block indices to sample indices + + Parameters + ---------- + blocks : np.ndarray + Block index or array of block indices + block_length : int > 0 + The number of frames per block + hop_length : int > 0 + The number of samples to advance between frames + + Returns + ------- + samples : np.ndarray [shape=samples.shape, dtype=int] + The index or indices of samples corresponding to the beginning + of each provided block. + + Note that these correspond to the *first* sample index in + each block, and are not frame-centered. + + See Also + -------- + blocks_to_frames + blocks_to_time + + Examples + -------- + Get sample indices for each block in a stream + + >>> filename = librosa.ex('brahms') + >>> sr = librosa.get_samplerate(filename) + >>> stream = librosa.stream(filename, block_length=16, + ... frame_length=2048, hop_length=512) + >>> for n, y in enumerate(stream): + ... n_sample = librosa.blocks_to_samples(n, block_length=16, + ... hop_length=512) + + """ + frames = blocks_to_frames(blocks, block_length=block_length) + return frames_to_samples(frames, hop_length=hop_length) + + +@overload +def blocks_to_time( + blocks: _IntLike_co, *, block_length: int, hop_length: int, sr: float +) -> np.floating[Any]: + ... + + +@overload +def blocks_to_time( + blocks: _SequenceLike[_IntLike_co], *, block_length: int, hop_length: int, sr: float +) -> np.ndarray: + ... + + +@overload +def blocks_to_time( + blocks: _ScalarOrSequence[_IntLike_co], + *, + block_length: int, + hop_length: int, + sr: float, +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def blocks_to_time( + blocks: _ScalarOrSequence[_IntLike_co], + *, + block_length: int, + hop_length: int, + sr: float, +) -> Union[np.floating[Any], np.ndarray]: + """Convert block indices to time (in seconds) + + Parameters + ---------- + blocks : np.ndarray + Block index or array of block indices + block_length : int > 0 + The number of frames per block + hop_length : int > 0 + The number of samples to advance between frames + sr : int > 0 + The sampling rate (samples per second) + + Returns + ------- + times : np.ndarray [shape=samples.shape] + The time index or indices (in seconds) corresponding to the + beginning of each provided block. + + Note that these correspond to the time of the *first* sample + in each block, and are not frame-centered. + + See Also + -------- + blocks_to_frames + blocks_to_samples + + Examples + -------- + Get time indices for each block in a stream + + >>> filename = librosa.ex('brahms') + >>> sr = librosa.get_samplerate(filename) + >>> stream = librosa.stream(filename, block_length=16, + ... frame_length=2048, hop_length=512) + >>> for n, y in enumerate(stream): + ... n_time = librosa.blocks_to_time(n, block_length=16, + ... hop_length=512, sr=sr) + + """ + samples = blocks_to_samples( + blocks, block_length=block_length, hop_length=hop_length + ) + return samples_to_time(samples, sr=sr) + + +@overload +def note_to_hz(note: str, **kwargs: Any) -> np.floating[Any]: + ... + + +@overload +def note_to_hz(note: _IterableLike[str], **kwargs: Any) -> np.ndarray: + ... + + +@overload +def note_to_hz( + note: Union[str, _IterableLike[str], Iterable[str]], **kwargs: Any +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def note_to_hz( + note: Union[str, _IterableLike[str], Iterable[str]], **kwargs: Any +) -> Union[np.floating[Any], np.ndarray]: + """Convert one or more note names to frequency (Hz) + + Examples + -------- + >>> # Get the frequency of a note + >>> librosa.note_to_hz('C') + array([ 16.352]) + >>> # Or multiple notes + >>> librosa.note_to_hz(['A3', 'A4', 'A5']) + array([ 220., 440., 880.]) + >>> # Or notes with tuning deviations + >>> librosa.note_to_hz('C2-32', round_midi=False) + array([ 64.209]) + + Parameters + ---------- + note : str or iterable of str + One or more note names to convert + **kwargs : additional keyword arguments + Additional parameters to `note_to_midi` + + Returns + ------- + frequencies : number or np.ndarray [shape=(len(note),)] + Array of frequencies (in Hz) corresponding to ``note`` + + See Also + -------- + midi_to_hz + note_to_midi + hz_to_note + """ + return midi_to_hz(note_to_midi(note, **kwargs)) + + +@overload +def note_to_midi(note: str, *, round_midi: bool = ...) -> Union[float, int]: + ... + + +@overload +def note_to_midi(note: _IterableLike[str], *, round_midi: bool = ...) -> np.ndarray: + ... + + +@overload +def note_to_midi( + note: Union[str, _IterableLike[str], Iterable[str]], *, round_midi: bool = ... +) -> Union[float, int, np.ndarray]: + ... + + +def note_to_midi( + note: Union[str, _IterableLike[str], Iterable[str]], *, round_midi: bool = True +) -> Union[float, np.ndarray]: + """Convert one or more spelled notes to MIDI number(s). + + Notes may be spelled out with optional accidentals or octave numbers. + + The leading note name is case-insensitive. + + Sharps are indicated with ``#``, flats may be indicated with ``!`` or ``b``. + + Parameters + ---------- + note : str or iterable of str + One or more note names. + round_midi : bool + - If ``True``, midi numbers are rounded to the nearest integer. + - If ``False``, allow fractional midi numbers. + + Returns + ------- + midi : float or np.array + Midi note numbers corresponding to inputs. + + Raises + ------ + ParameterError + If the input is not in valid note format + + See Also + -------- + midi_to_note + note_to_hz + + Examples + -------- + >>> librosa.note_to_midi('C') + 12 + >>> librosa.note_to_midi('C#3') + 49 + >>> librosa.note_to_midi('C♯3') # Using Unicode sharp + 49 + >>> librosa.note_to_midi('C♭3') # Using Unicode flat + 47 + >>> librosa.note_to_midi('f4') + 65 + >>> librosa.note_to_midi('Bb-1') + 10 + >>> librosa.note_to_midi('A!8') + 116 + >>> librosa.note_to_midi('Gđ„Ș6') # Double-sharp + 93 + >>> librosa.note_to_midi('Bđ„«6') # Double-flat + 93 + >>> librosa.note_to_midi('Câ™­đ„«5') # Triple-flats also work + 69 + >>> # Lists of notes also work + >>> librosa.note_to_midi(['C', 'E', 'G']) + array([12, 16, 19]) + """ + if not isinstance(note, str): + return np.array([note_to_midi(n, round_midi=round_midi) for n in note]) + + pitch_map: Dict[str, int] = { + "C": 0, + "D": 2, + "E": 4, + "F": 5, + "G": 7, + "A": 9, + "B": 11, + } + acc_map: Dict[str, int] = { + "#": 1, + "": 0, + "b": -1, + "!": -1, + "♯": 1, + "đ„Ș": 2, + "♭": -1, + "đ„«": -2, + "♼": 0, + } + + match = notation.NOTE_RE.match(note) + + if not match: + raise ParameterError(f"Improper note format: {note:s}") + + pitch = match.group("note").upper() + offset = np.sum([acc_map[o] for o in match.group("accidental")]) + octave = match.group("octave") + cents = match.group("cents") + + if not octave: + octave = 0 + else: + octave = int(octave) + + if not cents: + cents = 0 + else: + cents = int(cents) * 1e-2 + + note_value: float = 12 * (octave + 1) + pitch_map[pitch] + offset + cents + + if round_midi: + return int(np.round(note_value)) + else: + return note_value + + +@overload +def midi_to_note( + midi: _FloatLike_co, + *, + octave: bool = ..., + cents: bool = ..., + key: str = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def midi_to_note( + midi: _SequenceLike[_FloatLike_co], + *, + octave: bool = ..., + cents: bool = ..., + key: str = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def midi_to_note( + midi: _ScalarOrSequence[_FloatLike_co], + *, + octave: bool = ..., + cents: bool = ..., + key: str = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +@vectorize(excluded=["octave", "cents", "key", "unicode"]) +def midi_to_note( + midi: _ScalarOrSequence[_FloatLike_co], + *, + octave: bool = True, + cents: bool = False, + key: str = "C:maj", + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert one or more MIDI numbers to note strings. + + MIDI numbers will be rounded to the nearest integer. + + Notes will be of the format 'C0', 'C♯0', 'D0', ... + + Examples + -------- + >>> librosa.midi_to_note(0) + 'C-1' + + >>> librosa.midi_to_note(37) + 'C♯2' + + >>> librosa.midi_to_note(37, unicode=False) + 'C#2' + + >>> librosa.midi_to_note(-2) + 'A♯-2' + + >>> librosa.midi_to_note(104.7) + 'A7' + + >>> librosa.midi_to_note(104.7, cents=True) + 'A7-30' + + >>> librosa.midi_to_note(np.arange(12, 24))) + array(['C0', 'C♯0', 'D0', 'D♯0', 'E0', 'F0', 'F♯0', 'G0', 'G♯0', 'A0', + 'A♯0', 'B0'], dtype='>> librosa.midi_to_note(range(12, 24), key='F:min') + array(['C0', 'D♭0', 'D0', 'E♭0', 'E0', 'F0', 'G♭0', 'G0', 'A♭0', 'A0', + 'B♭0', 'B0'], dtype=' np.floating[Any]: + ... + + +@overload +def midi_to_hz(notes: _SequenceLike[_FloatLike_co]) -> np.ndarray: + ... + + +@overload +def midi_to_hz( + notes: _ScalarOrSequence[_FloatLike_co], +) -> Union[np.ndarray, np.floating[Any]]: + ... + + +def midi_to_hz( + notes: _ScalarOrSequence[_FloatLike_co], +) -> Union[np.ndarray, np.floating[Any]]: + """Get the frequency (Hz) of MIDI note(s) + + Examples + -------- + >>> librosa.midi_to_hz(36) + 65.406 + + >>> librosa.midi_to_hz(np.arange(36, 48)) + array([ 65.406, 69.296, 73.416, 77.782, 82.407, + 87.307, 92.499, 97.999, 103.826, 110. , + 116.541, 123.471]) + + Parameters + ---------- + notes : int or np.ndarray [shape=(n,), dtype=int] + midi number(s) of the note(s) + + Returns + ------- + frequency : number or np.ndarray [shape=(n,), dtype=float] + frequency (frequencies) of ``notes`` in Hz + + See Also + -------- + hz_to_midi + note_to_hz + """ + return 440.0 * (2.0 ** ((np.asanyarray(notes) - 69.0) / 12.0)) + + +@overload +def hz_to_midi(frequencies: _FloatLike_co) -> np.floating[Any]: + ... + + +@overload +def hz_to_midi(frequencies: _SequenceLike[_FloatLike_co]) -> np.ndarray: + ... + + +@overload +def hz_to_midi( + frequencies: _ScalarOrSequence[_FloatLike_co], +) -> Union[np.ndarray, np.floating[Any]]: + ... + + +def hz_to_midi( + frequencies: _ScalarOrSequence[_FloatLike_co], +) -> Union[np.ndarray, np.floating[Any]]: + """Get MIDI note number(s) for given frequencies + + Examples + -------- + >>> librosa.hz_to_midi(60) + 34.506 + >>> librosa.hz_to_midi([110, 220, 440]) + array([ 45., 57., 69.]) + + Parameters + ---------- + frequencies : float or np.ndarray [shape=(n,), dtype=float] + frequencies to convert + + Returns + ------- + note_nums : number or np.ndarray [shape=(n,), dtype=float] + MIDI notes to ``frequencies`` + + See Also + -------- + midi_to_hz + note_to_midi + hz_to_note + """ + midi: np.ndarray = 12 * (np.log2(np.asanyarray(frequencies)) - np.log2(440.0)) + 69 + return midi + + +@overload +def hz_to_note(frequencies: _FloatLike_co, **kwargs: Any) -> str: + ... + + +@overload +def hz_to_note(frequencies: _SequenceLike[_FloatLike_co], **kwargs: Any) -> np.ndarray: + ... + + +@overload +def hz_to_note( + frequencies: _ScalarOrSequence[_FloatLike_co], **kwargs: Any +) -> Union[str, np.ndarray]: + ... + + +def hz_to_note( + frequencies: _ScalarOrSequence[_FloatLike_co], **kwargs: Any +) -> Union[str, np.ndarray]: + """Convert one or more frequencies (in Hz) to the nearest note names. + + Parameters + ---------- + frequencies : float or iterable of float + Input frequencies, specified in Hz + **kwargs : additional keyword arguments + Arguments passed through to `midi_to_note` + + Returns + ------- + notes : str or np.ndarray of str + ``notes[i]`` is the closest note name to ``frequency[i]`` + (or ``frequency`` if the input is scalar) + + See Also + -------- + hz_to_midi + midi_to_note + note_to_hz + + Examples + -------- + Get a single note name for a frequency + + >>> librosa.hz_to_note(440.0) + 'A5' + + Get multiple notes with cent deviation + + >>> librosa.hz_to_note([32, 64], cents=True) + ['C1-38', 'C2-38'] + + Get multiple notes, but suppress octave labels + + >>> librosa.hz_to_note(440.0 * (2.0 ** np.linspace(0, 1, 12)), + ... octave=False) + ['A', 'A#', 'B', 'C', 'C#', 'D', 'E', 'F', 'F#', 'G', 'G#', 'A'] + + """ + return midi_to_note(hz_to_midi(frequencies), **kwargs) + + +@overload +def hz_to_mel(frequencies: _FloatLike_co, *, htk: bool = ...) -> np.floating[Any]: + ... + + +@overload +def hz_to_mel( + frequencies: _SequenceLike[_FloatLike_co], *, htk: bool = ... +) -> np.ndarray: + ... + + +@overload +def hz_to_mel( + frequencies: _ScalarOrSequence[_FloatLike_co], *, htk: bool = ... +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def hz_to_mel( + frequencies: _ScalarOrSequence[_FloatLike_co], *, htk: bool = False +) -> Union[np.floating[Any], np.ndarray]: + """Convert Hz to Mels + + Examples + -------- + >>> librosa.hz_to_mel(60) + 0.9 + >>> librosa.hz_to_mel([110, 220, 440]) + array([ 1.65, 3.3 , 6.6 ]) + + Parameters + ---------- + frequencies : number or np.ndarray [shape=(n,)] , float + scalar or array of frequencies + htk : bool + use HTK formula instead of Slaney + + Returns + ------- + mels : number or np.ndarray [shape=(n,)] + input frequencies in Mels + + See Also + -------- + mel_to_hz + """ + frequencies = np.asanyarray(frequencies) + + if htk: + mels: np.ndarray = 2595.0 * np.log10(1.0 + frequencies / 700.0) + return mels + + # Fill in the linear part + f_min = 0.0 + f_sp = 200.0 / 3 + + mels = (frequencies - f_min) / f_sp + + # Fill in the log-scale part + + min_log_hz = 1000.0 # beginning of log region (Hz) + min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) + logstep = np.log(6.4) / 27.0 # step size for log region + + if frequencies.ndim: + # If we have array data, vectorize + log_t = frequencies >= min_log_hz + mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep + elif frequencies >= min_log_hz: + # If we have scalar data, heck directly + mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep + + return mels + + +@overload +def mel_to_hz(mels: _FloatLike_co, *, htk: bool = ...) -> np.floating[Any]: + ... + + +@overload +def mel_to_hz(mels: _SequenceLike[_FloatLike_co], *, htk: bool = ...) -> np.ndarray: + ... + + +@overload +def mel_to_hz( + mels: _ScalarOrSequence[_FloatLike_co], *, htk: bool = ... +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def mel_to_hz( + mels: _ScalarOrSequence[_FloatLike_co], *, htk: bool = False +) -> Union[np.floating[Any], np.ndarray]: + """Convert mel bin numbers to frequencies + + Examples + -------- + >>> librosa.mel_to_hz(3) + 200. + + >>> librosa.mel_to_hz([1,2,3,4,5]) + array([ 66.667, 133.333, 200. , 266.667, 333.333]) + + Parameters + ---------- + mels : np.ndarray [shape=(n,)], float + mel bins to convert + htk : bool + use HTK formula instead of Slaney + + Returns + ------- + frequencies : np.ndarray [shape=(n,)] + input mels in Hz + + See Also + -------- + hz_to_mel + """ + mels = np.asanyarray(mels) + + if htk: + return 700.0 * (10.0 ** (mels / 2595.0) - 1.0) + + # Fill in the linear scale + f_min = 0.0 + f_sp = 200.0 / 3 + freqs = f_min + f_sp * mels + + # And now the nonlinear scale + min_log_hz = 1000.0 # beginning of log region (Hz) + min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels) + logstep = np.log(6.4) / 27.0 # step size for log region + + if mels.ndim: + # If we have vector data, vectorize + log_t = mels >= min_log_mel + freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel)) + elif mels >= min_log_mel: + # If we have scalar data, check directly + freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel)) + + return freqs + + +@overload +def hz_to_octs( + frequencies: _FloatLike_co, *, tuning: float = ..., bins_per_octave: int = ... +) -> np.floating[Any]: + ... + + +@overload +def hz_to_octs( + frequencies: _SequenceLike[_FloatLike_co], + *, + tuning: float = ..., + bins_per_octave: int = ..., +) -> np.ndarray: + ... + + +@overload +def hz_to_octs( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + tuning: float = ..., + bins_per_octave: int = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def hz_to_octs( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + tuning: float = 0.0, + bins_per_octave: int = 12, +) -> Union[np.floating[Any], np.ndarray]: + """Convert frequencies (Hz) to (fractional) octave numbers. + + Examples + -------- + >>> librosa.hz_to_octs(440.0) + 4. + >>> librosa.hz_to_octs([32, 64, 128, 256]) + array([ 0.219, 1.219, 2.219, 3.219]) + + Parameters + ---------- + frequencies : number >0 or np.ndarray [shape=(n,)] or float + scalar or vector of frequencies + tuning : float + Tuning deviation from A440 in (fractional) bins per octave. + bins_per_octave : int > 0 + Number of bins per octave. + + Returns + ------- + octaves : number or np.ndarray [shape=(n,)] + octave number for each frequency + + See Also + -------- + octs_to_hz + """ + A440 = 440.0 * 2.0 ** (tuning / bins_per_octave) + + octs: np.ndarray = np.log2(np.asanyarray(frequencies) / (float(A440) / 16)) + return octs + + +@overload +def octs_to_hz( + octs: _FloatLike_co, *, tuning: float = ..., bins_per_octave: int = ... +) -> np.floating[Any]: + ... + + +@overload +def octs_to_hz( + octs: _SequenceLike[_FloatLike_co], + *, + tuning: float = ..., + bins_per_octave: int = ..., +) -> np.ndarray: + ... + + +@overload +def octs_to_hz( + octs: _ScalarOrSequence[_FloatLike_co], + *, + tuning: float = ..., + bins_per_octave: int = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def octs_to_hz( + octs: _ScalarOrSequence[_FloatLike_co], + *, + tuning: float = 0.0, + bins_per_octave: int = 12, +) -> Union[np.floating[Any], np.ndarray]: + """Convert octaves numbers to frequencies. + + Octaves are counted relative to A. + + Examples + -------- + >>> librosa.octs_to_hz(1) + 55. + >>> librosa.octs_to_hz([-2, -1, 0, 1, 2]) + array([ 6.875, 13.75 , 27.5 , 55. , 110. ]) + + Parameters + ---------- + octs : np.ndarray [shape=(n,)] or float + octave number for each frequency + tuning : float + Tuning deviation from A440 in (fractional) bins per octave. + bins_per_octave : int > 0 + Number of bins per octave. + + Returns + ------- + frequencies : number or np.ndarray [shape=(n,)] + scalar or vector of frequencies + + See Also + -------- + hz_to_octs + """ + A440 = 440.0 * 2.0 ** (tuning / bins_per_octave) + + return (float(A440) / 16) * (2.0 ** np.asanyarray(octs)) + + +@overload +def A4_to_tuning(A4: _FloatLike_co, *, bins_per_octave: int = ...) -> np.floating[Any]: + ... + + +@overload +def A4_to_tuning( + A4: _SequenceLike[_FloatLike_co], *, bins_per_octave: int = ... +) -> np.ndarray: + ... + + +@overload +def A4_to_tuning( + A4: _ScalarOrSequence[_FloatLike_co], *, bins_per_octave: int = ... +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def A4_to_tuning( + A4: _ScalarOrSequence[_FloatLike_co], *, bins_per_octave: int = 12 +) -> Union[np.floating[Any], np.ndarray]: + """Convert a reference pitch frequency (e.g., ``A4=435``) to a tuning + estimation, in fractions of a bin per octave. + + This is useful for determining the tuning deviation relative to + A440 of a given frequency, assuming equal temperament. By default, + 12 bins per octave are used. + + This method is the inverse of `tuning_to_A4`. + + Examples + -------- + The base case of this method in which A440 yields 0 tuning offset + from itself. + + >>> librosa.A4_to_tuning(440.0) + 0. + + Convert a non-A440 frequency to a tuning offset relative + to A440 using the default of 12 bins per octave. + + >>> librosa.A4_to_tuning(432.0) + -0.318 + + Convert two reference pitch frequencies to corresponding + tuning estimations at once, but using 24 bins per octave. + + >>> librosa.A4_to_tuning([440.0, 444.0], bins_per_octave=24) + array([ 0., 0.313 ]) + + Parameters + ---------- + A4 : float or np.ndarray [shape=(n,), dtype=float] + Reference frequency(s) corresponding to A4. + bins_per_octave : int > 0 + Number of bins per octave. + + Returns + ------- + tuning : float or np.ndarray [shape=(n,), dtype=float] + Tuning deviation from A440 in (fractional) bins per octave. + + See Also + -------- + tuning_to_A4 + """ + tuning: np.ndarray = bins_per_octave * (np.log2(np.asanyarray(A4)) - np.log2(440.0)) + return tuning + + +@overload +def tuning_to_A4( + tuning: _FloatLike_co, *, bins_per_octave: int = ... +) -> np.floating[Any]: + ... + + +@overload +def tuning_to_A4( + tuning: _SequenceLike[_FloatLike_co], *, bins_per_octave: int = ... +) -> np.ndarray: + ... + + +@overload +def tuning_to_A4( + tuning: _ScalarOrSequence[_FloatLike_co], *, bins_per_octave: int = ... +) -> Union[np.floating[Any], np.ndarray]: + ... + + +def tuning_to_A4( + tuning: _ScalarOrSequence[_FloatLike_co], *, bins_per_octave: int = 12 +) -> Union[np.floating[Any], np.ndarray]: + """Convert a tuning deviation (from 0) in fractions of a bin per + octave (e.g., ``tuning=-0.1``) to a reference pitch frequency + relative to A440. + + This is useful if you are working in a non-A440 tuning system + to determine the reference pitch frequency given a tuning + offset and assuming equal temperament. By default, 12 bins per + octave are used. + + This method is the inverse of `A4_to_tuning`. + + Examples + -------- + The base case of this method in which a tuning deviation of 0 + gets us to our A440 reference pitch. + + >>> librosa.tuning_to_A4(0.0) + 440. + + Convert a nonzero tuning offset to its reference pitch frequency. + + >>> librosa.tuning_to_A4(-0.318) + 431.992 + + Convert 3 tuning deviations at once to respective reference + pitch frequencies, using 36 bins per octave. + + >>> librosa.tuning_to_A4([0.1, 0.2, -0.1], bins_per_octave=36) + array([ 440.848, 441.698 439.154]) + + Parameters + ---------- + tuning : float or np.ndarray [shape=(n,), dtype=float] + Tuning deviation from A440 in fractional bins per octave. + bins_per_octave : int > 0 + Number of bins per octave. + + Returns + ------- + A4 : float or np.ndarray [shape=(n,), dtype=float] + Reference frequency corresponding to A4. + + See Also + -------- + A4_to_tuning + """ + return 440.0 * 2.0 ** (np.asanyarray(tuning) / bins_per_octave) + + +def fft_frequencies(*, sr: float = 22050, n_fft: int = 2048) -> np.ndarray: + """Alternative interface for `np.fft.rfftfreq` + + Parameters + ---------- + sr : number > 0 [scalar] + Audio sampling rate + n_fft : int > 0 [scalar] + FFT window size + + Returns + ------- + freqs : np.ndarray [shape=(1 + n_fft/2,)] + Frequencies ``(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)`` + + Examples + -------- + >>> librosa.fft_frequencies(sr=22050, n_fft=16) + array([ 0. , 1378.125, 2756.25 , 4134.375, + 5512.5 , 6890.625, 8268.75 , 9646.875, 11025. ]) + """ + return np.fft.rfftfreq(n=n_fft, d=1.0 / sr) + + +def cqt_frequencies( + n_bins: int, *, fmin: float, bins_per_octave: int = 12, tuning: float = 0.0 +) -> np.ndarray: + """Compute the center frequencies of Constant-Q bins. + + Examples + -------- + >>> # Get the CQT frequencies for 24 notes, starting at C2 + >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2')) + array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307, + 92.499, 97.999, 103.826, 110. , 116.541, 123.471, + 130.813, 138.591, 146.832, 155.563, 164.814, 174.614, + 184.997, 195.998, 207.652, 220. , 233.082, 246.942]) + + Parameters + ---------- + n_bins : int > 0 [scalar] + Number of constant-Q bins + fmin : float > 0 [scalar] + Minimum frequency + bins_per_octave : int > 0 [scalar] + Number of bins per octave + tuning : float + Deviation from A440 tuning in fractional bins + + Returns + ------- + frequencies : np.ndarray [shape=(n_bins,)] + Center frequency for each CQT bin + """ + correction: float = 2.0 ** (float(tuning) / bins_per_octave) + frequencies: np.ndarray = 2.0 ** ( + np.arange(0, n_bins, dtype=float) / bins_per_octave + ) + + return correction * fmin * frequencies + + +def mel_frequencies( + n_mels: int = 128, *, fmin: float = 0.0, fmax: float = 11025.0, htk: bool = False +) -> np.ndarray: + """Compute an array of acoustic frequencies tuned to the mel scale. + + The mel scale is a quasi-logarithmic function of acoustic frequency + designed such that perceptually similar pitch intervals (e.g. octaves) + appear equal in width over the full hearing range. + + Because the definition of the mel scale is conditioned by a finite number + of subjective psychoaoustical experiments, several implementations coexist + in the audio signal processing literature [#]_. By default, librosa replicates + the behavior of the well-established MATLAB Auditory Toolbox of Slaney [#]_. + According to this default implementation, the conversion from Hertz to mel is + linear below 1 kHz and logarithmic above 1 kHz. Another available implementation + replicates the Hidden Markov Toolkit [#]_ (HTK) according to the following formula:: + + mel = 2595.0 * np.log10(1.0 + f / 700.0). + + The choice of implementation is determined by the ``htk`` keyword argument: setting + ``htk=False`` leads to the Auditory toolbox implementation, whereas setting it ``htk=True`` + leads to the HTK implementation. + + .. [#] Umesh, S., Cohen, L., & Nelson, D. Fitting the mel scale. + In Proc. International Conference on Acoustics, Speech, and Signal Processing + (ICASSP), vol. 1, pp. 217-220, 1998. + + .. [#] Slaney, M. Auditory Toolbox: A MATLAB Toolbox for Auditory + Modeling Work. Technical Report, version 2, Interval Research Corporation, 1998. + + .. [#] Young, S., Evermann, G., Gales, M., Hain, T., Kershaw, D., Liu, X., + Moore, G., Odell, J., Ollason, D., Povey, D., Valtchev, V., & Woodland, P. + The HTK book, version 3.4. Cambridge University, March 2009. + + See Also + -------- + hz_to_mel + mel_to_hz + librosa.feature.melspectrogram + librosa.feature.mfcc + + Parameters + ---------- + n_mels : int > 0 [scalar] + Number of mel bins. + fmin : float >= 0 [scalar] + Minimum frequency (Hz). + fmax : float >= 0 [scalar] + Maximum frequency (Hz). + htk : bool + If True, use HTK formula to convert Hz to mel. + Otherwise (False), use Slaney's Auditory Toolbox. + + Returns + ------- + bin_frequencies : ndarray [shape=(n_mels,)] + Vector of ``n_mels`` frequencies in Hz which are uniformly spaced on the Mel + axis. + + Examples + -------- + >>> librosa.mel_frequencies(n_mels=40) + array([ 0. , 85.317, 170.635, 255.952, + 341.269, 426.586, 511.904, 597.221, + 682.538, 767.855, 853.173, 938.49 , + 1024.856, 1119.114, 1222.042, 1334.436, + 1457.167, 1591.187, 1737.532, 1897.337, + 2071.84 , 2262.393, 2470.47 , 2697.686, + 2945.799, 3216.731, 3512.582, 3835.643, + 4188.417, 4573.636, 4994.285, 5453.621, + 5955.205, 6502.92 , 7101.009, 7754.107, + 8467.272, 9246.028, 10096.408, 11025. ]) + + """ + # 'Center freqs' of mel bands - uniformly spaced between limits + min_mel = hz_to_mel(fmin, htk=htk) + max_mel = hz_to_mel(fmax, htk=htk) + + mels = np.linspace(min_mel, max_mel, n_mels) + + hz: np.ndarray = mel_to_hz(mels, htk=htk) + return hz + + +def tempo_frequencies( + n_bins: int, *, hop_length: int = 512, sr: float = 22050 +) -> np.ndarray: + """Compute the frequencies (in beats per minute) corresponding + to an onset auto-correlation or tempogram matrix. + + Parameters + ---------- + n_bins : int > 0 + The number of lag bins + hop_length : int > 0 + The number of samples between each bin + sr : number > 0 + The audio sampling rate + + Returns + ------- + bin_frequencies : ndarray [shape=(n_bins,)] + vector of bin frequencies measured in BPM. + + .. note:: ``bin_frequencies[0] = +np.inf`` corresponds to 0-lag + + Examples + -------- + Get the tempo frequencies corresponding to a 384-bin (8-second) tempogram + + >>> librosa.tempo_frequencies(384, sr=22050) + array([ inf, 2583.984, 1291.992, ..., 6.782, + 6.764, 6.747]) + """ + bin_frequencies = np.zeros(int(n_bins), dtype=np.float64) + + bin_frequencies[0] = np.inf + bin_frequencies[1:] = 60.0 * sr / (hop_length * np.arange(1.0, n_bins)) + + return bin_frequencies + + +def fourier_tempo_frequencies( + *, sr: float = 22050, win_length: int = 384, hop_length: int = 512 +) -> np.ndarray: + """Compute the frequencies (in beats per minute) corresponding + to a Fourier tempogram matrix. + + Parameters + ---------- + sr : number > 0 + The audio sampling rate + win_length : int > 0 + The number of frames per analysis window + hop_length : int > 0 + The number of samples between each bin + + Returns + ------- + bin_frequencies : ndarray [shape=(win_length // 2 + 1 ,)] + vector of bin frequencies measured in BPM. + + Examples + -------- + Get the tempo frequencies corresponding to a 384-bin (8-second) tempogram + + >>> librosa.fourier_tempo_frequencies(win_length=384, sr=22050) + array([ 0. , 0.117, 0.234, ..., 22.266, 22.383, 22.5 ]) + """ + # sr / hop_length gets the frame rate + # multiplying by 60 turns frames / sec into frames / minute + return fft_frequencies(sr=sr * 60 / float(hop_length), n_fft=win_length) + + +# A-weighting should be capitalized: suppress the naming warning +@overload +def A_weighting( + frequencies: _FloatLike_co, *, min_db: Optional[float] = ... +) -> np.floating[Any]: # pylint: disable=invalid-name + ... + + +@overload +def A_weighting( + frequencies: _SequenceLike[_FloatLike_co], *, min_db: Optional[float] = ... +) -> np.ndarray: # pylint: disable=invalid-name + ... + + +@overload +def A_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = ... +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + ... + + +def A_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = -80.0 +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + """Compute the A-weighting of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + min_db : float [scalar] or None + Clip weights below this threshold. + If `None`, no clipping is performed. + + Returns + ------- + A_weighting : scalar or np.ndarray [shape=(n,)] + ``A_weighting[i]`` is the A-weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + frequency_weighting + multi_frequency_weighting + B_weighting + C_weighting + D_weighting + + Examples + -------- + Get the A-weighting for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weights = librosa.A_weighting(freqs) + >>> fig, ax = plt.subplots() + >>> ax.plot(freqs, weights) + >>> ax.set(xlabel='Frequency (Hz)', + ... ylabel='Weighting (log10)', + ... title='A-Weighting of CQT frequencies') + """ + f_sq = np.asanyarray(frequencies) ** 2.0 + + const = np.array([12194.217, 20.598997, 107.65265, 737.86223]) ** 2.0 + weights: np.ndarray = 2.0 + 20.0 * ( + np.log10(const[0]) + + 2 * np.log10(f_sq) + - np.log10(f_sq + const[0]) + - np.log10(f_sq + const[1]) + - 0.5 * np.log10(f_sq + const[2]) + - 0.5 * np.log10(f_sq + const[3]) + ) + + if min_db is None: + return weights + else: + return np.maximum(min_db, weights) + + +@overload +def B_weighting( + frequencies: _FloatLike_co, *, min_db: Optional[float] = ... +) -> np.floating[Any]: # pylint: disable=invalid-name + ... + + +@overload +def B_weighting( + frequencies: _SequenceLike[_FloatLike_co], *, min_db: Optional[float] = ... +) -> np.ndarray: # pylint: disable=invalid-name + ... + + +@overload +def B_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = ... +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + ... + + +def B_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = -80.0 +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + """Compute the B-weighting of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + min_db : float [scalar] or None + Clip weights below this threshold. + If `None`, no clipping is performed. + + Returns + ------- + B_weighting : scalar or np.ndarray [shape=(n,)] + ``B_weighting[i]`` is the B-weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + frequency_weighting + multi_frequency_weighting + A_weighting + C_weighting + D_weighting + + Examples + -------- + Get the B-weighting for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weights = librosa.B_weighting(freqs) + >>> fig, ax = plt.subplots() + >>> ax.plot(freqs, weights) + >>> ax.set(xlabel='Frequency (Hz)', + ... ylabel='Weighting (log10)', + ... title='B-Weighting of CQT frequencies') + """ + f_sq = np.asanyarray(frequencies) ** 2.0 + + const = np.array([12194.217, 20.598997, 158.48932]) ** 2.0 + weights: np.ndarray = 0.17 + 20.0 * ( + np.log10(const[0]) + + 1.5 * np.log10(f_sq) + - np.log10(f_sq + const[0]) + - np.log10(f_sq + const[1]) + - 0.5 * np.log10(f_sq + const[2]) + ) + + return weights if min_db is None else np.maximum(min_db, weights) + + +@overload +def C_weighting( + frequencies: _FloatLike_co, *, min_db: Optional[float] = ... +) -> np.floating[Any]: # pylint: disable=invalid-name + ... + + +@overload +def C_weighting( + frequencies: _SequenceLike[_FloatLike_co], *, min_db: Optional[float] = ... +) -> np.ndarray: # pylint: disable=invalid-name + ... + + +@overload +def C_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = ... +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + ... + + +def C_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = -80.0 +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + """Compute the C-weighting of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + min_db : float [scalar] or None + Clip weights below this threshold. + If `None`, no clipping is performed. + + Returns + ------- + C_weighting : scalar or np.ndarray [shape=(n,)] + ``C_weighting[i]`` is the C-weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + frequency_weighting + multi_frequency_weighting + A_weighting + B_weighting + D_weighting + + Examples + -------- + Get the C-weighting for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weights = librosa.C_weighting(freqs) + >>> fig, ax = plt.subplots() + >>> ax.plot(freqs, weights) + >>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)', + ... title='C-Weighting of CQT frequencies') + """ + f_sq = np.asanyarray(frequencies) ** 2.0 + + const = np.array([12194.217, 20.598997]) ** 2.0 + weights: np.ndarray = 0.062 + 20.0 * ( + np.log10(const[0]) + + np.log10(f_sq) + - np.log10(f_sq + const[0]) + - np.log10(f_sq + const[1]) + ) + + return weights if min_db is None else np.maximum(min_db, weights) + + +@overload +def D_weighting( + frequencies: _FloatLike_co, *, min_db: Optional[float] = ... +) -> np.floating[Any]: # pylint: disable=invalid-name + ... + + +@overload +def D_weighting( + frequencies: _SequenceLike[_FloatLike_co], *, min_db: Optional[float] = ... +) -> np.ndarray: # pylint: disable=invalid-name + ... + + +@overload +def D_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = ... +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + ... + + +def D_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, min_db: Optional[float] = -80.0 +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + """Compute the D-weighting of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + min_db : float [scalar] or None + Clip weights below this threshold. + If `None`, no clipping is performed. + + Returns + ------- + D_weighting : scalar or np.ndarray [shape=(n,)] + ``D_weighting[i]`` is the D-weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + frequency_weighting + multi_frequency_weighting + A_weighting + B_weighting + C_weighting + + Examples + -------- + Get the D-weighting for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weights = librosa.D_weighting(freqs) + >>> fig, ax = plt.subplots() + >>> ax.plot(freqs, weights) + >>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)', + ... title='D-Weighting of CQT frequencies') + """ + f_sq = np.asanyarray(frequencies) ** 2.0 + + const = np.array([8.3046305e-3, 1018.7, 1039.6, 3136.5, 3424, 282.7, 1160]) ** 2.0 + weights: np.ndarray = 20.0 * ( + 0.5 * np.log10(f_sq) + - np.log10(const[0]) + + 0.5 + * ( + +np.log10((const[1] - f_sq) ** 2 + const[2] * f_sq) + - np.log10((const[3] - f_sq) ** 2 + const[4] * f_sq) + - np.log10(const[5] + f_sq) + - np.log10(const[6] + f_sq) + ) + ) + + if min_db is None: + return weights + else: + return np.maximum(min_db, weights) + + +def Z_weighting( + frequencies: Sized, *, min_db: Optional[float] = None +) -> np.ndarray: # pylint: disable=invalid-name + """Apply no weighting curve (aka Z-weighting). + + This function behaves similarly to `A_weighting`, `B_weighting`, etc., + but all frequencies are equally weighted. + An optional threshold `min_db` can still be used to clip energies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + min_db : float [scalar] or None + Clip weights below this threshold. + If `None`, no clipping is performed. + + Returns + ------- + Z_weighting : scalar or np.ndarray [shape=(n,)] + ``Z_weighting[i]`` is the Z-weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + frequency_weighting + multi_frequency_weighting + A_weighting + B_weighting + C_weighting + D_weighting + """ + weights = np.zeros(len(frequencies)) + if min_db is None: + return weights + else: + return np.maximum(min_db, weights) + + +WEIGHTING_FUNCTIONS: Dict[ + Optional[str], Callable[..., Union[np.floating[Any], np.ndarray]] +] = { + "A": A_weighting, + "B": B_weighting, + "C": C_weighting, + "D": D_weighting, + "Z": Z_weighting, + None: Z_weighting, +} + + +@overload +def frequency_weighting( + frequencies: _FloatLike_co, *, kind: str = ..., **kwargs: Any +) -> np.floating[Any]: # pylint: disable=invalid-name + ... + + +@overload +def frequency_weighting( + frequencies: _SequenceLike[_FloatLike_co], *, kind: str = ..., **kwargs: Any +) -> np.ndarray: # pylint: disable=invalid-name + ... + + +@overload +def frequency_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, kind: str = ..., **kwargs: Any +) -> Union[np.floating[Any], np.ndarray]: # pylint: disable=invalid-name + ... + + +def frequency_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], *, kind: str = "A", **kwargs: Any +) -> Union[np.floating[Any], np.ndarray]: + """Compute the weighting of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + kind : str in + The weighting kind. e.g. `'A'`, `'B'`, `'C'`, `'D'`, `'Z'` + **kwargs + Additional keyword arguments to A_weighting, B_weighting, etc. + + Returns + ------- + weighting : scalar or np.ndarray [shape=(n,)] + ``weighting[i]`` is the weighting of ``frequencies[i]`` + + See Also + -------- + perceptual_weighting + multi_frequency_weighting + A_weighting + B_weighting + C_weighting + D_weighting + + Examples + -------- + Get the A-weighting for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weights = librosa.frequency_weighting(freqs, kind='A') + >>> fig, ax = plt.subplots() + >>> ax.plot(freqs, weights) + >>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)', + ... title='A-Weighting of CQT frequencies') + """ + if isinstance(kind, str): + kind = kind.upper() + return WEIGHTING_FUNCTIONS[kind](frequencies, **kwargs) + + +def multi_frequency_weighting( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + kinds: Iterable[str] = "ZAC", + **kwargs: Any, +) -> np.ndarray: + """Compute multiple weightings of a set of frequencies. + + Parameters + ---------- + frequencies : scalar or np.ndarray [shape=(n,)] + One or more frequencies (in Hz) + kinds : list or tuple or str + An iterable of weighting kinds. e.g. `('Z', 'B')`, `'ZAD'`, `'C'` + **kwargs : keywords to pass to the weighting function. + + Returns + ------- + weighting : scalar or np.ndarray [shape=(len(kinds), n)] + ``weighting[i, j]`` is the weighting of ``frequencies[j]`` + using the curve determined by ``kinds[i]``. + + See Also + -------- + perceptual_weighting + frequency_weighting + A_weighting + B_weighting + C_weighting + D_weighting + + Examples + -------- + Get the A, B, C, D, and Z weightings for CQT frequencies + + >>> import matplotlib.pyplot as plt + >>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1')) + >>> weightings = 'ABCDZ' + >>> weights = librosa.multi_frequency_weighting(freqs, kinds=weightings) + >>> fig, ax = plt.subplots() + >>> for label, w in zip(weightings, weights): + ... ax.plot(freqs, w, label=label) + >>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)', + ... title='Weightings of CQT frequencies') + >>> ax.legend() + """ + return np.stack( + [frequency_weighting(frequencies, kind=k, **kwargs) for k in kinds], axis=0 + ) + + +def times_like( + X: Union[np.ndarray, float], + *, + sr: float = 22050, + hop_length: int = 512, + n_fft: Optional[int] = None, + axis: int = -1, +) -> np.ndarray: + """Return an array of time values to match the time axis from a feature matrix. + + Parameters + ---------- + X : np.ndarray or scalar + - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. + - If scalar, X represents the number of frames. + sr : number > 0 [scalar] + audio sampling rate + hop_length : int > 0 [scalar] + number of samples between successive frames + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``n_fft // 2`` + to counteract windowing effects when using a non-centered STFT. + axis : int [scalar] + The axis representing the time axis of X. + By default, the last axis (-1) is taken. + + Returns + ------- + times : np.ndarray [shape=(n,)] + ndarray of times (in seconds) corresponding to each frame of X. + + See Also + -------- + samples_like : + Return an array of sample indices to match the time axis from a feature matrix. + + Examples + -------- + Provide a feature matrix input: + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> D = librosa.stft(y) + >>> times = librosa.times_like(D, sr=sr) + >>> times + array([0. , 0.023, ..., 5.294, 5.317]) + + Provide a scalar input: + + >>> n_frames = 2647 + >>> times = librosa.times_like(n_frames, sr=sr) + >>> times + array([ 0.00000000e+00, 2.32199546e-02, 4.64399093e-02, ..., + 6.13935601e+01, 6.14167800e+01, 6.14400000e+01]) + """ + samples = samples_like(X, hop_length=hop_length, n_fft=n_fft, axis=axis) + time: np.ndarray = samples_to_time(samples, sr=sr) + return time + + +def samples_like( + X: Union[np.ndarray, float], + *, + hop_length: int = 512, + n_fft: Optional[int] = None, + axis: int = -1, +) -> np.ndarray: + """Return an array of sample indices to match the time axis from a feature matrix. + + Parameters + ---------- + X : np.ndarray or scalar + - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. + - If scalar, X represents the number of frames. + hop_length : int > 0 [scalar] + number of samples between successive frames + n_fft : None or int > 0 [scalar] + Optional: length of the FFT window. + If given, time conversion will include an offset of ``n_fft // 2`` + to counteract windowing effects when using a non-centered STFT. + axis : int [scalar] + The axis representing the time axis of ``X``. + By default, the last axis (-1) is taken. + + Returns + ------- + samples : np.ndarray [shape=(n,)] + ndarray of sample indices corresponding to each frame of ``X``. + + See Also + -------- + times_like : + Return an array of time values to match the time axis from a feature matrix. + + Examples + -------- + Provide a feature matrix input: + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> X = librosa.stft(y) + >>> samples = librosa.samples_like(X) + >>> samples + array([ 0, 512, ..., 116736, 117248]) + + Provide a scalar input: + + >>> n_frames = 2647 + >>> samples = librosa.samples_like(n_frames) + >>> samples + array([ 0, 512, 1024, ..., 1353728, 1354240, 1354752]) + """ + # suppress type checks because mypy does not understand isscalar + if np.isscalar(X): + frames = np.arange(X) # type: ignore + else: + frames = np.arange(X.shape[axis]) # type: ignore + return frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft) + + +@overload +def midi_to_svara_h( + midi: _FloatLike_co, + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def midi_to_svara_h( + midi: np.ndarray, + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def midi_to_svara_h( + midi: Union[_FloatLike_co, np.ndarray], + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +@vectorize(excluded=["Sa", "abbr", "octave", "unicode"]) +def midi_to_svara_h( + midi: Union[_FloatLike_co, np.ndarray], + *, + Sa: _FloatLike_co, + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert MIDI numbers to Hindustani svara + + Parameters + ---------- + midi : numeric or np.ndarray + The MIDI number or numbers to convert + + Sa : number > 0 + MIDI number of the reference Sa. + + abbr : bool + If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...) + + If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + This only takes effect if `octave=True`. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given MIDI number(s) + + See Also + -------- + hz_to_svara_h + note_to_svara_h + midi_to_svara_c + midi_to_note + + Examples + -------- + Convert a single midi number: + + >>> librosa.midi_to_svara_h(65, Sa=60) + 'm' + + The first three svara with Sa at midi number 60: + + >>> librosa.midi_to_svara_h([60, 61, 62], Sa=60) + array(['S', 'r', 'R'], dtype='>> librosa.midi_to_svara_h([60, 61, 62], Sa=67) + array(['mÌŁ', 'MÌŁ', 'PÌŁ'], dtype='>> librosa.midi_to_svara_h([60, 61, 62], Sa=67, unicode=False) + array(['m,', 'M,', 'P,'], dtype='>> librosa.midi_to_svara_h([72, 73, 74], Sa=60, abbr=False) + array(['Ṡa', 'ṙe', 'Ṙe'], dtype=' svara_num >= 12: + if unicode: + svara = svara[0] + "\u0307" + svara[1:] + else: + svara += "'" + elif -12 <= svara_num < 0: + if unicode: + svara = svara[0] + "\u0323" + svara[1:] + else: + svara += "," + + return svara + + +@overload +def hz_to_svara_h( + frequencies: _FloatLike_co, + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def hz_to_svara_h( + frequencies: _SequenceLike[_FloatLike_co], + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def hz_to_svara_h( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + Sa: _FloatLike_co, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +def hz_to_svara_h( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + Sa: _FloatLike_co, + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert frequencies (in Hz) to Hindustani svara + + Note that this conversion assumes 12-tone equal temperament. + + Parameters + ---------- + frequencies : positive number or np.ndarray + The frequencies (in Hz) to convert + + Sa : positive number + Frequency (in Hz) of the reference Sa. + + abbr : bool + If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...) + + If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + This only takes effect if `octave=True`. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given frequency/frequencies + + See Also + -------- + midi_to_svara_h + note_to_svara_h + hz_to_svara_c + hz_to_note + + Examples + -------- + Convert Sa in three octaves: + + >>> librosa.hz_to_svara_h([261/2, 261, 261*2], Sa=261) + ['SÌŁ', 'S', 'Ṡ'] + + Convert one octave worth of frequencies with full names: + + >>> freqs = librosa.cqt_frequencies(n_bins=12, fmin=261) + >>> librosa.hz_to_svara_h(freqs, Sa=freqs[0], abbr=False) + ['Sa', 're', 'Re', 'ga', 'Ga', 'ma', 'Ma', 'Pa', 'dha', 'Dha', 'ni', 'Ni'] + """ + midis = hz_to_midi(frequencies) + return midi_to_svara_h( + midis, Sa=hz_to_midi(Sa), abbr=abbr, octave=octave, unicode=unicode + ) + + +@overload +def note_to_svara_h( + notes: str, *, Sa: str, abbr: bool = ..., octave: bool = ..., unicode: bool = ... +) -> str: + ... + + +@overload +def note_to_svara_h( + notes: _IterableLike[str], + *, + Sa: str, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def note_to_svara_h( + notes: Union[str, _IterableLike[str]], + *, + Sa: str, + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +def note_to_svara_h( + notes: Union[str, _IterableLike[str]], + *, + Sa: str, + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert western notes to Hindustani svara + + Note that this conversion assumes 12-tone equal temperament. + + Parameters + ---------- + notes : str or iterable of str + Notes to convert (e.g., `'C#'` or `['C4', 'Db4', 'D4']` + + Sa : str + Note corresponding to Sa (e.g., `'C'` or `'C5'`). + + If no octave information is provided, it will default to octave 0 + (``C0`` ~= 16 Hz) + + abbr : bool + If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...) + + If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + This only takes effect if `octave=True`. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given notes + + See Also + -------- + midi_to_svara_h + hz_to_svara_h + note_to_svara_c + note_to_midi + note_to_hz + + Examples + -------- + >>> librosa.note_to_svara_h(['C4', 'G4', 'C5', 'G5'], Sa='C5') + ['SÌŁ', 'PÌŁ', 'S', 'P'] + """ + midis = note_to_midi(notes, round_midi=False) + + return midi_to_svara_h( + midis, Sa=note_to_midi(Sa), abbr=abbr, octave=octave, unicode=unicode + ) + + +@overload +def midi_to_svara_c( + midi: _FloatLike_co, + *, + Sa: _FloatLike_co, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def midi_to_svara_c( + midi: np.ndarray, + *, + Sa: _FloatLike_co, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def midi_to_svara_c( + midi: Union[float, np.ndarray], + *, + Sa: _FloatLike_co, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +@vectorize(excluded=["Sa", "mela", "abbr", "octave", "unicode"]) # type: ignore +def midi_to_svara_c( + midi: Union[float, np.ndarray], + *, + Sa: _FloatLike_co, + mela: Union[int, str], + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert MIDI numbers to Carnatic svara within a given melakarta raga + + Parameters + ---------- + midi : numeric + The MIDI numbers to convert + + Sa : number > 0 + MIDI number of the reference Sa. + + Default: 60 (261.6 Hz, `C4`) + + mela : int or str + The name or index of the melakarta raga + + abbr : bool + If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...) + + If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information and subscript + numbers. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given MIDI number(s) + + See Also + -------- + hz_to_svara_c + note_to_svara_c + mela_to_degrees + mela_to_svara + list_mela + """ + svara_num = int(np.round(midi - Sa)) + + svara_map = notation.mela_to_svara(mela, abbr=abbr, unicode=unicode) + + svara = svara_map[svara_num % 12] + + if octave: + if 24 > svara_num >= 12: + if unicode: + svara = svara[0] + "\u0307" + svara[1:] + else: + svara += "'" + elif -12 <= svara_num < 0: + if unicode: + svara = svara[0] + "\u0323" + svara[1:] + else: + svara += "," + + return svara + + +@overload +def hz_to_svara_c( + frequencies: float, + *, + Sa: float, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def hz_to_svara_c( + frequencies: np.ndarray, + *, + Sa: float, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def hz_to_svara_c( + frequencies: Union[float, np.ndarray], + *, + Sa: float, + mela: Union[int, str], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +def hz_to_svara_c( + frequencies: Union[float, np.ndarray], + *, + Sa: float, + mela: Union[int, str], + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert frequencies (in Hz) to Carnatic svara + + Note that this conversion assumes 12-tone equal temperament. + + Parameters + ---------- + frequencies : positive number or np.ndarray + The frequencies (in Hz) to convert + + Sa : positive number + Frequency (in Hz) of the reference Sa. + + mela : int [1, 72] or string + The melakarta raga to use. + + abbr : bool + If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...) + + If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + This only takes effect if `octave=True`. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given frequency/frequencies + + See Also + -------- + note_to_svara_c + midi_to_svara_c + hz_to_svara_h + hz_to_note + list_mela + + Examples + -------- + Convert Sa in three octaves: + + >>> librosa.hz_to_svara_c([261/2, 261, 261*2], Sa=261, mela='kanakangi') + ['SÌŁ', 'S', 'Ṡ'] + + Convert one octave worth of frequencies using melakarta #36: + + >>> freqs = librosa.cqt_frequencies(n_bins=12, fmin=261) + >>> librosa.hz_to_svara_c(freqs, Sa=freqs[0], mela=36) + ['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'D₂', 'D₃', 'N₃'] + """ + midis = hz_to_midi(frequencies) + return midi_to_svara_c( + midis, Sa=hz_to_midi(Sa), mela=mela, abbr=abbr, octave=octave, unicode=unicode + ) + + +@overload +def note_to_svara_c( + notes: str, + *, + Sa: str, + mela: Union[str, int], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def note_to_svara_c( + notes: _IterableLike[str], + *, + Sa: str, + mela: Union[str, int], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def note_to_svara_c( + notes: Union[str, _IterableLike[str]], + *, + Sa: str, + mela: Union[str, int], + abbr: bool = ..., + octave: bool = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +def note_to_svara_c( + notes: Union[str, _IterableLike[str]], + *, + Sa: str, + mela: Union[str, int], + abbr: bool = True, + octave: bool = True, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert western notes to Carnatic svara + + Note that this conversion assumes 12-tone equal temperament. + + Parameters + ---------- + notes : str or iterable of str + Notes to convert (e.g., `'C#'` or `['C4', 'Db4', 'D4']` + + Sa : str + Note corresponding to Sa (e.g., `'C'` or `'C5'`). + + If no octave information is provided, it will default to octave 0 + (``C0`` ~= 16 Hz) + + mela : str or int [1, 72] + Melakarta raga name or index + + abbr : bool + If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...) + + If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...) + + octave : bool + If `True`, decorate svara in neighboring octaves with over- or under-dots. + + If `False`, ignore octave height information. + + unicode : bool + If `True`, use unicode symbols to decorate octave information. + + If `False`, use low-order ASCII (' and ,) for octave decorations. + + This only takes effect if `octave=True`. + + Returns + ------- + svara : str or np.ndarray of str + The svara corresponding to the given notes + + See Also + -------- + midi_to_svara_c + hz_to_svara_c + note_to_svara_h + note_to_midi + note_to_hz + list_mela + + Examples + -------- + >>> librosa.note_to_svara_h(['C4', 'G4', 'C5', 'D5', 'G5'], Sa='C5', mela=1) + ['SÌŁ', 'PÌŁ', 'S', 'G₁', 'P'] + """ + midis = note_to_midi(notes, round_midi=False) + + return midi_to_svara_c( + midis, Sa=note_to_midi(Sa), mela=mela, abbr=abbr, octave=octave, unicode=unicode + ) + + +@overload +def hz_to_fjs( + frequencies: _FloatLike_co, + *, + fmin: Optional[float] = ..., + unison: Optional[str] = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def hz_to_fjs( + frequencies: _SequenceLike[_FloatLike_co], + *, + fmin: Optional[float] = ..., + unison: Optional[str] = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +def hz_to_fjs( + frequencies: _ScalarOrSequence[_FloatLike_co], + *, + fmin: Optional[float] = None, + unison: Optional[str] = None, + unicode: bool = False, +) -> Union[str, np.ndarray]: + """Convert one or more frequencies (in Hz) from a just intonation + scale to notes in FJS notation. + + Parameters + ---------- + frequencies : float or iterable of float + Input frequencies, specified in Hz + fmin : float (optional) + The minimum frequency, corresponding to a unison note. + If not provided, it will be inferred as `min(frequencies)` + unison : str (optional) + The name of the unison note. + If not provided, it will be inferred as the scientific pitch + notation name of `fmin`, that is, `hz_to_note(fmin)` + unicode : bool + If `True`, then unicode symbols are used for accidentals. + If `False`, then low-order ASCII symbols are used for accidentals. + + Returns + ------- + notes : str or np.ndarray(dtype=str) + ``notes[i]`` is the closest note name to ``frequency[i]`` + (or ``frequency`` if the input is scalar) + + See Also + -------- + hz_to_note + interval_to_fjs + + Examples + -------- + Get a single note name for a frequency, relative to A=55 Hz + + >>> librosa.hz_to_fjs(66, fmin=55, unicode=True) + 'C₅' + + Get notation for a 5-limit frequency set starting at A=55 + + >>> freqs = librosa.interval_frequencies(24, intervals="ji5", fmin=55) + >>> freqs + array([ 55. , 58.667, 61.875, 66. , 68.75 , 73.333, 77.344, + 82.5 , 88. , 91.667, 99. , 103.125, 110. , 117.333, + 123.75 , 132. , 137.5 , 146.667, 154.687, 165. , 176. , + 183.333, 198. , 206.25 ]) + >>> librosa.hz_to_fjs(freqs, unicode=True) + array(['A', 'B♭₅', 'B', 'C₅', 'C♯⁔', 'D', 'D♯⁔', 'E', 'F₅', 'F♯⁔', 'G₅', + 'G♯⁔', 'A', 'B♭₅', 'B', 'C₅', 'C♯⁔', 'D', 'D♯⁔', 'E', 'F₅', 'F♯⁔', + 'G₅', 'G♯⁔'], dtype=' None: + """Set the FFT library used by librosa. + + .. warning:: This functionality is deprecated in librosa 0.11 and will be + removed in 1.0. To achieve the same effect, use either the + `scipy.fft.set_backend` context manager or + `scipy.fft.set_global_backend` function. + + Parameters + ---------- + lib : None or module + Must implement an interface compatible with `scipy.fft`. + If ``None``, reverts to `scipy.fft`. + + Examples + -------- + Use `pyfftw`: + + >>> import pyfftw + >>> librosa.set_fftlib(pyfftw.interfaces.numpy_fft) + + Reset to default `scipy` implementation + + >>> librosa.set_fftlib() + """ + global __FFTLIB + if lib is None: + lib = scipy.fft + + __FFTLIB = lib + + +def get_fftlib() -> ModuleType: + """Get the FFT library currently used by librosa + + Returns + ------- + fft : module + The FFT library currently used by librosa. + Must API-compatible with `numpy.fft`. + """ + if __FFTLIB is None: + # This path should never occur because importing + # this module will call set_fftlib + assert False # pragma: no cover + + return __FFTLIB diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/harmonic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/harmonic.py new file mode 100644 index 0000000000000000000000000000000000000000..de029fe795fcbce013a82ed83e3fc6b4d9d1f7da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/harmonic.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Harmonic calculations for frequency representations""" + +import warnings + +import numpy as np +import scipy.interpolate +import scipy.signal +from ..util.exceptions import ParameterError +from ..util import is_unique +from numpy.typing import ArrayLike +from typing import Callable, Optional, Sequence + +__all__ = ["salience", "interp_harmonics", "f0_harmonics"] + + +def salience( + S: np.ndarray, + *, + freqs: np.ndarray, + harmonics: Sequence[float], + weights: Optional[ArrayLike] = None, + aggregate: Optional[Callable] = None, + filter_peaks: bool = True, + fill_value: float = np.nan, + kind: str = "linear", + axis: int = -2, +) -> np.ndarray: + """Harmonic salience function. + + Parameters + ---------- + S : np.ndarray [shape=(..., d, n)] + input time frequency magnitude representation (e.g. STFT or CQT magnitudes). + Must be real-valued and non-negative. + + freqs : np.ndarray, shape=(S.shape[axis]) or shape=S.shape + The frequency values corresponding to S's elements along the + chosen axis. + + Frequencies can also be time-varying, e.g. as computed by + `reassigned_spectrogram`, in which case the shape should + match ``S``. + + harmonics : list-like, non-negative + Harmonics to include in salience computation. The first harmonic (1) + corresponds to ``S`` itself. Values less than one (e.g., 1/2) correspond + to sub-harmonics. + + weights : list-like + The weight to apply to each harmonic in the summation. (default: + uniform weights). Must be the same length as ``harmonics``. + + aggregate : function + aggregation function (default: `np.average`) + + If ``aggregate=np.average``, then a weighted average is + computed per-harmonic according to the specified weights. + For all other aggregation functions, all harmonics + are treated equally. + + filter_peaks : bool + If true, returns harmonic summation only on frequencies of peak + magnitude. Otherwise returns harmonic summation over the full spectrum. + Defaults to True. + + fill_value : float + The value to fill non-peaks in the output representation. (default: + `np.nan`) Only used if ``filter_peaks == True``. + + kind : str + Interpolation type for harmonic estimation. + See `scipy.interpolate.interp1d`. + + axis : int + The axis along which to compute harmonics + + Returns + ------- + S_sal : np.ndarray + ``S_sal`` will have the same shape as ``S``, and measure + the overall harmonic energy at each frequency. + + See Also + -------- + interp_harmonics + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet'), duration=3) + >>> S = np.abs(librosa.stft(y)) + >>> freqs = librosa.fft_frequencies(sr=sr) + >>> harms = [1, 2, 3, 4] + >>> weights = [1.0, 0.5, 0.33, 0.25] + >>> S_sal = librosa.salience(S, freqs=freqs, harmonics=harms, weights=weights, fill_value=0) + >>> print(S_sal.shape) + (1025, 115) + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... sr=sr, y_axis='log', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='Magnitude spectrogram') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(S_sal, + ... ref=np.max), + ... sr=sr, y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Salience spectrogram') + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + """ + if aggregate is None: + aggregate = np.average + + if weights is None: + weights = np.ones((len(harmonics),)) + else: + weights = np.array(weights, dtype=float) + + S_harm = interp_harmonics(S, freqs=freqs, harmonics=harmonics, kind=kind, axis=axis) + + S_sal: np.ndarray + if aggregate is np.average: + S_sal = aggregate(S_harm, axis=axis - 1, weights=weights) + else: + S_sal = aggregate(S_harm, axis=axis - 1) + + if filter_peaks: + S_peaks = scipy.signal.argrelmax(S, axis=axis) + S_out = np.empty(S.shape) + S_out.fill(fill_value) + S_out[S_peaks] = S_sal[S_peaks] + + S_sal = S_out + + return S_sal + + +def interp_harmonics( + x: np.ndarray, + *, + freqs: np.ndarray, + harmonics: ArrayLike, + kind: str = "linear", + fill_value: float = 0, + axis: int = -2, +) -> np.ndarray: + """Compute the energy at harmonics of time-frequency representation. + + Given a frequency-based energy representation such as a spectrogram + or tempogram, this function computes the energy at the chosen harmonics + of the frequency axis. (See examples below.) + The resulting harmonic array can then be used as input to a salience + computation. + + Parameters + ---------- + x : np.ndarray + The input energy + freqs : np.ndarray, shape=(x.shape[axis]) or shape=x.shape + The frequency values corresponding to x's elements along the + chosen axis. + Frequencies can also be time-varying, e.g. as computed by + `reassigned_spectrogram`, in which case the shape should + match ``x``. + harmonics : list-like, non-negative + Harmonics to compute as ``harmonics[i] * freqs``. + The first harmonic (1) corresponds to ``freqs``. + Values less than one (e.g., 1/2) correspond to sub-harmonics. + kind : str + Interpolation type. See `scipy.interpolate.interp1d`. + fill_value : float + The value to fill when extrapolating beyond the observed + frequency range. + axis : int + The axis along which to compute harmonics + + Returns + ------- + x_harm : np.ndarray + ``x_harm[i]`` will have the same shape as ``x``, and measure + the energy at the ``harmonics[i]`` harmonic of each frequency. + A new dimension indexing harmonics will be inserted immediately + before ``axis``. + + See Also + -------- + scipy.interpolate.interp1d + + Examples + -------- + Estimate the harmonics of a time-averaged tempogram + + >>> y, sr = librosa.load(librosa.ex('sweetwaltz')) + >>> # Compute the time-varying tempogram and average over time + >>> tempi = np.mean(librosa.feature.tempogram(y=y, sr=sr), axis=1) + >>> # We'll measure the first five harmonics + >>> harmonics = [1, 2, 3, 4, 5] + >>> f_tempo = librosa.tempo_frequencies(len(tempi), sr=sr) + >>> # Build the harmonic tensor; we only have one axis here (tempo) + >>> t_harmonics = librosa.interp_harmonics(tempi, freqs=f_tempo, harmonics=harmonics, axis=0) + >>> print(t_harmonics.shape) + (5, 384) + + >>> # And plot the results + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> librosa.display.specshow(t_harmonics, x_axis='tempo', sr=sr, ax=ax) + >>> ax.set(yticks=np.arange(len(harmonics)), + ... yticklabels=['{:.3g}'.format(_) for _ in harmonics], + ... ylabel='Harmonic', xlabel='Tempo (BPM)') + + We can also compute frequency harmonics for spectrograms. + To calculate sub-harmonic energy, use values < 1. + + >>> y, sr = librosa.load(librosa.ex('trumpet'), duration=3) + >>> harmonics = [1./3, 1./2, 1, 2, 3, 4] + >>> S = np.abs(librosa.stft(y)) + >>> fft_freqs = librosa.fft_frequencies(sr=sr) + >>> S_harm = librosa.interp_harmonics(S, freqs=fft_freqs, harmonics=harmonics, axis=0) + >>> print(S_harm.shape) + (6, 1025, 646) + + >>> fig, ax = plt.subplots(nrows=3, ncols=2, sharex=True, sharey=True) + >>> for i, _sh in enumerate(S_harm): + ... img = librosa.display.specshow(librosa.amplitude_to_db(_sh, + ... ref=S.max()), + ... sr=sr, y_axis='log', x_axis='time', + ... ax=ax.flat[i]) + ... ax.flat[i].set(title='h={:.3g}'.format(harmonics[i])) + ... ax.flat[i].label_outer() + >>> fig.colorbar(img, ax=ax, format="%+2.f dB") + """ + if freqs.ndim == 1 and len(freqs) == x.shape[axis]: + # Build the 1-D interpolator. + # All frames have a common domain, so we only need one interpolator here. + + # First, verify that the input frequencies are unique + if not is_unique(freqs, axis=0): + warnings.warn( + "Frequencies are not unique. This may produce incorrect harmonic interpolations.", + stacklevel=2, + ) + + f_interp = scipy.interpolate.interp1d( + freqs, + x, + axis=axis, + bounds_error=False, + copy=False, + kind=kind, + fill_value=fill_value, + ) + + # Set the interpolation points + f_out = np.multiply.outer(harmonics, freqs) + + # Interpolate; suppress type checks + return f_interp(f_out) # type: ignore + + elif freqs.shape == x.shape: + if not np.all(is_unique(freqs, axis=axis)): + warnings.warn( + "Frequencies are not unique. This may produce incorrect harmonic interpolations.", + stacklevel=2, + ) + + # If we have time-varying frequencies, then it must match exactly the shape of the input + + # We'll define a frame-wise interpolator helper function that we will vectorize over + # the entire input array + def _f_interp(_a, _b): + interp = scipy.interpolate.interp1d( + _a, _b, bounds_error=False, copy=False, kind=kind, fill_value=fill_value + ) + + return interp(np.multiply.outer(_a, harmonics)) + + # Signature is expanding frequency into a new dimension + xfunc = np.vectorize(_f_interp, signature="(f),(f)->(f,h)") + + # Rotate the vectorizing axis to the tail so that we get parallelism over frames + # Afterward, we're swapping (-1, axis-1) instead of (-1,axis) + # because a new dimension has been inserted + return ( # type: ignore + xfunc(freqs.swapaxes(axis, -1), x.swapaxes(axis, -1)) + .swapaxes( + # Return the original target axis to its place + -2, + axis, + ) + .swapaxes( + # Put the new harmonic axis directly in front of the target axis + -1, + axis - 1, + ) + ) + else: + raise ParameterError( + f"freqs.shape={freqs.shape} is incompatible with input shape={x.shape}" + ) + + +def f0_harmonics( + x: np.ndarray, + *, + f0: np.ndarray, + freqs: np.ndarray, + harmonics: ArrayLike, + kind: str = "linear", + fill_value: float = 0, + axis: int = -2, +) -> np.ndarray: + """Compute the energy at selected harmonics of a time-varying + fundamental frequency. + + This function can be used to reduce a `frequency * time` representation + to a `harmonic * time` representation, effectively normalizing out for + the fundamental frequency. The result can be used as a representation + of timbre when f0 corresponds to pitch, or as a representation of + rhythm when f0 corresponds to tempo. + + This function differs from `interp_harmonics`, which computes the + harmonics of *all* frequencies. + + Parameters + ---------- + x : np.ndarray [shape=(..., frequencies, n)] + The input array (e.g., STFT magnitudes) + f0 : np.ndarray [shape=(..., n)] + The fundamental frequency (f0) of each frame in the input + Shape should match ``x.shape[-1]`` + freqs : np.ndarray, shape=(x.shape[axis]) or shape=x.shape + The frequency values corresponding to X's elements along the + chosen axis. + Frequencies can also be time-varying, e.g. as computed by + `reassigned_spectrogram`, in which case the shape should + match ``x``. + harmonics : list-like, non-negative + Harmonics to compute as ``harmonics[i] * f0`` + Values less than one (e.g., 1/2) correspond to sub-harmonics. + kind : str + Interpolation type. See `scipy.interpolate.interp1d`. + fill_value : float + The value to fill when extrapolating beyond the observed + frequency range. + axis : int + The axis corresponding to frequency in ``x`` + + Returns + ------- + f0_harm : np.ndarray [shape=(..., len(harmonics), n)] + Interpolated energy at each specified harmonic of the fundamental + frequency for each time step. + + See Also + -------- + interp_harmonics + librosa.feature.tempogram_ratio + + Examples + -------- + This example estimates the fundamental (f0), and then extracts the first + 12 harmonics + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> f0, voicing, voicing_p = librosa.pyin(y=y, sr=sr, fmin=200, fmax=700) + >>> S = np.abs(librosa.stft(y)) + >>> freqs = librosa.fft_frequencies(sr=sr) + >>> harmonics = np.arange(1, 13) + >>> f0_harm = librosa.f0_harmonics(S, freqs=freqs, f0=f0, harmonics=harmonics) + + >>> import matplotlib.pyplot as plt + >>> fig, ax =plt.subplots(nrows=2, sharex=True) + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... x_axis='time', y_axis='log', ax=ax[0]) + >>> times = librosa.times_like(f0) + >>> for h in harmonics: + ... ax[0].plot(times, h * f0, label=f"{h}*f0") + >>> ax[0].legend(ncols=4, loc='lower right') + >>> ax[0].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(f0_harm, ref=np.max), + ... x_axis='time', ax=ax[1]) + >>> ax[1].set_yticks(harmonics-1) + >>> ax[1].set_yticklabels(harmonics) + >>> ax[1].set(ylabel='Harmonics') + """ + result: np.ndarray + if freqs.ndim == 1 and len(freqs) == x.shape[axis]: + if not is_unique(freqs, axis=0): + warnings.warn( + "Frequencies are not unique. This may produce incorrect harmonic interpolations.", + stacklevel=2, + ) + + # We have a fixed frequency grid + idx = np.isfinite(freqs) + + def _f_interps(data, f): + interp = scipy.interpolate.interp1d( + freqs[idx], + data[idx], + axis=0, + bounds_error=False, + copy=False, + assume_sorted=False, + kind=kind, + fill_value=fill_value, + ) + return interp(f) + + xfunc = np.vectorize(_f_interps, signature="(f),(h)->(h)") + result = xfunc(x.swapaxes(axis, -1), np.multiply.outer(f0, harmonics)).swapaxes( + axis, -1 + ) + + elif freqs.shape == x.shape: + if not np.all(is_unique(freqs, axis=axis)): + warnings.warn( + "Frequencies are not unique. This may produce incorrect harmonic interpolations.", + stacklevel=2, + ) + + # We have a dynamic frequency grid, not so bad + def _f_interpd(data, frequencies, f): + idx = np.isfinite(frequencies) + interp = scipy.interpolate.interp1d( + frequencies[idx], + data[idx], + axis=0, + bounds_error=False, + copy=False, + assume_sorted=False, + kind=kind, + fill_value=fill_value, + ) + return interp(f) + + xfunc = np.vectorize(_f_interpd, signature="(f),(f),(h)->(h)") + result = xfunc( + x.swapaxes(axis, -1), + freqs.swapaxes(axis, -1), + np.multiply.outer(f0, harmonics), + ).swapaxes(axis, -1) + + else: + raise ParameterError( + f"freqs.shape={freqs.shape} is incompatible with input shape={x.shape}" + ) + + return np.nan_to_num(result, copy=False, nan=fill_value) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/intervals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/intervals.py new file mode 100644 index 0000000000000000000000000000000000000000..6e833c15f1afa9b661eff94c029959a3f367d231 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/intervals.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +"""Functions for interval construction""" + +from typing import Collection, Dict, List, Union, overload, Iterable +from typing_extensions import Literal +import msgpack +import numpy as np +from numpy.typing import ArrayLike +from .._cache import cache +from .._typing import _FloatLike_co +from ..util.files import _resource_file + + +with _resource_file("librosa.core", "intervals.msgpack") as imsgpack: + with imsgpack.open("rb") as _fdesc: + # We use floats for dictionary keys, so strict mapping is disabled + INTERVALS = msgpack.load(_fdesc, strict_map_key=False) + + +@cache(level=10) +def interval_frequencies( + n_bins: int, + *, + fmin: _FloatLike_co, + intervals: Union[str, Collection[float]], + bins_per_octave: int = 12, + tuning: float = 0.0, + sort: bool = True +) -> np.ndarray: + """Construct a set of frequencies from an interval set + + Parameters + ---------- + n_bins : int + The number of frequencies to generate + + fmin : float > 0 + The minimum frequency + + intervals : str or array of floats in [1, 2) + If `str`, must be one of the following: + - `'equal'` - equal temperament + - `'pythagorean'` - Pythagorean intervals + - `'ji3'` - 3-limit just intonation + - `'ji5'` - 5-limit just intonation + - `'ji7'` - 7-limit just intonation + + Otherwise, an array of intervals in the range [1, 2) can be provided. + + bins_per_octave : int > 0 + If `intervals` is a string specification, how many bins to + generate per octave. + If `intervals` is an array, then this parameter is ignored. + + tuning : float + Deviation from A440 tuning in fractional bins. + This is only used when `intervals == 'equal'` + + sort : bool + Sort the intervals in ascending order. + + Returns + ------- + frequencies : array of float + The frequencies + + Examples + -------- + Generate two octaves of Pythagorean intervals starting at 55Hz + + >>> librosa.interval_frequencies(24, fmin=55, intervals="pythagorean", bins_per_octave=12) + array([ 55. , 58.733, 61.875, 66.075, 69.609, 74.334, 78.311, + 82.5 , 88.099, 92.812, 99.112, 104.414, 110. , 117.466, + 123.75 , 132.149, 139.219, 148.668, 156.621, 165. , 176.199, + 185.625, 198.224, 208.828]) + + Generate two octaves of 5-limit intervals starting at 55Hz + + >>> librosa.interval_frequencies(24, fmin=55, intervals="ji5", bins_per_octave=12) + array([ 55. , 58.667, 61.875, 66. , 68.75 , 73.333, 77.344, + 82.5 , 88. , 91.667, 99. , 103.125, 110. , 117.333, + 123.75 , 132. , 137.5 , 146.667, 154.687, 165. , 176. , + 183.333, 198. , 206.25 ]) + + Generate three octaves using only three intervals + + >>> intervals = [1, 4/3, 3/2] + >>> librosa.interval_frequencies(9, fmin=55, intervals=intervals) + array([ 55. , 73.333, 82.5 , 110. , 146.667, 165. , 220. , + 293.333, 330. ]) + """ + if isinstance(intervals, str): + if intervals == "equal": + # Maybe include tuning here? + ratios = 2.0 ** ( + (tuning + np.arange(0, bins_per_octave, dtype=float)) / bins_per_octave + ) + elif intervals == "pythagorean": + ratios = pythagorean_intervals(bins_per_octave=bins_per_octave, sort=sort) + elif intervals == "ji3": + ratios = plimit_intervals( + primes=[3], bins_per_octave=bins_per_octave, sort=sort + ) + elif intervals == "ji5": + ratios = plimit_intervals( + primes=[3, 5], bins_per_octave=bins_per_octave, sort=sort + ) + elif intervals == "ji7": + ratios = plimit_intervals( + primes=[3, 5, 7], bins_per_octave=bins_per_octave, sort=sort + ) + else: + ratios = np.array(intervals) + bins_per_octave = len(ratios) + + # We have one octave of ratios, tile it up to however many we need + # and trim back to the right number of bins + n_octaves = np.ceil(n_bins / bins_per_octave) + all_ratios = np.multiply.outer(2.0 ** np.arange(n_octaves), ratios).flatten()[ + :n_bins + ] + + if sort: + all_ratios = np.sort(all_ratios) + + return all_ratios * fmin + + +@overload +def pythagorean_intervals( + *, + bins_per_octave: int = ..., + sort: bool = ..., + return_factors: Literal[False] = ... +) -> np.ndarray: + ... + + +@overload +def pythagorean_intervals( + *, bins_per_octave: int = ..., sort: bool = ..., return_factors: Literal[True] +) -> List[Dict[int, int]]: + ... + + +@overload +def pythagorean_intervals( + *, bins_per_octave: int = ..., sort: bool = ..., return_factors: bool = ... +) -> Union[np.ndarray, List[Dict[int, int]]]: + ... + + +@cache(level=10) +def pythagorean_intervals( + *, bins_per_octave: int = 12, sort: bool = True, return_factors: bool = False +) -> Union[np.ndarray, List[Dict[int, int]]]: + """Pythagorean intervals + + Intervals are constructed by stacking ratios of 3/2 (i.e., + just perfect fifths) and folding down to a single octave:: + + 1, 3/2, 9/8, 27/16, 81/64, ... + + Note that this differs from 3-limit just intonation intervals + in that Pythagorean intervals only use positive powers of 3 + (ascending fifths) while 3-limit intervals use both positive + and negative powers (descending fifths). + + Parameters + ---------- + bins_per_octave : int + The number of intervals to generate + sort : bool + If `True` then intervals are returned in ascending order. + If `False`, then intervals are returned in circle-of-fifths order. + return_factors : bool + If `True` then return a list of dictionaries encoding the prime factorization + of each interval as `{2: p2, 3: p3}` (meaning `3**p3 * 2**p2`). + If `False` (default), return intervals as an array of floating point numbers. + + Returns + ------- + intervals : np.ndarray or list of dictionaries + The constructed interval set. All intervals are mapped + to the range [1, 2). + + See Also + -------- + plimit_intervals + + Examples + -------- + Generate the first 12 intervals + + >>> librosa.pythagorean_intervals(bins_per_octave=12) + array([1. , 1.067871, 1.125 , 1.201355, 1.265625, 1.351524, + 1.423828, 1.5 , 1.601807, 1.6875 , 1.802032, 1.898437]) + >>> # Compare to the 12-tone equal temperament intervals: + >>> 2**(np.arange(12)/12) + array([1. , 1.059463, 1.122462, 1.189207, 1.259921, 1.33484 , + 1.414214, 1.498307, 1.587401, 1.681793, 1.781797, 1.887749]) + + Or the first 7, in circle-of-fifths order + + >>> librosa.pythagorean_intervals(bins_per_octave=7, sort=False) + array([1. , 1.5 , 1.125 , 1.6875 , 1.265625, 1.898437, + 1.423828]) + + Generate the first 7, in circle-of-fifths other and factored form + + >>> librosa.pythagorean_intervals(bins_per_octave=7, sort=False, return_factors=True) + [ + {2: 0, 3: 0}, + {2: -1, 3: 1}, + {2: -3, 3: 2}, + {2: -4, 3: 3}, + {2: -6, 3: 4}, + {2: -7, 3: 5}, + {2: -9, 3: 6} + ] + """ + # Generate all powers of 3 in log space + pow3 = np.arange(bins_per_octave) + + # Using modf here to quickly get the fractional part of the log, + # accounting for whatever power of 2 is necessary to get 3**k + # within the octave. + log_ratios: np.ndarray + pow2: np.ndarray + log_ratios, pow2 = np.modf(pow3 * np.log2(3)) + + # If the fractional part is negative, add + # one more power of two to get it into the range [0, 1). + too_small = log_ratios < 0 + log_ratios[too_small] += 1 + pow2[too_small] += 1 + + # Convert powers of 2 to integer + pow2 = pow2.astype(int) + + idx: Iterable[int] + + if sort: + # Order the intervals + idx = np.argsort(log_ratios) + log_ratios = log_ratios[idx] + else: + # If not sorting, we'll take powers in order + idx = range(bins_per_octave) + + if return_factors: + return list({2: -pow2[i], 3: pow3[i]} for i in idx) + + return np.power(2, log_ratios) + + +def __harmonic_distance(logs, a, b): + """Compute the harmonic distance between ratios a and b. + + Harmonic distance is defined as `log2(a * b) - 2*log2(gcd(a, b))` [#]_. + + Here we are expressing a and b as prime factorization exponents, + and the prime basis are provided in their log2 form. + + .. [#] Tenney, James. + "On ‘Crystal Growth’ in harmonic space (1993–1998)." + Contemporary Music Review 27.1 (2008): 47-56. + """ + a = np.array(a) + b = np.array(b) + + # numerator = positive exponents + a_num = np.maximum(a, 0) + # denominator = negative exponents + a_den = a_num - a + + b_num = np.maximum(b, 0) + b_den = b_num - b + + # log2(ab / gcd(a,b)**2) = log(a) + log(b) - 2 * log(gcd(a,b)) + # gcd(a,b) for rationals: gcd(a_num, b_num) / lcm(a_den, b_den) + # gcd = minimum(a_num, b_num) and lcm = maximum(a_den, b_den) + gcd = np.minimum(a_num, b_num) - np.maximum(a_den, b_den) + + # Rounding this to 6 decimals to avoid floating point weirdness + return np.around(logs.dot(a + b - 2 * gcd), 6) + + +def _crystal_tie_break(a, b, logs): + """Given two tuples of prime powers, break ties.""" + return logs.dot(np.abs(a)) < logs.dot(np.abs(b)) + + +@overload +def plimit_intervals( + *, + primes: ArrayLike, + bins_per_octave: int = ..., + sort: bool = ..., + return_factors: Literal[False] = ... +) -> np.ndarray: + ... + + +@overload +def plimit_intervals( + *, + primes: ArrayLike, + bins_per_octave: int = ..., + sort: bool = ..., + return_factors: Literal[True] +) -> List[Dict[int, int]]: + ... + + +@overload +def plimit_intervals( + *, + primes: ArrayLike, + bins_per_octave: int = ..., + sort: bool = ..., + return_factors: bool = ... +) -> Union[np.ndarray, List[Dict[int, int]]]: + ... + + +@cache(level=10) +def plimit_intervals( + *, + primes: ArrayLike, + bins_per_octave: int = 12, + sort: bool = True, + return_factors: bool = False +) -> Union[np.ndarray, List[Dict[int, int]]]: + """Construct p-limit intervals for a given set of prime factors. + + This function is based on the "harmonic crystal growth" algorithm + of [#1]_ [#2]_. + + .. [#1] Tenney, James. + "On ‘Crystal Growth’ in harmonic space (1993–1998)." + Contemporary Music Review 27.1 (2008): 47-56. + + .. [#2] Sabat, Marc, and James Tenney. + "Three crystal growth algorithms in 23-limit constrained harmonic space." + Contemporary Music Review 27, no. 1 (2008): 57-78. + + Parameters + ---------- + primes : array of odd primes + Which prime factors are to be used + bins_per_octave : int + The number of intervals to construct + sort : bool + If `True` then intervals are returned in ascending order. + If `False`, then intervals are returned in crystal growth order. + return_factors : bool + If `True` then return a list of dictionaries encoding the prime factorization + of each interval as `{2: p2, 3: p3, ...}` (meaning `3**p3 * 2**p2`). + If `False` (default), return intervals as an array of floating point numbers. + + Returns + ------- + intervals : np.ndarray or list of dictionaries + The constructed interval set. All intervals are mapped + to the range [1, 2). + + See Also + -------- + pythagorean_intervals + + Examples + -------- + Compare 3-limit tuning to Pythagorean tuning and 12-TET + + >>> librosa.plimit_intervals(primes=[3], bins_per_octave=12) + array([1. , 1.05349794, 1.125 , 1.18518519, 1.265625 , + 1.33333333, 1.40466392, 1.5 , 1.58024691, 1.6875 , + 1.77777778, 1.8984375 ]) + >>> # Pythagorean intervals: + >>> librosa.pythagorean_intervals(bins_per_octave=12) + array([1. , 1.06787109, 1.125 , 1.20135498, 1.265625 , + 1.35152435, 1.42382812, 1.5 , 1.60180664, 1.6875 , + 1.80203247, 1.8984375 ]) + >>> # 12-TET intervals: + >>> 2**(np.arange(12)/12) + array([1. , 1.05946309, 1.12246205, 1.18920712, 1.25992105, + 1.33483985, 1.41421356, 1.49830708, 1.58740105, 1.68179283, + 1.78179744, 1.88774863]) + + Create a 7-bin, 5-limit interval set + + >>> librosa.plimit_intervals(primes=[3, 5], bins_per_octave=7) + array([1. , 1.125 , 1.25 , 1.33333333, 1.5 , + 1.66666667, 1.875 ]) + + The same example, but now in factored form + + >>> librosa.plimit_intervals(primes=[3, 5], bins_per_octave=7, + ... return_factors=True) + [ + {}, + {2: -3, 3: 2}, + {2: -2, 5: 1}, + {2: 2, 3: -1}, + {2: -1, 3: 1}, + {3: -1, 5: 1}, + {2: -3, 3: 1, 5: 1} + ] + """ + primes = np.atleast_1d(primes) + logs = np.log2(primes, dtype=np.float64) + + # The seed set are primes and their reciprocals + # These are the values that we can use to expand our + # interval set. These are expressed in terms of the + # prime factorization exponents + seeds = [] + for i in range(len(primes)): + # Add the prime + seed = [0] * len(primes) + seed[i] = 1 + seeds.append(tuple(seed)) + # Add the inverse + seed[i] = -1 + seeds.append(tuple(seed)) + + # The frontier is the set of candidate intervals for inclusion + frontier = seeds.copy() + + # The distances table will let us keep track of the harmonic + # distances between all selected intervals + distances = dict() + + # Initialize the interval set with the root (1) + intervals = list() + root = tuple([0] * len(primes)) + intervals.append(root) + + while len(intervals) < bins_per_octave: + # Find the element on the frontier that minimizes the total + # harmonic distance to the existing set + score = np.inf + best_f = 0 + for f, point in enumerate(frontier): + # Compute harmonic distance (HD) to each selected interval + HD = 0.0 + + for s in intervals: + if (s, point) not in distances: + distances[s, point] = __harmonic_distance(logs, point, s) + distances[point, s] = distances[s, point] + + HD += distances[s, point] + + if HD < score or ( + np.isclose(HD, score) + and _crystal_tie_break(point, frontier[best_f], logs) + ): + score = HD + best_f = f + + new_point = frontier.pop(best_f) + intervals.append(new_point) + + for _ in seeds: + new_seed = tuple(np.array(new_point) + np.array(_)) + if new_seed not in intervals and new_seed not in frontier: + frontier.append(new_seed) + + pows = np.array(list(intervals), dtype=float) + + log_ratios: np.ndarray + pow2: np.ndarray + log_ratios, pow2 = np.modf(pows.dot(logs)) + + # If the fractional part is negative, add + # one more power of two to get it into the range [0, 1). + too_small = log_ratios < 0 + log_ratios[too_small] += 1 + pow2[too_small] -= 1 + + # Convert powers of 2 to integer + pow2 = pow2.astype(int) + + idx: Iterable[int] + if sort: + # Order the intervals + idx = np.argsort(log_ratios) + log_ratios = log_ratios[idx] + else: + # If not sorting, we'll take powers in order + idx = range(bins_per_octave) + + if return_factors: + # Collect the factorized intervals into a list + factors = [] + for i in idx: + v = dict() + if pow2[i] != 0: + v[2] = -pow2[i] + + v.update({p: int(power) for p, power in zip(primes, pows[i]) if power != 0}) + + factors.append(v) + return factors + + # Otherwise, just return intervals as floats + return np.power(2, log_ratios) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/notation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/notation.py new file mode 100644 index 0000000000000000000000000000000000000000..18be3c9f9593a728a88a02ca816227e86886f7f3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/notation.py @@ -0,0 +1,1225 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Music notation utilities""" + +import re +import numpy as np +from numba import jit +from collections import Counter +from .intervals import INTERVALS +from .._cache import cache +from ..util.exceptions import ParameterError +from typing import Dict, List, Iterable, Union, overload +from ..util.decorators import vectorize +from .._typing import _ScalarOrSequence, _FloatLike_co, _SequenceLike, _IterableLike + + +__all__ = [ + "key_to_degrees", + "key_to_notes", + "mela_to_degrees", + "mela_to_svara", + "thaat_to_degrees", + "list_mela", + "list_thaat", + "fifths_to_note", + "interval_to_fjs", +] + +THAAT_MAP = dict( + bilaval=[0, 2, 4, 5, 7, 9, 11], + khamaj=[0, 2, 4, 5, 7, 9, 10], + kafi=[0, 2, 3, 5, 7, 9, 10], + asavari=[0, 2, 3, 5, 7, 8, 10], + bhairavi=[0, 1, 3, 5, 7, 8, 10], + kalyan=[0, 2, 4, 6, 7, 9, 11], + marva=[0, 1, 4, 6, 7, 9, 11], + poorvi=[0, 1, 4, 6, 7, 8, 11], + todi=[0, 1, 3, 6, 7, 8, 11], + bhairav=[0, 1, 4, 5, 7, 8, 11], +) + +# Enumeration will start from 1 +MELAKARTA_MAP = { + k: i + for i, k in enumerate( + [ + "kanakangi", + "ratnangi", + "ganamurthi", + "vanaspathi", + "manavathi", + "tanarupi", + "senavathi", + "hanumathodi", + "dhenuka", + "natakapriya", + "kokilapriya", + "rupavathi", + "gayakapriya", + "vakulabharanam", + "mayamalavagaula", + "chakravakom", + "suryakantham", + "hatakambari", + "jhankaradhwani", + "natabhairavi", + "keeravani", + "kharaharapriya", + "gaurimanohari", + "varunapriya", + "mararanjini", + "charukesi", + "sarasangi", + "harikambhoji", + "dheerasankarabharanam", + "naganandini", + "yagapriya", + "ragavardhini", + "gangeyabhushani", + "vagadheeswari", + "sulini", + "chalanatta", + "salagam", + "jalarnavam", + "jhalavarali", + "navaneetham", + "pavani", + "raghupriya", + "gavambodhi", + "bhavapriya", + "subhapanthuvarali", + "shadvidhamargini", + "suvarnangi", + "divyamani", + "dhavalambari", + "namanarayani", + "kamavardhini", + "ramapriya", + "gamanasrama", + "viswambhari", + "syamalangi", + "shanmukhapriya", + "simhendramadhyamam", + "hemavathi", + "dharmavathi", + "neethimathi", + "kanthamani", + "rishabhapriya", + "latangi", + "vachaspathi", + "mechakalyani", + "chitrambari", + "sucharitra", + "jyotisvarupini", + "dhatuvardhini", + "nasikabhushani", + "kosalam", + "rasikapriya", + ], + 1, + ) +} + + +# Pre-compiled regular expressions for note and key parsing +KEY_RE = re.compile( + r"^(?P[A-Ga-g])" + r"(?P[#♯đ„Șb!â™­đ„«â™źn]*)" + r":((?P(maj|min)(or)?)|(?P(((ion|dor|phryg|lyd|mixolyd|aeol|locr)(ian)?)|phr|mix|aeo|loc)))$" +) + +NOTE_RE = re.compile( + r"^(?P[A-Ga-g])" + r"(?P[#♯đ„Șb!â™­đ„«â™źn]*)" + r"(?P[+-]?\d+)?" + r"(?P[+-]\d+)?$" +) +# A dictionary converting the tonic name to the associated major key, e.g. C Dorian uses the notes of the Bb major scale, hence MAJOR_DICT['dor']['C'] = 'B♭' +MAJOR_DICT = { + 'ion': {'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F', 'G': 'G', 'A': 'A', 'B': 'B'}, + 'dor': {'C': 'B♭', 'D': 'C', 'E': 'D', 'F': 'E♭', 'G': 'F', 'A': 'G', 'B': 'A'}, + 'phr': {'C': 'A♭', 'D': 'B♭', 'E': 'C', 'F': 'D♭', 'G': 'E♭', 'A': 'F', 'B': 'G'}, + 'lyd': {'C': 'G', 'D': 'A', 'E': 'B', 'F': 'C', 'G': 'D', 'A': 'E', 'B': 'F♯'}, + 'mix': {'C': 'F', 'D': 'G', 'E': 'A', 'F': 'B♭', 'G': 'C', 'A': 'D', 'B': 'E'}, + 'aeo': {'C': 'E♭', 'D': 'F', 'E': 'G', 'F': 'A♭', 'G': 'B♭', 'A': 'C', 'B': 'D'}, + 'loc': {'C': 'D♭', 'D': 'E♭', 'E': 'F', 'F': 'G♭', 'G': 'A♭', 'A': 'B♭', 'B': 'C'} +} + +OFFSET_DICT = { "ion": 0, "dor": 1, "phr": 2, "lyd": 3, "mix": 4, "aeo": 5, "loc": 6 } + +ACC_MAP = {"#": 1, "♼": 0, "": 0, "n": 0, "b": -1, "!": -1, "♯": 1, "♭": -1, "đ„Ș": 2, "đ„«": -2} + + +def thaat_to_degrees(thaat: str) -> np.ndarray: + """Construct the svara indices (degrees) for a given thaat + + Parameters + ---------- + thaat : str + The name of the thaat + + Returns + ------- + indices : np.ndarray + A list of the seven svara indices (starting from 0=Sa) + contained in the specified thaat + + See Also + -------- + key_to_degrees + mela_to_degrees + list_thaat + + Examples + -------- + >>> librosa.thaat_to_degrees('bilaval') + array([ 0, 2, 4, 5, 7, 9, 11]) + + >>> librosa.thaat_to_degrees('todi') + array([ 0, 1, 3, 6, 7, 8, 11]) + """ + return np.asarray(THAAT_MAP[thaat.lower()]) + + +def mela_to_degrees(mela: Union[str, int]) -> np.ndarray: + """Construct the svara indices (degrees) for a given melakarta raga + + Parameters + ---------- + mela : str or int + Either the name or integer index ([1, 2, ..., 72]) of the melakarta raga + + Returns + ------- + degrees : np.ndarray + A list of the seven svara indices (starting from 0=Sa) + contained in the specified raga + + See Also + -------- + thaat_to_degrees + key_to_degrees + list_mela + + Examples + -------- + Melakarta #1 (kanakangi): + + >>> librosa.mela_to_degrees(1) + array([0, 1, 2, 5, 7, 8, 9]) + + Or using a name directly: + + >>> librosa.mela_to_degrees('kanakangi') + array([0, 1, 2, 5, 7, 8, 9]) + """ + if isinstance(mela, str): + index = MELAKARTA_MAP[mela.lower()] - 1 + elif 0 < mela <= 72: + index = mela - 1 + else: + raise ParameterError(f"mela={mela} must be in range [1, 72]") + + # always have Sa [0] + degrees = [0] + + # Fill in Ri and Ga + lower = index % 36 + if 0 <= lower < 6: + # Ri1, Ga1 + degrees.extend([1, 2]) + elif 6 <= lower < 12: + # Ri1, Ga2 + degrees.extend([1, 3]) + elif 12 <= lower < 18: + # Ri1, Ga3 + degrees.extend([1, 4]) + elif 18 <= lower < 24: + # Ri2, Ga2 + degrees.extend([2, 3]) + elif 24 <= lower < 30: + # Ri2, Ga3 + degrees.extend([2, 4]) + else: + # Ri3, Ga3 + degrees.extend([3, 4]) + + # Determine Ma + if index < 36: + # Ma1 + degrees.append(5) + else: + # Ma2 + degrees.append(6) + + # always have Pa [7] + degrees.append(7) + + # Determine Dha and Ni + upper = index % 6 + if upper == 0: + # Dha1, Ni1 + degrees.extend([8, 9]) + elif upper == 1: + # Dha1, Ni2 + degrees.extend([8, 10]) + elif upper == 2: + # Dha1, Ni3 + degrees.extend([8, 11]) + elif upper == 3: + # Dha2, Ni2 + degrees.extend([9, 10]) + elif upper == 4: + # Dha2, Ni3 + degrees.extend([9, 11]) + else: + # Dha3, Ni3 + degrees.extend([10, 11]) + + return np.array(degrees) + + +@cache(level=10) +def mela_to_svara( + mela: Union[str, int], *, abbr: bool = True, unicode: bool = True +) -> List[str]: + """Spell the Carnatic svara names for a given melakarta raga + + This function exists to resolve enharmonic equivalences between + pitch classes: + + - Ri2 / Ga1 + - Ri3 / Ga2 + - Dha2 / Ni1 + - Dha3 / Ni2 + + For svara outside the raga, names are chosen to preserve orderings + so that all Ri precede all Ga, and all Dha precede all Ni. + + Parameters + ---------- + mela : str or int + the name or numerical index of the melakarta raga + + abbr : bool + If `True`, use single-letter svara names: S, R, G, ... + + If `False`, use full names: Sa, Ri, Ga, ... + + unicode : bool + If `True`, use unicode symbols for numberings, e.g., Ri\u2081 + + If `False`, use low-order ASCII, e.g., Ri1. + + Returns + ------- + svara : list of strings + + The svara names for each of the 12 pitch classes. + + See Also + -------- + key_to_notes + mela_to_degrees + list_mela + + Examples + -------- + Melakarta #1 (Kanakangi) uses R1, G1, D1, N1 + + >>> librosa.mela_to_svara(1) + ['S', 'R₁', 'G₁', 'G₂', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'N₁', 'N₂', 'N₃'] + + #19 (Jhankaradhwani) uses R2 and G2 so the third svara are Ri: + + >>> librosa.mela_to_svara(19) + ['S', 'R₁', 'R₂', 'G₂', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'N₁', 'N₂', 'N₃'] + + #31 (Yagapriya) uses R3 and G3, so third and fourth svara are Ri: + + >>> librosa.mela_to_svara(31) + ['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'N₁', 'N₂', 'N₃'] + + #34 (Vagadheeswari) uses D2 and N2, so Ni1 becomes Dha2: + + >>> librosa.mela_to_svara(34) + ['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'D₂', 'N₂', 'N₃'] + + #36 (Chalanatta) uses D3 and N3, so Ni2 becomes Dha3: + + >>> librosa.mela_to_svara(36) + ['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'D₂', 'D₃', 'N₃'] + + # You can also query by raga name instead of index: + + >>> librosa.mela_to_svara('chalanatta') + ['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'D₂', 'D₃', 'N₃'] + """ + # The following will be constant for all ragas + svara_map = [ + "Sa", + "Ri\u2081", + "", # Ri2/Ga1 + "", # Ri3/Ga2 + "Ga\u2083", + "Ma\u2081", + "Ma\u2082", + "Pa", + "Dha\u2081", + "", # Dha2/Ni1 + "", # Dha3/Ni2 + "Ni\u2083", + ] + + if isinstance(mela, str): + mela_idx = MELAKARTA_MAP[mela.lower()] - 1 + elif 0 < mela <= 72: + mela_idx = mela - 1 + else: + raise ParameterError(f"mela={mela} must be in range [1, 72]") + + # Determine Ri2/Ga1 + lower = mela_idx % 36 + if lower < 6: + # First six will have Ri1/Ga1 + svara_map[2] = "Ga\u2081" + else: + # All others have either Ga2/Ga3 + # So we'll call this Ri2 + svara_map[2] = "Ri\u2082" + + # Determine Ri3/Ga2 + if lower < 30: + # First thirty should get Ga2 + svara_map[3] = "Ga\u2082" + else: + # Only the last six have Ri3 + svara_map[3] = "Ri\u2083" + + upper = mela_idx % 6 + + # Determine Dha2/Ni1 + if upper == 0: + # these are the only ones with Ni1 + svara_map[9] = "Ni\u2081" + else: + # Everyone else has Dha2 + svara_map[9] = "Dha\u2082" + + # Determine Dha3/Ni2 + if upper == 5: + # This one has Dha3 + svara_map[10] = "Dha\u2083" + else: + # Everyone else has Ni2 + svara_map[10] = "Ni\u2082" + + if abbr: + t_abbr = str.maketrans({"a": "", "h": "", "i": ""}) + svara_map = [s.translate(t_abbr) for s in svara_map] + + if not unicode: + t_uni = str.maketrans({"\u2081": "1", "\u2082": "2", "\u2083": "3"}) + svara_map = [s.translate(t_uni) for s in svara_map] + + return list(svara_map) + + +def list_mela() -> Dict[str, int]: + """List melakarta ragas by name and index. + + Melakarta raga names are transcribed from [#]_, with the exception of #45 + (subhapanthuvarali). + + .. [#] Bhagyalekshmy, S. (1990). + Ragas in Carnatic music. + South Asia Books. + + Returns + ------- + mela_map : dict + A dictionary mapping melakarta raga names to indices (1, 2, ..., 72) + + Examples + -------- + >>> librosa.list_mela() + {'kanakangi': 1, + 'ratnangi': 2, + 'ganamurthi': 3, + 'vanaspathi': 4, + ...} + + See Also + -------- + mela_to_degrees + mela_to_svara + list_thaat + """ + return MELAKARTA_MAP.copy() + + +def list_thaat() -> List[str]: + """List supported thaats by name. + + Returns + ------- + thaats : list + A list of supported thaats + + Examples + -------- + >>> librosa.list_thaat() + ['bilaval', + 'khamaj', + 'kafi', + 'asavari', + 'bhairavi', + 'kalyan', + 'marva', + 'poorvi', + 'todi', + 'bhairav'] + + See Also + -------- + list_mela + thaat_to_degrees + """ + return list(THAAT_MAP.keys()) + +@overload +def __note_to_degree(key: str) -> int: + ... +@overload +def __note_to_degree(key: _IterableLike[str]) -> np.ndarray: + ... +@overload +def __note_to_degree(key: Union[str, _IterableLike[str], Iterable[str]]) -> Union[int, np.ndarray]: + ... +def __note_to_degree(key: Union[str, _IterableLike[str], Iterable[str]]) -> Union[int,np.ndarray]: + """Take a note name and return the degree of that note (e.g. 'C#' -> 1). We allow possibilities like "C#b". + + >>> librosa.__note_to_degree('B#') + 0 + + >>> librosa.__note_to_degree('D♼##b') + 3 + + >>> librosa.__note_to_degree(['B#','D♼##b']) + array([0,3]) + + """ + if not isinstance(key, str): + return np.array([__note_to_degree(n) for n in key]) + + + match = NOTE_RE.match(key) + + if not match: + raise ParameterError(f"Improper key format: {key:s}") + + letter = match.group('note').upper() + accidental = match.group('accidental') + pitch_map = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} + counter = Counter(accidental) + return (pitch_map[letter]+sum([ACC_MAP[acc] * counter[acc] for acc in ACC_MAP]))%12 + +@overload +def __simplify_note(key: str, additional_acc: str =..., unicode: bool= ...) -> str: + ... + +@overload +def __simplify_note(key: _IterableLike[str], additional_acc: str=..., unicode: bool = ... ) -> np.ndarray: + ... + +@overload +def __simplify_note(key: Union[str, _IterableLike[str], Iterable[str]], additional_acc: str =..., unicode: bool = ...) -> Union[str, np.ndarray]: + ... + +def __simplify_note(key: Union[str, _IterableLike[str], Iterable[str]], additional_acc: str='', unicode: bool = True) -> Union[str, np.ndarray]: + """Take in a note name and simplify by canceling sharp-flat pairs, and doubling accidentals as appropriate. + + >>> librosa.__simplify_note('C♭♯') + 'C' + + >>> librosa.__simplify_note('C♭♭♭') + 'Câ™­đ„«' + + >>> librosa.__simplify_note(['C♭♯', 'C♭♭♭']) + array(['C', 'Câ™­đ„«'], dtype='=0: + simplified_note += "♯"*(offset%2)+ "đ„Ș"*(offset//2) + else: + simplified_note += "♭"*(offset%2)+ "đ„«"*(abs(offset)//2) + + if not unicode: + translations = str.maketrans({"♯": "#", "đ„Ș": "##", "♭": "b", "đ„«": "bb", "♼": "n"}) + simplified_note = simplified_note.translate(translations) + + return simplified_note + +def __mode_to_key(signature: str, unicode: bool = True) -> str: + """Translate a mode (eg D:dorian) into its equivalent major key. If unicode==True, return the accidentals as unicode symbols, regardless of nature of accidentals in signature. Otherwise, return accidentals as ASCII symbols. + + >>> librosa.__mode_to_key('Db:loc') + 'Eđ„«:maj' + + >>> librosa.__mode_to_key('D♭:loc', unicode = False) + 'Ebb:maj' + + """ + match = KEY_RE.match(signature) + + if not match: + raise ParameterError("Improper format: {:s}".format(signature)) + + if match.group('scale') or not match.group("mode"): + # We're already fine here, but let's pass the key through __simpify_note() to ensure good formatting. + signature = __simplify_note(match.group("tonic").upper()+match.group('accidental'), unicode=unicode)+(':'+match.group("scale") if match.group("scale") else '') + return signature + + # We have a mode, time to translate + mode = match.group("mode").lower()[:3] + + # Get the relative major + tonic = MAJOR_DICT[mode][match.group("tonic").upper()] + + return __simplify_note(tonic+match.group("accidental"), unicode = unicode)+":maj" + +@cache(level=10) +def key_to_notes(key: str, *, unicode: bool = True, natural: bool= False) -> List[str]: + """List all 12 note names in the chromatic scale, as spelled according to + a given key (major or minor) or mode (see below for details and accepted abbreviations). + + This function exists to resolve enharmonic equivalences between different + spellings for the same pitch (e.g. C♯ vs D♭), and is primarily useful when producing + human-readable outputs (e.g. plotting) for pitch content. + + Note names are decided by the following rules: + + 1. If the tonic of the key has an accidental (sharp or flat), that accidental will be + used consistently for all notes. + + 2. If the tonic does not have an accidental, accidentals will be inferred to minimize + the total number used for diatonic scale degrees. + + 3. If there is a tie (e.g., in the case of C:maj vs A:min), sharps will be preferred. + + Parameters + ---------- + key : string + Must be in the form TONIC:key. Tonic must be upper case (``CDEFGAB``), + key must be lower-case + (``major``, ``minor``, ``ionian``, ``dorian``, ``phrygian``, ``lydian``, ``mixolydian``, ``aeolian``, ``locrian``). + + The following abbreviations are supported for the modes: either the first three letters of the mode name + (e.g. "mix") or the mode name without "ian" (e.g. "mixolyd"). + + Both ``major`` and ``maj`` are supported as mode abbreviations. + + Single and multiple accidentals (``b!♭`` for flat, ``#♯`` for sharp, ``đ„Șđ„«`` for double-accidentals, or any combination thereof) are supported. + + Examples: ``C:maj, C:major, Dbb:min, A♭:min, D:aeo, Eđ„Ș:phryg``. + + unicode : bool + If ``True`` (default), use Unicode symbols (♯đ„Șâ™­đ„«)for accidentals. + + If ``False``, Unicode symbols will be mapped to low-order ASCII representations:: + + ♯ -> #, đ„Ș -> ##, ♭ -> b, đ„« -> bb, ♼ -> n + + natural : bool + If ``True'', mark natural accidentals with a natural symbol (♼). + + If ``False`` (default), do not print natural symbols. + + For example, `note_to_degrees('D:maj')[0]` is `C` if `natural=False` (default) and `C♼` if `natural=True`. + + Returns + ------- + notes : list + ``notes[k]`` is the name for semitone ``k`` (starting from C) + under the given key. All chromatic notes (0 through 11) are + included. + + See Also + -------- + midi_to_note + + Examples + -------- + `C:maj` will use all sharps + + >>> librosa.key_to_notes('C:maj') + ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'] + + `A:min` has the same notes + + >>> librosa.key_to_notes('A:min') + ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'] + + `A♯:min` will use sharps, but spell note 0 (`C`) as `B♯` + + >>> librosa.key_to_notes('A#:min') + ['B♯', 'C♯', 'D', 'D♯', 'E', 'E♯', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'] + + `G♯:maj` will use a double-sharp to spell note 7 (`G`) as `Fđ„Ș`: + + >>> librosa.key_to_notes('G#:maj') + ['B♯', 'C♯', 'D', 'D♯', 'E', 'E♯', 'F♯', 'Fđ„Ș', 'G♯', 'A', 'A♯', 'B'] + + `F♭:min` will use double-flats + + >>> librosa.key_to_notes('Fb:min') + ['Dđ„«', 'D♭', 'Eđ„«', 'E♭', 'F♭', 'F', 'G♭', 'Ađ„«', 'A♭', 'Bđ„«', 'B♭', 'C♭'] + + `G:loc` uses flats + + >>> librosa.key_to_notes('G:loc') + ['C', 'D♭', 'D', 'E♭', 'E', 'F', 'G♭', 'G', 'A♭', 'A', 'B♭', 'B'] + + If `natural=True`, print natural accidentals. + + >>> librosa.key_to_notes('G:loc', natural=True) + ['C', 'D♭', 'D♼', 'E♭', 'E♼', 'F', 'G♭', 'G', 'A♭', 'A♼', 'B♭', 'B♼'] + + >>> librosa.key_to_notes('D:maj', natural=True) + ['C♼', 'C♯', 'D', 'D♯', 'E', 'F♼', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'] + + >>> librosa.key_to_notes('G#:maj', unicode = False, natural = True) + ['B#', 'C#', 'Dn', 'D#', 'En', 'E#', 'F#', 'F##', 'G#', 'An', 'A#', 'B'] + + We can combine this with ``key_to_degrees`` to get the notes for a given scale: + + >>> notes = librosa.key_to_notes('D:maj') + >>> degrees = librosa.key_to_degrees('D:maj') + >>> print([notes[d] for d in degrees]) + ['D', 'E', 'F♯', 'G', 'A', 'B', 'C♯'] + """ + # Parse the key signature + match = KEY_RE.match(key) + + if not match: + raise ParameterError(f"Improper key format: {key:s}") + + pitch_map = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} + + tonic = match.group("tonic").upper() + accidental = match.group("accidental") + + offset = sum([ACC_MAP[acc] for acc in accidental]) + + if match.group('mode') or not match.group('scale'): + equiv = __mode_to_key(key) + return key_to_notes(equiv, unicode=unicode, natural = natural) + + scale = match.group("scale")[:3].lower() + + multiple = abs(offset)>=2 + + #If multiple accidentals, we use recursion, then cycle through so that the enharmonic equivalent of C is at the beginning again. + + if multiple: + sign_map = {+1: "♯", -1: "♭"} + additional_acc = sign_map[np.sign(offset)] + intermediate_notes = key_to_notes(tonic+additional_acc*(abs(offset)-1)+':'+scale, natural = False) + notes = [__simplify_note(note, additional_acc) for note in intermediate_notes] + degrees = __note_to_degree(notes) + notes = np.roll(notes, shift=-np.argwhere(degrees == 0)[0]) + + notes = list(notes) + + if not unicode: + translations = str.maketrans({"♯": "#", "đ„Ș": "##", "♭": "b", "đ„«": "bb", "♼": "n"}) + notes = list(n.translate(translations) for n in notes) + + return notes + + + # Determine major or minor + major = scale == "maj" + + # calculate how many clockwise steps we are on CoF (== # sharps) + if major: + tonic_number = ((pitch_map[tonic] + offset) * 7) % 12 + else: + tonic_number = ((pitch_map[tonic] + offset) * 7 + 9) % 12 + + # Decide if using flats or sharps + # Logic here is as follows: + # 1. respect the given notation for the tonic. + # Sharp tonics will always use sharps, likewise flats. + # 2. If no accidental in the tonic, try to minimize accidentals. + # 3. If there's a tie for accidentals, use sharp for major and flat for minor. + + if offset < 0: + # use flats explicitly + use_sharps = False + + elif offset > 0: + # use sharps explicitly + use_sharps = True + + elif 0 <= tonic_number < 6: + use_sharps = True + + elif tonic_number > 6: + use_sharps = False + + # Basic note sequences for simple keys + notes_sharp = ["C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B"] + notes_flat = ["C", "D♭", "D", "E♭", "E", "F", "G♭", "G", "A♭", "A", "B♭", "B"] + + # These apply when we have >= 6 sharps + sharp_corrections = [ + (5, "E♯"), + (0, "B♯"), + (7, "Fđ„Ș"), + (2, "Cđ„Ș"), + (9, "Gđ„Ș"), + (4, "Dđ„Ș"), + (11, "Ađ„Ș"), + ] + + # These apply when we have >= 6 flats + flat_corrections = [ + (11, "C♭"), + (4, "F♭"), + (9, "Bđ„«"), + (2, "Eđ„«"), + (7, "Ađ„«"), + (0, "Dđ„«"), + ] # last would be (5, 'Gđ„«') + + # Apply a mod-12 correction to distinguish B#:maj from C:maj + n_sharps = tonic_number + if tonic_number == 0 and tonic == "B": + n_sharps = 12 + + if use_sharps: + # This will only execute if n_sharps >= 6 + for n in range(0, n_sharps - 6 + 1): + index, name = sharp_corrections[n] + notes_sharp[index] = name + + notes = notes_sharp + else: + n_flats = (12 - tonic_number) % 12 + + # This will only execute if tonic_number <= 6 + for n in range(0, n_flats - 6 + 1): + index, name = flat_corrections[n] + notes_flat[index] = name + + notes = notes_flat + + # Apply natural signs to any note which has no other accidentals and does not appear in the scale for key. + if natural: + scale_notes = set(key_to_degrees(key)) + for place, note in enumerate(notes): + if __note_to_degree(note) in scale_notes: + continue + if len(note)==1: + notes[place] = note+'♼' + + # Finally, apply any unicode down-translation if necessary + if not unicode: + translations = str.maketrans({"♯": "#", "đ„Ș": "##", "♭": "b", "đ„«": "bb", "♼": "n"}) + notes = list(n.translate(translations) for n in notes) + + return notes + +# I made this work even for key signatures like 'C#b#:min' + +def key_to_degrees(key: str) -> np.ndarray: + """Construct the diatonic scale degrees for a given key. + + Parameters + ---------- + key : str + Must be in the form TONIC:key. Tonic must be upper case (``CDEFGAB``), + key must be lower-case + (``maj``, ``min``, ``ionian``, ``dorian``, ``phrygian``, ``lydian``, ``mixolydian``, ``aeolian``, ``locrian``). + + The following abbreviations are supported for the modes: either the first three letters of the mode name + (e.g. "mix") or the mode name without "ian" (e.g. "mixolyd"). + + Both ``major`` and ``maj`` are supported as abbreviations. + + Single and multiple accidentals (``b!♭`` for flat, or ``#♯`` for sharp) are supported. + + Examples: ``C:maj, C:major, Dbb:min, A♭:min, D:aeo, Eđ„Ș:phryg``. + + Returns + ------- + degrees : np.ndarray + An array containing the semitone numbers (0=C, 1=C#, ... 11=B) + for each of the seven scale degrees in the given key, starting + from the tonic. + + See Also + -------- + key_to_notes + + Examples + -------- + >>> librosa.key_to_degrees('C:maj') + array([ 0, 2, 4, 5, 7, 9, 11]) + + >>> librosa.key_to_degrees('C#:maj') + array([ 1, 3, 5, 6, 8, 10, 0]) + + >>> librosa.key_to_degrees('A:min') + array([ 9, 11, 0, 2, 4, 5, 7]) + + >>> librosa.key_to_degrees('A:min') + array([ 9, 11, 0, 2, 4, 5, 7]) + + """ + notes = dict( + maj=np.array([0, 2, 4, 5, 7, 9, 11]), min=np.array([0, 2, 3, 5, 7, 8, 10]) + ) + + match = KEY_RE.match(key) + + if not match: + raise ParameterError(f"Improper key format: {key:s}") + + if match.group('mode') or not match.group('scale'): + equiv = __mode_to_key(key) + offset = OFFSET_DICT[match.group('mode')[:3]] + return np.roll(key_to_degrees(equiv),-offset) + + pitch_map = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} + tonic = match.group("tonic").upper() + accidental = match.group("accidental") + counts = Counter(accidental) + offset = sum([ACC_MAP[acc]*counts[acc] for acc in ACC_MAP]) + + scale = match.group("scale")[:3].lower() + + return (notes[scale] + pitch_map[tonic] + offset) % 12 + + +@cache(level=10) +def fifths_to_note(*, unison: str, fifths: int, unicode: bool = True) -> str: + """Calculate the note name for a given number of perfect fifths + from a specified unison. + + This function is primarily intended as a utility routine for + Functional Just System (FJS) notation conversions. + + This function does not assume the "circle of fifths" or equal temperament, + so 12 fifths will not generally produce a note of the same pitch class + due to the accumulation of accidentals. + + Parameters + ---------- + unison : str + The name of the starting (unison) note, e.g., 'C' or 'Bb'. + Unicode accidentals are supported. + + fifths : integer + The number of perfect fifths to deviate from unison. + + unicode : bool + If ``True`` (default), use Unicode symbols (♯đ„Șâ™­đ„«)for accidentals. + + If ``False``, accidentals will be encoded as low-order ASCII representations:: + + ♯ -> #, đ„Ș -> ##, ♭ -> b, đ„« -> bb + + Returns + ------- + note : str + The name of the requested note + + Examples + -------- + >>> librosa.fifths_to_note(unison='C', fifths=6) + 'F♯' + + >>> librosa.fifths_to_note(unison='G', fifths=-3) + 'B♭' + + >>> librosa.fifths_to_note(unison='Eb', fifths=11, unicode=False) + 'G#' + + """ + # Starting the circle of fifths at F makes accidentals easier to count + COFMAP = "FCGDAEB" + + acc_map = { + "#": 1, + "": 0, + "b": -1, + "!": -1, + "♯": 1, + "đ„Ș": 2, + "♭": -1, + "đ„«": -2, + "♼": 0, + "n": 0 + } + + if unicode: + acc_map_inv = {1: "♯", 2: "đ„Ș", -1: "♭", -2: "đ„«", 0: ""} + else: + acc_map_inv = {1: "#", 2: "##", -1: "b", -2: "bb", 0: ""} + + match = NOTE_RE.match(unison) + + if not match: + raise ParameterError(f"Improper note format: {unison:s}") + + # Find unison in the alphabet + pitch = match.group("note").upper() + + # Find the number of accidentals to start from + offset = np.sum([acc_map[o] for o in match.group("accidental")]) + + # Find the raw target note + circle_idx = COFMAP.index(pitch) + raw_output = COFMAP[(circle_idx + fifths) % 7] + + # Now how many accidentals have we accrued? + # Equivalently, count times we cross a B<->F boundary + acc_index = offset + (circle_idx + fifths) // 7 + + # Compress multiple-accidentals as needed + acc_str = acc_map_inv[np.sign(acc_index) * 2] * int( + abs(acc_index) // 2 + ) + acc_map_inv[np.sign(acc_index)] * int(abs(acc_index) % 2) + + return raw_output + acc_str + + +@jit(nopython=True, nogil=True, cache=True) +def __o_fold(d): + """Compute the octave-folded interval. + + This maps intervals to the range [1, 2). + + This is part of the FJS notation converter. + It is equivalent to the `red` function described in the FJS + documentation. + """ + return d * (2.0 ** -np.floor(np.log2(d))) + + +@jit(nopython=True, nogil=True, cache=True) +def __bo_fold(d): + """Compute the balanced, octave-folded interval. + + This maps intervals to the range [sqrt(2)/2, sqrt(2)). + + This is part of the FJS notation converter. + It is equivalent to the `reb` function described in the FJS + documentation, but with a simpler implementation. + """ + return d * (2.0 ** -np.round(np.log2(d))) + + +@jit(nopython=True, nogil=True, cache=True) +def __fifth_search(interval, tolerance): + """Accelerated helper function for finding the number of fifths + to get within tolerance of a given interval. + + This implementation will give up after 32 fifths + """ + log_tolerance = np.abs(np.log2(tolerance)) + for power in range(32): + for sign in [1, -1]: + if ( + np.abs(np.log2(__bo_fold(interval / 3.0 ** (power * sign)))) + <= log_tolerance + ): + return power * sign + power += 1 + return power + + +# Translation grids for superscripts and subscripts +SUPER_TRANS = str.maketrans("0123456789", "⁰ÂčÂȳ⁎⁔⁶⁷⁞âč") +SUB_TRANS = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") + + +@overload +def interval_to_fjs( + interval: _FloatLike_co, + *, + unison: str = ..., + tolerance: float = ..., + unicode: bool = ..., +) -> str: + ... + + +@overload +def interval_to_fjs( + interval: _SequenceLike[_FloatLike_co], + *, + unison: str = ..., + tolerance: float = ..., + unicode: bool = ..., +) -> np.ndarray: + ... + + +@overload +def interval_to_fjs( + interval: _ScalarOrSequence[_FloatLike_co], + *, + unison: str = ..., + tolerance: float = ..., + unicode: bool = ..., +) -> Union[str, np.ndarray]: + ... + + +@vectorize(otypes="U", excluded=set(["unison", "tolerance", "unicode"])) +def interval_to_fjs( + interval: _ScalarOrSequence[_FloatLike_co], + *, + unison: str = "C", + tolerance: float = 65.0 / 63, + unicode: bool = True, +) -> Union[str, np.ndarray]: + """Convert an interval to Functional Just System (FJS) notation. + + See https://misotanni.github.io/fjs/en/index.html for a thorough overview + of the FJS notation system, and the examples below. + + FJS conversion works by identifying a Pythagorean interval which is within + a specified tolerance of the target interval, which provides the core note + name. If the interval is derived from ratios other than perfect fifths, + then the remaining factors are encoded as superscripts for otonal + (increasing) intervals and subscripts for utonal (decreasing) intervals. + + Parameters + ---------- + interval : float > 0 or iterable of floats + A (just) interval to notate in FJS. + + unison : str + The name of the unison note (corresponding to `interval=1`). + + tolerance : float + The tolerance threshold for identifying the core note name. + + unicode : bool + If ``True`` (default), use Unicode symbols (♯đ„Șâ™­đ„«)for accidentals, + and superscripts/subscripts for otonal and utonal accidentals. + + If ``False``, accidentals will be encoded as low-order ASCII representations:: + + ♯ -> #, đ„Ș -> ##, ♭ -> b, đ„« -> bb + + Otonal and utonal accidentals will be denoted by `^##` and `_##` + respectively (see examples below). + + Raises + ------ + ParameterError + If the provided interval is not positive + + If the provided interval cannot be identified with a + just intonation prime factorization. + + Returns + ------- + note_fjs : str or np.ndarray(dtype=str) + The interval(s) relative to the given unison in FJS notation. + + Examples + -------- + Pythagorean intervals appear as expected, with no otonal + or utonal extensions: + + >>> librosa.interval_to_fjs(3/2, unison='C') + 'G' + >>> librosa.interval_to_fjs(4/3, unison='F') + 'B♭' + + A ptolemaic major third will appear with an otonal '5': + + >>> librosa.interval_to_fjs(5/4, unison='A') + 'C♯⁔' + + And a ptolemaic minor third will appear with utonal '5': + + >>> librosa.interval_to_fjs(6/5, unison='A') + 'C₅' + + More complex intervals will have compound accidentals. + For example: + + >>> librosa.interval_to_fjs(25/14, unison='F#') + 'EÂČ⁔₇' + >>> librosa.interval_to_fjs(25/14, unison='F#', unicode=False) + 'E^25_7' + + Array inputs are also supported: + + >>> librosa.interval_to_fjs([3/2, 4/3, 5/3]) + array(['G', 'F', 'A⁔'], dtype=' 3} + + # Split into otonal and utonal accidentals + otonal = np.prod([p ** powers[p] for p in powers if powers[p] > 0]) + utonal = np.prod([p ** -powers[p] for p in powers if powers[p] < 0]) + + suffix = "" + if otonal > 1: + if unicode: + suffix += f"{otonal:d}".translate(SUPER_TRANS) + else: + suffix += f"^{otonal}" + + if utonal > 1: + if unicode: + suffix += f"{utonal:d}".translate(SUB_TRANS) + else: + suffix += f"_{utonal}" + + return note_name + suffix diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/pitch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/pitch.py new file mode 100644 index 0000000000000000000000000000000000000000..195275311c80b4365e8e4d7e32da310696b4ec95 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/pitch.py @@ -0,0 +1,1009 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Pitch-tracking and tuning estimation""" + +import warnings +import numpy as np +import scipy +import numba + + +from .spectrum import _spectrogram +from . import convert +from . import audio +from .._cache import cache +from .. import util +from .. import sequence +from ..util import Deprecated +from ..util.exceptions import ParameterError +from numpy.typing import ArrayLike +from typing import Any, Callable, Optional, Tuple, Union +from .._typing import _WindowSpec, _PadMode, _PadModeSTFT + +__all__ = ["estimate_tuning", "pitch_tuning", "piptrack", "yin", "pyin"] + + +def estimate_tuning( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: Optional[int] = 2048, + resolution: float = 0.01, + bins_per_octave: int = 12, + **kwargs: Any, +) -> float: + """Estimate the tuning of an audio time series or spectrogram input. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio signal. Multi-channel is supported.. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + magnitude or power spectrogram + n_fft : int > 0 [scalar] or None + number of FFT bins to use, if ``y`` is provided. + resolution : float in `(0, 1)` + Resolution of the tuning as a fraction of a bin. + 0.01 corresponds to measurements in cents. + bins_per_octave : int > 0 [scalar] + How many frequency bins per octave + **kwargs : additional keyword arguments + Additional arguments passed to `piptrack` + + Returns + ------- + tuning: float in `[-0.5, 0.5)` + estimated tuning deviation (fractions of a bin). + + Note that if multichannel input is provided, a single tuning estimate is provided spanning all + channels. + + See Also + -------- + piptrack : Pitch tracking by parabolic interpolation + + Examples + -------- + With time-series input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.estimate_tuning(y=y, sr=sr) + -0.08000000000000002 + + In tenths of a cent + + >>> librosa.estimate_tuning(y=y, sr=sr, resolution=1e-3) + -0.016000000000000014 + + Using spectrogram input + + >>> S = np.abs(librosa.stft(y)) + >>> librosa.estimate_tuning(S=S, sr=sr) + -0.08000000000000002 + + Using pass-through arguments to `librosa.piptrack` + + >>> librosa.estimate_tuning(y=y, sr=sr, n_fft=8192, + ... fmax=librosa.note_to_hz('G#9')) + -0.08000000000000002 + """ + pitch, mag = piptrack(y=y, sr=sr, S=S, n_fft=n_fft, **kwargs) + + # Only count magnitude where frequency is > 0 + pitch_mask = pitch > 0 + + if pitch_mask.any(): + threshold = np.median(mag[pitch_mask]) + else: + threshold = 0.0 + + return pitch_tuning( + pitch[(mag >= threshold) & pitch_mask], + resolution=resolution, + bins_per_octave=bins_per_octave, + ) + + +def pitch_tuning( + frequencies: ArrayLike, *, resolution: float = 0.01, bins_per_octave: int = 12 +) -> float: + """Given a collection of pitches, estimate its tuning offset + (in fractions of a bin) relative to A440=440.0Hz. + + Parameters + ---------- + frequencies : array-like, float + A collection of frequencies detected in the signal. + See `piptrack` + resolution : float in `(0, 1)` + Resolution of the tuning as a fraction of a bin. + 0.01 corresponds to cents. + bins_per_octave : int > 0 [scalar] + How many frequency bins per octave + + Returns + ------- + tuning: float in `[-0.5, 0.5)` + estimated tuning deviation (fractions of a bin) + + See Also + -------- + estimate_tuning : Estimating tuning from time-series or spectrogram input + + Examples + -------- + >>> # Generate notes at +25 cents + >>> freqs = librosa.cqt_frequencies(n_bins=24, fmin=55, tuning=0.25) + >>> librosa.pitch_tuning(freqs) + 0.25 + + >>> # Track frequencies from a real spectrogram + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> freqs, times, mags = librosa.reassigned_spectrogram(y, sr=sr, + ... fill_nan=True) + >>> # Select out pitches with high energy + >>> freqs = freqs[mags > np.median(mags)] + >>> librosa.pitch_tuning(freqs) + -0.07 + """ + frequencies = np.atleast_1d(frequencies) + + # Trim out any DC components + frequencies = frequencies[frequencies > 0] + + if not np.any(frequencies): + warnings.warn( + "Trying to estimate tuning from empty frequency set.", stacklevel=2 + ) + return 0.0 + + # Compute the residual relative to the number of bins + residual = np.mod(bins_per_octave * convert.hz_to_octs(frequencies), 1.0) + + # Are we on the wrong side of the semitone? + # A residual of 0.95 is more likely to be a deviation of -0.05 + # from the next tone up. + residual[residual >= 0.5] -= 1.0 + + bins = np.linspace(-0.5, 0.5, int(np.ceil(1.0 / resolution)) + 1) + + counts, tuning = np.histogram(residual, bins) + + # return the histogram peak + tuning_est: float = tuning[np.argmax(counts)] + return tuning_est + + +@cache(level=30) +def piptrack( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: Optional[int] = 2048, + hop_length: Optional[int] = None, + fmin: float = 150.0, + fmax: float = 4000.0, + threshold: float = 0.1, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + ref: Optional[Union[float, Callable]] = None, +) -> Tuple[np.ndarray, np.ndarray]: + """Pitch tracking on thresholded parabolically-interpolated STFT. + + This implementation uses the parabolic interpolation method described by [#]_. + + .. [#] https://ccrma.stanford.edu/~jos/sasp/Sinusoidal_Peak_Interpolation.html + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio signal. Multi-channel is supported.. + + sr : number > 0 [scalar] + audio sampling rate of ``y`` + + S : np.ndarray [shape=(..., d, t)] or None + magnitude or power spectrogram + + n_fft : int > 0 [scalar] or None + number of FFT bins to use, if ``y`` is provided. + + hop_length : int > 0 [scalar] or None + number of samples to hop + + threshold : float in `(0, 1)` + A bin in spectrum ``S`` is considered a pitch when it is greater than + ``threshold * ref(S)``. + + By default, ``ref(S)`` is taken to be ``max(S, axis=0)`` (the maximum value in + each column). + + fmin : float > 0 [scalar] + lower frequency cutoff. + + fmax : float > 0 [scalar] + upper frequency cutoff. + + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by ``window``. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + + If unspecified, defaults to ``win_length = n_fft``. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + + .. see also:: `filters.get_window` + + center : boolean + - If ``True``, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If ``False``, then frame ``t`` begins at ``y[t * hop_length]`` + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero-padding. + + See also: `np.pad`. + + ref : scalar or callable [default=np.max] + If scalar, the reference value against which ``S`` is compared for determining + pitches. + + If callable, the reference value is computed as ``ref(S, axis=0)``. + + Returns + ------- + pitches, magnitudes : np.ndarray [shape=(..., d, t)] + Where ``d`` is the subset of FFT bins within ``fmin`` and ``fmax``. + + ``pitches[..., f, t]`` contains instantaneous frequency at bin + ``f``, time ``t`` + + ``magnitudes[..., f, t]`` contains the corresponding magnitudes. + + Both ``pitches`` and ``magnitudes`` take value 0 at bins + of non-maximal magnitude. + + Notes + ----- + This function caches at level 30. + + One of ``S`` or ``y`` must be provided. + If ``S`` is not given, it is computed from ``y`` using + the default parameters of `librosa.stft`. + + Examples + -------- + Computing pitches from a waveform input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> pitches, magnitudes = librosa.piptrack(y=y, sr=sr) + + Or from a spectrogram input + + >>> S = np.abs(librosa.stft(y)) + >>> pitches, magnitudes = librosa.piptrack(S=S, sr=sr) + + Or with an alternate reference value for pitch detection, where + values above the mean spectral energy in each frame are counted as pitches + + >>> pitches, magnitudes = librosa.piptrack(S=S, sr=sr, threshold=1, + ... ref=np.mean) + """ + # Check that we received an audio time series or STFT + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + # Make sure we're dealing with magnitudes + S = np.abs(S) + + # Truncate to feasible region + fmin = np.maximum(fmin, 0) + fmax = np.minimum(fmax, float(sr) / 2) + + fft_freqs = convert.fft_frequencies(sr=sr, n_fft=n_fft) + + # Do the parabolic interpolation everywhere, + # then figure out where the peaks are + # then restrict to the feasible range (fmin:fmax) + avg = np.gradient(S, axis=-2) + shift = _parabolic_interpolation(S, axis=-2) + # this will get us the interpolated peak value + dskew = 0.5 * avg * shift + + # Pre-allocate output + pitches = np.zeros_like(S) + mags = np.zeros_like(S) + + # Clip to the viable frequency range + freq_mask = (fmin <= fft_freqs) & (fft_freqs < fmax) + freq_mask = util.expand_to(freq_mask, ndim=S.ndim, axes=-2) + + # Compute the column-wise local max of S after thresholding + # Find the argmax coordinates + if ref is None: + ref = np.max + + if callable(ref): + ref_value = threshold * ref(S, axis=-2) + # Reinsert the frequency axis here, in case the callable doesn't + + # support keepdims=True + ref_value = np.expand_dims(ref_value, -2) + else: + ref_value = np.abs(ref) + + # Store pitch and magnitude + idx = np.nonzero(freq_mask & util.localmax(S * (S > ref_value), axis=-2)) + pitches[idx] = (idx[-2] + shift[idx]) * float(sr) / n_fft + mags[idx] = S[idx] + dskew[idx] + + return pitches, mags + + +def _cumulative_mean_normalized_difference( + y_frames: np.ndarray, + min_period: int, + max_period: int, +) -> np.ndarray: + """Cumulative mean normalized difference function (equation 8 in [#]_) + + .. [#] De CheveignĂ©, Alain, and Hideki Kawahara. + "YIN, a fundamental frequency estimator for speech and music." + The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930. + + Parameters + ---------- + y_frames : np.ndarray [shape=(frame_length, n_frames)] + framed audio time series. + min_period : int > 0 [scalar] + minimum period. + max_period : int > 0 [scalar] + maximum period. + + Returns + ------- + yin_frames : np.ndarray [shape=(max_period-min_period+1,n_frames)] + Cumulative mean normalized difference function for each frame. + """ + acf_frames = audio.autocorrelate(y_frames, max_size=max_period + 1, axis=-2) + + # Energy terms. + yin_frames = np.square(y_frames) + np.cumsum(yin_frames, out=yin_frames, axis=-2) + + # Difference function: d(k) = 2 * (ACF(0) - ACF(k)) - sum_{m=0}^{k-1} y(m)^2 + k = slice(1, max_period + 1) + yin_frames[..., 0, :] = 0 + yin_frames[..., k, :] = ( + 2 * (acf_frames[..., 0:1, :] - acf_frames[..., k, :]) - yin_frames[..., :k.stop-1, :] + ) + + # Cumulative mean normalized difference function. + yin_numerator = yin_frames[..., min_period : max_period + 1, :] + # broadcast this shape to have leading ones + k_range = util.expand_to(np.r_[k], ndim=yin_frames.ndim, axes=-2) + + cumulative_mean = ( + np.cumsum(yin_frames[..., k, :], axis=-2) / k_range + ) + yin_denominator = cumulative_mean[..., min_period - 1 : max_period, :] + yin_frames: np.ndarray = yin_numerator / ( + yin_denominator + util.tiny(yin_denominator) + ) + return yin_frames + + +@numba.stencil # type: ignore +def _pi_stencil(x: np.ndarray) -> np.ndarray: + """Stencil to compute local parabolic interpolation""" + a = x[1] + x[-1] - 2 * x[0] + b = (x[1] - x[-1]) / 2 + + if np.abs(b) >= np.abs(a): + # If this happens, we'll shift by more than 1 bin + # Suppressing types because mypy has no idea about stencils + return 0 # type: ignore + + return -b / a # type: ignore + + +@numba.guvectorize( + ["void(float32[:], float32[:])", "void(float64[:], float64[:])"], + "(n)->(n)", + cache=True, + nopython=True, +) # type: ignore +def _pi_wrapper(x: np.ndarray, y: np.ndarray) -> None: # pragma: no cover + """Vectorized wrapper for the parabolic interpolation stencil""" + y[:] = _pi_stencil(x) + + +def _parabolic_interpolation(x: np.ndarray, *, axis: int = -2) -> np.ndarray: + """Piecewise parabolic interpolation for yin and pyin. + + Parameters + ---------- + x : np.ndarray + array to interpolate + axis : int + axis along which to interpolate + + Returns + ------- + parabolic_shifts : np.ndarray [shape=x.shape] + position of the parabola optima (relative to bin indices) + + Note: the shift at bin `n` is determined as 0 if the estimated + optimum is outside the range `[n-1, n+1]`. + """ + # Rotate the target axis to the end + xi = x.swapaxes(-1, axis) + + # Allocate the output array and rotate target axis + shifts = np.empty_like(x) + shiftsi = shifts.swapaxes(-1, axis) + + # Call the vectorized stencil + _pi_wrapper(xi, shiftsi) + + # Handle the edge condition not covered by the stencil + shiftsi[..., -1] = 0 + shiftsi[..., 0] = 0 + + return shifts + + +def yin( + y: np.ndarray, + *, + fmin: float, + fmax: float, + sr: float = 22050, + frame_length: int = 2048, + win_length: Optional[Union[int, Deprecated]] = Deprecated(), + hop_length: Optional[int] = None, + trough_threshold: float = 0.1, + center: bool = True, + pad_mode: _PadMode = "constant", +) -> np.ndarray: + """Fundamental frequency (F0) estimation using the YIN algorithm. + + YIN is an autocorrelation based method for fundamental frequency estimation [#]_. + First, a normalized difference function is computed over short (overlapping) frames of audio. + Next, the first minimum in the difference function below ``trough_threshold`` is selected as + an estimate of the signal's period. + Finally, the estimated period is refined using parabolic interpolation before converting + into the corresponding frequency. + + .. [#] De CheveignĂ©, Alain, and Hideki Kawahara. + "YIN, a fundamental frequency estimator for speech and music." + The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported.. + + fmin : number > 0 [scalar] + minimum frequency in Hertz. + The recommended minimum is ``librosa.note_to_hz('C2')`` (~65 Hz) + though lower values may be feasible. + + fmax : number > fmin, <= sr/2 [scalar] + maximum frequency in Hertz. + The recommended maximum is ``librosa.note_to_hz('C7')`` (~2093 Hz) + though higher values may be feasible. + + sr : number > 0 [scalar] + sampling rate of ``y`` in Hertz. + + frame_length : int > 0 [scalar] + length of the frames in samples. + By default, ``frame_length=2048`` corresponds to a time scale of about 93 ms at + a sampling rate of 22050 Hz. + + hop_length : None or int > 0 [scalar] + number of audio samples between adjacent YIN predictions. + If ``None``, defaults to ``frame_length // 4``. + + trough_threshold : number > 0 [scalar] + absolute threshold for peak estimation. + + center : boolean + If ``True``, the signal `y` is padded so that frame + ``D[:, t]`` is centered at `y[t * hop_length]`. + If ``False``, then ``D[:, t]`` begins at ``y[t * hop_length]``. + Defaults to ``True``, which simplifies the alignment of ``D`` onto a + time grid by means of ``librosa.core.frames_to_samples``. + + pad_mode : string or function + If ``center=True``, this argument is passed to ``np.pad`` for padding + the edges of the signal ``y``. By default (``pad_mode="constant"``), + ``y`` is padded on both sides with zeros. + If ``center=False``, this argument is ignored. + .. see also:: `np.pad` + + win_length : Deprecated + length of the window for calculating autocorrelation in samples. + + .. warning:: This parameter is deprecated as of 0.11.0 and + will be removed in 1.0. + + Returns + ------- + f0: np.ndarray [shape=(..., n_frames)] + time series of fundamental frequencies in Hertz. + + If multi-channel input is provided, f0 curves are estimated separately for each channel. + + See Also + -------- + librosa.pyin : + Fundamental frequency (F0) estimation using probabilistic YIN (pYIN). + + Examples + -------- + Computing a fundamental frequency (F0) curve from an audio input + + >>> y = librosa.chirp(fmin=440, fmax=880, duration=5.0, sr=22050) + >>> librosa.yin(y, fmin=440, fmax=880, sr=22050) + array([442.66354675, 441.95299983, 441.58010963, ..., + 871.161732 , 873.99001454, 877.04297681]) + """ + if fmin is None or fmax is None: + raise ParameterError('both "fmin" and "fmax" must be provided') + + if not isinstance(win_length, Deprecated): + warnings.warn( + "The win_length parameter has been deprecated in version 0.11.0 " + "and has no effect. It will be removed in version 1.0.0.", + category=FutureWarning, + stacklevel=3, + ) + + __check_yin_params( + sr=sr, fmax=fmax, fmin=fmin, frame_length=frame_length + ) + + # Set the default hop if it is not already specified. + if hop_length is None: + hop_length = frame_length // 4 + + # Check that audio is valid. + util.valid_audio(y) + + # Pad the time series so that frames are centered + if center: + padding = [(0, 0)] * y.ndim + padding[-1] = (frame_length // 2, frame_length // 2) + y = np.pad(y, padding, mode=pad_mode) + + # Frame audio. + y_frames = util.frame(y, frame_length=frame_length, hop_length=hop_length) + + # Calculate minimum and maximum periods + min_period = int(np.floor(sr / fmax)) + max_period = min(int(np.ceil(sr / fmin)), frame_length - 1) + + # Calculate cumulative mean normalized difference function. + yin_frames = _cumulative_mean_normalized_difference( + y_frames, min_period, max_period + ) + + # Parabolic interpolation. + parabolic_shifts = _parabolic_interpolation(yin_frames) + + # Find local minima. + is_trough = util.localmin(yin_frames, axis=-2) + is_trough[..., 0, :] = yin_frames[..., 0, :] < yin_frames[..., 1, :] + + # Find minima below peak threshold. + is_threshold_trough = np.logical_and(is_trough, yin_frames < trough_threshold) + + # Absolute threshold. + # "The solution we propose is to set an absolute threshold and choose the + # smallest value of tau that gives a minimum of d' deeper than + # this threshold. If none is found, the global minimum is chosen instead." + target_shape = list(yin_frames.shape) + target_shape[-2] = 1 + + global_min = np.argmin(yin_frames, axis=-2) + yin_period = np.argmax(is_threshold_trough, axis=-2) + + global_min = global_min.reshape(target_shape) + yin_period = yin_period.reshape(target_shape) + + no_trough_below_threshold = np.all(~is_threshold_trough, axis=-2, keepdims=True) + yin_period[no_trough_below_threshold] = global_min[no_trough_below_threshold] + + # Refine peak by parabolic interpolation. + + yin_period = ( + min_period + + yin_period + + np.take_along_axis(parabolic_shifts, yin_period, axis=-2) + )[..., 0, :] + + # Convert period to fundamental frequency. + f0: np.ndarray = sr / yin_period + return f0 + + +def pyin( + y: np.ndarray, + *, + fmin: float, + fmax: float, + sr: float = 22050, + frame_length: int = 2048, + win_length: Optional[Union[int, Deprecated]] = Deprecated(), + hop_length: Optional[int] = None, + n_thresholds: int = 100, + beta_parameters: Tuple[float, float] = (2, 18), + boltzmann_parameter: float = 2, + resolution: float = 0.1, + max_transition_rate: float = 35.92, + switch_prob: float = 0.01, + no_trough_prob: float = 0.01, + fill_na: Optional[float] = np.nan, + center: bool = True, + pad_mode: _PadMode = "constant", +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Fundamental frequency (F0) estimation using probabilistic YIN (pYIN). + + pYIN [#]_ is a modificatin of the YIN algorithm [#]_ for fundamental frequency (F0) estimation. + In the first step of pYIN, F0 candidates and their probabilities are computed using the YIN algorithm. + In the second step, Viterbi decoding is used to estimate the most likely F0 sequence and voicing flags. + + .. [#] Mauch, Matthias, and Simon Dixon. + "pYIN: A fundamental frequency estimator using probabilistic threshold distributions." + 2014 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2014. + + .. [#] De CheveignĂ©, Alain, and Hideki Kawahara. + "YIN, a fundamental frequency estimator for speech and music." + The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + + fmin : number > 0 [scalar] + minimum frequency in Hertz. + The recommended minimum is ``librosa.note_to_hz('C2')`` (~65 Hz) + though lower values may be feasible. + + fmax : number > fmin, <= sr/2 [scalar] + maximum frequency in Hertz. + The recommended maximum is ``librosa.note_to_hz('C7')`` (~2093 Hz) + though higher values may be feasible. + + sr : number > 0 [scalar] + sampling rate of ``y`` in Hertz. + + frame_length : int > 0 [scalar] + length of the frames in samples. + By default, ``frame_length=2048`` corresponds to a time scale of about 93 ms at + a sampling rate of 22050 Hz. + + hop_length : None or int > 0 [scalar] + number of audio samples between adjacent pYIN predictions. + If ``None``, defaults to ``frame_length // 4``. + + n_thresholds : int > 0 [scalar] + number of thresholds for peak estimation. + + beta_parameters : tuple + shape parameters for the beta distribution prior over thresholds. + + boltzmann_parameter : number > 0 [scalar] + shape parameter for the Boltzmann distribution prior over troughs. + Larger values will assign more mass to smaller periods. + + resolution : float in `(0, 1)` + Resolution of the pitch bins. + 0.01 corresponds to cents. + + max_transition_rate : float > 0 + maximum pitch transition rate in octaves per second. + + switch_prob : float in ``(0, 1)`` + probability of switching from voiced to unvoiced or vice versa. + + no_trough_prob : float in ``(0, 1)`` + maximum probability to add to global minimum if no trough is below threshold. + + fill_na : None, float, or ``np.nan`` + default value for unvoiced frames of ``f0``. + If ``None``, the unvoiced frames will contain a best guess value. + + center : boolean + If ``True``, the signal ``y`` is padded so that frame + ``D[:, t]`` is centered at ``y[t * hop_length]``. + If ``False``, then ``D[:, t]`` begins at ``y[t * hop_length]``. + Defaults to ``True``, which simplifies the alignment of ``D`` onto a + time grid by means of ``librosa.core.frames_to_samples``. + + pad_mode : string or function + If ``center=True``, this argument is passed to ``np.pad`` for padding + the edges of the signal ``y``. By default (``pad_mode="constant"``), + ``y`` is padded on both sides with zeros. + If ``center=False``, this argument is ignored. + .. see also:: `np.pad` + + win_length : Deprecated + length of the window for calculating autocorrelation in samples. + + .. warning:: This parameter is deprecated as of 0.11.0 and + will be removed in 1.0. + + Returns + ------- + f0: np.ndarray [shape=(..., n_frames)] + time series of fundamental frequencies in Hertz. + voiced_flag: np.ndarray [shape=(..., n_frames)] + time series containing boolean flags indicating whether a frame is voiced or not. + voiced_prob: np.ndarray [shape=(..., n_frames)] + time series containing the probability that a frame is voiced. + .. note:: If multi-channel input is provided, f0 and voicing are estimated separately for each channel. + + See Also + -------- + librosa.yin : + Fundamental frequency (F0) estimation using the YIN algorithm. + + Examples + -------- + Computing a fundamental frequency (F0) curve from an audio input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> f0, voiced_flag, voiced_probs = librosa.pyin(y, + ... sr=sr, + ... fmin=librosa.note_to_hz('C2'), + ... fmax=librosa.note_to_hz('C7')) + >>> times = librosa.times_like(f0, sr=sr) + + Overlay F0 over a spectrogram + + >>> import matplotlib.pyplot as plt + >>> D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max) + >>> fig, ax = plt.subplots() + >>> img = librosa.display.specshow(D, x_axis='time', y_axis='log', ax=ax) + >>> ax.set(title='pYIN fundamental frequency estimation') + >>> fig.colorbar(img, ax=ax, format="%+2.f dB") + >>> ax.plot(times, f0, label='f0', color='cyan', linewidth=3) + >>> ax.legend(loc='upper right') + """ + if fmin is None or fmax is None: + raise ParameterError('both "fmin" and "fmax" must be provided') + + if not isinstance(win_length, Deprecated): + warnings.warn( + "The win_length parameter has been deprecated in version 0.11.0 " + "and has no effect. It will be removed in version 1.0.0.", + category=FutureWarning, + stacklevel=3, + ) + + __check_yin_params( + sr=sr, fmax=fmax, fmin=fmin, frame_length=frame_length + ) + + # Set the default hop if it is not already specified. + if hop_length is None: + hop_length = frame_length // 4 + + # Check that audio is valid. + util.valid_audio(y) + + # Pad the time series so that frames are centered + if center: + padding = [(0, 0) for _ in y.shape] + padding[-1] = (frame_length // 2, frame_length // 2) + y = np.pad(y, padding, mode=pad_mode) + + # Frame audio. + y_frames = util.frame(y, frame_length=frame_length, hop_length=hop_length) + + # Calculate minimum and maximum periods + min_period = int(np.floor(sr / fmax)) + max_period = min(int(np.ceil(sr / fmin)), frame_length - 1) + + # Calculate cumulative mean normalized difference function. + yin_frames = _cumulative_mean_normalized_difference( + y_frames, min_period, max_period + ) + + # Parabolic interpolation. + parabolic_shifts = _parabolic_interpolation(yin_frames) + + # Find Yin candidates and probabilities. + # The implementation here follows the official pYIN software which + # differs from the method described in the paper. + # 1. Define the prior over the thresholds. + thresholds = np.linspace(0, 1, n_thresholds + 1) + beta_cdf = scipy.stats.beta.cdf(thresholds, beta_parameters[0], beta_parameters[1]) + beta_probs = np.diff(beta_cdf) + + n_bins_per_semitone = int(np.ceil(1.0 / resolution)) + n_pitch_bins = int(np.floor(12 * n_bins_per_semitone * np.log2(fmax / fmin))) + 1 + + def _helper(a, b): + return __pyin_helper( + a, + b, + sr, + thresholds, + boltzmann_parameter, + beta_probs, + no_trough_prob, + min_period, + fmin, + n_pitch_bins, + n_bins_per_semitone, + ) + + helper = np.vectorize(_helper, signature="(f,t),(k,t)->(1,d,t),(j,t)") + observation_probs, voiced_prob = helper(yin_frames, parabolic_shifts) + + # Construct transition matrix. + max_semitones_per_frame = round(max_transition_rate * 12 * hop_length / sr) + transition_width = max_semitones_per_frame * n_bins_per_semitone + 1 + # Construct the within voicing transition probabilities + transition = sequence.transition_local( + n_pitch_bins, transition_width, window="triangle", wrap=False + ) + + # Include across voicing transition probabilities + t_switch = sequence.transition_loop(2, 1 - switch_prob) + transition = np.kron(t_switch, transition) + + p_init = np.ones(2 * n_pitch_bins) / (2 * n_pitch_bins) + + states = sequence.viterbi(observation_probs, transition, p_init=p_init) + + # Find f0 corresponding to each decoded pitch bin. + freqs = fmin * 2 ** (np.arange(n_pitch_bins) / (12 * n_bins_per_semitone)) + f0 = freqs[states % n_pitch_bins] + voiced_flag = states < n_pitch_bins + + if fill_na is not None: + f0[~voiced_flag] = fill_na + + return f0[..., 0, :], voiced_flag[..., 0, :], voiced_prob[..., 0, :] + + +def __pyin_helper( + yin_frames, + parabolic_shifts, + sr, + thresholds, + boltzmann_parameter, + beta_probs, + no_trough_prob, + min_period, + fmin, + n_pitch_bins, + n_bins_per_semitone, +): + yin_probs = np.zeros_like(yin_frames) + + for i, yin_frame in enumerate(yin_frames.T): + # 2. For each frame find the troughs. + is_trough = util.localmin(yin_frame) + + is_trough[0] = yin_frame[0] < yin_frame[1] + (trough_index,) = np.nonzero(is_trough) + + if len(trough_index) == 0: + continue + + # 3. Find the troughs below each threshold. + # these are the local minima of the frame, could get them directly without the trough index + trough_heights = yin_frame[trough_index] + trough_thresholds = np.less.outer(trough_heights, thresholds[1:]) + + # 4. Define the prior over the troughs. + # Smaller periods are weighted more. + trough_positions = np.cumsum(trough_thresholds, axis=0) - 1 + n_troughs = np.count_nonzero(trough_thresholds, axis=0) + + trough_prior = scipy.stats.boltzmann.pmf( + trough_positions, boltzmann_parameter, n_troughs + ) + + trough_prior[~trough_thresholds] = 0 + + # 5. For each threshold add probability to global minimum if no trough is below threshold, + # else add probability to each trough below threshold biased by prior. + + probs = trough_prior.dot(beta_probs) + + global_min = np.argmin(trough_heights) + n_thresholds_below_min = np.count_nonzero(~trough_thresholds[global_min, :]) + probs[global_min] += no_trough_prob * np.sum( + beta_probs[:n_thresholds_below_min] + ) + + yin_probs[trough_index, i] = probs + + yin_period, frame_index = np.nonzero(yin_probs) + + # Refine peak by parabolic interpolation. + period_candidates = min_period + yin_period + period_candidates = period_candidates + parabolic_shifts[yin_period, frame_index] + f0_candidates = sr / period_candidates + + # Find pitch bin corresponding to each f0 candidate. + bin_index = 12 * n_bins_per_semitone * np.log2(f0_candidates / fmin) + bin_index = np.clip(np.round(bin_index), 0, n_pitch_bins).astype(int) + + # Observation probabilities. + observation_probs = np.zeros((2 * n_pitch_bins, yin_frames.shape[1])) + observation_probs[bin_index, frame_index] = yin_probs[yin_period, frame_index] + + voiced_prob = np.clip( + np.sum(observation_probs[:n_pitch_bins, :], axis=0, keepdims=True), 0, 1 + ) + observation_probs[n_pitch_bins:, :] = (1 - voiced_prob) / n_pitch_bins + + return observation_probs[np.newaxis], voiced_prob + + +def __check_yin_params( + *, sr: float, fmax: float, fmin: float, frame_length: int +): + """Check the feasibility of yin/pyin parameters against + the following conditions: + + 1. 0 < fmin < fmax <= sr/2 + 2. sr / fmin < frame_length - 1: At least one period of fmin needs to fit into the frame. + + Give a warning if parameters violate: + 3. sr / fmin < frame_length / 2: Ideally, at least two periods of fmin should fit into the frame. + """ + if fmax > sr / 2: + raise ParameterError(f"fmax={fmax:.3f} cannot exceed Nyquist frequency {sr/2}") + if fmin >= fmax: + raise ParameterError(f"fmin={fmin:.3f} must be less than fmax={fmax:.3f}") + if fmin <= 0: + raise ParameterError(f"fmin={fmin:.3f} must be strictly positive") + + if sr / fmin >= frame_length - 1: + fmin_feasible = sr / (frame_length - 1) + frame_length_feasible = int(np.ceil(sr / fmin) + 1) + raise ParameterError( + f"fmin={fmin:.3f} is too small for frame_length={frame_length} and sr={sr}. " + f"Either increase to fmin={fmin_feasible:.3f} or frame_length={frame_length_feasible}" + ) + + if sr / fmin >= frame_length // 2: + fmin_optimal = sr / (frame_length / 2) + frame_length_optimal = int(np.ceil(sr / fmin) * 2 + 1) + + warnings.warn( + f"With fmin={fmin:.3f}, sr={sr} and frame_length={frame_length}, less than two periods of fmin " + f"fit into the frame, which can cause inaccurate pitch detection. " + f"Consider increasing to fmin={fmin_optimal:.3f} or frame_length={frame_length_optimal}.", + stacklevel=3, + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/spectrum.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/spectrum.py new file mode 100644 index 0000000000000000000000000000000000000000..f552736fa0220658f9ab7b1f568a73a1336597a6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/core/spectrum.py @@ -0,0 +1,2958 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Utilities for spectral processing""" +from __future__ import annotations +import warnings + +import numpy as np +import scipy +import scipy.ndimage +import scipy.signal +import scipy.interpolate + +from numba import jit + +from . import convert +from .fft import get_fftlib +from .audio import resample +from .._cache import cache +from .. import util +from ..util.exceptions import ParameterError +from ..filters import get_window, semitone_filterbank +from ..filters import window_sumsquare +from numpy.typing import DTypeLike +from typing import Any, Callable, Optional, Tuple, List, Union, overload +from typing_extensions import Literal +from .._typing import ( + _WindowSpec, + _PadMode, + _PadModeSTFT, + _SequenceLike, + _ScalarOrSequence, + _ComplexLike_co, + _FloatLike_co +) + +__all__ = [ + "stft", + "istft", + "magphase", + "iirt", + "reassigned_spectrogram", + "phase_vocoder", + "perceptual_weighting", + "power_to_db", + "db_to_power", + "amplitude_to_db", + "db_to_amplitude", + "fmt", + "pcen", + "griffinlim", +] + + +@cache(level=20) +def stft( + y: np.ndarray, + *, + n_fft: int = 2048, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + dtype: Optional[DTypeLike] = None, + pad_mode: _PadModeSTFT = "constant", + out: Optional[np.ndarray] = None, +) -> np.ndarray: + """Short-time Fourier transform (STFT). + + The STFT represents a signal in the time-frequency domain by + computing discrete Fourier transforms (DFT) over short overlapping + windows. + + This function returns a complex-valued matrix D such that + + - ``np.abs(D[..., f, t])`` is the magnitude of frequency bin ``f`` + at frame ``t``, and + + - ``np.angle(D[..., f, t])`` is the phase of frequency bin ``f`` + at frame ``t``. + + The integers ``t`` and ``f`` can be converted to physical units by means + of the utility functions `frames_to_samples` and `fft_frequencies`. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)], real-valued + input signal. Multi-channel is supported. + + n_fft : int > 0 [scalar] + length of the windowed signal after padding with zeros. + The number of rows in the STFT matrix ``D`` is ``(1 + n_fft/2)``. + The default value, ``n_fft=2048`` samples, corresponds to a physical + duration of 93 milliseconds at a sample rate of 22050 Hz, i.e. the + default sample rate in librosa. This value is well adapted for music + signals. However, in speech processing, the recommended value is 512, + corresponding to 23 milliseconds at a sample rate of 22050 Hz. + In any case, we recommend setting ``n_fft`` to a power of two for + optimizing the speed of the fast Fourier transform (FFT) algorithm. + + hop_length : int > 0 [scalar] + number of audio samples between adjacent STFT columns. + + Smaller values increase the number of columns in ``D`` without + affecting the frequency resolution of the STFT. + + If unspecified, defaults to ``win_length // 4`` (see below). + + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by ``window`` of length ``win_length`` + and then padded with zeros to match ``n_fft``. Padding is added on + both the left- and the right-side of the window so that the window + is centered within the frame. + + Smaller values improve the temporal resolution of the STFT (i.e. the + ability to discriminate impulses that are closely spaced in time) + at the expense of frequency resolution (i.e. the ability to discriminate + pure tones that are closely spaced in frequency). This effect is known + as the time-frequency localization trade-off and needs to be adjusted + according to the properties of the input signal ``y``. + + If unspecified, defaults to ``win_length = n_fft``. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + Either: + + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + + Defaults to a raised cosine window (`'hann'`), which is adequate for + most applications in audio signal processing. + + .. see also:: `filters.get_window` + + center : boolean + If ``True``, the signal ``y`` is padded so that frame + ``D[:, t]`` is centered at ``y[t * hop_length]``. + + If ``False``, then ``D[:, t]`` begins at ``y[t * hop_length]``. + + Defaults to ``True``, which simplifies the alignment of ``D`` onto a + time grid by means of `librosa.frames_to_samples`. + Note, however, that ``center`` must be set to `False` when analyzing + signals with `librosa.stream`. + + .. see also:: `librosa.stream` + + dtype : np.dtype, optional + Complex numeric type for ``D``. Default is inferred to match the + precision of the input signal. + + pad_mode : string or function + If ``center=True``, this argument is passed to `np.pad` for padding + the edges of the signal ``y``. By default (``pad_mode="constant"``), + ``y`` is padded on both sides with zeros. + + .. note:: Not all padding modes supported by `numpy.pad` are supported here. + `wrap`, `mean`, `maximum`, `median`, and `minimum` are not supported. + + Other modes that depend at most on input values at the edges of the + signal (e.g., `constant`, `edge`, `linear_ramp`) are supported. + + If ``center=False``, this argument is ignored. + + .. see also:: `numpy.pad` + + out : np.ndarray or None + A pre-allocated, complex-valued array to store the STFT results. + This must be of compatible shape and dtype for the given input parameters. + + If `out` is larger than necessary for the provided input signal, then only + a prefix slice of `out` will be used. + + If not provided, a new array is allocated and returned. + + Returns + ------- + D : np.ndarray [shape=(..., 1 + n_fft/2, n_frames), dtype=dtype] + Complex-valued matrix of short-term Fourier transform + coefficients. + + If a pre-allocated `out` array is provided, then `D` will be + a reference to `out`. + + If `out` is larger than necessary, then `D` will be a sliced + view: `D = out[..., :n_frames]`. + + See Also + -------- + istft : Inverse STFT + reassigned_spectrogram : Time-frequency reassigned spectrogram + + Notes + ----- + This function caches at level 20. + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + >>> S + array([[5.395e-03, 3.332e-03, ..., 9.862e-07, 1.201e-05], + [3.244e-03, 2.690e-03, ..., 9.536e-07, 1.201e-05], + ..., + [7.523e-05, 3.722e-05, ..., 1.188e-04, 1.031e-03], + [7.640e-05, 3.944e-05, ..., 5.180e-04, 1.346e-03]], + dtype=float32) + + Use left-aligned frames, instead of centered frames + + >>> S_left = librosa.stft(y, center=False) + + Use a shorter hop length + + >>> D_short = librosa.stft(y, hop_length=64) + + Display a spectrogram + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(S, + ... ref=np.max), + ... y_axis='log', x_axis='time', ax=ax) + >>> ax.set_title('Power spectrogram') + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + """ + # By default, use the entire frame + if win_length is None: + win_length = n_fft + + # Set the default hop, if it's not already specified + if hop_length is None: + hop_length = int(win_length // 4) + elif not util.is_positive_int(hop_length): + raise ParameterError(f"hop_length={hop_length} must be a positive integer") + + # Check audio is valid + util.valid_audio(y) + + fft_window = get_window(window, win_length, fftbins=True) + + # Pad the window out to n_fft size + fft_window = util.pad_center(fft_window, size=n_fft) + + # Reshape so that the window can be broadcast + fft_window = util.expand_to(fft_window, ndim=1 + y.ndim, axes=-2) + + # Pad the time series so that frames are centered + if center: + if pad_mode in ("wrap", "maximum", "mean", "median", "minimum"): + # Note: padding with a user-provided function "works", but + # use at your own risk. + # Since we don't pass-through kwargs here, any arguments + # to a user-provided pad function should be encapsulated + # by using functools.partial: + # + # >>> my_pad_func = functools.partial(pad_func, foo=x, bar=y) + # >>> librosa.stft(..., pad_mode=my_pad_func) + + raise ParameterError( + f"pad_mode='{pad_mode}' is not supported by librosa.stft" + ) + + if n_fft > y.shape[-1]: + warnings.warn( + f"n_fft={n_fft} is too large for input signal of length={y.shape[-1]}" + ) + + # Set up the padding array to be empty, and we'll fix the target dimension later + padding = [(0, 0) for _ in range(y.ndim)] + + # How many frames depend on left padding? + start_k = int(np.ceil(n_fft // 2 / hop_length)) + + # What's the first frame that depends on extra right-padding? + tail_k = (y.shape[-1] + n_fft // 2 - n_fft) // hop_length + 1 + + if tail_k <= start_k: + # If tail and head overlap, then just copy-pad the signal and carry on + start = 0 + extra = 0 + padding[-1] = (n_fft // 2, n_fft // 2) + y = np.pad(y, padding, mode=pad_mode) + else: + # If tail and head do not overlap, then we can implement padding on each part separately + # and avoid a full copy-pad + + # "Middle" of the signal starts here, and does not depend on head padding + start = start_k * hop_length - n_fft // 2 + padding[-1] = (n_fft // 2, 0) + + # +1 here is to ensure enough samples to fill the window + # fixes bug #1567 + y_pre = np.pad( + y[..., : (start_k - 1) * hop_length - n_fft // 2 + n_fft + 1], + padding, + mode=pad_mode, + ) + y_frames_pre = util.frame(y_pre, frame_length=n_fft, hop_length=hop_length) + # Trim this down to the exact number of frames we should have + y_frames_pre = y_frames_pre[..., :start_k] + + # How many extra frames do we have from the head? + extra = y_frames_pre.shape[-1] + + # Determine if we have any frames that will fit inside the tail pad + if tail_k * hop_length - n_fft // 2 + n_fft <= y.shape[-1] + n_fft // 2: + padding[-1] = (0, n_fft // 2) + y_post = np.pad( + y[..., (tail_k) * hop_length - n_fft // 2 :], padding, mode=pad_mode + ) + y_frames_post = util.frame( + y_post, frame_length=n_fft, hop_length=hop_length + ) + # How many extra frames do we have from the tail? + extra += y_frames_post.shape[-1] + else: + # In this event, the first frame that touches tail padding would run off + # the end of the padded array + # We'll circumvent this by allocating an empty frame buffer for the tail + # this keeps the subsequent logic simple + post_shape = list(y_frames_pre.shape) + post_shape[-1] = 0 + y_frames_post = np.empty_like(y_frames_pre, shape=post_shape) + else: + if n_fft > y.shape[-1]: + raise ParameterError( + f"n_fft={n_fft} is too large for uncentered analysis of input signal of length={y.shape[-1]}" + ) + + # "Middle" of the signal starts at sample 0 + start = 0 + # We have no extra frames + extra = 0 + + fft = get_fftlib() + + if dtype is None: + dtype = util.dtype_r2c(y.dtype) + + # Window the time series. + y_frames = util.frame(y[..., start:], frame_length=n_fft, hop_length=hop_length) + + # Pre-allocate the STFT matrix + shape = list(y_frames.shape) + + # This is our frequency dimension + shape[-2] = 1 + n_fft // 2 + + # If there's padding, there will be extra head and tail frames + shape[-1] += extra + + if out is None: + stft_matrix = np.zeros(shape, dtype=dtype, order="F") + elif not (np.allclose(out.shape[:-1], shape[:-1]) and out.shape[-1] >= shape[-1]): + raise ParameterError( + f"Shape mismatch for provided output array out.shape={out.shape} and target shape={shape}" + ) + elif not np.iscomplexobj(out): + raise ParameterError(f"output with dtype={out.dtype} is not of complex type") + else: + if np.allclose(shape, out.shape): + stft_matrix = out + else: + stft_matrix = out[..., : shape[-1]] + + # Fill in the warm-up + if center and extra > 0: + off_start = y_frames_pre.shape[-1] + stft_matrix[..., :off_start] = fft.rfft(fft_window * y_frames_pre, axis=-2) + + off_end = y_frames_post.shape[-1] + if off_end > 0: + stft_matrix[..., -off_end:] = fft.rfft(fft_window * y_frames_post, axis=-2) + else: + off_start = 0 + + n_columns = int( + util.MAX_MEM_BLOCK // (np.prod(y_frames.shape[:-1]) * y_frames.itemsize) + ) + n_columns = max(n_columns, 1) + + for bl_s in range(0, y_frames.shape[-1], n_columns): + bl_t = min(bl_s + n_columns, y_frames.shape[-1]) + + stft_matrix[..., bl_s + off_start : bl_t + off_start] = fft.rfft( + fft_window * y_frames[..., bl_s:bl_t], axis=-2 + ) + return stft_matrix + + +@cache(level=30) +def istft( + stft_matrix: np.ndarray, + *, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + n_fft: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + dtype: Optional[DTypeLike] = None, + length: Optional[int] = None, + out: Optional[np.ndarray] = None, +) -> np.ndarray: + """ + Inverse short-time Fourier transform (ISTFT). + + Converts a complex-valued spectrogram ``stft_matrix`` to time-series ``y`` + by minimizing the mean squared error between ``stft_matrix`` and STFT of + ``y`` as described in [#]_ up to Section 2 (reconstruction from MSTFT). + + In general, window function, hop length and other parameters should be same + as in stft, which mostly leads to perfect reconstruction of a signal from + unmodified ``stft_matrix``. + + .. [#] D. W. Griffin and J. S. Lim, + "Signal estimation from modified short-time Fourier transform," + IEEE Trans. ASSP, vol.32, no.2, pp.236–243, Apr. 1984. + + Parameters + ---------- + stft_matrix : np.ndarray [shape=(..., 1 + n_fft//2, t)] + STFT matrix from ``stft`` + + hop_length : int > 0 [scalar] + Number of frames between STFT columns. + If unspecified, defaults to ``win_length // 4``. + + win_length : int <= n_fft = 2 * (stft_matrix.shape[0] - 1) + When reconstructing the time series, each frame is windowed + and each sample is normalized by the sum of squared window + according to the ``window`` function (see below). + + If unspecified, defaults to ``n_fft``. + + n_fft : int > 0 or None + The number of samples per frame in the input spectrogram. + By default, this will be inferred from the shape of ``stft_matrix``. + However, if an odd frame length was used, you can specify the correct + length by setting ``n_fft``. + + window : string, tuple, number, function, np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a user-specified window vector of length ``n_fft`` + + .. see also:: `filters.get_window` + + center : boolean + - If ``True``, ``D`` is assumed to have centered frames. + - If ``False``, ``D`` is assumed to have left-aligned frames. + + dtype : numeric type + Real numeric type for ``y``. Default is to match the numerical + precision of the input spectrogram. + + length : int > 0, optional + If provided, the output ``y`` is zero-padded or clipped to exactly + ``length`` samples. + + out : np.ndarray or None + A pre-allocated, complex-valued array to store the reconstructed signal + ``y``. This must be of the correct shape for the given input parameters. + + If not provided, a new array is allocated and returned. + + Returns + ------- + y : np.ndarray [shape=(..., n)] + time domain signal reconstructed from ``stft_matrix``. + If ``stft_matrix`` contains more than two axes + (e.g., from a stereo input signal), then ``y`` will match shape on the leading dimensions. + + See Also + -------- + stft : Short-time Fourier Transform + + Notes + ----- + This function caches at level 30. + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> D = librosa.stft(y) + >>> y_hat = librosa.istft(D) + >>> y_hat + array([-1.407e-03, -4.461e-04, ..., 5.131e-06, -1.417e-05], + dtype=float32) + + Exactly preserving length of the input signal requires explicit padding. + Otherwise, a partial frame at the end of ``y`` will not be represented. + + >>> n = len(y) + >>> n_fft = 2048 + >>> y_pad = librosa.util.fix_length(y, size=n + n_fft // 2) + >>> D = librosa.stft(y_pad, n_fft=n_fft) + >>> y_out = librosa.istft(D, length=n) + >>> np.max(np.abs(y - y_out)) + 8.940697e-08 + """ + if n_fft is None: + n_fft = 2 * (stft_matrix.shape[-2] - 1) + + # By default, use the entire frame + if win_length is None: + win_length = n_fft + + # Set the default hop, if it's not already specified + if hop_length is None: + hop_length = int(win_length // 4) + + ifft_window = get_window(window, win_length, fftbins=True) + + # Pad out to match n_fft, and add broadcasting axes + ifft_window = util.pad_center(ifft_window, size=n_fft) + ifft_window = util.expand_to(ifft_window, ndim=stft_matrix.ndim, axes=-2) + + # For efficiency, trim STFT frames according to signal length if available + if length: + if center: + padded_length = length + 2 * (n_fft // 2) + else: + padded_length = length + n_frames = min(stft_matrix.shape[-1], int(np.ceil(padded_length / hop_length))) + else: + n_frames = stft_matrix.shape[-1] + + if dtype is None: + dtype = util.dtype_c2r(stft_matrix.dtype) + + shape = list(stft_matrix.shape[:-2]) + expected_signal_len = n_fft + hop_length * (n_frames - 1) + + if length: + expected_signal_len = length + elif center: + expected_signal_len -= 2 * (n_fft // 2) + + shape.append(expected_signal_len) + + if out is None: + y = np.zeros(shape, dtype=dtype) + elif not np.allclose(out.shape, shape): + raise ParameterError( + f"Shape mismatch for provided output array out.shape={out.shape} != {shape}" + ) + else: + y = out + # Since we'll be doing overlap-add here, this needs to be initialized to zero. + y.fill(0.0) + + fft = get_fftlib() + + if center: + # First frame that does not depend on padding + # k * hop_length - n_fft//2 >= 0 + # k * hop_length >= n_fft // 2 + # k >= (n_fft//2 / hop_length) + + start_frame = int(np.ceil((n_fft // 2) / hop_length)) + + # Do overlap-add on the head block + ytmp = ifft_window * fft.irfft(stft_matrix[..., :start_frame], n=n_fft, axis=-2) + + shape[-1] = n_fft + hop_length * (start_frame - 1) + head_buffer = np.zeros(shape, dtype=dtype) + + __overlap_add(head_buffer, ytmp, hop_length) + + # If y is smaller than the head buffer, take everything + if y.shape[-1] < shape[-1] - n_fft // 2: + y[..., :] = head_buffer[..., n_fft // 2 : y.shape[-1] + n_fft // 2] + else: + # Trim off the first n_fft//2 samples from the head and copy into target buffer + y[..., : shape[-1] - n_fft // 2] = head_buffer[..., n_fft // 2 :] + + # This offset compensates for any differences between frame alignment + # and padding truncation + offset = start_frame * hop_length - n_fft // 2 + + else: + start_frame = 0 + offset = 0 + + n_columns = int( + util.MAX_MEM_BLOCK // (np.prod(stft_matrix.shape[:-1]) * stft_matrix.itemsize) + ) + n_columns = max(n_columns, 1) + + frame = 0 + for bl_s in range(start_frame, n_frames, n_columns): + bl_t = min(bl_s + n_columns, n_frames) + + # invert the block and apply the window function + ytmp = ifft_window * fft.irfft(stft_matrix[..., bl_s:bl_t], n=n_fft, axis=-2) + + # Overlap-add the istft block starting at the i'th frame + __overlap_add(y[..., frame * hop_length + offset :], ytmp, hop_length) + + frame += bl_t - bl_s + + # Normalize by sum of squared window + ifft_window_sum = window_sumsquare( + window=window, + n_frames=n_frames, + win_length=win_length, + n_fft=n_fft, + hop_length=hop_length, + dtype=dtype, + ) + + if center: + start = n_fft // 2 + else: + start = 0 + + ifft_window_sum = util.fix_length(ifft_window_sum[..., start:], size=y.shape[-1]) + + approx_nonzero_indices = ifft_window_sum > util.tiny(ifft_window_sum) + + y[..., approx_nonzero_indices] /= ifft_window_sum[approx_nonzero_indices] + + return y + + +@jit(nopython=True, cache=True) +def __overlap_add(y, ytmp, hop_length): + # numba-accelerated overlap add for inverse stft + # y is the pre-allocated output buffer + # ytmp is the windowed inverse-stft frames + # hop_length is the hop-length of the STFT analysis + + n_fft = ytmp.shape[-2] + N = n_fft + for frame in range(ytmp.shape[-1]): + sample = frame * hop_length + if N > y.shape[-1] - sample: + N = y.shape[-1] - sample + + y[..., sample : (sample + N)] += ytmp[..., :N, frame] + + +def __reassign_frequencies( + y: np.ndarray, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + dtype: Optional[DTypeLike] = None, + pad_mode: _PadModeSTFT = "constant", +) -> Tuple[np.ndarray, np.ndarray]: + """Instantaneous frequencies based on a spectrogram representation. + + The reassignment vector is calculated using equation 5.20 in Flandrin, + Auger, & Chassande-Mottin 2002:: + + omega_reassigned = omega - np.imag(S_dh/S_h) + + where ``S_h`` is the complex STFT calculated using the original window, and + ``S_dh`` is the complex STFT calculated using the derivative of the original + window. + + See `reassigned_spectrogram` for references. + + It is recommended to use ``pad_mode="wrap"`` or else ``center=False``, rather + than the defaults. Frequency reassignment assumes that the energy in each + FFT bin is associated with exactly one signal component. Reflection padding + at the edges of the signal may invalidate the reassigned estimates in the + boundary frames. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)], real-valued + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + S : np.ndarray [shape=(..., d, t)] or None + (optional) complex STFT calculated using the other arguments provided + to `__reassign_frequencies` + + n_fft : int > 0 [scalar] + FFT window size. Defaults to 2048. + + hop_length : int > 0 [scalar] + hop length, number samples between subsequent frames. + If not supplied, defaults to ``win_length // 4``. + + win_length : int > 0, <= n_fft + Window length. Defaults to ``n_fft``. + See ``stft`` for details. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a user-specified window vector of length ``n_fft`` + + See `stft` for details. + + .. see also:: `filters.get_window` + + center : boolean + - If ``True``, the signal ``y`` is padded so that frame + ``S[:, t]`` is centered at ``y[t * hop_length]``. + - If ``False``, then ``S[:, t]`` begins at ``y[t * hop_length]``. + + dtype : numeric type + Complex numeric type for ``S``. Default is inferred to match + the numerical precision of the input signal. + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + Returns + ------- + freqs : np.ndarray [shape=(..., 1 + n_fft/2, t), dtype=real] + Instantaneous frequencies: + ``freqs[f, t]`` is the frequency for bin ``f``, frame ``t``. + S : np.ndarray [shape=(..., 1 + n_fft/2, t), dtype=complex] + Short-time Fourier transform + + Warns + ----- + RuntimeWarning + Frequencies with zero support will produce a divide-by-zero warning and + will be returned as `np.nan`. + + See Also + -------- + stft : Short-time Fourier Transform + reassigned_spectrogram : Time-frequency reassigned spectrogram + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> frequencies, S = librosa.core.spectrum.__reassign_frequencies(y, sr=sr) + >>> frequencies + array([[0.000e+00, 0.000e+00, ..., 0.000e+00, 0.000e+00], + [3.628e+00, 4.698e+00, ..., 1.239e+01, 1.072e+01], + ..., + [1.101e+04, 1.102e+04, ..., 1.105e+04, 1.102e+04], + [1.102e+04, 1.102e+04, ..., 1.102e+04, 1.102e+04]]) + """ + # retrieve window samples if needed so that the window derivative can be + # calculated + if win_length is None: + win_length = n_fft + + window = get_window(window, win_length, fftbins=True) + window = util.pad_center(window, size=n_fft) + + if S is None: + if dtype is None: + dtype = util.dtype_r2c(y.dtype) + + S_h = stft( + y=y, + n_fft=n_fft, + hop_length=hop_length, + window=window, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + else: + if dtype is None: + dtype = S.dtype + + S_h = S + + # cyclic gradient to correctly handle edges of a periodic window + window_derivative = util.cyclic_gradient(window) + + S_dh = stft( + y=y, + n_fft=n_fft, + hop_length=hop_length, + window=window_derivative, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + # equation 5.20 of Flandrin, Auger, & Chassande-Mottin 2002 + # the sign of the correction is reversed in some papers - see Plante, + # Meyer, & Ainsworth 1998 pp. 283-284 + with np.errstate(invalid="ignore"): + # We can ignore divide-by-zero here because NaN is an acceptable correction value + correction = -np.imag(S_dh / S_h) + + freqs = convert.fft_frequencies(sr=sr, n_fft=n_fft) + freqs = util.expand_to(freqs, ndim=correction.ndim, axes=-2) + correction * ( + 0.5 * sr / np.pi + ) + + return freqs, S_h + + +def __reassign_times( + y: np.ndarray, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + dtype: Optional[DTypeLike] = None, + pad_mode: _PadModeSTFT = "constant", +) -> Tuple[np.ndarray, np.ndarray]: + """Time reassignments based on a spectrogram representation. + + The reassignment vector is calculated using equation 5.23 in Flandrin, + Auger, & Chassande-Mottin 2002:: + + t_reassigned = t + np.real(S_th/S_h) + + where ``S_h`` is the complex STFT calculated using the original window, and + ``S_th`` is the complex STFT calculated using the original window multiplied + by the time offset from the window center. + + See `reassigned_spectrogram` for references. + + It is recommended to use ``pad_mode="constant"`` (zero padding) or else + ``center=False``, rather than the defaults. Time reassignment assumes that + the energy in each FFT bin is associated with exactly one impulse event. + Reflection padding at the edges of the signal may invalidate the reassigned + estimates in the boundary frames. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)], real-valued + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + S : np.ndarray [shape=(..., d, t)] or None + (optional) complex STFT calculated using the other arguments provided + to `__reassign_times` + + n_fft : int > 0 [scalar] + FFT window size. Defaults to 2048. + + hop_length : int > 0 [scalar] + hop length, number samples between subsequent frames. + If not supplied, defaults to ``win_length // 4``. + + win_length : int > 0, <= n_fft + Window length. Defaults to ``n_fft``. + See `stft` for details. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a user-specified window vector of length ``n_fft`` + + See `stft` for details. + + .. see also:: `filters.get_window` + + center : boolean + - If ``True``, the signal ``y`` is padded so that frame + ``S[:, t]`` is centered at ``y[t * hop_length]``. + - If ``False``, then ``S[:, t]`` begins at ``y[t * hop_length]``. + + dtype : numeric type + Complex numeric type for ``S``. Default is inferred to match + the precision of the input signal. + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + Returns + ------- + times : np.ndarray [shape=(..., 1 + n_fft/2, t), dtype=real] + Reassigned times: + ``times[f, t]`` is the time for bin ``f``, frame ``t``. + S : np.ndarray [shape=(..., 1 + n_fft/2, t), dtype=complex] + Short-time Fourier transform + + Warns + ----- + RuntimeWarning + Time estimates with zero support will produce a divide-by-zero warning + and will be returned as `np.nan`. + + See Also + -------- + stft : Short-time Fourier Transform + reassigned_spectrogram : Time-frequency reassigned spectrogram + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> times, S = librosa.core.spectrum.__reassign_times(y, sr=sr) + >>> times + array([[ 2.268e-05, 1.144e-02, ..., 5.332e+00, 5.333e+00], + [ 2.268e-05, 1.451e-02, ..., 5.334e+00, 5.333e+00], + ..., + [ 2.268e-05, -6.177e-04, ..., 5.368e+00, 5.327e+00], + [ 2.268e-05, 1.420e-03, ..., 5.307e+00, 5.328e+00]]) + """ + # retrieve window samples if needed so that the time-weighted window can be + # calculated + if win_length is None: + win_length = n_fft + + window = get_window(window, win_length, fftbins=True) + window = util.pad_center(window, size=n_fft) + + # retrieve hop length if needed so that the frame times can be calculated + if hop_length is None: + hop_length = int(win_length // 4) + + if S is None: + if dtype is None: + dtype = util.dtype_r2c(y.dtype) + S_h = stft( + y=y, + n_fft=n_fft, + hop_length=hop_length, + window=window, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + else: + if dtype is None: + dtype = S.dtype + S_h = S + + # calculate window weighted by time + half_width = n_fft // 2 + + window_times: np.ndarray + if n_fft % 2: + window_times = np.arange(-half_width, half_width + 1) + + else: + window_times = np.arange(0.5 - half_width, half_width) + + window_time_weighted = window * window_times + + S_th = stft( + y=y, + n_fft=n_fft, + hop_length=hop_length, + window=window_time_weighted, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + # equation 5.23 of Flandrin, Auger, & Chassande-Mottin 2002 + # the sign of the correction is reversed in some papers - see Plante, + # Meyer, & Ainsworth 1998 pp. 283-284 + with np.errstate(invalid="ignore"): + # We can ignore divide-by-zero here because NaN is an acceptable correction value + correction = np.real(S_th / S_h) + + if center: + pad_length = None + + else: + pad_length = n_fft + + times = convert.frames_to_time( + np.arange(S_h.shape[-1]), sr=sr, hop_length=hop_length, n_fft=pad_length + ) + + times = util.expand_to(times, ndim=correction.ndim, axes=-1) + correction / sr + + return times, S_h + + +def reassigned_spectrogram( + y: np.ndarray, + *, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + reassign_frequencies: bool = True, + reassign_times: bool = True, + ref_power: Union[float, Callable] = 1e-6, + fill_nan: bool = False, + clip: bool = True, + dtype: Optional[DTypeLike] = None, + pad_mode: _PadModeSTFT = "constant", +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + r"""Time-frequency reassigned spectrogram. + + The reassignment vectors are calculated using equations 5.20 and 5.23 in + [#]_:: + + t_reassigned = t + np.real(S_th/S_h) + omega_reassigned = omega - np.imag(S_dh/S_h) + + where ``S_h`` is the complex STFT calculated using the original window, + ``S_dh`` is the complex STFT calculated using the derivative of the original + window, and ``S_th`` is the complex STFT calculated using the original window + multiplied by the time offset from the window center. See [#]_ for + additional algorithms, and [#]_ and [#]_ for history and discussion of the + method. + + .. [#] Flandrin, P., Auger, F., & Chassande-Mottin, E. (2002). + Time-Frequency reassignment: From principles to algorithms. In + Applications in Time-Frequency Signal Processing (Vol. 10, pp. + 179-204). CRC Press. + + .. [#] Fulop, S. A., & Fitz, K. (2006). Algorithms for computing the + time-corrected instantaneous frequency (reassigned) spectrogram, with + applications. The Journal of the Acoustical Society of America, 119(1), + 360. doi:10.1121/1.2133000 + + .. [#] Auger, F., Flandrin, P., Lin, Y.-T., McLaughlin, S., Meignen, S., + Oberlin, T., & Wu, H.-T. (2013). Time-Frequency Reassignment and + Synchrosqueezing: An Overview. IEEE Signal Processing Magazine, 30(6), + 32-41. doi:10.1109/MSP.2013.2265316 + + .. [#] Hainsworth, S., Macleod, M. (2003). Time-frequency reassignment: a + review and analysis. Tech. Rep. CUED/FINFENG/TR.459, Cambridge + University Engineering Department + + Parameters + ---------- + y : np.ndarray [shape=(..., n)], real-valued + audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + S : np.ndarray [shape=(..., d, t)] or None + (optional) complex STFT calculated using the other arguments provided + to ``reassigned_spectrogram`` + + n_fft : int > 0 [scalar] + FFT window size. Defaults to 2048. + + hop_length : int > 0 [scalar] + hop length, number samples between subsequent frames. + If not supplied, defaults to ``win_length // 4``. + + win_length : int > 0, <= n_fft + Window length. Defaults to ``n_fft``. + See `stft` for details. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a user-specified window vector of length ``n_fft`` + + See `stft` for details. + + .. see also:: `filters.get_window` + + center : boolean + - If ``True`` (default), the signal ``y`` is padded so that frame + ``S[:, t]`` is centered at ``y[t * hop_length]``. See `Notes` for + recommended usage in this function. + - If ``False``, then ``S[:, t]`` begins at ``y[t * hop_length]``. + + reassign_frequencies : boolean + - If ``True`` (default), the returned frequencies will be instantaneous + frequency estimates. + - If ``False``, the returned frequencies will be a read-only view of the + STFT bin frequencies for all frames. + + reassign_times : boolean + - If ``True`` (default), the returned times will be corrected + (reassigned) time estimates for each bin. + - If ``False``, the returned times will be a read-only view of the STFT + frame times for all bins. + + ref_power : float >= 0 or callable + Minimum power threshold for estimating time-frequency reassignments. + Any bin with ``np.abs(S[f, t])**2 < ref_power`` will be returned as + `np.nan` in both frequency and time, unless ``fill_nan`` is ``True``. If 0 + is provided, then only bins with zero power will be returned as + `np.nan` (unless ``fill_nan=True``). + + fill_nan : boolean + - If ``False`` (default), the frequency and time reassignments for bins + below the power threshold provided in ``ref_power`` will be returned as + `np.nan`. + - If ``True``, the frequency and time reassignments for these bins will + be returned as the bin center frequencies and frame times. + + clip : boolean + - If ``True`` (default), estimated frequencies outside the range + `[0, 0.5 * sr]` or times outside the range `[0, len(y) / sr]` will be + clipped to those ranges. + - If ``False``, estimated frequencies and times beyond the bounds of the + spectrogram may be returned. + + dtype : numeric type + Complex numeric type for STFT calculation. Default is inferred to match + the precision of the input signal. + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + Returns + ------- + freqs, times, mags : np.ndarray [shape=(..., 1 + n_fft/2, t), dtype=real] + Instantaneous frequencies: + ``freqs[..., f, t]`` is the frequency for bin ``f``, frame ``t``. + If ``reassign_frequencies=False``, this will instead be a read-only array + of the same shape containing the bin center frequencies for all frames. + + Reassigned times: + ``times[..., f, t]`` is the time for bin ``f``, frame ``t``. + If ``reassign_times=False``, this will instead be a read-only array of + the same shape containing the frame times for all bins. + + Magnitudes from short-time Fourier transform: + ``mags[..., f, t]`` is the magnitude for bin ``f``, frame ``t``. + + Warns + ----- + RuntimeWarning + Frequency or time estimates with zero support will produce a + divide-by-zero warning, and will be returned as `np.nan` unless + ``fill_nan=True``. + + See Also + -------- + stft : Short-time Fourier Transform + + Notes + ----- + It is recommended to use ``center=False`` with this function rather than the + librosa default ``True``. Unlike ``stft``, reassigned times are not aligned to + the left or center of each frame, so padding the signal does not affect the + meaning of the reassigned times. However, reassignment assumes that the + energy in each FFT bin is associated with exactly one signal component and + impulse event. + + If ``reassign_times`` is ``False``, the frame times that are returned will be + aligned to the left or center of the frame, depending on the value of + ``center``. In this case, if ``center`` is ``True``, then ``pad_mode="wrap"`` is + recommended for valid estimation of the instantaneous frequencies in the + boundary frames. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> amin = 1e-10 + >>> n_fft = 64 + >>> sr = 4000 + >>> y = 1e-3 * librosa.clicks(times=[0.3], sr=sr, click_duration=1.0, + ... click_freq=1200.0, length=8000) +\ + ... 1e-3 * librosa.clicks(times=[1.5], sr=sr, click_duration=0.5, + ... click_freq=400.0, length=8000) +\ + ... 1e-3 * librosa.chirp(fmin=200, fmax=1600, sr=sr, duration=2.0) +\ + ... 1e-6 * np.random.randn(2*sr) + >>> freqs, times, mags = librosa.reassigned_spectrogram(y=y, sr=sr, + ... n_fft=n_fft) + >>> mags_db = librosa.amplitude_to_db(mags, ref=np.max) + + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img = librosa.display.specshow(mags_db, x_axis="s", y_axis="linear", sr=sr, + ... hop_length=n_fft//4, ax=ax[0]) + >>> ax[0].set(title="Spectrogram", xlabel=None) + >>> ax[0].label_outer() + >>> ax[1].scatter(times, freqs, c=mags_db, cmap="magma", alpha=0.1, s=5) + >>> ax[1].set_title("Reassigned spectrogram") + >>> fig.colorbar(img, ax=ax, format="%+2.f dB") + """ + if not callable(ref_power) and ref_power < 0: + raise ParameterError("ref_power must be non-negative or callable.") + + if not reassign_frequencies and not reassign_times: + raise ParameterError("reassign_frequencies or reassign_times must be True.") + + if win_length is None: + win_length = n_fft + + if hop_length is None: + hop_length = int(win_length // 4) + + # frequency and time reassignment if requested + if reassign_frequencies: + freqs, S = __reassign_frequencies( + y=y, + sr=sr, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + if reassign_times: + times, S = __reassign_times( + y=y, + sr=sr, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + dtype=dtype, + pad_mode=pad_mode, + ) + + assert S is not None + + mags: np.ndarray = np.abs(S) + + # clean up reassignment issues: divide-by-zero, bins with near-zero power, + # and estimates outside the spectrogram bounds + + # retrieve bin frequencies and frame times to replace missing estimates + if fill_nan or not reassign_frequencies or not reassign_times: + if center: + pad_length = None + + else: + pad_length = n_fft + + bin_freqs = convert.fft_frequencies(sr=sr, n_fft=n_fft) + + frame_times = convert.frames_to_time( + frames=np.arange(S.shape[-1]), + sr=sr, + hop_length=hop_length, + n_fft=pad_length, + ) + + # find bins below the power threshold + # reassigned bins with zero power will already be NaN + if callable(ref_power): + ref_p = ref_power(mags**2) + else: + ref_p = ref_power + mags_low = np.less(mags, ref_p**0.5, where=~np.isnan(mags)) + + # for reassigned estimates, optionally set thresholded bins to NaN, return + # bin frequencies and frame times in place of NaN generated by + # divide-by-zero and power threshold, and clip to spectrogram bounds + if reassign_frequencies: + if ref_p > 0: + freqs[mags_low] = np.nan + + if fill_nan: + freqs = np.where(np.isnan(freqs), bin_freqs[:, np.newaxis], freqs) + + if clip: + np.clip(freqs, 0, sr / 2.0, out=freqs) + + # or if reassignment was not requested, return bin frequencies and frame + # times for every cell is the spectrogram + else: + freqs = np.broadcast_to(bin_freqs[:, np.newaxis], S.shape) + + if reassign_times: + if ref_p > 0: + times[mags_low] = np.nan + + if fill_nan: + times = np.where(np.isnan(times), frame_times[np.newaxis, :], times) + + if clip: + np.clip(times, 0, y.shape[-1] / float(sr), out=times) + + else: + times = np.broadcast_to(frame_times[np.newaxis, :], S.shape) + + return freqs, times, mags + + +def magphase(D: np.ndarray, *, power: float = 1) -> Tuple[np.ndarray, np.ndarray]: + """Separate a complex-valued spectrogram D into its magnitude (S) + and phase (P) components, so that ``D = S * P``. + + Parameters + ---------- + D : np.ndarray [shape=(..., d, t), dtype=complex] + complex-valued spectrogram + power : float > 0 + Exponent for the magnitude spectrogram, + e.g., 1 for energy, 2 for power, etc. + + Returns + ------- + D_mag : np.ndarray [shape=(..., d, t), dtype=real] + magnitude of ``D``, raised to ``power`` + D_phase : np.ndarray [shape=(..., d, t), dtype=complex] + ``exp(1.j * phi)`` where ``phi`` is the phase of ``D`` + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> D = librosa.stft(y) + >>> magnitude, phase = librosa.magphase(D) + >>> magnitude + array([[5.395e-03, 3.332e-03, ..., 9.862e-07, 1.201e-05], + [3.244e-03, 2.690e-03, ..., 9.536e-07, 1.201e-05], + ..., + [7.523e-05, 3.722e-05, ..., 1.188e-04, 1.031e-03], + [7.640e-05, 3.944e-05, ..., 5.180e-04, 1.346e-03]], + dtype=float32) + >>> phase + array([[ 1. +0.000e+00j, 1. +0.000e+00j, ..., + -1. -8.742e-08j, -1. -8.742e-08j], + [-1. -8.742e-08j, -0.775-6.317e-01j, ..., + -0.885-4.648e-01j, 0.472-8.815e-01j], + ..., + [ 1. -4.342e-12j, 0.028-9.996e-01j, ..., + -0.222-9.751e-01j, -0.75 -6.610e-01j], + [-1. -8.742e-08j, -1. -8.742e-08j, ..., + 1. +0.000e+00j, 1. +0.000e+00j]], dtype=complex64) + + Or get the phase angle (in radians) + + >>> np.angle(phase) + array([[ 0.000e+00, 0.000e+00, ..., -3.142e+00, -3.142e+00], + [-3.142e+00, -2.458e+00, ..., -2.658e+00, -1.079e+00], + ..., + [-4.342e-12, -1.543e+00, ..., -1.794e+00, -2.419e+00], + [-3.142e+00, -3.142e+00, ..., 0.000e+00, 0.000e+00]], + dtype=float32) + """ + mag = np.abs(D) + + # Prevent NaNs and return magnitude 0, phase 1+0j for zero + zeros_to_ones = mag == 0 + mag_nonzero = mag + zeros_to_ones + # Compute real and imaginary separately, because complex division can + # produce NaNs when denormalized numbers are involved (< ~2e-39 for + # complex64, ~5e-309 for complex128) + phase = np.empty_like(D, dtype=util.dtype_r2c(D.dtype)) + phase.real = D.real / mag_nonzero + zeros_to_ones + phase.imag = D.imag / mag_nonzero + + mag **= power + + return mag, phase + + +def phase_vocoder( + D: np.ndarray, + *, + rate: float, + hop_length: Optional[int] = None, + n_fft: Optional[int] = None, +) -> np.ndarray: + """Phase vocoder. Given an STFT matrix D, speed up by a factor of ``rate`` + + Based on the implementation provided by [#]_. + + This is a simplified implementation, intended primarily for + reference and pedagogical purposes. It makes no attempt to + handle transients, and is likely to produce many audible + artifacts. For a higher quality implementation, we recommend + the RubberBand library [#]_ and its Python wrapper `pyrubberband`. + + .. [#] Ellis, D. P. W. "A phase vocoder in Matlab." + Columbia University, 2002. + https://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/ + + .. [#] https://breakfastquay.com/rubberband/ + + Examples + -------- + >>> # Play at double speed + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> D = librosa.stft(y, n_fft=2048, hop_length=512) + >>> D_fast = librosa.phase_vocoder(D, rate=2.0, hop_length=512) + >>> y_fast = librosa.istft(D_fast, hop_length=512) + + >>> # Or play at 1/3 speed + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> D = librosa.stft(y, n_fft=2048, hop_length=512) + >>> D_slow = librosa.phase_vocoder(D, rate=1./3, hop_length=512) + >>> y_slow = librosa.istft(D_slow, hop_length=512) + + Parameters + ---------- + D : np.ndarray [shape=(..., d, t), dtype=complex] + STFT matrix + + rate : float > 0 [scalar] + Speed-up factor: ``rate > 1`` is faster, ``rate < 1`` is slower. + + hop_length : int > 0 [scalar] or None + The number of samples between successive columns of ``D``. + + If None, defaults to ``n_fft//4 = (D.shape[0]-1)//2`` + + n_fft : int > 0 or None + The number of samples per frame in D. + By default (None), this will be inferred from the shape of D. + However, if D was constructed using an odd-length window, the correct + frame length can be specified here. + + Returns + ------- + D_stretched : np.ndarray [shape=(..., d, t / rate), dtype=complex] + time-stretched STFT + + See Also + -------- + pyrubberband + """ + if n_fft is None: + n_fft = 2 * (D.shape[-2] - 1) + + if hop_length is None: + hop_length = int(n_fft // 4) + + time_steps = np.arange(0, D.shape[-1], rate, dtype=np.float64) + + # Create an empty output array + shape = list(D.shape) + shape[-1] = len(time_steps) + d_stretch = np.zeros_like(D, shape=shape) + + # Expected phase advance in each bin per frame + phi_advance = hop_length * convert.fft_frequencies(sr=2 * np.pi, n_fft=n_fft) + + # Phase accumulator; initialize to the first sample + phase_acc = np.angle(D[..., 0]) + + # Pad 0 columns to simplify boundary logic + padding = [(0, 0) for _ in D.shape] + padding[-1] = (0, 2) + D = np.pad(D, padding, mode="constant") + + for t, step in enumerate(time_steps): + columns = D[..., int(step) : int(step + 2)] + + # Weighting for linear magnitude interpolation + alpha = np.mod(step, 1.0) + mag = (1.0 - alpha) * np.abs(columns[..., 0]) + alpha * np.abs(columns[..., 1]) + + # Store to output array + d_stretch[..., t] = util.phasor(phase_acc, mag=mag) + + # Compute phase advance + dphase = np.angle(columns[..., 1]) - np.angle(columns[..., 0]) - phi_advance + + # Wrap to -pi:pi range + dphase = dphase - 2.0 * np.pi * np.round(dphase / (2.0 * np.pi)) + + # Accumulate phase + phase_acc += phi_advance + dphase + + return d_stretch + + +@cache(level=20) +def iirt( + y: np.ndarray, + *, + sr: float = 22050, + win_length: int = 2048, + hop_length: Optional[int] = None, + center: bool = True, + tuning: float = 0.0, + pad_mode: _PadMode = "constant", + flayout: str = "sos", + res_type: str = "soxr_hq", + **kwargs: Any, +) -> np.ndarray: + r"""Time-frequency representation using IIR filters + + This function will return a time-frequency representation + using a multirate filter bank consisting of IIR filters. [#]_ + + First, ``y`` is resampled as needed according to the provided ``sample_rates``. + + Then, a filterbank with with ``n`` band-pass filters is designed. + + The resampled input signals are processed by the filterbank as a whole. + (`scipy.signal.filtfilt` resp. `sosfiltfilt` is used to make the phase linear.) + The output of the filterbank is cut into frames. + For each band, the short-time mean-square power (STMSP) is calculated by + summing ``win_length`` subsequent filtered time samples. + + When called with the default set of parameters, it will generate the TF-representation + (pitch filterbank): + + * 85 filters with MIDI pitches [24, 108] as ``center_freqs``. + * each filter having a bandwidth of one semitone. + + .. [#] MĂŒller, Meinard. + "Information Retrieval for Music and Motion." + Springer Verlag. 2007. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + win_length : int > 0, <= n_fft + Window length. + hop_length : int > 0 [scalar] + Hop length, number samples between subsequent frames. + If not supplied, defaults to ``win_length // 4``. + center : boolean + - If ``True``, the signal ``y`` is padded so that frame + ``D[..., :, t]`` is centered at ``y[t * hop_length]``. + - If ``False``, then `D[..., :, t]`` begins at ``y[t * hop_length]`` + tuning : float [scalar] + Tuning deviation from A440 in fractions of a bin. + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, this function uses zero padding. + flayout : string + - If `sos` (default), a series of second-order filters is used for filtering with `scipy.signal.sosfiltfilt`. + Minimizes numerical precision errors for high-order filters, but is slower. + - If `ba`, the standard difference equation is used for filtering with `scipy.signal.filtfilt`. + Can be unstable for high-order filters. + res_type : string + The resampling mode. See `librosa.resample` for details. + **kwargs : additional keyword arguments + Additional arguments for `librosa.filters.semitone_filterbank` + (e.g., could be used to provide another set of ``center_freqs`` and ``sample_rates``). + + Returns + ------- + bands_power : np.ndarray [shape=(..., n, t), dtype=dtype] + Short-time mean-square power for the input signal. + + Raises + ------ + ParameterError + If ``flayout`` is not None, `ba`, or `sos`. + + See Also + -------- + librosa.filters.semitone_filterbank + librosa.filters.mr_frequencies + librosa.cqt + scipy.signal.filtfilt + scipy.signal.sosfiltfilt + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> y, sr = librosa.load(librosa.ex('trumpet'), duration=3) + >>> D = np.abs(librosa.iirt(y, sr=sr)) + >>> C = np.abs(librosa.cqt(y=y, sr=sr)) + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img = librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max), + ... y_axis='cqt_hz', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='Constant-Q transform') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max), + ... y_axis='cqt_hz', x_axis='time', ax=ax[1]) + >>> ax[1].set_title('Semitone spectrogram (iirt)') + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + """ + if flayout not in ("ba", "sos"): + raise ParameterError(f"Unsupported flayout={flayout}") + + # check audio input + util.valid_audio(y) + + # Set the default hop, if it's not already specified + if hop_length is None: + hop_length = win_length // 4 + + # Pad the time series so that frames are centered + if center: + padding = [(0, 0) for _ in y.shape] + padding[-1] = (win_length // 2, win_length // 2) + y = np.pad(y, padding, mode=pad_mode) + + # get the semitone filterbank + filterbank_ct, sample_rates = semitone_filterbank( + tuning=tuning, flayout=flayout, **kwargs + ) + + # create three downsampled versions of the audio signal + y_resampled = [] + + y_srs = np.unique(sample_rates) + + for cur_sr in y_srs: + y_resampled.append(resample(y, orig_sr=sr, target_sr=cur_sr, res_type=res_type)) + + # Compute the number of frames that will fit. The end may get truncated. + n_frames = int(1 + (y.shape[-1] - win_length) // hop_length) + + # Pre-allocate the output array + shape = list(y.shape) + # Time dimension reduces to n_frames + shape[-1] = n_frames + # Insert a new axis at position -2 for filter response + shape.insert(-1, len(filterbank_ct)) + + bands_power = np.empty_like(y, shape=shape) + + slices: List[Union[int, slice]] = [slice(None) for _ in bands_power.shape] + for i, (cur_sr, cur_filter) in enumerate(zip(sample_rates, filterbank_ct)): + slices[-2] = i + + # filter the signal + cur_sr_idx = np.flatnonzero(y_srs == cur_sr)[0] + + if flayout == "ba": + cur_filter_output = scipy.signal.filtfilt( + cur_filter[0], cur_filter[1], y_resampled[cur_sr_idx], axis=-1 + ) + elif flayout == "sos": + cur_filter_output = scipy.signal.sosfiltfilt( + cur_filter, y_resampled[cur_sr_idx], axis=-1 + ) + + factor = sr / cur_sr + hop_length_STMSP = hop_length / factor + win_length_STMSP_round = int(round(win_length / factor)) + + # hop_length_STMSP is used here as a floating-point number. + # The discretization happens at the end to avoid accumulated rounding errors. + start_idx = np.arange( + 0, cur_filter_output.shape[-1] - win_length_STMSP_round, hop_length_STMSP + ) + if len(start_idx) < n_frames: + min_length = ( + int(np.ceil(n_frames * hop_length_STMSP)) + win_length_STMSP_round + ) + cur_filter_output = util.fix_length(cur_filter_output, size=min_length) + start_idx = np.arange( + 0, + cur_filter_output.shape[-1] - win_length_STMSP_round, + hop_length_STMSP, + ) + start_idx = np.round(start_idx).astype(int)[:n_frames] + + idx = np.add.outer(start_idx, np.arange(win_length_STMSP_round)) + + bands_power[tuple(slices)] = factor * np.sum( + cur_filter_output[..., idx] ** 2, axis=-1 + ) + + return bands_power + + +@overload +def power_to_db( + S: _ComplexLike_co, + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> np.floating[Any]: + ... + +@overload +def power_to_db( + S: _SequenceLike[_ComplexLike_co], + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> np.ndarray: + ... + +@overload +def power_to_db( + S: _ScalarOrSequence[_ComplexLike_co], + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + +@cache(level=30) +def power_to_db( + S: _ScalarOrSequence[_ComplexLike_co], + *, + ref: Union[float, Callable] = 1.0, + amin: float = 1e-10, + top_db: Optional[float] = 80.0, +) -> Union[np.floating[Any], np.ndarray]: + """Convert a power spectrogram (amplitude squared) to decibel (dB) units + + This computes the scaling ``10 * log10(S / ref)`` in a numerically + stable way. + + Parameters + ---------- + S : np.ndarray + input power + + ref : scalar or callable + If scalar, the amplitude ``abs(S)`` is scaled relative to ``ref``:: + + 10 * log10(S / ref) + + Zeros in the output correspond to positions where ``S == ref``. + + If callable, the reference value is computed as ``ref(S)``. + + amin : float > 0 [scalar] + minimum threshold for ``abs(S)`` and ``ref`` + + top_db : float >= 0 [scalar] + threshold the output at ``top_db`` below the peak: + ``max(10 * log10(S/ref)) - top_db`` + + Returns + ------- + S_db : np.ndarray + ``S_db ~= 10 * log10(S) - 10 * log10(ref)`` + + See Also + -------- + perceptual_weighting + db_to_power + amplitude_to_db + db_to_amplitude + + Notes + ----- + This function caches at level 30. + + Examples + -------- + Get a power spectrogram from a waveform ``y`` + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + >>> librosa.power_to_db(S**2) + array([[-41.809, -41.809, ..., -41.809, -41.809], + [-41.809, -41.809, ..., -41.809, -41.809], + ..., + [-41.809, -41.809, ..., -41.809, -41.809], + [-41.809, -41.809, ..., -41.809, -41.809]], dtype=float32) + + Compute dB relative to peak power + + >>> librosa.power_to_db(S**2, ref=np.max) + array([[-80., -80., ..., -80., -80.], + [-80., -80., ..., -80., -80.], + ..., + [-80., -80., ..., -80., -80.], + [-80., -80., ..., -80., -80.]], dtype=float32) + + Or compare to median power + + >>> librosa.power_to_db(S**2, ref=np.median) + array([[16.578, 16.578, ..., 16.578, 16.578], + [16.578, 16.578, ..., 16.578, 16.578], + ..., + [16.578, 16.578, ..., 16.578, 16.578], + [16.578, 16.578, ..., 16.578, 16.578]], dtype=float32) + + And plot the results + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> imgpow = librosa.display.specshow(S**2, sr=sr, y_axis='log', x_axis='time', + ... ax=ax[0]) + >>> ax[0].set(title='Power spectrogram') + >>> ax[0].label_outer() + >>> imgdb = librosa.display.specshow(librosa.power_to_db(S**2, ref=np.max), + ... sr=sr, y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Log-Power spectrogram') + >>> fig.colorbar(imgpow, ax=ax[0]) + >>> fig.colorbar(imgdb, ax=ax[1], format="%+2.0f dB") + """ + S = np.asarray(S) + + if amin <= 0: + raise ParameterError("amin must be strictly positive") + + if np.issubdtype(S.dtype, np.complexfloating): + warnings.warn( + "power_to_db was called on complex input so phase " + "information will be discarded. To suppress this warning, " + "call power_to_db(np.abs(D)**2) instead.", + stacklevel=2, + ) + magnitude = np.abs(S) + else: + magnitude = S + + if callable(ref): + # User supplied a function to calculate reference power + ref_value = ref(magnitude) + else: + ref_value = np.abs(ref) + + log_spec: np.ndarray = 10.0 * np.log10(np.maximum(amin, magnitude)) + log_spec -= 10.0 * np.log10(np.maximum(amin, ref_value)) + + if top_db is not None: + if top_db < 0: + raise ParameterError("top_db must be non-negative") + log_spec = np.maximum(log_spec, log_spec.max() - top_db) + + return log_spec + + +@overload +def db_to_power( + S_db: _FloatLike_co, + *, + ref: float = ..., +) -> np.floating[Any]: + ... + +@overload +def db_to_power( + S_db: np.ndarray, + *, + ref: float = ..., +) -> np.ndarray: + ... + +@overload +def db_to_power( + S_db: Union[_FloatLike_co, np.ndarray], + *, + ref: float = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + +@cache(level=30) +def db_to_power(S_db: Union[_FloatLike_co, np.ndarray], *, ref: float = 1.0) -> Union[np.floating[Any], np.ndarray]: + """Convert dB-scale values to a power values. + + This effectively inverts ``power_to_db``:: + + db_to_power(S_db) ~= ref * 10.0**(S_db / 10) + + Parameters + ---------- + S_db : np.ndarray + dB-scaled values + ref : number > 0 + Reference power: output will be scaled by this value + + Returns + ------- + S : np.ndarray + Power values + + Notes + ----- + This function caches at level 30. + """ + return ref * np.power(10.0, S_db * 0.1) + + +@overload +def amplitude_to_db( + S: _ComplexLike_co, + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> np.floating[Any]: + ... + +@overload +def amplitude_to_db( + S: _SequenceLike[_ComplexLike_co], + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> np.ndarray: + ... + +@overload +def amplitude_to_db( + S: _ScalarOrSequence[_ComplexLike_co], + *, + ref: Union[float, Callable] = ..., + amin: float = ..., + top_db: Optional[float] = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + +@cache(level=30) +def amplitude_to_db( + S: _ScalarOrSequence[_ComplexLike_co], + *, + ref: Union[float, Callable] = 1.0, + amin: float = 1e-5, + top_db: Optional[float] = 80.0, +) -> Union[np.floating[Any], np.ndarray]: + """Convert an amplitude spectrogram to dB-scaled spectrogram. + + This is equivalent to ``power_to_db(S**2, ref=ref**2, amin=amin**2, top_db=top_db)``, + but is provided for convenience. + + Parameters + ---------- + S : np.ndarray + input amplitude + + ref : scalar or callable + If scalar, the amplitude ``abs(S)`` is scaled relative to ``ref``: + ``20 * log10(S / ref)``. + Zeros in the output correspond to positions where ``S == ref``. + + If callable, the reference value is computed as ``ref(S)``. + + amin : float > 0 [scalar] + minimum threshold for ``S`` and ``ref`` + + top_db : float >= 0 [scalar] + threshold the output at ``top_db`` below the peak: + ``max(20 * log10(S/ref)) - top_db`` + + Returns + ------- + S_db : np.ndarray + ``S`` measured in dB + + See Also + -------- + power_to_db, db_to_amplitude + + Notes + ----- + This function caches at level 30. + """ + S = np.asarray(S) + + if np.issubdtype(S.dtype, np.complexfloating): + warnings.warn( + "amplitude_to_db was called on complex input so phase " + "information will be discarded. To suppress this warning, " + "call amplitude_to_db(np.abs(S)) instead.", + stacklevel=2, + ) + + magnitude = np.abs(S) + + if callable(ref): + # User supplied a function to calculate reference power + ref_value = ref(magnitude) + else: + ref_value = np.abs(ref) + + out_array = magnitude if isinstance(magnitude, np.ndarray) else None + power = np.square(magnitude, out=out_array) + + db: np.ndarray = power_to_db(power, ref=ref_value**2, amin=amin**2, top_db=top_db) + return db + + +@overload +def db_to_amplitude( + S_db: _FloatLike_co, + *, + ref: float = ..., +) -> np.floating[Any]: + ... + +@overload +def db_to_amplitude( + S_db: np.ndarray, + *, + ref: float = ..., +) -> np.ndarray: + ... + +@overload +def db_to_amplitude( + S_db: Union[_FloatLike_co, np.ndarray], + *, + ref: float = ..., +) -> Union[np.floating[Any], np.ndarray]: + ... + +@cache(level=30) +def db_to_amplitude(S_db: Union[_FloatLike_co, np.ndarray], *, ref: float = 1.0) -> Union[np.floating[Any], np.ndarray]: + """Convert a dB-scaled spectrogram to an amplitude spectrogram. + + This effectively inverts `amplitude_to_db`:: + + db_to_amplitude(S_db) ~= 10.0**(0.5 * S_db/10 + log10(ref)) + + Parameters + ---------- + S_db : np.ndarray + dB-scaled values + ref : number > 0 + Optional reference amplitude. + + Returns + ------- + S : np.ndarray + Linear magnitude values + + Notes + ----- + This function caches at level 30. + """ + return db_to_power(S_db, ref=ref**2) ** 0.5 + + +@cache(level=30) +def perceptual_weighting( + S: np.ndarray, frequencies: np.ndarray, *, kind: str = "A", **kwargs: Any +) -> np.ndarray: + """Perceptual weighting of a power spectrogram:: + + S_p[..., f, :] = frequency_weighting(f, 'A') + 10*log(S[..., f, :] / ref) + + Parameters + ---------- + S : np.ndarray [shape=(..., d, t)] + Power spectrogram + frequencies : np.ndarray [shape=(d,)] + Center frequency for each row of` `S`` + kind : str + The frequency weighting curve to use. + e.g. `'A'`, `'B'`, `'C'`, `'D'`, `None or 'Z'` + **kwargs : additional keyword arguments + Additional keyword arguments to `power_to_db`. + + Returns + ------- + S_p : np.ndarray [shape=(..., d, t)] + perceptually weighted version of ``S`` + + See Also + -------- + power_to_db + + Notes + ----- + This function caches at level 30. + + Examples + -------- + Re-weight a CQT power spectrum, using peak power as reference + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('A1'))) + >>> freqs = librosa.cqt_frequencies(C.shape[0], + ... fmin=librosa.note_to_hz('A1')) + >>> perceptual_CQT = librosa.perceptual_weighting(C**2, + ... freqs, + ... ref=np.max) + >>> perceptual_CQT + array([[ -96.528, -97.101, ..., -108.561, -108.561], + [ -95.88 , -96.479, ..., -107.551, -107.551], + ..., + [ -65.142, -53.256, ..., -80.098, -80.098], + [ -71.542, -53.197, ..., -80.311, -80.311]]) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img = librosa.display.specshow(librosa.amplitude_to_db(C, + ... ref=np.max), + ... fmin=librosa.note_to_hz('A1'), + ... y_axis='cqt_hz', x_axis='time', + ... ax=ax[0]) + >>> ax[0].set(title='Log CQT power') + >>> ax[0].label_outer() + >>> imgp = librosa.display.specshow(perceptual_CQT, y_axis='cqt_hz', + ... fmin=librosa.note_to_hz('A1'), + ... x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Perceptually weighted log CQT') + >>> fig.colorbar(img, ax=ax[0], format="%+2.0f dB") + >>> fig.colorbar(imgp, ax=ax[1], format="%+2.0f dB") + """ + offset = convert.frequency_weighting(frequencies, kind=kind).reshape((-1, 1)) + + result: np.ndarray = offset + power_to_db(S, **kwargs) + return result + + +@cache(level=30) +def fmt( + y: np.ndarray, + *, + t_min: float = 0.5, + n_fmt: Optional[int] = None, + kind: str = "cubic", + beta: float = 0.5, + over_sample: float = 1, + axis: int = -1, +) -> np.ndarray: + """Fast Mellin transform (FMT) + + The Mellin of a signal `y` is performed by interpolating `y` on an exponential time + axis, applying a polynomial window, and then taking the discrete Fourier transform. + + When the Mellin parameter (beta) is 1/2, it is also known as the scale transform. [#]_ + The scale transform can be useful for audio analysis because its magnitude is invariant + to scaling of the domain (e.g., time stretching or compression). This is analogous + to the magnitude of the Fourier transform being invariant to shifts in the input domain. + + .. [#] De Sena, Antonio, and Davide Rocchesso. + "A fast Mellin and scale transform." + EURASIP Journal on Applied Signal Processing 2007.1 (2007): 75-75. + + .. [#] Cohen, L. + "The scale representation." + IEEE Transactions on Signal Processing 41, no. 12 (1993): 3275-3292. + + Parameters + ---------- + y : np.ndarray, real-valued + The input signal(s). Can be multidimensional. + The target axis must contain at least 3 samples. + + t_min : float > 0 + The minimum time spacing (in samples). + This value should generally be less than 1 to preserve as much information as + possible. + + n_fmt : int > 2 or None + The number of scale transform bins to use. + If None, then ``n_bins = over_sample * ceil(n * log((n-1)/t_min))`` is taken, + where ``n = y.shape[axis]`` + + kind : str + The type of interpolation to use when re-sampling the input. + See `scipy.interpolate.interp1d` for possible values. + + Note that the default is to use high-precision (cubic) interpolation. + This can be slow in practice; if speed is preferred over accuracy, + then consider using ``kind='linear'``. + + beta : float + The Mellin parameter. ``beta=0.5`` provides the scale transform. + + over_sample : float >= 1 + Over-sampling factor for exponential resampling. + + axis : int + The axis along which to transform ``y`` + + Returns + ------- + x_scale : np.ndarray [dtype=complex] + The scale transform of ``y`` along the ``axis`` dimension. + + Raises + ------ + ParameterError + if ``n_fmt < 2`` or ``t_min <= 0`` + or if ``y`` is not finite + or if ``y.shape[axis] < 3``. + + Notes + ----- + This function caches at level 30. + + Examples + -------- + >>> # Generate a signal and time-stretch it (with energy normalization) + >>> scale = 1.25 + >>> freq = 3.0 + >>> x1 = np.linspace(0, 1, num=1024, endpoint=False) + >>> x2 = np.linspace(0, 1, num=int(scale * len(x1)), endpoint=False) + >>> y1 = np.sin(2 * np.pi * freq * x1) + >>> y2 = np.sin(2 * np.pi * freq * x2) / np.sqrt(scale) + >>> # Verify that the two signals have the same energy + >>> np.sum(np.abs(y1)**2), np.sum(np.abs(y2)**2) + (255.99999999999997, 255.99999999999969) + >>> scale1 = librosa.fmt(y1, n_fmt=512) + >>> scale2 = librosa.fmt(y2, n_fmt=512) + + >>> # And plot the results + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2) + >>> ax[0].plot(y1, label='Original') + >>> ax[0].plot(y2, linestyle='--', label='Stretched') + >>> ax[0].set(xlabel='time (samples)', title='Input signals') + >>> ax[0].legend() + >>> ax[1].semilogy(np.abs(scale1), label='Original') + >>> ax[1].semilogy(np.abs(scale2), linestyle='--', label='Stretched') + >>> ax[1].set(xlabel='scale coefficients', title='Scale transform magnitude') + >>> ax[1].legend() + + >>> # Plot the scale transform of an onset strength autocorrelation + >>> y, sr = librosa.load(librosa.ex('choice')) + >>> odf = librosa.onset.onset_strength(y=y, sr=sr) + >>> # Auto-correlate with up to 10 seconds lag + >>> odf_ac = librosa.autocorrelate(odf, max_size=10 * sr // 512) + >>> # Normalize + >>> odf_ac_norm = librosa.util.normalize(odf_ac, norm=np.inf) + >>> # Compute the scale transform + >>> odf_ac_scale = librosa.fmt(odf_ac_norm, n_fmt=512) + >>> # Plot the results + >>> fig, ax = plt.subplots(nrows=3) + >>> ax[0].plot(odf, label='Onset strength') + >>> ax[0].set(xlabel='Time (frames)', title='Onset strength') + >>> ax[1].plot(odf_ac_norm, label='Onset autocorrelation') + >>> ax[1].set(xlabel='Lag (frames)', title='Onset autocorrelation') + >>> ax[2].semilogy(np.abs(odf_ac_scale), label='Scale transform magnitude') + >>> ax[2].set(xlabel='scale coefficients') + """ + n = y.shape[axis] + + if n < 3: + raise ParameterError(f"y.shape[{axis}]=={n} < 3") + + if t_min <= 0: + raise ParameterError(f"t_min={t_min} must be a positive number") + + if n_fmt is None: + if over_sample < 1: + raise ParameterError(f"over_sample={over_sample} must be >= 1") + + # The base is the maximum ratio between adjacent samples + # Since the sample spacing is increasing, this is simply the + # ratio between the positions of the last two samples: (n-1)/(n-2) + log_base = np.log(n - 1) - np.log(n - 2) + + n_fmt = int(np.ceil(over_sample * (np.log(n - 1) - np.log(t_min)) / log_base)) + + elif n_fmt < 3: + raise ParameterError(f"n_fmt=={n_fmt} < 3") + else: + log_base = (np.log(n_fmt - 1) - np.log(n_fmt - 2)) / over_sample + + if not np.all(np.isfinite(y)): + raise ParameterError("y must be finite everywhere") + + base = np.exp(log_base) + # original grid: signal covers [0, 1). This range is arbitrary, but convenient. + # The final sample is positioned at (n-1)/n, so we omit the endpoint + x = np.linspace(0, 1, num=n, endpoint=False) + + # build the interpolator + f_interp = scipy.interpolate.interp1d(x, y, kind=kind, axis=axis) + + # build the new sampling grid + # exponentially spaced between t_min/n and 1 (exclusive) + # we'll go one past where we need, and drop the last sample + # When over-sampling, the last input sample contributions n_over samples. + # To keep the spacing consistent, we over-sample by n_over, and then + # trim the final samples. + n_over = int(np.ceil(over_sample)) + x_exp = np.logspace( + (np.log(t_min) - np.log(n)) / log_base, + 0, + num=n_fmt + n_over, + endpoint=False, + base=base, + )[:-n_over] + + # Clean up any rounding errors at the boundaries of the interpolation + # The interpolator gets angry if we try to extrapolate, so clipping is necessary here. + if x_exp[0] < t_min or x_exp[-1] > float(n - 1.0) / n: + x_exp = np.clip(x_exp, float(t_min) / n, x[-1]) + + # Make sure that all sample points are unique + # This should never happen! + if len(np.unique(x_exp)) != len(x_exp): + raise ParameterError("Redundant sample positions in Mellin transform") + + # Resample the signal + y_res = f_interp(x_exp) + + # Broadcast the window correctly + shape = [1] * y_res.ndim + shape[axis] = -1 + + # Apply the window and fft + # Normalization is absorbed into the window here for expedience + fft = get_fftlib() + result: np.ndarray = fft.rfft( + y_res * ((x_exp**beta).reshape(shape) * np.sqrt(n) / n_fmt), axis=axis + ) + return result + + +@overload +def pcen( + S: np.ndarray, + *, + sr: float = ..., + hop_length: int = ..., + gain: float = ..., + bias: float = ..., + power: float = ..., + time_constant: float = ..., + eps: float = ..., + b: Optional[float] = ..., + max_size: int = ..., + ref: Optional[np.ndarray] = ..., + axis: int = ..., + max_axis: Optional[int] = ..., + zi: Optional[np.ndarray] = ..., + return_zf: Literal[False] = ..., +) -> np.ndarray: + ... + + +@overload +def pcen( + S: np.ndarray, + *, + sr: float = ..., + hop_length: int = ..., + gain: float = ..., + bias: float = ..., + power: float = ..., + time_constant: float = ..., + eps: float = ..., + b: Optional[float] = ..., + max_size: int = ..., + ref: Optional[np.ndarray] = ..., + axis: int = ..., + max_axis: Optional[int] = ..., + zi: Optional[np.ndarray] = ..., + return_zf: Literal[True], +) -> Tuple[np.ndarray, np.ndarray]: + ... + + +@overload +def pcen( + S: np.ndarray, + *, + sr: float = ..., + hop_length: int = ..., + gain: float = ..., + bias: float = ..., + power: float = ..., + time_constant: float = ..., + eps: float = ..., + b: Optional[float] = ..., + max_size: int = ..., + ref: Optional[np.ndarray] = ..., + axis: int = ..., + max_axis: Optional[int] = ..., + zi: Optional[np.ndarray] = ..., + return_zf: bool = ..., +) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: + ... + + +@cache(level=30) +def pcen( + S: np.ndarray, + *, + sr: float = 22050, + hop_length: int = 512, + gain: float = 0.98, + bias: float = 2, + power: float = 0.5, + time_constant: float = 0.400, + eps: float = 1e-6, + b: Optional[float] = None, + max_size: int = 1, + ref: Optional[np.ndarray] = None, + axis: int = -1, + max_axis: Optional[int] = None, + zi: Optional[np.ndarray] = None, + return_zf: bool = False, +) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: + """Per-channel energy normalization (PCEN) + + This function normalizes a time-frequency representation ``S`` by + performing automatic gain control, followed by nonlinear compression [#]_ :: + + P[f, t] = (S / (eps + M[f, t])**gain + bias)**power - bias**power + + IMPORTANT: the default values of eps, gain, bias, and power match the + original publication, in which ``S`` is a 40-band mel-frequency + spectrogram with 25 ms windowing, 10 ms frame shift, and raw audio values + in the interval [-2**31; 2**31-1[. If you use these default values, we + recommend to make sure that the raw audio is properly scaled to this + interval, and not to [-1, 1[ as is most often the case. + + The matrix ``M`` is the result of applying a low-pass, temporal IIR filter + to ``S``:: + + M[f, t] = (1 - b) * M[f, t - 1] + b * S[f, t] + + If ``b`` is not provided, it is calculated as:: + + b = (sqrt(1 + 4* T**2) - 1) / (2 * T**2) + + where ``T = time_constant * sr / hop_length``. [#]_ + + This normalization is designed to suppress background noise and + emphasize foreground signals, and can be used as an alternative to + decibel scaling (`amplitude_to_db`). + + This implementation also supports smoothing across frequency bins + by specifying ``max_size > 1``. If this option is used, the filtered + spectrogram ``M`` is computed as:: + + M[f, t] = (1 - b) * M[f, t - 1] + b * R[f, t] + + where ``R`` has been max-filtered along the frequency axis, similar to + the SuperFlux algorithm implemented in `onset.onset_strength`:: + + R[f, t] = max(S[f - max_size//2: f + max_size//2, t]) + + This can be used to perform automatic gain control on signals that cross + or span multiple frequency bans, which may be desirable for spectrograms + with high frequency resolution. + + .. [#] Wang, Y., Getreuer, P., Hughes, T., Lyon, R. F., & Saurous, R. A. + (2017, March). Trainable frontend for robust and far-field keyword spotting. + In Acoustics, Speech and Signal Processing (ICASSP), 2017 + IEEE International Conference on (pp. 5670-5674). IEEE. + + .. [#] Lostanlen, V., Salamon, J., McFee, B., Cartwright, M., Farnsworth, A., + Kelling, S., and Bello, J. P. Per-Channel Energy Normalization: Why and How. + IEEE Signal Processing Letters, 26(1), 39-43. + + Parameters + ---------- + S : np.ndarray (non-negative) + The input (magnitude) spectrogram + + sr : number > 0 [scalar] + The audio sampling rate + + hop_length : int > 0 [scalar] + The hop length of ``S``, expressed in samples + + gain : number >= 0 [scalar] + The gain factor. Typical values should be slightly less than 1. + + bias : number >= 0 [scalar] + The bias point of the nonlinear compression (default: 2) + + power : number >= 0 [scalar] + The compression exponent. Typical values should be between 0 and 0.5. + Smaller values of ``power`` result in stronger compression. + At the limit ``power=0``, polynomial compression becomes logarithmic. + + time_constant : number > 0 [scalar] + The time constant for IIR filtering, measured in seconds. + + eps : number > 0 [scalar] + A small constant used to ensure numerical stability of the filter. + + b : number in [0, 1] [scalar] + The filter coefficient for the low-pass filter. + If not provided, it will be inferred from ``time_constant``. + + max_size : int > 0 [scalar] + The width of the max filter applied to the frequency axis. + If left as `1`, no filtering is performed. + + ref : None or np.ndarray (shape=S.shape) + An optional pre-computed reference spectrum (``R`` in the above). + If not provided it will be computed from ``S``. + + axis : int [scalar] + The (time) axis of the input spectrogram. + + max_axis : None or int [scalar] + The frequency axis of the input spectrogram. + If `None`, and ``S`` is two-dimensional, it will be inferred + as the opposite from ``axis``. + If ``S`` is not two-dimensional, and ``max_size > 1``, an error + will be raised. + + zi : np.ndarray + The initial filter delay values. + + This may be the ``zf`` (final delay values) of a previous call to ``pcen``, or + computed by `scipy.signal.lfilter_zi`. + + return_zf : bool + If ``True``, return the final filter delay values along with the PCEN output ``P``. + This is primarily useful in streaming contexts, where the final state of one + block of processing should be used to initialize the next block. + + If ``False`` (default) only the PCEN values ``P`` are returned. + + Returns + ------- + P : np.ndarray, non-negative [shape=(n, m)] + The per-channel energy normalized version of ``S``. + zf : np.ndarray (optional) + The final filter delay values. Only returned if ``return_zf=True``. + + See Also + -------- + amplitude_to_db + librosa.onset.onset_strength + + Examples + -------- + Compare PCEN to log amplitude (dB) scaling on Mel spectra + + >>> import matplotlib.pyplot as plt + >>> y, sr = librosa.load(librosa.ex('robin')) + + >>> # We recommend scaling y to the range [-2**31, 2**31[ before applying + >>> # PCEN's default parameters. Furthermore, we use power=1 to get a + >>> # magnitude spectrum instead of a power spectrum. + >>> S = librosa.feature.melspectrogram(y=y, sr=sr, power=1) + >>> log_S = librosa.amplitude_to_db(S, ref=np.max) + >>> pcen_S = librosa.pcen(S * (2**31)) + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img = librosa.display.specshow(log_S, x_axis='time', y_axis='mel', ax=ax[0]) + >>> ax[0].set(title='log amplitude (dB)', xlabel=None) + >>> ax[0].label_outer() + >>> imgpcen = librosa.display.specshow(pcen_S, x_axis='time', y_axis='mel', ax=ax[1]) + >>> ax[1].set(title='Per-channel energy normalization') + >>> fig.colorbar(img, ax=ax[0], format="%+2.0f dB") + >>> fig.colorbar(imgpcen, ax=ax[1]) + + Compare PCEN with and without max-filtering + + >>> pcen_max = librosa.pcen(S * (2**31), max_size=3) + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> librosa.display.specshow(pcen_S, x_axis='time', y_axis='mel', ax=ax[0]) + >>> ax[0].set(title='Per-channel energy normalization (no max-filter)') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(pcen_max, x_axis='time', y_axis='mel', ax=ax[1]) + >>> ax[1].set(title='Per-channel energy normalization (max_size=3)') + >>> fig.colorbar(img, ax=ax) + """ + if power < 0: + raise ParameterError(f"power={power} must be nonnegative") + + if gain < 0: + raise ParameterError(f"gain={gain} must be non-negative") + + if bias < 0: + raise ParameterError(f"bias={bias} must be non-negative") + + if eps <= 0: + raise ParameterError(f"eps={eps} must be strictly positive") + + if time_constant <= 0: + raise ParameterError(f"time_constant={time_constant} must be strictly positive") + + if not util.is_positive_int(max_size): + raise ParameterError(f"max_size={max_size} must be a positive integer") + + if b is None: + t_frames = time_constant * sr / float(hop_length) + # By default, this solves the equation for b: + # b**2 + (1 - b) / t_frames - 2 = 0 + # which approximates the full-width half-max of the + # squared frequency response of the IIR low-pass filter + + b = (np.sqrt(1 + 4 * t_frames**2) - 1) / (2 * t_frames**2) + + if not 0 <= b <= 1: + raise ParameterError(f"b={b} must be between 0 and 1") + + if np.issubdtype(S.dtype, np.complexfloating): + warnings.warn( + "pcen was called on complex input so phase " + "information will be discarded. To suppress this warning, " + "call pcen(np.abs(D)) instead.", + stacklevel=2, + ) + S = np.abs(S) + + if ref is None: + if max_size == 1: + ref = S + elif S.ndim == 1: + raise ParameterError( + "Max-filtering cannot be applied to 1-dimensional input" + ) + else: + if max_axis is None: + if S.ndim != 2: + raise ParameterError( + f"Max-filtering a {S.ndim:d}-dimensional spectrogram " + "requires you to specify max_axis" + ) + # if axis = 0, max_axis=1 + # if axis = +- 1, max_axis = 0 + max_axis = np.mod(1 - axis, 2) + + ref = scipy.ndimage.maximum_filter1d(S, max_size, axis=max_axis) + + if zi is None: + # Make sure zi matches dimension to input + shape = tuple([1] * ref.ndim) + zi = np.empty(shape) + zi[:] = scipy.signal.lfilter_zi([b], [1, b - 1])[:] + + # Temporal integration + S_smooth: np.ndarray + zf: np.ndarray + S_smooth, zf = scipy.signal.lfilter([b], [1, b - 1], ref, zi=zi, axis=axis) + + # Adaptive gain control + # Working in log-space gives us some stability, and a slight speedup + smooth = np.exp(-gain * (np.log(eps) + np.log1p(S_smooth / eps))) + + # Dynamic range compression + S_out: np.ndarray + if power == 0: + S_out = np.log1p(S * smooth) + elif bias == 0: + S_out = np.exp(power * (np.log(S) + np.log(smooth))) + else: + S_out = (bias**power) * np.expm1(power * np.log1p(S * smooth / bias)) + + if return_zf: + return S_out, zf + else: + return S_out + + +def griffinlim( + S: np.ndarray, + *, + n_iter: int = 32, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + n_fft: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + dtype: Optional[DTypeLike] = None, + length: Optional[int] = None, + pad_mode: _PadModeSTFT = "constant", + momentum: float = 0.99, + init: Optional[str] = "random", + random_state: Optional[ + Union[int, np.random.RandomState, np.random.Generator] + ] = None, +) -> np.ndarray: + """Approximate magnitude spectrogram inversion using the "fast" Griffin-Lim algorithm. + + Given a short-time Fourier transform magnitude matrix (``S``), the algorithm randomly + initializes phase estimates, and then alternates forward- and inverse-STFT + operations. [#]_ + + Note that this assumes reconstruction of a real-valued time-domain signal, and + that ``S`` contains only the non-negative frequencies (as computed by + `stft`). + + The "fast" GL method [#]_ uses a momentum parameter to accelerate convergence. + + .. [#] D. W. Griffin and J. S. Lim, + "Signal estimation from modified short-time Fourier transform," + IEEE Trans. ASSP, vol.32, no.2, pp.236–243, Apr. 1984. + + .. [#] Perraudin, N., Balazs, P., & SĂžndergaard, P. L. + "A fast Griffin-Lim algorithm," + IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (pp. 1-4), + Oct. 2013. + + Parameters + ---------- + S : np.ndarray [shape=(..., n_fft // 2 + 1, t), non-negative] + An array of short-time Fourier transform magnitudes as produced by + `stft`. + + n_iter : int > 0 + The number of iterations to run + + hop_length : None or int > 0 + The hop length of the STFT. If not provided, it will default to ``n_fft // 4`` + + win_length : None or int > 0 + The window length of the STFT. By default, it will equal ``n_fft`` + + n_fft : None or int > 0 + The number of samples per frame. + By default, this will be inferred from the shape of ``S`` as an even number. + However, if an odd frame length was used, you can explicitly set ``n_fft``. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + A window specification as supported by `stft` or `istft` + + center : boolean + If ``True``, the STFT is assumed to use centered frames. + If ``False``, the STFT is assumed to use left-aligned frames. + + dtype : np.dtype + Real numeric type for the time-domain signal. Default is inferred + to match the precision of the input spectrogram. + + length : None or int > 0 + If provided, the output ``y`` is zero-padded or clipped to exactly ``length`` + samples. + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + momentum : number >= 0 + The momentum parameter for fast Griffin-Lim. + Setting this to 0 recovers the original Griffin-Lim method [1]_. + Values near 1 can lead to faster convergence, but above 1 may not converge. + + init : None or 'random' [default] + If 'random' (the default), then phase values are initialized randomly + according to ``random_state``. This is recommended when the input ``S`` is + a magnitude spectrogram with no initial phase estimates. + + If `None`, then the phase is initialized from ``S``. This is useful when + an initial guess for phase can be provided, or when you want to resume + Griffin-Lim from a previous output. + + random_state : None, int, np.random.RandomState, or np.random.Generator + If int, random_state is the seed used by the random number generator + for phase initialization. + + If `np.random.RandomState` or `np.random.Generator` instance, the random number + generator itself. + + If `None`, defaults to the `np.random.default_rng()` object. + + Returns + ------- + y : np.ndarray [shape=(..., n)] + time-domain signal reconstructed from ``S`` + + See Also + -------- + stft + istft + magphase + filters.get_window + + Examples + -------- + A basic STFT inverse example + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> # Get the magnitude spectrogram + >>> S = np.abs(librosa.stft(y)) + >>> # Invert using Griffin-Lim + >>> y_inv = librosa.griffinlim(S) + >>> # Invert without estimating phase + >>> y_istft = librosa.istft(S) + + Wave-plot the results + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> librosa.display.waveshow(y, sr=sr, color='b', ax=ax[0]) + >>> ax[0].set(title='Original', xlabel=None) + >>> ax[0].label_outer() + >>> librosa.display.waveshow(y_inv, sr=sr, color='g', ax=ax[1]) + >>> ax[1].set(title='Griffin-Lim reconstruction', xlabel=None) + >>> ax[1].label_outer() + >>> librosa.display.waveshow(y_istft, sr=sr, color='r', ax=ax[2]) + >>> ax[2].set_title('Magnitude-only istft reconstruction') + """ + if random_state is None: + rng = np.random.default_rng() + elif isinstance(random_state, int): + rng = np.random.RandomState(seed=random_state) # type: ignore + elif isinstance(random_state, (np.random.RandomState, np.random.Generator)): + rng = random_state # type: ignore + else: + raise ParameterError(f"Unsupported random_state={random_state!r}") + + if momentum > 1: + warnings.warn( + f"Griffin-Lim with momentum={momentum} > 1 can be unstable. " + "Proceed with caution!", + stacklevel=2, + ) + elif momentum < 0: + raise ParameterError(f"griffinlim() called with momentum={momentum} < 0") + + # Infer n_fft from the spectrogram shape + if n_fft is None: + n_fft = 2 * (S.shape[-2] - 1) + + # Infer the dtype from S + angles = np.empty(S.shape, dtype=util.dtype_r2c(S.dtype)) + eps = util.tiny(angles) + + if init == "random": + # randomly initialize the phase + angles[:] = util.phasor((2 * np.pi * rng.random(size=S.shape))) + elif init is None: + # Initialize an all ones complex matrix + angles[:] = 1.0 + else: + raise ParameterError(f"init={init} must either None or 'random'") + + # Place-holders for temporary data and reconstructed buffer + rebuilt = None + tprev = None + inverse = None + + # Absorb magnitudes into angles + angles *= S + for _ in range(n_iter): + # Invert with our current estimate of the phases + inverse = istft( + angles, + hop_length=hop_length, + win_length=win_length, + n_fft=n_fft, + window=window, + center=center, + dtype=dtype, + length=length, + out=inverse, + ) + + # Rebuild the spectrogram + rebuilt = stft( + inverse, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + out=rebuilt, + ) + + # Update our phase estimates + angles[:] = rebuilt + if tprev is not None: + angles -= (momentum / (1 + momentum)) * tprev + angles /= np.abs(angles) + eps + angles *= S + # Store + rebuilt, tprev = tprev, rebuilt + + # Return the final phase estimates + return istft( + angles, + hop_length=hop_length, + win_length=win_length, + n_fft=n_fft, + window=window, + center=center, + dtype=dtype, + length=length, + out=inverse, + ) + + +def _spectrogram( + *, + y: Optional[np.ndarray] = None, + S: Optional[np.ndarray] = None, + n_fft: Optional[int] = 2048, + hop_length: Optional[int] = 512, + power: float = 1, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", +) -> Tuple[np.ndarray, int]: + """Retrieve a magnitude spectrogram. + + This is primarily used in feature extraction functions that can operate on + either audio time-series or spectrogram input. + + Parameters + ---------- + y : None or np.ndarray + If provided, an audio time series + + S : None or np.ndarray + Spectrogram input, optional + + n_fft : int > 0 + STFT window size + + hop_length : int > 0 + STFT hop length + + power : float > 0 + Exponent for the magnitude spectrogram, + e.g., 1 for energy, 2 for power, etc. + + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by ``window``. + The window will be of length ``win_length`` and then padded + with zeros to match ``n_fft``. + + If unspecified, defaults to ``win_length = n_fft``. + + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + + .. see also:: `filters.get_window` + + center : boolean + - If ``True``, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If ``False``, then frame ``t`` begins at ``y[t * hop_length]`` + + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + Returns + ------- + S_out : np.ndarray [dtype=np.float] + - If ``S`` is provided as input, then ``S_out == S`` + - Else, ``S_out = |stft(y, ...)|**power`` + n_fft : int > 0 + - If ``S`` is provided, then ``n_fft`` is inferred from ``S`` + - Else, copied from input + """ + if S is not None: + # Infer n_fft from spectrogram shape, but only if it mismatches + if n_fft is None or n_fft // 2 + 1 != S.shape[-2]: + n_fft = 2 * (S.shape[-2] - 1) + else: + # Otherwise, compute a magnitude spectrogram from input + if n_fft is None: + raise ParameterError(f"Unable to compute spectrogram with n_fft={n_fft}") + if y is None: + raise ParameterError( + "Input signal must be provided to compute a spectrogram" + ) + S = ( + np.abs( + stft( + y, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + center=center, + window=window, + pad_mode=pad_mode, + ) + ) + ** power + ) + + return S, n_fft diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1b9f8628718228fa0880d6f2107a1102a48c6637 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Feature extraction +================== + +Spectral features +----------------- + +.. autosummary:: + :toctree: generated/ + + chroma_stft + chroma_cqt + chroma_cens + chroma_vqt + melspectrogram + mfcc + rms + spectral_centroid + spectral_bandwidth + spectral_contrast + spectral_flatness + spectral_rolloff + poly_features + tonnetz + zero_crossing_rate + +Rhythm features +--------------- +.. autosummary:: + :toctree: generated/ + + tempo + tempogram + fourier_tempogram + tempogram_ratio + +Feature manipulation +-------------------- + +.. autosummary:: + :toctree: generated/ + + delta + stack_memory + + +Feature inversion +----------------- + +.. autosummary:: + :toctree: generated + + inverse.mel_to_stft + inverse.mel_to_audio + inverse.mfcc_to_mel + inverse.mfcc_to_audio +""" + +import lazy_loader as lazy + +__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9500aac64eb99abd885613e003bf5541404541ae --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__init__.pyi @@ -0,0 +1,31 @@ +from .utils import ( + delta as delta, + stack_memory as stack_memory, +) +from .spectral import ( + spectral_centroid as spectral_centroid, + spectral_bandwidth as spectral_bandwidth, + spectral_contrast as spectral_contrast, + spectral_rolloff as spectral_rolloff, + spectral_flatness as spectral_flatness, + poly_features as poly_features, + rms as rms, + zero_crossing_rate as zero_crossing_rate, + chroma_stft as chroma_stft, + chroma_cqt as chroma_cqt, + chroma_cens as chroma_cens, + chroma_vqt as chroma_vqt, + melspectrogram as melspectrogram, + mfcc as mfcc, + tonnetz as tonnetz, +) +from .rhythm import ( + tempogram as tempogram, + fourier_tempogram as fourier_tempogram, + tempo as tempo, + tempogram_ratio as tempogram_ratio, +) + +from . import ( + inverse as inverse, +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..512802b63c0fa57328fd35baef27474f55c60863 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/inverse.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/inverse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fff3c0a2f69bf19fd2c67c6a183e9e6ce34258f1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/inverse.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/rhythm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/rhythm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b982677cab6ef8956ee1c4be531b42fdb48171e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/rhythm.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/spectral.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/spectral.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22c394be4260e874972d947c961505d322694f46 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/spectral.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b02d939199244dbc0a3067b5a5489b1fe3b07cd4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/inverse.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/inverse.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd4dfb96265b3b2ae896787086060bb85b5ead9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/inverse.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Feature inversion""" + +import warnings +import numpy as np + +from ..core.fft import get_fftlib +from ..util.exceptions import ParameterError +from ..core.spectrum import griffinlim +from ..core.spectrum import db_to_power +from ..util.utils import tiny +from .. import filters +from ..util import nnls, expand_to +from numpy.typing import DTypeLike +from typing import Any, Optional +from .._typing import _WindowSpec, _PadModeSTFT + +__all__ = ["mel_to_stft", "mel_to_audio", "mfcc_to_mel", "mfcc_to_audio"] + + +def mel_to_stft( + M: np.ndarray, + *, + sr: float = 22050, + n_fft: int = 2048, + power: float = 2.0, + **kwargs: Any, +) -> np.ndarray: + """Approximate STFT magnitude from a Mel power spectrogram. + + Parameters + ---------- + M : np.ndarray [shape=(..., n_mels, n), non-negative] + The spectrogram as produced by `feature.melspectrogram` + sr : number > 0 [scalar] + sampling rate of the underlying signal + n_fft : int > 0 [scalar] + number of FFT components in the resulting STFT + power : float > 0 [scalar] + Exponent for the magnitude melspectrogram + **kwargs : additional keyword arguments for Mel filter bank parameters + fmin : float >= 0 [scalar] + lowest frequency (in Hz) + fmax : float >= 0 [scalar] + highest frequency (in Hz). + If `None`, use ``fmax = sr / 2.0`` + htk : bool [scalar] + use HTK formula instead of Slaney + norm : {None, 'slaney', or number} [scalar] + If 'slaney', divide the triangular mel weights by the width of + the mel band (area normalization). + If numeric, use `librosa.util.normalize` to normalize each filter + by to unit l_p norm. See `librosa.util.normalize` for a full + description of supported norm values (including `+-np.inf`). + Otherwise, leave all the triangles aiming for a peak value of 1.0 + dtype : np.dtype + The data type of the output basis. + By default, uses 32-bit (single-precision) floating point. + + Returns + ------- + S : np.ndarray [shape=(..., n_fft, t), non-negative] + An approximate linear magnitude spectrogram + + See Also + -------- + librosa.feature.melspectrogram + librosa.stft + librosa.filters.mel + librosa.util.nnls + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = librosa.util.abs2(librosa.stft(y)) + >>> mel_spec = librosa.feature.melspectrogram(S=S, sr=sr) + >>> S_inv = librosa.feature.inverse.mel_to_stft(mel_spec, sr=sr) + + Compare the results visually + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> img = librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max, top_db=None), + ... y_axis='log', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='Original STFT') + >>> ax[0].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(S_inv, ref=np.max, top_db=None), + ... y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Reconstructed STFT') + >>> ax[1].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(np.abs(S_inv - S), + ... ref=S.max(), top_db=None), + ... vmax=0, y_axis='log', x_axis='time', cmap='magma', ax=ax[2]) + >>> ax[2].set(title='Residual error (dB)') + >>> fig.colorbar(img, ax=ax, format="%+2.f dB") + """ + # Construct a mel basis with dtype matching the input data + mel_basis = filters.mel( + sr=sr, n_fft=n_fft, n_mels=M.shape[-2], dtype=M.dtype, **kwargs + ) + + # Find the non-negative least squares solution, and apply + # the inverse exponent. + # We'll do the exponentiation in-place. + inverse = nnls(mel_basis, M) + return np.power(inverse, 1.0 / power, out=inverse) + + +def mel_to_audio( + M: np.ndarray, + *, + sr: float = 22050, + n_fft: int = 2048, + hop_length: Optional[int] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + power: float = 2.0, + n_iter: int = 32, + length: Optional[int] = None, + dtype: DTypeLike = np.float32, + **kwargs: Any, +) -> np.ndarray: + """Invert a mel power spectrogram to audio using Griffin-Lim. + + This is primarily a convenience wrapper for: + + >>> S = librosa.feature.inverse.mel_to_stft(M) + >>> y = librosa.griffinlim(S) + + Parameters + ---------- + M : np.ndarray [shape=(..., n_mels, n), non-negative] + The spectrogram as produced by `feature.melspectrogram` + sr : number > 0 [scalar] + sampling rate of the underlying signal + n_fft : int > 0 [scalar] + number of FFT components in the resulting STFT + hop_length : None or int > 0 + The hop length of the STFT. If not provided, it will default to ``n_fft // 4`` + win_length : None or int > 0 + The window length of the STFT. By default, it will equal ``n_fft`` + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + A window specification as supported by `stft` or `istft` + center : boolean + If `True`, the STFT is assumed to use centered frames. + If `False`, the STFT is assumed to use left-aligned frames. + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + power : float > 0 [scalar] + Exponent for the magnitude melspectrogram + n_iter : int > 0 + The number of iterations for Griffin-Lim + length : None or int > 0 + If provided, the output ``y`` is zero-padded or clipped to exactly ``length`` + samples. + dtype : np.dtype + Real numeric type for the time-domain signal. Default is 32-bit float. + **kwargs : additional keyword arguments for Mel filter bank parameters + fmin : float >= 0 [scalar] + lowest frequency (in Hz) + fmax : float >= 0 [scalar] + highest frequency (in Hz). + If `None`, use ``fmax = sr / 2.0`` + htk : bool [scalar] + use HTK formula instead of Slaney + norm : {None, 'slaney', or number} [scalar] + If 'slaney', divide the triangular mel weights by the width of + the mel band (area normalization). + If numeric, use `librosa.util.normalize` to normalize each filter + by to unit l_p norm. See `librosa.util.normalize` for a full + description of supported norm values (including `+-np.inf`). + Otherwise, leave all the triangles aiming for a peak value of 1.0 + + Returns + ------- + y : np.ndarray [shape(..., n,)] + time-domain signal reconstructed from ``M`` + + See Also + -------- + librosa.griffinlim + librosa.feature.melspectrogram + librosa.filters.mel + librosa.feature.inverse.mel_to_stft + """ + stft = mel_to_stft(M, sr=sr, n_fft=n_fft, power=power, **kwargs) + + return griffinlim( + stft, + n_iter=n_iter, + hop_length=hop_length, + win_length=win_length, + n_fft=n_fft, + window=window, + center=center, + dtype=dtype, + length=length, + pad_mode=pad_mode, + ) + + +def mfcc_to_mel( + mfcc: np.ndarray, + *, + n_mels: int = 128, + dct_type: int = 2, + norm: Optional[str] = "ortho", + ref: float = 1.0, + lifter: float = 0, +) -> np.ndarray: + """Invert Mel-frequency cepstral coefficients to approximate a Mel power + spectrogram. + + This inversion proceeds in two steps: + + 1. The inverse DCT is applied to the MFCCs + 2. `librosa.db_to_power` is applied to map the dB-scaled result to a power spectrogram + + Parameters + ---------- + mfcc : np.ndarray [shape=(..., n_mfcc, n)] + The Mel-frequency cepstral coefficients + n_mels : int > 0 + The number of Mel frequencies + dct_type : {1, 2, 3} + Discrete cosine transform (DCT) type + By default, DCT type-2 is used. + norm : None or 'ortho' + If ``dct_type`` is `2 or 3`, setting ``norm='ortho'`` uses an orthonormal + DCT basis. + Normalization is not supported for `dct_type=1`. + ref : float + Reference power for (inverse) decibel calculation + lifter : number >= 0 + If ``lifter>0``, apply inverse liftering (inverse cepstral filtering):: + M[n, :] <- M[n, :] / (1 + sin(pi * (n + 1) / lifter) * lifter / 2) + + Returns + ------- + M : np.ndarray [shape=(..., n_mels, n)] + An approximate Mel power spectrum recovered from ``mfcc`` + + Warns + ----- + UserWarning + due to critical values in lifter array that invokes underflow. + + See Also + -------- + librosa.feature.mfcc + librosa.feature.melspectrogram + scipy.fft.dct + """ + if lifter > 0: + n_mfcc = mfcc.shape[-2] + idx = np.arange(1, 1 + n_mfcc, dtype=mfcc.dtype) + idx = expand_to(idx, ndim=mfcc.ndim, axes=-2) + lifter_sine = 1 + lifter * 0.5 * np.sin(np.pi * idx / lifter) + + # raise a UserWarning if lifter array includes critical values + if np.any(np.abs(lifter_sine) < np.finfo(lifter_sine.dtype).eps): + warnings.warn( + message="lifter array includes critical values that may invoke underflow.", + category=UserWarning, + stacklevel=2, + ) + + # lifter mfcc values + mfcc = mfcc / (lifter_sine + tiny(mfcc)) + + elif lifter != 0: + raise ParameterError("MFCC to mel lifter must be a non-negative number.") + + fft = get_fftlib() + logmel = fft.idct(mfcc, axis=-2, type=dct_type, norm=norm, n=n_mels) + melspec: np.ndarray = db_to_power(logmel, ref=ref) + return melspec + + +def mfcc_to_audio( + mfcc: np.ndarray, + *, + n_mels: int = 128, + dct_type: int = 2, + norm: Optional[str] = "ortho", + ref: float = 1.0, + lifter: float = 0, + **kwargs: Any, +) -> np.ndarray: + """Convert Mel-frequency cepstral coefficients to a time-domain audio signal + + This function is primarily a convenience wrapper for the following steps: + + 1. Convert mfcc to Mel power spectrum (`mfcc_to_mel`) + 2. Convert Mel power spectrum to time-domain audio (`mel_to_audio`) + + Parameters + ---------- + mfcc : np.ndarray [shape=(..., n_mfcc, n)] + The Mel-frequency cepstral coefficients + n_mels : int > 0 + The number of Mel frequencies + dct_type : {1, 2, 3} + Discrete cosine transform (DCT) type + By default, DCT type-2 is used. + norm : None or 'ortho' + If ``dct_type`` is `2 or 3`, setting ``norm='ortho'`` uses an orthonormal + DCT basis. + Normalization is not supported for ``dct_type=1``. + ref : float + Reference power for (inverse) decibel calculation + lifter : number >= 0 + If ``lifter>0``, apply inverse liftering (inverse cepstral filtering):: + M[n, :] <- M[n, :] / (1 + sin(pi * (n + 1) / lifter)) * lifter / 2 + **kwargs : additional keyword arguments to pass through to `mel_to_audio` + M : np.ndarray [shape=(..., n_mels, n), non-negative] + The spectrogram as produced by `feature.melspectrogram` + sr : number > 0 [scalar] + sampling rate of the underlying signal + n_fft : int > 0 [scalar] + number of FFT components in the resulting STFT + hop_length : None or int > 0 + The hop length of the STFT. If not provided, it will default to ``n_fft // 4`` + win_length : None or int > 0 + The window length of the STFT. By default, it will equal ``n_fft`` + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + A window specification as supported by `stft` or `istft` + center : boolean + If `True`, the STFT is assumed to use centered frames. + If `False`, the STFT is assumed to use left-aligned frames. + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + power : float > 0 [scalar] + Exponent for the magnitude melspectrogram + n_iter : int > 0 + The number of iterations for Griffin-Lim + length : None or int > 0 + If provided, the output ``y`` is zero-padded or clipped to exactly ``length`` + samples. + dtype : np.dtype + Real numeric type for the time-domain signal. Default is 32-bit float. + **kwargs : additional keyword arguments for Mel filter bank parameters + fmin : float >= 0 [scalar] + lowest frequency (in Hz) + fmax : float >= 0 [scalar] + highest frequency (in Hz). + If `None`, use ``fmax = sr / 2.0`` + htk : bool [scalar] + use HTK formula instead of Slaney + + Returns + ------- + y : np.ndarray [shape=(..., n)] + A time-domain signal reconstructed from `mfcc` + + See Also + -------- + mfcc_to_mel + mel_to_audio + librosa.feature.mfcc + librosa.griffinlim + scipy.fft.dct + """ + mel_spec = mfcc_to_mel( + mfcc, n_mels=n_mels, dct_type=dct_type, norm=norm, ref=ref, lifter=lifter + ) + + return mel_to_audio(mel_spec, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/rhythm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/rhythm.py new file mode 100644 index 0000000000000000000000000000000000000000..c1181eb6958d78522bd7fb94180209cfafc70136 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/rhythm.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Rhythmic feature extraction""" + +import numpy as np +import scipy + +from .. import util + +from .._cache import cache +from ..core.audio import autocorrelate +from ..core.spectrum import stft +from ..core.convert import tempo_frequencies, time_to_frames +from ..core.harmonic import f0_harmonics +from ..util.exceptions import ParameterError +from ..filters import get_window +from typing import Optional, Callable, Any +from .._typing import _WindowSpec + +__all__ = ["tempogram", "fourier_tempogram", "tempo", "tempogram_ratio"] + + +# -- Rhythmic features -- # +def tempogram( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + onset_envelope: Optional[np.ndarray] = None, + hop_length: int = 512, + win_length: int = 384, + center: bool = True, + window: _WindowSpec = "hann", + norm: Optional[float] = np.inf, +) -> np.ndarray: + """Compute the tempogram: local autocorrelation of the onset strength envelope. [#]_ + + .. [#] Grosche, Peter, Meinard MĂŒller, and Frank Kurth. + "Cyclic tempogram - A mid-level tempo representation for music signals." + ICASSP, 2010. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + Audio time series. Multi-channel is supported. + + sr : number > 0 [scalar] + sampling rate of ``y`` + + onset_envelope : np.ndarray [shape=(..., n) or (..., m, n)] or None + Optional pre-computed onset strength envelope as provided by + `librosa.onset.onset_strength`. + + If multi-dimensional, tempograms are computed independently for each + band (first dimension). + + hop_length : int > 0 + number of audio samples between successive onset measurements + + win_length : int > 0 + length of the onset autocorrelation window (in frames/onset measurements) + The default settings (384) corresponds to ``384 * hop_length / sr ~= 8.9s``. + + center : bool + If `True`, onset autocorrelation windows are centered. + If `False`, windows are left-aligned. + + window : string, function, number, tuple, or np.ndarray [shape=(win_length,)] + A window specification as in `stft`. + + norm : {np.inf, -np.inf, 0, float > 0, None} + Normalization mode. Set to `None` to disable normalization. + + Returns + ------- + tempogram : np.ndarray [shape=(..., win_length, n)] + Localized autocorrelation of the onset strength envelope. + + If given multi-band input (``onset_envelope.shape==(m,n)``) then + ``tempogram[i]`` is the tempogram of ``onset_envelope[i]``. + + Raises + ------ + ParameterError + if neither ``y`` nor ``onset_envelope`` are provided + + if ``win_length < 1`` + + See Also + -------- + fourier_tempogram + librosa.onset.onset_strength + librosa.util.normalize + librosa.stft + + Examples + -------- + >>> # Compute local onset autocorrelation + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=30) + >>> hop_length = 512 + >>> oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length) + >>> tempogram = librosa.feature.tempogram(onset_envelope=oenv, sr=sr, + ... hop_length=hop_length) + >>> # Compute global onset autocorrelation + >>> ac_global = librosa.autocorrelate(oenv, max_size=tempogram.shape[0]) + >>> ac_global = librosa.util.normalize(ac_global) + >>> # Estimate the global tempo for display purposes + >>> tempo = librosa.feature.tempo(onset_envelope=oenv, sr=sr, + ... hop_length=hop_length)[0] + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=4, figsize=(10, 10)) + >>> times = librosa.times_like(oenv, sr=sr, hop_length=hop_length) + >>> ax[0].plot(times, oenv, label='Onset strength') + >>> ax[0].label_outer() + >>> ax[0].legend(frameon=True) + >>> librosa.display.specshow(tempogram, sr=sr, hop_length=hop_length, + >>> x_axis='time', y_axis='tempo', cmap='magma', + ... ax=ax[1]) + >>> ax[1].axhline(tempo, color='w', linestyle='--', alpha=1, + ... label='Estimated tempo={:g}'.format(tempo)) + >>> ax[1].legend(loc='upper right') + >>> ax[1].set(title='Tempogram') + >>> x = np.linspace(0, tempogram.shape[0] * float(hop_length) / sr, + ... num=tempogram.shape[0]) + >>> ax[2].plot(x, np.mean(tempogram, axis=1), label='Mean local autocorrelation') + >>> ax[2].plot(x, ac_global, '--', alpha=0.75, label='Global autocorrelation') + >>> ax[2].set(xlabel='Lag (seconds)') + >>> ax[2].legend(frameon=True) + >>> freqs = librosa.tempo_frequencies(tempogram.shape[0], hop_length=hop_length, sr=sr) + >>> ax[3].semilogx(freqs[1:], np.mean(tempogram[1:], axis=1), + ... label='Mean local autocorrelation', base=2) + >>> ax[3].semilogx(freqs[1:], ac_global[1:], '--', alpha=0.75, + ... label='Global autocorrelation', base=2) + >>> ax[3].axvline(tempo, color='black', linestyle='--', alpha=.8, + ... label='Estimated tempo={:g}'.format(tempo)) + >>> ax[3].legend(frameon=True) + >>> ax[3].set(xlabel='BPM') + >>> ax[3].grid(True) + """ + from ..onset import onset_strength + + if win_length < 1: + raise ParameterError("win_length must be a positive integer") + + ac_window = get_window(window, win_length, fftbins=True) + + if onset_envelope is None: + if y is None: + raise ParameterError("Either y or onset_envelope must be provided") + + onset_envelope = onset_strength(y=y, sr=sr, hop_length=hop_length) + + # Center the autocorrelation windows + n = onset_envelope.shape[-1] + + if center: + padding = [(0, 0) for _ in onset_envelope.shape] + padding[-1] = (int(win_length // 2),) * 2 + onset_envelope = np.pad( + onset_envelope, padding, mode="linear_ramp", end_values=[0, 0] + ) + + # Carve onset envelope into frames + odf_frame = util.frame(onset_envelope, frame_length=win_length, hop_length=1) + + # Truncate to the length of the original signal + if center: + odf_frame = odf_frame[..., :n] + + # explicit broadcast of ac_window + ac_window = util.expand_to(ac_window, ndim=odf_frame.ndim, axes=-2) + + # Window, autocorrelate, and normalize + return util.normalize( + autocorrelate(odf_frame * ac_window, axis=-2), norm=norm, axis=-2 + ) + + +def fourier_tempogram( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + onset_envelope: Optional[np.ndarray] = None, + hop_length: int = 512, + win_length: int = 384, + center: bool = True, + window: _WindowSpec = "hann", +) -> np.ndarray: + """Compute the Fourier tempogram: the short-time Fourier transform of the + onset strength envelope. [#]_ + + .. [#] Grosche, Peter, Meinard MĂŒller, and Frank Kurth. + "Cyclic tempogram - A mid-level tempo representation for music signals." + ICASSP, 2010. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + Audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + onset_envelope : np.ndarray [shape=(..., n)] or None + Optional pre-computed onset strength envelope as provided by + ``librosa.onset.onset_strength``. + Multi-channel is supported. + hop_length : int > 0 + number of audio samples between successive onset measurements + win_length : int > 0 + length of the onset window (in frames/onset measurements) + The default settings (384) corresponds to ``384 * hop_length / sr ~= 8.9s``. + center : bool + If `True`, onset windows are centered. + If `False`, windows are left-aligned. + window : string, function, number, tuple, or np.ndarray [shape=(win_length,)] + A window specification as in `stft`. + + Returns + ------- + tempogram : np.ndarray [shape=(..., win_length // 2 + 1, n)] + Complex short-time Fourier transform of the onset envelope. + + Raises + ------ + ParameterError + if neither ``y`` nor ``onset_envelope`` are provided + + if ``win_length < 1`` + + See Also + -------- + tempogram + librosa.onset.onset_strength + librosa.util.normalize + librosa.stft + + Examples + -------- + >>> # Compute local onset autocorrelation + >>> y, sr = librosa.load(librosa.ex('nutcracker')) + >>> hop_length = 512 + >>> oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length) + >>> tempogram = librosa.feature.fourier_tempogram(onset_envelope=oenv, sr=sr, + ... hop_length=hop_length) + >>> # Compute the auto-correlation tempogram, unnormalized to make comparison easier + >>> ac_tempogram = librosa.feature.tempogram(onset_envelope=oenv, sr=sr, + ... hop_length=hop_length, norm=None) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True) + >>> ax[0].plot(librosa.times_like(oenv), oenv, label='Onset strength') + >>> ax[0].legend(frameon=True) + >>> ax[0].label_outer() + >>> librosa.display.specshow(np.abs(tempogram), sr=sr, hop_length=hop_length, + >>> x_axis='time', y_axis='fourier_tempo', cmap='magma', + ... ax=ax[1]) + >>> ax[1].set(title='Fourier tempogram') + >>> ax[1].label_outer() + >>> librosa.display.specshow(ac_tempogram, sr=sr, hop_length=hop_length, + >>> x_axis='time', y_axis='tempo', cmap='magma', + ... ax=ax[2]) + >>> ax[2].set(title='Autocorrelation tempogram') + """ + from ..onset import onset_strength + + if win_length < 1: + raise ParameterError("win_length must be a positive integer") + + if onset_envelope is None: + if y is None: + raise ParameterError("Either y or onset_envelope must be provided") + + onset_envelope = onset_strength(y=y, sr=sr, hop_length=hop_length) + + # Generate the short-time Fourier transform + return stft( + onset_envelope, n_fft=win_length, hop_length=1, center=center, window=window + ) + + +@cache(level=30) +def tempo( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + onset_envelope: Optional[np.ndarray] = None, + tg: Optional[np.ndarray] = None, + hop_length: int = 512, + start_bpm: float = 120, + std_bpm: float = 1.0, + ac_size: float = 8.0, + max_tempo: Optional[float] = 320.0, + aggregate: Optional[Callable[..., Any]] = np.mean, + prior: Optional[scipy.stats.rv_continuous] = None, +) -> np.ndarray: + """Estimate the tempo (beats per minute) + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of the time series + onset_envelope : np.ndarray [shape=(..., n)] + pre-computed onset strength envelope + tg : np.ndarray + pre-computed tempogram. If provided, then `y` and + `onset_envelope` are ignored, and `win_length` is + inferred from the shape of the tempogram. + hop_length : int > 0 [scalar] + hop length of the time series + start_bpm : float [scalar] + initial guess of the BPM + std_bpm : float > 0 [scalar] + standard deviation of tempo distribution + ac_size : float > 0 [scalar] + length (in seconds) of the auto-correlation window + max_tempo : float > 0 [scalar, optional] + If provided, only estimate tempo below this threshold + aggregate : callable [optional] + Aggregation function for estimating global tempo. + If `None`, then tempo is estimated independently for each frame. + prior : scipy.stats.rv_continuous [optional] + A prior distribution over tempo (in beats per minute). + By default, a pseudo-log-normal prior is used. + If given, ``start_bpm`` and ``std_bpm`` will be ignored. + + Returns + ------- + tempo : np.ndarray + estimated tempo (beats per minute). + If input is multi-channel, one tempo estimate per channel is provided. + + See Also + -------- + librosa.onset.onset_strength + librosa.feature.tempogram + + Notes + ----- + This function caches at level 30. + + Examples + -------- + >>> # Estimate a static tempo + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=30) + >>> onset_env = librosa.onset.onset_strength(y=y, sr=sr) + >>> tempo = librosa.feature.tempo(onset_envelope=onset_env, sr=sr) + >>> tempo + array([143.555]) + + >>> # Or a static tempo with a uniform prior instead + >>> import scipy.stats + >>> prior = scipy.stats.uniform(30, 300) # uniform over 30-300 BPM + >>> utempo = librosa.feature.tempo(onset_envelope=onset_env, sr=sr, prior=prior) + >>> utempo + array([161.499]) + + >>> # Or a dynamic tempo + >>> dtempo = librosa.feature.tempo(onset_envelope=onset_env, sr=sr, + ... aggregate=None) + >>> dtempo + array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) + + >>> # Dynamic tempo with a proper log-normal prior + >>> prior_lognorm = scipy.stats.lognorm(loc=np.log(120), scale=120, s=1) + >>> dtempo_lognorm = librosa.feature.tempo(onset_envelope=onset_env, sr=sr, + ... aggregate=None, + ... prior=prior_lognorm) + >>> dtempo_lognorm + array([ 89.103, 89.103, 89.103, ..., 123.047, 123.047, 123.047]) + + Plot the estimated tempo against the onset autocorrelation + + >>> import matplotlib.pyplot as plt + >>> # Convert to scalar + >>> tempo = tempo.item() + >>> utempo = utempo.item() + >>> # Compute 2-second windowed autocorrelation + >>> hop_length = 512 + >>> ac = librosa.autocorrelate(onset_env, max_size=2 * sr // hop_length) + >>> freqs = librosa.tempo_frequencies(len(ac), sr=sr, + ... hop_length=hop_length) + >>> # Plot on a BPM axis. We skip the first (0-lag) bin. + >>> fig, ax = plt.subplots() + >>> ax.semilogx(freqs[1:], librosa.util.normalize(ac)[1:], + ... label='Onset autocorrelation', base=2) + >>> ax.axvline(tempo, 0, 1, alpha=0.75, linestyle='--', color='r', + ... label='Tempo (default prior): {:.2f} BPM'.format(tempo)) + >>> ax.axvline(utempo, 0, 1, alpha=0.75, linestyle=':', color='g', + ... label='Tempo (uniform prior): {:.2f} BPM'.format(utempo)) + >>> ax.set(xlabel='Tempo (BPM)', title='Static tempo estimation') + >>> ax.grid(True) + >>> ax.legend() + + Plot dynamic tempo estimates over a tempogram + + >>> fig, ax = plt.subplots() + >>> tg = librosa.feature.tempogram(onset_envelope=onset_env, sr=sr, + ... hop_length=hop_length) + >>> librosa.display.specshow(tg, x_axis='time', y_axis='tempo', cmap='magma', ax=ax) + >>> ax.plot(librosa.times_like(dtempo), dtempo, + ... color='c', linewidth=1.5, label='Tempo estimate (default prior)') + >>> ax.plot(librosa.times_like(dtempo_lognorm), dtempo_lognorm, + ... color='c', linewidth=1.5, linestyle='--', + ... label='Tempo estimate (lognorm prior)') + >>> ax.set(title='Dynamic tempo estimation') + >>> ax.legend() + """ + if start_bpm <= 0: + raise ParameterError("start_bpm must be strictly positive") + + if tg is None: + win_length = time_to_frames(ac_size, sr=sr, hop_length=hop_length).item() + + tg = tempogram( + y=y, + sr=sr, + onset_envelope=onset_envelope, + hop_length=hop_length, + win_length=win_length, + ) + else: + # Override window length by what's actually given + win_length = tg.shape[-2] + + # Eventually, we want this to work for time-varying tempo + if aggregate is not None: + tg = aggregate(tg, axis=-1, keepdims=True) + + assert tg is not None + + # Get the BPM values for each bin, skipping the 0-lag bin + bpms = tempo_frequencies(win_length, hop_length=hop_length, sr=sr) + + # Weight the autocorrelation by a log-normal distribution + if prior is None: + logprior = -0.5 * ((np.log2(bpms) - np.log2(start_bpm)) / std_bpm) ** 2 + else: + logprior = prior.logpdf(bpms) + + # Kill everything above the max tempo + if max_tempo is not None: + max_idx = int(np.argmax(bpms < max_tempo)) + logprior[:max_idx] = -np.inf + # explicit axis expansion + logprior = util.expand_to(logprior, ndim=tg.ndim, axes=-2) + + # Get the maximum, weighted by the prior + # Using log1p here for numerical stability + best_period = np.argmax(np.log1p(1e6 * tg) + logprior, axis=-2) + + tempo_est: np.ndarray = np.take(bpms, best_period) + return tempo_est + + +@cache(level=40) +def tempogram_ratio( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + onset_envelope: Optional[np.ndarray] = None, + tg: Optional[np.ndarray] = None, + bpm: Optional[np.ndarray] = None, + hop_length: int = 512, + win_length: int = 384, + start_bpm: float = 120, + std_bpm: float = 1.0, + max_tempo: Optional[float] = 320.0, + freqs: Optional[np.ndarray] = None, + factors: Optional[np.ndarray] = None, + aggregate: Optional[Callable[..., Any]] = None, + prior: Optional[scipy.stats.rv_continuous] = None, + center: bool = True, + window: _WindowSpec = "hann", + kind: str = "linear", + fill_value: float = 0, + norm: Optional[float] = np.inf, +) -> np.ndarray: + """Tempogram ratio features, also known as spectral rhythm patterns. [1]_ + + This function summarizes the energy at metrically important multiples + of the tempo. For example, if the tempo corresponds to the quarter-note + period, the tempogram ratio will measure the energy at the eighth note, + sixteenth note, half note, whole note, etc. periods, as well as dotted + and triplet ratios. + + By default, the multiplicative factors used here are as specified by + [2]_. If the estimated tempo corresponds to a quarter note, these factors + will measure relative energy at the following metrical subdivisions: + + +-------+--------+------------------+ + | Index | Factor | Description | + +=======+========+==================+ + | 0 | 4 | Sixteenth note | + +-------+--------+------------------+ + | 1 | 8/3 | Dotted sixteenth | + +-------+--------+------------------+ + | 2 | 3 | Eighth triplet | + +-------+--------+------------------+ + | 3 | 2 | Eighth note | + +-------+--------+------------------+ + | 4 | 4/3 | Dotted eighth | + +-------+--------+------------------+ + | 5 | 3/2 | Quarter triplet | + +-------+--------+------------------+ + | 6 | 1 | Quarter note | + +-------+--------+------------------+ + | 7 | 2/3 | Dotted quarter | + +-------+--------+------------------+ + | 8 | 3/4 | Half triplet | + +-------+--------+------------------+ + | 9 | 1/2 | Half note | + +-------+--------+------------------+ + | 10 | 1/3 | Dotted half note | + +-------+--------+------------------+ + | 11 | 3/8 | Whole triplet | + +-------+--------+------------------+ + | 12 | 1/4 | Whole note | + +-------+--------+------------------+ + + .. [1] Peeters, Geoffroy. + "Rhythm Classification Using Spectral Rhythm Patterns." + In ISMIR, pp. 644-647. 2005. + + .. [2] Prockup, Matthew, Andreas F. Ehmann, Fabien Gouyon, Erik M. Schmidt, and Youngmoo E. Kim. + "Modeling musical rhythm at scale with the music genome project." + In 2015 IEEE workshop on applications of signal processing to audio and acoustics (WASPAA), pp. 1-5. IEEE, 2015. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series + sr : number > 0 [scalar] + sampling rate of the time series + onset_envelope : np.ndarray [shape=(..., n)] + pre-computed onset strength envelope + tg : np.ndarray + pre-computed tempogram. If provided, then `y` and + `onset_envelope` are ignored, and `win_length` is + inferred from the shape of the tempogram. + bpm : np.ndarray + pre-computed tempo estimate. This must be a per-frame + estimate, and have dimension compatible with `tg`. + hop_length : int > 0 [scalar] + hop length of the time series + win_length : int > 0 [scalar] + window length of the autocorrelation window for tempogram + calculation + start_bpm : float [scalar] + initial guess of the BPM if `bpm` is not provided + std_bpm : float > 0 [scalar] + standard deviation of tempo distribution + max_tempo : float > 0 [scalar, optional] + If provided, only estimate tempo below this threshold + freqs : np.ndarray + Frequencies (in BPM) of the tempogram axis. + factors : np.ndarray + Multiples of the fundamental tempo (bpm) to estimate. + If not provided, the factors are as specified above. + prior : scipy.stats.rv_continuous [optional] + A prior distribution over tempo (in beats per minute). + By default, a pseudo-log-normal prior is used. + If given, ``start_bpm`` and ``std_bpm`` will be ignored. + center : bool + If `True`, onset windows are centered. + If `False`, windows are left-aligned. + aggregate : callable [optional] + Aggregation function for estimating global tempogram ratio. + If `None`, then ratios are estimated independently for each frame. + window : string, function, number, tuple, or np.ndarray [shape=(win_length,)] + A window specification as in `stft`. + kind : str + Interpolation mode for measuring tempogram ratios + fill_value : float + The value to fill when extrapolating beyond the observed + frequency range. + norm : {np.inf, -np.inf, 0, float > 0, None} + Normalization mode. Set to `None` to disable normalization. + + Returns + ------- + tgr : np.ndarray + The tempogram ratio for the specified factors. + If `aggregate` is provided, the trailing time axis + will be removed. + If `aggregate` is not provided (default), ratios + will be estimated for each frame. + + See Also + -------- + tempogram + tempo + librosa.f0_harmonics + librosa.tempo_frequencies + + Examples + -------- + Compute tempogram ratio features using the default factors + for a waltz (3/4 time) + + >>> import matplotlib.pyplot as plt + >>> y, sr = librosa.load(librosa.ex('sweetwaltz')) + >>> tempogram = librosa.feature.tempogram(y=y, sr=sr) + >>> tgr = librosa.feature.tempogram_ratio(tg=tempogram, sr=sr) + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> librosa.display.specshow(tempogram, x_axis='time', y_axis='tempo', + ... ax=ax[0]) + >>> librosa.display.specshow(tgr, x_axis='time', ax=ax[1]) + >>> ax[0].label_outer() + >>> ax[0].set(title="Tempogram") + >>> ax[1].set(title="Tempogram ratio") + """ + # Get a tempogram and time-varying tempo estimate + if tg is None: + tg = tempogram( + y=y, + sr=sr, + onset_envelope=onset_envelope, + hop_length=hop_length, + win_length=win_length, + center=center, + window=window, + norm=norm, + ) + + if freqs is None: + freqs = tempo_frequencies(sr=sr, n_bins=len(tg), hop_length=hop_length) + + # Estimate tempo per-frame, no aggregation yet + if bpm is None: + bpm = tempo( + sr=sr, + tg=tg, + hop_length=hop_length, + start_bpm=start_bpm, + std_bpm=std_bpm, + max_tempo=max_tempo, + aggregate=None, + prior=prior, + ) + + if factors is None: + # metric multiples from Prockup'15 + factors = np.array( + [4, 8 / 3, 3, 2, 4 / 3, 3 / 2, 1, 2 / 3, 3 / 4, 1 / 2, 1 / 3, 3 / 8, 1 / 4] + ) + + tgr = f0_harmonics( + tg, freqs=freqs, f0=bpm, harmonics=factors, kind=kind, fill_value=fill_value + ) + + if aggregate is not None: + return aggregate(tgr, axis=-1) # type: ignore + + return tgr diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/spectral.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..eea1bbcd3e77d8b31051537cbde93606e90d1aec --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/spectral.py @@ -0,0 +1,2151 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Spectral feature extraction""" + +import numpy as np +import scipy +import scipy.signal + +from .. import util +from .. import filters +from ..util.exceptions import ParameterError + +from ..core.fft import get_fftlib +from ..core.convert import fft_frequencies +from ..core.audio import zero_crossings +from ..core.spectrum import power_to_db, _spectrogram +from ..core.constantq import cqt, hybrid_cqt, vqt +from ..core.pitch import estimate_tuning +from typing import Any, Optional, Union, Collection +from typing_extensions import Literal +from numpy.typing import DTypeLike +from .._typing import _FloatLike_co, _WindowSpec, _PadMode, _PadModeSTFT + + +__all__ = [ + "spectral_centroid", + "spectral_bandwidth", + "spectral_contrast", + "spectral_rolloff", + "spectral_flatness", + "poly_features", + "rms", + "zero_crossing_rate", + "chroma_stft", + "chroma_cqt", + "chroma_cens", + "chroma_vqt", + "melspectrogram", + "mfcc", + "tonnetz", +] + + +# -- Spectral features -- # +def spectral_centroid( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + freq: Optional[np.ndarray] = None, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", +) -> np.ndarray: + """Compute the spectral centroid. + + Each frame of a magnitude spectrogram is normalized and treated as a + distribution over frequency bins, from which the mean (centroid) is + extracted per frame. + + More precisely, the centroid at frame ``t`` is defined as [#]_:: + + centroid[t] = sum_k S[k, t] * freq[k] / (sum_j S[j, t]) + + where ``S`` is a magnitude spectrogram, and ``freq`` is the array of + frequencies (e.g., FFT frequencies in Hz) of the rows of ``S``. + + .. [#] Klapuri, A., & Davy, M. (Eds.). (2007). Signal processing + methods for music transcription, chapter 5. + Springer Science & Business Media. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + (optional) spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + freq : None or np.ndarray [shape=(d,) or shape=(d, t)] + Center frequencies for spectrogram bins. + If `None`, then FFT bin center frequencies are used. + Otherwise, it can be a single array of ``d`` center frequencies, + or a matrix of center frequencies as constructed by + `librosa.reassigned_spectrogram` + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length ``win_length`` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + `t` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + + Returns + ------- + centroid : np.ndarray [shape=(..., 1, t)] + centroid frequencies + + See Also + -------- + librosa.stft : Short-time Fourier Transform + librosa.reassigned_spectrogram : Time-frequency reassigned spectrogram + + Examples + -------- + From time-series input: + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> cent = librosa.feature.spectral_centroid(y=y, sr=sr) + >>> cent + array([[1768.888, 1921.774, ..., 5663.477, 5813.683]]) + + From spectrogram input: + + >>> S, phase = librosa.magphase(librosa.stft(y=y)) + >>> librosa.feature.spectral_centroid(S=S) + array([[1768.888, 1921.774, ..., 5663.477, 5813.683]]) + + Using variable bin center frequencies: + + >>> freqs, times, D = librosa.reassigned_spectrogram(y, fill_nan=True) + >>> librosa.feature.spectral_centroid(S=np.abs(D), freq=freqs) + array([[1768.838, 1921.801, ..., 5663.513, 5813.747]]) + + Plot the result + + >>> import matplotlib.pyplot as plt + >>> times = librosa.times_like(cent) + >>> fig, ax = plt.subplots() + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax) + >>> ax.plot(times, cent.T, label='Spectral centroid', color='w') + >>> ax.legend(loc='upper right') + >>> ax.set(title='log Power spectrogram') + """ + # input is time domain:y or spectrogram:s + # + + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + if not np.isrealobj(S): + raise ParameterError( + "Spectral centroid is only defined " "with real-valued input" + ) + elif np.any(S < 0): + raise ParameterError( + "Spectral centroid is only defined " "with non-negative energies" + ) + + # Compute the center frequencies of each bin + if freq is None: + freq = fft_frequencies(sr=sr, n_fft=n_fft) + + if freq.ndim == 1: + # reshape for broadcasting + freq = util.expand_to(freq, ndim=S.ndim, axes=-2) + + # Column-normalize S + centroid: np.ndarray = np.sum( + freq * util.normalize(S, norm=1, axis=-2), axis=-2, keepdims=True + ) + return centroid + + +def spectral_bandwidth( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + freq: Optional[np.ndarray] = None, + centroid: Optional[np.ndarray] = None, + norm: bool = True, + p: float = 2, +) -> np.ndarray: + """Compute p'th-order spectral bandwidth. + + The spectral bandwidth [#]_ at frame ``t`` is computed by:: + + (sum_k S[k, t] * (freq[k, t] - centroid[t])**p)**(1/p) + + .. [#] Klapuri, A., & Davy, M. (Eds.). (2007). Signal processing + methods for music transcription, chapter 5. + Springer Science & Business Media. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + (optional) spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length ``win_length`` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If ``False``, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + freq : None or np.ndarray [shape=(d,) or shape=(..., d, t)] + Center frequencies for spectrogram bins. + If `None`, then FFT bin center frequencies are used. + Otherwise, it can be a single array of ``d`` center frequencies, + or a matrix of center frequencies as constructed by + `librosa.reassigned_spectrogram` + centroid : None or np.ndarray [shape=(..., 1, t)] + pre-computed centroid frequencies + norm : bool + Normalize per-frame spectral energy (sum to one) + p : float > 0 + Power to raise deviation from spectral centroid. + + Returns + ------- + bandwidth : np.ndarray [shape=(..., 1, t)] + frequency bandwidth for each frame + + Examples + -------- + From time-series input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr) + >>> spec_bw + array([[1273.836, 1228.873, ..., 2952.357, 3013.68 ]]) + + From spectrogram input + + >>> S, phase = librosa.magphase(librosa.stft(y=y)) + >>> librosa.feature.spectral_bandwidth(S=S) + array([[1273.836, 1228.873, ..., 2952.357, 3013.68 ]]) + + Using variable bin center frequencies + + >>> freqs, times, D = librosa.reassigned_spectrogram(y, fill_nan=True) + >>> librosa.feature.spectral_bandwidth(S=np.abs(D), freq=freqs) + array([[1274.637, 1228.786, ..., 2952.4 , 3013.735]]) + + Plot the result + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> times = librosa.times_like(spec_bw) + >>> centroid = librosa.feature.spectral_centroid(S=S) + >>> ax[0].semilogy(times, spec_bw[0], label='Spectral bandwidth') + >>> ax[0].set(ylabel='Hz', xticks=[], xlim=[times.min(), times.max()]) + >>> ax[0].legend() + >>> ax[0].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='log Power spectrogram') + >>> ax[1].fill_between(times, np.maximum(0, centroid[0] - spec_bw[0]), + ... np.minimum(centroid[0] + spec_bw[0], sr/2), + ... alpha=0.5, label='Centroid +- bandwidth') + >>> ax[1].plot(times, centroid[0], label='Spectral centroid', color='w') + >>> ax[1].legend(loc='lower right') + """ + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + if not np.isrealobj(S): + raise ParameterError( + "Spectral bandwidth is only defined " "with real-valued input" + ) + elif np.any(S < 0): + raise ParameterError( + "Spectral bandwidth is only defined " "with non-negative energies" + ) + + # If we don't have a centroid provided, compute it using the existing + # spectrogram S + if centroid is None: + centroid = spectral_centroid( + y=y, sr=sr, S=S, n_fft=n_fft, hop_length=hop_length, freq=freq + ) + + # Compute the center frequencies of each bin + if freq is None: + freq = fft_frequencies(sr=sr, n_fft=n_fft) + + if freq.ndim == 1: + deviation = np.abs( + np.subtract.outer(centroid[..., 0, :], freq).swapaxes(-2, -1) + ) + else: + deviation = np.abs(freq - centroid) + + # Column-normalize S + if norm: + S = util.normalize(S, norm=1, axis=-2) + + bw: np.ndarray = np.sum(S * deviation**p, axis=-2, keepdims=True) ** (1.0 / p) + return bw + + +def spectral_contrast( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + freq: Optional[np.ndarray] = None, + fmin: float = 200.0, + n_bands: int = 6, + quantile: float = 0.02, + linear: bool = False, +) -> np.ndarray: + """Compute spectral contrast + + Each frame of a spectrogram ``S`` is divided into sub-bands. + For each sub-band, the energy contrast is estimated by comparing + the mean energy in the top quantile (peak energy) to that of the + bottom quantile (valley energy). High contrast values generally + correspond to clear, narrow-band signals, while low contrast values + correspond to broad-band noise. [#]_ + + .. [#] Jiang, Dan-Ning, Lie Lu, Hong-Jiang Zhang, Jian-Hua Tao, + and Lian-Hong Cai. + "Music type classification by spectral contrast feature." + In Multimedia and Expo, 2002. ICME'02. Proceedings. + 2002 IEEE International Conference on, vol. 1, pp. 113-116. + IEEE, 2002. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + (optional) spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + freq : None or np.ndarray [shape=(d,)] + Center frequencies for spectrogram bins. + If `None`, then FFT bin center frequencies are used. + Otherwise, it can be a single array of ``d`` center frequencies. + fmin : float > 0 + Frequency cutoff for the first bin ``[0, fmin]`` + Subsequent bins will cover ``[fmin, 2*fmin]`, `[2*fmin, 4*fmin]``, etc. + n_bands : int > 1 + number of frequency bands + quantile : float in (0, 1) + quantile for determining peaks and valleys + linear : bool + If `True`, return the linear difference of magnitudes: + ``peaks - valleys``. + If `False`, return the logarithmic difference: + ``log(peaks) - log(valleys)``. + + Returns + ------- + contrast : np.ndarray [shape=(..., n_bands + 1, t)] + each row of spectral contrast values corresponds to a given + octave-based frequency + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + >>> contrast = librosa.feature.spectral_contrast(S=S, sr=sr) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> img1 = librosa.display.specshow(librosa.amplitude_to_db(S, + ... ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[0]) + >>> fig.colorbar(img1, ax=[ax[0]], format='%+2.0f dB') + >>> ax[0].set(title='Power spectrogram') + >>> ax[0].label_outer() + >>> img2 = librosa.display.specshow(contrast, x_axis='time', ax=ax[1]) + >>> fig.colorbar(img2, ax=[ax[1]]) + >>> ax[1].set(ylabel='Frequency bands', title='Spectral contrast') + """ + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + # Compute the center frequencies of each bin + if freq is None: + freq = fft_frequencies(sr=sr, n_fft=n_fft) + + freq = np.atleast_1d(freq) + + if freq.ndim != 1 or len(freq) != S.shape[-2]: + raise ParameterError(f"freq.shape mismatch: expected ({S.shape[-2]:d},)") + + if n_bands < 1 or not isinstance(n_bands, (int, np.integer)): + raise ParameterError("n_bands must be a positive integer") + + if not 0.0 < quantile < 1.0: + raise ParameterError("quantile must lie in the range (0, 1)") + + if fmin <= 0: + raise ParameterError("fmin must be a positive number") + + octa = np.zeros(n_bands + 2) + octa[1:] = fmin * (2.0 ** np.arange(0, n_bands + 1)) + + if np.any(octa[:-1] >= 0.5 * sr): + raise ParameterError( + "Frequency band exceeds Nyquist. " "Reduce either fmin or n_bands." + ) + + # shape of valleys and peaks based on spectrogram + shape = list(S.shape) + shape[-2] = n_bands + 1 + + valley = np.zeros(shape) + peak = np.zeros_like(valley) + + for k, (f_low, f_high) in enumerate(zip(octa[:-1], octa[1:])): + current_band = np.logical_and(freq >= f_low, freq <= f_high) + + idx = np.flatnonzero(current_band) + + if k > 0: + current_band[idx[0] - 1] = True + + if k == n_bands: + current_band[idx[-1] + 1 :] = True + + sub_band = S[..., current_band, :] + + if k < n_bands: + sub_band = sub_band[..., :-1, :] + + # Always take at least one bin from each side + idx = np.rint(quantile * np.sum(current_band)) + idx = int(np.maximum(idx, 1)) + + sortedr = np.sort(sub_band, axis=-2) + + valley[..., k, :] = np.mean(sortedr[..., :idx, :], axis=-2) + peak[..., k, :] = np.mean(sortedr[..., -idx:, :], axis=-2) + + contrast: np.ndarray + if linear: + contrast = peak - valley + else: + contrast = power_to_db(peak) - power_to_db(valley) + return contrast + + +def spectral_rolloff( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + freq: Optional[np.ndarray] = None, + roll_percent: float = 0.85, +) -> np.ndarray: + """Compute roll-off frequency. + + The roll-off frequency is defined for each frame as the center frequency + for a spectrogram bin such that at least roll_percent (0.85 by default) + of the energy of the spectrum in this frame is contained in this bin and + the bins below. This can be used to, e.g., approximate the maximum (or + minimum) frequency by setting roll_percent to a value close to 1 (or 0). + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(d, t)] or None + (optional) spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + freq : None or np.ndarray [shape=(d,) or shape=(..., d, t)] + Center frequencies for spectrogram bins. + If `None`, then FFT bin center frequencies are used. + Otherwise, it can be a single array of ``d`` center frequencies, + .. note:: ``freq`` is assumed to be sorted in increasing order + roll_percent : float [0 < roll_percent < 1] + Roll-off percentage. + + Returns + ------- + rolloff : np.ndarray [shape=(..., 1, t)] + roll-off frequency for each frame + + Examples + -------- + From time-series input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> # Approximate maximum frequencies with roll_percent=0.85 (default) + >>> librosa.feature.spectral_rolloff(y=y, sr=sr) + array([[2583.984, 3036.182, ..., 9173.145, 9248.511]]) + >>> # Approximate maximum frequencies with roll_percent=0.99 + >>> rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.99) + >>> rolloff + array([[ 7192.09 , 6739.893, ..., 10960.4 , 10992.7 ]]) + >>> # Approximate minimum frequencies with roll_percent=0.01 + >>> rolloff_min = librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.01) + >>> rolloff_min + array([[516.797, 538.33 , ..., 764.429, 764.429]]) + + From spectrogram input + + >>> S, phase = librosa.magphase(librosa.stft(y)) + >>> librosa.feature.spectral_rolloff(S=S, sr=sr) + array([[2583.984, 3036.182, ..., 9173.145, 9248.511]]) + + >>> # With a higher roll percentage: + >>> librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.95) + array([[ 3919.043, 3994.409, ..., 10443.604, 10594.336]]) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax) + >>> ax.plot(librosa.times_like(rolloff), rolloff[0], label='Roll-off frequency (0.99)') + >>> ax.plot(librosa.times_like(rolloff), rolloff_min[0], color='w', + ... label='Roll-off frequency (0.01)') + >>> ax.legend(loc='lower right') + >>> ax.set(title='log Power spectrogram') + """ + if not 0.0 < roll_percent < 1.0: + raise ParameterError("roll_percent must lie in the range (0, 1)") + + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + if not np.isrealobj(S): + raise ParameterError( + "Spectral rolloff is only defined " "with real-valued input" + ) + elif np.any(S < 0): + raise ParameterError( + "Spectral rolloff is only defined " "with non-negative energies" + ) + + # Compute the center frequencies of each bin + if freq is None: + freq = fft_frequencies(sr=sr, n_fft=n_fft) + + # Make sure that frequency can be broadcast + if freq.ndim == 1: + # reshape for broadcasting + freq = util.expand_to(freq, ndim=S.ndim, axes=-2) + + total_energy = np.cumsum(S, axis=-2) + # (channels,freq,frames) + + threshold = roll_percent * total_energy[..., -1, :] + + # reshape threshold for broadcasting + threshold = np.expand_dims(threshold, axis=-2) + + ind = np.where(total_energy < threshold, np.nan, 1) + + rolloff: np.ndarray = np.nanmin(ind * freq, axis=-2, keepdims=True) + return rolloff + + +def spectral_flatness( + *, + y: Optional[np.ndarray] = None, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + amin: float = 1e-10, + power: float = 2.0, +) -> np.ndarray: + """Compute spectral flatness + + Spectral flatness (or tonality coefficient) is a measure to + quantify how much noise-like a sound is, as opposed to being + tone-like [#]_. A high spectral flatness (closer to 1.0) + indicates the spectrum is similar to white noise. + It is often converted to decibel. + + .. [#] Dubnov, Shlomo "Generalization of spectral flatness + measure for non-gaussian linear processes" + IEEE Signal Processing Letters, 2004, Vol. 11. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + S : np.ndarray [shape=(..., d, t)] or None + (optional) pre-computed spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame `t` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + amin : float > 0 [scalar] + minimum threshold for ``S`` (=added noise floor for numerical stability) + power : float > 0 [scalar] + Exponent for the magnitude spectrogram. + e.g., 1 for energy, 2 for power, etc. + Power spectrogram is usually used for computing spectral flatness. + + Returns + ------- + flatness : np.ndarray [shape=(..., 1, t)] + spectral flatness for each frame. + The returned value is in [0, 1] and often converted to dB scale. + + Examples + -------- + From time-series input + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> flatness = librosa.feature.spectral_flatness(y=y) + >>> flatness + array([[0.001, 0. , ..., 0.218, 0.184]], dtype=float32) + + From spectrogram input + + >>> S, phase = librosa.magphase(librosa.stft(y)) + >>> librosa.feature.spectral_flatness(S=S) + array([[0.001, 0. , ..., 0.218, 0.184]], dtype=float32) + + From power spectrogram input + + >>> S, phase = librosa.magphase(librosa.stft(y)) + >>> S_power = S ** 2 + >>> librosa.feature.spectral_flatness(S=S_power, power=1.0) + array([[0.001, 0. , ..., 0.218, 0.184]], dtype=float32) + + """ + if amin <= 0: + raise ParameterError("amin must be strictly positive") + + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + power=1.0, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + if not np.isrealobj(S): + raise ParameterError( + "Spectral flatness is only defined " "with real-valued input" + ) + elif np.any(S < 0): + raise ParameterError( + "Spectral flatness is only defined " "with non-negative energies" + ) + + S_thresh = np.maximum(amin, S**power) + gmean = np.exp(np.mean(np.log(S_thresh), axis=-2, keepdims=True)) + amean = np.mean(S_thresh, axis=-2, keepdims=True) + flatness: np.ndarray = gmean / amean + return flatness + + +def rms( + *, + y: Optional[np.ndarray] = None, + S: Optional[np.ndarray] = None, + frame_length: int = 2048, + hop_length: int = 512, + center: bool = True, + pad_mode: _PadMode = "constant", + dtype: DTypeLike = np.float32, +) -> np.ndarray: + """Compute root-mean-square (RMS) value for each frame, either from the + audio samples ``y`` or from a spectrogram ``S``. + + Computing the RMS value from audio samples is faster as it doesn't require + a STFT calculation. However, using a spectrogram will give a more accurate + representation of energy over time because its frames can be windowed, + thus prefer using ``S`` if it's already available. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + (optional) audio time series. Required if ``S`` is not input. + Multi-channel is supported. + S : np.ndarray [shape=(..., d, t)] or None + (optional) spectrogram magnitude. Required if ``y`` is not input. + frame_length : int > 0 [scalar] + length of analysis frame (in samples) for energy calculation + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + center : bool + If `True` and operating on time-domain input (``y``), pad the signal + by ``frame_length//2`` on either side. + If operating on spectrogram input, this has no effect. + pad_mode : str + Padding mode for centered analysis. See `numpy.pad` for valid + values. + dtype : np.dtype, optional + Data type of the output array. Defaults to float32. + + Returns + ------- + rms : np.ndarray [shape=(..., 1, t)] + RMS value for each frame + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.feature.rms(y=y) + array([[1.248e-01, 1.259e-01, ..., 1.845e-05, 1.796e-05]], + dtype=float32) + + Or from spectrogram input + + >>> S, phase = librosa.magphase(librosa.stft(y)) + >>> rms = librosa.feature.rms(S=S) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> times = librosa.times_like(rms) + >>> ax[0].semilogy(times, rms[0], label='RMS Energy') + >>> ax[0].set(xticks=[]) + >>> ax[0].legend() + >>> ax[0].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='log Power spectrogram') + + Use a STFT window of constant ones and no frame centering to get consistent + results with the RMS computed from the audio samples ``y`` + + >>> S = librosa.magphase(librosa.stft(y, window=np.ones, center=False))[0] + >>> librosa.feature.rms(S=S) + >>> plt.show() + + """ + if y is not None: + if center: + padding = [(0, 0) for _ in range(y.ndim)] + padding[-1] = (int(frame_length // 2), int(frame_length // 2)) + y = np.pad(y, padding, mode=pad_mode) + + x = util.frame(y, frame_length=frame_length, hop_length=hop_length) + + # Calculate power + power = np.mean(util.abs2(x, dtype=dtype), axis=-2, keepdims=True) + elif S is not None: + # Check the frame length + if S.shape[-2] != frame_length // 2 + 1: + raise ParameterError( + "Since S.shape[-2] is {}, " + "frame_length is expected to be {} or {}; " + "found {}".format( + S.shape[-2], S.shape[-2] * 2 - 2, S.shape[-2] * 2 - 1, frame_length + ) + ) + + # power spectrogram + x = util.abs2(S, dtype=dtype) + + # Adjust the DC and sr/2 component + x[..., 0, :] *= 0.5 + if frame_length % 2 == 0: + x[..., -1, :] *= 0.5 + + # Calculate power + power = 2 * np.sum(x, axis=-2, keepdims=True) / frame_length**2 + else: + raise ParameterError("Either `y` or `S` must be input.") + + rms_result: np.ndarray = np.sqrt(power) + return rms_result + + +def poly_features( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + order: int = 1, + freq: Optional[np.ndarray] = None, +) -> np.ndarray: + """Get coefficients of fitting an nth-order polynomial to the columns + of a spectrogram. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + audio sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + (optional) spectrogram magnitude + n_fft : int > 0 [scalar] + FFT window size + hop_length : int > 0 [scalar] + hop length for STFT. See `librosa.stft` for details. + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + `t` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + order : int > 0 + order of the polynomial to fit + freq : None or np.ndarray [shape=(d,) or shape=(..., d, t)] + Center frequencies for spectrogram bins. + If `None`, then FFT bin center frequencies are used. + Otherwise, it can be a single array of ``d`` center frequencies, + or a matrix of center frequencies as constructed by + `librosa.reassigned_spectrogram` + + Returns + ------- + coefficients : np.ndarray [shape=(..., order+1, t)] + polynomial coefficients for each frame. + + ``coefficients[..., 0, :]`` corresponds to the highest degree (``order``), + + ``coefficients[..., 1, :]`` corresponds to the next highest degree (``order-1``), + + down to the constant term ``coefficients[..., order, :]``. + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + + Fit a degree-0 polynomial (constant) to each frame + + >>> p0 = librosa.feature.poly_features(S=S, order=0) + + Fit a linear polynomial to each frame + + >>> p1 = librosa.feature.poly_features(S=S, order=1) + + Fit a quadratic to each frame + + >>> p2 = librosa.feature.poly_features(S=S, order=2) + + Plot the results for comparison + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=4, sharex=True, figsize=(8, 8)) + >>> times = librosa.times_like(p0) + >>> ax[0].plot(times, p0[0], label='order=0', alpha=0.8) + >>> ax[0].plot(times, p1[1], label='order=1', alpha=0.8) + >>> ax[0].plot(times, p2[2], label='order=2', alpha=0.8) + >>> ax[0].legend() + >>> ax[0].label_outer() + >>> ax[0].set(ylabel='Constant term ') + >>> ax[1].plot(times, p1[0], label='order=1', alpha=0.8) + >>> ax[1].plot(times, p2[1], label='order=2', alpha=0.8) + >>> ax[1].set(ylabel='Linear term') + >>> ax[1].label_outer() + >>> ax[1].legend() + >>> ax[2].plot(times, p2[0], label='order=2', alpha=0.8) + >>> ax[2].set(ylabel='Quadratic term') + >>> ax[2].legend() + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[3]) + """ + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + # Compute the center frequencies of each bin + if freq is None: + freq = fft_frequencies(sr=sr, n_fft=n_fft) + + coefficients: np.ndarray + + if freq.ndim == 1: + # If frequencies are constant over frames, then we only need to fit once + fitter = np.vectorize( + lambda y: np.polyfit(freq, y, order), signature="(f,t)->(d,t)" + ) + coefficients = fitter(S) + else: + # Otherwise, we have variable frequencies, and need to fit independently + fitter = np.vectorize( + lambda x, y: np.polyfit(x, y, order), signature="(f),(f)->(d)" + ) + + # We have to do some axis swapping to preserve layout + # otherwise, the new dimension gets put at the end instead of the penultimate position + coefficients = fitter(freq.swapaxes(-2, -1), S.swapaxes(-2, -1)).swapaxes( + -2, -1 + ) + + return coefficients + + +def zero_crossing_rate( + y: np.ndarray, + *, + frame_length: int = 2048, + hop_length: int = 512, + center: bool = True, + **kwargs: Any, +) -> np.ndarray: + """Compute the zero-crossing rate of an audio time series. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] + Audio time series. Multi-channel is supported. + frame_length : int > 0 + Length of the frame over which to compute zero crossing rates + hop_length : int > 0 + Number of samples to advance for each frame + center : bool + If `True`, frames are centered by padding the edges of ``y``. + This is similar to the padding in `librosa.stft`, + but uses edge-value copies instead of zero-padding. + **kwargs : additional keyword arguments to pass to `librosa.zero_crossings` + threshold : float >= 0 + If specified, values where ``-threshold <= y <= threshold`` are + clipped to 0. + ref_magnitude : float > 0 or callable + If numeric, the threshold is scaled relative to ``ref_magnitude``. + If callable, the threshold is scaled relative to + ``ref_magnitude(np.abs(y))``. + zero_pos : boolean + If ``True`` then the value 0 is interpreted as having positive sign. + If ``False``, then 0, -1, and +1 all have distinct signs. + axis : int + Axis along which to compute zero-crossings. + .. note:: By default, the ``pad`` parameter is set to `False`, which + differs from the default specified by + `librosa.zero_crossings`. + + Returns + ------- + zcr : np.ndarray [shape=(..., 1, t)] + ``zcr[..., 0, i]`` is the fraction of zero crossings in frame ``i`` + + See Also + -------- + librosa.zero_crossings : Compute zero-crossings in a time-series + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.feature.zero_crossing_rate(y) + array([[0.044, 0.074, ..., 0.488, 0.355]]) + """ + # check if audio is valid + util.valid_audio(y) + + if center: + padding = [(0, 0) for _ in range(y.ndim)] + padding[-1] = (int(frame_length // 2), int(frame_length // 2)) + y = np.pad(y, padding, mode="edge") + + y_framed = util.frame(y, frame_length=frame_length, hop_length=hop_length) + + kwargs["axis"] = -2 + kwargs.setdefault("pad", False) + + crossings = zero_crossings(y_framed, **kwargs) + + zcrate: np.ndarray = np.mean(crossings, axis=-2, keepdims=True) + return zcrate + + +# -- Chroma --# +def chroma_stft( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + norm: Optional[float] = np.inf, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + tuning: Optional[float] = None, + n_chroma: int = 12, + **kwargs: Any, +) -> np.ndarray: + """Compute a chromagram from a waveform or power spectrogram. + + This implementation is derived from ``chromagram_E`` [#]_ + + .. [#] Ellis, Daniel P.W. "Chroma feature analysis and synthesis" + 2007/04/21 + https://www.ee.columbia.edu/~dpwe/resources/matlab/chroma-ansyn/ + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + power spectrogram + norm : float or None + Column-wise normalization. + See `librosa.util.normalize` for details. + If `None`, no normalization is performed. + n_fft : int > 0 [scalar] + FFT window size if provided ``y, sr`` instead of ``S`` + hop_length : int > 0 [scalar] + hop length if provided ``y, sr`` instead of ``S`` + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + tuning : float [scalar] or None. + Deviation from A440 tuning in fractional chroma bins. + If `None`, it is automatically estimated. + n_chroma : int > 0 [scalar] + Number of chroma bins to produce (12 by default). + **kwargs : additional keyword arguments to parameterize chroma filters. + ctroct : float > 0 [scalar] + octwidth : float > 0 or None [scalar] + ``ctroct`` and ``octwidth`` specify a dominance window: + a Gaussian weighting centered on ``ctroct`` (in octs, A0 = 27.5Hz) + and with a gaussian half-width of ``octwidth``. + Set ``octwidth`` to `None` to use a flat weighting. + norm : float > 0 or np.inf + Normalization factor for each filter + base_c : bool + If True, the filter bank will start at 'C'. + If False, the filter bank will start at 'A'. + dtype : np.dtype + The data type of the output basis. + By default, uses 32-bit (single-precision) floating point. + + Returns + ------- + chromagram : np.ndarray [shape=(..., n_chroma, t)] + Normalized energy for each chroma bin at each frame. + + See Also + -------- + librosa.filters.chroma : Chroma filter bank construction + librosa.util.normalize : Vector normalization + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=15) + >>> librosa.feature.chroma_stft(y=y, sr=sr) + array([[1. , 0.962, ..., 0.143, 0.278], + [0.688, 0.745, ..., 0.103, 0.162], + ..., + [0.468, 0.598, ..., 0.18 , 0.342], + [0.681, 0.702, ..., 0.553, 1. ]], dtype=float32) + + Use an energy (magnitude) spectrum instead of power spectrogram + + >>> S = np.abs(librosa.stft(y)) + >>> chroma = librosa.feature.chroma_stft(S=S, sr=sr) + >>> chroma + array([[1. , 0.973, ..., 0.527, 0.569], + [0.774, 0.81 , ..., 0.518, 0.506], + ..., + [0.624, 0.73 , ..., 0.611, 0.644], + [0.766, 0.822, ..., 0.92 , 1. ]], dtype=float32) + + Use a pre-computed power spectrogram with a larger frame + + >>> S = np.abs(librosa.stft(y, n_fft=4096))**2 + >>> chroma = librosa.feature.chroma_stft(S=S, sr=sr) + >>> chroma + array([[0.994, 0.873, ..., 0.169, 0.227], + [0.735, 0.64 , ..., 0.141, 0.135], + ..., + [0.6 , 0.937, ..., 0.214, 0.257], + [0.743, 0.937, ..., 0.684, 0.815]], dtype=float32) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> img = librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[0]) + >>> fig.colorbar(img, ax=[ax[0]]) + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(chroma, y_axis='chroma', x_axis='time', ax=ax[1]) + >>> fig.colorbar(img, ax=[ax[1]]) + """ + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + power=2, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + if tuning is None: + tuning = estimate_tuning(S=S, sr=sr, bins_per_octave=n_chroma) + + # Get the filter bank + chromafb = filters.chroma( + sr=sr, n_fft=n_fft, tuning=tuning, n_chroma=n_chroma, **kwargs + ) + + # Compute raw chroma + raw_chroma = np.einsum("cf,...ft->...ct", chromafb, S, optimize=True) + + # Compute normalization factor for each frame + return util.normalize(raw_chroma, norm=norm, axis=-2) + + +def chroma_cqt( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + C: Optional[np.ndarray] = None, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + norm: Optional[Union[int, float]] = np.inf, + threshold: float = 0.0, + tuning: Optional[float] = None, + n_chroma: int = 12, + n_octaves: int = 7, + window: Optional[np.ndarray] = None, + bins_per_octave: Optional[int] = 36, + cqt_mode: str = "full", +) -> np.ndarray: + r"""Constant-Q chromagram + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] + audio time series. Multi-channel is supported. + sr : number > 0 + sampling rate of ``y`` + C : np.ndarray [shape=(..., d, t)] [Optional] + a pre-computed constant-Q spectrogram + hop_length : int > 0 + number of samples between successive chroma frames + fmin : float > 0 + minimum frequency to analyze in the CQT. + Default: `C1 ~= 32.7 Hz` + norm : int > 0, +-np.inf, or None + Column-wise normalization of the chromagram. + threshold : float + Pre-normalization energy threshold. Values below the + threshold are discarded, resulting in a sparse chromagram. + tuning : float [scalar] or None. + Deviation (in fractions of a CQT bin) from A440 tuning + n_chroma : int > 0 + Number of chroma bins to produce + n_octaves : int > 0 + Number of octaves to analyze above ``fmin`` + window : None or np.ndarray + Optional window parameter to `filters.cq_to_chroma` + bins_per_octave : int > 0, optional + Number of bins per octave in the CQT. + Must be an integer multiple of ``n_chroma``. + Default: 36 (3 bins per semitone) + If `None`, it will match ``n_chroma``. + cqt_mode : ['full', 'hybrid'] + Constant-Q transform mode + + Returns + ------- + chromagram : np.ndarray [shape=(..., n_chroma, t)] + The output chromagram + + See Also + -------- + librosa.util.normalize + librosa.cqt + librosa.hybrid_cqt + chroma_stft + + Examples + -------- + Compare a long-window STFT chromagram to the CQT chromagram + + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=15) + >>> chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr, + ... n_chroma=12, n_fft=4096) + >>> chroma_cq = librosa.feature.chroma_cqt(y=y, sr=sr) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> librosa.display.specshow(chroma_stft, y_axis='chroma', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='chroma_stft') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(chroma_cq, y_axis='chroma', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='chroma_cqt') + >>> fig.colorbar(img, ax=ax) + """ + cqt_func = {"full": cqt, "hybrid": hybrid_cqt} + + if bins_per_octave is None: + bins_per_octave = n_chroma + elif np.remainder(bins_per_octave, n_chroma) != 0: + raise ParameterError( + f"bins_per_octave={bins_per_octave} must be an integer " + f"multiple of n_chroma={n_chroma}" + ) + + # Build the CQT if we don't have one already + if C is None: + if y is None: + raise ParameterError( + "At least one of C or y must be provided to compute chroma" + ) + C = np.abs( + cqt_func[cqt_mode]( + y, + sr=sr, + hop_length=hop_length, + fmin=fmin, + n_bins=n_octaves * bins_per_octave, + bins_per_octave=bins_per_octave, + tuning=tuning, + ) + ) + + # Map to chroma + cq_to_chr = filters.cq_to_chroma( + C.shape[-2], + bins_per_octave=bins_per_octave, + n_chroma=n_chroma, + fmin=fmin, + window=window, + ) + + chroma = np.einsum("cf,...ft->...ct", cq_to_chr, C, optimize=True) + + if threshold is not None: + chroma[chroma < threshold] = 0.0 + + # Normalize + chroma = util.normalize(chroma, norm=norm, axis=-2) + + return chroma + + +def chroma_cens( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + C: Optional[np.ndarray] = None, + hop_length: int = 512, + fmin: Optional[_FloatLike_co] = None, + tuning: Optional[float] = None, + n_chroma: int = 12, + n_octaves: int = 7, + bins_per_octave: int = 36, + cqt_mode: str = "full", + window: Optional[np.ndarray] = None, + norm: Optional[float] = 2, + win_len_smooth: Optional[int] = 41, + smoothing_window: _WindowSpec = "hann", +) -> np.ndarray: + r"""Compute the chroma variant "Chroma Energy Normalized" (CENS) + + To compute CENS features, following steps are taken after obtaining chroma vectors + using `chroma_cqt`: [#]_. + + 1. L-1 normalization of each chroma vector + 2. Quantization of amplitude based on "log-like" amplitude thresholds + 3. (optional) Smoothing with sliding window. Default window length = 41 frames + 4. (not implemented) Downsampling + + CENS features are robust to dynamics, timbre and articulation, thus these are commonly used in audio + matching and retrieval applications. + + .. [#] Meinard MĂŒller and Sebastian Ewert + "Chroma Toolbox: MATLAB implementations for extracting variants of chroma-based audio features" + In Proceedings of the International Conference on Music Information Retrieval (ISMIR), 2011. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] + audio time series. Multi-channel is supported. + sr : number > 0 + sampling rate of ``y`` + C : np.ndarray [shape=(d, t)] [Optional] + a pre-computed constant-Q spectrogram + hop_length : int > 0 + number of samples between successive chroma frames + fmin : float > 0 + minimum frequency to analyze in the CQT. + Default: `C1 ~= 32.7 Hz` + norm : int > 0, +-np.inf, or None + Column-wise normalization of the chromagram. + tuning : float [scalar] or None. + Deviation (in fractions of a CQT bin) from A440 tuning + n_chroma : int > 0 + Number of chroma bins to produce + n_octaves : int > 0 + Number of octaves to analyze above ``fmin`` + window : None or np.ndarray + Optional window parameter to `filters.cq_to_chroma` + bins_per_octave : int > 0 + Number of bins per octave in the CQT. + Default: 36 + cqt_mode : ['full', 'hybrid'] + Constant-Q transform mode + win_len_smooth : int > 0 or None + Length of temporal smoothing window. `None` disables temporal smoothing. + Default: 41 + smoothing_window : str, float or tuple + Type of window function for temporal smoothing. See `librosa.filters.get_window` for possible inputs. + Default: 'hann' + + Returns + ------- + cens : np.ndarray [shape=(..., n_chroma, t)] + The output cens-chromagram + + See Also + -------- + chroma_cqt : Compute a chromagram from a constant-Q transform. + chroma_stft : Compute a chromagram from an STFT spectrogram or waveform. + librosa.filters.get_window : Compute a window function. + + Examples + -------- + Compare standard cqt chroma to CENS. + + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=15) + >>> chroma_cens = librosa.feature.chroma_cens(y=y, sr=sr) + >>> chroma_cq = librosa.feature.chroma_cqt(y=y, sr=sr) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img = librosa.display.specshow(chroma_cq, y_axis='chroma', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='chroma_cq') + >>> ax[0].label_outer() + >>> librosa.display.specshow(chroma_cens, y_axis='chroma', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='chroma_cens') + >>> fig.colorbar(img, ax=ax) + """ + if not ( + (win_len_smooth is None) + or (isinstance(win_len_smooth, (int, np.integer)) and win_len_smooth > 0) + ): + raise ParameterError( + f"win_len_smooth={win_len_smooth} must be a positive integer or None" + ) + + chroma = chroma_cqt( + y=y, + C=C, + sr=sr, + hop_length=hop_length, + fmin=fmin, + bins_per_octave=bins_per_octave, + tuning=tuning, + norm=None, + n_chroma=n_chroma, + n_octaves=n_octaves, + cqt_mode=cqt_mode, + window=window, + ) + + # L1-Normalization + chroma = util.normalize(chroma, norm=1, axis=-2) + + # Quantize amplitudes + QUANT_STEPS = [0.4, 0.2, 0.1, 0.05] + QUANT_WEIGHTS = [0.25, 0.25, 0.25, 0.25] + + chroma_quant = np.zeros_like(chroma) + + for cur_quant_step_idx, cur_quant_step in enumerate(QUANT_STEPS): + chroma_quant += (chroma > cur_quant_step) * QUANT_WEIGHTS[cur_quant_step_idx] + + if win_len_smooth: + # Apply temporal smoothing + win = filters.get_window(smoothing_window, win_len_smooth + 2, fftbins=False) + win /= np.sum(win) + + # reshape for broadcasting + win = util.expand_to(win, ndim=chroma_quant.ndim, axes=-1) + + cens = scipy.ndimage.convolve(chroma_quant, win, mode="constant") + else: + cens = chroma_quant + + # L2-Normalization + return util.normalize(cens, norm=norm, axis=-2) + + +def chroma_vqt( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + V: Optional[np.ndarray] = None, + hop_length: int = 512, + fmin: Optional[float] = None, + intervals: Union[str, Collection[float]], + norm: Optional[float] = np.inf, + threshold: float = 0.0, + n_octaves: int = 7, + bins_per_octave: int = 12, + gamma: float = 0, +) -> np.ndarray: + r"""Variable-Q chromagram + + This differs from CQT-based chroma by supporting non-equal temperament + intervals. + + Note: unlike CQT- and STFT-based chroma, VQT chroma does not aggregate energy + from neighboring frequency bands. As a result, the number of chroma + features produced is equal to the number of intervals used, or equivalently, + the number of bins per octave in the underlying VQT representation. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] + audio time series. Multi-channel is supported. + sr : number > 0 + sampling rate of ``y`` + V : np.ndarray [shape=(..., d, t)] [Optional] + a pre-computed variable-Q spectrogram + hop_length : int > 0 + number of samples between successive chroma frames + fmin : float > 0 + minimum frequency to analyze in the CQT. + Default: `C1 ~= 32.7 Hz` + intervals : str or array of floats in [1, 2) + Either a string specification for an interval set, e.g., + `'equal'`, `'pythagorean'`, `'ji3'`, etc. or an array of + intervals expressed as numbers between 1 and 2. + .. see also:: librosa.interval_frequencies + norm : int > 0, +-np.inf, or None + Column-wise normalization of the chromagram. + threshold : float + Pre-normalization energy threshold. Values below the + threshold are discarded, resulting in a sparse chromagram. + n_octaves : int > 0 + Number of octaves to analyze above ``fmin`` + bins_per_octave : int > 0, optional + Number of bins per octave in the VQT. + gamma : number > 0 [scalar] + Bandwidth offset for determining filter lengths. + .. see also:: librosa.vqt + + Returns + ------- + chromagram : np.ndarray [shape=(..., bins_per_octave, t)] + The output chromagram + + See Also + -------- + librosa.util.normalize + librosa.vqt + chroma_cqt + librosa.interval_frequencies + + Examples + -------- + Compare an equal-temperament CQT chromagram to a 5-limit just intonation + chromagram. Both use 36 bins per octave. + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> n_bins = 36 + >>> chroma_cq = librosa.feature.chroma_cqt(y=y, sr=sr, n_chroma=n_bins) + >>> chroma_vq = librosa.feature.chroma_vqt(y=y, sr=sr, + ... intervals='ji5', + ... bins_per_octave=n_bins) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> librosa.display.specshow(chroma_cq, y_axis='chroma', x_axis='time', + ... ax=ax[0], bins_per_octave=n_bins) + >>> ax[0].set(ylabel='chroma_cqt') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(chroma_vq, y_axis='chroma_fjs', x_axis='time', + ... ax=ax[1], bins_per_octave=n_bins, + ... intervals='ji5') + >>> ax[1].set(ylabel='chroma_vqt') + >>> fig.colorbar(img, ax=ax) + """ + # If intervals are provided as an array, override BPO + if not isinstance(intervals, str): + bins_per_octave = len(intervals) + + # Build the CQT if we don't have one already + if V is None: + if y is None: + raise ParameterError( + "At least one of y or V must be provided to compute chroma" + ) + V = np.abs( + vqt( + y=y, + sr=sr, + hop_length=hop_length, + fmin=fmin, + intervals=intervals, + n_bins=n_octaves * bins_per_octave, + bins_per_octave=bins_per_octave, + gamma=gamma, + ) + ) + + # Map to chroma + vq_to_chr = filters.cq_to_chroma( + V.shape[-2], + bins_per_octave=bins_per_octave, + n_chroma=bins_per_octave, + fmin=fmin, + ) + + chroma = np.einsum("cf,...ft->...ct", vq_to_chr, V, optimize=True) + + if threshold is not None: + chroma[chroma < threshold] = 0.0 + + # Normalize + chroma = util.normalize(chroma, norm=norm, axis=-2) + + return chroma + + +def tonnetz( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + chroma: Optional[np.ndarray] = None, + **kwargs: Any, +) -> np.ndarray: + """Compute the tonal centroid features (tonnetz) + + This representation uses the method of [#]_ to project chroma features + onto a 6-dimensional basis representing the perfect fifth, minor third, + and major third each as two-dimensional coordinates. + + .. [#] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic + Change in Musical Audio." In Proceedings of the 1st ACM Workshop + on Audio and Music Computing Multimedia (pp. 21-26). + Santa Barbara, CA, USA: ACM Press. doi:10.1145/1178723.1178727. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] or None + Audio time series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + chroma : np.ndarray [shape=(n_chroma, t)] or None + Normalized energy for each chroma bin at each frame. + If `None`, a cqt chromagram is performed. + **kwargs : Additional keyword arguments to `chroma_cqt`, + if ``chroma`` is not pre-computed. + C : np.ndarray [shape=(..., d, t)] [Optional] + a pre-computed constant-Q spectrogram + hop_length : int > 0 + number of samples between successive chroma frames + fmin : float > 0 + minimum frequency to analyze in the CQT. + Default: `C1 ~= 32.7 Hz` + norm : int > 0, +-np.inf, or None + Column-wise normalization of the chromagram. + threshold : float + Pre-normalization energy threshold. Values below the + threshold are discarded, resulting in a sparse chromagram. + tuning : float [scalar] or None. + Deviation (in fractions of a CQT bin) from A440 tuning + n_chroma : int > 0 + Number of chroma bins to produce + n_octaves : int > 0 + Number of octaves to analyze above ``fmin`` + window : None or np.ndarray + Optional window parameter to `filters.cq_to_chroma` + bins_per_octave : int > 0, optional + Number of bins per octave in the CQT. + Must be an integer multiple of ``n_chroma``. + Default: 36 (3 bins per semitone) + If `None`, it will match ``n_chroma``. + cqt_mode : ['full', 'hybrid'] + Constant-Q transform mode + + Returns + ------- + tonnetz : np.ndarray [shape(..., 6, t)] + Tonal centroid features for each frame. + + Tonnetz dimensions: + - 0: Fifth x-axis + - 1: Fifth y-axis + - 2: Minor x-axis + - 3: Minor y-axis + - 4: Major x-axis + - 5: Major y-axis + + See Also + -------- + chroma_cqt : Compute a chromagram from a constant-Q transform. + chroma_stft : Compute a chromagram from an STFT spectrogram or waveform. + + Examples + -------- + Compute tonnetz features from the harmonic component of a song + + >>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=10, offset=10) + >>> y = librosa.effects.harmonic(y) + >>> tonnetz = librosa.feature.tonnetz(y=y, sr=sr) + >>> tonnetz + array([[ 0.007, -0.026, ..., 0.055, 0.056], + [-0.01 , -0.009, ..., -0.012, -0.017], + ..., + [ 0.006, -0.021, ..., -0.012, -0.01 ], + [-0.009, 0.031, ..., -0.05 , -0.037]]) + + Compare the tonnetz features to `chroma_cqt` + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> img1 = librosa.display.specshow(tonnetz, + ... y_axis='tonnetz', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='Tonal Centroids (Tonnetz)') + >>> ax[0].label_outer() + >>> img2 = librosa.display.specshow(librosa.feature.chroma_cqt(y=y, sr=sr), + ... y_axis='chroma', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Chroma') + >>> fig.colorbar(img1, ax=[ax[0]]) + >>> fig.colorbar(img2, ax=[ax[1]]) + """ + if y is None and chroma is None: + raise ParameterError( + "Either the audio samples or the chromagram must be " + "passed as an argument." + ) + + if chroma is None: + chroma = chroma_cqt(y=y, sr=sr, **kwargs) + + # Generate Transformation matrix + dim_map = np.linspace(0, 12, num=chroma.shape[-2], endpoint=False) + + scale = np.asarray([7.0 / 6, 7.0 / 6, 3.0 / 2, 3.0 / 2, 2.0 / 3, 2.0 / 3]) + + V = np.multiply.outer(scale, dim_map) + + # Even rows compute sin() + V[::2] -= 0.5 + + R = np.array([1, 1, 1, 1, 0.5, 0.5]) # Fifths # Minor # Major + + phi = R[:, np.newaxis] * np.cos(np.pi * V) + + # Do the transform to tonnetz + ton: np.ndarray = np.einsum( + "pc,...ci->...pi", phi, util.normalize(chroma, norm=1, axis=-2), optimize=True + ) + return ton + + +# -- Mel spectrogram and MFCCs -- # +def mfcc( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_mfcc: int = 20, + dct_type: int = 2, + norm: Optional[str] = "ortho", + lifter: float = 0, + mel_norm: Optional[Union[Literal["slaney"], float]] = "slaney", + **kwargs: Any, +) -> np.ndarray: + """Mel-frequency cepstral coefficients (MFCCs) + + .. warning:: If multi-channel audio input ``y`` is provided, the MFCC + calculation will depend on the peak loudness (in decibels) across + all channels. The result may differ from independent MFCC calculation + of each channel. + + Parameters + ---------- + y : np.ndarray [shape=(..., n,)] or None + audio time series. Multi-channel is supported.. + sr : number > 0 [scalar] + sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] or None + log-power Mel spectrogram + n_mfcc : int > 0 [scalar] + number of MFCCs to return + dct_type : {1, 2, 3} + Discrete cosine transform (DCT) type. + By default, DCT type-2 is used. + norm : None or 'ortho' + If ``dct_type`` is `2 or 3`, setting ``norm='ortho'`` uses an ortho-normal + DCT basis. + Normalization is not supported for ``dct_type=1``. + lifter : number >= 0 + If ``lifter>0``, apply *liftering* (cepstral filtering) to the MFCCs:: + M[n, :] <- M[n, :] * (1 + sin(pi * (n + 1) / lifter) * lifter / 2) + Setting ``lifter >= 2 * n_mfcc`` emphasizes the higher-order coefficients. + As ``lifter`` increases, the coefficient weighting becomes approximately linear. + mel_norm : `norm` argument to `melspectrogram` + **kwargs : additional keyword arguments to `melspectrogram` + if operating on time series input + n_fft : int > 0 [scalar] + length of the FFT window + hop_length : int > 0 [scalar] + number of samples between successive frames. + See `librosa.stft` + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + power : float > 0 [scalar] + Exponent applied to the spectrum before calculating the melspectrogram when the input is a time signal, + e.g. 1 for magnitude, 2 for power **(default)**, etc. + **kwargs : additional keyword arguments for Mel filter bank parameters + n_mels : int > 0 [scalar] + number of Mel bands to generate + fmin : float >= 0 [scalar] + lowest frequency (in Hz) + fmax : float >= 0 [scalar] + highest frequency (in Hz). + If `None`, use ``fmax = sr / 2.0`` + htk : bool [scalar] + use HTK formula instead of Slaney + dtype : np.dtype + The data type of the output basis. + By default, uses 32-bit (single-precision) floating point. + + Returns + ------- + M : np.ndarray [shape=(..., n_mfcc, t)] + MFCC sequence + + See Also + -------- + melspectrogram + scipy.fft.dct + + Examples + -------- + Generate mfccs from a time series + + >>> y, sr = librosa.load(librosa.ex('libri1')) + >>> librosa.feature.mfcc(y=y, sr=sr) + array([[-565.919, -564.288, ..., -426.484, -434.668], + [ 10.305, 12.509, ..., 88.43 , 90.12 ], + ..., + [ 2.807, 2.068, ..., -6.725, -5.159], + [ 2.822, 2.244, ..., -6.198, -6.177]], dtype=float32) + + Using a different hop length and HTK-style Mel frequencies + + >>> librosa.feature.mfcc(y=y, sr=sr, hop_length=1024, htk=True) + array([[-5.471e+02, -5.464e+02, ..., -4.446e+02, -4.200e+02], + [ 1.361e+01, 1.402e+01, ..., 9.764e+01, 9.869e+01], + ..., + [ 4.097e-01, -2.029e+00, ..., -1.051e+01, -1.130e+01], + [-1.119e-01, -1.688e+00, ..., -3.442e+00, -4.687e+00]], + dtype=float32) + + Use a pre-computed log-power Mel spectrogram + + >>> S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, + ... fmax=8000) + >>> librosa.feature.mfcc(S=librosa.power_to_db(S)) + array([[-559.974, -558.449, ..., -411.96 , -420.458], + [ 11.018, 13.046, ..., 76.972, 80.888], + ..., + [ 2.713, 2.379, ..., 1.464, -2.835], + [ 2.712, 2.619, ..., 2.209, 0.648]], dtype=float32) + + Get more components + + >>> mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40) + + Visualize the MFCC series + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> img = librosa.display.specshow(librosa.power_to_db(S, ref=np.max), + ... x_axis='time', y_axis='mel', fmax=8000, + ... ax=ax[0]) + >>> fig.colorbar(img, ax=[ax[0]]) + >>> ax[0].set(title='Mel spectrogram') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(mfccs, x_axis='time', ax=ax[1]) + >>> fig.colorbar(img, ax=[ax[1]]) + >>> ax[1].set(title='MFCC') + + Compare different DCT bases + + >>> m_slaney = librosa.feature.mfcc(y=y, sr=sr, dct_type=2) + >>> m_htk = librosa.feature.mfcc(y=y, sr=sr, dct_type=3) + >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True) + >>> img1 = librosa.display.specshow(m_slaney, x_axis='time', ax=ax[0]) + >>> ax[0].set(title='RASTAMAT / Auditory toolbox (dct_type=2)') + >>> fig.colorbar(img, ax=[ax[0]]) + >>> img2 = librosa.display.specshow(m_htk, x_axis='time', ax=ax[1]) + >>> ax[1].set(title='HTK-style (dct_type=3)') + >>> fig.colorbar(img2, ax=[ax[1]]) + """ + if S is None: + # multichannel behavior may be different due to relative noise floor differences between channels + S = power_to_db(melspectrogram(y=y, sr=sr, norm = mel_norm, **kwargs)) + + fft = get_fftlib() + M: np.ndarray = fft.dct(S, axis=-2, type=dct_type, norm=norm)[ + ..., :n_mfcc, : + ] + + if lifter > 0: + # shape lifter for broadcasting + LI = np.sin(np.pi * np.arange(1, 1 + n_mfcc, dtype=M.dtype) / lifter) + LI = util.expand_to(LI, ndim=S.ndim, axes=-2) + + M *= 1 + (lifter / 2) * LI + return M + elif lifter == 0: + return M + else: + raise ParameterError(f"MFCC lifter={lifter} must be a non-negative number") + + +def melspectrogram( + *, + y: Optional[np.ndarray] = None, + sr: float = 22050, + S: Optional[np.ndarray] = None, + n_fft: int = 2048, + hop_length: int = 512, + win_length: Optional[int] = None, + window: _WindowSpec = "hann", + center: bool = True, + pad_mode: _PadModeSTFT = "constant", + power: float = 2.0, + **kwargs: Any, +) -> np.ndarray: + """Compute a mel-scaled spectrogram. + + If a spectrogram input ``S`` is provided, then it is mapped directly onto + the mel basis by ``mel_f.dot(S)``. + + If a time-series input ``y, sr`` is provided, then its magnitude spectrogram + ``S`` is first computed, and then mapped onto the mel scale by + ``mel_f.dot(S**power)``. + + By default, ``power=2`` operates on a power spectrum. + + Parameters + ---------- + y : np.ndarray [shape=(..., n)] or None + audio time-series. Multi-channel is supported. + sr : number > 0 [scalar] + sampling rate of ``y`` + S : np.ndarray [shape=(..., d, t)] + spectrogram + n_fft : int > 0 [scalar] + length of the FFT window + hop_length : int > 0 [scalar] + number of samples between successive frames. + See `librosa.stft` + win_length : int <= n_fft [scalar] + Each frame of audio is windowed by `window()`. + The window will be of length `win_length` and then padded + with zeros to match ``n_fft``. + If unspecified, defaults to ``win_length = n_fft``. + window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)] + - a window specification (string, tuple, or number); + see `scipy.signal.get_window` + - a window function, such as `scipy.signal.windows.hann` + - a vector or array of length ``n_fft`` + .. see also:: `librosa.filters.get_window` + center : boolean + - If `True`, the signal ``y`` is padded so that frame + ``t`` is centered at ``y[t * hop_length]``. + - If `False`, then frame ``t`` begins at ``y[t * hop_length]`` + pad_mode : string + If ``center=True``, the padding mode to use at the edges of the signal. + By default, STFT uses zero padding. + power : float > 0 [scalar] + Exponent for the magnitude melspectrogram. + e.g., 1 for energy, 2 for power, etc. + **kwargs : additional keyword arguments for Mel filter bank parameters + n_mels : int > 0 [scalar] + number of Mel bands to generate + fmin : float >= 0 [scalar] + lowest frequency (in Hz) + fmax : float >= 0 [scalar] + highest frequency (in Hz). + If `None`, use ``fmax = sr / 2.0`` + htk : bool [scalar] + use HTK formula instead of Slaney + norm : {None, 'slaney', or number} [scalar] + If 'slaney', divide the triangular mel weights by the width of + the mel band (area normalization). + If numeric, use `librosa.util.normalize` to normalize each filter + by to unit l_p norm. See `librosa.util.normalize` for a full + description of supported norm values (including `+-np.inf`). + Otherwise, leave all the triangles aiming for a peak value of 1.0 + dtype : np.dtype + The data type of the output basis. + By default, uses 32-bit (single-precision) floating point. + + Returns + ------- + S : np.ndarray [shape=(..., n_mels, t)] + Mel spectrogram + + See Also + -------- + librosa.filters.mel : Mel filter bank construction + librosa.stft : Short-time Fourier Transform + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> librosa.feature.melspectrogram(y=y, sr=sr) + array([[3.837e-06, 1.451e-06, ..., 8.352e-14, 1.296e-11], + [2.213e-05, 7.866e-06, ..., 8.532e-14, 1.329e-11], + ..., + [1.115e-05, 5.192e-06, ..., 3.675e-08, 2.470e-08], + [6.473e-07, 4.402e-07, ..., 1.794e-08, 2.908e-08]], + dtype=float32) + + Using a pre-computed power spectrogram would give the same result: + + >>> D = np.abs(librosa.stft(y))**2 + >>> S = librosa.feature.melspectrogram(S=D, sr=sr) + + Display of mel-frequency spectrogram coefficients, with custom + arguments for mel filterbank construction (default is fmax=sr/2): + + >>> # Passing through arguments to the Mel filters + >>> S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, + ... fmax=8000) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> S_dB = librosa.power_to_db(S, ref=np.max) + >>> img = librosa.display.specshow(S_dB, x_axis='time', + ... y_axis='mel', sr=sr, + ... fmax=8000, ax=ax) + >>> fig.colorbar(img, ax=ax, format='%+2.0f dB') + >>> ax.set(title='Mel-frequency spectrogram') + """ + S, n_fft = _spectrogram( + y=y, + S=S, + n_fft=n_fft, + hop_length=hop_length, + power=power, + win_length=win_length, + window=window, + center=center, + pad_mode=pad_mode, + ) + + # Build a Mel filter + mel_basis = filters.mel(sr=sr, n_fft=n_fft, **kwargs) + + melspec: np.ndarray = np.einsum("...ft,mf->...mt", S, mel_basis, optimize=True) + return melspec diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b69d9fc81b053e0404478d8bc73a8be2a997e29f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/feature/utils.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Feature manipulation utilities""" + +import numpy as np +import scipy.signal +from numba import jit + +from .._cache import cache +from ..util.exceptions import ParameterError +from typing import Any + +__all__ = ["delta", "stack_memory"] + + +@cache(level=40) +def delta( + data: np.ndarray, + *, + width: int = 9, + order: int = 1, + axis: int = -1, + mode: str = "interp", + **kwargs: Any, +) -> np.ndarray: + r"""Compute delta features: local estimate of the derivative + of the input data along the selected axis. + + Delta features are computed Savitsky-Golay filtering. + + Parameters + ---------- + data : np.ndarray + the input data matrix (eg, spectrogram) + + width : int, positive, odd [scalar] + Number of frames over which to compute the delta features. + Cannot exceed the length of ``data`` along the specified axis. + + If ``mode='interp'``, then ``width`` must be at least ``data.shape[axis]``. + + order : int > 0 [scalar] + the order of the difference operator. + 1 for first derivative, 2 for second, etc. + + axis : int [scalar] + the axis along which to compute deltas. + Default is -1 (columns). + + mode : str, {'interp', 'nearest', 'mirror', 'constant', 'wrap'} + Padding mode for estimating differences at the boundaries. + + **kwargs : additional keyword arguments + See `scipy.signal.savgol_filter` + + Returns + ------- + delta_data : np.ndarray [shape=(..., t)] + delta matrix of ``data`` at specified order + + Notes + ----- + This function caches at level 40. + + See Also + -------- + scipy.signal.savgol_filter + + Examples + -------- + Compute MFCC deltas, delta-deltas + + >>> y, sr = librosa.load(librosa.ex('libri1'), duration=5) + >>> mfcc = librosa.feature.mfcc(y=y, sr=sr) + >>> mfcc_delta = librosa.feature.delta(mfcc) + >>> mfcc_delta + array([[-5.713e+02, -5.697e+02, ..., -1.522e+02, -1.224e+02], + [ 1.104e+01, 1.330e+01, ..., 2.089e+02, 1.698e+02], + ..., + [ 2.829e+00, 1.933e+00, ..., -3.149e+00, 2.294e-01], + [ 2.890e+00, 2.187e+00, ..., 6.959e+00, -1.039e+00]], + dtype=float32) + + >>> mfcc_delta2 = librosa.feature.delta(mfcc, order=2) + >>> mfcc_delta2 + array([[-1.195, -1.195, ..., -4.328, -4.328], + [-1.566, -1.566, ..., -9.949, -9.949], + ..., + [ 0.707, 0.707, ..., 2.287, 2.287], + [ 0.655, 0.655, ..., -1.719, -1.719]], dtype=float32) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> img1 = librosa.display.specshow(mfcc, ax=ax[0], x_axis='time') + >>> ax[0].set(title='MFCC') + >>> ax[0].label_outer() + >>> img2 = librosa.display.specshow(mfcc_delta, ax=ax[1], x_axis='time') + >>> ax[1].set(title=r'MFCC-$\Delta$') + >>> ax[1].label_outer() + >>> img3 = librosa.display.specshow(mfcc_delta2, ax=ax[2], x_axis='time') + >>> ax[2].set(title=r'MFCC-$\Delta^2$') + >>> fig.colorbar(img1, ax=[ax[0]]) + >>> fig.colorbar(img2, ax=[ax[1]]) + >>> fig.colorbar(img3, ax=[ax[2]]) + """ + data = np.atleast_1d(data) + + if mode == "interp" and width > data.shape[axis]: + raise ParameterError( + f"when mode='interp', width={width} " + f"cannot exceed data.shape[axis]={data.shape[axis]}" + ) + + if width < 3 or np.mod(width, 2) != 1: + raise ParameterError("width must be an odd integer >= 3") + + if order <= 0 or not isinstance(order, (int, np.integer)): + raise ParameterError("order must be a positive integer") + + kwargs.pop("deriv", None) + kwargs.setdefault("polyorder", order) + result: np.ndarray = scipy.signal.savgol_filter( + data, width, deriv=order, axis=axis, mode=mode, **kwargs + ) + return result + + +@cache(level=40) +def stack_memory( + data: np.ndarray, *, n_steps: int = 2, delay: int = 1, **kwargs: Any +) -> np.ndarray: + """Short-term history embedding: vertically concatenate a data + vector or matrix with delayed copies of itself. + + Each column ``data[:, i]`` is mapped to:: + + data[..., i] -> [data[..., i], + data[..., i - delay], + ... + data[..., i - (n_steps-1)*delay]] + + For columns ``i < (n_steps - 1) * delay``, the data will be padded. + By default, the data is padded with zeros, but this behavior can be + overridden by supplying additional keyword arguments which are passed + to `np.pad()`. + + Parameters + ---------- + data : np.ndarray [shape=(..., d, t)] + Input data matrix. If ``data`` is a vector (``data.ndim == 1``), + it will be interpreted as a row matrix and reshaped to ``(1, t)``. + + n_steps : int > 0 [scalar] + embedding dimension, the number of steps back in time to stack + + delay : int != 0 [scalar] + the number of columns to step. + + Positive values embed from the past (previous columns). + + Negative values embed from the future (subsequent columns). + + **kwargs : additional keyword arguments + Additional arguments to pass to `numpy.pad` + + Returns + ------- + data_history : np.ndarray [shape=(..., m * d, t)] + data augmented with lagged copies of itself, + where ``m == n_steps - 1``. + + Notes + ----- + This function caches at level 40. + + Examples + -------- + Keep two steps (current and previous) + + >>> data = np.arange(-3, 3) + >>> librosa.feature.stack_memory(data) + array([[-3, -2, -1, 0, 1, 2], + [ 0, -3, -2, -1, 0, 1]]) + + Or three steps + + >>> librosa.feature.stack_memory(data, n_steps=3) + array([[-3, -2, -1, 0, 1, 2], + [ 0, -3, -2, -1, 0, 1], + [ 0, 0, -3, -2, -1, 0]]) + + Use reflection padding instead of zero-padding + + >>> librosa.feature.stack_memory(data, n_steps=3, mode='reflect') + array([[-3, -2, -1, 0, 1, 2], + [-2, -3, -2, -1, 0, 1], + [-1, -2, -3, -2, -1, 0]]) + + Or pad with edge-values, and delay by 2 + + >>> librosa.feature.stack_memory(data, n_steps=3, delay=2, mode='edge') + array([[-3, -2, -1, 0, 1, 2], + [-3, -3, -3, -2, -1, 0], + [-3, -3, -3, -3, -3, -2]]) + + Stack time-lagged beat-synchronous chroma edge padding + + >>> y, sr = librosa.load(librosa.ex('sweetwaltz'), duration=10) + >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr) + >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=512) + >>> beats = librosa.util.fix_frames(beats, x_min=0) + >>> chroma_sync = librosa.util.sync(chroma, beats) + >>> chroma_lag = librosa.feature.stack_memory(chroma_sync, n_steps=3, + ... mode='edge') + + Plot the result + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=512) + >>> librosa.display.specshow(chroma_lag, y_axis='chroma', x_axis='time', + ... x_coords=beat_times, ax=ax) + >>> ax.text(1.0, 1/6, "Lag=0", transform=ax.transAxes, rotation=-90, ha="left", va="center") + >>> ax.text(1.0, 3/6, "Lag=1", transform=ax.transAxes, rotation=-90, ha="left", va="center") + >>> ax.text(1.0, 5/6, "Lag=2", transform=ax.transAxes, rotation=-90, ha="left", va="center") + >>> ax.set(title='Time-lagged chroma', ylabel="") + """ + if n_steps < 1: + raise ParameterError("n_steps must be a positive integer") + + if delay == 0: + raise ParameterError("delay must be a non-zero integer") + + data = np.atleast_2d(data) + t = data.shape[-1] + + if t < 1: + raise ParameterError( + "Cannot stack memory when input data has " + f"no columns. Given data.shape={data.shape}" + ) + kwargs.setdefault("mode", "constant") + + if kwargs["mode"] == "constant": + kwargs.setdefault("constant_values", [0]) + + padding = [(0, 0) for _ in range(data.ndim)] + + # Pad the end with zeros, which will roll to the front below + if delay > 0: + padding[-1] = (int((n_steps - 1) * delay), 0) + else: + padding[-1] = (0, int((n_steps - 1) * -delay)) + + data = np.pad(data, padding, **kwargs) + + # Construct the shape of the target array + shape = list(data.shape) + shape[-2] = shape[-2] * n_steps + shape[-1] = t + shape = tuple(shape) + + # Construct the output array to match layout and dtype of input + history = np.empty_like(data, shape=shape) + + # Populate the output array + __stack(history, data, n_steps, delay) + + return history + + +@jit(nopython=True, cache=True) +def __stack(history, data, n_steps, delay): + """Memory-stacking helper function. + + Parameters + ---------- + history : output array (2-dimensional) + data : pre-padded input array (2-dimensional) + n_steps : int > 0, the number of steps to stack + delay : int != 0, the amount of delay between steps + + Returns + ------- + None + Output is stored directly in the history array + """ + # Dimension of each copy of the data + d = data.shape[-2] + + # Total number of time-steps to output + t = history.shape[-1] + + if delay > 0: + for step in range(n_steps): + q = n_steps - 1 - step + # nth block is original shifted left by n*delay steps + history[..., step * d : (step + 1) * d, :] = data[ + ..., q * delay : q * delay + t + ] + else: + # Handle the last block separately to avoid -t:0 empty slices + history[..., -d:, :] = data[..., -t:] + + for step in range(n_steps - 1): + # nth block is original shifted right by n*delay steps + q = n_steps - 1 - step + history[..., step * d : (step + 1) * d, :] = data[ + ..., -t + q * delay : q * delay + ] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..87c1c5aa6e962626efc9d43d5a1e4c550194f1d9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Skip pydocstyle checks that erroneously trigger on "example" +# noqa: D405,D214,D407 +""" +Utilities +========= + +Array operations +---------------- +.. autosummary:: + :toctree: generated/ + + frame + pad_center + expand_to + fix_length + fix_frames + index_to_slice + softmask + stack + sync + + axis_sort + normalize + shear + sparsify_rows + + buf_to_float + tiny + +Matching +-------- +.. autosummary:: + :toctree: generated/ + + match_intervals + match_events + +Miscellaneous +------------- +.. autosummary:: + :toctree: generated/ + + localmax + localmin + peak_pick + nnls + cyclic_gradient + dtype_c2r + dtype_r2c + count_unique + is_unique + abs2 + phasor + + +Input validation +---------------- +.. autosummary:: + :toctree: generated/ + + valid_audio + valid_int + valid_intervals + is_positive_int + + +File operations +--------------- +.. autosummary:: + :toctree: generated/ + + example + example_info + list_examples + find_files + cite +""" + +import lazy_loader as lazy + +__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..64ceec2f5e7fe2271f104972a6874a2301e64e8b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__init__.pyi @@ -0,0 +1,59 @@ +from . import decorators +from . import exceptions + +from .files import ( + find_files as find_files, + example as example, + ex as ex, + list_examples as list_examples, + example_info as example_info, + cite as cite, +) + +from .matching import ( + match_intervals as match_intervals, + match_events as match_events, +) + +from .deprecation import ( + Deprecated as Deprecated, + rename_kw as rename_kw, +) + +from ._nnls import ( + nnls as nnls, +) + +from .utils import ( + MAX_MEM_BLOCK as MAX_MEM_BLOCK, + frame as frame, + pad_center as pad_center, + expand_to as expand_to, + fix_length as fix_length, + valid_audio as valid_audio, + valid_int as valid_int, + is_positive_int as is_positive_int, + valid_intervals as valid_intervals, + fix_frames as fix_frames, + axis_sort as axis_sort, + localmax as localmax, + localmin as localmin, + normalize as normalize, + peak_pick as peak_pick, + sparsify_rows as sparsify_rows, + shear as shear, + stack as stack, + fill_off_diagonal as fill_off_diagonal, + index_to_slice as index_to_slice, + sync as sync, + softmask as softmask, + buf_to_float as buf_to_float, + tiny as tiny, + cyclic_gradient as cyclic_gradient, + dtype_r2c as dtype_r2c, + dtype_c2r as dtype_c2r, + count_unique as count_unique, + is_unique as is_unique, + abs2 as abs2, + phasor as phasor, +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8bfbb363c50b486f6526e514d9a4801d2118f18 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/_nnls.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/_nnls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..104a0c26f95cfe7ec5967e65afba2f75907732c9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/_nnls.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/decorators.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cdd594b1c0df0eff1f1766566f616b9fbe9336c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/decorators.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/deprecation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/deprecation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f7c65cf505f27a7b866f5e96680b0719147dcf1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/deprecation.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e36cce87234084d8ad3036662fb5ed8e7e2e25a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/files.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/files.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd3dc422a528046cc8dd7c669a80c2a0405d5a60 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/files.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/matching.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/matching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2be56f73e3e5f9dbb74a7e32d8939a2ce552e9a4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/matching.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..108a06c5dd44eebb6ddaee8fa9628dc1f642334d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/__pycache__/utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/_nnls.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/_nnls.py new file mode 100644 index 0000000000000000000000000000000000000000..e22b2f070597b2581b14561f09fa8b57609841c4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/_nnls.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Non-negative least squares""" + +# The scipy library provides an nnls solver, but it does +# not generalize efficiently to matrix-valued problems. +# We therefore provide an alternate solver here. +# +# The vectorized solver uses the L-BFGS-B over blocks of +# data to efficiently solve the constrained least-squares problem. + +import numpy as np +import scipy.optimize +from .utils import MAX_MEM_BLOCK +from typing import Any, Optional, Tuple, Sequence + + +__all__ = ["nnls"] + + +def _nnls_obj( + x: np.ndarray, shape: Sequence[int], A: np.ndarray, B: np.ndarray +) -> Tuple[float, np.ndarray]: + """Compute the objective and gradient for NNLS""" + # Scipy's lbfgs flattens all arrays, so we first reshape + # the iterate x + x = x.reshape(shape) + + # Compute the difference matrix + diff = np.einsum("mf,...ft->...mt", A, x, optimize=True) - B + + # Compute the objective value + value = (1 / B.size) * 0.5 * np.sum(diff**2) + + # And the gradient + grad = (1 / B.size) * np.einsum("mf,...mt->...ft", A, diff, optimize=True) + + # Flatten the gradient + return value, grad.flatten() + + +def _nnls_lbfgs_block( + A: np.ndarray, B: np.ndarray, x_init: Optional[np.ndarray] = None, **kwargs: Any +) -> np.ndarray: + """Solve the constrained problem over a single block + + Parameters + ---------- + A : np.ndarray [shape=(m, d)] + The basis matrix + B : np.ndarray [shape=(m, N)] + The regression targets + x_init : np.ndarray [shape=(d, N)] + An initial guess + **kwargs + Additional keyword arguments to `scipy.optimize.fmin_l_bfgs_b` + + Returns + ------- + x : np.ndarray [shape=(d, N)] + Non-negative matrix such that Ax ~= B + """ + # If we don't have an initial point, start at the projected + # least squares solution + if x_init is None: + # Suppress type checks because mypy can't find pinv + x_init = np.einsum("fm,...mt->...ft", np.linalg.pinv(A), B, optimize=True) + np.clip(x_init, 0, None, out=x_init) + + # Adapt the hessian approximation to the dimension of the problem + kwargs.setdefault("m", A.shape[1]) + + # Construct non-negative bounds + bounds = [(0, None)] * x_init.size + shape = x_init.shape + + # optimize + x: np.ndarray + x, obj_value, diagnostics = scipy.optimize.fmin_l_bfgs_b( + _nnls_obj, x_init, args=(shape, A, B), bounds=bounds, **kwargs + ) + # reshape the solution + return x.reshape(shape) + + +def nnls(A: np.ndarray, B: np.ndarray, **kwargs: Any) -> np.ndarray: + """Non-negative least squares. + + Given two matrices A and B, find a non-negative matrix X + that minimizes the sum squared error:: + + err(X) = sum_i,j ((AX)[i,j] - B[i, j])^2 + + Parameters + ---------- + A : np.ndarray [shape=(m, n)] + The basis matrix + B : np.ndarray [shape=(..., m, N)] + The target array. Additional leading dimensions are supported. + **kwargs + Additional keyword arguments to `scipy.optimize.fmin_l_bfgs_b` + + Returns + ------- + X : np.ndarray [shape=(..., n, N), non-negative] + A minimizing solution to ``|AX - B|^2`` + + See Also + -------- + scipy.optimize.nnls + scipy.optimize.fmin_l_bfgs_b + + Examples + -------- + Approximate a magnitude spectrum from its mel spectrogram + + >>> y, sr = librosa.load(librosa.ex('trumpet'), duration=3) + >>> S = np.abs(librosa.stft(y, n_fft=2048)) + >>> M = librosa.feature.melspectrogram(S=S, sr=sr, power=1) + >>> mel_basis = librosa.filters.mel(sr=sr, n_fft=2048, n_mels=M.shape[0]) + >>> S_recover = librosa.util.nnls(mel_basis, M) + + Plot the results + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[2]) + >>> ax[2].set(title='Original spectrogram (1025 bins)') + >>> ax[2].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(M, ref=np.max), + ... y_axis='mel', x_axis='time', ax=ax[0]) + >>> ax[0].set(title='Mel spectrogram (128 bins)') + >>> ax[0].label_outer() + >>> img = librosa.display.specshow(librosa.amplitude_to_db(S_recover, ref=np.max(S)), + ... y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Reconstructed spectrogram (1025 bins)') + >>> ax[1].label_outer() + >>> fig.colorbar(img, ax=ax, format="%+2.0f dB") + """ + # If B is a single vector, punt up to the scipy method + if B.ndim == 1: + return scipy.optimize.nnls(A, B)[0] # type: ignore + + n_columns = int(MAX_MEM_BLOCK // (np.prod(B.shape[:-1]) * A.itemsize)) + n_columns = max(n_columns, 1) + + # Process in blocks: + if B.shape[-1] <= n_columns: + return _nnls_lbfgs_block(A, B, **kwargs).astype(A.dtype) + + x: np.ndarray + x = np.einsum("fm,...mt->...ft", np.linalg.pinv(A), B, optimize=True) + np.clip(x, 0, None, out=x) + x_init = x + + for bl_s in range(0, x.shape[-1], n_columns): + bl_t = min(bl_s + n_columns, B.shape[-1]) + x[..., bl_s:bl_t] = _nnls_lbfgs_block( + A, B[..., bl_s:bl_t], x_init=x_init[..., bl_s:bl_t], **kwargs + ) + return x diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/decorators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..fd52627f738d26e701ddb63ef4f2024be80e81a6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/decorators.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +# CREATED:2015-02-15 10:06:03 by Brian McFee +"""Helpful tools for deprecation""" + +from typing import Any, Callable, Iterable, Optional, TypeVar, Union +import warnings +import functools +from decorator import decorator +import numpy as np +from numpy.typing import DTypeLike +from typing_extensions import ParamSpec # Install typing_extensions in Python 3.8 + +__all__ = ["moved", "deprecated", "vectorize"] + +P = ParamSpec("P") +R = TypeVar("R") + + +def moved( + *, moved_from: str, version: str, version_removed: str +) -> Callable[[Callable[P, R]], Callable[P, R]]: + """Mark functions as moved/renamed. + + Using the decorated (old) function will result in a warning. + """ + + def __wrapper(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: + """Warn the user, and then proceed.""" + warnings.warn( + "{:s}\n\tThis function was moved to '{:s}.{:s}' in " + "librosa version {:s}." + "\n\tThis alias will be removed in librosa version " + "{:s}.".format( + moved_from, func.__module__, func.__name__, version, version_removed + ), + category=FutureWarning, + stacklevel=3, # Would be 2, but the decorator adds a level + ) + return func(*args, **kwargs) + + return decorator(__wrapper) + + +def deprecated( + *, version: str, version_removed: str +) -> Callable[[Callable[P, R]], Callable[P, R]]: + """Mark a function as deprecated. + + Using the decorated (old) function will result in a warning. + """ + + def __wrapper(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: + """Warn the user, and then proceed.""" + warnings.warn( + "{:s}.{:s}\n\tDeprecated as of librosa version {:s}." + "\n\tIt will be removed in librosa version {:s}.".format( + func.__module__, func.__name__, version, version_removed + ), + category=FutureWarning, + stacklevel=3, # Would be 2, but the decorator adds a level + ) + return func(*args, **kwargs) + + return decorator(__wrapper) + + +_F = TypeVar("_F", bound=Callable[..., Any]) + + +def vectorize( + *, + otypes: Optional[Union[str, Iterable[DTypeLike]]] = None, + doc: Optional[str] = None, + excluded: Optional[Iterable[Union[int, str]]] = None, + cache: bool = False, + signature: Optional[str] = None +) -> Callable[[_F], _F]: + """Wrap a function for use with np.vectorize. + + This function is not quite a decorator, but is used as a wrapper + to np.vectorize that preserves scalar behavior. + """ + + def __wrapper(function): + vecfunc = np.vectorize( + function, + otypes=otypes, + doc=doc, + excluded=excluded, + cache=cache, + signature=signature, + ) + + @functools.wraps(function) + def _vec(*args, **kwargs): + y = vecfunc(*args, **kwargs) + if np.isscalar(args[0]): + return y.item() + else: + return y + + return _vec + + return __wrapper diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/deprecation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..59536547503d3d8def79dcfe9cd95f827fa88c92 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/deprecation.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +"""Deprecation utilities""" + +import inspect +import warnings +from typing import Any + + +class Deprecated(object): + """A placeholder class to catch usage of deprecated variable names""" + + def __repr__(self) -> str: + """Pretty-print display for deprecated objects""" + return "" + + +def rename_kw( + *, + old_name: str, + old_value: Any, + new_name: str, + new_value: Any, + version_deprecated: str, + version_removed: str +) -> Any: + """Handle renamed arguments. + + Parameters + ---------- + old_name : str + old_value + The name and value of the old argument + new_name : str + new_value + The name and value of the new argument + version_deprecated : str + The version at which the old name became deprecated + version_removed : str + The version at which the old name will be removed + + Returns + ------- + value + - ``new_value`` if ``old_value`` of type `Deprecated` + - ``old_value`` otherwise + + Warnings + -------- + if ``old_value`` is not of type `Deprecated` + + """ + if isinstance(old_value, Deprecated): + return new_value + else: + stack = inspect.stack() + dep_func = stack[1] + + warnings.warn( + "{:s}() keyword argument '{:s}' has been " + "renamed to '{:s}' in version {:}." + "\n\tThis alias will be removed in version " + "{:}.".format( + dep_func[3], old_name, new_name, version_deprecated, version_removed + ), + category=FutureWarning, + stacklevel=3, + ) + + return old_value diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c66ba7ebe3f89367374804d1609e170f009a3d9d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__init__.py @@ -0,0 +1 @@ +"""Resources for loading example data""" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea10b66bec461856106d97b9fa3ace608220c8e8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/index.json b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/index.json new file mode 100644 index 0000000000000000000000000000000000000000..93dc769f2aeccf103912840b32eee876ee4bf173 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/index.json @@ -0,0 +1 @@ +{"vibeace": {"path": "Kevin_MacLeod_-_Vibe_Ace", "desc": "Kevin MacLeod - Vibe Ace"}, "choice": {"path": "admiralbob77_-_Choice_-_Drum-bass", "desc": "Admiral Bob - Choice (drum+bass)"}, "nutcracker": {"path": "Kevin_MacLeod_-_P_I_Tchaikovsky_Dance_of_the_Sugar_Plum_Fairy", "desc": "Tchaikovsky - Dance of the Sugar Plum Fairy"}, "brahms": {"path": "Hungarian_Dance_number_5_-_Allegro_in_F_sharp_minor_(string_orchestra)", "desc": "Brahms - Hungarian Dance #5"}, "trumpet": {"path": "sorohanro_-_solo-trumpet-06", "desc": "Mihai Sorohan - Trumpet loop"}, "fishin": {"path": "Karissa_Hobbs_-_Lets_Go_Fishin", "desc": "Karissa Hobbs - Let's Go Fishin'"}, "sweetwaltz": {"path": "147793__setuniman__sweet-waltz-0i-22mi", "desc": "Setuniman - Sweet Waltz"}, "humpback": {"path": "glacier-bay-humpback", "desc": "Glacier Bay 60-second clip humpback whale song November 2020"}, "libri1": {"path": "5703-47212-0000", "desc": "Ashiel Mystery - A Detective Story, chapter 2, narrated by Garth Comira"}, "libri2": {"path": "3436-172162-0000", "desc": "The Age of Chivalry / Chapter 18: Perceval / Read by Anders Lankford"}, "pistachio": {"path": "442789__lena-orsa__happy-music-pistachio-ice-cream-ragtime", "desc": "The Piano Lady - Pistachio Ice Cream Ragtime"}, "robin": {"path": "456440__inspectorj__bird-whistling-robin-single-13", "desc": "Bird Whistling, Robin, Single, 13.wav / InspectorJ"}, "libri3": {"path": "198-209-0000", "desc": "Sense and Sensibility / Chapter 18 / Jane Austen / Read by Heather Barnett"}, "pibble": {"path": "pibble", "desc": "Who's a good girl?"}} diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/registry.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/registry.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d14fe65e8d590eb9db04b11ca396bffe0c03da8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/example_data/registry.txt @@ -0,0 +1,43 @@ +147793__setuniman__sweet-waltz-0i-22mi.hq.ogg 248f93b7c729bc0bd6c4cbc107e6b67ec4d60e40c111e313d4d69f77748da26a +147793__setuniman__sweet-waltz-0i-22mi.ogg 4baff8ebf1771c33618b58aa12ac3fbac1e0462894ae74247f2fb8e649d1c63b +147793__setuniman__sweet-waltz-0i-22mi.txt 6e6e9265ae9a9a36033ce305a893abdc15f43bb5a41ec29efba368ad91905f43 +198-209-0000.hq.ogg 6a8d2c16e56dcb27b7f5fe5aa99bfd26b4722a6dabca1968eff951b456936514 +198-209-0000.ogg 0473ba9613befa1026db5e254546f105aeffba8366b5468fc5e8d474d844ca1d +198-209-0000.txt c5bf58b2a4aa0d6bf1e6051690312f3238960d455776a6d37e469d80db1da167 +3436-172162-0000.hq.ogg 8e034529f2f171c7e5e772df6eccc2d169183c39605b45b351c2bfabddf14162 +3436-172162-0000.ogg 780e482b52f2c8a500356babf60178ce005449cc171a8537eb3ef2961eb3e855 +3436-172162-0000.txt 8cf4b20e148c4366205bc607f447c169256e945d62c64ead43d0a4dfa7d3ab98 +442789__lena-orsa__happy-music-pistachio-ice-cream-ragtime.hq.ogg 1cc83b775e640a8dd409da9e29f5b5e0124bc5ec9bb4fda975919d31d1d893b8 +442789__lena-orsa__happy-music-pistachio-ice-cream-ragtime.ogg 9617c9be55c128177b13c20fbc52178ed482e3545094517efb30a7db2798991e +442789__lena-orsa__happy-music-pistachio-ice-cream-ragtime.txt 99f9c44368918572ac154ae4a2fec4020d1d4bb418ae7bf241864916d68f9d04 +456440__inspectorj__bird-whistling-robin-single-13.hq.ogg a3b3ecf749befde43bdf35f839fdcb8d399a4deb5666de6f399c35ce12936baa +456440__inspectorj__bird-whistling-robin-single-13.ogg 57c2b861d028e25d7c086b48853f20eda1ae9a7a33e1125a1f3bec91539b4208 +456440__inspectorj__bird-whistling-robin-single-13.txt 34d25a379408d9144fbc4ce8cceb72be5196aeb6140cec6c90e6bdcb0567cb6e +5703-47212-0000.hq.ogg f09254a0daf4b14b292868d46dc2e3c8e158d19fafff739ad4c3931e2ce7b1b0 +5703-47212-0000.ogg a284612b46af0535f7e1873758c4387bb8369f6dbbe192ffdec1f171108f98dd +5703-47212-0000.txt 1c5bd5eb792ff0d2fbe895e3a3dd0acf3beb48ee364e64e12cde3a646304a9f4 +Hungarian_Dance_number_5_-_Allegro_in_F_sharp_minor_(string_orchestra).hq.ogg 8e93ff0182a93168b15346c497b164cb49d2a97bf1e987a1149ea579e914532e +Hungarian_Dance_number_5_-_Allegro_in_F_sharp_minor_(string_orchestra).ogg 919b48aa4cc66a0357d2cd5728664c5ab8f15c4b3469460df4b59470d35d3e49 +Hungarian_Dance_number_5_-_Allegro_in_F_sharp_minor_(string_orchestra).txt 0c857ef8a7365e3df9d5c25c2b08ec3169c0585e3ec08c9c6423d2a04d72fe5f +Karissa_Hobbs_-_Lets_Go_Fishin.hq.ogg 85901bde0bc5f2cad28acb83487ccf99bd6908d7359f1a449fd799d8bebb3319 +Karissa_Hobbs_-_Lets_Go_Fishin.ogg 27b3667c396c1831511aa3c415fcf582b6e8be560cafb844c5b67b76b72c1cb3 +Karissa_Hobbs_-_Lets_Go_Fishin.txt 199bf3408b98916cd9d28a22b2b43c1935ab70072b46fa05c0b9f40e7882802e +Kevin_MacLeod_-_P_I_Tchaikovsky_Dance_of_the_Sugar_Plum_Fairy.hq.ogg f062221a56a227cdb7c067cf2e6ac0e250a50012f7693ca0c8e31f05f83e49b1 +Kevin_MacLeod_-_P_I_Tchaikovsky_Dance_of_the_Sugar_Plum_Fairy.ogg b5c1a3e26310e6618d3c124f458654cd235650fcb9db7d711302644566600484 +Kevin_MacLeod_-_P_I_Tchaikovsky_Dance_of_the_Sugar_Plum_Fairy.txt 059acb340170385d2bfa4c7ab7c2a06b1d8f8af3e0f11cb4f46ff4049e950915 +Kevin_MacLeod_-_Vibe_Ace.hq.ogg 73d6443ef90a7c022f164e5aa90e56c2291585930b39b1656d0765abbc1f1779 +Kevin_MacLeod_-_Vibe_Ace.ogg 6c23aed3dd5aa57f2b1652ecab68d15d9b82ad257f54e639eb2880ca09bc118a +Kevin_MacLeod_-_Vibe_Ace.txt 6c71e0525cb0452ea74c6d6f5fde6fa1e221223db7b2aa35b9914b98367ee7b9 +admiralbob77_-_Choice_-_Drum-bass.hq.ogg 57b4d95473b92a8441c1d3ab20f836a3e0cbf501bf3afe1ce7a5d0d98d7d4576 +admiralbob77_-_Choice_-_Drum-bass.ogg ac644f9645e7c15174e4a4f8561e4d1448d7f6e59ff6b0556b310ebbced879bc +admiralbob77_-_Choice_-_Drum-bass.txt 76525d6a4fd135053c5ff7463ae43a8ffcf064b575e8ef2fc3eb37786a45342b +glacier-bay-humpback.hq.ogg c3250ff526898aa5528aeb6b81a49aff58f63400ec2ddb8bcb86caf611d33144 +glacier-bay-humpback.ogg 64395c617b28b5e31a03032b99b4617bc96b926f3bc5c141862cd13fb79ccd8e +glacier-bay-humpback.txt bec2c73fe2368604f161ffdd44b7afea5f597473e2d51c03906bb05c22113910 +pibble.hq.ogg dfd796becf38b6f5ff606f2c822ce24e81d8df936b1ced9bffd29e0d1f05b800 +pibble.ogg c596c027f604defa522a1734f599c6db5624fa62dd3f1be2a933d85b077f7400 +pibble.txt 341fdf46cae7c165875667ed729f6d18983e8cfe32e491816705e7be00d57c76 +sorohanro_-_solo-trumpet-06.hq.ogg beb954ae2c9c16919b5ca6973d6d5196cdcb196b46a3c2a201dd8861e7e324de +sorohanro_-_solo-trumpet-06.ogg 8374466fd3951d24509da6e799b132a0db0bdeda69d99c69d989a6888d3d727d +sorohanro_-_solo-trumpet-06.txt 750a191b9d0cc94b2f19cfbf11acc13783f75bedcccfcf562f5b076efd068aba +version_index.msgpack 9e06db4cf390d7b308a8e253f138237501b1d1a4cf46e7185f3d7081a71aef1a diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/exceptions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..95f6888c00473834d4e5d1bec7c6cfae4d0cf53b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/exceptions.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +"""Exception classes for librosa""" + + +class LibrosaError(Exception): + """The root librosa exception class""" + + pass + + +class ParameterError(LibrosaError): + """Exception class for mal-formed inputs""" + + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/files.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/files.py new file mode 100644 index 0000000000000000000000000000000000000000..60fe65224615d3e35e7efcf71f9e286baa2616af --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/files.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Utility functions for dealing with files""" +from __future__ import annotations +from typing import List, Optional, Union, Any, Set + +import os +import glob +import json +import msgpack +import contextlib +import sys + +from importlib import resources + +import pooch + +from .exceptions import ParameterError +from ..version import version as librosa_version + + +__all__ = [ + "find_files", + "example", + "ex", + "list_examples", + "example_info", +] + + +# Instantiate the pooch +__data_path = os.environ.get("LIBROSA_DATA_DIR", pooch.os_cache("librosa")) +__GOODBOY = pooch.create( + __data_path, base_url="https://librosa.org/data/audio/", registry=None +) + + +@contextlib.contextmanager +def _resource_file(package: str, resource: str): + """Provide a context manager for accessing resources in a package. + + It acts as a shim to provide a consistent interface for accessing resources + since the 3.9 series deprecated the "path" method in favor of the "files" method. + """ + if sys.version_info < (3, 9): + with resources.path(package, resource) as path: + yield path + + else: + with resources.as_file(resources.files(package).joinpath(resource)) as path: + yield path + + +with _resource_file("librosa.util.example_data", "registry.txt") as reg: + __GOODBOY.load_registry(str(reg)) + # We want to bypass version checks here to allow asynchronous updates for new releases + __GOODBOY.registry['version_index.msgpack'] = None + +with _resource_file("librosa.util.example_data", "index.json") as index: + with index.open("r") as _fdesc: + __TRACKMAP = json.load(_fdesc) + + +def example(key: str, *, hq: bool = False) -> str: + """Retrieve the example recording identified by 'key'. + + The first time an example is requested, it will be downloaded from + the remote repository over HTTPS. + All subsequent requests will use a locally cached copy of the recording. + + For a list of examples (and their keys), see `librosa.util.list_examples`. + + By default, local files will be cached in the directory given by + `pooch.os_cache('librosa')`. You can override this by setting + an environment variable ``LIBROSA_DATA_DIR`` prior to importing librosa: + + >>> import os + >>> os.environ['LIBROSA_DATA_DIR'] = '/path/to/store/data' + >>> import librosa + + Parameters + ---------- + key : str + The identifier for the track to load + hq : bool + If ``True``, return the high-quality version of the recording. + If ``False``, return the 22KHz mono version of the recording. + + Returns + ------- + path : str + The path to the requested example file + + Examples + -------- + Load "Hungarian Dance #5" by Johannes Brahms + + >>> y, sr = librosa.load(librosa.example('brahms')) + + Load "Vibe Ace" by Kevin MacLeod (the example previously packaged with librosa) + in high-quality mode + + >>> y, sr = librosa.load(librosa.example('vibeace', hq=True)) + + See Also + -------- + librosa.util.list_examples + pooch.os_cache + """ + if key not in __TRACKMAP: + raise ParameterError(f"Unknown example key: {key}") + + if hq: + ext = ".hq.ogg" + else: + ext = ".ogg" + + return str(__GOODBOY.fetch(__TRACKMAP[key]["path"] + ext)) + + +ex = example +"""Alias for example""" + + +def list_examples() -> None: + """List the available audio recordings included with librosa. + + Each recording is given a unique identifier (e.g., "brahms" or "nutcracker"), + listed in the first column of the output. + + A brief description is provided in the second column. + + See Also + -------- + util.example + util.example_info + """ + print("AVAILABLE EXAMPLES") + print("-" * 68) + for key in sorted(__TRACKMAP.keys()): + if key == "pibble": + # Shh... she's sleeping + continue + print(f"{key:10}\t{__TRACKMAP[key]['desc']}") + + +def example_info(key: str) -> None: + """Display licensing and metadata information for the given example recording. + + The first time an example is requested, it will be downloaded from + the remote repository over HTTPS. + All subsequent requests will use a locally cached copy of the recording. + + For a list of examples (and their keys), see `librosa.util.list_examples`. + + By default, local files will be cached in the directory given by + `pooch.os_cache('librosa')`. You can override this by setting + an environment variable ``LIBROSA_DATA_DIR`` prior to importing librosa. + + Parameters + ---------- + key : str + The identifier for the recording (see `list_examples`) + + See Also + -------- + librosa.util.example + librosa.util.list_examples + pooch.os_cache + """ + if key not in __TRACKMAP: + raise ParameterError(f"Unknown example key: {key}") + + license_file = __GOODBOY.fetch(__TRACKMAP[key]["path"] + ".txt") + + with open(license_file, "r") as fdesc: + print(f"{key:10s}\t{__TRACKMAP[key]['desc']:s}") + print("-" * 68) + for line in fdesc: + print(line) + + +def find_files( + directory: Union[str, os.PathLike[Any]], + *, + ext: Optional[Union[str, List[str]]] = None, + recurse: bool = True, + case_sensitive: bool = False, + limit: Optional[int] = None, + offset: int = 0, +) -> List[str]: + """Get a sorted list of (audio) files in a directory or directory sub-tree. + + Examples + -------- + >>> # Get all audio files in a directory sub-tree + >>> files = librosa.util.find_files('~/Music') + + >>> # Look only within a specific directory, not the sub-tree + >>> files = librosa.util.find_files('~/Music', recurse=False) + + >>> # Only look for mp3 files + >>> files = librosa.util.find_files('~/Music', ext='mp3') + + >>> # Or just mp3 and ogg + >>> files = librosa.util.find_files('~/Music', ext=['mp3', 'ogg']) + + >>> # Only get the first 10 files + >>> files = librosa.util.find_files('~/Music', limit=10) + + >>> # Or last 10 files + >>> files = librosa.util.find_files('~/Music', offset=-10) + + >>> # Avoid including search patterns in the path string + >>> import glob + >>> directory = '~/[202206] Music' + >>> directory = glob.escape(directory) # Escape the special characters + >>> files = librosa.util.find_files(directory) + + Parameters + ---------- + directory : str + Path to look for files + + ext : str or list of str + A file extension or list of file extensions to include in the search. + + Default: ``['aac', 'au', 'flac', 'm4a', 'mp3', 'ogg', 'wav']`` + + recurse : boolean + If ``True``, then all subfolders of ``directory`` will be searched. + + Otherwise, only ``directory`` will be searched. + + case_sensitive : boolean + If ``False``, files matching upper-case version of + extensions will be included. + + limit : int > 0 or None + Return at most ``limit`` files. If ``None``, all files are returned. + + offset : int + Return files starting at ``offset`` within the list. + + Use negative values to offset from the end of the list. + + Returns + ------- + files : list of str + The list of audio files. + """ + if ext is None: + ext = ["aac", "au", "flac", "m4a", "mp3", "ogg", "wav"] + + elif isinstance(ext, str): + ext = [ext] + + # Cast into a set + ext = set(ext) + + # Generate upper-case versions + if not case_sensitive: + # Force to lower-case + ext = {e.lower() for e in ext} + # Add in upper-case versions + ext |= {e.upper() for e in ext} + + fileset = set() + + if recurse: + for walk in os.walk(directory): # type: ignore + fileset |= __get_files(walk[0], ext) + else: + fileset = __get_files(directory, ext) + + files = list(fileset) + files.sort() + files = files[offset:] + if limit is not None: + files = files[:limit] + + return files + + +def __get_files(dir_name: Union[str, os.PathLike[Any]], extensions: Set[str]): + """Get a list of files in a single directory""" + # Expand out the directory + dir_name = os.path.abspath(os.path.expanduser(dir_name)) + + myfiles = set() + + for sub_ext in extensions: + globstr = os.path.join(dir_name, "*" + os.path.extsep + sub_ext) + myfiles |= set(glob.glob(globstr)) + + return myfiles + + +def cite(version: Optional[str]=None) -> str: + """Print the citation information for librosa. + + Parameters + ---------- + version : str or None + The version of librosa to cite. If None, the current version is used. + + Returns + ------- + doi : str + The DOI for the given version of librosa. + + Raises + ------ + ParameterError + If the requested version is not found in the citation index. + + Examples + -------- + >>> librosa.cite("0.10.1") + "https://doi.org/10.5281/zenodo.8252662" + """ + if version is None: + version = librosa_version + + version_data = __GOODBOY.fetch("version_index.msgpack") + with open(version_data, "rb") as fdesc: + version_index = msgpack.load(fdesc) + + if version not in version_index: + if "dev" in version: + raise ParameterError(f"Version {version} is not yet released and therefore does not yet have a citable DOI.") + else: + raise ParameterError(f"Version {version} not found in the citation index") + + return f"https://doi.org/{version_index[version]}" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/matching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..05cb907408465ccbd9bbd4c06046d1e3bdc84409 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/matching.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Matching functions""" + +import numpy as np +import numba + +from .exceptions import ParameterError +from .utils import valid_intervals +from .._typing import _SequenceLike + +__all__ = ["match_intervals", "match_events"] + + +@numba.jit(nopython=True, cache=True) # type: ignore +def __jaccard(int_a: np.ndarray, int_b: np.ndarray): # pragma: no cover + """Jaccard similarity between two intervals + + Parameters + ---------- + int_a, int_b : np.ndarrays, shape=(2,) + + Returns + ------- + Jaccard similarity between intervals + """ + ends = [int_a[1], int_b[1]] + if ends[1] < ends[0]: + ends.reverse() + + starts = [int_a[0], int_b[0]] + if starts[1] < starts[0]: + starts.reverse() + + intersection = ends[0] - starts[1] + if intersection < 0: + intersection = 0.0 + + union = ends[1] - starts[0] + + if union > 0: + return intersection / union + + return 0.0 + + +@numba.jit(nopython=True, cache=True) +def __match_interval_overlaps(query, intervals_to, candidates): # pragma: no cover + """Find the best Jaccard match from query to candidates""" + best_score = -1 + best_idx = -1 + for idx in candidates: + score = __jaccard(query, intervals_to[idx]) + + if score > best_score: + best_score, best_idx = score, idx + return best_idx + + +@numba.jit(nopython=True, cache=True) # type: ignore +def __match_intervals( + intervals_from: np.ndarray, intervals_to: np.ndarray, strict: bool = True +) -> np.ndarray: # pragma: no cover + """Numba-accelerated interval matching algorithm.""" + # sort index of the interval starts + start_index = np.argsort(intervals_to[:, 0]) + + # sort index of the interval ends + end_index = np.argsort(intervals_to[:, 1]) + + # and sorted values of starts + start_sorted = intervals_to[start_index, 0] + # and ends + end_sorted = intervals_to[end_index, 1] + + search_ends = np.searchsorted(start_sorted, intervals_from[:, 1], side="right") + search_starts = np.searchsorted(end_sorted, intervals_from[:, 0], side="left") + + output = np.empty(len(intervals_from), dtype=numba.uint32) + for i in range(len(intervals_from)): + query = intervals_from[i] + + # Find the intervals that start after our query ends + after_query = search_ends[i] + # And the intervals that end after our query begins + before_query = search_starts[i] + + # Candidates for overlapping have to (end after we start) and (begin before we end) + candidates = set(start_index[:after_query]) & set(end_index[before_query:]) + + # Proceed as before + if len(candidates) > 0: + output[i] = __match_interval_overlaps(query, intervals_to, candidates) + elif strict: + # Numba only lets us use compile-time constants in exception messages + raise ParameterError + else: + # Find the closest interval + # (start_index[after_query] - query[1]) is the distance to the next interval + # (query[0] - end_index[before_query]) + dist_before = np.inf + dist_after = np.inf + if search_starts[i] > 0: + dist_before = query[0] - end_sorted[search_starts[i] - 1] + if search_ends[i] + 1 < len(intervals_to): + dist_after = start_sorted[search_ends[i] + 1] - query[1] + if dist_before < dist_after: + output[i] = end_index[search_starts[i] - 1] + else: + output[i] = start_index[search_ends[i] + 1] + return output + + +def match_intervals( + intervals_from: np.ndarray, intervals_to: np.ndarray, strict: bool = True +) -> np.ndarray: + """Match one set of time intervals to another. + + This can be useful for tasks such as mapping beat timings + to segments. + + Each element ``[a, b]`` of ``intervals_from`` is matched to the + element ``[c, d]`` of ``intervals_to`` which maximizes the + Jaccard similarity between the intervals:: + + max(0, |min(b, d) - max(a, c)|) / |max(d, b) - min(a, c)| + + In ``strict=True`` mode, if there is no interval with positive + intersection with ``[a,b]``, an exception is thrown. + + In ``strict=False`` mode, any interval ``[a, b]`` that has no + intersection with any element of ``intervals_to`` is instead + matched to the interval ``[c, d]`` which minimizes:: + + min(|b - c|, |a - d|) + + that is, the disjoint interval [c, d] with a boundary closest + to [a, b]. + + .. note:: An element of ``intervals_to`` may be matched to multiple + entries of ``intervals_from``. + + Parameters + ---------- + intervals_from : np.ndarray [shape=(n, 2)] + The time range for source intervals. + The ``i`` th interval spans time ``intervals_from[i, 0]`` + to ``intervals_from[i, 1]``. + ``intervals_from[0, 0]`` should be 0, ``intervals_from[-1, 1]`` + should be the track duration. + intervals_to : np.ndarray [shape=(m, 2)] + Analogous to ``intervals_from``. + strict : bool + If ``True``, intervals can only match if they intersect. + If ``False``, disjoint intervals can match. + + Returns + ------- + interval_mapping : np.ndarray [shape=(n,)] + For each interval in ``intervals_from``, the + corresponding interval in ``intervals_to``. + + See Also + -------- + match_events + + Raises + ------ + ParameterError + If either array of input intervals is not the correct shape + + If ``strict=True`` and some element of ``intervals_from`` is disjoint from + every element of ``intervals_to``. + + Examples + -------- + >>> ints_from = np.array([[3, 5], [1, 4], [4, 5]]) + >>> ints_to = np.array([[0, 2], [1, 3], [4, 5], [6, 7]]) + >>> librosa.util.match_intervals(ints_from, ints_to) + array([2, 1, 2], dtype=uint32) + >>> # [3, 5] => [4, 5] (ints_to[2]) + >>> # [1, 4] => [1, 3] (ints_to[1]) + >>> # [4, 5] => [4, 5] (ints_to[2]) + + The reverse matching of the above is not possible in ``strict`` mode + because ``[6, 7]`` is disjoint from all intervals in ``ints_from``. + With ``strict=False``, we get the following: + + >>> librosa.util.match_intervals(ints_to, ints_from, strict=False) + array([1, 1, 2, 2], dtype=uint32) + >>> # [0, 2] => [1, 4] (ints_from[1]) + >>> # [1, 3] => [1, 4] (ints_from[1]) + >>> # [4, 5] => [4, 5] (ints_from[2]) + >>> # [6, 7] => [4, 5] (ints_from[2]) + """ + if len(intervals_from) == 0 or len(intervals_to) == 0: + raise ParameterError("Attempting to match empty interval list") + + # Verify that the input intervals has correct shape and size + valid_intervals(intervals_from) + valid_intervals(intervals_to) + + try: + # Suppress type check because of numba wrapper + return __match_intervals(intervals_from, intervals_to, strict=strict) # type: ignore + except ParameterError as exc: + raise ParameterError(f"Unable to match intervals with strict={strict}") from exc + + +def match_events( + events_from: _SequenceLike, + events_to: _SequenceLike, + left: bool = True, + right: bool = True, +) -> np.ndarray: + """Match one set of events to another. + + This is useful for tasks such as matching beats to the nearest + detected onsets, or frame-aligned events to the nearest zero-crossing. + + .. note:: A target event may be matched to multiple source events. + + Examples + -------- + >>> # Sources are multiples of 7 + >>> s_from = np.arange(0, 100, 7) + >>> s_from + array([ 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, + 98]) + >>> # Targets are multiples of 10 + >>> s_to = np.arange(0, 100, 10) + >>> s_to + array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90]) + >>> # Find the matching + >>> idx = librosa.util.match_events(s_from, s_to) + >>> idx + array([0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 9]) + >>> # Print each source value to its matching target + >>> zip(s_from, s_to[idx]) + [(0, 0), (7, 10), (14, 10), (21, 20), (28, 30), (35, 30), + (42, 40), (49, 50), (56, 60), (63, 60), (70, 70), (77, 80), + (84, 80), (91, 90), (98, 90)] + + Parameters + ---------- + events_from : ndarray [shape=(n,)] + Array of events (eg, times, sample or frame indices) to match from. + events_to : ndarray [shape=(m,)] + Array of events (eg, times, sample or frame indices) to + match against. + left : bool + right : bool + If ``False``, then matched events cannot be to the left (or right) + of source events. + + Returns + ------- + event_mapping : np.ndarray [shape=(n,)] + For each event in ``events_from``, the corresponding event + index in ``events_to``:: + + event_mapping[i] == arg min |events_from[i] - events_to[:]| + + See Also + -------- + match_intervals + + Raises + ------ + ParameterError + If either array of input events is not the correct shape + """ + if len(events_from) == 0 or len(events_to) == 0: + raise ParameterError("Attempting to match empty event list") + + # If we can't match left or right, then only strict equivalence + # counts as a match. + if not (left or right) and not np.all(np.isin(events_from, events_to)): + raise ParameterError( + "Cannot match events with left=right=False " + "and events_from is not contained " + "in events_to" + ) + + # If we can't match to the left, then there should be at least one + # target event greater-equal to every source event + if (not left) and max(events_to) < max(events_from): + raise ParameterError( + "Cannot match events with left=False " + "and max(events_to) < max(events_from)" + ) + + # If we can't match to the right, then there should be at least one + # target event less-equal to every source event + if (not right) and min(events_to) > min(events_from): + raise ParameterError( + "Cannot match events with right=False " + "and min(events_to) > min(events_from)" + ) + + # array of matched items + output = np.empty_like(events_from, dtype=np.int32) + + # Suppress type check because of numba + return __match_events_helper(output, events_from, events_to, left, right) # type: ignore + + +@numba.jit(nopython=True, cache=True) # type: ignore +def __match_events_helper( + output: np.ndarray, + events_from: np.ndarray, + events_to: np.ndarray, + left: bool = True, + right: bool = True, +): # pragma: no cover + # mock dictionary for events + from_idx = np.argsort(events_from) + sorted_from = events_from[from_idx] + + to_idx = np.argsort(events_to) + sorted_to = events_to[to_idx] + + # find the matching indices + matching_indices = np.searchsorted(sorted_to, sorted_from) + + # iterate over indices in matching_indices + for ind, middle_ind in enumerate(matching_indices): + left_flag = False + right_flag = False + + left_ind = -1 + right_ind = len(matching_indices) + + left_diff = 0 + right_diff = 0 + mid_diff = 0 + + middle_ind = matching_indices[ind] + sorted_from_num = sorted_from[ind] + + # Prevent oob from chosen index + if middle_ind == len(sorted_to): + middle_ind -= 1 + + # Permitted to look to the left + if left and middle_ind > 0: + left_ind = middle_ind - 1 + left_flag = True + + # Permitted to look to right + if right and middle_ind < len(sorted_to) - 1: + right_ind = middle_ind + 1 + right_flag = True + + mid_diff = abs(sorted_to[middle_ind] - sorted_from_num) + if left and left_flag: + left_diff = abs(sorted_to[left_ind] - sorted_from_num) + if right and right_flag: + right_diff = abs(sorted_to[right_ind] - sorted_from_num) + + if left_flag and ( + not right + and (sorted_to[middle_ind] > sorted_from_num) + or (not right_flag and left_diff < mid_diff) + or (left_diff < right_diff and left_diff < mid_diff) + ): + output[ind] = to_idx[left_ind] + + # Check if right should be chosen + elif right_flag and (right_diff < mid_diff): + output[ind] = to_idx[right_ind] + + # Selected index wins + else: + output[ind] = to_idx[middle_ind] + + # Undo sorting + solutions = np.empty_like(output) + solutions[from_idx] = output + + return solutions diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5a92c440fd065d9c07ea327a157e206139fb1eab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/librosa/util/utils.py @@ -0,0 +1,2571 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Utility functions""" + +from __future__ import annotations + +import scipy.ndimage +import scipy.sparse + +import numpy as np +import numba +from numpy.lib.stride_tricks import as_strided + +from .._cache import cache +from .exceptions import ParameterError +from .deprecation import Deprecated +from numpy.typing import DTypeLike +from typing import ( + Any, + Callable, + List, + Dict, + Optional, + Sequence, + Tuple, + TypeVar, + Union, + overload, +) +from typing_extensions import Literal +from .._typing import _SequenceLike, _FloatLike_co, _ComplexLike_co + +# Constrain STFT block sizes to 256 KB +MAX_MEM_BLOCK = 2**8 * 2**10 + +__all__ = [ + "MAX_MEM_BLOCK", + "frame", + "pad_center", + "expand_to", + "fix_length", + "valid_audio", + "valid_int", + "is_positive_int", + "valid_intervals", + "fix_frames", + "axis_sort", + "localmax", + "localmin", + "normalize", + "peak_pick", + "sparsify_rows", + "shear", + "stack", + "fill_off_diagonal", + "index_to_slice", + "sync", + "softmask", + "buf_to_float", + "tiny", + "cyclic_gradient", + "dtype_r2c", + "dtype_c2r", + "count_unique", + "is_unique", + "abs2", + "phasor", +] + + +def frame( + x: np.ndarray, + *, + frame_length: int, + hop_length: int, + axis: int = -1, + writeable: bool = False, + subok: bool = False, +) -> np.ndarray: + """Slice a data array into (overlapping) frames. + + This implementation uses low-level stride manipulation to avoid + making a copy of the data. The resulting frame representation + is a new view of the same input data. + + For example, a one-dimensional input ``x = [0, 1, 2, 3, 4, 5, 6]`` + can be framed with frame length 3 and hop length 2 in two ways. + The first (``axis=-1``), results in the array ``x_frames``:: + + [[0, 2, 4], + [1, 3, 5], + [2, 4, 6]] + + where each column ``x_frames[:, i]`` contains a contiguous slice of + the input ``x[i * hop_length : i * hop_length + frame_length]``. + + The second way (``axis=0``) results in the array ``x_frames``:: + + [[0, 1, 2], + [2, 3, 4], + [4, 5, 6]] + + where each row ``x_frames[i]`` contains a contiguous slice of the input. + + This generalizes to higher dimensional inputs, as shown in the examples below. + In general, the framing operation increments by 1 the number of dimensions, + adding a new "frame axis" either before the framing axis (if ``axis < 0``) + or after the framing axis (if ``axis >= 0``). + + Parameters + ---------- + x : np.ndarray + Array to frame + frame_length : int > 0 [scalar] + Length of the frame + hop_length : int > 0 [scalar] + Number of steps to advance between frames + axis : int + The axis along which to frame. + writeable : bool + If ``False``, then the framed view of ``x`` is read-only. + If ``True``, then the framed view is read-write. Note that writing to the framed view + will also write to the input array ``x`` in this case. + subok : bool + If True, sub-classes will be passed-through, otherwise the returned array will be + forced to be a base-class array (default). + + Returns + ------- + x_frames : np.ndarray [shape=(..., frame_length, N_FRAMES, ...)] + A framed view of ``x``, for example with ``axis=-1`` (framing on the last dimension):: + + x_frames[..., j] == x[..., j * hop_length : j * hop_length + frame_length] + + If ``axis=0`` (framing on the first dimension), then:: + + x_frames[j] = x[j * hop_length : j * hop_length + frame_length] + + Raises + ------ + ParameterError + If ``x.shape[axis] < frame_length``, there is not enough data to fill one frame. + + If ``hop_length < 1``, frames cannot advance. + + See Also + -------- + numpy.lib.stride_tricks.as_strided + + Examples + -------- + Extract 2048-sample frames from monophonic signal with a hop of 64 samples per frame + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> frames = librosa.util.frame(y, frame_length=2048, hop_length=64) + >>> frames + array([[-1.407e-03, -2.604e-02, ..., -1.795e-05, -8.108e-06], + [-4.461e-04, -3.721e-02, ..., -1.573e-05, -1.652e-05], + ..., + [ 7.960e-02, -2.335e-01, ..., -6.815e-06, 1.266e-05], + [ 9.568e-02, -1.252e-01, ..., 7.397e-06, -1.921e-05]], + dtype=float32) + >>> y.shape + (117601,) + + >>> frames.shape + (2048, 1806) + + Or frame along the first axis instead of the last: + + >>> frames = librosa.util.frame(y, frame_length=2048, hop_length=64, axis=0) + >>> frames.shape + (1806, 2048) + + Frame a stereo signal: + + >>> y, sr = librosa.load(librosa.ex('trumpet', hq=True), mono=False) + >>> y.shape + (2, 117601) + >>> frames = librosa.util.frame(y, frame_length=2048, hop_length=64) + (2, 2048, 1806) + + Carve an STFT into fixed-length patches of 32 frames with 50% overlap + + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + >>> S.shape + (1025, 230) + >>> S_patch = librosa.util.frame(S, frame_length=32, hop_length=16) + >>> S_patch.shape + (1025, 32, 13) + >>> # The first patch contains the first 32 frames of S + >>> np.allclose(S_patch[:, :, 0], S[:, :32]) + True + >>> # The second patch contains frames 16 to 16+32=48, and so on + >>> np.allclose(S_patch[:, :, 1], S[:, 16:48]) + True + """ + # This implementation is derived from numpy.lib.stride_tricks.sliding_window_view (1.20.0) + # https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html + + x = np.array(x, copy=False, subok=subok) + + if x.shape[axis] < frame_length: + raise ParameterError( + f"Input is too short (n={x.shape[axis]:d}) for frame_length={frame_length:d}" + ) + + if hop_length < 1: + raise ParameterError(f"Invalid hop_length: {hop_length:d}") + + # put our new within-frame axis at the end for now + out_strides = x.strides + tuple([x.strides[axis]]) + + # Reduce the shape on the framing axis + x_shape_trimmed = list(x.shape) + x_shape_trimmed[axis] -= frame_length - 1 + + out_shape = tuple(x_shape_trimmed) + tuple([frame_length]) + xw = as_strided( + x, strides=out_strides, shape=out_shape, subok=subok, writeable=writeable + ) + + if axis < 0: + target_axis = axis - 1 + else: + target_axis = axis + 1 + + xw = np.moveaxis(xw, -1, target_axis) + + # Downsample along the target axis + slices = [slice(None)] * xw.ndim + slices[axis] = slice(0, None, hop_length) + return xw[tuple(slices)] + + +@cache(level=20) +def valid_audio(y: np.ndarray) -> bool: + """Determine whether a variable contains valid audio data. + + The following conditions must be satisfied: + + - ``type(y)`` is ``np.ndarray`` + - ``y.dtype`` is floating-point + - ``y.ndim != 0`` (must have at least one dimension) + - ``np.isfinite(y).all()`` samples must be all finite values + + Parameters + ---------- + y : np.ndarray + The input data to validate + + Returns + ------- + valid : bool + True if all tests pass + + Raises + ------ + ParameterError + In any of the conditions specified above fails + + Notes + ----- + This function caches at level 20. + + Examples + -------- + We can make an array that can be interpreted as an audio signal + + >>> y = np.random.randn(5000) + >>> librosa.util.valid_audio(y) + True + + If we insert a non-finite sample value somewhere, it will fail + + >>> y[5] = np.nan + >>> librosa.util.valid_audio(y) + ... + ParameterError: Audio buffer is not finite everywhere + + See Also + -------- + numpy.float32 + """ + if not isinstance(y, np.ndarray): + raise ParameterError("Audio data must be of type numpy.ndarray") + + if not np.issubdtype(y.dtype, np.floating): + raise ParameterError("Audio data must be floating-point") + + if y.ndim == 0: + raise ParameterError( + f"Audio data must be at least one-dimensional, given y.shape={y.shape}" + ) + + if not np.isfinite(y).all(): + raise ParameterError("Audio buffer is not finite everywhere") + + return True + + +def valid_int(x: float, *, cast: Optional[Callable[[float], float]] = None) -> int: + """Ensure that an input value is integer-typed. + This is primarily useful for ensuring integrable-valued + array indices. + + Parameters + ---------- + x : number + A scalar value to be cast to int + cast : function [optional] + A function to modify ``x`` before casting. + Default: `np.floor` + + Returns + ------- + x_int : int + ``x_int = int(cast(x))`` + + Raises + ------ + ParameterError + If ``cast`` is provided and is not callable. + """ + if cast is None: + cast = np.floor + + if not callable(cast): + raise ParameterError("cast parameter must be callable") + + return int(cast(x)) + + +def is_positive_int(x: float) -> bool: + """Check that x is a positive integer, i.e. 1 or greater. + + Parameters + ---------- + x : number + + Returns + ------- + positive : bool + """ + # Check type first to catch None values. + return isinstance(x, (int, np.integer)) and (x > 0) + + +def valid_intervals(intervals: np.ndarray) -> bool: + """Ensure that an array is a valid representation of time intervals: + + - intervals.ndim == 2 + - intervals.shape[1] == 2 + - intervals[i, 0] <= intervals[i, 1] for all i + + Parameters + ---------- + intervals : np.ndarray [shape=(n, 2)] + set of time intervals + + Returns + ------- + valid : bool + True if ``intervals`` passes validation. + """ + if intervals.ndim != 2 or intervals.shape[-1] != 2: + raise ParameterError("intervals must have shape (n, 2)") + + if np.any(intervals[:, 0] > intervals[:, 1]): + raise ParameterError(f"intervals={intervals} must have non-negative durations") + + return True + + +def pad_center( + data: np.ndarray, *, size: int, axis: int = -1, **kwargs: Any +) -> np.ndarray: + """Pad an array to a target length along a target axis. + + This differs from `np.pad` by centering the data prior to padding, + analogous to `str.center` + + Examples + -------- + >>> # Generate a vector + >>> data = np.ones(5) + >>> librosa.util.pad_center(data, size=10, mode='constant') + array([ 0., 0., 1., 1., 1., 1., 1., 0., 0., 0.]) + + >>> # Pad a matrix along its first dimension + >>> data = np.ones((3, 5)) + >>> librosa.util.pad_center(data, size=7, axis=0) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> # Or its second dimension + >>> librosa.util.pad_center(data, size=7, axis=1) + array([[ 0., 1., 1., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 1., 1., 0.], + [ 0., 1., 1., 1., 1., 1., 0.]]) + + Parameters + ---------- + data : np.ndarray + Vector to be padded and centered + size : int >= len(data) [scalar] + Length to pad ``data`` + axis : int + Axis along which to pad and center the data + **kwargs : additional keyword arguments + arguments passed to `np.pad` + + Returns + ------- + data_padded : np.ndarray + ``data`` centered and padded to length ``size`` along the + specified axis + + Raises + ------ + ParameterError + If ``size < data.shape[axis]`` + + See Also + -------- + numpy.pad + """ + kwargs.setdefault("mode", "constant") + + n = data.shape[axis] + + lpad = int((size - n) // 2) + + lengths = [(0, 0)] * data.ndim + lengths[axis] = (lpad, int(size - n - lpad)) + + if lpad < 0: + raise ParameterError( + f"Target size ({size:d}) must be at least input size ({n:d})" + ) + + return np.pad(data, lengths, **kwargs) + + +def expand_to( + x: np.ndarray, *, ndim: int, axes: Union[int, slice, Sequence[int], Sequence[slice]] +) -> np.ndarray: + """Expand the dimensions of an input array with + + Parameters + ---------- + x : np.ndarray + The input array + ndim : int + The number of dimensions to expand to. Must be at least ``x.ndim`` + axes : int or slice + The target axis or axes to preserve from x. + All other axes will have length 1. + + Returns + ------- + x_exp : np.ndarray + The expanded version of ``x``, satisfying the following: + ``x_exp[axes] == x`` + ``x_exp.ndim == ndim`` + + See Also + -------- + np.expand_dims + + Examples + -------- + Expand a 1d array into an (n, 1) shape + + >>> x = np.arange(3) + >>> librosa.util.expand_to(x, ndim=2, axes=0) + array([[0], + [1], + [2]]) + + Expand a 1d array into a (1, n) shape + + >>> librosa.util.expand_to(x, ndim=2, axes=1) + array([[0, 1, 2]]) + + Expand a 2d array into (1, n, m, 1) shape + + >>> x = np.vander(np.arange(3)) + >>> librosa.util.expand_to(x, ndim=4, axes=[1,2]).shape + (1, 3, 3, 1) + """ + # Force axes into a tuple + axes_tup: Tuple[int] + try: + axes_tup = tuple(axes) # type: ignore + except TypeError: + axes_tup = tuple([axes]) # type: ignore + + if len(axes_tup) != x.ndim: + raise ParameterError( + f"Shape mismatch between axes={axes_tup} and input x.shape={x.shape}" + ) + + if ndim < x.ndim: + raise ParameterError( + f"Cannot expand x.shape={x.shape} to fewer dimensions ndim={ndim}" + ) + + shape: List[int] = [1] * ndim + for i, axi in enumerate(axes_tup): + shape[axi] = x.shape[i] + + return x.reshape(shape) + + +def fix_length( + data: np.ndarray, *, size: int, axis: int = -1, **kwargs: Any +) -> np.ndarray: + """Fix the length an array ``data`` to exactly ``size`` along a target axis. + + If ``data.shape[axis] < n``, pad according to the provided kwargs. + By default, ``data`` is padded with trailing zeros. + + Examples + -------- + >>> y = np.arange(7) + >>> # Default: pad with zeros + >>> librosa.util.fix_length(y, size=10) + array([0, 1, 2, 3, 4, 5, 6, 0, 0, 0]) + >>> # Trim to a desired length + >>> librosa.util.fix_length(y, size=5) + array([0, 1, 2, 3, 4]) + >>> # Use edge-padding instead of zeros + >>> librosa.util.fix_length(y, size=10, mode='edge') + array([0, 1, 2, 3, 4, 5, 6, 6, 6, 6]) + + Parameters + ---------- + data : np.ndarray + array to be length-adjusted + size : int >= 0 [scalar] + desired length of the array + axis : int, <= data.ndim + axis along which to fix length + **kwargs : additional keyword arguments + Parameters to ``np.pad`` + + Returns + ------- + data_fixed : np.ndarray [shape=data.shape] + ``data`` either trimmed or padded to length ``size`` + along the specified axis. + + See Also + -------- + numpy.pad + """ + kwargs.setdefault("mode", "constant") + + n = data.shape[axis] + + if n > size: + slices = [slice(None)] * data.ndim + slices[axis] = slice(0, size) + return data[tuple(slices)] + + elif n < size: + lengths = [(0, 0)] * data.ndim + lengths[axis] = (0, size - n) + return np.pad(data, lengths, **kwargs) + + return data + + +def fix_frames( + frames: _SequenceLike[int], + *, + x_min: Optional[int] = 0, + x_max: Optional[int] = None, + pad: bool = True, +) -> np.ndarray: + """Fix a list of frames to lie within [x_min, x_max] + + Examples + -------- + >>> # Generate a list of frame indices + >>> frames = np.arange(0, 1000.0, 50) + >>> frames + array([ 0., 50., 100., 150., 200., 250., 300., 350., + 400., 450., 500., 550., 600., 650., 700., 750., + 800., 850., 900., 950.]) + >>> # Clip to span at most 250 + >>> librosa.util.fix_frames(frames, x_max=250) + array([ 0, 50, 100, 150, 200, 250]) + >>> # Or pad to span up to 2500 + >>> librosa.util.fix_frames(frames, x_max=2500) + array([ 0, 50, 100, 150, 200, 250, 300, 350, 400, + 450, 500, 550, 600, 650, 700, 750, 800, 850, + 900, 950, 2500]) + >>> librosa.util.fix_frames(frames, x_max=2500, pad=False) + array([ 0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, + 550, 600, 650, 700, 750, 800, 850, 900, 950]) + + >>> # Or starting away from zero + >>> frames = np.arange(200, 500, 33) + >>> frames + array([200, 233, 266, 299, 332, 365, 398, 431, 464, 497]) + >>> librosa.util.fix_frames(frames) + array([ 0, 200, 233, 266, 299, 332, 365, 398, 431, 464, 497]) + >>> librosa.util.fix_frames(frames, x_max=500) + array([ 0, 200, 233, 266, 299, 332, 365, 398, 431, 464, 497, + 500]) + + Parameters + ---------- + frames : np.ndarray [shape=(n_frames,)] + List of non-negative frame indices + x_min : int >= 0 or None + Minimum allowed frame index + x_max : int >= 0 or None + Maximum allowed frame index + pad : boolean + If ``True``, then ``frames`` is expanded to span the full range + ``[x_min, x_max]`` + + Returns + ------- + fixed_frames : np.ndarray [shape=(n_fixed_frames,), dtype=int] + Fixed frame indices, flattened and sorted + + Raises + ------ + ParameterError + If ``frames`` contains negative values + """ + frames = np.asarray(frames) + + if np.any(frames < 0): + raise ParameterError("Negative frame index detected") + + # TODO: this whole function could be made more efficient + + if pad and (x_min is not None or x_max is not None): + frames = np.clip(frames, x_min, x_max) + + if pad: + pad_data = [] + if x_min is not None: + pad_data.append(x_min) + if x_max is not None: + pad_data.append(x_max) + frames = np.concatenate((np.asarray(pad_data), frames)) + + if x_min is not None: + frames = frames[frames >= x_min] + + if x_max is not None: + frames = frames[frames <= x_max] + + unique: np.ndarray = np.unique(frames).astype(int) + return unique + + +@overload +def axis_sort( + S: np.ndarray, + *, + axis: int = ..., + index: Literal[False] = ..., + value: Optional[Callable[..., Any]] = ..., +) -> np.ndarray: + ... + + +@overload +def axis_sort( + S: np.ndarray, + *, + axis: int = ..., + index: Literal[True], + value: Optional[Callable[..., Any]] = ..., +) -> Tuple[np.ndarray, np.ndarray]: + ... + + +def axis_sort( + S: np.ndarray, + *, + axis: int = -1, + index: bool = False, + value: Optional[Callable[..., Any]] = None, +) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: + """Sort an array along its rows or columns. + + Examples + -------- + Visualize NMF output for a spectrogram S + + >>> # Sort the columns of W by peak frequency bin + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> S = np.abs(librosa.stft(y)) + >>> W, H = librosa.decompose.decompose(S, n_components=64) + >>> W_sort = librosa.util.axis_sort(W) + + Or sort by the lowest frequency bin + + >>> W_sort = librosa.util.axis_sort(W, value=np.argmin) + + Or sort the rows instead of the columns + + >>> W_sort_rows = librosa.util.axis_sort(W, axis=0) + + Get the sorting index also, and use it to permute the rows of H + + >>> W_sort, idx = librosa.util.axis_sort(W, index=True) + >>> H_sort = H[idx, :] + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots(nrows=2, ncols=2) + >>> img_w = librosa.display.specshow(librosa.amplitude_to_db(W, ref=np.max), + ... y_axis='log', ax=ax[0, 0]) + >>> ax[0, 0].set(title='W') + >>> ax[0, 0].label_outer() + >>> img_act = librosa.display.specshow(H, x_axis='time', ax=ax[0, 1]) + >>> ax[0, 1].set(title='H') + >>> ax[0, 1].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(W_sort, + ... ref=np.max), + ... y_axis='log', ax=ax[1, 0]) + >>> ax[1, 0].set(title='W sorted') + >>> librosa.display.specshow(H_sort, x_axis='time', ax=ax[1, 1]) + >>> ax[1, 1].set(title='H sorted') + >>> ax[1, 1].label_outer() + >>> fig.colorbar(img_w, ax=ax[:, 0], orientation='horizontal') + >>> fig.colorbar(img_act, ax=ax[:, 1], orientation='horizontal') + + Parameters + ---------- + S : np.ndarray [shape=(d, n)] + Array to be sorted + + axis : int [scalar] + The axis along which to compute the sorting values + + - ``axis=0`` to sort rows by peak column index + - ``axis=1`` to sort columns by peak row index + + index : boolean [scalar] + If true, returns the index array as well as the permuted data. + + value : function + function to return the index corresponding to the sort order. + Default: `np.argmax`. + + Returns + ------- + S_sort : np.ndarray [shape=(d, n)] + ``S`` with the columns or rows permuted in sorting order + idx : np.ndarray (optional) [shape=(d,) or (n,)] + If ``index == True``, the sorting index used to permute ``S``. + Length of ``idx`` corresponds to the selected ``axis``. + + Raises + ------ + ParameterError + If ``S`` does not have exactly 2 dimensions (``S.ndim != 2``) + """ + if value is None: + value = np.argmax + + if S.ndim != 2: + raise ParameterError("axis_sort is only defined for 2D arrays") + + bin_idx = value(S, axis=np.mod(1 - axis, S.ndim)) + idx = np.argsort(bin_idx) + + sort_slice = [slice(None)] * S.ndim + sort_slice[axis] = idx # type: ignore + + if index: + return S[tuple(sort_slice)], idx + else: + return S[tuple(sort_slice)] + + +@cache(level=40) +def normalize( + S: np.ndarray, + *, + norm: Optional[float] = np.inf, + axis: Optional[int] = 0, + threshold: Optional[_FloatLike_co] = None, + fill: Optional[bool] = None, +) -> np.ndarray: + """Normalize an array along a chosen axis. + + Given a norm (described below) and a target axis, the input + array is scaled so that:: + + norm(S, axis=axis) == 1 + + For example, ``axis=0`` normalizes each column of a 2-d array + by aggregating over the rows (0-axis). + Similarly, ``axis=1`` normalizes each row of a 2-d array. + + This function also supports thresholding small-norm slices: + any slice (i.e., row or column) with norm below a specified + ``threshold`` can be left un-normalized, set to all-zeros, or + filled with uniform non-zero values that normalize to 1. + + Note: the semantics of this function differ from + `scipy.linalg.norm` in two ways: multi-dimensional arrays + are supported, but matrix-norms are not. + + Parameters + ---------- + S : np.ndarray + The array to normalize + + norm : {np.inf, -np.inf, 0, float > 0, None} + - `np.inf` : maximum absolute value + - `-np.inf` : minimum absolute value + - `0` : number of non-zeros (the support) + - float : corresponding l_p norm + See `scipy.linalg.norm` for details. + - None : no normalization is performed + + axis : int [scalar] + Axis along which to compute the norm. + + threshold : number > 0 [optional] + Only the columns (or rows) with norm at least ``threshold`` are + normalized. + + By default, the threshold is determined from + the numerical precision of ``S.dtype``. + + fill : None or bool + If None, then columns (or rows) with norm below ``threshold`` + are left as is. + + If False, then columns (rows) with norm below ``threshold`` + are set to 0. + + If True, then columns (rows) with norm below ``threshold`` + are filled uniformly such that the corresponding norm is 1. + + .. note:: ``fill=True`` is incompatible with ``norm=0`` because + no uniform vector exists with l0 "norm" equal to 1. + + Returns + ------- + S_norm : np.ndarray [shape=S.shape] + Normalized array + + Raises + ------ + ParameterError + If ``norm`` is not among the valid types defined above + + If ``S`` is not finite + + If ``fill=True`` and ``norm=0`` + + See Also + -------- + scipy.linalg.norm + + Notes + ----- + This function caches at level 40. + + Examples + -------- + >>> # Construct an example matrix + >>> S = np.vander(np.arange(-2.0, 2.0)) + >>> S + array([[-8., 4., -2., 1.], + [-1., 1., -1., 1.], + [ 0., 0., 0., 1.], + [ 1., 1., 1., 1.]]) + >>> # Max (l-infinity)-normalize the columns + >>> librosa.util.normalize(S) + array([[-1. , 1. , -1. , 1. ], + [-0.125, 0.25 , -0.5 , 1. ], + [ 0. , 0. , 0. , 1. ], + [ 0.125, 0.25 , 0.5 , 1. ]]) + >>> # Max (l-infinity)-normalize the rows + >>> librosa.util.normalize(S, axis=1) + array([[-1. , 0.5 , -0.25 , 0.125], + [-1. , 1. , -1. , 1. ], + [ 0. , 0. , 0. , 1. ], + [ 1. , 1. , 1. , 1. ]]) + >>> # l1-normalize the columns + >>> librosa.util.normalize(S, norm=1) + array([[-0.8 , 0.667, -0.5 , 0.25 ], + [-0.1 , 0.167, -0.25 , 0.25 ], + [ 0. , 0. , 0. , 0.25 ], + [ 0.1 , 0.167, 0.25 , 0.25 ]]) + >>> # l2-normalize the columns + >>> librosa.util.normalize(S, norm=2) + array([[-0.985, 0.943, -0.816, 0.5 ], + [-0.123, 0.236, -0.408, 0.5 ], + [ 0. , 0. , 0. , 0.5 ], + [ 0.123, 0.236, 0.408, 0.5 ]]) + + >>> # Thresholding and filling + >>> S[:, -1] = 1e-308 + >>> S + array([[ -8.000e+000, 4.000e+000, -2.000e+000, + 1.000e-308], + [ -1.000e+000, 1.000e+000, -1.000e+000, + 1.000e-308], + [ 0.000e+000, 0.000e+000, 0.000e+000, + 1.000e-308], + [ 1.000e+000, 1.000e+000, 1.000e+000, + 1.000e-308]]) + + >>> # By default, small-norm columns are left untouched + >>> librosa.util.normalize(S) + array([[ -1.000e+000, 1.000e+000, -1.000e+000, + 1.000e-308], + [ -1.250e-001, 2.500e-001, -5.000e-001, + 1.000e-308], + [ 0.000e+000, 0.000e+000, 0.000e+000, + 1.000e-308], + [ 1.250e-001, 2.500e-001, 5.000e-001, + 1.000e-308]]) + >>> # Small-norm columns can be zeroed out + >>> librosa.util.normalize(S, fill=False) + array([[-1. , 1. , -1. , 0. ], + [-0.125, 0.25 , -0.5 , 0. ], + [ 0. , 0. , 0. , 0. ], + [ 0.125, 0.25 , 0.5 , 0. ]]) + >>> # Or set to constant with unit-norm + >>> librosa.util.normalize(S, fill=True) + array([[-1. , 1. , -1. , 1. ], + [-0.125, 0.25 , -0.5 , 1. ], + [ 0. , 0. , 0. , 1. ], + [ 0.125, 0.25 , 0.5 , 1. ]]) + >>> # With an l1 norm instead of max-norm + >>> librosa.util.normalize(S, norm=1, fill=True) + array([[-0.8 , 0.667, -0.5 , 0.25 ], + [-0.1 , 0.167, -0.25 , 0.25 ], + [ 0. , 0. , 0. , 0.25 ], + [ 0.1 , 0.167, 0.25 , 0.25 ]]) + """ + # Avoid div-by-zero + if threshold is None: + threshold = tiny(S) + + elif threshold <= 0: + raise ParameterError(f"threshold={threshold} must be strictly positive") + + if fill not in [None, False, True]: + raise ParameterError(f"fill={fill} must be None or boolean") + + if not np.all(np.isfinite(S)): + raise ParameterError("Input must be finite") + + # All norms only depend on magnitude, let's do that first + mag = np.abs(S).astype(float) + + # For max/min norms, filling with 1 works + fill_norm = 1 + + if norm is None: + return S + + elif norm == np.inf: + length = np.max(mag, axis=axis, keepdims=True) + + elif norm == -np.inf: + length = np.min(mag, axis=axis, keepdims=True) + + elif norm == 0: + if fill is True: + raise ParameterError("Cannot normalize with norm=0 and fill=True") + + length = np.sum(mag > 0, axis=axis, keepdims=True, dtype=mag.dtype) + + elif np.issubdtype(type(norm), np.number) and norm > 0: + length = np.sum(mag**norm, axis=axis, keepdims=True) ** (1.0 / norm) + + if axis is None: + fill_norm = mag.size ** (-1.0 / norm) + else: + fill_norm = mag.shape[axis] ** (-1.0 / norm) + + else: + raise ParameterError(f"Unsupported norm: {repr(norm)}") + + # indices where norm is below the threshold + small_idx = length < threshold + + Snorm = np.empty_like(S) + if fill is None: + # Leave small indices un-normalized + length[small_idx] = 1.0 + Snorm[:] = S / length + + elif fill: + # If we have a non-zero fill value, we locate those entries by + # doing a nan-divide. + # If S was finite, then length is finite (except for small positions) + length[small_idx] = np.nan + Snorm[:] = S / length + Snorm[np.isnan(Snorm)] = fill_norm + else: + # Set small values to zero by doing an inf-divide. + # This is safe (by IEEE-754) as long as S is finite. + length[small_idx] = np.inf + Snorm[:] = S / length + + return Snorm + + +@numba.stencil +def _localmax_sten(x): # pragma: no cover + """Numba stencil for local maxima computation""" + return (x[0] > x[-1]) & (x[0] >= x[1]) + + +@numba.stencil +def _localmin_sten(x): # pragma: no cover + """Numba stencil for local minima computation""" + return (x[0] < x[-1]) & (x[0] <= x[1]) + + +@numba.guvectorize( + [ + "void(int16[:], bool_[:])", + "void(int32[:], bool_[:])", + "void(int64[:], bool_[:])", + "void(float32[:], bool_[:])", + "void(float64[:], bool_[:])", + ], + "(n)->(n)", + cache=True, + nopython=True, +) +def _localmax(x, y): # pragma: no cover + """Vectorized wrapper for the localmax stencil""" + y[:] = _localmax_sten(x) + + +@numba.guvectorize( + [ + "void(int16[:], bool_[:])", + "void(int32[:], bool_[:])", + "void(int64[:], bool_[:])", + "void(float32[:], bool_[:])", + "void(float64[:], bool_[:])", + ], + "(n)->(n)", + cache=True, + nopython=True, +) +def _localmin(x, y): # pragma: no cover + """Vectorized wrapper for the localmin stencil""" + y[:] = _localmin_sten(x) + + +def localmax(x: np.ndarray, *, axis: int = 0) -> np.ndarray: + """Find local maxima in an array + + An element ``x[i]`` is considered a local maximum if the following + conditions are met: + + - ``x[i] > x[i-1]`` + - ``x[i] >= x[i+1]`` + + Note that the first condition is strict, and that the first element + ``x[0]`` will never be considered as a local maximum. + + Examples + -------- + >>> x = np.array([1, 0, 1, 2, -1, 0, -2, 1]) + >>> librosa.util.localmax(x) + array([False, False, False, True, False, True, False, True], dtype=bool) + + >>> # Two-dimensional example + >>> x = np.array([[1,0,1], [2, -1, 0], [2, 1, 3]]) + >>> librosa.util.localmax(x, axis=0) + array([[False, False, False], + [ True, False, False], + [False, True, True]], dtype=bool) + >>> librosa.util.localmax(x, axis=1) + array([[False, False, True], + [False, False, True], + [False, False, True]], dtype=bool) + + Parameters + ---------- + x : np.ndarray [shape=(d1,d2,...)] + input vector or array + axis : int + axis along which to compute local maximality + + Returns + ------- + m : np.ndarray [shape=x.shape, dtype=bool] + indicator array of local maximality along ``axis`` + + See Also + -------- + localmin + """ + # Rotate the target axis to the end + xi = x.swapaxes(-1, axis) + + # Allocate the output array and rotate target axis + lmax = np.empty_like(x, dtype=bool) + lmaxi = lmax.swapaxes(-1, axis) + + # Call the vectorized stencil + _localmax(xi, lmaxi) + + # Handle the edge condition not covered by the stencil + lmaxi[..., -1] = xi[..., -1] > xi[..., -2] + + return lmax + + +def localmin(x: np.ndarray, *, axis: int = 0) -> np.ndarray: + """Find local minima in an array + + An element ``x[i]`` is considered a local minimum if the following + conditions are met: + + - ``x[i] < x[i-1]`` + - ``x[i] <= x[i+1]`` + + Note that the first condition is strict, and that the first element + ``x[0]`` will never be considered as a local minimum. + + Examples + -------- + >>> x = np.array([1, 0, 1, 2, -1, 0, -2, 1]) + >>> librosa.util.localmin(x) + array([False, True, False, False, True, False, True, False]) + + >>> # Two-dimensional example + >>> x = np.array([[1,0,1], [2, -1, 0], [2, 1, 3]]) + >>> librosa.util.localmin(x, axis=0) + array([[False, False, False], + [False, True, True], + [False, False, False]]) + + >>> librosa.util.localmin(x, axis=1) + array([[False, True, False], + [False, True, False], + [False, True, False]]) + + Parameters + ---------- + x : np.ndarray [shape=(d1,d2,...)] + input vector or array + axis : int + axis along which to compute local minimality + + Returns + ------- + m : np.ndarray [shape=x.shape, dtype=bool] + indicator array of local minimality along ``axis`` + + See Also + -------- + localmax + """ + # Rotate the target axis to the end + xi = x.swapaxes(-1, axis) + + # Allocate the output array and rotate target axis + lmin = np.empty_like(x, dtype=bool) + lmini = lmin.swapaxes(-1, axis) + + # Call the vectorized stencil + _localmin(xi, lmini) + + # Handle the edge condition not covered by the stencil + lmini[..., -1] = xi[..., -1] < xi[..., -2] + + return lmin + + + +@numba.guvectorize( + [ + "void(float32[:], uint32, uint32, uint32, uint32, float32, uint32, bool_[:])", + "void(float64[:], uint32, uint32, uint32, uint32, float32, uint32, bool_[:])", + "void(int32[:], uint32, uint32, uint32, uint32, float32, uint32, bool_[:])", + "void(int64[:], uint32, uint32, uint32, uint32, float32, uint32, bool_[:])", + ], + "(n),(),(),(),(),(),()->(n)", + nopython=True, cache=True) +def __peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait, peaks): + """Vectorized wrapper for the peak-picker""" + # Special case the first frame + peaks[0] = (x[0] >= np.max(x[:min(post_max, x.shape[0])])) + peaks[0] &= (x[0] >= np.mean(x[:min(post_avg, x.shape[0])]) + delta) + + if peaks[0]: + n = wait + 1 + else: + n = 1 + + while n < x.shape[0]: + maxn = np.max( x[max(0, n-pre_max):min(n+post_max, x.shape[0])]) + + # Are we the local max and sufficiently above average? + peaks[n] = (x[n] == maxn) + + if not peaks[n]: + n += 1 + continue + + avgn = np.mean(x[max(0, n-pre_avg):min(n+post_avg, x.shape[0])]) + peaks[n] &= (x[n] >= avgn + delta) + + if not peaks[n]: + n += 1 + continue + + # Skip the next `wait` frames + n += wait + 1 + + +def peak_pick( + x: np.ndarray, + *, + pre_max: int, + post_max: int, + pre_avg: int, + post_avg: int, + delta: float, + wait: int, + sparse: bool = True, + axis: int = -1 +) -> np.ndarray: + """Use a flexible heuristic to pick peaks in a signal. + + A sample n is selected as an peak if the corresponding ``x[n]`` + fulfills the following three conditions: + + 1. ``x[n] == max(x[n - pre_max:n + post_max])`` + 2. ``x[n] >= mean(x[n - pre_avg:n + post_avg]) + delta`` + 3. ``n - previous_n > wait`` + + where ``previous_n`` is the last sample picked as a peak (greedily). + + This implementation is based on [#]_ and [#]_. + + .. [#] Boeck, Sebastian, Florian Krebs, and Markus Schedl. + "Evaluating the Online Capabilities of Onset Detection Methods." ISMIR. + 2012. + + .. [#] https://github.com/CPJKU/onset_detection/blob/master/onset_program.py + + Parameters + ---------- + x : np.ndarray + input signal to peak picks from + pre_max : int >= 0 [scalar] + number of samples before ``n`` over which max is computed + post_max : int >= 1 [scalar] + number of samples after ``n`` over which max is computed + pre_avg : int >= 0 [scalar] + number of samples before ``n`` over which mean is computed + post_avg : int >= 1 [scalar] + number of samples after ``n`` over which mean is computed + delta : float >= 0 [scalar] + threshold offset for mean + wait : int >= 0 [scalar] + number of samples to wait after picking a peak + sparse : bool [scalar] + If `True`, the output are indices of detected peaks. + If `False`, the output is a dense boolean array of the same + shape as ``x``. + axis : int [scalar] + the axis over which to detect peaks. + + Returns + ------- + peaks : np.ndarray [shape=(n_peaks,) or shape=x.shape, dtype=int or bool] + indices of peaks in ``x`` (sparse=True) + or a boolean array where `peaks[..., n]` indicates a peak at frame index `n` (sparse=False) + + Raises + ------ + ParameterError + If any input lies outside its defined range + + Examples + -------- + >>> y, sr = librosa.load(librosa.ex('trumpet')) + >>> onset_env = librosa.onset.onset_strength(y=y, sr=sr, + ... hop_length=512, + ... aggregate=np.median) + >>> peaks = librosa.util.peak_pick(onset_env, pre_max=3, post_max=3, pre_avg=3, post_avg=5, delta=0.5, wait=10) + >>> peaks + array([ 3, 27, 40, 61, 72, 88, 103]) + + Using dense output to make a boolean array of peak indicators + >>> librosa.util.peak_pick(onset_env, pre_max=3, post_max=3, pre_avg=3, post_avg=5, + ... delta=0.5, wait=10, sparse=False) + array([False, False, ..., False, False]) + + >>> import matplotlib.pyplot as plt + >>> times = librosa.times_like(onset_env, sr=sr, hop_length=512) + >>> fig, ax = plt.subplots(nrows=2, sharex=True) + >>> D = np.abs(librosa.stft(y)) + >>> librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max), + ... y_axis='log', x_axis='time', ax=ax[1]) + >>> ax[0].plot(times, onset_env, alpha=0.8, label='Onset strength') + >>> ax[0].vlines(times[peaks], 0, + ... onset_env.max(), color='r', alpha=0.8, + ... label='Selected peaks') + >>> ax[0].legend(frameon=True, framealpha=0.8) + >>> ax[0].label_outer() + """ + if pre_max < 0: + raise ParameterError("pre_max must be non-negative") + if pre_avg < 0: + raise ParameterError("pre_avg must be non-negative") + if delta < 0: + raise ParameterError("delta must be non-negative") + if wait < 0: + raise ParameterError("wait must be non-negative") + if post_max <= 0: + raise ParameterError("post_max must be positive") + if post_avg <= 0: + raise ParameterError("post_avg must be positive") + if sparse and x.ndim != 1: + raise ParameterError(f"sparse=True (default) does not support " + f"{x.ndim}-dimensional inputs. " + f"Either set sparse=False or process each dimension independently.") + + # Ensure valid index types + pre_max = valid_int(pre_max, cast=np.ceil) + post_max = valid_int(post_max, cast=np.ceil) + pre_avg = valid_int(pre_avg, cast=np.ceil) + post_avg = valid_int(post_avg, cast=np.ceil) + wait = valid_int(wait, cast=np.ceil) + + peaks = np.zeros_like(x, dtype=bool) + __peak_pick(x.swapaxes(axis, -1), pre_max, post_max, pre_avg, post_avg, delta, wait, peaks.swapaxes(axis, -1)) + + if sparse: + return np.flatnonzero(peaks) + + return peaks + + +@cache(level=40) +def sparsify_rows( + x: np.ndarray, *, quantile: float = 0.01, dtype: Optional[DTypeLike] = None +) -> scipy.sparse.csr_matrix: + """Return a row-sparse matrix approximating the input + + Parameters + ---------- + x : np.ndarray [ndim <= 2] + The input matrix to sparsify. + quantile : float in [0, 1.0) + Percentage of magnitude to discard in each row of ``x`` + dtype : np.dtype, optional + The dtype of the output array. + If not provided, then ``x.dtype`` will be used. + + Returns + ------- + x_sparse : ``scipy.sparse.csr_matrix`` [shape=x.shape] + Row-sparsified approximation of ``x`` + + If ``x.ndim == 1``, then ``x`` is interpreted as a row vector, + and ``x_sparse.shape == (1, len(x))``. + + Raises + ------ + ParameterError + If ``x.ndim > 2`` + + If ``quantile`` lies outside ``[0, 1.0)`` + + Notes + ----- + This function caches at level 40. + + Examples + -------- + >>> # Construct a Hann window to sparsify + >>> x = scipy.signal.hann(32) + >>> x + array([ 0. , 0.01 , 0.041, 0.09 , 0.156, 0.236, 0.326, + 0.424, 0.525, 0.625, 0.72 , 0.806, 0.879, 0.937, + 0.977, 0.997, 0.997, 0.977, 0.937, 0.879, 0.806, + 0.72 , 0.625, 0.525, 0.424, 0.326, 0.236, 0.156, + 0.09 , 0.041, 0.01 , 0. ]) + >>> # Discard the bottom percentile + >>> x_sparse = librosa.util.sparsify_rows(x, quantile=0.01) + >>> x_sparse + <1x32 sparse matrix of type '' + with 26 stored elements in Compressed Sparse Row format> + >>> x_sparse.todense() + matrix([[ 0. , 0. , 0. , 0.09 , 0.156, 0.236, 0.326, + 0.424, 0.525, 0.625, 0.72 , 0.806, 0.879, 0.937, + 0.977, 0.997, 0.997, 0.977, 0.937, 0.879, 0.806, + 0.72 , 0.625, 0.525, 0.424, 0.326, 0.236, 0.156, + 0.09 , 0. , 0. , 0. ]]) + >>> # Discard up to the bottom 10th percentile + >>> x_sparse = librosa.util.sparsify_rows(x, quantile=0.1) + >>> x_sparse + <1x32 sparse matrix of type '' + with 20 stored elements in Compressed Sparse Row format> + >>> x_sparse.todense() + matrix([[ 0. , 0. , 0. , 0. , 0. , 0. , 0.326, + 0.424, 0.525, 0.625, 0.72 , 0.806, 0.879, 0.937, + 0.977, 0.997, 0.997, 0.977, 0.937, 0.879, 0.806, + 0.72 , 0.625, 0.525, 0.424, 0.326, 0. , 0. , + 0. , 0. , 0. , 0. ]]) + """ + if x.ndim == 1: + x = x.reshape((1, -1)) + + elif x.ndim > 2: + raise ParameterError( + f"Input must have 2 or fewer dimensions. Provided x.shape={x.shape}." + ) + + if not 0.0 <= quantile < 1: + raise ParameterError(f"Invalid quantile {quantile:.2f}") + + if dtype is None: + dtype = x.dtype + + x_sparse = scipy.sparse.lil_matrix(x.shape, dtype=dtype) + + mags = np.abs(x) + norms = np.sum(mags, axis=1, keepdims=True) + + mag_sort = np.sort(mags, axis=1) + cumulative_mag = np.cumsum(mag_sort / norms, axis=1) + + threshold_idx = np.argmin(cumulative_mag < quantile, axis=1) + + for i, j in enumerate(threshold_idx): + idx = np.where(mags[i] >= mag_sort[i, j]) + x_sparse[i, idx] = x[i, idx] + + return x_sparse.tocsr() + + +def buf_to_float( + x: np.ndarray, *, n_bytes: int = 2, dtype: DTypeLike = np.float32 +) -> np.ndarray: + """Convert an integer buffer to floating point values. + This is primarily useful when loading integer-valued wav data + into numpy arrays. + + Parameters + ---------- + x : np.ndarray [dtype=int] + The integer-valued data buffer + n_bytes : int [1, 2, 4] + The number of bytes per sample in ``x`` + dtype : numeric type + The target output type (default: 32-bit float) + + Returns + ------- + x_float : np.ndarray [dtype=float] + The input data buffer cast to floating point + """ + # Invert the scale of the data + scale = 1.0 / float(1 << ((8 * n_bytes) - 1)) + + # Construct the format string + fmt = f" List[slice]: + """Generate a slice array from an index array. + + Parameters + ---------- + idx : list-like + Array of index boundaries + idx_min, idx_max : None or int + Minimum and maximum allowed indices + step : None or int + Step size for each slice. If `None`, then the default + step of 1 is used. + pad : boolean + If `True`, pad ``idx`` to span the range ``idx_min:idx_max``. + + Returns + ------- + slices : list of slice + ``slices[i] = slice(idx[i], idx[i+1], step)`` + Additional slice objects may be added at the beginning or end, + depending on whether ``pad==True`` and the supplied values for + ``idx_min`` and ``idx_max``. + + See Also + -------- + fix_frames + + Examples + -------- + >>> # Generate slices from spaced indices + >>> librosa.util.index_to_slice(np.arange(20, 100, 15)) + [slice(20, 35, None), slice(35, 50, None), slice(50, 65, None), slice(65, 80, None), + slice(80, 95, None)] + >>> # Pad to span the range (0, 100) + >>> librosa.util.index_to_slice(np.arange(20, 100, 15), + ... idx_min=0, idx_max=100) + [slice(0, 20, None), slice(20, 35, None), slice(35, 50, None), slice(50, 65, None), + slice(65, 80, None), slice(80, 95, None), slice(95, 100, None)] + >>> # Use a step of 5 for each slice + >>> librosa.util.index_to_slice(np.arange(20, 100, 15), + ... idx_min=0, idx_max=100, step=5) + [slice(0, 20, 5), slice(20, 35, 5), slice(35, 50, 5), slice(50, 65, 5), slice(65, 80, 5), + slice(80, 95, 5), slice(95, 100, 5)] + """ + # First, normalize the index set + idx_fixed = fix_frames(idx, x_min=idx_min, x_max=idx_max, pad=pad) + + # Now convert the indices to slices + return [slice(start, end, step) for (start, end) in zip(idx_fixed, idx_fixed[1:])] + + +@cache(level=40) +def sync( + data: np.ndarray, + idx: Union[Sequence[int], Sequence[slice]], + *, + aggregate: Optional[Callable[..., Any]] = None, + pad: bool = True, + axis: int = -1, +) -> np.ndarray: + """Aggregate a multi-dimensional array between specified boundaries. + + .. note:: + In order to ensure total coverage, boundary points may be added + to ``idx``. + + If synchronizing a feature matrix against beat tracker output, ensure + that frame index numbers are properly aligned and use the same hop length. + + Parameters + ---------- + data : np.ndarray + multi-dimensional array of features + idx : sequence of ints or slices + Either an ordered array of boundary indices, or + an iterable collection of slice objects. + aggregate : function + aggregation function (default: `np.mean`) + pad : boolean + If `True`, ``idx`` is padded to span the full range ``[0, data.shape[axis]]`` + axis : int + The axis along which to aggregate data + + Returns + ------- + data_sync : ndarray + ``data_sync`` will have the same dimension as ``data``, except that the ``axis`` + coordinate will be reduced according to ``idx``. + + For example, a 2-dimensional ``data`` with ``axis=-1`` should satisfy:: + + data_sync[:, i] = aggregate(data[:, idx[i-1]:idx[i]], axis=-1) + + Raises + ------ + ParameterError + If the index set is not of consistent type (all slices or all integers) + + Notes + ----- + This function caches at level 40. + + Examples + -------- + Beat-synchronous CQT spectra + + >>> y, sr = librosa.load(librosa.ex('choice')) + >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False) + >>> C = np.abs(librosa.cqt(y=y, sr=sr)) + >>> beats = librosa.util.fix_frames(beats) + + By default, use mean aggregation + + >>> C_avg = librosa.util.sync(C, beats) + + Use median-aggregation instead of mean + + >>> C_med = librosa.util.sync(C, beats, + ... aggregate=np.median) + + Or sub-beat synchronization + + >>> sub_beats = librosa.segment.subsegment(C, beats) + >>> sub_beats = librosa.util.fix_frames(sub_beats) + >>> C_med_sub = librosa.util.sync(C, sub_beats, aggregate=np.median) + + Plot the results + + >>> import matplotlib.pyplot as plt + >>> beat_t = librosa.frames_to_time(beats, sr=sr) + >>> subbeat_t = librosa.frames_to_time(sub_beats, sr=sr) + >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) + >>> librosa.display.specshow(librosa.amplitude_to_db(C, + ... ref=np.max), + ... x_axis='time', ax=ax[0]) + >>> ax[0].set(title='CQT power, shape={}'.format(C.shape)) + >>> ax[0].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(C_med, + ... ref=np.max), + ... x_coords=beat_t, x_axis='time', ax=ax[1]) + >>> ax[1].set(title='Beat synchronous CQT power, ' + ... 'shape={}'.format(C_med.shape)) + >>> ax[1].label_outer() + >>> librosa.display.specshow(librosa.amplitude_to_db(C_med_sub, + ... ref=np.max), + ... x_coords=subbeat_t, x_axis='time', ax=ax[2]) + >>> ax[2].set(title='Sub-beat synchronous CQT power, ' + ... 'shape={}'.format(C_med_sub.shape)) + """ + if aggregate is None: + aggregate = np.mean + + shape = list(data.shape) + + if np.all([isinstance(_, slice) for _ in idx]): + slices = idx + elif np.all([np.issubdtype(type(_), np.integer) for _ in idx]): + slices = index_to_slice( + np.asarray(idx), idx_min=0, idx_max=shape[axis], pad=pad + ) + else: + raise ParameterError(f"Invalid index set: {idx}") + + agg_shape = list(shape) + agg_shape[axis] = len(slices) + + data_agg = np.empty( + agg_shape, order="F" if np.isfortran(data) else "C", dtype=data.dtype + ) + + idx_in = [slice(None)] * data.ndim + idx_agg = [slice(None)] * data_agg.ndim + + for i, segment in enumerate(slices): + idx_in[axis] = segment # type: ignore + idx_agg[axis] = i # type: ignore + data_agg[tuple(idx_agg)] = aggregate(data[tuple(idx_in)], axis=axis) + + return data_agg + + +def softmask( + X: np.ndarray, X_ref: np.ndarray, *, power: float = 1, split_zeros: bool = False +) -> np.ndarray: + """Robustly compute a soft-mask operation. + + ``M = X**power / (X**power + X_ref**power)`` + + Parameters + ---------- + X : np.ndarray + The (non-negative) input array corresponding to the positive mask elements + + X_ref : np.ndarray + The (non-negative) array of reference or background elements. + Must have the same shape as ``X``. + + power : number > 0 or np.inf + If finite, returns the soft mask computed in a numerically stable way + + If infinite, returns a hard (binary) mask equivalent to ``X > X_ref``. + Note: for hard masks, ties are always broken in favor of ``X_ref`` (``mask=0``). + + split_zeros : bool + If `True`, entries where ``X`` and ``X_ref`` are both small (close to 0) + will receive mask values of 0.5. + + Otherwise, the mask is set to 0 for these entries. + + Returns + ------- + mask : np.ndarray, shape=X.shape + The output mask array + + Raises + ------ + ParameterError + If ``X`` and ``X_ref`` have different shapes. + + If ``X`` or ``X_ref`` are negative anywhere + + If ``power <= 0`` + + Examples + -------- + >>> X = 2 * np.ones((3, 3)) + >>> X_ref = np.vander(np.arange(3.0)) + >>> X + array([[ 2., 2., 2.], + [ 2., 2., 2.], + [ 2., 2., 2.]]) + >>> X_ref + array([[ 0., 0., 1.], + [ 1., 1., 1.], + [ 4., 2., 1.]]) + >>> librosa.util.softmask(X, X_ref, power=1) + array([[ 1. , 1. , 0.667], + [ 0.667, 0.667, 0.667], + [ 0.333, 0.5 , 0.667]]) + >>> librosa.util.softmask(X_ref, X, power=1) + array([[ 0. , 0. , 0.333], + [ 0.333, 0.333, 0.333], + [ 0.667, 0.5 , 0.333]]) + >>> librosa.util.softmask(X, X_ref, power=2) + array([[ 1. , 1. , 0.8], + [ 0.8, 0.8, 0.8], + [ 0.2, 0.5, 0.8]]) + >>> librosa.util.softmask(X, X_ref, power=4) + array([[ 1. , 1. , 0.941], + [ 0.941, 0.941, 0.941], + [ 0.059, 0.5 , 0.941]]) + >>> librosa.util.softmask(X, X_ref, power=100) + array([[ 1.000e+00, 1.000e+00, 1.000e+00], + [ 1.000e+00, 1.000e+00, 1.000e+00], + [ 7.889e-31, 5.000e-01, 1.000e+00]]) + >>> librosa.util.softmask(X, X_ref, power=np.inf) + array([[ True, True, True], + [ True, True, True], + [False, False, True]], dtype=bool) + """ + if X.shape != X_ref.shape: + raise ParameterError(f"Shape mismatch: {X.shape}!={X_ref.shape}") + + if np.any(X < 0) or np.any(X_ref < 0): + raise ParameterError("X and X_ref must be non-negative") + + if power <= 0: + raise ParameterError("power must be strictly positive") + + # We're working with ints, cast to float. + dtype = X.dtype + if not np.issubdtype(dtype, np.floating): + dtype = np.float32 + + # Re-scale the input arrays relative to the larger value + Z = np.maximum(X, X_ref).astype(dtype) + bad_idx = Z < np.finfo(dtype).tiny + Z[bad_idx] = 1 + + # For finite power, compute the softmask + mask: np.ndarray + + if np.isfinite(power): + mask = (X / Z) ** power + ref_mask = (X_ref / Z) ** power + good_idx = ~bad_idx + mask[good_idx] /= mask[good_idx] + ref_mask[good_idx] + # Wherever energy is below energy in both inputs, split the mask + if split_zeros: + mask[bad_idx] = 0.5 + else: + mask[bad_idx] = 0.0 + else: + # Otherwise, compute the hard mask + mask = X > X_ref + + return mask + + +def tiny(x: Union[float, np.ndarray]) -> _FloatLike_co: + """Compute the tiny-value corresponding to an input's data type. + + This is the smallest "usable" number representable in ``x.dtype`` + (e.g., float32). + + This is primarily useful for determining a threshold for + numerical underflow in division or multiplication operations. + + Parameters + ---------- + x : number or np.ndarray + The array to compute the tiny-value for. + All that matters here is ``x.dtype`` + + Returns + ------- + tiny_value : float + The smallest positive usable number for the type of ``x``. + If ``x`` is integer-typed, then the tiny value for ``np.float32`` + is returned instead. + + See Also + -------- + numpy.finfo + + Examples + -------- + For a standard double-precision floating point number: + + >>> librosa.util.tiny(1.0) + 2.2250738585072014e-308 + + Or explicitly as double-precision + + >>> librosa.util.tiny(np.asarray(1e-5, dtype=np.float64)) + 2.2250738585072014e-308 + + Or complex numbers + + >>> librosa.util.tiny(1j) + 2.2250738585072014e-308 + + Single-precision floating point: + + >>> librosa.util.tiny(np.asarray(1e-5, dtype=np.float32)) + 1.1754944e-38 + + Integer + + >>> librosa.util.tiny(5) + 1.1754944e-38 + """ + # Make sure we have an array view + x = np.asarray(x) + + # Only floating types generate a tiny + if np.issubdtype(x.dtype, np.floating) or np.issubdtype( + x.dtype, np.complexfloating + ): + dtype = x.dtype + else: + dtype = np.dtype(np.float32) + + return np.finfo(dtype).tiny + + +def fill_off_diagonal(x: np.ndarray, *, radius: float, value: float = 0) -> None: + """Set all cells of a matrix to a given ``value`` + if they lie outside a constraint region. + + In this case, the constraint region is the + Sakoe-Chiba band which runs with a fixed ``radius`` + along the main diagonal. + + When ``x.shape[0] != x.shape[1]``, the radius will be + expanded so that ``x[-1, -1] = 1`` always. + + ``x`` will be modified in place. + + Parameters + ---------- + x : np.ndarray [shape=(N, M)] + Input matrix, will be modified in place. + radius : float + The band radius (1/2 of the width) will be + ``int(radius*min(x.shape))`` + value : float + ``x[n, m] = value`` when ``(n, m)`` lies outside the band. + + Examples + -------- + >>> x = np.ones((8, 8)) + >>> librosa.util.fill_off_diagonal(x, radius=0.25) + >>> x + array([[1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1]]) + >>> x = np.ones((8, 12)) + >>> librosa.util.fill_off_diagonal(x, radius=0.25) + >>> x + array([[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]]) + """ + nx, ny = x.shape + + # Calculate the radius in indices, rather than proportion + radius = int(np.round(radius * np.min(x.shape))) + + nx, ny = x.shape + offset = np.abs((x.shape[0] - x.shape[1])) + + if nx < ny: + idx_u = np.triu_indices_from(x, k=radius + offset) + idx_l = np.tril_indices_from(x, k=-radius) + else: + idx_u = np.triu_indices_from(x, k=radius) + idx_l = np.tril_indices_from(x, k=-radius - offset) + + # modify input matrix + x[idx_u] = value + x[idx_l] = value + + +def cyclic_gradient( + data: np.ndarray, *, edge_order: Literal[1, 2] = 1, axis: int = -1 +) -> np.ndarray: + """Estimate the gradient of a function over a uniformly sampled, + periodic domain. + + This is essentially the same as `np.gradient`, except that edge effects + are handled by wrapping the observations (i.e. assuming periodicity) + rather than extrapolation. + + Parameters + ---------- + data : np.ndarray + The function values observed at uniformly spaced positions on + a periodic domain + edge_order : {1, 2} + The order of the difference approximation used for estimating + the gradient + axis : int + The axis along which gradients are calculated. + + Returns + ------- + grad : np.ndarray like ``data`` + The gradient of ``data`` taken along the specified axis. + + See Also + -------- + numpy.gradient + + Examples + -------- + This example estimates the gradient of cosine (-sine) from 64 + samples using direct (aperiodic) and periodic gradient + calculation. + + >>> import matplotlib.pyplot as plt + >>> x = 2 * np.pi * np.linspace(0, 1, num=64, endpoint=False) + >>> y = np.cos(x) + >>> grad = np.gradient(y) + >>> cyclic_grad = librosa.util.cyclic_gradient(y) + >>> true_grad = -np.sin(x) * 2 * np.pi / len(x) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, true_grad, label='True gradient', linewidth=5, + ... alpha=0.35) + >>> ax.plot(x, cyclic_grad, label='cyclic_gradient') + >>> ax.plot(x, grad, label='np.gradient', linestyle=':') + >>> ax.legend() + >>> # Zoom into the first part of the sequence + >>> ax.set(xlim=[0, np.pi/16], ylim=[-0.025, 0.025]) + """ + # Wrap-pad the data along the target axis by `edge_order` on each side + padding = [(0, 0)] * data.ndim + padding[axis] = (edge_order, edge_order) + data_pad = np.pad(data, padding, mode="wrap") + + # Compute the gradient + grad = np.gradient(data_pad, edge_order=edge_order, axis=axis) + + # Remove the padding + slices = [slice(None)] * data.ndim + slices[axis] = slice(edge_order, -edge_order) + grad_slice: np.ndarray = grad[tuple(slices)] + return grad_slice + + +@numba.jit(nopython=True, cache=True) # type: ignore +def __shear_dense(X: np.ndarray, *, factor: int = +1, axis: int = -1) -> np.ndarray: + """Numba-accelerated shear for dense (ndarray) arrays""" + if axis == 0: + X = X.T + + X_shear = np.empty_like(X) + + for i in range(X.shape[1]): + X_shear[:, i] = np.roll(X[:, i], factor * i) + + if axis == 0: + X_shear = X_shear.T + + return X_shear + + +def __shear_sparse( + X: scipy.sparse.spmatrix, *, factor: int = +1, axis: int = -1 +) -> scipy.sparse.spmatrix: + """Fast shearing for sparse matrices + + Shearing is performed using CSC array indices, + and the result is converted back to whatever sparse format + the data was originally provided in. + """ + fmt = X.format + if axis == 0: + X = X.T + + # Now we're definitely rolling on the correct axis + X_shear = X.tocsc(copy=True) + + # The idea here is to repeat the shear amount (factor * range) + # by the number of non-zeros for each column. + # The number of non-zeros is computed by diffing the index pointer array + roll = np.repeat(factor * np.arange(X_shear.shape[1]), np.diff(X_shear.indptr)) + + # In-place roll + np.mod(X_shear.indices + roll, X_shear.shape[0], out=X_shear.indices) + + if axis == 0: + X_shear = X_shear.T + + # And convert back to the input format + return X_shear.asformat(fmt) + + +_ArrayOrSparseMatrix = TypeVar( + "_ArrayOrSparseMatrix", bound=Union[np.ndarray, scipy.sparse.spmatrix] +) + + +@overload +def shear(X: np.ndarray, *, factor: int = ..., axis: int = ...) -> np.ndarray: + ... + + +@overload +def shear( + X: scipy.sparse.spmatrix, *, factor: int = ..., axis: int = ... +) -> scipy.sparse.spmatrix: + ... + + +def shear( + X: _ArrayOrSparseMatrix, *, factor: int = 1, axis: int = -1 +) -> _ArrayOrSparseMatrix: + """Shear a matrix by a given factor. + + The column ``X[:, n]`` will be displaced (rolled) + by ``factor * n`` + + This is primarily useful for converting between lag and recurrence + representations: shearing with ``factor=-1`` converts the main diagonal + to a horizontal. Shearing with ``factor=1`` converts a horizontal to + a diagonal. + + Parameters + ---------- + X : np.ndarray [ndim=2] or scipy.sparse matrix + The array to be sheared + factor : integer + The shear factor: ``X[:, n] -> np.roll(X[:, n], factor * n)`` + axis : integer + The axis along which to shear + + Returns + ------- + X_shear : same type as ``X`` + The sheared matrix + + Examples + -------- + >>> E = np.eye(3) + >>> librosa.util.shear(E, factor=-1, axis=-1) + array([[1., 1., 1.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> librosa.util.shear(E, factor=-1, axis=0) + array([[1., 0., 0.], + [1., 0., 0.], + [1., 0., 0.]]) + >>> librosa.util.shear(E, factor=1, axis=-1) + array([[1., 0., 0.], + [0., 0., 1.], + [0., 1., 0.]]) + """ + if not np.issubdtype(type(factor), np.integer): + raise ParameterError(f"factor={factor} must be integer-valued") + + # Suppress type checks because mypy doesn't like numba jitting + # or scipy sparse conversion + if scipy.sparse.isspmatrix(X): + return __shear_sparse(X, factor=factor, axis=axis) # type: ignore + else: + return __shear_dense(X, factor=factor, axis=axis) # type: ignore + + +def stack(arrays: List[np.ndarray], *, axis: int = 0) -> np.ndarray: + """Stack one or more arrays along a target axis. + + This function is similar to `np.stack`, except that memory contiguity is + retained when stacking along the first dimension. + + This is useful when combining multiple monophonic audio signals into a + multi-channel signal, or when stacking multiple feature representations + to form a multi-dimensional array. + + Parameters + ---------- + arrays : list + one or more `np.ndarray` + axis : integer + The target axis along which to stack. ``axis=0`` creates a new first axis, + and ``axis=-1`` creates a new last axis. + + Returns + ------- + arr_stack : np.ndarray [shape=(len(arrays), array_shape) or shape=(array_shape, len(arrays))] + The input arrays, stacked along the target dimension. + + If ``axis=0``, then ``arr_stack`` will be F-contiguous. + Otherwise, ``arr_stack`` will be C-contiguous by default, as computed by + `np.stack`. + + Raises + ------ + ParameterError + - If ``arrays`` do not all have the same shape + - If no ``arrays`` are given + + See Also + -------- + numpy.stack + numpy.ndarray.flags + frame + + Examples + -------- + Combine two buffers into a contiguous arrays + + >>> y_left = np.ones(5) + >>> y_right = -np.ones(5) + >>> y_stereo = librosa.util.stack([y_left, y_right], axis=0) + >>> y_stereo + array([[ 1., 1., 1., 1., 1.], + [-1., -1., -1., -1., -1.]]) + >>> y_stereo.flags + C_CONTIGUOUS : False + F_CONTIGUOUS : True + OWNDATA : True + WRITEABLE : True + ALIGNED : True + WRITEBACKIFCOPY : False + UPDATEIFCOPY : False + + Or along the trailing axis + + >>> y_stereo = librosa.util.stack([y_left, y_right], axis=-1) + >>> y_stereo + array([[ 1., -1.], + [ 1., -1.], + [ 1., -1.], + [ 1., -1.], + [ 1., -1.]]) + >>> y_stereo.flags + C_CONTIGUOUS : True + F_CONTIGUOUS : False + OWNDATA : True + WRITEABLE : True + ALIGNED : True + WRITEBACKIFCOPY : False + UPDATEIFCOPY : False + """ + shapes = {arr.shape for arr in arrays} + if len(shapes) > 1: + raise ParameterError("all input arrays must have the same shape") + elif len(shapes) < 1: + raise ParameterError("at least one input array must be provided for stack") + + shape_in = shapes.pop() + + if axis != 0: + return np.stack(arrays, axis=axis) + else: + # If axis is 0, enforce F-ordering + shape = tuple([len(arrays)] + list(shape_in)) + + # Find the common dtype for all inputs + dtype = np.result_type(*arrays) + + # Allocate an empty array of the right shape and type + result = np.empty(shape, dtype=dtype, order="F") + + # Stack into the preallocated buffer + np.stack(arrays, axis=axis, out=result) + + return result + + +def dtype_r2c(d: DTypeLike, *, default: Optional[type] = np.complex64) -> DTypeLike: + """Find the complex numpy dtype corresponding to a real dtype. + + This is used to maintain numerical precision and memory footprint + when constructing complex arrays from real-valued data + (e.g. in a Fourier transform). + + A `float32` (single-precision) type maps to `complex64`, + while a `float64` (double-precision) maps to `complex128`. + + Parameters + ---------- + d : np.dtype + The real-valued dtype to convert to complex. + If ``d`` is a complex type already, it will be returned. + default : np.dtype, optional + The default complex target type, if ``d`` does not match a + known dtype + + Returns + ------- + d_c : np.dtype + The complex dtype + + See Also + -------- + dtype_c2r + numpy.dtype + + Examples + -------- + >>> librosa.util.dtype_r2c(np.float32) + dtype('complex64') + + >>> librosa.util.dtype_r2c(np.int16) + dtype('complex64') + + >>> librosa.util.dtype_r2c(np.complex128) + dtype('complex128') + """ + mapping: Dict[DTypeLike, type] = { + np.dtype(np.float32): np.complex64, + np.dtype(np.float64): np.complex128, + np.dtype(float): np.dtype(complex).type, + } + + # If we're given a complex type already, return it + dt = np.dtype(d) + if dt.kind == "c": + return dt + + # Otherwise, try to map the dtype. + # If no match is found, return the default. + return np.dtype(mapping.get(dt, default)) + + +def dtype_c2r(d: DTypeLike, *, default: Optional[type] = np.float32) -> DTypeLike: + """Find the real numpy dtype corresponding to a complex dtype. + + This is used to maintain numerical precision and memory footprint + when constructing real arrays from complex-valued data + (e.g. in an inverse Fourier transform). + + A `complex64` (single-precision) type maps to `float32`, + while a `complex128` (double-precision) maps to `float64`. + + Parameters + ---------- + d : np.dtype + The complex-valued dtype to convert to real. + If ``d`` is a real (float) type already, it will be returned. + default : np.dtype, optional + The default real target type, if ``d`` does not match a + known dtype + + Returns + ------- + d_r : np.dtype + The real dtype + + See Also + -------- + dtype_r2c + numpy.dtype + + Examples + -------- + >>> librosa.util.dtype_r2c(np.complex64) + dtype('float32') + + >>> librosa.util.dtype_r2c(np.float32) + dtype('float32') + + >>> librosa.util.dtype_r2c(np.int16) + dtype('float32') + + >>> librosa.util.dtype_r2c(np.complex128) + dtype('float64') + """ + mapping: Dict[DTypeLike, type] = { + np.dtype(np.complex64): np.float32, + np.dtype(np.complex128): np.float64, + np.dtype(complex): np.dtype(float).type, + } + + # If we're given a real type already, return it + dt = np.dtype(d) + if dt.kind == "f": + return dt + + # Otherwise, try to map the dtype. + # If no match is found, return the default. + return np.dtype(mapping.get(dt, default)) + + +@numba.jit(nopython=True, cache=True) +def __count_unique(x): + """Count the number of unique values in an array. + + This function is a helper for `count_unique` and is not + to be called directly. + """ + uniques = np.unique(x) + return uniques.shape[0] + + +def count_unique(data: np.ndarray, *, axis: int = -1) -> np.ndarray: + """Count the number of unique values in a multi-dimensional array + along a given axis. + + Parameters + ---------- + data : np.ndarray + The input array + axis : int + The target axis to count + + Returns + ------- + n_uniques + The number of unique values. + This array will have one fewer dimension than the input. + + See Also + -------- + is_unique + + Examples + -------- + >>> x = np.vander(np.arange(5)) + >>> x + array([[ 0, 0, 0, 0, 1], + [ 1, 1, 1, 1, 1], + [ 16, 8, 4, 2, 1], + [ 81, 27, 9, 3, 1], + [256, 64, 16, 4, 1]]) + >>> # Count unique values along rows (within columns) + >>> librosa.util.count_unique(x, axis=0) + array([5, 5, 5, 5, 1]) + >>> # Count unique values along columns (within rows) + >>> librosa.util.count_unique(x, axis=-1) + array([2, 1, 5, 5, 5]) + """ + return np.apply_along_axis(__count_unique, axis, data) + + +@numba.jit(nopython=True, cache=True) +def __is_unique(x): + """Determine if the input array has all unique values. + + This function is a helper for `is_unique` and is not + to be called directly. + """ + uniques = np.unique(x) + return uniques.shape[0] == x.size + + +def is_unique(data: np.ndarray, *, axis: int = -1) -> np.ndarray: + """Determine if the input array consists of all unique values + along a given axis. + + Parameters + ---------- + data : np.ndarray + The input array + axis : int + The target axis + + Returns + ------- + is_unique + Array of booleans indicating whether the data is unique along the chosen + axis. + This array will have one fewer dimension than the input. + + See Also + -------- + count_unique + + Examples + -------- + >>> x = np.vander(np.arange(5)) + >>> x + array([[ 0, 0, 0, 0, 1], + [ 1, 1, 1, 1, 1], + [ 16, 8, 4, 2, 1], + [ 81, 27, 9, 3, 1], + [256, 64, 16, 4, 1]]) + >>> # Check uniqueness along rows + >>> librosa.util.is_unique(x, axis=0) + array([ True, True, True, True, False]) + >>> # Check uniqueness along columns + >>> librosa.util.is_unique(x, axis=-1) + array([False, False, True, True, True]) + """ + return np.apply_along_axis(__is_unique, axis, data) + + +@numba.vectorize( + ["float32(complex64)", "float64(complex128)"], nopython=True, cache=True, identity=0 +) # type: ignore +def _cabs2(x: _ComplexLike_co) -> _FloatLike_co: # pragma: no cover + """Efficiently compute abs2 on complex inputs""" + return x.real**2 + x.imag**2 + + +_Number = Union[complex, "np.number[Any]"] +_NumberOrArray = TypeVar("_NumberOrArray", bound=Union[_Number, np.ndarray]) + + +def abs2(x: _NumberOrArray, dtype: Optional[DTypeLike] = None) -> _NumberOrArray: + """Compute the squared magnitude of a real or complex array. + + This function is equivalent to calling `np.abs(x)**2` but it + is slightly more efficient. + + Parameters + ---------- + x : np.ndarray or scalar, real or complex typed + The input data, either real (float32, float64) or complex (complex64, complex128) typed + dtype : np.dtype, optional + The data type of the output array. + If not provided, it will be inferred from `x` + + Returns + ------- + p : np.ndarray or scale, real + squared magnitude of `x` + + Examples + -------- + >>> librosa.util.abs2(3 + 4j) + 25.0 + + >>> librosa.util.abs2((0.5j)**np.arange(8)) + array([1.000e+00, 2.500e-01, 6.250e-02, 1.562e-02, 3.906e-03, 9.766e-04, + 2.441e-04, 6.104e-05]) + """ + if np.iscomplexobj(x): + # suppress type check, mypy doesn't like vectorization + y = _cabs2(x) + if dtype is None: + return y # type: ignore + else: + return y.astype(dtype) # type: ignore + else: + # suppress type check, mypy doesn't know this is real + return np.square(x, dtype=dtype) # type: ignore + + +@numba.vectorize( + ["complex64(float32)", "complex128(float64)"], nopython=True, cache=True, identity=1 +) # type: ignore +def _phasor_angles(x) -> np.complexfloating[Any, Any]: + return np.cos(x) + 1j * np.sin(x) # type: ignore + + +_Real = Union[float, "np.integer[Any]", "np.floating[Any]"] + + +@overload +def phasor(angles: np.ndarray, *, mag: Optional[np.ndarray] = ...) -> np.ndarray: + ... + + +@overload +def phasor(angles: _Real, *, mag: Optional[_Number] = ...) -> np.complexfloating[Any, Any]: + ... + + +def phasor( + angles: Union[np.ndarray, _Real], + *, + mag: Optional[Union[np.ndarray, _Number]] = None, +) -> Union[np.ndarray, np.complexfloating[Any, Any]]: + """Construct a complex phasor representation from angles. + + When `mag` is not provided, this is equivalent to: + + z = np.cos(angles) + 1j * np.sin(angles) + + or by Euler's formula: + + z = np.exp(1j * angles) + + When `mag` is provided, this is equivalent to: + + z = mag * np.exp(1j * angles) + + This function should be more efficient (in time and memory) than the equivalent' + formulations above, but produce numerically identical results. + + Parameters + ---------- + angles : np.ndarray or scalar, real-valued + Angle(s), measured in radians + + mag : np.ndarray or scalar, optional + If provided, phasor(s) will be scaled by `mag`. + + If not provided (default), phasors will have unit magnitude. + + `mag` must be of compatible shape to multiply with `angles`. + + Returns + ------- + z : np.ndarray or scalar, complex-valued + Complex number(s) z corresponding to the given angle(s) + and optional magnitude(s). + + Examples + -------- + Construct unit phasors at angles 0, pi/2, and pi: + + >>> librosa.util.phasor([0, np.pi/2, np.pi]) + array([ 1.000e+00+0.000e+00j, 6.123e-17+1.000e+00j, + -1.000e+00+1.225e-16j]) + + Construct a phasor with magnitude 1/2: + + >>> librosa.util.phasor(np.pi/2, mag=0.5) + (3.061616997868383e-17+0.5j) + + Or arrays of angles and magnitudes: + + >>> librosa.util.phasor(np.array([0, np.pi/2]), mag=np.array([0.5, 1.5])) + array([5.000e-01+0.j , 9.185e-17+1.5j]) + """ + z = _phasor_angles(angles) + + if mag is not None: + z *= mag + + return z # type: ignore diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6407e2614184d8b1c085576247b4151f9bbb4448 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/recipes.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/recipes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26409cdd4e95413ab7a6b5029a4428ea8fff818a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/more_itertools/__pycache__/recipes.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff54a4d6820fae84f4bda25d4cd577c1389fea8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/__init__.py @@ -0,0 +1,23 @@ +""" +Utilities for getting information about Numba C extensions +""" + +import os + + +def get_extension_libs(): + """Return the .c files in the `numba.cext` directory. + """ + libs = [] + base = get_path() + for fn in os.listdir(base): + if fn.endswith('.c'): + fn = os.path.join(base, fn) + libs.append(fn) + return libs + + +def get_path(): + """Returns the path to the directory for `numba.cext`. + """ + return os.path.abspath(os.path.join(os.path.dirname(__file__))) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/cext.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/cext.h new file mode 100644 index 0000000000000000000000000000000000000000..aa2b7eb26b979c353090a9f0f5fef641f9cde970 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/cext.h @@ -0,0 +1,21 @@ +#ifndef NUMBA_EXTENSION_HELPER_H_ +#define NUMBA_EXTENSION_HELPER_H_ + +#include "Python.h" +#include "../_numba_common.h" + +/* Define all runtime-required symbols in this C module, but do not + export them outside the shared library if possible. */ +#define NUMBA_EXPORT_FUNC(_rettype) VISIBILITY_HIDDEN _rettype +#define NUMBA_EXPORT_DATA(_vartype) VISIBILITY_HIDDEN _vartype + +/* Use to declare a symbol as exported (global). */ +#define NUMBA_GLOBAL_FUNC(_rettype) VISIBILITY_GLOBAL _rettype + +NUMBA_EXPORT_FUNC(Py_ssize_t) +aligned_size(Py_ssize_t sz); + +#include "dictobject.h" +#include "listobject.h" + +#endif // end NUMBA_EXTENSION_HELPER_H_ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.c b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.c new file mode 100644 index 0000000000000000000000000000000000000000..3557757ba577235d02cbedbf371cf7fedbff4cc4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.c @@ -0,0 +1,1265 @@ +/* The following is adapted from CPython3.7. +The exact commit is: + +- https://github.com/python/cpython/blob/44467e8ea4cea390b0718702291b4cfe8ddd67ed/Objects/dictobject.c + + +*/ + +/* Dictionary object implementation using a hash table */ + +/* The distribution includes a separate file, Objects/dictnotes.txt, + describing explorations into dictionary design and optimization. + It covers typical dictionary use patterns, the parameters for + tuning dictionaries, and several ideas for possible optimizations. +*/ + +/* PyDictKeysObject + +This implements the dictionary's hashtable. + +As of Python 3.6, this is compact and ordered. Basic idea is described here: +* https://mail.python.org/pipermail/python-dev/2012-December/123028.html +* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html + +layout: + ++---------------+ +| dk_refcnt | +| dk_size | +| dk_lookup | +| dk_usable | +| dk_nentries | ++---------------+ +| dk_indices | +| | ++---------------+ +| dk_entries | +| | ++---------------+ + +dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1) +or DKIX_DUMMY(-2). +Size of indices is dk_size. Type of each index in indices is vary on dk_size: + +* int8 for dk_size <= 128 +* int16 for 256 <= dk_size <= 2**15 +* int32 for 2**16 <= dk_size <= 2**31 +* int64 for 2**32 <= dk_size + +dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size). +DK_ENTRIES(dk) can be used to get pointer to entries. + +NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of +dk_indices entry is signed integer and int16 is used for table which +dk_size == 256. +*/ + + +/* +The DictObject can be in one of two forms. + +Either: + A combined table: + ma_values == NULL, dk_refcnt == 1. + Values are stored in the me_value field of the PyDictKeysObject. +Or: + + (Numba dev notes: split table logic is removed) + + A split table: + ma_values != NULL, dk_refcnt >= 1 + Values are stored in the ma_values array. + Only string (unicode) keys are allowed. + All dicts sharing same key must have same insertion order. + +There are four kinds of slots in the table (slot is index, and +DK_ENTRIES(keys)[index] if index >= 0): + +1. Unused. index == DKIX_EMPTY + Does not hold an active (key, value) pair now and never did. Unused can + transition to Active upon key insertion. This is each slot's initial state. + +2. Active. index >= 0, me_key != NULL and me_value != NULL + Holds an active (key, value) pair. Active can transition to Dummy or + Pending upon key deletion (for combined and split tables respectively). + This is the only case in which me_value != NULL. + +3. Dummy. index == DKIX_DUMMY (combined only) + Previously held an active (key, value) pair, but that was deleted and an + active pair has not yet overwritten the slot. Dummy can transition to + Active upon key insertion. Dummy slots cannot be made Unused again + else the probe sequence in case of collision would have no way to know + they were once active. + +4. Pending. index >= 0, key != NULL, and value == NULL (split only) + Not yet inserted in split-table. +*/ + +/* +Preserving insertion order + +It's simple for combined table. Since dk_entries is mostly append only, we can +get insertion order by just iterating dk_entries. + +One exception is .popitem(). It removes last item in dk_entries and decrement +dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in +dk_indices, we can't increment dk_usable even though dk_nentries is +decremented. + +In split table, inserting into pending entry is allowed only for dk_entries[ix] +where ix == mp->ma_used. Inserting into other index and deleting item cause +converting the dict to the combined table. +*/ + + +/* D_MINSIZE (adapted from PyDict_MINSIZE) + * is the starting size for any new dict. + * 8 allows dicts with no more than 5 active entries; experiments suggested + * this suffices for the majority of dicts (consisting mostly of usually-small + * dicts created to pass keyword arguments). + * Making this 8, rather than 4 reduces the number of resizes for most + * dictionaries, without any significant extra memory use. + */ +#define D_MINSIZE 8 + +#include "dictobject.h" + + +#if defined(_MSC_VER) +# if _MSC_VER <= 1900 /* Visual Studio 2014 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; +# endif + /* Use _alloca() to dynamically allocate on the stack on MSVC */ + #define STACK_ALLOC(Type, Name, Size) Type * const Name = _alloca(Size); +#else + #define STACK_ALLOC(Type, Name, Size) Type Name[Size]; +#endif + + +/*[clinic input] +class dict "PyDictObject *" "&PyDict_Type" +[clinic start generated code]*/ +/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/ + + +/* +To ensure the lookup algorithm terminates, there must be at least one Unused +slot (NULL key) in the table. +To avoid slowing down lookups on a near-full table, we resize the table when +it's USABLE_FRACTION (currently two-thirds) full. +*/ + +#define PERTURB_SHIFT 5 + +/* +Major subtleties ahead: Most hash schemes depend on having a "good" hash +function, in the sense of simulating randomness. Python doesn't: its most +important hash functions (for ints) are very regular in common +cases: + + >>>[hash(i) for i in range(4)] + [0, 1, 2, 3] + +This isn't necessarily bad! To the contrary, in a table of size 2**i, taking +the low-order i bits as the initial table index is extremely fast, and there +are no collisions at all for dicts indexed by a contiguous range of ints. So +this gives better-than-random behavior in common cases, and that's very +desirable. + +OTOH, when collisions occur, the tendency to fill contiguous slices of the +hash table makes a good collision resolution strategy crucial. Taking only +the last i bits of the hash code is also vulnerable: for example, consider +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +their own hash codes, and this fits in a dict of size 2**15, the last 15 bits + of every hash code are all 0: they *all* map to the same table index. + +But catering to unusual cases should not slow the usual ones, so we just take +the last i bits anyway. It's up to collision resolution to do the rest. If +we *usually* find the key we're looking for on the first try (and, it turns +out, we usually do -- the table load factor is kept under 2/3, so the odds +are solidly in our favor), then it makes best sense to keep the initial index +computation dirt cheap. + +The first half of collision resolution is to visit table indices via this +recurrence: + + j = ((5*j) + 1) mod 2**i + +For any initial j in range(2**i), repeating that 2**i times generates each +int in range(2**i) exactly once (see any text on random-number generation for +proof). By itself, this doesn't help much: like linear probing (setting +j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed +order. This would be bad, except that's not the only thing we do, and it's +actually *good* in the common cases where hash keys are consecutive. In an +example that's really too small to make this entirely clear, for a table of +size 2**3 the order of indices is: + + 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating] + +If two things come in at index 5, the first place we look after is index 2, +not 6, so if another comes in at index 6 the collision at 5 didn't hurt it. +Linear probing is deadly in this case because there the fixed probe order +is the *same* as the order consecutive keys are likely to arrive. But it's +extremely unlikely hash codes will follow a 5*j+1 recurrence by accident, +and certain that consecutive hash codes do not. + +The other half of the strategy is to get the other bits of the hash code +into play. This is done by initializing a (unsigned) vrbl "perturb" to the +full hash code, and changing the recurrence to: + + perturb >>= PERTURB_SHIFT; + j = (5*j) + 1 + perturb; + use j % 2**i as the next table index; + +Now the probe sequence depends (eventually) on every bit in the hash code, +and the pseudo-scrambling property of recurring on 5*j+1 is more valuable, +because it quickly magnifies small differences in the bits that didn't affect +the initial index. Note that because perturb is unsigned, if the recurrence +is executed often enough perturb eventually becomes and remains 0. At that +point (very rarely reached) the recurrence is on (just) 5*j+1 again, and +that's certain to find an empty slot eventually (since it generates every int +in range(2**i), and we make sure there's always at least one empty slot). + +Selecting a good value for PERTURB_SHIFT is a balancing act. You want it +small so that the high bits of the hash code continue to affect the probe +sequence across iterations; but you want it large so that in really bad cases +the high-order hash bits have an effect on early iterations. 5 was "the +best" in minimizing total collisions across experiments Tim Peters ran (on +both normal and pathological cases), but 4 and 6 weren't significantly worse. + +Historical: Reimer Behrends contributed the idea of using a polynomial-based +approach, using repeated multiplication by x in GF(2**n) where an irreducible +polynomial for each table size was chosen such that x was a primitive root. +Christian Tismer later extended that to use division by x instead, as an +efficient way to get the high bits of the hash code into play. This scheme +also gave excellent collision statistics, but was more expensive: two +if-tests were required inside the loop; computing "the next" index took about +the same number of operations but without as much potential parallelism +(e.g., computing 5*j can go on at the same time as computing 1+perturb in the +above, and then shifting perturb can be done while the table index is being +masked); and the PyDictObject struct required a member to hold the table's +polynomial. In Tim's experiments the current scheme ran faster, produced +equally good collision statistics, needed less code & used less memory. + +*/ + +#define DKIX_EMPTY (-1) +#define DKIX_DUMMY (-2) /* Used internally */ +#define DKIX_ERROR (-3) + +typedef enum { + OK = 0, + OK_REPLACED = 1, + ERR_NO_MEMORY = -1, + ERR_DICT_MUTATED = -2, + ERR_ITER_EXHAUSTED = -3, + ERR_DICT_EMPTY = -4, + ERR_CMP_FAILED = -5, +} Status; + + +#ifndef NDEBUG +static +int mem_cmp_zeros(void *obj, size_t n){ + int diff = 0; + char *mem = obj; + char *it; + for (it = mem; it < mem + n; ++it) { + if (*it != 0) diff += 1; + } + return diff; +} +#endif + +#define D_MASK(dk) ((dk)->size-1) +#define D_GROWTH_RATE(d) ((d)->used*3) + +static int +ix_size(Py_ssize_t size) { + if ( size < 0xff ) return 1; + if ( size < 0xffff ) return 2; + if ( size < 0xffffffff ) return 4; + return sizeof(int64_t); +} + +#ifndef NDEBUG +/* NOTE: This function is only used in assert()s */ +/* Align pointer *ptr* to pointer size */ +static void* +aligned_pointer(void *ptr) { + return (void*)aligned_size((size_t)ptr); +} +#endif + +/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */ +static Py_ssize_t +get_index(NB_DictKeys *dk, Py_ssize_t i) +{ + Py_ssize_t s = dk->size; + Py_ssize_t ix; + + if (s <= 0xff) { + int8_t *indices = (int8_t*)(dk->indices); + assert (i < dk->size); + ix = indices[i]; + } + else if (s <= 0xffff) { + int16_t *indices = (int16_t*)(dk->indices); + ix = indices[i]; + } +#if SIZEOF_VOID_P > 4 + else if (s > 0xffffffff) { + int64_t *indices = (int64_t*)(dk->indices); + ix = indices[i]; + } +#endif + else { + int32_t *indices = (int32_t*)(dk->indices); + ix = indices[i]; + } + assert(ix >= DKIX_DUMMY); + return ix; +} + +/* write to indices. */ +static void +set_index(NB_DictKeys *dk, Py_ssize_t i, Py_ssize_t ix) +{ + Py_ssize_t s = dk->size; + + assert(ix >= DKIX_DUMMY); + + if (s <= 0xff) { + int8_t *indices = (int8_t*)(dk->indices); + assert(ix <= 0x7f); + indices[i] = (char)ix; + } + else if (s <= 0xffff) { + int16_t *indices = (int16_t*)(dk->indices); + assert(ix <= 0x7fff); + indices[i] = (int16_t)ix; + } +#if SIZEOF_VOID_P > 4 + else if (s > 0xffffffff) { + int64_t *indices = (int64_t*)(dk->indices); + indices[i] = ix; + } +#endif + else { + int32_t *indices = (int32_t*)(dk->indices); + assert(ix <= 0x7fffffff); + indices[i] = (int32_t)ix; + } +} + + +/* USABLE_FRACTION is the maximum dictionary load. + * Increasing this ratio makes dictionaries more dense resulting in more + * collisions. Decreasing it improves sparseness at the expense of spreading + * indices over more cache lines and at the cost of total memory consumed. + * + * USABLE_FRACTION must obey the following: + * (0 < USABLE_FRACTION(n) < n) for all n >= 2 + * + * USABLE_FRACTION should be quick to calculate. + * Fractions around 1/2 to 2/3 seem to work well in practice. + */ + +#define USABLE_FRACTION(n) (((n) << 1)/3) // ratio: 2/3 + +/* Alternative fraction that is otherwise close enough to 2n/3 to make + * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10. + * 32 * 2/3 = 21, 32 * 5/8 = 20. + * Its advantage is that it is faster to compute on machines with slow division. + * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3)) // ratio: 5/8 + */ + + +/* INV_USABLE_FRACTION gives the inverse of USABLE_FRACTION. + * Used for sizing a new dictionary to a specified number of keys. + * + * NOTE: If the denominator of the USABLE_FRACTION ratio is not a power + * of 2, must add 1 to the result of the inverse for correct sizing. + * + * For example, when USABLE_FRACTION ratio = 5/8 (8 is a power of 2): + * #define INV_USABLE_FRACTION(n) (((n) << 3)/5) // inv_ratio: 8/5 + * + * When USABLE_FRACTION ratio = 5/7 (7 is not a power of 2): + * #define INV_USABLE_FRACTION(n) ((7*(n))/5 + 1) // inv_ratio: 7/5 + */ + +#define INV_USABLE_FRACTION(n) ((n) + ((n) >> 1) + 1) // inv_ratio: 3/2 + + +/* GROWTH_RATE. Growth rate upon hitting maximum load. + * Currently set to used*3. + * This means that dicts double in size when growing without deletions, + * but have more head room when the number of deletions is on a par with the + * number of insertions. See also bpo-17563 and bpo-33205. + * + * GROWTH_RATE was set to used*4 up to version 3.2. + * GROWTH_RATE was set to used*2 in version 3.3.0 + * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0. + */ +#define GROWTH_RATE(d) ((d)->ma_used*3) + + +static NB_DictEntry* +get_entry(NB_DictKeys *dk, Py_ssize_t idx) { + Py_ssize_t offset; + char *ptr; + + assert (idx < dk->size); + offset = idx * dk->entry_size; + ptr = dk->indices + dk->entry_offset + offset; + return (NB_DictEntry*)ptr; +} + +static void +zero_key(NB_DictKeys *dk, char *data){ + memset(data, 0, dk->key_size); +} + +static void +zero_val(NB_DictKeys *dk, char *data){ + memset(data, 0, dk->val_size); +} + +static void +copy_key(NB_DictKeys *dk, char *dst, const char *src){ + memcpy(dst, src, dk->key_size); +} + +static void +copy_val(NB_DictKeys *dk, char *dst, const char *src){ + memcpy(dst, src, dk->val_size); +} + +/* Returns -1 for error; 0 for not equal; 1 for equal */ +static int +key_equal(NB_DictKeys *dk, const char *lhs, const char *rhs) { + if ( dk->methods.key_equal ) { + return dk->methods.key_equal(lhs, rhs); + } else { + return memcmp(lhs, rhs, dk->key_size) == 0; + } +} + +static char * +entry_get_key(NB_DictKeys *dk, NB_DictEntry* entry) { + char * out = entry->keyvalue; + assert (out == aligned_pointer(out)); + return out; +} + +static char * +entry_get_val(NB_DictKeys *dk, NB_DictEntry* entry) { + char * out = entry_get_key(dk, entry) + aligned_size(dk->key_size); + assert (out == aligned_pointer(out)); + return out; +} + +static void +dk_incref_key(NB_DictKeys *dk, const char *key) { + if ( dk->methods.key_incref ) { + dk->methods.key_incref(key); + } +} + +static void +dk_decref_key(NB_DictKeys *dk, const char *key) { + if ( dk->methods.key_decref ) { + dk->methods.key_decref(key); + } +} + +static void +dk_incref_val(NB_DictKeys *dk, const char *val) { + if ( dk->methods.value_incref ) { + dk->methods.value_incref(val); + } +} + +static void +dk_decref_val(NB_DictKeys *dk, const char *val) { + if ( dk->methods.value_decref ) { + dk->methods.value_decref(val); + } +} + + +void +numba_dictkeys_free(NB_DictKeys *dk) { + /* Clear all references from the entries */ + Py_ssize_t i; + NB_DictEntry *ep; + + for (i = 0; i < dk->nentries; i++) { + ep = get_entry(dk, i); + if (ep->hash != DKIX_EMPTY) { + dk_decref_key(dk, entry_get_key(dk, ep)); + dk_decref_val(dk, entry_get_val(dk, ep)); + } + } + /* Deallocate */ + free(dk); +} + +void +numba_dict_free(NB_Dict *d) { + numba_dictkeys_free(d->keys); + free(d); +} + +Py_ssize_t +numba_dict_length(NB_Dict *d) { + return d->used; +} + +/* Allocate new dictionary keys + +Adapted from CPython's new_keys_object(). +*/ +int +numba_dictkeys_new(NB_DictKeys **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size) { + Py_ssize_t usable = USABLE_FRACTION(size); + Py_ssize_t index_size = ix_size(size); + Py_ssize_t entry_size = aligned_size(sizeof(NB_DictEntry) + aligned_size(key_size) + aligned_size(val_size)); + Py_ssize_t entry_offset = aligned_size(index_size * size); + Py_ssize_t alloc_size = sizeof(NB_DictKeys) + entry_offset + entry_size * usable; + + NB_DictKeys *dk = malloc(aligned_size(alloc_size)); + if (!dk) return ERR_NO_MEMORY; + + assert ( size >= D_MINSIZE ); + + dk->size = size; + dk->usable = usable; + dk->nentries = 0; + dk->key_size = key_size; + dk->val_size = val_size; + dk->entry_offset = entry_offset; + dk->entry_size = entry_size; + + assert (aligned_pointer(dk->indices) == dk->indices ); + /* Ensure that the method table is all nulls */ + memset(&dk->methods, 0x00, sizeof(type_based_methods_table)); + /* Ensure hash is (-1) for empty entry */ + memset(dk->indices, 0xff, entry_offset + entry_size * usable); + + *out = dk; + return OK; +} + + +/* Allocate new dictionary */ +int +numba_dict_new(NB_Dict **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size) { + NB_DictKeys *dk; + NB_Dict *d; + int status = numba_dictkeys_new(&dk, size, key_size, val_size); + if (status != OK) return status; + + d = malloc(sizeof(NB_Dict)); + if (!d) { + numba_dictkeys_free(dk); + return ERR_NO_MEMORY; + } + + d->used = 0; + d->keys = dk; + *out = d; + return OK; +} + + +/* +Adapted from CPython lookdict_index(). + +Search index of hash table from offset of entry table +*/ +static Py_ssize_t +lookdict_index(NB_DictKeys *dk, Py_hash_t hash, Py_ssize_t index) +{ + size_t mask = D_MASK(dk); + size_t perturb = (size_t)hash; + size_t i = (size_t)hash & mask; + + for (;;) { + Py_ssize_t ix = get_index(dk, i); + if (ix == index) { + return i; + } + if (ix == DKIX_EMPTY) { + return DKIX_EMPTY; + } + perturb >>= PERTURB_SHIFT; + i = mask & (i*5 + perturb + 1); + } + assert(0 && "unreachable"); +} + +/* + +Adapted from the CPython3.7 lookdict(). + +The basic lookup function used by all operations. +This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. +Open addressing is preferred over chaining since the link overhead for +chaining would be substantial (100% with typical malloc overhead). + +The initial probe index is computed as hash mod the table size. Subsequent +probe indices are computed as explained earlier. + +All arithmetic on hash should ignore overflow. + +The details in this version are due to Tim Peters, building on many past +contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and +Christian Tismer. + +lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a +comparison raises an exception. +lookdict_unicode() below is specialized to string keys, comparison of which can +never raise an exception; that function can never return DKIX_ERROR when key +is string. Otherwise, it falls back to lookdict(). +lookdict_unicode_nodummy is further specialized for string keys that cannot be +the value. +For both, when the key isn't found a DKIX_EMPTY is returned. +*/ +Py_ssize_t +numba_dict_lookup(NB_Dict *d, const char *key_bytes, Py_hash_t hash, char *oldval_bytes) +{ + NB_DictKeys *dk = d->keys; + size_t mask = D_MASK(dk); + size_t perturb = hash; + size_t i = (size_t)hash & mask; + + for (;;) { + Py_ssize_t ix = get_index(dk, i); + if (ix == DKIX_EMPTY) { + zero_val(dk, oldval_bytes); + return ix; + } + if (ix >= 0) { + NB_DictEntry *ep = get_entry(dk, ix); + const char *startkey = NULL; + if (ep->hash == hash) { + int cmp; + + startkey = entry_get_key(dk, ep); + cmp = key_equal(dk, startkey, key_bytes); + if (cmp < 0) { + // error'ed in comparison + memset(oldval_bytes, 0, dk->val_size); + return DKIX_ERROR; + } + if (cmp > 0) { + // key is equal; retrieve the value. + copy_val(dk, oldval_bytes, entry_get_val(dk, ep)); + return ix; + } + } + } + perturb >>= PERTURB_SHIFT; + i = (i*5 + perturb + 1) & mask; + } + assert(0 && "unreachable"); +} + + +/* Internal function to find slot for an item from its hash + when it is known that the key is not present in the dict. + + The dict must be combined. */ +static Py_ssize_t +find_empty_slot(NB_DictKeys *dk, Py_hash_t hash){ + size_t mask; + size_t i; + Py_ssize_t ix; + size_t perturb; + + assert(dk != NULL); + + mask = D_MASK(dk); + i = hash & mask; + ix = get_index(dk, i); + for (perturb = hash; ix >= 0;) { + perturb >>= PERTURB_SHIFT; + i = (i*5 + perturb + 1) & mask; + ix = get_index(dk, i); + } + return i; +} + +static int +insertion_resize(NB_Dict *d) +{ + return numba_dict_resize(d, D_GROWTH_RATE(d)); +} + +int +numba_dict_insert( + NB_Dict *d, + const char *key_bytes, + Py_hash_t hash, + const char *val_bytes, + char *oldval_bytes + ) +{ + + NB_DictKeys *dk = d->keys; + + Py_ssize_t ix = numba_dict_lookup(d, key_bytes, hash, oldval_bytes); + if (ix == DKIX_ERROR) { + // exception in key comparison in lookup. + return ERR_CMP_FAILED; + } + + if (ix == DKIX_EMPTY) { + /* Insert into new slot */ + Py_ssize_t hashpos; + NB_DictEntry *ep; + + if (dk->usable <= 0) { + /* Need to resize */ + if (insertion_resize(d) != OK) + return ERR_NO_MEMORY; + else + dk = d->keys; // reload + } + hashpos = find_empty_slot(dk, hash); + ep = get_entry(dk, dk->nentries); + set_index(dk, hashpos, dk->nentries); + copy_key(dk, entry_get_key(dk, ep), key_bytes); + assert ( hash != -1 ); + ep->hash = hash; + copy_val(dk, entry_get_val(dk, ep), val_bytes); + + /* incref */ + dk_incref_key(dk, key_bytes); + dk_incref_val(dk, val_bytes); + + d->used += 1; + dk->usable -= 1; + dk->nentries += 1; + assert (dk->usable >= 0); + return OK; + } else { + /* Replace existing value in the slot at ix */ + /* decref old value */ + dk_decref_val(dk, oldval_bytes); + // Replace the previous value + copy_val(dk, entry_get_val(dk, get_entry(dk, ix)), val_bytes); + + /* incref */ + dk_incref_val(dk, val_bytes); + return OK_REPLACED; + } +} + +/* +Adapted from build_indices(). +Internal routine used by dictresize() to build a hashtable of entries. +*/ +void +build_indices(NB_DictKeys *keys, Py_ssize_t n) { + size_t mask = (size_t)D_MASK(keys); + Py_ssize_t ix; + for (ix = 0; ix != n; ix++) { + size_t perturb; + Py_hash_t hash = get_entry(keys, ix)->hash; + size_t i = hash & mask; + for (perturb = hash; get_index(keys, i) != DKIX_EMPTY;) { + perturb >>= PERTURB_SHIFT; + i = mask & (i*5 + perturb + 1); + } + set_index(keys, i, ix); + } +} + +/* + +Adapted from CPython dictresize(). + +Restructure the table by allocating a new table and reinserting all +items again. When entries have been deleted, the new table may +actually be smaller than the old one. +If a table is split (its keys and hashes are shared, its values are not), +then the values are temporarily copied into the table, it is resized as +a combined table, then the me_value slots in the old table are NULLed out. +After resizing a table is always combined, +but can be resplit by make_keys_shared(). +*/ +int +numba_dict_resize(NB_Dict *d, Py_ssize_t minsize) { + Py_ssize_t newsize, numentries; + NB_DictKeys *oldkeys; + int status; + + /* Find the smallest table size > minused. */ + for (newsize = D_MINSIZE; + newsize < minsize && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + return ERR_NO_MEMORY; + } + oldkeys = d->keys; + + /* NOTE: Current odict checks mp->ma_keys to detect resize happen. + * So we can't reuse oldkeys even if oldkeys->dk_size == newsize. + * TODO: Try reusing oldkeys when reimplement odict. + */ + + /* Allocate a new table. */ + status = numba_dictkeys_new( + &d->keys, newsize, oldkeys->key_size, oldkeys->val_size + ); + if (status != OK) { + d->keys = oldkeys; + return status; + } + // New table must be large enough. + assert(d->keys->usable >= d->used); + // Copy method table + memcpy(&d->keys->methods, &oldkeys->methods, sizeof(type_based_methods_table)); + + numentries = d->used; + + if (oldkeys->nentries == numentries) { + NB_DictEntry *oldentries, *newentries; + + oldentries = get_entry(oldkeys, 0); + newentries = get_entry(d->keys, 0); + memcpy(newentries, oldentries, numentries * oldkeys->entry_size); + // to avoid decref + memset(oldentries, 0xff, numentries * oldkeys->entry_size); + } + else { + Py_ssize_t i; + size_t epi = 0; + for (i=0; ihash == (-1) hash means it is empty + + Here, we skip until a non empty entry is encountered. + */ + while( get_entry(oldkeys, epi)->hash == DKIX_EMPTY ) { + assert( mem_cmp_zeros(entry_get_val(oldkeys, get_entry(oldkeys, epi)), oldkeys->val_size) == 0 ); + epi += 1; + } + memcpy( + get_entry(d->keys, i), + get_entry(oldkeys, epi), + oldkeys->entry_size + ); + get_entry(oldkeys, epi)->hash = DKIX_EMPTY; // to avoid decref + epi += 1; + + } + + } + numba_dictkeys_free(oldkeys); + + build_indices(d->keys, numentries); + d->keys->usable -= numentries; + d->keys->nentries = numentries; + return OK; +} + +/* + Adapted from CPython delitem_common + */ +int +numba_dict_delitem(NB_Dict *d, Py_hash_t hash, Py_ssize_t ix) +{ + Py_ssize_t hashpos; + NB_DictEntry *ep; + NB_DictKeys *dk = d->keys; + + hashpos = lookdict_index(dk, hash, ix); + assert(hashpos >= 0); + + d->used -= 1; + ep = get_entry(dk, ix); + set_index(dk, hashpos, DKIX_DUMMY); + + /* decref */ + dk_decref_key(dk, entry_get_key(dk, ep)); + dk_decref_val(dk, entry_get_val(dk, ep)); + + /* zero the entries */ + zero_key(dk, entry_get_key(dk, ep)); + zero_val(dk, entry_get_val(dk, ep)); + ep->hash = DKIX_EMPTY; // to mark it as empty; + + return OK; +} + + +/** + * Adapted from dict_popitem + * + */ +int +numba_dict_popitem(NB_Dict *d, char *key_bytes, char *val_bytes) +{ + Py_ssize_t i, j; + char *key_ptr, *val_ptr; + NB_DictEntry *ep = NULL; + + if (d->used == 0) { + return ERR_DICT_EMPTY; + } + + /* Pop last item */ + i = d->keys->nentries - 1; + while (i >= 0 && (ep = get_entry(d->keys, i))->hash == DKIX_EMPTY ) { + i--; + } + assert(i >= 0); + + j = lookdict_index(d->keys, ep->hash, i); + assert(j >= 0); + assert(get_index(d->keys, j) == i); + set_index(d->keys, j, DKIX_DUMMY); + + key_ptr = entry_get_key(d->keys, ep); + val_ptr = entry_get_val(d->keys, ep); + + copy_key(d->keys, key_bytes, key_ptr); + copy_val(d->keys, val_bytes, val_ptr); + + zero_key(d->keys, key_ptr); + zero_val(d->keys, val_ptr); + + /* We can't dk_usable++ since there is DKIX_DUMMY in indices */ + d->keys->nentries = i; + d->used--; + + return OK; +} + +void +numba_dict_dump(NB_Dict *d) { + long long i, j, k; + long long size, n; + char *cp; + NB_DictEntry *ep; + NB_DictKeys *dk = d->keys; + + n = d->used; + size = dk->nentries; + + printf("Dict dump\n"); + printf(" key_size = %lld\n", (long long)d->keys->key_size); + printf(" val_size = %lld\n", (long long)d->keys->val_size); + + for (i = 0, j = 0; i < size; i++) { + ep = get_entry(dk, i); + if (ep->hash != DKIX_EMPTY) { + long long hash = ep->hash; + printf(" key="); + for (cp=entry_get_key(dk, ep), k=0; k < d->keys->key_size; ++k, ++cp){ + printf("%02x ", ((int)*cp) & 0xff); + } + printf(" hash=%llu value=", hash); + for (cp=entry_get_val(dk, ep), k=0; k < d->keys->val_size; ++k, ++cp){ + printf("%02x ", ((int)*cp) & 0xff); + } + printf("\n"); + j++; + } + } + printf("j = %lld; n = %lld\n", j, n); + assert(j == n); +} + +size_t +numba_dict_iter_sizeof() { + return sizeof(NB_DictIter); +} + +void +numba_dict_iter(NB_DictIter *it, NB_Dict *d) { + it->parent = d; + it->parent_keys = d->keys; + it->size = d->used; + it->pos = 0; +} + +int +numba_dict_iter_next(NB_DictIter *it, const char **key_ptr, const char **val_ptr) { + /* Detect dictionary mutation during iteration */ + NB_DictKeys *dk; + if (it->parent->keys != it->parent_keys || + it->parent->used != it->size) { + return ERR_DICT_MUTATED; + } + dk = it->parent_keys; + while ( it->pos < dk->nentries ) { + NB_DictEntry *ep = get_entry(dk, it->pos++); + if ( ep->hash != DKIX_EMPTY ) { + *key_ptr = entry_get_key(dk, ep); + *val_ptr = entry_get_val(dk, ep); + return OK; + } + } + return ERR_ITER_EXHAUSTED; +} + +int +numba_dict_insert_ez( + NB_Dict *d, + const char *key_bytes, + Py_hash_t hash, + const char *val_bytes + ) +{ + STACK_ALLOC(char, old, d->keys->val_size); + return numba_dict_insert(d, key_bytes, hash, val_bytes, old); +} + + +/* Allocate a new dictionary with enough space to hold n_keys without resizes */ +int +numba_dict_new_sized(NB_Dict **out, Py_ssize_t n_keys, Py_ssize_t key_size, Py_ssize_t val_size) { + + /* Respect D_MINSIZE */ + if (n_keys <= USABLE_FRACTION(D_MINSIZE)) { + return numba_dict_new(out, D_MINSIZE, key_size, val_size); + } + + /* Adjust for load factor */ + Py_ssize_t size = INV_USABLE_FRACTION(n_keys) - 1; + + /* Round up size to the nearest power of 2. */ + for (unsigned int shift = 1; shift < sizeof(Py_ssize_t) * CHAR_BIT; shift <<= 1) { + size |= (size >> shift); + } + size++; + + /* Handle overflows */ + if (size <= 0) { + return ERR_NO_MEMORY; + } + + return numba_dict_new(out, size, key_size, val_size); +} + + +void +numba_dict_set_method_table(NB_Dict *d, type_based_methods_table *methods) +{ + memcpy(&d->keys->methods, methods, sizeof(type_based_methods_table)); +} + + +#define CHECK(CASE) { \ + if ( !(CASE) ) { \ + printf("'%s' failed file %s:%d\n", #CASE, __FILE__, __LINE__); \ + return 1; \ + } \ +} + +int +numba_test_dict(void) { + NB_Dict *d; + int status; + Py_ssize_t ix; + Py_ssize_t usable; + Py_ssize_t it_count; + const char *it_key, *it_val; + NB_DictIter iter; + +#if defined(_MSC_VER) + /* So that VS2008 compiler is happy */ + char *got_key, *got_value; + got_key = _alloca(4); + got_value = _alloca(8); +#else + char got_key[4]; + char got_value[8]; +#endif + puts("test_dict"); + + status = numba_dict_new(&d, D_MINSIZE, 4, 8); + CHECK(status == OK); + CHECK(d->keys->size == D_MINSIZE); + CHECK(d->keys->key_size == 4); + CHECK(d->keys->val_size == 8); + CHECK(ix_size(d->keys->size) == 1); + printf("aligned_size(index_size * size) = %d\n", (int)(aligned_size(ix_size(d->keys->size) * d->keys->size))); + + printf("d %p\n", d); + printf("d->usable = %u\n", (int)d->keys->usable); + usable = d->keys->usable; + printf("d[0] %d\n", (int)((char*)get_entry(d->keys, 0) - (char*)d->keys)); + CHECK ((char*)get_entry(d->keys, 0) - (char*)d->keys->indices == d->keys->entry_offset); + printf("d[1] %d\n", (int)((char*)get_entry(d->keys, 1) - (char*)d->keys)); + CHECK ((char*)get_entry(d->keys, 1) - (char*)d->keys->indices == d->keys->entry_offset + d->keys->entry_size); + + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + printf("ix = %d\n", (int)ix); + CHECK (ix == DKIX_EMPTY); + + // insert 1st key + status = numba_dict_insert(d, "bef", 0xbeef, "1234567", got_value); + CHECK (status == OK); + CHECK (d->used == 1); + CHECK (d->keys->usable == usable - d->used); + + // insert same key + status = numba_dict_insert(d, "bef", 0xbeef, "1234567", got_value); + CHECK (status == OK_REPLACED); + printf("got_value %s\n", got_value); + CHECK (d->used == 1); + CHECK (d->keys->usable == usable - d->used); + + // insert 2nd key + status = numba_dict_insert(d, "beg", 0xbeef, "1234568", got_value); + CHECK (status == OK); + CHECK (d->used == 2); + CHECK (d->keys->usable == usable - d->used); + + // insert 3rd key + status = numba_dict_insert(d, "beh", 0xcafe, "1234569", got_value); + CHECK (status == OK); + CHECK (d->used == 3); + CHECK (d->keys->usable == usable - d->used); + + // replace key "bef"'s value + status = numba_dict_insert(d, "bef", 0xbeef, "7654321", got_value); + CHECK (status == OK_REPLACED); + CHECK (d->used == 3); + CHECK (d->keys->usable == usable - d->used); + + // insert 4th key + status = numba_dict_insert(d, "bei", 0xcafe, "0_0_0_1", got_value); + CHECK (status == OK); + CHECK (d->used == 4); + CHECK (d->keys->usable == usable - d->used); + + // insert 5th key + status = numba_dict_insert(d, "bej", 0xcafe, "0_0_0_2", got_value); + CHECK (status == OK); + CHECK (d->used == 5); + CHECK (d->keys->usable == usable - d->used); + + // insert 6th key & triggers resize + status = numba_dict_insert(d, "bek", 0xcafe, "0_0_0_3", got_value); + CHECK (status == OK); + CHECK (d->used == 6); + CHECK (d->keys->usable == USABLE_FRACTION(d->keys->size) - d->used); + + // Dump + numba_dict_dump(d); + + // Make sure everything are still in there + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "7654321", d->keys->val_size)); + + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "1234567", d->keys->val_size)); + + ix = numba_dict_lookup(d, "beh", 0xcafe, got_value); + printf("ix = %d\n", (int)ix); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "1234569", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bei", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_1", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bej", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_2", d->keys->val_size)); + + ix = numba_dict_lookup(d, "bek", 0xcafe, got_value); + CHECK (ix >= 0); + CHECK (memcpy(got_value, "0_0_0_3", d->keys->val_size)); + + // Test delete + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + status = numba_dict_delitem(d, 0xbeef, ix); + CHECK (status == OK); + + ix = numba_dict_lookup(d, "beg", 0xbeef, got_value); + CHECK (ix == DKIX_EMPTY); // not found + + ix = numba_dict_lookup(d, "bef", 0xbeef, got_value); + CHECK (ix >= 0); + ix = numba_dict_lookup(d, "beh", 0xcafe, got_value); + CHECK (ix >= 0); + + + // Test popitem + // They are always the last item + status = numba_dict_popitem(d, got_key, got_value); + CHECK(status == OK); + CHECK(memcmp("bek", got_key, d->keys->key_size) == 0); + CHECK(memcmp("0_0_0_3", got_value, d->keys->val_size) == 0); + + status = numba_dict_popitem(d, got_key, got_value); + CHECK(status == OK); + CHECK(memcmp("bej", got_key, d->keys->key_size) == 0); + CHECK(memcmp("0_0_0_2", got_value, d->keys->val_size) == 0); + + // Test iterator + CHECK( d->used > 0 ); + numba_dict_iter(&iter, d); + it_count = 0; + while ( (status = numba_dict_iter_next(&iter, &it_key, &it_val)) == OK) { + it_count += 1; // valid items + CHECK(it_key != NULL); + CHECK(it_val != NULL); + } + + CHECK(status == ERR_ITER_EXHAUSTED); + CHECK(d->used == it_count); + + numba_dict_free(d); + + /* numba_dict_new_sized() */ + + Py_ssize_t target_size; + Py_ssize_t n_keys; + + // Test if minsize dict returned with n_keys=0 + target_size = D_MINSIZE; + n_keys = 0; + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable == USABLE_FRACTION(target_size)); + numba_dict_free(d); + + // Test sizing at power of 2 boundary + target_size = D_MINSIZE * 2; + n_keys = USABLE_FRACTION(target_size); + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable == n_keys); + numba_dict_free(d); + + target_size *= 2; + n_keys++; + + numba_dict_new_sized(&d, n_keys, 1, 1); + CHECK(d->keys->size == target_size); + CHECK(d->keys->usable > n_keys); + CHECK(d->keys->usable == USABLE_FRACTION(target_size)); + numba_dict_free(d); + + return 0; + +} + +#undef CHECK diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.h new file mode 100644 index 0000000000000000000000000000000000000000..82f237a2de1b781cb7a69975fed157b615f09060 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/dictobject.h @@ -0,0 +1,228 @@ +/* Adapted from CPython3.7 Objects/dict-common.h */ +#include "cext.h" + +#ifndef NUMBA_DICT_COMMON_H +#define NUMBA_DICT_COMMON_H + +typedef struct { + /* Uses Py_ssize_t instead of Py_hash_t to guarantee word size alignment */ + Py_ssize_t hash; + char keyvalue[]; +} NB_DictEntry; + + +typedef int (*dict_key_comparator_t)(const char *lhs, const char *rhs); +typedef void (*dict_refcount_op_t)(const void*); + + +typedef struct { + dict_key_comparator_t key_equal; + dict_refcount_op_t key_incref; + dict_refcount_op_t key_decref; + dict_refcount_op_t value_incref; + dict_refcount_op_t value_decref; +} type_based_methods_table; + + +typedef struct { + /* hash table size */ + Py_ssize_t size; + /* Usable size of the hash table. + Also, size of the entries */ + Py_ssize_t usable; + /* hash table used entries */ + Py_ssize_t nentries; + /* Entry info + - key_size is the sizeof key type + - val_size is the sizeof value type + - entry_size is key_size + val_size + alignment + */ + Py_ssize_t key_size, val_size, entry_size; + /* Byte offset from indices to the first entry. */ + Py_ssize_t entry_offset; + + /* Method table for type-dependent operations. */ + type_based_methods_table methods; + + /* hash table */ + char indices[]; +} NB_DictKeys; + + +typedef struct { + /* num of elements in the hashtable */ + Py_ssize_t used; + NB_DictKeys *keys; +} NB_Dict; + + +typedef struct { + /* parent dictionary */ + NB_Dict *parent; + /* parent keys object */ + NB_DictKeys *parent_keys; + /* dict size */ + Py_ssize_t size; + /* iterator position; indicates the next position to read */ + Py_ssize_t pos; +} NB_DictIter; + + + +/* A test function for the dict +Returns 0 for OK; 1 for failure. +*/ +NUMBA_EXPORT_FUNC(int) +numba_test_dict(void); + +/* Allocate a new dict +Parameters +- NB_Dict **out + Output for the new dictionary. +- Py_ssize_t size + Hashtable size. Must be power of two. +- Py_ssize_t key_size + Size of a key entry. +- Py_ssize_t val_size + Size of a value entry. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_new(NB_Dict **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size); + +/* Allocate a new dict with enough space to hold n_keys without resizing. +Parameters +- NB_Dict **out + Output for the new dictionary. +- Py_ssize_t n_keys + The number of keys to fit without needing resize. +- Py_ssize_t key_size + Size of a key entry. +- Py_ssize_t val_size + Size of a value entry. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_new_sized(NB_Dict** out, Py_ssize_t n_keys, Py_ssize_t key_size, Py_ssize_t val_size); + +/* Free a dict */ +NUMBA_EXPORT_FUNC(void) +numba_dict_free(NB_Dict *d); + +/* Returns length of a dict */ +NUMBA_EXPORT_FUNC(Py_ssize_t) +numba_dict_length(NB_Dict *d); + +/* Set the method table for type specific operations +*/ +NUMBA_EXPORT_FUNC(void) +numba_dict_set_method_table(NB_Dict *d, type_based_methods_table *methods); + +/* Lookup a key + +Parameters +- NB_Dict *d + The dictionary object. +- const char *key_bytes + The key as a byte buffer. +- Py_hash_t hash + The precomputed hash of the key. +- char *oldval_bytes + An output parameter to store the associated value if the key is found. + Must point to memory of sufficient size to store the value. +*/ +NUMBA_EXPORT_FUNC(Py_ssize_t) +numba_dict_lookup(NB_Dict *d, const char *key_bytes, Py_hash_t hash, char *oldval_bytes); + +/* Resize the dict to at least *minsize*. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_resize(NB_Dict *d, Py_ssize_t minsize); + +/* Insert to the dict + +Parameters +- NB_Dict *d + The dictionary object. +- const char *key_bytes + The key as a byte buffer. +- Py_hash_t hash + The precomputed hash of key. +- const char *val_bytes + The value as a byte buffer. +- char *oldval_bytes + An output buffer to store the replaced value. + Must point to memory of sufficient size to store the value. + +Returns +- < 0 for error +- 0 for ok +- 1 for ok and oldval_bytes has a copy of the replaced value. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_insert(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes, char *oldval_bytes); + +/* Same as numba_dict_insert() but oldval_bytes is not needed */ +NUMBA_EXPORT_FUNC(int) +numba_dict_insert_ez(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes); + +/* Delete an entry from the dict +Parameters +- NB_Dict *d + The dictionary +- Py_hash_t hash + Precomputed hash of the key to be deleted +- Py_ssize_t ix + Precomputed entry index of the key to be deleted. + Usually results of numba_dict_lookup(). +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_delitem(NB_Dict *d, Py_hash_t hash, Py_ssize_t ix); + +/* Remove an item from the dict +Parameters +- NB_Dict *d + The dictionary +- char *key_bytes + Output. The key as a byte buffer +- char *val_bytes + Output. The value as a byte buffer +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_popitem(NB_Dict *d, char *key_bytes, char *val_bytes); + +/* Returns the sizeof a dictionary iterator +*/ +NUMBA_EXPORT_FUNC(size_t) +numba_dict_iter_sizeof(void); + +/* Fill a NB_DictIter for a dictionary to begin iteration +Parameters +- NB_DictIter *it + Output. Must points to memory of size at least `numba_dict_iter_sizeof()`. +- NB_Dict *d + The dictionary to be iterated. +*/ +NUMBA_EXPORT_FUNC(void) +numba_dict_iter(NB_DictIter *it, NB_Dict *d); + +/* Advance the iterator +Parameters +- NB_DictIter *it + The iterator +- const char **key_ptr + Output pointer for the key. Points to data in the dictionary. +- const char **val_ptr + Output pointer for the key. Points to data in the dictionary. + +Returns +- 0 for success; valid key_ptr and val_ptr +- ERR_ITER_EXHAUSTED for end of iterator. +- ERR_DICT_MUTATED for detected dictionary mutation. +*/ +NUMBA_EXPORT_FUNC(int) +numba_dict_iter_next(NB_DictIter *it, const char **key_ptr, const char **val_ptr); + + +NUMBA_EXPORT_FUNC(void) +numba_dict_dump(NB_Dict *); + +#endif diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.c b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.c new file mode 100644 index 0000000000000000000000000000000000000000..9de03f5ff1d61b73bf6e4a340d51388bc09f2bc9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.c @@ -0,0 +1,977 @@ +#include "listobject.h" + +/* This implements the C component of the Numba typed list. It is loosely + * inspired by the list implementation of the cpython list with some parts + * taken from the cpython slice implementation. The exact commit-id of the + * relevant files are: + * + * https://github.com/python/cpython/blob/51ddab8dae056867f3595ab3400bffc93f67c8d4/Objects/listobject.c + * https://github.com/python/cpython/blob/51ddab8dae056867f3595ab3400bffc93f67c8d4/Objects/sliceobject.c + * + * Algorithmically, this list is very similar to the cpython implementation so + * it should have the same performance (Big-O) characteristics for accessing, + * adding and removing elements/items. Specifically, it implements the same + * algorithms for list overallocation and growth. However, it never deals with + * PyObject types and instead must be typed with a type-size. As a result, the + * typed-list is type homogeneous and in contrast to the cpython version can + * not store a mixture of arbitrarily typed objects. Reference counting via the + * Numba Runtime (NRT) is supported and incrementing and decrementing functions + * are store as part of the struct and can be setup from the compiler level. + * + * Importantly, only a very limited subset of the cpython c functions have been + * ported over and the rest have been implemented (in Python) at the compiler + * level using the c functions provided. Additionally, initialization of, and + * iteration over, a ListIter is provided + * + * The following functions are implemented for the list: + * + * - Check valid index valid_index + * - Creation numba_list_new + * - Deletion numba_list_free + * - Accessing the length numba_list_length + * - Appending to the list numba_list_append + * - Getting an item numba_list_setitem + * - Setting an item numba_list_getitem + * - Resizing the list numba_list_resize + * - Deleting an item numba_list_delitem + * - Deleting a slice numba_list_delete_slice + * + * As you can see, only a single function for slices is implemented. The rest + * is all done entirely at the compiler level which then calls the c functions + * to mutate the list accordingly. Since slicing allows for replace, insert and + * delete operations over multiple items, we can simply implement those using + * the basic functions above. + * + * The following additional functions are implemented for the list, these are + * needed to make the list work within Numba. + * + * - Accessing the allocation numba_list_allocated + * - Copying an item copy_item + * - Calling incref on item list_incref_item + * - Calling decref on item list_decref_item + * - Set method table numba_list_set_method_table + * + * The following functions are implemented for the iterator: + * + * - Size of the iterator numba_list_iter_size + * - Initialization of iter numba_list_iter + * - Get next item from iter numba_list_iter_next + * + * Two methods are provided to query and set the 'is_mutable': + * + * - Query numba_list_is_mutable + * - Set numba_list_set_is_mutable + * + * Lastly a set of pure C level tests are provided which come in handy when + * needing to use valgrind and friends. + * + */ + + +/* Return status for the list functions. + */ +typedef enum { + LIST_OK = 0, + LIST_ERR_INDEX = -1, + LIST_ERR_NO_MEMORY = -2, + LIST_ERR_MUTATED = -3, + LIST_ERR_ITER_EXHAUSTED = -4, + LIST_ERR_IMMUTABLE = -5, +} ListStatus; + +/* Copy an item from a list. + * + * lp: a list + * dst: destination pointer + * src: source pointer + */ +static void +copy_item(NB_List *lp, char *dst, const char *src){ + memcpy(dst, src, lp->item_size); +} + +/* Increment a reference to an item in a list. + * + * lp: a list + * item: the item to increment the reference for + */ +static void +list_incref_item(NB_List *lp, const char *item){ + if (lp->methods.item_incref) { + lp->methods.item_incref(item); + } +} + +/* Decrement a reference to an item in a list. + * + * lp: a list + * item: the item to decrement the reference for + */ +static void +list_decref_item(NB_List *lp, const char *item){ + if (lp->methods.item_decref) { + lp->methods.item_decref(item); + } +} + +/* Setup the method table for a list. + * + * This function is used from the compiler level to initialize the internal + * method table. + * + * lp: a list + * methods: the methods table to set up + */ +void +numba_list_set_method_table(NB_List *lp, list_type_based_methods_table *methods) +{ + memcpy(&lp->methods, methods, sizeof(list_type_based_methods_table)); +} + +/* Check if a list index is valid. + * + * i: the index to check + * limit: the size of a list + * + * Adapted from CPython's valid_index(). + * + * FIXME: need to find a way to inline this, even for Python 2.7 on Windows + */ +static int +valid_index(Py_ssize_t i, Py_ssize_t limit){ + /* The cast to size_t lets us use just a single comparison + to check whether i is in the range: 0 <= i < limit. + + See: Section 14.2 "Bounds Checking" in the Agner Fog + optimization manual found at: + https://www.agner.org/optimize/optimizing_cpp.pdf + */ + return (size_t) i < (size_t) limit; +} + +/* Initialize a new list. + * + * out: pointer to hold an initialized list + * item_size: the size in bytes of the items in the list + * allocated: preallocation of the list in items + * + * This will allocate sufficient memory to hold the list structure and any + * items if requested (allocated != 0). See _listobject.h for more information + * on the NB_List struct. + */ +int +numba_list_new(NB_List **out, Py_ssize_t item_size, Py_ssize_t allocated){ + NB_List *lp; + char *items; + // allocate memory to hold the struct + lp = malloc(aligned_size(sizeof(NB_List))); + if (lp == NULL) { + return LIST_ERR_NO_MEMORY; + } + // set up members + lp->size = 0; + lp->item_size = item_size; + lp->allocated = allocated; + lp->is_mutable = 1; + // set method table to zero */ + memset(&lp->methods, 0x00, sizeof(list_type_based_methods_table)); + // allocate memory to hold items, if requested + if (allocated != 0) { + items = malloc(aligned_size(lp->item_size * allocated)); + // allocated was definitely not zero, if malloc returns NULL + // this is definitely an error + if (items == NULL) { + // free previously allocated struct to avoid leaking memory + free(lp); + return LIST_ERR_NO_MEMORY; + } + lp->items = items; + } + else { + // be explicit + lp->items = NULL; + } + *out = lp; + return LIST_OK; +} + +/* Free the memory associated with a list. + * + * lp: a list + */ +void +numba_list_free(NB_List *lp) { + // decref all items, if needed + Py_ssize_t i; + if (lp->methods.item_decref) { + for (i = 0; i < lp->size; i++) { + char *item = lp->items + lp->item_size * i; + list_decref_item(lp, item); + } + } + // free items and list + if (lp->items != NULL) { + free(lp->items); + } + free(lp); +} + +/* Return the base pointer of the list items. + */ +char * +numba_list_base_ptr(NB_List *lp) +{ + return lp->items; +} + +/* Return the address of the list size. + */ +Py_ssize_t +numba_list_size_address(NB_List *lp) +{ + return (Py_ssize_t)&lp->size; +} + + +/* Return the length of a list. + * + * lp: a list + */ +Py_ssize_t +numba_list_length(NB_List *lp) { + return lp->size; +} + +/* Return the current allocation of a list. + * + * lp: a list + */ +Py_ssize_t +numba_list_allocated(NB_List *lp) { + return lp->allocated; +} + +/* Return the mutability status of the list + * + * lp: a list + * + */ +int +numba_list_is_mutable(NB_List *lp){ + return lp->is_mutable; +} + +/* Set the is_mutable attribute + * + * lp: a list + * is_mutable: an int, 0(False) or 1(True) + * + */ +void +numba_list_set_is_mutable(NB_List *lp, int is_mutable){ + lp->is_mutable = is_mutable; +} + +/* Set an item in a list. + * + * lp: a list + * index: the index of the item to set (must be in range 0 <= index < len(list)) + * item: the item to set + * + * This assume there is already an element at the given index that will be + * overwritten and thereby have its reference decremented. DO NOT use this to + * write to an unassigned location. + */ +int +numba_list_setitem(NB_List *lp, Py_ssize_t index, const char *item) { + char *loc; + // check for mutability + if (!lp->is_mutable) { + return LIST_ERR_IMMUTABLE; + } + // check index is valid + // FIXME: this can be (and probably is) checked at the compiler level + if (!valid_index(index, lp->size)) { + return LIST_ERR_INDEX; + } + // set item at desired location + loc = lp->items + lp-> item_size * index; + list_decref_item(lp, loc); + copy_item(lp, loc, item); + list_incref_item(lp, loc); + return LIST_OK; +} + +/* Get an item from a list. + * + * lp: a list + * index: the index of the item to get (must be in range 0 <= index < len(list)) + * out: a pointer to hold the item + */ +int +numba_list_getitem(NB_List *lp, Py_ssize_t index, char *out) { + char *loc; + // check index is valid + // FIXME: this can be (and probably is) checked at the compiler level + if (!valid_index(index, lp->size)) { + return LIST_ERR_INDEX; + } + // get item at desired location + loc = lp->items + lp->item_size * index; + copy_item(lp, out, loc); + return LIST_OK; +} + +/* Append an item to the end of a list. + * + * lp: a list + * item: the item to append. + */ +int +numba_list_append(NB_List *lp, const char *item) { + char *loc; + // check for mutability + if (!lp->is_mutable) { + return LIST_ERR_IMMUTABLE; + } + // resize by one, will change list size + int result = numba_list_resize(lp, lp->size + 1); + if(result < LIST_OK) { + return result; + } + // insert item at index: original size before resize + loc = lp->items + lp->item_size * (lp->size - 1); + copy_item(lp, loc, item); + list_incref_item(lp, loc); + return LIST_OK; +} + +/* Resize a list. + * + * lp: a list + * newsize: the desired new size of the list. + * + * This will increase or decrease the size of the list, including reallocating + * the required memory and increasing the total allocation (additional free + * space to hold new items). + * + * + * Adapted from CPython's list_resize(). + * + * Ensure lp->items has room for at least newsize elements, and set + * lp->size to newsize. If newsize > lp->size on entry, the content + * of the new slots at exit is undefined heap trash; it's the caller's + * responsibility to overwrite them with sane values. + * The number of allocated elements may grow, shrink, or stay the same. + * Failure is impossible if newsize <= lp->allocated on entry, although + * that partly relies on an assumption that the system realloc() never + * fails when passed a number of bytes <= the number of bytes last + * allocated (the C standard doesn't guarantee this, but it's hard to + * imagine a realloc implementation where it wouldn't be true). + * Note that lp->items may change, and even if newsize is less + * than lp->size on entry. + */ +int +numba_list_resize(NB_List *lp, Py_ssize_t newsize) { + char * items; + // check for mutability + if (!lp->is_mutable) { + return LIST_ERR_IMMUTABLE; + } + size_t new_allocated, num_allocated_bytes; + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize falls lower than half + the allocated size, then proceed with the realloc() to shrink the list. + */ + if (lp->allocated >= newsize && newsize >= (lp->allocated >> 1)) { + assert(lp->items != NULL || newsize == 0); + lp->size = newsize; + return LIST_OK; + } + /* This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... + * Note: new_allocated won't overflow because the largest possible value + * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t. + */ + new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6); + if (new_allocated > (size_t)PY_SSIZE_T_MAX / lp->item_size) { + return LIST_ERR_NO_MEMORY; + } + + if (newsize == 0) + new_allocated = 0; + num_allocated_bytes = new_allocated * lp->item_size; + items = realloc(lp->items, aligned_size(num_allocated_bytes)); + // realloc may return NULL if requested size is 0 + if (num_allocated_bytes != 0 && items == NULL) { + return LIST_ERR_NO_MEMORY; + } + lp->items = items; + lp->size = newsize; + lp->allocated = (Py_ssize_t)new_allocated; + return LIST_OK; +} + +/* Delete a single item. + * + * lp: a list + * index: the index of the item to delete + * (must be in range 0 <= index < len(list)) + * + * */ +int +numba_list_delitem(NB_List *lp, Py_ssize_t index) { + int result; + char *loc, *new_loc; + Py_ssize_t leftover_bytes; + // check for mutability + if (!lp->is_mutable) { + return LIST_ERR_IMMUTABLE; + } + // check index is valid + // FIXME: this can be (and probably is) checked at the compiler level + if (!valid_index(index, lp->size)) { + return LIST_ERR_INDEX; + } + // obtain item and decref if needed + loc = lp->items + lp->item_size * index; + list_decref_item(lp, loc); + if (index != lp->size - 1) { + // delitem from somewhere other than the end, incur the memory copy + leftover_bytes = (lp->size - 1 - index) * lp->item_size; + new_loc = lp->items + (lp->item_size * (index + 1)); + // use memmove instead of memcpy since we may be dealing with + // overlapping regions of memory and the behaviour of memcpy is + // undefined in such situation (C99). + memmove(loc, new_loc, leftover_bytes); + } + // finally, shrink list by one + result = numba_list_resize(lp, lp->size - 1); + if(result < LIST_OK) { + // Since we are decreasing the size, this should never happen + return result; + } + return LIST_OK; + +} + +/* Delete a slice + * + * start: the start index of ths slice + * stop: the stop index of the slice (not included) + * step: the step to take + * + * This function assumes that the start and stop were clipped appropriately. + * I.e. if step > 0 start >= 0 and stop <= len(l) and + * if step < 0 start <= length and stop >= -1 + * step != 0 and no Python negative indexing allowed. + * + * This code was copied and edited from the relevant section in + * list_ass_subscript from the cpython implementation, see the top of this file + * for the exact source + */ +int +numba_list_delete_slice(NB_List *lp, + Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step) { + int result, i, slicelength, new_length; + char *loc, *new_loc; + Py_ssize_t leftover_bytes, cur, lim; + // check for mutability + if (!lp->is_mutable) { + return LIST_ERR_IMMUTABLE; + } + // calculate the slicelength, taken from PySlice_AdjustIndices, see the top + // of this file for the exact source + if (step > 0) { + slicelength = start < stop ? (stop - start - 1) / step + 1 : 0; + } else { + slicelength = stop < start ? (start - stop - 1) / -step + 1 : 0; + } + if (slicelength <= 0){ + return LIST_OK; + } + new_length = lp->size - slicelength; + // reverse step and indices + if (step < 0) { + stop = start + 1; + start = stop + step * (slicelength - 1) - 1; + step = -step; + } + if (step == 1) { + // decref if needed + if (lp->methods.item_decref) { + for (i = start ; i < stop ; i++){ + loc = lp->items + lp->item_size * i; + lp->methods.item_decref(loc); + } + } + // memmove items into place + leftover_bytes = (lp->size - stop) * lp->item_size; + loc = lp->items + lp->item_size * start; + new_loc = lp->items + lp->item_size * stop; + memmove(loc, new_loc, leftover_bytes); + } + else { // step != 1 + /* drawing pictures might help understand these for + * loops. Basically, we memmove the parts of the + * list that are *not* part of the slice: step-1 + * items for each item that is part of the slice, + * and then tail end of the list that was not + * covered by the slice + * + * */ + for (cur = start, // index of item to be deleted + i = 0; // counter of total items deleted so far + cur < stop; + cur += step, + i++) { + lim = step - 1; // number of leftover items after deletion of item + // clip limit, in case we are at the end of the slice, and there + // are now less than step-1 items to be moved + if (cur + step >= lp->size) { + lim = lp->size - cur - 1; + } + // decref item being removed + loc = lp->items + lp->item_size * cur; + list_decref_item(lp, loc); + /* memmove the aforementioned step-1 (or less) items + * dst : index of deleted item minus total deleted sofar + * src : index of deleted item plus one (next item) + */ + memmove(lp->items + lp->item_size * (cur - i), + lp->items + lp->item_size * (cur + 1), + lim * lp->item_size); + } + // memmove tail of the list + cur = start + slicelength * step; + if (cur < lp->size) { + memmove(lp->items + lp->item_size * (cur - slicelength), + lp->items + lp->item_size * cur, + (lp->size - cur) * lp->item_size); + } + } + // resize to correct size + result = numba_list_resize(lp, new_length); + if(result < LIST_OK) { + // Since we are decreasing the size, this should never happen + return result; + } + return LIST_OK; +} + + +/* Return the size of the list iterator (NB_ListIter) struct. + */ +size_t +numba_list_iter_sizeof() { + return sizeof(NB_ListIter); +} + +/* Initialize a list iterator (NB_ListIter). + * + * it: an iterator + * lp: a list to iterate over + */ +void +numba_list_iter(NB_ListIter *it, NB_List *lp) { + // set members of iterator + it->parent = lp; + it->size = lp->size; + it->pos = 0; +} + +/* Obtain the next item from a list iterator. + * + * it: an iterator + * item_ptr: pointer to hold the next item + */ +int +numba_list_iter_next(NB_ListIter *it, const char **item_ptr) { + NB_List *lp; + lp = it->parent; + /* FIXME: Detect list mutation during iteration */ + if (lp->size != it->size) { + return LIST_ERR_MUTATED; + } + // get next element + if (it->pos < lp->size) { + *item_ptr = lp->items + lp->item_size * it->pos++; + return LIST_OK; + }else{ + return LIST_ERR_ITER_EXHAUSTED; + } +} + + +#define CHECK(CASE) { \ + if ( !(CASE) ) { \ + printf("'%s' failed file %s:%d\n", #CASE, __FILE__, __LINE__); \ + return -1; \ + } \ +} + +/* Basic C based tests for the list. + */ +int +numba_test_list(void) { + NB_List *lp = NULL; + int status, i; + Py_ssize_t it_count; + const char *it_item = NULL; + NB_ListIter iter; + char got_item[4] = "\x00\x00\x00\x00"; + const char *test_items_1 = NULL, *test_items_2 = NULL; + char *test_items_3 = NULL; + puts("test_list"); + + + status = numba_list_new(&lp, 4, 0); + CHECK(status == LIST_OK); + CHECK(lp->item_size == 4); + CHECK(lp->size == 0); + CHECK(lp->allocated == 0); + CHECK(lp->is_mutable == 1); + + // flip and check the is_mutable bit + CHECK(numba_list_is_mutable(lp) == 1); + numba_list_set_is_mutable(lp, 0); + CHECK(numba_list_is_mutable(lp) == 0); + numba_list_set_is_mutable(lp, 1); + CHECK(numba_list_is_mutable(lp) == 1); + + // append 1st item, this will cause a realloc + status = numba_list_append(lp, "abc"); + CHECK(status == LIST_OK); + CHECK(lp->size == 1); + CHECK(lp->allocated == 4); + status = numba_list_getitem(lp, 0, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "abc", 4) == 0); + + // append 2nd item + status = numba_list_append(lp, "def"); + CHECK(status == LIST_OK); + CHECK(lp->size == 2); + CHECK(lp->allocated == 4); + status = numba_list_getitem(lp, 1, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "def", 4) == 0); + + // append 3rd item + status = numba_list_append(lp, "ghi"); + CHECK(status == LIST_OK); + CHECK(lp->size == 3); + CHECK(lp->allocated == 4); + status = numba_list_getitem(lp, 2, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "ghi", 4) == 0); + + // append 4th item + status = numba_list_append(lp, "jkl"); + CHECK(status == LIST_OK); + CHECK(lp->size == 4); + CHECK(lp->allocated == 4); + status = numba_list_getitem(lp, 3, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "jkl", 4) == 0); + + // append 5th item, this will cause another realloc + status = numba_list_append(lp, "mno"); + CHECK(status == LIST_OK); + CHECK(lp->size == 5); + CHECK(lp->allocated == 8); + status = numba_list_getitem(lp, 4, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "mno", 4) == 0); + + // overwrite 1st item + status = numba_list_setitem(lp, 0, "pqr"); + CHECK(status == LIST_OK); + CHECK(lp->size == 5); + CHECK(lp->allocated == 8); + status = numba_list_getitem(lp, 0, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "pqr", 4) == 0); + + // get and del 1st item, check item shift + status = numba_list_getitem(lp, 0, got_item); + status = numba_list_delitem(lp, 0); + CHECK(status == LIST_OK); + CHECK(lp->size == 4); + CHECK(lp->allocated == 8); + CHECK(memcmp(got_item, "pqr", 4) == 0); + CHECK(memcmp(lp->items, "def\x00ghi\x00jkl\x00mno\x00", 16) == 0); + + // get and del last (4th) item, no shift since only last item affected + status = numba_list_getitem(lp, 3, got_item); + status = numba_list_delitem(lp, 3); + CHECK(status == LIST_OK); + CHECK(lp->size == 3); + CHECK(lp->allocated == 6); // this also shrinks the allocation + CHECK(memcmp(got_item, "mno", 4) == 0); + CHECK(memcmp(lp->items, "def\x00ghi\x00jkl\x00", 12) == 0); + + // flip and check the is_mutable member + CHECK(numba_list_is_mutable(lp) == 1); + numba_list_set_is_mutable(lp, 0); + CHECK(numba_list_is_mutable(lp) == 0); + + // ensure that any attempts to mutate an immutable list fail + CHECK(numba_list_setitem(lp, 0, "zzz") == LIST_ERR_IMMUTABLE); + CHECK(numba_list_append(lp, "zzz") == LIST_ERR_IMMUTABLE); + CHECK(numba_list_delitem(lp, 0) == LIST_ERR_IMMUTABLE); + CHECK(numba_list_resize(lp, 23) == LIST_ERR_IMMUTABLE); + CHECK(numba_list_delete_slice(lp, 0, 3, 1) == LIST_ERR_IMMUTABLE); + + // ensure that all attempts to query/read from and immutable list succeed + CHECK(numba_list_length(lp) == 3); + status = numba_list_getitem(lp, 0, got_item); + CHECK(status == LIST_OK); + CHECK(memcmp(got_item, "def", 4) == 0); + + // flip the is_mutable member back and check + numba_list_set_is_mutable(lp, 1); + CHECK(numba_list_is_mutable(lp) == 1); + + // test iterator + CHECK(lp->size > 0); + numba_list_iter(&iter, lp); + it_count = 0; + CHECK(iter.parent == lp); + CHECK(iter.pos == it_count); + + // current contents of list + test_items_1 = "def\x00ghi\x00jkl\x00"; + while ( (status = numba_list_iter_next(&iter, &it_item)) == LIST_OK) { + it_count += 1; + CHECK(iter.pos == it_count); // check iterator position + CHECK(it_item != NULL); // quick check item is non-null + // go fishing in test_items_1 + CHECK(memcmp((const char *)test_items_1 + ((it_count - 1) * 4), it_item, 4) == 0); + } + + CHECK(status == LIST_ERR_ITER_EXHAUSTED); + CHECK(lp->size == it_count); + + // free existing list + numba_list_free(lp); + + // test growth upon append and shrink during delitem + status = numba_list_new(&lp, 1, 0); + CHECK(status == LIST_OK); + CHECK(lp->item_size == 1); + CHECK(lp->size == 0); + CHECK(lp->allocated == 0); + + // first, grow the list + // Use exactly 17 elements, should go through the allocation pattern: + // 0, 4, 8, 16, 25 + for (i = 0; i < 17 ; i++) { + switch(i) { + // Check the allocation before + case 0: CHECK(lp->allocated == 0); break; + case 4: CHECK(lp->allocated == 4); break; + case 8: CHECK(lp->allocated == 8); break; + case 16: CHECK(lp->allocated == 16); break; + } + status = numba_list_append(lp, (const char*)&i); + CHECK(status == LIST_OK); + switch(i) { + // Check that the growth happened accordingly + case 0: CHECK(lp->allocated == 4); break; + case 4: CHECK(lp->allocated == 8); break; + case 8: CHECK(lp->allocated == 16); break; + case 16: CHECK(lp->allocated == 25); break; + } + } + CHECK(lp->size == 17); + + // Check current contents of list + test_items_2 = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"; + CHECK(memcmp(lp->items, test_items_2, 17) == 0); + + // Now, delete them again and check that list shrinks + for (i = 17; i > 0 ; i--) { + switch(i) { + // Check the allocation before delitem + case 17: CHECK(lp->allocated == 25); break; + case 12: CHECK(lp->allocated == 25); break; + case 9: CHECK(lp->allocated == 18); break; + case 6: CHECK(lp->allocated == 12); break; + case 4: CHECK(lp->allocated == 8); break; + case 3: CHECK(lp->allocated == 6); break; + case 2: CHECK(lp->allocated == 5); break; + case 1: CHECK(lp->allocated == 4); break; + } + status = numba_list_getitem(lp, i-1, got_item); + status = numba_list_delitem(lp, i-1); + CHECK(status == LIST_OK); + switch(i) { + // Check that the shrink happened accordingly + case 17: CHECK(lp->allocated == 25); break; + case 12: CHECK(lp->allocated == 18); break; + case 9: CHECK(lp->allocated == 12); break; + case 6: CHECK(lp->allocated == 8); break; + case 4: CHECK(lp->allocated == 6); break; + case 3: CHECK(lp->allocated == 5); break; + case 2: CHECK(lp->allocated == 4); break; + case 1: CHECK(lp->allocated == 0); break; + } + } + // free existing list + numba_list_free(lp); + + + // Setup list for testing delete_slice + status = numba_list_new(&lp, 1, 0); + CHECK(status == LIST_OK); + CHECK(lp->item_size == 1); + CHECK(lp->size == 0); + CHECK(lp->allocated == 0); + for (i = 0; i < 17 ; i++) { + status = numba_list_append(lp, (const char*)&i); + CHECK(status == LIST_OK); + } + CHECK(lp->size == 17); + test_items_3 = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"; + CHECK(memcmp(lp->items, test_items_3, 17) == 0); + + // delete multiple elements from the middle + status = numba_list_delete_slice(lp, 2, 5, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 14); + test_items_3 = "\x00\x01\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"; + CHECK(memcmp(lp->items, test_items_3, 14) == 0); + + // delete single element from start + status = numba_list_delete_slice(lp, 0, 1, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 13); + test_items_3 = "\x01\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"; + CHECK(memcmp(lp->items, test_items_3, 13) == 0); + + // delete single element from end + status = numba_list_delete_slice(lp, 12, 13, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 12); + test_items_3 = "\x01\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"; + CHECK(memcmp(lp->items, test_items_3, 12) == 0); + + // delete single element from middle + status = numba_list_delete_slice(lp, 4, 5, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 11); + test_items_3 = "\x01\x05\x06\x07\x09\x0a\x0b\x0c\x0d\x0e\x0f"; + CHECK(memcmp(lp->items, test_items_3, 11) == 0); + + // delete all elements except first and last + status = numba_list_delete_slice(lp, 1, 10, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 2); + test_items_3 = "\x01\x0f"; + CHECK(memcmp(lp->items, test_items_3, 2) == 0); + + // delete all remaining elements + status = numba_list_delete_slice(lp, 0, lp->size, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 0); + test_items_3 = ""; + CHECK(memcmp(lp->items, test_items_3, 0) == 0); + + // free existing list + numba_list_free(lp); + + // Setup list for testing delete_slice with non unary step + status = numba_list_new(&lp, 1, 0); + CHECK(status == LIST_OK); + CHECK(lp->item_size == 1); + CHECK(lp->size == 0); + CHECK(lp->allocated == 0); + for (i = 0; i < 17 ; i++) { + status = numba_list_append(lp, (const char*)&i); + CHECK(status == LIST_OK); + } + CHECK(lp->size == 17); + + // delete all items with odd index + status = numba_list_delete_slice(lp, 0, 17, 2); + CHECK(status == LIST_OK); + CHECK(lp->size == 8); + test_items_3 = "\x01\x03\x05\x07\x09\x0b\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 8) == 0); + + // delete with a step of 4, starting at index 1 + status = numba_list_delete_slice(lp, 1, 8, 4); + CHECK(status == LIST_OK); + CHECK(lp->size == 6); + test_items_3 = "\x01\x05\x07\x09\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 6) == 0); + + // delete with a step of 2, but finish before end of list + status = numba_list_delete_slice(lp, 0, 4, 2); + CHECK(status == LIST_OK); + CHECK(lp->size == 4); + test_items_3 = "\x05\x09\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 4) == 0); + + // no-op on empty slice + status = numba_list_delete_slice(lp, 0, 0, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 4); + test_items_3 = "\x05\x09\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 4) == 0); + + // no-op on empty slice, non-zero index + status = numba_list_delete_slice(lp, 2, 2, 1); + CHECK(status == LIST_OK); + CHECK(lp->size == 4); + test_items_3 = "\x05\x09\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 4) == 0); + + // free list and return 0 + numba_list_free(lp); + + // Setup list for testing delete_slice with negative step + status = numba_list_new(&lp, 1, 0); + CHECK(status == LIST_OK); + CHECK(lp->item_size == 1); + CHECK(lp->size == 0); + CHECK(lp->allocated == 0); + for (i = 0; i < 17 ; i++) { + status = numba_list_append(lp, (const char*)&i); + CHECK(status == LIST_OK); + } + CHECK(lp->size == 17); + + // delete all items using unary negative slice + status = numba_list_delete_slice(lp, 16, -1, -1); + CHECK(status == LIST_OK); + CHECK(lp->size == 0); + + // refill list + for (i = 0; i < 17 ; i++) { + status = numba_list_append(lp, (const char*)&i); + CHECK(status == LIST_OK); + } + + // delete all items using unary negative slice + // need to start at index of last item (16) and + // go beyond first item, i.e. -1 in Cd + status = numba_list_delete_slice(lp, 16, -1, -2); + CHECK(status == LIST_OK); + CHECK(lp->size == 8); + test_items_3 = "\x01\x03\x05\x07\x09\x0b\x0d\x0f"; + CHECK(memcmp(lp->items, test_items_3, 8) == 0); + + // free list and return 0 + numba_list_free(lp); + return 0; + + +} + +#undef CHECK diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.h new file mode 100644 index 0000000000000000000000000000000000000000..099840ac24c139a30055fd78c9dfc9321348b8da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/listobject.h @@ -0,0 +1,137 @@ +/* Adapted from CPython3.7 Include/listobject.h + * + * The exact commit-id of the relevant file is: + * + * https://github.com/python/cpython/blob/51ddab8dae056867f3595ab3400bffc93f67c8d4/Include/listobject.h + * + * WARNING: + * Most interfaces listed here are exported (global), but they are not + * supported, stable, or part of Numba's public API. These interfaces and their + * underlying implementations may be changed or removed in future without + * notice. + * */ + +#ifndef NUMBA_LIST_H +#define NUMBA_LIST_H + +#include "cext.h" + +typedef void (*list_refcount_op_t)(const void*); + +typedef struct { + list_refcount_op_t item_incref; + list_refcount_op_t item_decref; +} list_type_based_methods_table; + +/* This is the struct for the Numba typed list. It is largely inspired by the + * CPython list struct in listobject.h. In essence the list is a homogeneously + * typed container that can grow and shrink upon insertion and deletion. This + * means that appending an item to, or removing an item from, the end of the + * list, this will have a O(1) amortized runtime. This matches the + * behaviour of the CPython list type and it will grow with the same + * increments. + * + * 'items' contains space for 'allocated' elements. The number + * currently in use is 'size'. The size in bytes of the items stored in the + * list is given by 'item_size'. + * + * Invariants: + * 0 <= size <= allocated + * len(list) == size + * item == NULL implies size == allocated == 0 + * + * FIXME: list.sort() temporarily sets allocated to -1 to detect mutations. + * + * Items must normally not be NULL, except during construction when + * the list is not yet visible outside the function that builds it. + * + * Additionally, this list has boolean member 'is_mutable' that can be used to + * set a list as immutable. Two functions to query and set this member are + * provided. Any attempt to mutate an immutable list will result in a status + * of LIST_ERR_IMMUTABLE. + * + */ +typedef struct { + /* size of the list in items */ + Py_ssize_t size; + /* size of the list items in bytes */ + Py_ssize_t item_size; + /* total allocated slots in items */ + Py_ssize_t allocated; + /* is the list mutable */ + int is_mutable; + /* method table for type-dependent operations */ + list_type_based_methods_table methods; + /* array/pointer for items. Interpretation is governed by item_size */ + char * items; +} NB_List; + + +typedef struct { + /* parent list */ + NB_List *parent; + /* list size */ + Py_ssize_t size; + /* iterator position; indicates the next position to read */ + Py_ssize_t pos; +} NB_ListIter; + +NUMBA_GLOBAL_FUNC(void) +numba_list_set_method_table(NB_List *lp, list_type_based_methods_table *methods); + +NUMBA_GLOBAL_FUNC(int) +numba_list_new(NB_List **out, Py_ssize_t item_size, Py_ssize_t allocated); + +NUMBA_GLOBAL_FUNC(void) +numba_list_free(NB_List *lp); + +NUMBA_GLOBAL_FUNC(char *) +numba_list_base_ptr(NB_List *lp); + +NUMBA_GLOBAL_FUNC(Py_ssize_t) +numba_list_size_address(NB_List *lp); + +NUMBA_GLOBAL_FUNC(Py_ssize_t) +numba_list_length(NB_List *lp); + +NUMBA_GLOBAL_FUNC(Py_ssize_t) +numba_list_allocated(NB_List *lp); + +NUMBA_GLOBAL_FUNC(int) +numba_list_is_mutable(NB_List *lp); + +NUMBA_GLOBAL_FUNC(void) +numba_list_set_is_mutable(NB_List *lp, int is_mutable); + +NUMBA_GLOBAL_FUNC(int) +numba_list_setitem(NB_List *lp, Py_ssize_t index, const char *item); + +NUMBA_GLOBAL_FUNC(int) +numba_list_getitem(NB_List *lp, Py_ssize_t index, char *out); + +NUMBA_GLOBAL_FUNC(int) +numba_list_append(NB_List *lp, const char *item); + +NUMBA_GLOBAL_FUNC(int) +numba_list_resize(NB_List *lp, Py_ssize_t newsize); + +NUMBA_GLOBAL_FUNC(int) +numba_list_delitem(NB_List *lp, Py_ssize_t index); + +NUMBA_GLOBAL_FUNC(int) +numba_list_delete_slice(NB_List *lp, + Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step); + +NUMBA_GLOBAL_FUNC(size_t) +numba_list_iter_sizeof(void); + +NUMBA_GLOBAL_FUNC(void) +numba_list_iter(NB_ListIter *it, NB_List *l); + +NUMBA_GLOBAL_FUNC(int) +numba_list_iter_next(NB_ListIter *it, const char **item_ptr); + +NUMBA_EXPORT_FUNC(int) +numba_test_list(void); + +#endif diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/utils.c b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/utils.c new file mode 100644 index 0000000000000000000000000000000000000000..17f4992f40d1eed2573b8dbda7cbdaa0d2280f76 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cext/utils.c @@ -0,0 +1,8 @@ +#include "cext.h" + +/* Align size *sz* to pointer width */ +Py_ssize_t +aligned_size(Py_ssize_t sz) { + Py_ssize_t alignment = sizeof(void*); + return sz + (alignment - sz % alignment) % alignment; +} diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3768a936efd38d3799af95d4420457525c119a42 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/__init__.py @@ -0,0 +1,18 @@ +from . import cloudpickle +from .cloudpickle import * # noqa + +__doc__ = cloudpickle.__doc__ + +__version__ = "3.1.1" + +__all__ = [ # noqa + "__version__", + "Pickler", + "CloudPickler", + "dumps", + "loads", + "dump", + "load", + "register_pickle_by_value", + "unregister_pickle_by_value", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle.py new file mode 100644 index 0000000000000000000000000000000000000000..6f48e0026d2d98cecad0619f24824c73cf049cf1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle.py @@ -0,0 +1,1562 @@ +""" +This is a modified version of the cloudpickle module. +Patches: +- https://github.com/numba/numba/pull/7388 + Avoid resetting class state of dynamic classes. + +Original module docstring: + +Pickler class to extend the standard pickle.Pickler functionality + +The main objective is to make it natural to perform distributed computing on +clusters (such as PySpark, Dask, Ray...) with interactively defined code +(functions, classes, ...) written in notebooks or console. + +In particular this pickler adds the following features: +- serialize interactively-defined or locally-defined functions, classes, + enums, typevars, lambdas and nested functions to compiled byte code; +- deal with some other non-serializable objects in an ad-hoc manner where + applicable. + +This pickler is therefore meant to be used for the communication between short +lived Python processes running the same version of Python and libraries. In +particular, it is not meant to be used for long term storage of Python objects. + +It does not include an unpickler, as standard Python unpickling suffices. + +This module was extracted from the `cloud` package, developed by `PiCloud, Inc. +`_. + +Copyright (c) 2012-now, CloudPickle developers and contributors. +Copyright (c) 2012, Regents of the University of California. +Copyright (c) 2009 `PiCloud, Inc. `_. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the University of California, Berkeley nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import _collections_abc +from collections import ChainMap, OrderedDict +import abc +import builtins +import copyreg +import dataclasses +import dis +from enum import Enum +import io +import itertools +import logging +import opcode +import pickle +from pickle import _getattribute as _pickle_getattribute +import platform +import struct +import sys +import threading +import types +import typing +import uuid +import warnings +import weakref + +# The following import is required to be imported in the cloudpickle +# namespace to be able to load pickle files generated with older versions of +# cloudpickle. See: tests/test_backward_compat.py +from types import CellType # noqa: F401 + + +# cloudpickle is meant for inter process communication: we expect all +# communicating processes to run the same Python version hence we favor +# communication speed over compatibility: +DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL + +# Names of modules whose resources should be treated as dynamic. +_PICKLE_BY_VALUE_MODULES = set() + +# Track the provenance of reconstructed dynamic classes to make it possible to +# reconstruct instances from the matching singleton class definition when +# appropriate and preserve the usual "isinstance" semantics of Python objects. +_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary() +_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary() +_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock() +_DYNAMIC_CLASS_TRACKER_REUSING = weakref.WeakSet() + +PYPY = platform.python_implementation() == "PyPy" + +builtin_code_type = None +if PYPY: + # builtin-code objects only exist in pypy + builtin_code_type = type(float.__new__.__code__) + +_extract_code_globals_cache = weakref.WeakKeyDictionary() + + +def _get_or_create_tracker_id(class_def): + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def) + if class_tracker_id is None: + class_tracker_id = uuid.uuid4().hex + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def + return class_tracker_id + + +def _lookup_class_or_track(class_tracker_id, class_def): + if class_tracker_id is not None: + with _DYNAMIC_CLASS_TRACKER_LOCK: + orig_class_def = class_def + class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault( + class_tracker_id, class_def + ) + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + # Check if we are reusing a previous class_def + if orig_class_def is not class_def: + # Remember the class_def is being reused + _DYNAMIC_CLASS_TRACKER_REUSING.add(class_def) + return class_def + + +def register_pickle_by_value(module): + """Register a module to make its functions and classes picklable by value. + + By default, functions and classes that are attributes of an importable + module are to be pickled by reference, that is relying on re-importing + the attribute from the module at load time. + + If `register_pickle_by_value(module)` is called, all its functions and + classes are subsequently to be pickled by value, meaning that they can + be loaded in Python processes where the module is not importable. + + This is especially useful when developing a module in a distributed + execution environment: restarting the client Python process with the new + source code is enough: there is no need to re-install the new version + of the module on all the worker nodes nor to restart the workers. + + Note: this feature is considered experimental. See the cloudpickle + README.md file for more details and limitations. + """ + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + # In the future, cloudpickle may need a way to access any module registered + # for pickling by value in order to introspect relative imports inside + # functions pickled by value. (see + # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633). + # This access can be ensured by checking that module is present in + # sys.modules at registering time and assuming that it will still be in + # there when accessed during pickling. Another alternative would be to + # store a weakref to the module. Even though cloudpickle does not implement + # this introspection yet, in order to avoid a possible breaking change + # later, we still enforce the presence of module inside sys.modules. + if module.__name__ not in sys.modules: + raise ValueError( + f"{module} was not imported correctly, have you used an " + "`import` statement to access it?" + ) + _PICKLE_BY_VALUE_MODULES.add(module.__name__) + + +def unregister_pickle_by_value(module): + """Unregister that the input module should be pickled by value.""" + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + if module.__name__ not in _PICKLE_BY_VALUE_MODULES: + raise ValueError(f"{module} is not registered for pickle by value") + else: + _PICKLE_BY_VALUE_MODULES.remove(module.__name__) + + +def list_registry_pickle_by_value(): + return _PICKLE_BY_VALUE_MODULES.copy() + + +def _is_registered_pickle_by_value(module): + module_name = module.__name__ + if module_name in _PICKLE_BY_VALUE_MODULES: + return True + while True: + parent_name = module_name.rsplit(".", 1)[0] + if parent_name == module_name: + break + if parent_name in _PICKLE_BY_VALUE_MODULES: + return True + module_name = parent_name + return False + + +if sys.version_info >= (3, 14): + def _getattribute(obj, name): + return _pickle_getattribute(obj, name.split('.')) +else: + def _getattribute(obj, name): + return _pickle_getattribute(obj, name)[0] + + +def _whichmodule(obj, name): + """Find the module an object belongs to. + + This function differs from ``pickle.whichmodule`` in two ways: + - it does not mangle the cases where obj's module is __main__ and obj was + not found in any module. + - Errors arising during module introspection are ignored, as those errors + are considered unwanted side effects. + """ + module_name = getattr(obj, "__module__", None) + + if module_name is not None: + return module_name + # Protect the iteration by using a copy of sys.modules against dynamic + # modules that trigger imports of other modules upon calls to getattr or + # other threads importing at the same time. + for module_name, module in sys.modules.copy().items(): + # Some modules such as coverage can inject non-module objects inside + # sys.modules + if ( + module_name == "__main__" + or module_name == "__mp_main__" + or module is None + or not isinstance(module, types.ModuleType) + ): + continue + try: + if _getattribute(module, name) is obj: + return module_name + except Exception: + pass + return None + + +def _should_pickle_by_reference(obj, name=None): + """Test whether an function or a class should be pickled by reference + + Pickling by reference means by that the object (typically a function or a + class) is an attribute of a module that is assumed to be importable in the + target Python environment. Loading will therefore rely on importing the + module and then calling `getattr` on it to access the function or class. + + Pickling by reference is the only option to pickle functions and classes + in the standard library. In cloudpickle the alternative option is to + pickle by value (for instance for interactively or locally defined + functions and classes or for attributes of modules that have been + explicitly registered to be pickled by value. + """ + if isinstance(obj, types.FunctionType) or issubclass(type(obj), type): + module_and_name = _lookup_module_and_qualname(obj, name=name) + if module_and_name is None: + return False + module, name = module_and_name + return not _is_registered_pickle_by_value(module) + + elif isinstance(obj, types.ModuleType): + # We assume that sys.modules is primarily used as a cache mechanism for + # the Python import machinery. Checking if a module has been added in + # is sys.modules therefore a cheap and simple heuristic to tell us + # whether we can assume that a given module could be imported by name + # in another Python process. + if _is_registered_pickle_by_value(obj): + return False + return obj.__name__ in sys.modules + else: + raise TypeError( + "cannot check importability of {} instances".format(type(obj).__name__) + ) + + +def _lookup_module_and_qualname(obj, name=None): + if name is None: + name = getattr(obj, "__qualname__", None) + if name is None: # pragma: no cover + # This used to be needed for Python 2.7 support but is probably not + # needed anymore. However we keep the __name__ introspection in case + # users of cloudpickle rely on this old behavior for unknown reasons. + name = getattr(obj, "__name__", None) + + module_name = _whichmodule(obj, name) + + if module_name is None: + # In this case, obj.__module__ is None AND obj was not found in any + # imported module. obj is thus treated as dynamic. + return None + + if module_name == "__main__": + return None + + # Note: if module_name is in sys.modules, the corresponding module is + # assumed importable at unpickling time. See #357 + module = sys.modules.get(module_name, None) + if module is None: + # The main reason why obj's module would not be imported is that this + # module has been dynamically created, using for example + # types.ModuleType. The other possibility is that module was removed + # from sys.modules after obj was created/imported. But this case is not + # supported, as the standard pickle does not support it either. + return None + + try: + obj2 = _getattribute(module, name) + except AttributeError: + # obj was not found inside the module it points to + return None + if obj2 is not obj: + return None + return module, name + + +def _extract_code_globals(co): + """Find all globals names read or written to by codeblock co.""" + out_names = _extract_code_globals_cache.get(co) + if out_names is None: + # We use a dict with None values instead of a set to get a + # deterministic order and avoid introducing non-deterministic pickle + # bytes as a results. + out_names = {name: None for name in _walk_global_ops(co)} + + # Declaring a function inside another one using the "def ..." syntax + # generates a constant code object corresponding to the one of the + # nested function's As the nested function may itself need global + # variables, we need to introspect its code, extract its globals, (look + # for code object in it's co_consts attribute..) and add the result to + # code_globals + if co.co_consts: + for const in co.co_consts: + if isinstance(const, types.CodeType): + out_names.update(_extract_code_globals(const)) + + _extract_code_globals_cache[co] = out_names + + return out_names + + +def _find_imported_submodules(code, top_level_dependencies): + """Find currently imported submodules used by a function. + + Submodules used by a function need to be detected and referenced for the + function to work correctly at depickling time. Because submodules can be + referenced as attribute of their parent package (``package.submodule``), we + need a special introspection technique that does not rely on GLOBAL-related + opcodes to find references of them in a code object. + + Example: + ``` + import concurrent.futures + import cloudpickle + def func(): + x = concurrent.futures.ThreadPoolExecutor + if __name__ == '__main__': + cloudpickle.dumps(func) + ``` + The globals extracted by cloudpickle in the function's state include the + concurrent package, but not its submodule (here, concurrent.futures), which + is the module used by func. Find_imported_submodules will detect the usage + of concurrent.futures. Saving this module alongside with func will ensure + that calling func once depickled does not fail due to concurrent.futures + not being imported + """ + + subimports = [] + # check if any known dependency is an imported package + for x in top_level_dependencies: + if ( + isinstance(x, types.ModuleType) + and hasattr(x, "__package__") + and x.__package__ + ): + # check if the package has any currently loaded sub-imports + prefix = x.__name__ + "." + # A concurrent thread could mutate sys.modules, + # make sure we iterate over a copy to avoid exceptions + for name in list(sys.modules): + # Older versions of pytest will add a "None" module to + # sys.modules. + if name is not None and name.startswith(prefix): + # check whether the function can address the sub-module + tokens = set(name[len(prefix) :].split(".")) + if not tokens - set(code.co_names): + subimports.append(sys.modules[name]) + return subimports + + +# relevant opcodes +STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"] +DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"] +LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"] +GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL) +HAVE_ARGUMENT = dis.HAVE_ARGUMENT +EXTENDED_ARG = dis.EXTENDED_ARG + + +_BUILTIN_TYPE_NAMES = {} +for k, v in types.__dict__.items(): + if type(v) is type: + _BUILTIN_TYPE_NAMES[v] = k + + +def _builtin_type(name): + if name == "ClassType": # pragma: no cover + # Backward compat to load pickle files generated with cloudpickle + # < 1.3 even if loading pickle files from older versions is not + # officially supported. + return type + return getattr(types, name) + + +def _walk_global_ops(code): + """Yield referenced name for global-referencing instructions in code.""" + for instr in dis.get_instructions(code): + op = instr.opcode + if op in GLOBAL_OPS: + yield instr.argval + + +def _extract_class_dict(cls): + """Retrieve a copy of the dict of a class without the inherited method.""" + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + clsdict = {"".join(k): cls.__dict__[k] for k in sorted(cls.__dict__)} + + if len(cls.__bases__) == 1: + inherited_dict = cls.__bases__[0].__dict__ + else: + inherited_dict = {} + for base in reversed(cls.__bases__): + inherited_dict.update(base.__dict__) + to_remove = [] + for name, value in clsdict.items(): + try: + base_value = inherited_dict[name] + if value is base_value: + to_remove.append(name) + except KeyError: + pass + for name in to_remove: + clsdict.pop(name) + return clsdict + + +def is_tornado_coroutine(func): + """Return whether `func` is a Tornado coroutine function. + + Running coroutines are not supported. + """ + warnings.warn( + "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be " + "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function " + "directly instead.", + category=DeprecationWarning, + ) + if "tornado.gen" not in sys.modules: + return False + gen = sys.modules["tornado.gen"] + if not hasattr(gen, "is_coroutine_function"): + # Tornado version is too old + return False + return gen.is_coroutine_function(func) + + +def subimport(name): + # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is + # the name of a submodule, __import__ will return the top-level root module + # of this submodule. For instance, __import__('os.path') returns the `os` + # module. + __import__(name) + return sys.modules[name] + + +def dynamic_subimport(name, vars): + mod = types.ModuleType(name) + mod.__dict__.update(vars) + mod.__dict__["__builtins__"] = builtins.__dict__ + return mod + + +def _get_cell_contents(cell): + try: + return cell.cell_contents + except ValueError: + # Handle empty cells explicitly with a sentinel value. + return _empty_cell_value + + +def instance(cls): + """Create a new instance of a class. + + Parameters + ---------- + cls : type + The class to create an instance of. + + Returns + ------- + instance : cls + A new instance of ``cls``. + """ + return cls() + + +@instance +class _empty_cell_value: + """Sentinel for empty closures.""" + + @classmethod + def __reduce__(cls): + return cls.__name__ + + +def _make_function(code, globals, name, argdefs, closure): + # Setting __builtins__ in globals is needed for nogil CPython. + globals["__builtins__"] = __builtins__ + return types.FunctionType(code, globals, name, argdefs, closure) + + +def _make_empty_cell(): + if False: + # trick the compiler into creating an empty cell in our lambda + cell = None + raise AssertionError("this route should not be executed") + + return (lambda: cell).__closure__[0] + + +def _make_cell(value=_empty_cell_value): + cell = _make_empty_cell() + if value is not _empty_cell_value: + cell.cell_contents = value + return cell + + +def _make_skeleton_class( + type_constructor, name, bases, type_kwargs, class_tracker_id, extra +): + """Build dynamic class with an empty __dict__ to be filled once memoized + + If class_tracker_id is not None, try to lookup an existing class definition + matching that id. If none is found, track a newly reconstructed class + definition under that id so that other instances stemming from the same + class id will also reuse this class definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # We need to intern the keys of the type_kwargs dict to avoid having + # different pickles for the same dynamic class depending on whether it was + # dynamically created or reconstructed from a pickled stream. + type_kwargs = {sys.intern(k): v for k, v in type_kwargs.items()} + + skeleton_class = types.new_class( + name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs) + ) + + return _lookup_class_or_track(class_tracker_id, skeleton_class) + + +def _make_skeleton_enum( + bases, name, qualname, members, module, class_tracker_id, extra +): + """Build dynamic enum with an empty __dict__ to be filled once memoized + + The creation of the enum class is inspired by the code of + EnumMeta._create_. + + If class_tracker_id is not None, try to lookup an existing enum definition + matching that id. If none is found, track a newly reconstructed enum + definition under that id so that other instances stemming from the same + class id will also reuse this enum definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # enums always inherit from their base Enum class at the last position in + # the list of base classes: + enum_base = bases[-1] + metacls = enum_base.__class__ + classdict = metacls.__prepare__(name, bases) + + for member_name, member_value in members.items(): + classdict[member_name] = member_value + enum_class = metacls.__new__(metacls, name, bases, classdict) + enum_class.__module__ = module + enum_class.__qualname__ = qualname + + return _lookup_class_or_track(class_tracker_id, enum_class) + + +def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id): + tv = typing.TypeVar( + name, + *constraints, + bound=bound, + covariant=covariant, + contravariant=contravariant, + ) + return _lookup_class_or_track(class_tracker_id, tv) + + +def _decompose_typevar(obj): + return ( + obj.__name__, + obj.__bound__, + obj.__constraints__, + obj.__covariant__, + obj.__contravariant__, + _get_or_create_tracker_id(obj), + ) + + +def _typevar_reduce(obj): + # TypeVar instances require the module information hence why we + # are not using the _should_pickle_by_reference directly + module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__) + + if module_and_name is None: + return (_make_typevar, _decompose_typevar(obj)) + elif _is_registered_pickle_by_value(module_and_name[0]): + return (_make_typevar, _decompose_typevar(obj)) + + return (getattr, module_and_name) + + +def _get_bases(typ): + if "__orig_bases__" in getattr(typ, "__dict__", {}): + # For generic types (see PEP 560) + # Note that simply checking `hasattr(typ, '__orig_bases__')` is not + # correct. Subclasses of a fully-parameterized generic class does not + # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')` + # will return True because it's defined in the base class. + bases_attr = "__orig_bases__" + else: + # For regular class objects + bases_attr = "__bases__" + return getattr(typ, bases_attr) + + +def _make_dict_keys(obj, is_ordered=False): + if is_ordered: + return OrderedDict.fromkeys(obj).keys() + else: + return dict.fromkeys(obj).keys() + + +def _make_dict_values(obj, is_ordered=False): + if is_ordered: + return OrderedDict((i, _) for i, _ in enumerate(obj)).values() + else: + return {i: _ for i, _ in enumerate(obj)}.values() + + +def _make_dict_items(obj, is_ordered=False): + if is_ordered: + return OrderedDict(obj).items() + else: + return obj.items() + + +# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS +# ------------------------------------------------- + + +def _class_getnewargs(obj): + type_kwargs = {} + if "__module__" in obj.__dict__: + type_kwargs["__module__"] = obj.__module__ + + __dict__ = obj.__dict__.get("__dict__", None) + if isinstance(__dict__, property): + type_kwargs["__dict__"] = __dict__ + + return ( + type(obj), + obj.__name__, + _get_bases(obj), + type_kwargs, + _get_or_create_tracker_id(obj), + None, + ) + + +def _enum_getnewargs(obj): + members = {e.name: e.value for e in obj} + return ( + obj.__bases__, + obj.__name__, + obj.__qualname__, + members, + obj.__module__, + _get_or_create_tracker_id(obj), + None, + ) + + +# COLLECTION OF OBJECTS RECONSTRUCTORS +# ------------------------------------ +def _file_reconstructor(retval): + return retval + + +# COLLECTION OF OBJECTS STATE GETTERS +# ----------------------------------- + + +def _function_getstate(func): + # - Put func's dynamic attributes (stored in func.__dict__) in state. These + # attributes will be restored at unpickling time using + # f.__dict__.update(state) + # - Put func's members into slotstate. Such attributes will be restored at + # unpickling time by iterating over slotstate and calling setattr(func, + # slotname, slotvalue) + slotstate = { + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + "__name__": "".join(func.__name__), + "__qualname__": "".join(func.__qualname__), + "__annotations__": func.__annotations__, + "__kwdefaults__": func.__kwdefaults__, + "__defaults__": func.__defaults__, + "__module__": func.__module__, + "__doc__": func.__doc__, + "__closure__": func.__closure__, + } + + f_globals_ref = _extract_code_globals(func.__code__) + f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__} + + if func.__closure__ is not None: + closure_values = list(map(_get_cell_contents, func.__closure__)) + else: + closure_values = () + + # Extract currently-imported submodules used by func. Storing these modules + # in a smoke _cloudpickle_subimports attribute of the object's state will + # trigger the side effect of importing these modules at unpickling time + # (which is necessary for func to work correctly once depickled) + slotstate["_cloudpickle_submodules"] = _find_imported_submodules( + func.__code__, itertools.chain(f_globals.values(), closure_values) + ) + slotstate["__globals__"] = f_globals + + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + state = {"".join(k): v for k, v in func.__dict__.items()} + return state, slotstate + + +def _class_getstate(obj): + clsdict = _extract_class_dict(obj) + clsdict.pop("__weakref__", None) + + if issubclass(type(obj), abc.ABCMeta): + # If obj is an instance of an ABCMeta subclass, don't pickle the + # cache/negative caches populated during isinstance/issubclass + # checks, but pickle the list of registered subclasses of obj. + clsdict.pop("_abc_cache", None) + clsdict.pop("_abc_negative_cache", None) + clsdict.pop("_abc_negative_cache_version", None) + registry = clsdict.pop("_abc_registry", None) + if registry is None: + # The abc caches and registered subclasses of a + # class are bundled into the single _abc_impl attribute + clsdict.pop("_abc_impl", None) + (registry, _, _, _) = abc._get_dump(obj) + + clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry] + else: + # In the above if clause, registry is a set of weakrefs -- in + # this case, registry is a WeakSet + clsdict["_abc_impl"] = [type_ for type_ in registry] + + if "__slots__" in clsdict: + # pickle string length optimization: member descriptors of obj are + # created automatically from obj's __slots__ attribute, no need to + # save them in obj's state + if isinstance(obj.__slots__, str): + clsdict.pop(obj.__slots__) + else: + for k in obj.__slots__: + clsdict.pop(k, None) + + clsdict.pop("__dict__", None) # unpicklable property object + + return (clsdict, {}) + + +def _enum_getstate(obj): + clsdict, slotstate = _class_getstate(obj) + + members = {e.name: e.value for e in obj} + # Cleanup the clsdict that will be passed to _make_skeleton_enum: + # Those attributes are already handled by the metaclass. + for attrname in [ + "_generate_next_value_", + "_member_names_", + "_member_map_", + "_member_type_", + "_value2member_map_", + ]: + clsdict.pop(attrname, None) + for member in members: + clsdict.pop(member) + # Special handling of Enum subclasses + return clsdict, slotstate + + +# COLLECTIONS OF OBJECTS REDUCERS +# ------------------------------- +# A reducer is a function taking a single argument (obj), and that returns a +# tuple with all the necessary data to re-construct obj. Apart from a few +# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to +# correctly pickle an object. +# While many built-in objects (Exceptions objects, instances of the "object" +# class, etc), are shipped with their own built-in reducer (invoked using +# obj.__reduce__), some do not. The following methods were created to "fill +# these holes". + + +def _code_reduce(obj): + """code object reducer.""" + # If you are not sure about the order of arguments, take a look at help + # of the specific type from types, for example: + # >>> from types import CodeType + # >>> help(CodeType) + + # Hack to circumvent non-predictable memoization caused by string interning. + # See the inline comment in _class_setstate for details. + co_name = "".join(obj.co_name) + + # Create shallow copies of these tuple to make cloudpickle payload deterministic. + # When creating a code object during load, copies of these four tuples are + # created, while in the main process, these tuples can be shared. + # By always creating copies, we make sure the resulting payload is deterministic. + co_names = tuple(name for name in obj.co_names) + co_varnames = tuple(name for name in obj.co_varnames) + co_freevars = tuple(name for name in obj.co_freevars) + co_cellvars = tuple(name for name in obj.co_cellvars) + if hasattr(obj, "co_exceptiontable"): + # Python 3.11 and later: there are some new attributes + # related to the enhanced exceptions. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_qualname, + obj.co_firstlineno, + obj.co_linetable, + obj.co_exceptiontable, + co_freevars, + co_cellvars, + ) + elif hasattr(obj, "co_linetable"): + # Python 3.10 and later: obj.co_lnotab is deprecated and constructor + # expects obj.co_linetable instead. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_linetable, + co_freevars, + co_cellvars, + ) + elif hasattr(obj, "co_nmeta"): # pragma: no cover + # "nogil" Python: modified attributes from 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_framesize, + obj.co_ndefaultargs, + obj.co_nmeta, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_exc_handlers, + obj.co_jump_table, + co_freevars, + co_cellvars, + obj.co_free2reg, + obj.co_cell2reg, + ) + else: + # Backward compat for 3.8 and 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + co_names, + co_varnames, + obj.co_filename, + co_name, + obj.co_firstlineno, + obj.co_lnotab, + co_freevars, + co_cellvars, + ) + return types.CodeType, args + + +def _cell_reduce(obj): + """Cell (containing values of a function's free variables) reducer.""" + try: + obj.cell_contents + except ValueError: # cell is empty + return _make_empty_cell, () + else: + return _make_cell, (obj.cell_contents,) + + +def _classmethod_reduce(obj): + orig_func = obj.__func__ + return type(obj), (orig_func,) + + +def _file_reduce(obj): + """Save a file.""" + import io + + if not hasattr(obj, "name") or not hasattr(obj, "mode"): + raise pickle.PicklingError( + "Cannot pickle files that do not map to an actual file" + ) + if obj is sys.stdout: + return getattr, (sys, "stdout") + if obj is sys.stderr: + return getattr, (sys, "stderr") + if obj is sys.stdin: + raise pickle.PicklingError("Cannot pickle standard input") + if obj.closed: + raise pickle.PicklingError("Cannot pickle closed files") + if hasattr(obj, "isatty") and obj.isatty(): + raise pickle.PicklingError("Cannot pickle files that map to tty objects") + if "r" not in obj.mode and "+" not in obj.mode: + raise pickle.PicklingError( + "Cannot pickle files that are not opened for reading: %s" % obj.mode + ) + + name = obj.name + + retval = io.StringIO() + + try: + # Read the whole file + curloc = obj.tell() + obj.seek(0) + contents = obj.read() + obj.seek(curloc) + except OSError as e: + raise pickle.PicklingError( + "Cannot pickle file %s as it cannot be read" % name + ) from e + retval.write(contents) + retval.seek(curloc) + + retval.name = name + return _file_reconstructor, (retval,) + + +def _getset_descriptor_reduce(obj): + return getattr, (obj.__objclass__, obj.__name__) + + +def _mappingproxy_reduce(obj): + return types.MappingProxyType, (dict(obj),) + + +def _memoryview_reduce(obj): + return bytes, (obj.tobytes(),) + + +def _module_reduce(obj): + if _should_pickle_by_reference(obj): + return subimport, (obj.__name__,) + else: + # Some external libraries can populate the "__builtins__" entry of a + # module's `__dict__` with unpicklable objects (see #316). For that + # reason, we do not attempt to pickle the "__builtins__" entry, and + # restore a default value for it at unpickling time. + state = obj.__dict__.copy() + state.pop("__builtins__", None) + return dynamic_subimport, (obj.__name__, state) + + +def _method_reduce(obj): + return (types.MethodType, (obj.__func__, obj.__self__)) + + +def _logger_reduce(obj): + return logging.getLogger, (obj.name,) + + +def _root_logger_reduce(obj): + return logging.getLogger, () + + +def _property_reduce(obj): + return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__) + + +def _weakset_reduce(obj): + return weakref.WeakSet, (list(obj),) + + +def _dynamic_class_reduce(obj): + """Save a class that can't be referenced as a module attribute. + + This method is used to serialize classes that are defined inside + functions, or that otherwise can't be serialized as attribute lookups + from importable modules. + """ + if Enum is not None and issubclass(obj, Enum): + return ( + _make_skeleton_enum, + _enum_getnewargs(obj), + _enum_getstate(obj), + None, + None, + _class_setstate, + ) + else: + return ( + _make_skeleton_class, + _class_getnewargs(obj), + _class_getstate(obj), + None, + None, + _class_setstate, + ) + + +def _class_reduce(obj): + """Select the reducer depending on the dynamic nature of the class obj.""" + if obj is type(None): # noqa + return type, (None,) + elif obj is type(Ellipsis): + return type, (Ellipsis,) + elif obj is type(NotImplemented): + return type, (NotImplemented,) + elif obj in _BUILTIN_TYPE_NAMES: + return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],) + elif not _should_pickle_by_reference(obj): + return _dynamic_class_reduce(obj) + return NotImplemented + + +def _dict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj),) + + +def _dict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj),) + + +def _dict_items_reduce(obj): + return _make_dict_items, (dict(obj),) + + +def _odict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj), True) + + +def _odict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj), True) + + +def _odict_items_reduce(obj): + return _make_dict_items, (dict(obj), True) + + +def _dataclass_field_base_reduce(obj): + return _get_dataclass_field_type_sentinel, (obj.name,) + + +# COLLECTIONS OF OBJECTS STATE SETTERS +# ------------------------------------ +# state setters are called at unpickling time, once the object is created and +# it has to be updated to how it was at unpickling time. + + +def _function_setstate(obj, state): + """Update the state of a dynamic function. + + As __closure__ and __globals__ are readonly attributes of a function, we + cannot rely on the native setstate routine of pickle.load_build, that calls + setattr on items of the slotstate. Instead, we have to modify them inplace. + """ + state, slotstate = state + obj.__dict__.update(state) + + obj_globals = slotstate.pop("__globals__") + obj_closure = slotstate.pop("__closure__") + # _cloudpickle_subimports is a set of submodules that must be loaded for + # the pickled function to work correctly at unpickling time. Now that these + # submodules are depickled (hence imported), they can be removed from the + # object's state (the object state only served as a reference holder to + # these submodules) + slotstate.pop("_cloudpickle_submodules") + + obj.__globals__.update(obj_globals) + obj.__globals__["__builtins__"] = __builtins__ + + if obj_closure is not None: + for i, cell in enumerate(obj_closure): + try: + value = cell.cell_contents + except ValueError: # cell is empty + continue + obj.__closure__[i].cell_contents = value + + for k, v in slotstate.items(): + setattr(obj, k, v) + + +def _class_setstate(obj, state): + # Check if class is being reused and needs bypass setstate logic. + if obj in _DYNAMIC_CLASS_TRACKER_REUSING: + return obj + state, slotstate = state + registry = None + for attrname, attr in state.items(): + if attrname == "_abc_impl": + registry = attr + else: + # Note: setting attribute names on a class automatically triggers their + # interning in CPython: + # https://github.com/python/cpython/blob/v3.12.0/Objects/object.c#L957 + # + # This means that to get deterministic pickling for a dynamic class that + # was initially defined in a different Python process, the pickler + # needs to ensure that dynamic class and function attribute names are + # systematically copied into a non-interned version to avoid + # unpredictable pickle payloads. + # + # Indeed the Pickler's memoizer relies on physical object identity to break + # cycles in the reference graph of the object being serialized. + setattr(obj, attrname, attr) + + if sys.version_info >= (3, 13) and "__firstlineno__" in state: + # Set the Python 3.13+ only __firstlineno__ attribute one more time, as it + # will be automatically deleted by the `setattr(obj, attrname, attr)` call + # above when `attrname` is "__firstlineno__". We assume that preserving this + # information might be important for some users and that it not stale in the + # context of cloudpickle usage, hence legitimate to propagate. Furthermore it + # is necessary to do so to keep deterministic chained pickling as tested in + # test_deterministic_str_interning_for_chained_dynamic_class_pickling. + obj.__firstlineno__ = state["__firstlineno__"] + + if registry is not None: + for subclass in registry: + obj.register(subclass) + + return obj + + +# COLLECTION OF DATACLASS UTILITIES +# --------------------------------- +# There are some internal sentinel values whose identity must be preserved when +# unpickling dataclass fields. Each sentinel value has a unique name that we can +# use to retrieve its identity at unpickling time. + + +_DATACLASSE_FIELD_TYPE_SENTINELS = { + dataclasses._FIELD.name: dataclasses._FIELD, + dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR, + dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR, +} + + +def _get_dataclass_field_type_sentinel(name): + return _DATACLASSE_FIELD_TYPE_SENTINELS[name] + + +class Pickler(pickle.Pickler): + # set of reducers defined and used by cloudpickle (private) + _dispatch_table = {} + _dispatch_table[classmethod] = _classmethod_reduce + _dispatch_table[io.TextIOWrapper] = _file_reduce + _dispatch_table[logging.Logger] = _logger_reduce + _dispatch_table[logging.RootLogger] = _root_logger_reduce + _dispatch_table[memoryview] = _memoryview_reduce + _dispatch_table[property] = _property_reduce + _dispatch_table[staticmethod] = _classmethod_reduce + _dispatch_table[CellType] = _cell_reduce + _dispatch_table[types.CodeType] = _code_reduce + _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce + _dispatch_table[types.ModuleType] = _module_reduce + _dispatch_table[types.MethodType] = _method_reduce + _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce + _dispatch_table[weakref.WeakSet] = _weakset_reduce + _dispatch_table[typing.TypeVar] = _typevar_reduce + _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce + _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce + _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce + _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce + _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce + _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce + _dispatch_table[abc.abstractmethod] = _classmethod_reduce + _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce + _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce + _dispatch_table[abc.abstractproperty] = _property_reduce + _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce + + dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table) + + # function reducers are defined as instance methods of cloudpickle.Pickler + # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref) + def _dynamic_function_reduce(self, func): + """Reduce a function that is not pickleable via attribute lookup.""" + newargs = self._function_getnewargs(func) + state = _function_getstate(func) + return (_make_function, newargs, state, None, None, _function_setstate) + + def _function_reduce(self, obj): + """Reducer for function objects. + + If obj is a top-level attribute of a file-backed module, this reducer + returns NotImplemented, making the cloudpickle.Pickler fall back to + traditional pickle.Pickler routines to save obj. Otherwise, it reduces + obj using a custom cloudpickle reducer designed specifically to handle + dynamic functions. + """ + if _should_pickle_by_reference(obj): + return NotImplemented + else: + return self._dynamic_function_reduce(obj) + + def _function_getnewargs(self, func): + code = func.__code__ + + # base_globals represents the future global namespace of func at + # unpickling time. Looking it up and storing it in + # cloudpickle.Pickler.globals_ref allow functions sharing the same + # globals at pickling time to also share them once unpickled, at one + # condition: since globals_ref is an attribute of a cloudpickle.Pickler + # instance, and that a new cloudpickle.Pickler is created each time + # cloudpickle.dump or cloudpickle.dumps is called, functions also need + # to be saved within the same invocation of + # cloudpickle.dump/cloudpickle.dumps (for example: + # cloudpickle.dumps([f1, f2])). There is no such limitation when using + # cloudpickle.Pickler.dump, as long as the multiple invocations are + # bound to the same cloudpickle.Pickler instance. + base_globals = self.globals_ref.setdefault(id(func.__globals__), {}) + + if base_globals == {}: + # Add module attributes used to resolve relative imports + # instructions inside func. + for k in ["__package__", "__name__", "__path__", "__file__"]: + if k in func.__globals__: + base_globals[k] = func.__globals__[k] + + # Do not bind the free variables before the function is created to + # avoid infinite recursion. + if func.__closure__ is None: + closure = None + else: + closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars))) + + return code, base_globals, None, None, closure + + def dump(self, obj): + try: + return super().dump(obj) + except RuntimeError as e: + if len(e.args) > 0 and "recursion" in e.args[0]: + msg = "Could not pickle object as excessively deep recursion required." + raise pickle.PicklingError(msg) from e + else: + raise + + def __init__(self, file, protocol=None, buffer_callback=None): + if protocol is None: + protocol = DEFAULT_PROTOCOL + super().__init__(file, protocol=protocol, buffer_callback=buffer_callback) + # map functions __globals__ attribute ids, to ensure that functions + # sharing the same global namespace at pickling time also share + # their global namespace at unpickling time. + self.globals_ref = {} + self.proto = int(protocol) + + if not PYPY: + # pickle.Pickler is the C implementation of the CPython pickler and + # therefore we rely on reduce_override method to customize the pickler + # behavior. + + # `cloudpickle.Pickler.dispatch` is only left for backward + # compatibility - note that when using protocol 5, + # `cloudpickle.Pickler.dispatch` is not an extension of + # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler` + # subclasses the C-implemented `pickle.Pickler`, which does not expose + # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler` + # used `cloudpickle.Pickler.dispatch` as a class-level attribute + # storing all reducers implemented by cloudpickle, but the attribute + # name was not a great choice given because it would collide with a + # similarly named attribute in the pure-Python `pickle._Pickler` + # implementation in the standard library. + dispatch = dispatch_table + + # Implementation of the reducer_override callback, in order to + # efficiently serialize dynamic functions and classes by subclassing + # the C-implemented `pickle.Pickler`. + # TODO: decorrelate reducer_override (which is tied to CPython's + # implementation - would it make sense to backport it to pypy? - and + # pickle's protocol 5 which is implementation agnostic. Currently, the + # availability of both notions coincide on CPython's pickle, but it may + # not be the case anymore when pypy implements protocol 5. + + def reducer_override(self, obj): + """Type-agnostic reducing callback for function and classes. + + For performance reasons, subclasses of the C `pickle.Pickler` class + cannot register custom reducers for functions and classes in the + dispatch_table attribute. Reducers for such types must instead + implemented via the special `reducer_override` method. + + Note that this method will be called for any object except a few + builtin-types (int, lists, dicts etc.), which differs from reducers + in the Pickler's dispatch_table, each of them being invoked for + objects of a specific type only. + + This property comes in handy for classes: although most classes are + instances of the ``type`` metaclass, some of them can be instances + of other custom metaclasses (such as enum.EnumMeta for example). In + particular, the metaclass will likely not be known in advance, and + thus cannot be special-cased using an entry in the dispatch_table. + reducer_override, among other things, allows us to register a + reducer that will be called for any class, independently of its + type. + + Notes: + + * reducer_override has the priority over dispatch_table-registered + reducers. + * reducer_override can be used to fix other limitations of + cloudpickle for other types that suffered from type-specific + reducers, such as Exceptions. See + https://github.com/cloudpipe/cloudpickle/issues/248 + """ + t = type(obj) + try: + is_anyclass = issubclass(t, type) + except TypeError: # t is not a class (old Boost; see SF #502085) + is_anyclass = False + + if is_anyclass: + return _class_reduce(obj) + elif isinstance(obj, types.FunctionType): + return self._function_reduce(obj) + else: + # fallback to save_global, including the Pickler's + # dispatch_table + return NotImplemented + + else: + # When reducer_override is not available, hack the pure-Python + # Pickler's types.FunctionType and type savers. Note: the type saver + # must override Pickler.save_global, because pickle.py contains a + # hard-coded call to save_global when pickling meta-classes. + dispatch = pickle.Pickler.dispatch.copy() + + def _save_reduce_pickle5( + self, + func, + args, + state=None, + listitems=None, + dictitems=None, + state_setter=None, + obj=None, + ): + save = self.save + write = self.write + self.save_reduce( + func, + args, + state=None, + listitems=listitems, + dictitems=dictitems, + obj=obj, + ) + # backport of the Python 3.8 state_setter pickle operations + save(state_setter) + save(obj) # simple BINGET opcode as obj is already memoized. + save(state) + write(pickle.TUPLE2) + # Trigger a state_setter(obj, state) function call. + write(pickle.REDUCE) + # The purpose of state_setter is to carry-out an + # inplace modification of obj. We do not care about what the + # method might return, so its output is eventually removed from + # the stack. + write(pickle.POP) + + def save_global(self, obj, name=None, pack=struct.pack): + """Main dispatch method. + + The name of this method is somewhat misleading: all types get + dispatched here. + """ + if obj is type(None): # noqa + return self.save_reduce(type, (None,), obj=obj) + elif obj is type(Ellipsis): + return self.save_reduce(type, (Ellipsis,), obj=obj) + elif obj is type(NotImplemented): + return self.save_reduce(type, (NotImplemented,), obj=obj) + elif obj in _BUILTIN_TYPE_NAMES: + return self.save_reduce( + _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj + ) + + if name is not None: + super().save_global(obj, name=name) + elif not _should_pickle_by_reference(obj, name=name): + self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj) + else: + super().save_global(obj, name=name) + + dispatch[type] = save_global + + def save_function(self, obj, name=None): + """Registered with the dispatch to handle all function types. + + Determines what kind of function obj is (e.g. lambda, defined at + interactive prompt, etc) and handles the pickling appropriately. + """ + if _should_pickle_by_reference(obj, name=name): + return super().save_global(obj, name=name) + elif PYPY and isinstance(obj.__code__, builtin_code_type): + return self.save_pypy_builtin_func(obj) + else: + return self._save_reduce_pickle5( + *self._dynamic_function_reduce(obj), obj=obj + ) + + def save_pypy_builtin_func(self, obj): + """Save pypy equivalent of builtin functions. + + PyPy does not have the concept of builtin-functions. Instead, + builtin-functions are simple function instances, but with a + builtin-code attribute. + Most of the time, builtin functions should be pickled by attribute. + But PyPy has flaky support for __qualname__, so some builtin + functions such as float.__new__ will be classified as dynamic. For + this reason only, we created this special routine. Because + builtin-functions are not expected to have closure or globals, + there is no additional hack (compared the one already implemented + in pickle) to protect ourselves from reference cycles. A simple + (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note + also that PyPy improved their support for __qualname__ in v3.6, so + this routing should be removed when cloudpickle supports only PyPy + 3.6 and later. + """ + rv = ( + types.FunctionType, + (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), + obj.__dict__, + ) + self.save_reduce(*rv, obj=obj) + + dispatch[types.FunctionType] = save_function + + +# Shorthands similar to pickle.dump/pickle.dumps + + +def dump(obj, file, protocol=None, buffer_callback=None): + """Serialize obj as bytes streamed into file + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj) + + +def dumps(obj, protocol=None, buffer_callback=None): + """Serialize obj as a string of bytes allocated in memory + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + with io.BytesIO() as file: + cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback) + cp.dump(obj) + return file.getvalue() + + +# Include pickles unloading functions in this namespace for convenience. +load, loads = pickle.load, pickle.loads + +# Backward compat alias. +CloudPickler = Pickler diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle_fast.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..20280f0ca354a691861ab6f17821bbeb04632003 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cloudpickle/cloudpickle_fast.py @@ -0,0 +1,14 @@ +"""Compatibility module. + +It can be necessary to load files generated by previous versions of cloudpickle +that rely on symbols being defined under the `cloudpickle.cloudpickle_fast` +namespace. + +See: tests/test_backward_compat.py +""" + +from . import cloudpickle + + +def __getattr__(name): + return getattr(cloudpickle, name) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6691b5bb7c4a221ab9419ca606d598f7b3f012 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/analysis.py @@ -0,0 +1,726 @@ +""" +Utils for IR analysis +""" +import operator +from functools import reduce +from collections import namedtuple, defaultdict + +from .controlflow import CFGraph +from numba.core import types, errors, ir, consts +from numba.misc import special + +# +# Analysis related to variable lifetime +# + +_use_defs_result = namedtuple('use_defs_result', 'usemap,defmap') + +# other packages that define new nodes add calls for finding defs +# format: {type:function} +ir_extension_usedefs = {} + + +def compute_use_defs(blocks): + """ + Find variable use/def per block. + """ + + var_use_map = {} # { block offset -> set of vars } + var_def_map = {} # { block offset -> set of vars } + for offset, ir_block in blocks.items(): + var_use_map[offset] = use_set = set() + var_def_map[offset] = def_set = set() + for stmt in ir_block.body: + if type(stmt) in ir_extension_usedefs: + func = ir_extension_usedefs[type(stmt)] + func(stmt, use_set, def_set) + continue + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, ir.Inst): + rhs_set = set(var.name for var in stmt.value.list_vars()) + elif isinstance(stmt.value, ir.Var): + rhs_set = set([stmt.value.name]) + elif isinstance(stmt.value, (ir.Arg, ir.Const, ir.Global, + ir.FreeVar)): + rhs_set = () + else: + raise AssertionError('unreachable', type(stmt.value)) + # If lhs not in rhs of the assignment + if stmt.target.name not in rhs_set: + def_set.add(stmt.target.name) + + for var in stmt.list_vars(): + # do not include locally defined vars to use-map + if var.name not in def_set: + use_set.add(var.name) + + return _use_defs_result(usemap=var_use_map, defmap=var_def_map) + + +def compute_live_map(cfg, blocks, var_use_map, var_def_map): + """ + Find variables that must be alive at the ENTRY of each block. + We use a simple fix-point algorithm that iterates until the set of + live variables is unchanged for each block. + """ + def fix_point_progress(dct): + """Helper function to determine if a fix-point has been reached. + """ + return tuple(len(v) for v in dct.values()) + + def fix_point(fn, dct): + """Helper function to run fix-point algorithm. + """ + old_point = None + new_point = fix_point_progress(dct) + while old_point != new_point: + fn(dct) + old_point = new_point + new_point = fix_point_progress(dct) + + def def_reach(dct): + """Find all variable definition reachable at the entry of a block + """ + for offset in var_def_map: + used_or_defined = var_def_map[offset] | var_use_map[offset] + dct[offset] |= used_or_defined + # Propagate to outgoing nodes + for out_blk, _ in cfg.successors(offset): + dct[out_blk] |= dct[offset] + + def liveness(dct): + """Find live variables. + + Push var usage backward. + """ + for offset in dct: + # Live vars here + live_vars = dct[offset] + for inc_blk, _data in cfg.predecessors(offset): + # Reachable at the predecessor + reachable = live_vars & def_reach_map[inc_blk] + # But not defined in the predecessor + dct[inc_blk] |= reachable - var_def_map[inc_blk] + + live_map = {} + for offset in blocks.keys(): + live_map[offset] = set(var_use_map[offset]) + + def_reach_map = defaultdict(set) + fix_point(def_reach, def_reach_map) + fix_point(liveness, live_map) + return live_map + + +_dead_maps_result = namedtuple('dead_maps_result', 'internal,escaping,combined') + + +def compute_dead_maps(cfg, blocks, live_map, var_def_map): + """ + Compute the end-of-live information for variables. + `live_map` contains a mapping of block offset to all the living + variables at the ENTRY of the block. + """ + # The following three dictionaries will be + # { block offset -> set of variables to delete } + # all vars that should be deleted at the start of the successors + escaping_dead_map = defaultdict(set) + # all vars that should be deleted within this block + internal_dead_map = defaultdict(set) + # all vars that should be deleted after the function exit + exit_dead_map = defaultdict(set) + + for offset, ir_block in blocks.items(): + # live vars WITHIN the block will include all the locally + # defined variables + cur_live_set = live_map[offset] | var_def_map[offset] + # vars alive in the outgoing blocks + outgoing_live_map = dict((out_blk, live_map[out_blk]) + for out_blk, _data in cfg.successors(offset)) + # vars to keep alive for the terminator + terminator_liveset = set(v.name + for v in ir_block.terminator.list_vars()) + # vars to keep alive in the successors + combined_liveset = reduce(operator.or_, outgoing_live_map.values(), + set()) + # include variables used in terminator + combined_liveset |= terminator_liveset + # vars that are dead within the block because they are not + # propagated to any outgoing blocks + internal_set = cur_live_set - combined_liveset + internal_dead_map[offset] = internal_set + # vars that escape this block + escaping_live_set = cur_live_set - internal_set + for out_blk, new_live_set in outgoing_live_map.items(): + # successor should delete the unused escaped vars + new_live_set = new_live_set | var_def_map[out_blk] + escaping_dead_map[out_blk] |= escaping_live_set - new_live_set + + # if no outgoing blocks + if not outgoing_live_map: + # insert var used by terminator + exit_dead_map[offset] = terminator_liveset + + # Verify that the dead maps cover all live variables + all_vars = reduce(operator.or_, live_map.values(), set()) + internal_dead_vars = reduce(operator.or_, internal_dead_map.values(), + set()) + escaping_dead_vars = reduce(operator.or_, escaping_dead_map.values(), + set()) + exit_dead_vars = reduce(operator.or_, exit_dead_map.values(), set()) + dead_vars = (internal_dead_vars | escaping_dead_vars | exit_dead_vars) + missing_vars = all_vars - dead_vars + if missing_vars: + # There are no exit points + if not cfg.exit_points(): + # We won't be able to verify this + pass + else: + msg = 'liveness info missing for vars: {0}'.format(missing_vars) + raise RuntimeError(msg) + + combined = dict((k, internal_dead_map[k] | escaping_dead_map[k]) + for k in blocks) + + return _dead_maps_result(internal=internal_dead_map, + escaping=escaping_dead_map, + combined=combined) + + +def compute_live_variables(cfg, blocks, var_def_map, var_dead_map): + """ + Compute the live variables at the beginning of each block + and at each yield point. + The ``var_def_map`` and ``var_dead_map`` indicates the variable defined + and deleted at each block, respectively. + """ + # live var at the entry per block + block_entry_vars = defaultdict(set) + + def fix_point_progress(): + return tuple(map(len, block_entry_vars.values())) + + old_point = None + new_point = fix_point_progress() + + # Propagate defined variables and still live the successors. + # (note the entry block automatically gets an empty set) + + # Note: This is finding the actual available variables at the entry + # of each block. The algorithm in compute_live_map() is finding + # the variable that must be available at the entry of each block. + # This is top-down in the dataflow. The other one is bottom-up. + while old_point != new_point: + # We iterate until the result stabilizes. This is necessary + # because of loops in the graphself. + for offset in blocks: + # vars available + variable defined + avail = block_entry_vars[offset] | var_def_map[offset] + # subtract variables deleted + avail -= var_dead_map[offset] + # add ``avail`` to each successors + for succ, _data in cfg.successors(offset): + block_entry_vars[succ] |= avail + + old_point = new_point + new_point = fix_point_progress() + + return block_entry_vars + + +# +# Analysis related to controlflow +# + +def compute_cfg_from_blocks(blocks): + cfg = CFGraph() + for k in blocks: + cfg.add_node(k) + + for k, b in blocks.items(): + term = b.terminator + for target in term.get_targets(): + cfg.add_edge(k, target) + + cfg.set_entry_point(min(blocks)) + cfg.process() + return cfg + + +def find_top_level_loops(cfg): + """ + A generator that yields toplevel loops given a control-flow-graph + """ + blocks_in_loop = set() + # get loop bodies + for loop in cfg.loops().values(): + insiders = set(loop.body) | set(loop.entries) | set(loop.exits) + insiders.discard(loop.header) + blocks_in_loop |= insiders + # find loop that is not part of other loops + for loop in cfg.loops().values(): + if loop.header not in blocks_in_loop: + yield _fix_loop_exit(cfg, loop) + + +def _fix_loop_exit(cfg, loop): + """ + Fixes loop.exits for Py3.8+ bytecode CFG changes. + This is to handle `break` inside loops. + """ + # Computes the common postdoms of exit nodes + postdoms = cfg.post_dominators() + exits = reduce( + operator.and_, + [postdoms[b] for b in loop.exits], + loop.exits, + ) + if exits: + # Put the non-common-exits as body nodes + body = loop.body | loop.exits - exits + return loop._replace(exits=exits, body=body) + else: + return loop + + +# Used to describe a nullified condition in dead branch pruning +nullified = namedtuple('nullified', 'condition, taken_br, rewrite_stmt') + + +# Functions to manipulate IR +def dead_branch_prune(func_ir, called_args): + """ + Removes dead branches based on constant inference from function args. + This directly mutates the IR. + + func_ir is the IR + called_args are the actual arguments with which the function is called + """ + from numba.core.ir_utils import (get_definition, guard, find_const, + GuardException) + + DEBUG = 0 + + def find_branches(func_ir): + # find *all* branches + branches = [] + for blk in func_ir.blocks.values(): + branch_or_jump = blk.body[-1] + if isinstance(branch_or_jump, ir.Branch): + branch = branch_or_jump + pred = guard(get_definition, func_ir, branch.cond.name) + if pred is not None and getattr(pred, "op", None) == "call": + function = guard(get_definition, func_ir, pred.func) + if (function is not None and + isinstance(function, ir.Global) and + function.value is bool): + condition = guard(get_definition, func_ir, pred.args[0]) + if condition is not None: + branches.append((branch, condition, blk)) + return branches + + def do_prune(take_truebr, blk): + keep = branch.truebr if take_truebr else branch.falsebr + # replace the branch with a direct jump + jmp = ir.Jump(keep, loc=branch.loc) + blk.body[-1] = jmp + return 1 if keep == branch.truebr else 0 + + def prune_by_type(branch, condition, blk, *conds): + # this prunes a given branch and fixes up the IR + # at least one needs to be a NoneType + lhs_cond, rhs_cond = conds + lhs_none = isinstance(lhs_cond, types.NoneType) + rhs_none = isinstance(rhs_cond, types.NoneType) + if lhs_none or rhs_none: + try: + take_truebr = condition.fn(lhs_cond, rhs_cond) + except Exception: + return False, None + if DEBUG > 0: + kill = branch.falsebr if take_truebr else branch.truebr + print("Pruning %s" % kill, branch, lhs_cond, rhs_cond, + condition.fn) + taken = do_prune(take_truebr, blk) + return True, taken + return False, None + + def prune_by_value(branch, condition, blk, *conds): + lhs_cond, rhs_cond = conds + try: + take_truebr = condition.fn(lhs_cond, rhs_cond) + except Exception: + return False, None + if DEBUG > 0: + kill = branch.falsebr if take_truebr else branch.truebr + print("Pruning %s" % kill, branch, lhs_cond, rhs_cond, condition.fn) + do_prune(take_truebr, blk) + # It is not safe to rewrite the predicate to a nominal value based on + # which branch is taken, the rewritten const predicate needs to + # hold the actual computed const value as something else may refer to + # it! + return True, take_truebr + + def prune_by_predicate(branch, pred, blk): + try: + # Just to prevent accidents, whilst already guarded, ensure this + # is an ir.Const + if not isinstance(pred, (ir.Const, ir.FreeVar, ir.Global)): + raise TypeError('Expected constant Numba IR node') + take_truebr = bool(pred.value) + except TypeError: + return False, None + if DEBUG > 0: + kill = branch.falsebr if take_truebr else branch.truebr + print("Pruning %s" % kill, branch, pred) + taken = do_prune(take_truebr, blk) + return True, taken + + class Unknown(object): + pass + + def resolve_input_arg_const(input_arg_idx): + """ + Resolves an input arg to a constant (if possible) + """ + input_arg_ty = called_args[input_arg_idx] + + # comparing to None? + if isinstance(input_arg_ty, types.NoneType): + return input_arg_ty + + # is it a kwarg default + if isinstance(input_arg_ty, types.Omitted): + val = input_arg_ty.value + if isinstance(val, types.NoneType): + return val + elif val is None: + return types.NoneType('none') + + # literal type, return the type itself so comparisons like `x == None` + # still work as e.g. x = types.int64 will never be None/NoneType so + # the branch can still be pruned + return getattr(input_arg_ty, 'literal_type', Unknown()) + + if DEBUG > 1: + print("before".center(80, '-')) + print(func_ir.dump()) + + phi2lbl = dict() + phi2asgn = dict() + for lbl, blk in func_ir.blocks.items(): + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, ir.Expr) and stmt.value.op == 'phi': + phi2lbl[stmt.value] = lbl + phi2asgn[stmt.value] = stmt + + # This looks for branches where: + # at least one arg of the condition is in input args and const + # at least one an arg of the condition is a const + # if the condition is met it will replace the branch with a jump + branch_info = find_branches(func_ir) + # stores conditions that have no impact post prune + nullified_conditions = [] + + for branch, condition, blk in branch_info: + const_conds = [] + if isinstance(condition, ir.Expr) and condition.op == 'binop': + prune = prune_by_value + for arg in [condition.lhs, condition.rhs]: + resolved_const = Unknown() + arg_def = guard(get_definition, func_ir, arg) + if isinstance(arg_def, ir.Arg): + # it's an e.g. literal argument to the function + resolved_const = resolve_input_arg_const(arg_def.index) + prune = prune_by_type + else: + # it's some const argument to the function, cannot use guard + # here as the const itself may be None + try: + resolved_const = find_const(func_ir, arg) + if resolved_const is None: + resolved_const = types.NoneType('none') + except GuardException: + pass + + if not isinstance(resolved_const, Unknown): + const_conds.append(resolved_const) + + # lhs/rhs are consts + if len(const_conds) == 2: + # prune the branch, switch the branch for an unconditional jump + prune_stat, taken = prune(branch, condition, blk, *const_conds) + if (prune_stat): + # add the condition to the list of nullified conditions + nullified_conditions.append(nullified(condition, taken, + True)) + else: + # see if this is a branch on a constant value predicate + resolved_const = Unknown() + try: + pred_call = get_definition(func_ir, branch.cond) + resolved_const = find_const(func_ir, pred_call.args[0]) + if resolved_const is None: + resolved_const = types.NoneType('none') + except GuardException: + pass + + if not isinstance(resolved_const, Unknown): + prune_stat, taken = prune_by_predicate(branch, condition, blk) + if (prune_stat): + # add the condition to the list of nullified conditions + nullified_conditions.append(nullified(condition, taken, + False)) + + # 'ERE BE DRAGONS... + # It is the evaluation of the condition expression that often trips up type + # inference, so ideally it would be removed as it is effectively rendered + # dead by the unconditional jump if a branch was pruned. However, there may + # be references to the condition that exist in multiple places (e.g. dels) + # and we cannot run DCE here as typing has not taken place to give enough + # information to run DCE safely. Upshot of all this is the condition gets + # rewritten below into a benign const that typing will be happy with and DCE + # can remove it and its reference post typing when it is safe to do so + # (if desired). It is required that the const is assigned a value that + # indicates the branch taken as its mutated value would be read in the case + # of object mode fall back in place of the condition itself. For + # completeness the func_ir._definitions and ._consts are also updated to + # make the IR state self consistent. + + deadcond = [x.condition for x in nullified_conditions] + for _, cond, blk in branch_info: + if cond in deadcond: + for x in blk.body: + if isinstance(x, ir.Assign) and x.value is cond: + # rewrite the condition as a true/false bit + nullified_info = nullified_conditions[deadcond.index(cond)] + # only do a rewrite of conditions, predicates need to retain + # their value as they may be used later. + if nullified_info.rewrite_stmt: + branch_bit = nullified_info.taken_br + x.value = ir.Const(branch_bit, loc=x.loc) + # update the specific definition to the new const + defns = func_ir._definitions[x.target.name] + repl_idx = defns.index(cond) + defns[repl_idx] = x.value + + # Check post dominators of dead nodes from in the original CFG for use of + # vars that are being removed in the dead blocks which might be referred to + # by phi nodes. + # + # Multiple things to fix up: + # + # 1. Cases like: + # + # A A + # |\ | + # | B --> B + # |/ | + # C C + # + # i.e. the branch is dead but the block is still alive. In this case CFG + # simplification will fuse A-B-C and any phi in C can be updated as an + # direct assignment from the last assigned version in the dominators of the + # fused block. + # + # 2. Cases like: + # + # A A + # / \ | + # B C --> B + # \ / | + # D D + # + # i.e. the block C is dead. In this case the phis in D need updating to + # reflect the collapse of the phi condition. This should result in a direct + # assignment of the surviving version in B to the LHS of the phi in D. + + new_cfg = compute_cfg_from_blocks(func_ir.blocks) + dead_blocks = new_cfg.dead_nodes() + + # for all phis that are still in live blocks. + for phi, lbl in phi2lbl.items(): + if lbl in dead_blocks: + continue + new_incoming = [x[0] for x in new_cfg.predecessors(lbl)] + if set(new_incoming) != set(phi.incoming_blocks): + # Something has changed in the CFG... + if len(new_incoming) == 1: + # There's now just one incoming. Replace the PHI node by a + # direct assignment + idx = phi.incoming_blocks.index(new_incoming[0]) + phi2asgn[phi].value = phi.incoming_values[idx] + else: + # There's more than one incoming still, then look through the + # incoming and remove dead + ic_val_tmp = [] + ic_blk_tmp = [] + for ic_val, ic_blk in zip(phi.incoming_values, + phi.incoming_blocks): + if ic_blk in dead_blocks: + continue + else: + ic_val_tmp.append(ic_val) + ic_blk_tmp.append(ic_blk) + phi.incoming_values.clear() + phi.incoming_values.extend(ic_val_tmp) + phi.incoming_blocks.clear() + phi.incoming_blocks.extend(ic_blk_tmp) + + # Remove dead blocks, this is safe as it relies on the CFG only. + for dead in dead_blocks: + del func_ir.blocks[dead] + + # if conditions were nullified then consts were rewritten, update + if nullified_conditions: + func_ir._consts = consts.ConstantInference(func_ir) + + if DEBUG > 1: + print("after".center(80, '-')) + print(func_ir.dump()) + + +def rewrite_semantic_constants(func_ir, called_args): + """ + This rewrites values known to be constant by their semantics as ir.Const + nodes, this is to give branch pruning the best chance possible of killing + branches. An example might be rewriting len(tuple) as the literal length. + + func_ir is the IR + called_args are the actual arguments with which the function is called + """ + DEBUG = 0 + + if DEBUG > 1: + print(("rewrite_semantic_constants: " + + func_ir.func_id.func_name).center(80, '-')) + print("before".center(80, '*')) + func_ir.dump() + + def rewrite_statement(func_ir, stmt, new_val): + """ + Rewrites the stmt as a ir.Const new_val and fixes up the entries in + func_ir._definitions + """ + stmt.value = ir.Const(new_val, stmt.loc) + defns = func_ir._definitions[stmt.target.name] + repl_idx = defns.index(val) + defns[repl_idx] = stmt.value + + def rewrite_array_ndim(val, func_ir, called_args): + # rewrite Array.ndim as const(ndim) + if getattr(val, 'op', None) == 'getattr': + if val.attr == 'ndim': + arg_def = guard(get_definition, func_ir, val.value) + if isinstance(arg_def, ir.Arg): + argty = called_args[arg_def.index] + if isinstance(argty, types.Array): + rewrite_statement(func_ir, stmt, argty.ndim) + + def rewrite_tuple_len(val, func_ir, called_args): + # rewrite len(tuple) as const(len(tuple)) + if getattr(val, 'op', None) == 'call': + func = guard(get_definition, func_ir, val.func) + if (func is not None and isinstance(func, ir.Global) and + getattr(func, 'value', None) is len): + + (arg,) = val.args + arg_def = guard(get_definition, func_ir, arg) + if isinstance(arg_def, ir.Arg): + argty = called_args[arg_def.index] + if isinstance(argty, types.BaseTuple): + rewrite_statement(func_ir, stmt, argty.count) + elif (isinstance(arg_def, ir.Expr) and + arg_def.op == 'typed_getitem'): + argty = arg_def.dtype + if isinstance(argty, types.BaseTuple): + rewrite_statement(func_ir, stmt, argty.count) + + from numba.core.ir_utils import get_definition, guard + for blk in func_ir.blocks.values(): + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + val = stmt.value + if isinstance(val, ir.Expr): + rewrite_array_ndim(val, func_ir, called_args) + rewrite_tuple_len(val, func_ir, called_args) + + if DEBUG > 1: + print("after".center(80, '*')) + func_ir.dump() + print('-' * 80) + + +def find_literally_calls(func_ir, argtypes): + """An analysis to find `numba.literally` call inside the given IR. + When an unsatisfied literal typing request is found, a `ForceLiteralArg` + exception is raised. + + Parameters + ---------- + + func_ir : numba.ir.FunctionIR + + argtypes : Sequence[numba.types.Type] + The argument types. + """ + from numba.core import ir_utils + + marked_args = set() + first_loc = {} + # Scan for literally calls + for blk in func_ir.blocks.values(): + for assign in blk.find_exprs(op='call'): + var = ir_utils.guard(ir_utils.get_definition, func_ir, assign.func) + if isinstance(var, (ir.Global, ir.FreeVar)): + fnobj = var.value + else: + fnobj = ir_utils.guard(ir_utils.resolve_func_from_module, + func_ir, var) + if fnobj is special.literally: + # Found + [arg] = assign.args + defarg = func_ir.get_definition(arg) + if isinstance(defarg, ir.Arg): + argindex = defarg.index + marked_args.add(argindex) + first_loc.setdefault(argindex, assign.loc) + # Signal the dispatcher to force literal typing + for pos in marked_args: + query_arg = argtypes[pos] + do_raise = (isinstance(query_arg, types.InitialValue) and + query_arg.initial_value is None) + if do_raise: + loc = first_loc[pos] + raise errors.ForceLiteralArg(marked_args, loc=loc) + + if not isinstance(query_arg, (types.Literal, types.InitialValue)): + loc = first_loc[pos] + raise errors.ForceLiteralArg(marked_args, loc=loc) + + +ir_extension_use_alloca = {} + + +def must_use_alloca(blocks): + """ + Analyzes a dictionary of blocks to find variables that must be + stack allocated with alloca. For each statement in the blocks, + determine if that statement requires certain variables to be + stack allocated. This function uses the extension point + ir_extension_use_alloca to allow other IR node types like parfors + to register to be processed by this analysis function. At the + moment, parfors are the only IR node types that may require + something to be stack allocated. + """ + use_alloca_vars = set() + + for ir_block in blocks.values(): + for stmt in ir_block.body: + if type(stmt) in ir_extension_use_alloca: + func = ir_extension_use_alloca[type(stmt)] + func(stmt, use_alloca_vars) + continue + + return use_alloca_vars diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/base.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/base.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7aa7871167f92b7a9a02b2d9c83161f4b3b659 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/base.py @@ -0,0 +1,1269 @@ +from collections import defaultdict +import copy +import sys +from itertools import permutations, takewhile +from contextlib import contextmanager +from functools import cached_property + +from llvmlite import ir as llvmir +from llvmlite.ir import Constant +import llvmlite.binding as ll + +from numba.core import types, utils, datamodel, debuginfo, funcdesc, config, cgutils, imputils +from numba.core import event, errors, targetconfig +from numba import _dynfunc, _helperlib +from numba.core.compiler_lock import global_compiler_lock +from numba.core.pythonapi import PythonAPI +from numba.core.imputils import (user_function, user_generator, + builtin_registry, impl_ret_borrowed, + RegistryLoader) +from numba.cpython import builtins + +GENERIC_POINTER = llvmir.PointerType(llvmir.IntType(8)) +PYOBJECT = GENERIC_POINTER +void_ptr = GENERIC_POINTER + + +class OverloadSelector(object): + """ + An object matching an actual signature against a registry of formal + signatures and choosing the best candidate, if any. + + In the current implementation: + - a "signature" is a tuple of type classes or type instances + - the "best candidate" is the most specific match + """ + + def __init__(self): + # A list of (formal args tuple, value) + self.versions = [] + self._cache = {} + + def find(self, sig): + out = self._cache.get(sig) + if out is None: + out = self._find(sig) + self._cache[sig] = out + return out + + def _find(self, sig): + candidates = self._select_compatible(sig) + if candidates: + return candidates[self._best_signature(candidates)] + else: + raise errors.NumbaNotImplementedError(f'{self}, {sig}') + + def _select_compatible(self, sig): + """ + Select all compatible signatures and their implementation. + """ + out = {} + for ver_sig, impl in self.versions: + if self._match_arglist(ver_sig, sig): + out[ver_sig] = impl + return out + + def _best_signature(self, candidates): + """ + Returns the best signature out of the candidates + """ + ordered, genericity = self._sort_signatures(candidates) + # check for ambiguous signatures + if len(ordered) > 1: + firstscore = genericity[ordered[0]] + same = list(takewhile(lambda x: genericity[x] == firstscore, + ordered)) + if len(same) > 1: + msg = ["{n} ambiguous signatures".format(n=len(same))] + for sig in same: + msg += ["{0} => {1}".format(sig, candidates[sig])] + raise errors.NumbaTypeError('\n'.join(msg)) + return ordered[0] + + def _sort_signatures(self, candidates): + """ + Sort signatures in ascending level of genericity. + + Returns a 2-tuple: + + * ordered list of signatures + * dictionary containing genericity scores + """ + # score by genericity + genericity = defaultdict(int) + for this, other in permutations(candidates.keys(), r=2): + matched = self._match_arglist(formal_args=this, actual_args=other) + if matched: + # genericity score +1 for every another compatible signature + genericity[this] += 1 + # order candidates in ascending level of genericity + ordered = sorted(candidates.keys(), key=lambda x: genericity[x]) + return ordered, genericity + + def _match_arglist(self, formal_args, actual_args): + """ + Returns True if the signature is "matching". + A formal signature is "matching" if the actual signature matches exactly + or if the formal signature is a compatible generic signature. + """ + # normalize VarArg + if formal_args and isinstance(formal_args[-1], types.VarArg): + ndiff = len(actual_args) - len(formal_args) + 1 + formal_args = formal_args[:-1] + (formal_args[-1].dtype,) * ndiff + + if len(formal_args) != len(actual_args): + return False + + for formal, actual in zip(formal_args, actual_args): + if not self._match(formal, actual): + return False + + return True + + def _match(self, formal, actual): + if formal == actual: + # formal argument matches actual arguments + return True + elif types.Any == formal: + # formal argument is any + return True + elif isinstance(formal, type) and issubclass(formal, types.Type): + if isinstance(actual, type) and issubclass(actual, formal): + # formal arg is a type class and actual arg is a subclass + return True + elif isinstance(actual, formal): + # formal arg is a type class of which actual arg is an instance + return True + + def append(self, value, sig): + """ + Add a formal signature and its associated value. + """ + assert isinstance(sig, tuple), (value, sig) + self.versions.append((sig, value)) + self._cache.clear() + + +@utils.runonce +def _load_global_helpers(): + """ + Execute once to install special symbols into the LLVM symbol table. + """ + # This is Py_None's real C name + ll.add_symbol("_Py_NoneStruct", id(None)) + + # Add Numba C helper functions + for c_helpers in (_helperlib.c_helpers, _dynfunc.c_helpers): + for py_name, c_address in c_helpers.items(): + c_name = "numba_" + py_name + ll.add_symbol(c_name, c_address) + + # Add all built-in exception classes + for obj in utils.builtins.__dict__.values(): + if isinstance(obj, type) and issubclass(obj, BaseException): + ll.add_symbol("PyExc_%s" % (obj.__name__), id(obj)) + + +class BaseContext(object): + """ + + Notes on Structure + ------------------ + + Most objects are lowered as plain-old-data structure in the generated + llvm. They are passed around by reference (a pointer to the structure). + Only POD structure can live across function boundaries by copying the + data. + """ + # True if the target requires strict alignment + # Causes exception to be raised if the record members are not aligned. + strict_alignment = False + + # Force powi implementation as math.pow call + implement_powi_as_math_call = False + implement_pow_as_math_call = False + + # Emit Debug info + enable_debuginfo = False + DIBuilder = debuginfo.DIBuilder + + # Bound checking + @property + def enable_boundscheck(self): + if config.BOUNDSCHECK is not None: + return config.BOUNDSCHECK + return self._boundscheck + + @enable_boundscheck.setter + def enable_boundscheck(self, value): + self._boundscheck = value + + # NRT + enable_nrt = False + + # Auto parallelization + auto_parallel = False + + # PYCC + aot_mode = False + + # Error model for various operations (only FP exceptions currently) + error_model = None + + # Whether dynamic globals (CPU runtime addresses) is allowed + allow_dynamic_globals = False + + # Fast math flags + fastmath = False + + # python execution environment + environment = None + + # the function descriptor + fndesc = None + + def __init__(self, typing_context, target): + _load_global_helpers() + + self.address_size = utils.MACHINE_BITS + self.typing_context = typing_context + from numba.core.target_extension import target_registry + self.target_name = target + self.target = target_registry[target] + + # A mapping of installed registries to their loaders + self._registries = {} + # Declarations loaded from registries and other sources + self._defns = defaultdict(OverloadSelector) + self._getattrs = defaultdict(OverloadSelector) + self._setattrs = defaultdict(OverloadSelector) + self._casts = OverloadSelector() + self._get_constants = OverloadSelector() + # Other declarations + self._generators = {} + self.special_ops = {} + self.cached_internal_func = {} + self._pid = None + self._codelib_stack = [] + + self._boundscheck = False + + self.data_model_manager = datamodel.default_manager + + # Initialize + self.init() + + def init(self): + """ + For subclasses to add initializer + """ + + def refresh(self): + """ + Refresh context with new declarations from known registries. + Useful for third-party extensions. + """ + # load target specific registries + self.load_additional_registries() + + # Populate the builtin registry, this has to happen after loading + # additional registries as some of the "additional" registries write + # their implementations into the builtin_registry and would be missed if + # this ran first. + self.install_registry(builtin_registry) + + # Also refresh typing context, since @overload declarations can + # affect it. + self.typing_context.refresh() + + def load_additional_registries(self): + """ + Load target-specific registries. Can be overridden by subclasses. + """ + + def mangler(self, name, types, *, abi_tags=(), uid=None): + """ + Perform name mangling. + """ + return funcdesc.default_mangler(name, types, abi_tags=abi_tags, uid=uid) + + def get_env_name(self, fndesc): + """Get the environment name given a FunctionDescriptor. + + Use this instead of the ``fndesc.env_name`` so that the target-context + can provide necessary mangling of the symbol to meet ABI requirements. + """ + return fndesc.env_name + + def declare_env_global(self, module, envname): + """Declare the Environment pointer as a global of the module. + + The pointer is initialized to NULL. It must be filled by the runtime + with the actual address of the Env before the associated function + can be executed. + + Parameters + ---------- + module : + The LLVM Module + envname : str + The name of the global variable. + """ + if envname not in module.globals: + gv = llvmir.GlobalVariable(module, cgutils.voidptr_t, name=envname) + gv.linkage = 'common' + gv.initializer = cgutils.get_null_value(gv.type.pointee) + + return module.globals[envname] + + def get_arg_packer(self, fe_args): + return datamodel.ArgPacker(self.data_model_manager, fe_args) + + def get_data_packer(self, fe_types): + return datamodel.DataPacker(self.data_model_manager, fe_types) + + @property + def target_data(self): + raise NotImplementedError + + @cached_property + def nonconst_module_attrs(self): + """ + All module attrs are constant for targets using BaseContext. + """ + return tuple() + + @cached_property + def nrt(self): + from numba.core.runtime.context import NRTContext + return NRTContext(self, self.enable_nrt) + + def subtarget(self, **kws): + obj = copy.copy(self) # shallow copy + for k, v in kws.items(): + if not hasattr(obj, k): + raise NameError("unknown option {0!r}".format(k)) + setattr(obj, k, v) + if obj.codegen() is not self.codegen(): + # We can't share functions across different codegens + obj.cached_internal_func = {} + return obj + + def install_registry(self, registry): + """ + Install a *registry* (a imputils.Registry instance) of function + and attribute implementations. + """ + try: + loader = self._registries[registry] + except KeyError: + loader = RegistryLoader(registry) + self._registries[registry] = loader + self.insert_func_defn(loader.new_registrations('functions')) + self._insert_getattr_defn(loader.new_registrations('getattrs')) + self._insert_setattr_defn(loader.new_registrations('setattrs')) + self._insert_cast_defn(loader.new_registrations('casts')) + self._insert_get_constant_defn(loader.new_registrations('constants')) + + def insert_func_defn(self, defns): + for impl, func, sig in defns: + self._defns[func].append(impl, sig) + + def _insert_getattr_defn(self, defns): + for impl, attr, sig in defns: + self._getattrs[attr].append(impl, sig) + + def _insert_setattr_defn(self, defns): + for impl, attr, sig in defns: + self._setattrs[attr].append(impl, sig) + + def _insert_cast_defn(self, defns): + for impl, sig in defns: + self._casts.append(impl, sig) + + def _insert_get_constant_defn(self, defns): + for impl, sig in defns: + self._get_constants.append(impl, sig) + + def insert_user_function(self, func, fndesc, libs=()): + impl = user_function(fndesc, libs) + self._defns[func].append(impl, impl.signature) + + def insert_generator(self, genty, gendesc, libs=()): + assert isinstance(genty, types.Generator) + impl = user_generator(gendesc, libs) + self._generators[genty] = gendesc, impl + + def remove_user_function(self, func): + """ + Remove user function *func*. + KeyError is raised if the function isn't known to us. + """ + del self._defns[func] + + def get_external_function_type(self, fndesc): + argtypes = [self.get_argument_type(aty) + for aty in fndesc.argtypes] + # don't wrap in pointer + restype = self.get_argument_type(fndesc.restype) + fnty = llvmir.FunctionType(restype, argtypes) + return fnty + + def declare_function(self, module, fndesc): + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + fn = cgutils.get_or_insert_function(module, fnty, fndesc.mangled_name) + self.apply_target_attributes(fn, fndesc.argtypes, fndesc.restype) + self.call_conv.decorate_function(fn, fndesc.args, fndesc.argtypes, noalias=fndesc.noalias) + if fndesc.inline: + fn.attributes.add('alwaysinline') + # alwaysinline overrides optnone + fn.attributes.discard('noinline') + fn.attributes.discard('optnone') + return fn + + # Define the hook as a no-op so other contexts (like GPU) don't break + def apply_target_attributes(self, llvm_func, argtypes=None, restype=None): + """ + Hook for subclasses to apply target-specific attributes (e.g. signext). + """ + pass + + def declare_external_function(self, module, fndesc): + fnty = self.get_external_function_type(fndesc) + fn = cgutils.get_or_insert_function(module, fnty, fndesc.mangled_name) + assert fn.is_declaration + for ak, av in zip(fndesc.args, fn.args): + av.name = "arg.%s" % ak + return fn + + def insert_const_string(self, mod, string): + """ + Insert constant *string* (a str object) into module *mod*. + """ + stringtype = GENERIC_POINTER + name = ".const.%s" % string + text = cgutils.make_bytearray(string.encode("utf-8") + b"\x00") + gv = self.insert_unique_const(mod, name, text) + return Constant.bitcast(gv, stringtype) + + def insert_const_bytes(self, mod, bytes, name=None): + """ + Insert constant *byte* (a `bytes` object) into module *mod*. + """ + stringtype = GENERIC_POINTER + name = ".bytes.%s" % (name or hash(bytes)) + text = cgutils.make_bytearray(bytes) + gv = self.insert_unique_const(mod, name, text) + return Constant.bitcast(gv, stringtype) + + def insert_unique_const(self, mod, name, val): + """ + Insert a unique internal constant named *name*, with LLVM value + *val*, into module *mod*. + """ + try: + gv = mod.get_global(name) + except KeyError: + return cgutils.global_constant(mod, name, val) + else: + return gv + + def get_argument_type(self, ty): + return self.data_model_manager[ty].get_argument_type() + + def get_return_type(self, ty): + return self.data_model_manager[ty].get_return_type() + + def get_data_type(self, ty): + """ + Get a LLVM data representation of the Numba type *ty* that is safe + for storage. Record data are stored as byte array. + + The return value is a llvmlite.ir.Type object, or None if the type + is an opaque pointer (???). + """ + return self.data_model_manager[ty].get_data_type() + + def get_value_type(self, ty): + return self.data_model_manager[ty].get_value_type() + + def pack_value(self, builder, ty, value, ptr, align=None): + """ + Pack value into the array storage at *ptr*. + If *align* is given, it is the guaranteed alignment for *ptr* + (by default, the standard ABI alignment). + """ + dataval = self.data_model_manager[ty].as_data(builder, value) + builder.store(dataval, ptr, align=align) + + def unpack_value(self, builder, ty, ptr, align=None): + """ + Unpack value from the array storage at *ptr*. + If *align* is given, it is the guaranteed alignment for *ptr* + (by default, the standard ABI alignment). + """ + dm = self.data_model_manager[ty] + return dm.load_from_data_pointer(builder, ptr, align) + + def get_constant_generic(self, builder, ty, val): + """ + Return a LLVM constant representing value *val* of Numba type *ty*. + """ + try: + impl = self._get_constants.find((ty,)) + return impl(self, builder, ty, val) + except NotImplementedError: + raise NotImplementedError("Cannot lower constant of type '%s'" % (ty,)) + + def get_constant(self, ty, val): + """ + Same as get_constant_generic(), but without specifying *builder*. + Works only for simple types. + """ + # HACK: pass builder=None to preserve get_constant() API + return self.get_constant_generic(None, ty, val) + + def get_constant_undef(self, ty): + lty = self.get_value_type(ty) + return Constant(lty, llvmir.Undefined) + + def get_constant_null(self, ty): + lty = self.get_value_type(ty) + return Constant(lty, None) + + def get_function(self, fn, sig, _firstcall=True): + """ + Return the implementation of function *fn* for signature *sig*. + The return value is a callable with the signature (builder, args). + """ + assert sig is not None + sig = sig.as_function() + if isinstance(fn, types.Callable): + key = fn.get_impl_key(sig) + overloads = self._defns[key] + else: + key = fn + overloads = self._defns[key] + + try: + return _wrap_impl(overloads.find(sig.args), self, sig) + except errors.NumbaNotImplementedError: + pass + if isinstance(fn, types.Type): + # It's a type instance => try to find a definition for the type class + try: + return self.get_function(type(fn), sig) + except NotImplementedError: + # Raise exception for the type instance, for a better error message + pass + + # Automatically refresh the context to load new registries if we are + # calling the first time. + if _firstcall: + self.refresh() + return self.get_function(fn, sig, _firstcall=False) + + raise NotImplementedError("No definition for lowering %s%s" % (key, sig)) + + def get_generator_desc(self, genty): + """ + """ + return self._generators[genty][0] + + def get_generator_impl(self, genty): + """ + """ + res = self._generators[genty][1] + self.add_linking_libs(getattr(res, 'libs', ())) + return res + + def get_bound_function(self, builder, obj, ty): + assert self.get_value_type(ty) == obj.type + return obj + + def get_getattr(self, typ, attr): + """ + Get the getattr() implementation for the given type and attribute name. + The return value is a callable with the signature + (context, builder, typ, val, attr). + """ + const_attr = (typ, attr) not in self.nonconst_module_attrs + is_module = isinstance(typ, types.Module) + if is_module and const_attr: + # Implement getattr for module-level globals that we treat as + # constants. + # XXX We shouldn't have to retype this + attrty = self.typing_context.resolve_module_constants(typ, attr) + if attrty is None or isinstance(attrty, types.Dummy): + # No implementation required for dummies (functions, modules...), + # which are dealt with later + return None + else: + pyval = getattr(typ.pymod, attr) + def imp(context, builder, typ, val, attr): + llval = self.get_constant_generic(builder, attrty, pyval) + return impl_ret_borrowed(context, builder, attrty, llval) + return imp + + # Lookup specific getattr implementation for this type and attribute + overloads = self._getattrs[attr] + try: + return overloads.find((typ,)) + except errors.NumbaNotImplementedError: + pass + # Lookup generic getattr implementation for this type + overloads = self._getattrs[None] + try: + return overloads.find((typ,)) + except errors.NumbaNotImplementedError: + pass + + raise NotImplementedError("No definition for lowering %s.%s" % (typ, attr)) + + def get_setattr(self, attr, sig): + """ + Get the setattr() implementation for the given attribute name + and signature. + The return value is a callable with the signature (builder, args). + """ + assert len(sig.args) == 2 + typ = sig.args[0] + valty = sig.args[1] + + def wrap_setattr(impl): + def wrapped(builder, args): + return impl(self, builder, sig, args, attr) + return wrapped + + # Lookup specific setattr implementation for this type and attribute + overloads = self._setattrs[attr] + try: + return wrap_setattr(overloads.find((typ, valty))) + except errors.NumbaNotImplementedError: + pass + # Lookup generic setattr implementation for this type + overloads = self._setattrs[None] + try: + return wrap_setattr(overloads.find((typ, valty))) + except errors.NumbaNotImplementedError: + pass + + raise NotImplementedError("No definition for lowering %s.%s = %s" + % (typ, attr, valty)) + + def get_argument_value(self, builder, ty, val): + """ + Argument representation to local value representation + """ + return self.data_model_manager[ty].from_argument(builder, val) + + def get_returned_value(self, builder, ty, val): + """ + Return value representation to local value representation + """ + return self.data_model_manager[ty].from_return(builder, val) + + def get_return_value(self, builder, ty, val): + """ + Local value representation to return type representation + """ + return self.data_model_manager[ty].as_return(builder, val) + + def get_value_as_argument(self, builder, ty, val): + """Prepare local value representation as argument type representation + """ + return self.data_model_manager[ty].as_argument(builder, val) + + def get_value_as_data(self, builder, ty, val): + return self.data_model_manager[ty].as_data(builder, val) + + def get_data_as_value(self, builder, ty, val): + return self.data_model_manager[ty].from_data(builder, val) + + def pair_first(self, builder, val, ty): + """ + Extract the first element of a heterogeneous pair. + """ + pair = self.make_helper(builder, ty, val) + return pair.first + + def pair_second(self, builder, val, ty): + """ + Extract the second element of a heterogeneous pair. + """ + pair = self.make_helper(builder, ty, val) + return pair.second + + def cast(self, builder, val, fromty, toty): + """ + Cast a value of type *fromty* to type *toty*. + This implements implicit conversions as can happen due to the + granularity of the Numba type system, or lax Python semantics. + """ + if fromty is types._undef_var: + # Special case for undefined variable + return self.get_constant_null(toty) + elif fromty == toty or toty == types.Any: + return val + try: + impl = self._casts.find((fromty, toty)) + return impl(self, builder, fromty, toty, val) + except errors.NumbaNotImplementedError: + raise errors.NumbaNotImplementedError( + "Cannot cast %s to %s: %s" % (fromty, toty, val)) + + def generic_compare(self, builder, key, argtypes, args): + """ + Compare the given LLVM values of the given Numba types using + the comparison *key* (e.g. '=='). The values are first cast to + a common safe conversion type. + """ + at, bt = argtypes + av, bv = args + ty = self.typing_context.unify_types(at, bt) + assert ty is not None + cav = self.cast(builder, av, at, ty) + cbv = self.cast(builder, bv, bt, ty) + fnty = self.typing_context.resolve_value_type(key) + # the sig is homogeneous in the unified casted type + cmpsig = fnty.get_call_type(self.typing_context, (ty, ty), {}) + cmpfunc = self.get_function(fnty, cmpsig) + self.add_linking_libs(getattr(cmpfunc, 'libs', ())) + return cmpfunc(builder, (cav, cbv)) + + def make_optional_none(self, builder, valtype): + optval = self.make_helper(builder, types.Optional(valtype)) + optval.valid = cgutils.false_bit + return optval._getvalue() + + def make_optional_value(self, builder, valtype, value): + optval = self.make_helper(builder, types.Optional(valtype)) + optval.valid = cgutils.true_bit + optval.data = value + return optval._getvalue() + + def is_true(self, builder, typ, val): + """ + Return the truth value of a value of the given Numba type. + """ + fnty = self.typing_context.resolve_value_type(bool) + sig = fnty.get_call_type(self.typing_context, (typ,), {}) + impl = self.get_function(fnty, sig) + return impl(builder, (val,)) + + def get_c_value(self, builder, typ, name, dllimport=False): + """ + Get a global value through its C-accessible *name*, with the given + LLVM type. + If *dllimport* is true, the symbol will be marked as imported + from a DLL (necessary for AOT compilation under Windows). + """ + module = builder.function.module + try: + gv = module.globals[name] + except KeyError: + gv = cgutils.add_global_variable(module, typ, name) + if dllimport and self.aot_mode and sys.platform == 'win32': + gv.storage_class = "dllimport" + return gv + + def call_external_function(self, builder, callee, argtys, args): + args = [self.get_value_as_argument(builder, ty, arg) + for ty, arg in zip(argtys, args)] + retval = builder.call(callee, args) + return retval + + def get_function_pointer_type(self, typ): + return self.data_model_manager[typ].get_data_type() + + def call_function_pointer(self, builder, funcptr, args, cconv=None): + return builder.call(funcptr, args, cconv=cconv) + + def print_string(self, builder, text): + mod = builder.module + cstring = GENERIC_POINTER + fnty = llvmir.FunctionType(llvmir.IntType(32), [cstring]) + puts = cgutils.get_or_insert_function(mod, fnty, "puts") + return builder.call(puts, [text]) + + def debug_print(self, builder, text): + mod = builder.module + cstr = self.insert_const_string(mod, str(text)) + self.print_string(builder, cstr) + + def printf(self, builder, format_string, *args): + mod = builder.module + if isinstance(format_string, str): + cstr = self.insert_const_string(mod, format_string) + else: + cstr = format_string + fnty = llvmir.FunctionType(llvmir.IntType(32), (GENERIC_POINTER,), var_arg=True) + fn = cgutils.get_or_insert_function(mod, fnty, "printf") + return builder.call(fn, (cstr,) + tuple(args)) + + def get_struct_type(self, struct): + """ + Get the LLVM struct type for the given Structure class *struct*. + """ + fields = [self.get_value_type(v) for _, v in struct._fields] + return llvmir.LiteralStructType(fields) + + def get_dummy_value(self): + return Constant(self.get_dummy_type(), None) + + def get_dummy_type(self): + return GENERIC_POINTER + + def _compile_subroutine_no_cache(self, builder, impl, sig, locals=None, + flags=None): + """ + Invoke the compiler to compile a function to be used inside a + nopython function, but without generating code to call that + function. + + Note this context's flags are not inherited. + """ + # Compile + from numba.core import compiler + + if locals is None: + locals = {} + with global_compiler_lock: + codegen = self.codegen() + library = codegen.create_library(impl.__name__) + if flags is None: + + cstk = targetconfig.ConfigStack() + flags = compiler.Flags() + if cstk: + tls_flags = cstk.top() + if tls_flags.is_set("nrt") and tls_flags.nrt: + flags.nrt = True + + flags.no_compile = True + flags.no_cpython_wrapper = True + flags.no_cfunc_wrapper = True + + cres = compiler.compile_internal(self.typing_context, self, + library, + impl, sig.args, + sig.return_type, flags, + locals=locals) + + # Allow inlining the function inside callers. + self.active_code_library.add_linking_library(cres.library) + return cres + + def compile_subroutine(self, builder, impl, sig, locals=None, flags=None, + caching=True): + """ + Compile the function *impl* for the given *sig* (in nopython mode). + Return an instance of CompileResult. + + If *caching* evaluates True, the function keeps the compiled function + for reuse in *.cached_internal_func*. + """ + if locals is None: + locals = {} + cache_key = (impl.__code__, sig, type(self.error_model)) + if not caching: + cached = None + else: + if impl.__closure__: + # XXX This obviously won't work if a cell's value is + # unhashable. + cache_key += tuple(c.cell_contents for c in impl.__closure__) + cached = self.cached_internal_func.get(cache_key) + if cached is None: + cres = self._compile_subroutine_no_cache(builder, impl, sig, + locals=locals, + flags=flags) + self.cached_internal_func[cache_key] = cres + + cres = self.cached_internal_func[cache_key] + # Allow inlining the function inside callers. + self.active_code_library.add_linking_library(cres.library) + return cres + + def compile_internal(self, builder, impl, sig, args, locals=None): + """ + Like compile_subroutine(), but also call the function with the given + *args*. + """ + if locals is None: + locals = {} + cres = self.compile_subroutine(builder, impl, sig, locals) + return self.call_internal(builder, cres.fndesc, sig, args) + + def call_internal(self, builder, fndesc, sig, args): + """ + Given the function descriptor of an internally compiled function, + emit a call to that function with the given arguments. + """ + status, res = self.call_internal_no_propagate(builder, fndesc, sig, args) + with cgutils.if_unlikely(builder, status.is_error): + self.call_conv.return_status_propagate(builder, status) + + res = imputils.fix_returning_optional(self, builder, sig, status, res) + return res + + def call_internal_no_propagate(self, builder, fndesc, sig, args): + """Similar to `.call_internal()` but does not handle or propagate + the return status automatically. + """ + # Add call to the generated function + llvm_mod = builder.module + fn = self.declare_function(llvm_mod, fndesc) + status, res = self.call_conv.call_function(builder, fn, sig.return_type, + sig.args, args) + return status, res + + def call_unresolved(self, builder, name, sig, args): + """ + Insert a function call to an unresolved symbol with the given *name*. + + Note: this is used for recursive call. + + In the mutual recursion case:: + + @njit + def foo(): + ... # calls bar() + + @njit + def bar(): + ... # calls foo() + + foo() + + When foo() is called, the compilation of bar() is fully completed + (codegen'ed and loaded) before foo() is. Since MCJIT's eager compilation + doesn't allow loading modules with declare-only functions (which is + needed for foo() in bar()), the call_unresolved injects a global + variable that the "linker" can update even after the module is loaded by + MCJIT. The linker would allocate space for the global variable before + the bar() module is loaded. When later foo() module is defined, it will + update bar()'s reference to foo(). + + The legacy lazy JIT and the new ORC JIT would allow a declare-only + function be used in a module as long as it is defined by the time of its + first use. + """ + # Insert an unresolved reference to the function being called. + codegen = self.codegen() + fnty = self.call_conv.get_function_type(sig.return_type, sig.args) + fn = codegen.insert_unresolved_ref(builder, fnty, name) + # Normal call sequence + status, res = self.call_conv.call_function(builder, fn, sig.return_type, + sig.args, args) + with cgutils.if_unlikely(builder, status.is_error): + self.call_conv.return_status_propagate(builder, status) + + res = imputils.fix_returning_optional(self, builder, sig, status, res) + return res + + def get_executable(self, func, fndesc, env): + raise NotImplementedError + + def get_python_api(self, builder): + return PythonAPI(self, builder) + + def sentry_record_alignment(self, rectyp, attr): + """ + Assumes offset starts from a properly aligned location + """ + if self.strict_alignment: + offset = rectyp.offset(attr) + elemty = rectyp.typeof(attr) + if isinstance(elemty, types.NestedArray): + # For a NestedArray we need to consider the data type of + # elements of the array for alignment, not the array structure + # itself + elemty = elemty.dtype + align = self.get_abi_alignment(self.get_data_type(elemty)) + if offset % align: + msg = "{rec}.{attr} of type {type} is not aligned".format( + rec=rectyp, attr=attr, type=elemty) + raise errors.NumbaTypeError(msg) + + def get_helper_class(self, typ, kind='value'): + """ + Get a helper class for the given *typ*. + """ + # XXX handle all types: complex, array, etc. + # XXX should it be a method on the model instead? this would allow a default kind... + return cgutils.create_struct_proxy(typ, kind) + + def _make_helper(self, builder, typ, value=None, ref=None, kind='value'): + cls = self.get_helper_class(typ, kind) + return cls(self, builder, value=value, ref=ref) + + def make_helper(self, builder, typ, value=None, ref=None): + """ + Get a helper object to access the *typ*'s members, + for the given value or reference. + """ + return self._make_helper(builder, typ, value, ref, kind='value') + + def make_data_helper(self, builder, typ, ref=None): + """ + As make_helper(), but considers the value as stored in memory, + rather than a live value. + """ + return self._make_helper(builder, typ, ref=ref, kind='data') + + def make_array(self, typ): + from numba.np import arrayobj + return arrayobj.make_array(typ) + + def populate_array(self, arr, **kwargs): + """ + Populate array structure. + """ + from numba.np import arrayobj + return arrayobj.populate_array(arr, **kwargs) + + def make_complex(self, builder, typ, value=None): + """ + Get a helper object to access the given complex numbers' members. + """ + assert isinstance(typ, types.Complex), typ + return self.make_helper(builder, typ, value) + + def make_tuple(self, builder, typ, values): + """ + Create a tuple of the given *typ* containing the *values*. + """ + tup = self.get_constant_undef(typ) + for i, val in enumerate(values): + tup = builder.insert_value(tup, val, i) + return tup + + def make_constant_array(self, builder, typ, ary): + """ + Create an array structure reifying the given constant array. + A low-level contiguous array constant is created in the LLVM IR. + """ + datatype = self.get_data_type(typ.dtype) + # don't freeze ary of non-contig or bigger than 1MB + size_limit = 10**6 + + if (self.allow_dynamic_globals and + (typ.layout not in 'FC' or ary.nbytes > size_limit)): + # get pointer from the ary + dataptr = ary.ctypes.data + data = self.add_dynamic_addr(builder, dataptr, info=str(type(dataptr))) + rt_addr = self.add_dynamic_addr(builder, id(ary), info=str(type(ary))) + else: + # Handle data: reify the flattened array in "C" or "F" order as a + # global array of bytes. + flat = ary.flatten(order=typ.layout) + # Note: we use `bytearray(flat.data)` instead of `bytearray(flat)` to + # workaround issue #1850 which is due to numpy issue #3147 + consts = cgutils.create_constant_array(llvmir.IntType(8), bytearray(flat.data)) + data = cgutils.global_constant(builder, ".const.array.data", consts) + # Ensure correct data alignment (issue #1933) + data.align = self.get_abi_alignment(datatype) + # No reference to parent ndarray + rt_addr = None + + # Handle shape + llintp = self.get_value_type(types.intp) + shapevals = [self.get_constant(types.intp, s) for s in ary.shape] + cshape = cgutils.create_constant_array(llintp, shapevals) + + # Handle strides + stridevals = [self.get_constant(types.intp, s) for s in ary.strides] + cstrides = cgutils.create_constant_array(llintp, stridevals) + + # Create array structure + cary = self.make_array(typ)(self, builder) + + intp_itemsize = self.get_constant(types.intp, ary.dtype.itemsize) + self.populate_array(cary, + data=builder.bitcast(data, cary.data.type), + shape=cshape, + strides=cstrides, + itemsize=intp_itemsize, + parent=rt_addr, + meminfo=None) + + return cary._getvalue() + + def add_dynamic_addr(self, builder, intaddr, info): + """ + Returns dynamic address as a void pointer `i8*`. + + Internally, a global variable is added to inform the lowerer about + the usage of dynamic addresses. Caching will be disabled. + """ + assert self.allow_dynamic_globals, "dyn globals disabled in this target" + assert isinstance(intaddr, int), 'dyn addr not of int type' + mod = builder.module + llvoidptr = self.get_value_type(types.voidptr) + addr = self.get_constant(types.uintp, intaddr).inttoptr(llvoidptr) + # Use a unique name by embedding the address value + symname = 'numba.dynamic.globals.{:x}'.format(intaddr) + gv = cgutils.add_global_variable(mod, llvoidptr, symname) + # Use linkonce linkage to allow merging with other GV of the same name. + # And, avoid optimization from assuming its value. + gv.linkage = 'linkonce' + gv.initializer = addr + return builder.load(gv) + + def get_abi_sizeof(self, ty): + """ + Get the ABI size of LLVM type *ty*. + """ + assert isinstance(ty, llvmir.Type), "Expected LLVM type" + return ty.get_abi_size(self.target_data) + + def get_abi_alignment(self, ty): + """ + Get the ABI alignment of LLVM type *ty*. + """ + assert isinstance(ty, llvmir.Type), "Expected LLVM type" + return ty.get_abi_alignment(self.target_data) + + def get_preferred_array_alignment(context, ty): + """ + Get preferred array alignment for Numba type *ty*. + """ + # AVX prefers 32-byte alignment + return 32 + + def post_lowering(self, mod, library): + """Run target specific post-lowering transformation here. + """ + + def create_module(self, name): + """Create a LLVM module + + The default implementation in BaseContext always raises a + ``NotImplementedError`` exception. Subclasses should implement + this method. + """ + raise NotImplementedError + + @property + def active_code_library(self): + """Get the active code library + """ + return self._codelib_stack[-1] + + @contextmanager + def push_code_library(self, lib): + """Push the active code library for the context + """ + self._codelib_stack.append(lib) + try: + yield + finally: + self._codelib_stack.pop() + + def add_linking_libs(self, libs): + """Add iterable of linking libraries to the *active_code_library*. + """ + colib = self.active_code_library + for lib in libs: + colib.add_linking_library(lib) + + def get_ufunc_info(self, ufunc_key): + """Get the ufunc implementation for a given ufunc object. + + The default implementation in BaseContext always raises a + ``NotImplementedError`` exception. Subclasses may raise ``KeyError`` + to signal that the given ``ufunc_key`` is not available. + + Parameters + ---------- + ufunc_key : NumPy ufunc + + Returns + ------- + res : dict[str, callable] + A mapping of a NumPy ufunc type signature to a lower-level + implementation. + """ + raise NotImplementedError(f"{self} does not support ufunc") + +class _wrap_impl(object): + """ + A wrapper object to call an implementation function with some predefined + (context, signature) arguments. + The wrapper also forwards attribute queries, which is important. + """ + + def __init__(self, imp, context, sig): + self._callable = _wrap_missing_loc(imp) + self._imp = self._callable() + self._context = context + self._sig = sig + + def __call__(self, builder, args, loc=None): + res = self._imp(self._context, builder, self._sig, args, loc=loc) + self._context.add_linking_libs(getattr(self, 'libs', ())) + return res + + def __getattr__(self, item): + return getattr(self._imp, item) + + def __repr__(self): + return "" % repr(self._callable) + +def _has_loc(fn): + """Does function *fn* take ``loc`` argument? + """ + sig = utils.pysignature(fn) + return 'loc' in sig.parameters + + +class _wrap_missing_loc(object): + + def __init__(self, fn): + self.func = fn # store this to help with debug + + def __call__(self): + """Wrap function for missing ``loc`` keyword argument. + Otherwise, return the original *fn*. + """ + fn = self.func + if not _has_loc(fn): + def wrapper(*args, **kwargs): + kwargs.pop('loc') # drop unused loc + return fn(*args, **kwargs) + + # Copy the following attributes from the wrapped. + # Following similar implementation as functools.wraps but + # ignore attributes if not available (i.e fix py2.7) + attrs = '__name__', 'libs' + for attr in attrs: + try: + val = getattr(fn, attr) + except AttributeError: + pass + else: + setattr(wrapper, attr, val) + + return wrapper + else: + return fn + + def __repr__(self): + return "" % self.func + + +@utils.runonce +def _initialize_llvm_lock_event(): + """Initial event triggers for LLVM lock + """ + def enter_fn(): + event.start_event("numba:llvm_lock") + + def exit_fn(): + event.end_event("numba:llvm_lock") + + ll.ffi.register_lock_callback(enter_fn, exit_fn) + + +_initialize_llvm_lock_event() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/boxing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/boxing.py new file mode 100644 index 0000000000000000000000000000000000000000..0432f35243438ea6efea19e581e2b5c54d74923d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/boxing.py @@ -0,0 +1,1313 @@ +""" +Boxing and unboxing of native Numba values to / from CPython objects. +""" + +from llvmlite import ir + +from numba.core import types, cgutils +from numba.core.pythonapi import box, unbox, reflect, NativeValue +from numba.core.errors import NumbaNotImplementedError, TypingError +from numba.core.typing.typeof import typeof, Purpose + +from numba.cpython import setobj, listobj +from numba.np import numpy_support +from contextlib import contextmanager, ExitStack + + +# +# Scalar types +# + +@box(types.Boolean) +def box_bool(typ, val, c): + return c.pyapi.bool_from_bool(val) + +@unbox(types.Boolean) +def unbox_boolean(typ, obj, c): + istrue = c.pyapi.object_istrue(obj) + zero = ir.Constant(istrue.type, 0) + val = c.builder.icmp_signed('!=', istrue, zero) + return NativeValue(val, is_error=c.pyapi.c_api_error()) + + +@box(types.IntegerLiteral) +@box(types.BooleanLiteral) +def box_literal_integer(typ, val, c): + val = c.context.cast(c.builder, val, typ, typ.literal_type) + return c.box(typ.literal_type, val) + + +@box(types.Integer) +def box_integer(typ, val, c): + if typ.signed: + ival = c.builder.sext(val, c.pyapi.longlong) + return c.pyapi.long_from_longlong(ival) + else: + ullval = c.builder.zext(val, c.pyapi.ulonglong) + return c.pyapi.long_from_ulonglong(ullval) + +@unbox(types.Integer) +def unbox_integer(typ, obj, c): + ll_type = c.context.get_argument_type(typ) + val = cgutils.alloca_once(c.builder, ll_type) + longobj = c.pyapi.number_long(obj) + with c.pyapi.if_object_ok(longobj): + if typ.signed: + llval = c.pyapi.long_as_longlong(longobj) + else: + llval = c.pyapi.long_as_ulonglong(longobj) + c.pyapi.decref(longobj) + c.builder.store(c.builder.trunc(llval, ll_type), val) + return NativeValue(c.builder.load(val), + is_error=c.pyapi.c_api_error()) + + +@box(types.Float) +def box_float(typ, val, c): + if typ == types.float32: + dbval = c.builder.fpext(val, c.pyapi.double) + else: + assert typ == types.float64 + dbval = val + return c.pyapi.float_from_double(dbval) + +@unbox(types.Float) +def unbox_float(typ, obj, c): + fobj = c.pyapi.number_float(obj) + dbval = c.pyapi.float_as_double(fobj) + c.pyapi.decref(fobj) + if typ == types.float32: + val = c.builder.fptrunc(dbval, + c.context.get_argument_type(typ)) + else: + assert typ == types.float64 + val = dbval + return NativeValue(val, is_error=c.pyapi.c_api_error()) + + +@box(types.Complex) +def box_complex(typ, val, c): + cval = c.context.make_complex(c.builder, typ, value=val) + + if typ == types.complex64: + freal = c.builder.fpext(cval.real, c.pyapi.double) + fimag = c.builder.fpext(cval.imag, c.pyapi.double) + else: + assert typ == types.complex128 + freal, fimag = cval.real, cval.imag + return c.pyapi.complex_from_doubles(freal, fimag) + +@unbox(types.Complex) +def unbox_complex(typ, obj, c): + # First unbox to complex128, since that's what CPython gives us + c128 = c.context.make_complex(c.builder, types.complex128) + ok = c.pyapi.complex_adaptor(obj, c128._getpointer()) + failed = cgutils.is_false(c.builder, ok) + + with cgutils.if_unlikely(c.builder, failed): + c.pyapi.err_set_string("PyExc_TypeError", + "conversion to %s failed" % (typ,)) + + if typ == types.complex64: + # Downcast to complex64 if necessary + cplx = c.context.make_complex(c.builder, typ) + cplx.real = c.context.cast(c.builder, c128.real, + types.float64, types.float32) + cplx.imag = c.context.cast(c.builder, c128.imag, + types.float64, types.float32) + else: + assert typ == types.complex128 + cplx = c128 + return NativeValue(cplx._getvalue(), is_error=failed) + + +@box(types.NoneType) +def box_none(typ, val, c): + return c.pyapi.make_none() + +@unbox(types.NoneType) +@unbox(types.EllipsisType) +def unbox_none(typ, val, c): + return NativeValue(c.context.get_dummy_value()) + + +@box(types.NPDatetime) +def box_npdatetime(typ, val, c): + return c.pyapi.create_np_datetime(val, typ.unit_code) + +@unbox(types.NPDatetime) +def unbox_npdatetime(typ, obj, c): + val = c.pyapi.extract_np_datetime(obj) + return NativeValue(val, is_error=c.pyapi.c_api_error()) + + +@box(types.NPTimedelta) +def box_nptimedelta(typ, val, c): + return c.pyapi.create_np_timedelta(val, typ.unit_code) + +@unbox(types.NPTimedelta) +def unbox_nptimedelta(typ, obj, c): + val = c.pyapi.extract_np_timedelta(obj) + return NativeValue(val, is_error=c.pyapi.c_api_error()) + + +@box(types.RawPointer) +def box_raw_pointer(typ, val, c): + """ + Convert a raw pointer to a Python int. + """ + ll_intp = c.context.get_value_type(types.uintp) + addr = c.builder.ptrtoint(val, ll_intp) + return c.box(types.uintp, addr) + + +@box(types.EnumMember) +def box_enum(typ, val, c): + """ + Fetch an enum member given its native value. + """ + valobj = c.box(typ.dtype, val) + # Call the enum class with the value object + cls_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.instance_class)) + return c.pyapi.call_function_objargs(cls_obj, (valobj,)) + + +@unbox(types.EnumMember) +def unbox_enum(typ, obj, c): + """ + Convert an enum member's value to its native value. + """ + valobj = c.pyapi.object_getattr_string(obj, "value") + return c.unbox(typ.dtype, valobj) + + +@box(types.UndefVar) +def box_undefvar(typ, val, c): + """This type cannot be boxed, there's no Python equivalent""" + msg = ("UndefVar type cannot be boxed, there is no Python equivalent of " + "this type.") + raise TypingError(msg) + +# +# Composite types +# + +@box(types.Record) +def box_record(typ, val, c): + # Note we will create a copy of the record + # This is the only safe way. + size = ir.Constant(ir.IntType(32), val.type.pointee.count) + ptr = c.builder.bitcast(val, ir.PointerType(ir.IntType(8))) + return c.pyapi.recreate_record(ptr, size, typ.dtype, c.env_manager) + + +@unbox(types.Record) +def unbox_record(typ, obj, c): + buf = c.pyapi.alloca_buffer() + ptr = c.pyapi.extract_record_data(obj, buf) + is_error = cgutils.is_null(c.builder, ptr) + + ltyp = c.context.get_value_type(typ) + val = c.builder.bitcast(ptr, ltyp) + + def cleanup(): + c.pyapi.release_buffer(buf) + return NativeValue(val, cleanup=cleanup, is_error=is_error) + + +@box(types.UnicodeCharSeq) +def box_unicodecharseq(typ, val, c): + # XXX could kind be determined from strptr? + unicode_kind = { + 1: c.pyapi.py_unicode_1byte_kind, + 2: c.pyapi.py_unicode_2byte_kind, + 4: c.pyapi.py_unicode_4byte_kind}[numpy_support.sizeof_unicode_char] + kind = c.context.get_constant(types.int32, unicode_kind) + rawptr = cgutils.alloca_once_value(c.builder, value=val) + strptr = c.builder.bitcast(rawptr, c.pyapi.cstring) + + fullsize = c.context.get_constant(types.intp, typ.count) + zero = fullsize.type(0) + one = fullsize.type(1) + step = fullsize.type(numpy_support.sizeof_unicode_char) + count = cgutils.alloca_once_value(c.builder, zero) + with cgutils.loop_nest(c.builder, [fullsize], fullsize.type) as [idx]: + # Get char at idx + ch = c.builder.load(c.builder.gep(strptr, [c.builder.mul(idx, step)])) + # If the char is a non-null-byte, store the next index as count + with c.builder.if_then(cgutils.is_not_null(c.builder, ch)): + c.builder.store(c.builder.add(idx, one), count) + strlen = c.builder.load(count) + return c.pyapi.string_from_kind_and_data(kind, strptr, strlen) + + +@unbox(types.UnicodeCharSeq) +def unbox_unicodecharseq(typ, obj, c): + lty = c.context.get_value_type(typ) + + ok, buffer, size, kind, is_ascii, hashv = \ + c.pyapi.string_as_string_size_and_kind(obj) + + # If conversion is ok, copy the buffer to the output storage. + with cgutils.if_likely(c.builder, ok): + # Check if the returned string size fits in the charseq + storage_size = ir.Constant(size.type, typ.count) + size_fits = c.builder.icmp_unsigned("<=", size, storage_size) + + # Allow truncation of string + size = c.builder.select(size_fits, size, storage_size) + + # Initialize output to zero bytes + null_string = ir.Constant(lty, None) + outspace = cgutils.alloca_once_value(c.builder, null_string) + + # We don't need to set the NULL-terminator because the storage + # is already zero-filled. + cgutils.memcpy(c.builder, + c.builder.bitcast(outspace, buffer.type), + buffer, size) + + ret = c.builder.load(outspace) + return NativeValue(ret, is_error=c.builder.not_(ok)) + + +@box(types.Bytes) +def box_bytes(typ, val, c): + obj = c.context.make_helper(c.builder, typ, val) + ret = c.pyapi.bytes_from_string_and_size(obj.data, obj.nitems) + c.context.nrt.decref(c.builder, typ, val) + return ret + + +@box(types.CharSeq) +def box_charseq(typ, val, c): + rawptr = cgutils.alloca_once_value(c.builder, value=val) + strptr = c.builder.bitcast(rawptr, c.pyapi.cstring) + fullsize = c.context.get_constant(types.intp, typ.count) + zero = fullsize.type(0) + one = fullsize.type(1) + count = cgutils.alloca_once_value(c.builder, zero) + + # Find the length of the string, mimicking Numpy's behaviour: + # search for the last non-null byte in the underlying storage + # (e.g. b'A\0\0B\0\0\0' will return the logical string b'A\0\0B') + with cgutils.loop_nest(c.builder, [fullsize], fullsize.type) as [idx]: + # Get char at idx + ch = c.builder.load(c.builder.gep(strptr, [idx])) + # If the char is a non-null-byte, store the next index as count + with c.builder.if_then(cgutils.is_not_null(c.builder, ch)): + c.builder.store(c.builder.add(idx, one), count) + + strlen = c.builder.load(count) + return c.pyapi.bytes_from_string_and_size(strptr, strlen) + + +@unbox(types.CharSeq) +def unbox_charseq(typ, obj, c): + lty = c.context.get_value_type(typ) + ok, buffer, size = c.pyapi.string_as_string_and_size(obj) + + # If conversion is ok, copy the buffer to the output storage. + with cgutils.if_likely(c.builder, ok): + # Check if the returned string size fits in the charseq + storage_size = ir.Constant(size.type, typ.count) + size_fits = c.builder.icmp_unsigned("<=", size, storage_size) + + # Allow truncation of string + size = c.builder.select(size_fits, size, storage_size) + + # Initialize output to zero bytes + null_string = ir.Constant(lty, None) + outspace = cgutils.alloca_once_value(c.builder, null_string) + + # We don't need to set the NULL-terminator because the storage + # is already zero-filled. + cgutils.memcpy(c.builder, + c.builder.bitcast(outspace, buffer.type), + buffer, size) + + ret = c.builder.load(outspace) + return NativeValue(ret, is_error=c.builder.not_(ok)) + + +@box(types.Optional) +def box_optional(typ, val, c): + optval = c.context.make_helper(c.builder, typ, val) + ret = cgutils.alloca_once_value(c.builder, c.pyapi.borrow_none()) + with c.builder.if_else(optval.valid) as (then, otherwise): + with then: + validres = c.box(typ.type, optval.data) + c.builder.store(validres, ret) + with otherwise: + c.builder.store(c.pyapi.make_none(), ret) + return c.builder.load(ret) + + +@unbox(types.Optional) +def unbox_optional(typ, obj, c): + """ + Convert object *obj* to a native optional structure. + """ + noneval = c.context.make_optional_none(c.builder, typ.type) + is_not_none = c.builder.icmp_signed('!=', obj, c.pyapi.borrow_none()) + + retptr = cgutils.alloca_once(c.builder, noneval.type) + errptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + + with c.builder.if_else(is_not_none) as (then, orelse): + with then: + native = c.unbox(typ.type, obj) + just = c.context.make_optional_value(c.builder, + typ.type, native.value) + c.builder.store(just, retptr) + c.builder.store(native.is_error, errptr) + + with orelse: + c.builder.store(noneval, retptr) + + if native.cleanup is not None: + def cleanup(): + with c.builder.if_then(is_not_none): + native.cleanup() + else: + cleanup = None + + ret = c.builder.load(retptr) + return NativeValue(ret, is_error=c.builder.load(errptr), + cleanup=cleanup) + + +@unbox(types.SliceType) +def unbox_slice(typ, obj, c): + """ + Convert object *obj* to a native slice structure. + """ + from numba.cpython import slicing + ok, start, stop, step = c.pyapi.slice_as_ints(obj) + sli = c.context.make_helper(c.builder, typ) + sli.start = start + sli.stop = stop + sli.step = step + return NativeValue(sli._getvalue(), is_error=c.builder.not_(ok)) + +@box(types.SliceLiteral) +def box_slice_literal(typ, val, c): + # Check for integer overflows at compile time. + slice_lit = typ.literal_value + for field_name in ("start", "stop", "step"): + field_obj = getattr(slice_lit, field_name) + if isinstance(field_obj, int): + try: + typeof(field_obj, Purpose) + except ValueError as e: + raise ValueError(( + f"Unable to create literal slice. " + f"Error encountered with {field_name} " + f"attribute. {str(e)}") + ) + + py_ctor, py_args = typ.literal_value.__reduce__() + serialized_ctor = c.pyapi.serialize_object(py_ctor) + serialized_args = c.pyapi.serialize_object(py_args) + ctor = c.pyapi.unserialize(serialized_ctor) + args = c.pyapi.unserialize(serialized_args) + obj = c.pyapi.call(ctor, args) + c.pyapi.decref(ctor) + c.pyapi.decref(args) + return obj + +@unbox(types.StringLiteral) +def unbox_string_literal(typ, obj, c): + # A string literal is a dummy value + return NativeValue(c.context.get_dummy_value()) + +# +# Collections +# + +# NOTE: boxing functions are supposed to steal any NRT references in +# the given native value. + +@box(types.Array) +def box_array(typ, val, c): + nativearycls = c.context.make_array(typ) + nativeary = nativearycls(c.context, c.builder, value=val) + if c.context.enable_nrt: + np_dtype = numpy_support.as_dtype(typ.dtype) + dtypeptr = c.env_manager.read_const(c.env_manager.add_const(np_dtype)) + newary = c.pyapi.nrt_adapt_ndarray_to_python(typ, val, dtypeptr) + # Steals NRT ref + c.context.nrt.decref(c.builder, typ, val) + return newary + else: + parent = nativeary.parent + c.pyapi.incref(parent) + return parent + + +@unbox(types.Buffer) +def unbox_buffer(typ, obj, c): + """ + Convert a Py_buffer-providing object to a native array structure. + """ + buf = c.pyapi.alloca_buffer() + res = c.pyapi.get_buffer(obj, buf) + is_error = cgutils.is_not_null(c.builder, res) + + nativearycls = c.context.make_array(typ) + nativeary = nativearycls(c.context, c.builder) + aryptr = nativeary._getpointer() + + with cgutils.if_likely(c.builder, c.builder.not_(is_error)): + ptr = c.builder.bitcast(aryptr, c.pyapi.voidptr) + if c.context.enable_nrt: + c.pyapi.nrt_adapt_buffer_from_python(buf, ptr) + else: + c.pyapi.numba_buffer_adaptor(buf, ptr) + + def cleanup(): + c.pyapi.release_buffer(buf) + + return NativeValue(c.builder.load(aryptr), is_error=is_error, + cleanup=cleanup) + +@unbox(types.Array) +def unbox_array(typ, obj, c): + """ + Convert a Numpy array object to a native array structure. + """ + # This is necessary because unbox_buffer() does not work on some + # dtypes, e.g. datetime64 and timedelta64. + # TODO check matching dtype. + # currently, mismatching dtype will still work and causes + # potential memory corruption + nativearycls = c.context.make_array(typ) + nativeary = nativearycls(c.context, c.builder) + aryptr = nativeary._getpointer() + + ptr = c.builder.bitcast(aryptr, c.pyapi.voidptr) + if c.context.enable_nrt: + errcode = c.pyapi.nrt_adapt_ndarray_from_python(obj, ptr) + else: + errcode = c.pyapi.numba_array_adaptor(obj, ptr) + + # TODO: here we have minimal typechecking by the itemsize. + # need to do better + try: + expected_itemsize = numpy_support.as_dtype(typ.dtype).itemsize + except NumbaNotImplementedError: + # Don't check types that can't be `as_dtype()`-ed + itemsize_mismatch = cgutils.false_bit + else: + expected_itemsize = nativeary.itemsize.type(expected_itemsize) + itemsize_mismatch = c.builder.icmp_unsigned( + '!=', + nativeary.itemsize, + expected_itemsize, + ) + + failed = c.builder.or_( + cgutils.is_not_null(c.builder, errcode), + itemsize_mismatch, + ) + # Handle error + with c.builder.if_then(failed, likely=False): + c.pyapi.err_set_string("PyExc_TypeError", + "can't unbox array from PyObject into " + "native value. The object maybe of a " + "different type") + return NativeValue(c.builder.load(aryptr), is_error=failed) + + +@box(types.Tuple) +@box(types.UniTuple) +def box_tuple(typ, val, c): + """ + Convert native array or structure *val* to a tuple object. + """ + tuple_val = c.pyapi.tuple_new(typ.count) + + for i, dtype in enumerate(typ): + item = c.builder.extract_value(val, i) + obj = c.box(dtype, item) + c.pyapi.tuple_setitem(tuple_val, i, obj) + + return tuple_val + +@box(types.NamedTuple) +@box(types.NamedUniTuple) +def box_namedtuple(typ, val, c): + """ + Convert native array or structure *val* to a namedtuple object. + """ + cls_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.instance_class)) + tuple_obj = box_tuple(typ, val, c) + obj = c.pyapi.call(cls_obj, tuple_obj) + c.pyapi.decref(cls_obj) + c.pyapi.decref(tuple_obj) + return obj + + +@unbox(types.BaseTuple) +def unbox_tuple(typ, obj, c): + """ + Convert tuple *obj* to a native array (if homogeneous) or structure. + """ + n = len(typ) + values = [] + cleanups = [] + lty = c.context.get_value_type(typ) + + is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + value_ptr = cgutils.alloca_once(c.builder, lty) + + # Issue #1638: need to check the tuple size + actual_size = c.pyapi.tuple_size(obj) + size_matches = c.builder.icmp_unsigned('==', actual_size, + ir.Constant(actual_size.type, n)) + with c.builder.if_then(c.builder.not_(size_matches), likely=False): + c.pyapi.err_format( + "PyExc_ValueError", + "size mismatch for tuple, expected %d element(s) but got %%zd" % (n,), + actual_size) + c.builder.store(cgutils.true_bit, is_error_ptr) + + # We unbox the items even if not `size_matches`, to avoid issues with + # the generated IR (instruction doesn't dominate all uses) + for i, eltype in enumerate(typ): + elem = c.pyapi.tuple_getitem(obj, i) + native = c.unbox(eltype, elem) + values.append(native.value) + with c.builder.if_then(native.is_error, likely=False): + c.builder.store(cgutils.true_bit, is_error_ptr) + if native.cleanup is not None: + cleanups.append(native.cleanup) + + value = c.context.make_tuple(c.builder, typ, values) + c.builder.store(value, value_ptr) + + if cleanups: + with c.builder.if_then(size_matches, likely=True): + def cleanup(): + for func in reversed(cleanups): + func() + else: + cleanup = None + + return NativeValue(c.builder.load(value_ptr), cleanup=cleanup, + is_error=c.builder.load(is_error_ptr)) + + +@box(types.List) +def box_list(typ, val, c): + """ + Convert native list *val* to a list object. + """ + list = listobj.ListInstance(c.context, c.builder, typ, val) + obj = list.parent + res = cgutils.alloca_once_value(c.builder, obj) + with c.builder.if_else(cgutils.is_not_null(c.builder, obj)) as (has_parent, otherwise): + with has_parent: + # List is actually reflected => return the original object + # (note not all list instances whose *type* is reflected are + # actually reflected; see numba.tests.test_lists for an example) + c.pyapi.incref(obj) + + with otherwise: + # Build a new Python list + nitems = list.size + obj = c.pyapi.list_new(nitems) + with c.builder.if_then(cgutils.is_not_null(c.builder, obj), + likely=True): + with cgutils.for_range(c.builder, nitems) as loop: + item = list.getitem(loop.index) + list.incref_value(item) + itemobj = c.box(typ.dtype, item) + c.pyapi.list_setitem(obj, loop.index, itemobj) + + c.builder.store(obj, res) + + # Steal NRT ref + c.context.nrt.decref(c.builder, typ, val) + return c.builder.load(res) + + +class _NumbaTypeHelper(object): + """A helper for acquiring `numba.typeof` for type checking. + + Usage + ----- + + # `c` is the boxing context. + with _NumbaTypeHelper(c) as nth: + # This contextmanager maintains the lifetime of the `numba.typeof` + # function. + the_numba_type = nth.typeof(some_object) + # Do work on the type object + do_checks(the_numba_type) + # Cleanup + c.pyapi.decref(the_numba_type) + # At this point *nth* should not be used. + """ + def __init__(self, c): + self.c = c + + def __enter__(self): + c = self.c + numba_name = c.context.insert_const_string(c.builder.module, 'numba') + numba_mod = c.pyapi.import_module(numba_name) + typeof_fn = c.pyapi.object_getattr_string(numba_mod, 'typeof') + self.typeof_fn = typeof_fn + c.pyapi.decref(numba_mod) + return self + + def __exit__(self, *args, **kwargs): + c = self.c + c.pyapi.decref(self.typeof_fn) + + def typeof(self, obj): + res = self.c.pyapi.call_function_objargs(self.typeof_fn, [obj]) + return res + + +def _python_list_to_native(typ, obj, c, size, listptr, errorptr): + """ + Construct a new native list from a Python list. + """ + def check_element_type(nth, itemobj, expected_typobj): + typobj = nth.typeof(itemobj) + # Check if *typobj* is NULL + with c.builder.if_then( + cgutils.is_null(c.builder, typobj), + likely=False, + ): + c.builder.store(cgutils.true_bit, errorptr) + loop.do_break() + # Mandate that objects all have the same exact type + type_mismatch = c.builder.icmp_signed('!=', typobj, expected_typobj) + + with c.builder.if_then(type_mismatch, likely=False): + c.builder.store(cgutils.true_bit, errorptr) + c.pyapi.err_format( + "PyExc_TypeError", + "can't unbox heterogeneous list: %S != %S", + expected_typobj, typobj, + ) + c.pyapi.decref(typobj) + loop.do_break() + c.pyapi.decref(typobj) + + # Allocate a new native list + ok, list = listobj.ListInstance.allocate_ex(c.context, c.builder, typ, size) + with c.builder.if_else(ok, likely=True) as (if_ok, if_not_ok): + with if_ok: + list.size = size + zero = ir.Constant(size.type, 0) + with c.builder.if_then(c.builder.icmp_signed('>', size, zero), + likely=True): + # Traverse Python list and unbox objects into native list + with _NumbaTypeHelper(c) as nth: + # Note: *expected_typobj* can't be NULL + expected_typobj = nth.typeof(c.pyapi.list_getitem(obj, zero)) + with cgutils.for_range(c.builder, size) as loop: + itemobj = c.pyapi.list_getitem(obj, loop.index) + check_element_type(nth, itemobj, expected_typobj) + # XXX we don't call native cleanup for each + # list element, since that would require keeping + # of which unboxings have been successful. + native = c.unbox(typ.dtype, itemobj) + with c.builder.if_then(native.is_error, likely=False): + c.builder.store(cgutils.true_bit, errorptr) + loop.do_break() + # The reference is borrowed so incref=False + list.setitem(loop.index, native.value, incref=False) + c.pyapi.decref(expected_typobj) + if typ.reflected: + list.parent = obj + # Stuff meminfo pointer into the Python object for + # later reuse. + with c.builder.if_then(c.builder.not_(c.builder.load(errorptr)), + likely=False): + c.pyapi.object_set_private_data(obj, list.meminfo) + list.set_dirty(False) + c.builder.store(list.value, listptr) + + with if_not_ok: + c.builder.store(cgutils.true_bit, errorptr) + + # If an error occurred, drop the whole native list + with c.builder.if_then(c.builder.load(errorptr)): + c.context.nrt.decref(c.builder, typ, list.value) + + +@unbox(types.List) +def unbox_list(typ, obj, c): + """ + Convert list *obj* to a native list. + + If list was previously unboxed, we reuse the existing native list + to ensure consistency. + """ + size = c.pyapi.list_size(obj) + + errorptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + listptr = cgutils.alloca_once(c.builder, c.context.get_value_type(typ)) + + # See if the list was previously unboxed, if so, re-use the meminfo. + ptr = c.pyapi.object_get_private_data(obj) + + with c.builder.if_else(cgutils.is_not_null(c.builder, ptr)) \ + as (has_meminfo, otherwise): + + with has_meminfo: + # List was previously unboxed => reuse meminfo + list = listobj.ListInstance.from_meminfo(c.context, c.builder, typ, ptr) + list.size = size + if typ.reflected: + list.parent = obj + c.builder.store(list.value, listptr) + + with otherwise: + _python_list_to_native(typ, obj, c, size, listptr, errorptr) + + def cleanup(): + # Clean up the associated pointer, as the meminfo is now invalid. + c.pyapi.object_reset_private_data(obj) + + return NativeValue(c.builder.load(listptr), + is_error=c.builder.load(errorptr), + cleanup=cleanup) + + +@reflect(types.List) +def reflect_list(typ, val, c): + """ + Reflect the native list's contents into the Python object. + """ + if not typ.reflected: + return + if typ.dtype.reflected: + msg = "cannot reflect element of reflected container: {}\n".format(typ) + raise TypeError(msg) + + list = listobj.ListInstance(c.context, c.builder, typ, val) + with c.builder.if_then(list.dirty, likely=False): + obj = list.parent + size = c.pyapi.list_size(obj) + new_size = list.size + diff = c.builder.sub(new_size, size) + diff_gt_0 = c.builder.icmp_signed('>=', diff, + ir.Constant(diff.type, 0)) + with c.builder.if_else(diff_gt_0) as (if_grow, if_shrink): + # XXX no error checking below + with if_grow: + # First overwrite existing items + with cgutils.for_range(c.builder, size) as loop: + item = list.getitem(loop.index) + list.incref_value(item) + itemobj = c.box(typ.dtype, item) + c.pyapi.list_setitem(obj, loop.index, itemobj) + # Then add missing items + with cgutils.for_range(c.builder, diff) as loop: + idx = c.builder.add(size, loop.index) + item = list.getitem(idx) + list.incref_value(item) + itemobj = c.box(typ.dtype, item) + c.pyapi.list_append(obj, itemobj) + c.pyapi.decref(itemobj) + + with if_shrink: + # First delete list tail + c.pyapi.list_setslice(obj, new_size, size, None) + # Then overwrite remaining items + with cgutils.for_range(c.builder, new_size) as loop: + item = list.getitem(loop.index) + list.incref_value(item) + itemobj = c.box(typ.dtype, item) + c.pyapi.list_setitem(obj, loop.index, itemobj) + + # Mark the list clean, in case it is reflected twice + list.set_dirty(False) + + +def _python_set_to_native(typ, obj, c, size, setptr, errorptr): + """ + Construct a new native set from a Python set. + """ + # Allocate a new native set + ok, inst = setobj.SetInstance.allocate_ex(c.context, c.builder, typ, size) + with c.builder.if_else(ok, likely=True) as (if_ok, if_not_ok): + with if_ok: + # Traverse Python set and unbox objects into native set + typobjptr = cgutils.alloca_once_value(c.builder, + ir.Constant(c.pyapi.pyobj, None)) + + with c.pyapi.set_iterate(obj) as loop: + itemobj = loop.value + # Mandate that objects all have the same exact type + typobj = c.pyapi.get_type(itemobj) + expected_typobj = c.builder.load(typobjptr) + + with c.builder.if_else( + cgutils.is_null(c.builder, expected_typobj), + likely=False) as (if_first, if_not_first): + with if_first: + # First iteration => store item type + c.builder.store(typobj, typobjptr) + with if_not_first: + # Otherwise, check item type + type_mismatch = c.builder.icmp_signed('!=', typobj, + expected_typobj) + with c.builder.if_then(type_mismatch, likely=False): + c.builder.store(cgutils.true_bit, errorptr) + c.pyapi.err_set_string("PyExc_TypeError", + "can't unbox heterogeneous set") + loop.do_break() + + # XXX we don't call native cleanup for each set element, + # since that would require keeping track + # of which unboxings have been successful. + native = c.unbox(typ.dtype, itemobj) + with c.builder.if_then(native.is_error, likely=False): + c.builder.store(cgutils.true_bit, errorptr) + inst.add_pyapi(c.pyapi, native.value, do_resize=False) + + if typ.reflected: + inst.parent = obj + # Associate meminfo pointer with the Python object for later reuse. + with c.builder.if_then(c.builder.not_(c.builder.load(errorptr)), + likely=False): + c.pyapi.object_set_private_data(obj, inst.meminfo) + inst.set_dirty(False) + c.builder.store(inst.value, setptr) + + with if_not_ok: + c.builder.store(cgutils.true_bit, errorptr) + + # If an error occurred, drop the whole native set + with c.builder.if_then(c.builder.load(errorptr)): + c.context.nrt.decref(c.builder, typ, inst.value) + + +@unbox(types.Set) +def unbox_set(typ, obj, c): + """ + Convert set *obj* to a native set. + + If set was previously unboxed, we reuse the existing native set + to ensure consistency. + """ + size = c.pyapi.set_size(obj) + + errorptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + setptr = cgutils.alloca_once(c.builder, c.context.get_value_type(typ)) + + # See if the set was previously unboxed, if so, re-use the meminfo. + ptr = c.pyapi.object_get_private_data(obj) + + with c.builder.if_else(cgutils.is_not_null(c.builder, ptr)) \ + as (has_meminfo, otherwise): + + with has_meminfo: + # Set was previously unboxed => reuse meminfo + inst = setobj.SetInstance.from_meminfo(c.context, c.builder, typ, ptr) + if typ.reflected: + inst.parent = obj + c.builder.store(inst.value, setptr) + + with otherwise: + _python_set_to_native(typ, obj, c, size, setptr, errorptr) + + def cleanup(): + # Clean up the associated pointer, as the meminfo is now invalid. + c.pyapi.object_reset_private_data(obj) + + return NativeValue(c.builder.load(setptr), + is_error=c.builder.load(errorptr), + cleanup=cleanup) + + +def _native_set_to_python_list(typ, payload, c): + """ + Create a Python list from a native set's items. + """ + nitems = payload.used + listobj = c.pyapi.list_new(nitems) + ok = cgutils.is_not_null(c.builder, listobj) + with c.builder.if_then(ok, likely=True): + index = cgutils.alloca_once_value(c.builder, + ir.Constant(nitems.type, 0)) + with payload._iterate() as loop: + i = c.builder.load(index) + item = loop.entry.key + c.context.nrt.incref(c.builder, typ.dtype, item) + itemobj = c.box(typ.dtype, item) + c.pyapi.list_setitem(listobj, i, itemobj) + i = c.builder.add(i, ir.Constant(i.type, 1)) + c.builder.store(i, index) + + return ok, listobj + + +@box(types.Set) +def box_set(typ, val, c): + """ + Convert native set *val* to a set object. + """ + inst = setobj.SetInstance(c.context, c.builder, typ, val) + obj = inst.parent + res = cgutils.alloca_once_value(c.builder, obj) + + with c.builder.if_else(cgutils.is_not_null(c.builder, obj)) as (has_parent, otherwise): + with has_parent: + # Set is actually reflected => return the original object + # (note not all set instances whose *type* is reflected are + # actually reflected; see numba.tests.test_sets for an example) + c.pyapi.incref(obj) + + with otherwise: + # Build a new Python list and then create a set from that + payload = inst.payload + ok, listobj = _native_set_to_python_list(typ, payload, c) + with c.builder.if_then(ok, likely=True): + obj = c.pyapi.set_new(listobj) + c.pyapi.decref(listobj) + c.builder.store(obj, res) + + # Steal NRT ref + c.context.nrt.decref(c.builder, typ, val) + return c.builder.load(res) + +@reflect(types.Set) +def reflect_set(typ, val, c): + """ + Reflect the native set's contents into the Python object. + """ + if not typ.reflected: + return + inst = setobj.SetInstance(c.context, c.builder, typ, val) + payload = inst.payload + + with c.builder.if_then(payload.dirty, likely=False): + obj = inst.parent + # XXX errors are not dealt with below + c.pyapi.set_clear(obj) + + # Build a new Python list and then update the set with that + ok, listobj = _native_set_to_python_list(typ, payload, c) + with c.builder.if_then(ok, likely=True): + c.pyapi.set_update(obj, listobj) + c.pyapi.decref(listobj) + + # Mark the set clean, in case it is reflected twice + inst.set_dirty(False) + + +# +# Other types +# + +@box(types.Generator) +def box_generator(typ, val, c): + return c.pyapi.from_native_generator(val, typ, c.env_manager.env_ptr) + +@unbox(types.Generator) +def unbox_generator(typ, obj, c): + return c.pyapi.to_native_generator(obj, typ) + + +@box(types.DType) +def box_dtype(typ, val, c): + np_dtype = numpy_support.as_dtype(typ.dtype) + return c.pyapi.unserialize(c.pyapi.serialize_object(np_dtype)) + +@unbox(types.DType) +def unbox_dtype(typ, val, c): + return NativeValue(c.context.get_dummy_value()) + + +@box(types.NumberClass) +def box_number_class(typ, val, c): + np_dtype = numpy_support.as_dtype(typ.dtype) + return c.pyapi.unserialize(c.pyapi.serialize_object(np_dtype)) + +@unbox(types.NumberClass) +def unbox_number_class(typ, val, c): + return NativeValue(c.context.get_dummy_value()) + + +@box(types.PyObject) +@box(types.Object) +def box_pyobject(typ, val, c): + return val + +@unbox(types.PyObject) +@unbox(types.Object) +def unbox_pyobject(typ, obj, c): + return NativeValue(obj) + + +@unbox(types.ExternalFunctionPointer) +def unbox_funcptr(typ, obj, c): + if typ.get_pointer is None: + raise NotImplementedError(typ) + + # Call get_pointer() on the object to get the raw pointer value + ptrty = c.context.get_function_pointer_type(typ) + ret = cgutils.alloca_once_value(c.builder, + ir.Constant(ptrty, None), + name='fnptr') + ser = c.pyapi.serialize_object(typ.get_pointer) + get_pointer = c.pyapi.unserialize(ser) + with cgutils.if_likely(c.builder, + cgutils.is_not_null(c.builder, get_pointer)): + intobj = c.pyapi.call_function_objargs(get_pointer, (obj,)) + c.pyapi.decref(get_pointer) + with cgutils.if_likely(c.builder, + cgutils.is_not_null(c.builder, intobj)): + ptr = c.pyapi.long_as_voidptr(intobj) + c.pyapi.decref(intobj) + c.builder.store(c.builder.bitcast(ptr, ptrty), ret) + return NativeValue(c.builder.load(ret), is_error=c.pyapi.c_api_error()) + +@box(types.DeferredType) +def box_deferred(typ, val, c): + out = c.pyapi.from_native_value(typ.get(), + c.builder.extract_value(val, [0]), + env_manager=c.env_manager) + return out + + +@unbox(types.DeferredType) +def unbox_deferred(typ, obj, c): + native_value = c.pyapi.to_native_value(typ.get(), obj) + model = c.context.data_model_manager[typ] + res = model.set(c.builder, model.make_uninitialized(), native_value.value) + return NativeValue(res, is_error=native_value.is_error, + cleanup=native_value.cleanup) + + +@unbox(types.Dispatcher) +def unbox_dispatcher(typ, obj, c): + # In native code, Dispatcher types can be casted to FunctionType. + return NativeValue(obj) + + +@box(types.Dispatcher) +def box_pyobject(typ, val, c): + c.pyapi.incref(val) + return val + + +def unbox_unsupported(typ, obj, c): + c.pyapi.err_set_string("PyExc_TypeError", + "can't unbox {!r} type".format(typ)) + res = c.context.get_constant_null(typ) + return NativeValue(res, is_error=cgutils.true_bit) + + +def box_unsupported(typ, val, c): + msg = "cannot convert native %s to Python object" % (typ,) + c.pyapi.err_set_string("PyExc_TypeError", msg) + res = c.pyapi.get_null_object() + return res + + +@box(types.Literal) +def box_literal(typ, val, c): + # Const type contains the python object of the constant value, + # which we can directly return. + retval = typ.literal_value + # Serialize the value into the IR + return c.pyapi.unserialize(c.pyapi.serialize_object(retval)) + + +@box(types.MemInfoPointer) +def box_meminfo_pointer(typ, val, c): + return c.pyapi.nrt_meminfo_as_pyobject(val) + + +@unbox(types.MemInfoPointer) +def unbox_meminfo_pointer(typ, obj, c): + res = c.pyapi.nrt_meminfo_from_pyobject(obj) + errored = cgutils.is_null(c.builder, res) + return NativeValue(res, is_error=errored) + +@unbox(types.TypeRef) +def unbox_typeref(typ, val, c): + return NativeValue(c.context.get_dummy_value(), is_error=cgutils.false_bit) + + +@box(types.LiteralStrKeyDict) +def box_LiteralStrKeyDict(typ, val, c): + return box_unsupported(typ, val, c) + + +# Original implementation at: https://github.com/numba/numba/issues/4499#issuecomment-1063138477 +@unbox(types.NumPyRandomBitGeneratorType) +def unbox_numpy_random_bitgenerator(typ, obj, c): + """ + The bit_generator instance has a `.ctypes` attr which is a namedtuple + with the following members (types): + * state_address (Python int) + * state (ctypes.c_void_p) + * next_uint64 (ctypes.CFunctionType instance) + * next_uint32 (ctypes.CFunctionType instance) + * next_double (ctypes.CFunctionType instance) + * bit_generator (ctypes.c_void_p) + """ + + is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + extra_refs = [] + + def clear_extra_refs(): + for _ref in extra_refs: + c.pyapi.decref(_ref) + + def handle_failure(): + c.builder.store(cgutils.true_bit, is_error_ptr) + clear_extra_refs() + + with ExitStack() as stack: + + def object_getattr_safely(obj, attr): + attr_obj = c.pyapi.object_getattr_string(obj, attr) + extra_refs.append(attr_obj) + return attr_obj + + struct_ptr = cgutils.create_struct_proxy(typ)(c.context, c.builder) + struct_ptr.parent = obj + + # Get the .ctypes attr + ctypes_binding = object_getattr_safely(obj, 'ctypes') + with cgutils.early_exit_if_null(c.builder, stack, ctypes_binding): + handle_failure() + + # Look up the "state_address" member and wire it into the struct + interface_state_address = object_getattr_safely( + ctypes_binding, 'state_address') + with cgutils.early_exit_if_null(c.builder, stack, interface_state_address): + handle_failure() + + setattr(struct_ptr, 'state_address', + c.unbox(types.uintp, interface_state_address).value) + + # Look up the "state" member and wire it into the struct + interface_state = object_getattr_safely(ctypes_binding, 'state') + with cgutils.early_exit_if_null(c.builder, stack, interface_state): + handle_failure() + + interface_state_value = object_getattr_safely( + interface_state, 'value') + with cgutils.early_exit_if_null(c.builder, stack, interface_state_value): + handle_failure() + setattr( + struct_ptr, + 'state', + c.unbox( + types.uintp, + interface_state_value).value) + + # Want to store callable function pointers to these CFunctionTypes, so + # import ctypes and use it to cast the CFunctionTypes to c_void_p and + # store the results. + # First find ctypes.cast, and ctypes.c_void_p + ctypes_name = c.context.insert_const_string(c.builder.module, 'ctypes') + ctypes_module = c.pyapi.import_module(ctypes_name) + extra_refs.append(ctypes_module) + with cgutils.early_exit_if_null(c.builder, stack, ctypes_module): + handle_failure() + + ct_cast = object_getattr_safely(ctypes_module, 'cast') + with cgutils.early_exit_if_null(c.builder, stack, ct_cast): + handle_failure() + + ct_voidptr_ty = object_getattr_safely(ctypes_module, 'c_void_p') + with cgutils.early_exit_if_null(c.builder, stack, ct_voidptr_ty): + handle_failure() + + # This wires in the fnptrs referred to by name + def wire_in_fnptrs(name): + # Find the CFunctionType function + interface_next_fn = c.pyapi.object_getattr_string( + ctypes_binding, name) + + extra_refs.append(interface_next_fn) + with cgutils.early_exit_if_null(c.builder, stack, interface_next_fn): + handle_failure() + + # Want to do ctypes.cast(CFunctionType, ctypes.c_void_p), create an + # args tuple for that. + args = c.pyapi.tuple_pack([interface_next_fn, ct_voidptr_ty]) + with cgutils.early_exit_if_null(c.builder, stack, args): + handle_failure() + extra_refs.append(args) + + # Call ctypes.cast() + interface_next_fn_casted = c.pyapi.call(ct_cast, args) + extra_refs.append(interface_next_fn_casted) + + # Fetch the .value attr on the resulting ctypes.c_void_p for storage + # in the function pointer slot. + interface_next_fn_casted_value = object_getattr_safely( + interface_next_fn_casted, 'value') + with cgutils.early_exit_if_null(c.builder, stack, interface_next_fn_casted_value): + handle_failure() + + # Wire up + setattr(struct_ptr, f'fnptr_{name}', + c.unbox(types.uintp, interface_next_fn_casted_value).value) + + + wire_in_fnptrs('next_double') + wire_in_fnptrs('next_uint64') + wire_in_fnptrs('next_uint32') + + clear_extra_refs() + + return NativeValue(struct_ptr._getvalue(), is_error=c.builder.load(is_error_ptr)) + +_bit_gen_type = types.NumPyRandomBitGeneratorType('bit_generator') + +@unbox(types.NumPyRandomGeneratorType) +def unbox_numpy_random_generator(typ, obj, c): + """ + Here we're creating a NumPyRandomGeneratorType StructModel with following fields: + * ('bit_generator', _bit_gen_type): The unboxed BitGenerator associated with + this Generator object instance. + * ('parent', types.pyobject): Pointer to the original Generator PyObject. + * ('meminfo', types.MemInfoPointer(types.voidptr)): The information about the memory + stored at the pointer (to the original Generator PyObject). This is useful for + keeping track of reference counts within the Python runtime. Helps prevent cases + where deletion happens in Python runtime without NRT being awareness of it. + """ + is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit) + + with ExitStack() as stack: + struct_ptr = cgutils.create_struct_proxy(typ)(c.context, c.builder) + bit_gen_inst = c.pyapi.object_getattr_string(obj, 'bit_generator') + with cgutils.early_exit_if_null(c.builder, stack, bit_gen_inst): + c.builder.store(cgutils.true_bit, is_error_ptr) + unboxed = c.unbox(_bit_gen_type, bit_gen_inst).value + struct_ptr.bit_generator = unboxed + struct_ptr.parent = obj + NULL = cgutils.voidptr_t(None) + struct_ptr.meminfo = c.pyapi.nrt_meminfo_new_from_pyobject( + NULL, # there's no data + obj, # the python object, the call to nrt_meminfo_new_from_pyobject + # will py_incref + ) + c.pyapi.decref(bit_gen_inst) + + return NativeValue(struct_ptr._getvalue(), is_error=c.builder.load(is_error_ptr)) + + +@box(types.NumPyRandomGeneratorType) +def box_numpy_random_generator(typ, val, c): + inst = c.context.make_helper(c.builder, typ, val) + obj = inst.parent + res = cgutils.alloca_once_value(c.builder, obj) + c.pyapi.incref(obj) + # Steal NRT ref + c.context.nrt.decref(c.builder, typ, val) + return c.builder.load(res) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/bytecode.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/bytecode.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd4424da8636d067f1c4f7dc5d0c94fff8175df --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/bytecode.py @@ -0,0 +1,688 @@ +import sys +from collections import namedtuple, OrderedDict +import dis +import inspect +import itertools + +from types import CodeType, ModuleType + +from numba.core import errors, utils, serialize +from numba.core.utils import PYVERSION + + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + from opcode import _inline_cache_entries + # Instruction/opcode length in bytes + INSTR_LEN = 2 +elif PYVERSION in ((3, 10), (3, 11)): + pass +else: + raise NotImplementedError(PYVERSION) + + +opcode_info = namedtuple('opcode_info', ['argsize']) +_ExceptionTableEntry = namedtuple("_ExceptionTableEntry", + "start end target depth lasti") + +# The following offset is used as a hack to inject a NOP at the start of the +# bytecode. So that function starting with `while True` will not have block-0 +# as a jump target. The Lowerer puts argument initialization at block-0. +_FIXED_OFFSET = 2 + + +def get_function_object(obj): + """ + Objects that wraps function should provide a "__numba__" magic attribute + that contains a name of an attribute that contains the actual python + function object. + """ + attr = getattr(obj, "__numba__", None) + if attr: + return getattr(obj, attr) + return obj + + +def get_code_object(obj): + "Shamelessly borrowed from llpython" + return getattr(obj, '__code__', getattr(obj, 'func_code', None)) + + +def _as_opcodes(seq): + lst = [] + for s in seq: + c = dis.opmap.get(s) + if c is not None: + lst.append(c) + return lst + + +JREL_OPS = frozenset(dis.hasjrel) +JABS_OPS = frozenset(dis.hasjabs) +JUMP_OPS = JREL_OPS | JABS_OPS +TERM_OPS = frozenset(_as_opcodes(['RETURN_VALUE', 'RAISE_VARARGS'])) +EXTENDED_ARG = dis.EXTENDED_ARG +HAVE_ARGUMENT = dis.HAVE_ARGUMENT + + +class ByteCodeInst(object): + ''' + Attributes + ---------- + - offset: + byte offset of opcode + - opcode: + opcode integer value + - arg: + instruction arg + - lineno: + -1 means unknown + ''' + __slots__ = 'offset', 'next', 'opcode', 'opname', 'arg', 'lineno' + + def __init__(self, offset, opcode, arg, nextoffset): + self.offset = offset + self.next = nextoffset + self.opcode = opcode + self.opname = dis.opname[opcode] + self.arg = arg + self.lineno = -1 # unknown line number + + @property + def is_jump(self): + return self.opcode in JUMP_OPS + + @property + def is_terminator(self): + return self.opcode in TERM_OPS + + def get_jump_target(self): + # With Python 3.10 the addressing of "bytecode" instructions has + # changed from using bytes to using 16-bit words instead. As a + # consequence the code to determine where a jump will lead had to be + # adapted. + # See also: + # https://bugs.python.org/issue26647 + # https://bugs.python.org/issue27129 + # https://github.com/python/cpython/pull/25069 + assert self.is_jump + if PYVERSION in ((3, 13), (3, 14)): + if self.opcode in (dis.opmap[k] + for k in ["JUMP_BACKWARD", + "JUMP_BACKWARD_NO_INTERRUPT"]): + return self.next - (self.arg * 2) + elif PYVERSION in ((3, 12),): + if self.opcode in (dis.opmap[k] + for k in ["JUMP_BACKWARD"]): + return self.offset - (self.arg - 1) * 2 + elif PYVERSION in ((3, 11), ): + if self.opcode in (dis.opmap[k] + for k in ("JUMP_BACKWARD", + "POP_JUMP_BACKWARD_IF_TRUE", + "POP_JUMP_BACKWARD_IF_FALSE", + "POP_JUMP_BACKWARD_IF_NONE", + "POP_JUMP_BACKWARD_IF_NOT_NONE",)): + return self.offset - (self.arg - 1) * 2 + elif PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13), (3, 14)): + if self.opcode in JREL_OPS: + return self.next + self.arg * 2 + else: + assert self.opcode in JABS_OPS + return self.arg * 2 - 2 + else: + raise NotImplementedError(PYVERSION) + + def __repr__(self): + return '%s(arg=%s, lineno=%d)' % (self.opname, self.arg, self.lineno) + + @property + def block_effect(self): + """Effect of the block stack + Returns +1 (push), 0 (none) or -1 (pop) + """ + if self.opname.startswith('SETUP_'): + return 1 + elif self.opname == 'POP_BLOCK': + return -1 + else: + return 0 + + +CODE_LEN = 1 +ARG_LEN = 1 +NO_ARG_LEN = 1 + +OPCODE_NOP = dis.opname.index('NOP') + + +if PYVERSION in ((3, 13), (3, 14)): + + def _unpack_opargs(code): + buf = [] + for i, start_offset, op, arg in dis._unpack_opargs(code): + buf.append((start_offset, op, arg)) + for i, (start_offset, op, arg) in enumerate(buf): + if i + 1 < len(buf): + next_offset = buf[i + 1][0] + else: + next_offset = len(code) + yield (start_offset, op, arg, next_offset) + +elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + + # Adapted from Lib/dis.py + def _unpack_opargs(code): + """ + Returns a 4-int-tuple of + (bytecode offset, opcode, argument, offset of next bytecode). + """ + extended_arg = 0 + n = len(code) + offset = i = 0 + while i < n: + op = code[i] + i += CODE_LEN + if op >= HAVE_ARGUMENT: + arg = code[i] | extended_arg + for j in range(ARG_LEN): + arg |= code[i + j] << (8 * j) + i += ARG_LEN + if PYVERSION in ((3, 12),): + # Python 3.12 introduced cache slots. We need to account for + # cache slots when we determine the offset of the next + # opcode. The number of cache slots is specific to each + # opcode and can be looked up in the _inline_cache_entries + # dictionary. + i += _inline_cache_entries[op] * INSTR_LEN + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + if op == EXTENDED_ARG: + # This is a deviation from what dis does... + # In python 3.11 it seems like EXTENDED_ARGs appear more + # often and are also used as jump targets. So as to not have + # to do "book keeping" for where EXTENDED_ARGs have been + # "skipped" they are replaced with NOPs so as to provide a + # legal jump target and also ensure that the bytecode + # offsets are correct. + yield (offset, OPCODE_NOP, arg, i) + extended_arg = arg << 8 * ARG_LEN + offset = i + continue + else: + arg = None + i += NO_ARG_LEN + if PYVERSION in ((3, 12),): + # Python 3.12 introduced cache slots. We need to account for + # cache slots when we determine the offset of the next + # opcode. The number of cache slots is specific to each + # opcode and can be looked up in the _inline_cache_entries + # dictionary. + i += _inline_cache_entries[op] * INSTR_LEN + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + extended_arg = 0 + yield (offset, op, arg, i) + offset = i # Mark inst offset at first extended +else: + raise NotImplementedError(PYVERSION) + + +def _patched_opargs(bc_stream): + """Patch the bytecode stream. + + - Adds a NOP bytecode at the start to avoid jump target being at the entry. + """ + # Injected NOP + yield (0, OPCODE_NOP, None, _FIXED_OFFSET) + # Adjust bytecode offset for the rest of the stream + for offset, opcode, arg, nextoffset in bc_stream: + # If the opcode has an absolute jump target, adjust it. + if opcode in JABS_OPS: + arg += _FIXED_OFFSET + yield offset + _FIXED_OFFSET, opcode, arg, nextoffset + _FIXED_OFFSET + + +class ByteCodeIter(object): + def __init__(self, code): + self.code = code + self.iter = iter(_patched_opargs(_unpack_opargs(self.code.co_code))) + + def __iter__(self): + return self + + def _fetch_opcode(self): + return next(self.iter) + + def next(self): + offset, opcode, arg, nextoffset = self._fetch_opcode() + return offset, ByteCodeInst(offset=offset, opcode=opcode, arg=arg, + nextoffset=nextoffset) + + __next__ = next + + def read_arg(self, size): + buf = 0 + for i in range(size): + _offset, byte = next(self.iter) + buf |= byte << (8 * i) + return buf + + +class _ByteCode(object): + """ + The decoded bytecode of a function, and related information. + """ + __slots__ = ('func_id', 'co_names', 'co_varnames', 'co_consts', + 'co_cellvars', 'co_freevars', 'exception_entries', + 'table', 'labels') + + def __init__(self, func_id): + code = func_id.code + + labels = set(x + _FIXED_OFFSET for x in dis.findlabels(code.co_code)) + labels.add(0) + + # A map of {offset: ByteCodeInst} + table = OrderedDict(ByteCodeIter(code)) + self._compute_lineno(table, code) + + self.func_id = func_id + self.co_names = code.co_names + self.co_varnames = code.co_varnames + self.co_consts = code.co_consts + self.co_cellvars = code.co_cellvars + self.co_freevars = code.co_freevars + + self.table = table + self.labels = sorted(labels) + + @classmethod + def _compute_lineno(cls, table, code): + """ + Compute the line numbers for all bytecode instructions. + """ + for offset, lineno in dis.findlinestarts(code): + adj_offset = offset + _FIXED_OFFSET + if adj_offset in table: + table[adj_offset].lineno = lineno + # Assign unfilled lineno + # Start with first bytecode's lineno + known = code.co_firstlineno + for inst in table.values(): + if inst.lineno is not None and inst.lineno >= 0: + known = inst.lineno + else: + inst.lineno = known + return table + + def __iter__(self): + return iter(self.table.values()) + + def __getitem__(self, offset): + return self.table[offset] + + def __contains__(self, offset): + return offset in self.table + + def dump(self): + def label_marker(i): + if i[1].offset in self.labels: + return '>' + else: + return ' ' + + return '\n'.join('%s %10s\t%s' % ((label_marker(i),) + i) + for i in self.table.items() + if i[1].opname != "CACHE") + + @classmethod + def _compute_used_globals(cls, func, table, co_consts, co_names): + """ + Compute the globals used by the function with the given + bytecode table. + """ + d = {} + globs = func.__globals__ + builtins = globs.get('__builtins__', utils.builtins) + if isinstance(builtins, ModuleType): + builtins = builtins.__dict__ + # Look for LOAD_GLOBALs in the bytecode + for inst in table.values(): + if inst.opname == 'LOAD_GLOBAL': + name = co_names[_fix_LOAD_GLOBAL_arg(inst.arg)] + if name not in d: + try: + value = globs[name] + except KeyError: + value = builtins[name] + d[name] = value + # Add globals used by any nested code object + for co in co_consts: + if isinstance(co, CodeType): + subtable = OrderedDict(ByteCodeIter(co)) + d.update(cls._compute_used_globals(func, subtable, + co.co_consts, co.co_names)) + return d + + def get_used_globals(self): + """ + Get a {name: value} map of the globals used by this code + object and any nested code objects. + """ + return self._compute_used_globals(self.func_id.func, self.table, + self.co_consts, self.co_names) + + +def _fix_LOAD_GLOBAL_arg(arg): + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + return arg >> 1 + elif PYVERSION in ((3, 10),): + return arg + else: + raise NotImplementedError(PYVERSION) + + +class ByteCodePy311(_ByteCode): + + def __init__(self, func_id): + super().__init__(func_id) + entries = dis.Bytecode(func_id.code).exception_entries + self.exception_entries = tuple(map(self.fixup_eh, entries)) + + @staticmethod + def fixup_eh(ent): + # Patch up the exception table offset + # because we add a NOP in _patched_opargs + out = dis._ExceptionTableEntry( + start=ent.start + _FIXED_OFFSET, end=ent.end + _FIXED_OFFSET, + target=ent.target + _FIXED_OFFSET, + depth=ent.depth, lasti=ent.lasti, + ) + return out + + def find_exception_entry(self, offset): + """ + Returns the exception entry for the given instruction offset + """ + candidates = [] + for ent in self.exception_entries: + if ent.start <= offset < ent.end: + candidates.append((ent.depth, ent)) + if candidates: + ent = max(candidates)[1] + return ent + + +class ByteCodePy312(ByteCodePy311): + + def __init__(self, func_id): + super().__init__(func_id) + + # initialize lazy property + self._ordered_offsets = None + + # Fixup offsets for all exception entries. + entries = [self.fixup_eh(e) for e in + dis.Bytecode(func_id.code).exception_entries + ] + + # Remove exceptions, innermost ones first + # Can be done by using a stack + entries = self.remove_build_list_swap_pattern(entries) + + # If this is a generator, we need to skip any exception table entries + # that point to the exception handler with the highest offset. + if func_id.is_generator: + # Get the exception handler with the highest offset. + max_exception_target = max([e.target for e in entries]) + # Remove any exception table entries that point to that exception + # handler. + entries = [e for e in entries if e.target != max_exception_target] + + self.exception_entries = tuple(entries) + + @property + def ordered_offsets(self): + if not self._ordered_offsets: + # Get an ordered list of offsets. + self._ordered_offsets = [o for o in self.table] + return self._ordered_offsets + + def remove_build_list_swap_pattern(self, entries): + """ Find the following bytecode pattern: + + BUILD_{LIST, MAP, SET} + SWAP(2) + FOR_ITER + ... + END_FOR + SWAP(2) + + This pattern indicates that a list/dict/set comprehension has + been inlined. In this case we can skip the exception blocks + entirely along with the dead exceptions that it points to. + A pair of exception that sandwiches these exception will + also be merged into a single exception. + + Update for Python 3.13, the ending of the pattern has a extra + POP_TOP: + + ... + END_FOR + POP_TOP + SWAP(2) + + Update for Python 3.13.1, there's now a GET_ITER before FOR_ITER. + This patch the GET_ITER to NOP to minimize changes downstream + (e.g. array-comprehension). + """ + def pop_and_merge_exceptions(entries: list, + entry_to_remove: _ExceptionTableEntry): + lower_entry_idx = entries.index(entry_to_remove) - 1 + upper_entry_idx = entries.index(entry_to_remove) + 1 + + # Merge the upper and lower exceptions if possible. + if lower_entry_idx >= 0 and upper_entry_idx < len(entries): + lower_entry = entries[lower_entry_idx] + upper_entry = entries[upper_entry_idx] + if lower_entry.target == upper_entry.target: + entries[lower_entry_idx] = _ExceptionTableEntry( + lower_entry.start, + upper_entry.end, + lower_entry.target, + lower_entry.depth, + upper_entry.lasti) + entries.remove(upper_entry) + + # Remove the exception entry. + entries.remove(entry_to_remove) + # Remove dead exceptions, if any, that the entry above may point to. + entries = [e for e in entries + if not e.start == entry_to_remove.target] + return entries + + change_to_nop = set() + work_remaining = True + while work_remaining: + # Temporarily set work_remaining to False, if we find a pattern + # then work is not complete, hence we set it again to True. + work_remaining = False + current_nop_fixes = set() + for entry in entries.copy(): + # Check start of pattern, three instructions. + # Work out the index of the instruction. + index = self.ordered_offsets.index(entry.start) + # If there is a BUILD_{LIST, MAP, SET} instruction at this + # location. + curr_inst = self.table[self.ordered_offsets[index]] + if curr_inst.opname not in ("BUILD_LIST", + "BUILD_MAP", + "BUILD_SET"): + continue + # Check if the BUILD_{LIST, MAP, SET} instruction is followed + # by a SWAP(2). + next_inst = self.table[self.ordered_offsets[index + 1]] + if not next_inst.opname == "SWAP" and next_inst.arg == 2: + continue + next_inst = self.table[self.ordered_offsets[index + 2]] + # Check if the SWAP is followed by a FOR_ITER + # BUT Python3.13.1 introduced an extra GET_ITER. + # If we see a GET_ITER here, check if the next thing is a + # FOR_ITER. + if next_inst.opname == "GET_ITER": + # In Python 3.13.4, this becomes the only GET_ITER, + # so don't turn it into a NOP. + # Python 3.13.5 reverted the change. + if sys.version_info[:3] != (3, 13, 4): + # Add the inst to potentially be replaced to NOP. + current_nop_fixes.add(next_inst) + # Loop up next instruction. + next_inst = self.table[self.ordered_offsets[index + 3]] + + if not next_inst.opname == "FOR_ITER": + continue + + if PYVERSION in ((3, 13), (3, 14)): + # Check end of pattern, two instructions. + # Check for the corresponding END_FOR, exception table end + # is non-inclusive, so subtract one. + index = self.ordered_offsets.index(entry.end) + curr_inst = self.table[self.ordered_offsets[index - 2]] + if not curr_inst.opname == "END_FOR": + continue + next_inst = self.table[self.ordered_offsets[index - 1]] + if PYVERSION in ((3, 13), ): + if not next_inst.opname == "POP_TOP": + continue + elif PYVERSION in ((3, 14), ): + if not next_inst.opname == "POP_ITER": + continue + else: + raise NotImplementedError(PYVERSION) + # END_FOR must be followed by SWAP(2) + next_inst = self.table[self.ordered_offsets[index]] + if not next_inst.opname == "SWAP" and next_inst.arg == 2: + continue + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + # Check end of pattern, two instructions. + # Check for the corresponding END_FOR, exception table end + # is non-inclusive, so subtract one. + index = self.ordered_offsets.index(entry.end) + curr_inst = self.table[self.ordered_offsets[index - 1]] + if not curr_inst.opname == "END_FOR": + continue + # END_FOR must be followed by SWAP(2) + next_inst = self.table[self.ordered_offsets[index]] + if not next_inst.opname == "SWAP" and next_inst.arg == 2: + continue + else: + raise NotImplementedError(PYVERSION) + # If all conditions are met that means this exception entry + # is for a list/dict/set comprehension and can be removed. + # Also if there exist exception entries above and below this + # entry pointing to the same target. those can be merged into + # a single bigger exception block. + entries = pop_and_merge_exceptions(entries, entry) + work_remaining = True + + # Commit NOP fixes since we confirmed the suspects belong to + # a comprehension code. + change_to_nop |= current_nop_fixes + + # Complete fixes to NOPs + for inst in change_to_nop: + self.table[inst.offset] = ByteCodeInst(inst.offset, + dis.opmap["NOP"], + None, + inst.next) + return entries + + +if PYVERSION == (3, 11): + ByteCode = ByteCodePy311 +elif PYVERSION in ((3, 12), (3, 13), (3, 14)): + ByteCode = ByteCodePy312 +elif PYVERSION < (3, 11): + ByteCode = _ByteCode +else: + raise NotImplementedError(PYVERSION) + + +class FunctionIdentity(serialize.ReduceMixin): + """ + A function's identity and metadata. + + Note this typically represents a function whose bytecode is + being compiled, not necessarily the top-level user function + (the two might be distinct). + """ + _unique_ids = itertools.count(1) + + @classmethod + def from_function(cls, pyfunc): + """ + Create the FunctionIdentity of the given function. + """ + func = get_function_object(pyfunc) + code = get_code_object(func) + pysig = utils.pysignature(func) + if not code: + raise errors.ByteCodeSupportError( + "%s does not provide its bytecode" % func) + + try: + func_qualname = func.__qualname__ + except AttributeError: + func_qualname = func.__name__ + + self = cls() + self.func = func + self.func_qualname = func_qualname + self.func_name = func_qualname.split('.')[-1] + self.code = code + self.module = inspect.getmodule(func) + self.modname = (utils._dynamic_modname + if self.module is None + else self.module.__name__) + self.is_generator = inspect.isgeneratorfunction(func) + self.pysig = pysig + self.filename = code.co_filename + self.firstlineno = code.co_firstlineno + self.arg_count = len(pysig.parameters) + self.arg_names = list(pysig.parameters) + + # Even the same function definition can be compiled into + # several different function objects with distinct closure + # variables, so we make sure to disambiguate using an unique id. + uid = next(cls._unique_ids) + self.unique_name = '{}${}'.format(self.func_qualname, uid) + self.unique_id = uid + + return self + + def derive(self): + """Copy the object and increment the unique counter. + """ + return self.from_function(self.func) + + def _reduce_states(self): + """ + NOTE: part of ReduceMixin protocol + """ + return dict(pyfunc=self.func) + + @classmethod + def _rebuild(cls, pyfunc): + """ + NOTE: part of ReduceMixin protocol + """ + return cls.from_function(pyfunc) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/byteflow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/byteflow.py new file mode 100644 index 0000000000000000000000000000000000000000..931ee85cb43c69c110577c32d4dba2953da76759 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/byteflow.py @@ -0,0 +1,2458 @@ +""" +Implement python 3.8+ bytecode analysis +""" +import dis +import logging +from collections import namedtuple, defaultdict, deque +from functools import total_ordering + +from numba.core.utils import (UniqueDict, PYVERSION, ALL_BINOPS_TO_OPERATORS, + _lazy_pformat) +from numba.core.controlflow import NEW_BLOCKERS, CFGraph +from numba.core.ir import Loc +from numba.core.errors import UnsupportedBytecodeError + + +_logger = logging.getLogger(__name__) + +_EXCEPT_STACK_OFFSET = 6 +_FINALLY_POP = _EXCEPT_STACK_OFFSET +_NO_RAISE_OPS = frozenset({ + 'LOAD_CONST', + 'NOP', + 'LOAD_DEREF', + 'PRECALL', +}) + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + from enum import Enum + + # Operands for CALL_INTRINSIC_1 + class CALL_INTRINSIC_1_Operand(Enum): + INTRINSIC_STOPITERATION_ERROR = 3 + UNARY_POSITIVE = 5 + INTRINSIC_LIST_TO_TUPLE = 6 + ci1op = CALL_INTRINSIC_1_Operand +elif PYVERSION in ((3, 10), (3, 11)): + pass +else: + raise NotImplementedError(PYVERSION) + + +@total_ordering +class BlockKind(object): + """Kinds of block to make related code safer than just `str`. + """ + _members = frozenset({ + 'LOOP', + 'TRY', 'EXCEPT', 'FINALLY', + 'WITH', 'WITH_FINALLY', + }) + + def __init__(self, value): + assert value in self._members + self._value = value + + def __hash__(self): + return hash((type(self), self._value)) + + def __lt__(self, other): + if isinstance(other, BlockKind): + return self._value < other._value + else: + raise TypeError('cannot compare to {!r}'.format(type(other))) + + def __eq__(self, other): + if isinstance(other, BlockKind): + return self._value == other._value + else: + raise TypeError('cannot compare to {!r}'.format(type(other))) + + def __repr__(self): + return "BlockKind({})".format(self._value) + + +class Flow(object): + """Data+Control Flow analysis. + + Simulate execution to recover dataflow and controlflow information. + """ + def __init__(self, bytecode): + _logger.debug("bytecode dump:\n%s", + _lazy_pformat(bytecode, lazy_func=lambda x: x.dump())) + self._bytecode = bytecode + self.block_infos = UniqueDict() + + def run(self): + """Run a trace over the bytecode over all reachable path. + + The trace starts at bytecode offset 0 and gathers stack and control- + flow information by partially interpreting each bytecode. + Each ``State`` instance in the trace corresponds to a basic-block. + The State instances forks when a jump instruction is encountered. + A newly forked state is then added to the list of pending states. + The trace ends when there are no more pending states. + """ + firststate = State(bytecode=self._bytecode, pc=0, nstack=0, + blockstack=()) + runner = TraceRunner(debug_filename=self._bytecode.func_id.filename) + runner.pending.append(firststate) + + # Enforce unique-ness on initial PC to avoid re-entering the PC with + # a different stack-depth. We don't know if such a case is ever + # possible, but no such case has been encountered in our tests. + first_encounter = UniqueDict() + # Loop over each pending state at a initial PC. + # Each state is tracing a basic block + while runner.pending: + _logger.debug("pending: %s", runner.pending) + state = runner.pending.popleft() + if state not in runner.finished: + _logger.debug("stack: %s", state._stack) + _logger.debug("state.pc_initial: %s", state) + first_encounter[state.pc_initial] = state + # Loop over the state until it is terminated. + while True: + runner.dispatch(state) + # Terminated? + if state.has_terminated(): + break + else: + if self._run_handle_exception(runner, state): + break + + if self._is_implicit_new_block(state): + # check if this is a with...as, abort if so + self._guard_with_as(state) + # else split + state.split_new_block() + break + _logger.debug("end state. edges=%s", state.outgoing_edges) + runner.finished.add(state) + out_states = state.get_outgoing_states() + runner.pending.extend(out_states) + + # Complete controlflow + self._build_cfg(runner.finished) + # Prune redundant PHI-nodes + self._prune_phis(runner) + # Post process + for state in sorted(runner.finished, key=lambda x: x.pc_initial): + self.block_infos[state.pc_initial] = si = adapt_state_infos(state) + _logger.debug("block_infos %s:\n%s", state, si) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def _run_handle_exception(self, runner, state): + if not state.in_with() and ( + state.has_active_try() and + state.get_inst().opname not in _NO_RAISE_OPS): + # Is in a *try* block + state.fork(pc=state.get_inst().next) + runner._adjust_except_stack(state) + return True + else: + state.advance_pc() + + # Must the new PC be a new block? + if not state.in_with() and state.is_in_exception(): + _logger.debug("3.11 exception %s PC=%s", + state.get_exception(), state._pc) + eh = state.get_exception() + eh_top = state.get_top_block('TRY') + if eh_top and eh_top['end'] == eh.target: + # Same exception + eh_block = None + else: + eh_block = state.make_block("TRY", end=eh.target) + eh_block['end_offset'] = eh.end + eh_block['stack_depth'] = eh.depth + eh_block['push_lasti'] = eh.lasti + state.fork(pc=state._pc, extra_block=eh_block) + return True + elif PYVERSION in ((3, 10),): + def _run_handle_exception(self, runner, state): + if (state.has_active_try() and + state.get_inst().opname not in _NO_RAISE_OPS): + # Is in a *try* block + state.fork(pc=state.get_inst().next) + tryblk = state.get_top_block('TRY') + state.pop_block_and_above(tryblk) + nstack = state.stack_depth + kwargs = {} + if nstack > tryblk['entry_stack']: + kwargs['npop'] = nstack - tryblk['entry_stack'] + handler = tryblk['handler'] + kwargs['npush'] = { + BlockKind('EXCEPT'): _EXCEPT_STACK_OFFSET, + BlockKind('FINALLY'): _FINALLY_POP + }[handler['kind']] + kwargs['extra_block'] = handler + state.fork(pc=tryblk['end'], **kwargs) + return True + else: + state.advance_pc() + else: + raise NotImplementedError(PYVERSION) + + def _build_cfg(self, all_states): + graph = CFGraph() + for state in all_states: + b = state.pc_initial + graph.add_node(b) + for state in all_states: + for edge in state.outgoing_edges: + graph.add_edge(state.pc_initial, edge.pc, 0) + graph.set_entry_point(0) + graph.process() + self.cfgraph = graph + + def _prune_phis(self, runner): + # Find phis that are unused in the local block + _logger.debug("Prune PHIs".center(60, '-')) + + # Compute dataflow for used phis and propagate + + # 1. Get used-phis for each block + # Map block to used_phis + def get_used_phis_per_state(): + used_phis = defaultdict(set) + phi_set = set() + for state in runner.finished: + used = set(state._used_regs) + phis = set(state._phis) + used_phis[state] |= phis & used + phi_set |= phis + return used_phis, phi_set + + # Find use-defs + def find_use_defs(): + defmap = {} + phismap = defaultdict(set) + for state in runner.finished: + for phi, rhs in state._outgoing_phis.items(): + if rhs not in phi_set: + # Is a definition + defmap[phi] = state + phismap[phi].add((rhs, state)) + _logger.debug("defmap: %s", _lazy_pformat(defmap)) + _logger.debug("phismap: %s", _lazy_pformat(phismap)) + return defmap, phismap + + def propagate_phi_map(phismap): + """An iterative dataflow algorithm to find the definition + (the source) of each PHI node. + """ + blacklist = defaultdict(set) + + while True: + changing = False + for phi, defsites in sorted(list(phismap.items())): + for rhs, state in sorted(list(defsites)): + if rhs in phi_set: + defsites |= phismap[rhs] + blacklist[phi].add((rhs, state)) + to_remove = blacklist[phi] + if to_remove & defsites: + defsites -= to_remove + changing = True + + _logger.debug("changing phismap: %s", _lazy_pformat(phismap)) + if not changing: + break + + def apply_changes(used_phis, phismap): + keep = {} + for state, used_set in used_phis.items(): + for phi in used_set: + keep[phi] = phismap[phi] + _logger.debug("keep phismap: %s", _lazy_pformat(keep)) + new_out = defaultdict(dict) + for phi in keep: + for rhs, state in keep[phi]: + new_out[state][phi] = rhs + + _logger.debug("new_out: %s", _lazy_pformat(new_out)) + for state in runner.finished: + state._outgoing_phis.clear() + state._outgoing_phis.update(new_out[state]) + + used_phis, phi_set = get_used_phis_per_state() + _logger.debug("Used_phis: %s", _lazy_pformat(used_phis)) + defmap, phismap = find_use_defs() + propagate_phi_map(phismap) + apply_changes(used_phis, phismap) + _logger.debug("DONE Prune PHIs".center(60, '-')) + + def _is_implicit_new_block(self, state): + inst = state.get_inst() + + if inst.offset in self._bytecode.labels: + return True + elif inst.opname in NEW_BLOCKERS: + return True + else: + return False + + if PYVERSION in ((3, 14),): + def _guard_with_as(self, state): + # Handled as part of `LOAD_SPECIAL` as of 3.14. + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def _guard_with_as(self, state): + """Checks if the next instruction after a SETUP_WITH is something + other than a POP_TOP, if it is something else it'll be some sort of + store which is not supported (this corresponds to `with CTXMGR as + VAR(S)`).""" + current_inst = state.get_inst() + if current_inst.opname in {"SETUP_WITH", "BEFORE_WITH"}: + next_op = self._bytecode[current_inst.next].opname + if next_op != "POP_TOP": + msg = ("The 'with (context manager) as (variable):' " + "construct is not supported.") + raise UnsupportedBytecodeError(msg) + else: + raise NotImplementedError(PYVERSION) + + +def _is_null_temp_reg(reg): + return reg.startswith("$null$") + + +class TraceRunner(object): + """Trace runner contains the states for the trace and the opcode dispatch. + """ + def __init__(self, debug_filename): + self.debug_filename = debug_filename + self.pending = deque() + self.finished = set() + + def get_debug_loc(self, lineno): + return Loc(self.debug_filename, lineno) + + def dispatch(self, state): + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + if state._blockstack: + state: State + while state._blockstack: + topblk = state._blockstack[-1] + blk_end = topblk['end'] + if blk_end is not None and blk_end <= state.pc_initial: + state._blockstack.pop() + else: + break + elif PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(PYVERSION) + inst = state.get_inst() + if inst.opname != "CACHE": + _logger.debug("dispatch pc=%s, inst=%s", state._pc, inst) + _logger.debug("stack %s", state._stack) + fn = getattr(self, "op_{}".format(inst.opname), None) + if fn is not None: + fn(state, inst) + else: + msg = "Use of unsupported opcode (%s) found" % inst.opname + raise UnsupportedBytecodeError(msg, + loc=self.get_debug_loc(inst.lineno)) + + def _adjust_except_stack(self, state): + """ + Adjust stack when entering an exception handler to match expectation + by the bytecode. + """ + tryblk = state.get_top_block('TRY') + state.pop_block_and_above(tryblk) + nstack = state.stack_depth + kwargs = {} + expected_depth = tryblk['stack_depth'] + if nstack > expected_depth: + # Pop extra item in the stack + kwargs['npop'] = nstack - expected_depth + # Set extra stack itemcount due to the exception values. + extra_stack = 1 + if tryblk['push_lasti']: + extra_stack += 1 + kwargs['npush'] = extra_stack + state.fork(pc=tryblk['end'], **kwargs) + + def op_NOP(self, state, inst): + state.append(inst) + + if PYVERSION in ((3,14), ): + # New in 3.14 + op_NOT_TAKEN = op_NOP + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_RESUME(self, state, inst): + state.append(inst) + + def op_CACHE(self, state, inst): + state.append(inst) + + def op_PRECALL(self, state, inst): + state.append(inst) + + def op_PUSH_NULL(self, state, inst): + state.push(state.make_null()) + state.append(inst) + + def op_RETURN_GENERATOR(self, state, inst): + # This impl doesn't follow what CPython does. CPython is hacking + # the frame stack in the interpreter. From usage, it always + # has a POP_TOP after it so we push a dummy value to the stack. + # + # Example bytecode: + # > 0 NOP(arg=None, lineno=80) + # 2 RETURN_GENERATOR(arg=None, lineno=80) + # 4 POP_TOP(arg=None, lineno=80) + # 6 RESUME(arg=0, lineno=80) + state.push(state.make_temp()) + state.append(inst) + + if PYVERSION in ((3, 13), (3, 14)): + def op_FORMAT_SIMPLE(self, state, inst): + value = state.pop() + strvar = state.make_temp() + res = state.make_temp() + state.append(inst, value=value, res=res, strvar=strvar) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_FORMAT_VALUE(self, state, inst): + """ + FORMAT_VALUE(flags): flags argument specifies format spec which is + not supported yet. Currently, we just call str() on the value. + Pops a value from stack and pushes results back. + Required for supporting f-strings. + https://docs.python.org/3/library/dis.html#opcode-FORMAT_VALUE + """ + if inst.arg != 0: + msg = "format spec in f-strings not supported yet" + raise UnsupportedBytecodeError(msg, + loc=self.get_debug_loc(inst.lineno)) + value = state.pop() + strvar = state.make_temp() + res = state.make_temp() + state.append(inst, value=value, res=res, strvar=strvar) + state.push(res) + + def op_BUILD_STRING(self, state, inst): + """ + BUILD_STRING(count): Concatenates count strings from the stack and + pushes the resulting string onto the stack. + Required for supporting f-strings. + https://docs.python.org/3/library/dis.html#opcode-BUILD_STRING + """ + count = inst.arg + strings = list(reversed([state.pop() for _ in range(count)])) + # corner case: f"" + if count == 0: + tmps = [state.make_temp()] + else: + tmps = [state.make_temp() for _ in range(count - 1)] + state.append(inst, strings=strings, tmps=tmps) + state.push(tmps[-1]) + + def op_POP_TOP(self, state, inst): + state.pop() + + if PYVERSION in ((3, 14), ): + # New in 3.14 + op_POP_ITER = op_POP_TOP + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 13), (3,14)): + def op_TO_BOOL(self, state, inst): + res = state.make_temp() + tos = state.pop() + state.append(inst, val=tos, res=res) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 13), (3, 14)): + def op_LOAD_GLOBAL(self, state, inst): + # Ordering of the global value and NULL is swapped in Py3.13 + res = state.make_temp() + idx = inst.arg >> 1 + state.append(inst, idx=idx, res=res) + state.push(res) + # ignoring the NULL + if inst.arg & 1: + state.push(state.make_null()) + elif PYVERSION in ((3, 11), (3, 12)): + def op_LOAD_GLOBAL(self, state, inst): + res = state.make_temp() + idx = inst.arg >> 1 + state.append(inst, idx=idx, res=res) + # ignoring the NULL + if inst.arg & 1: + state.push(state.make_null()) + state.push(res) + elif PYVERSION in ((3, 10),): + def op_LOAD_GLOBAL(self, state, inst): + res = state.make_temp() + state.append(inst, res=res) + state.push(res) + else: + raise NotImplementedError(PYVERSION) + + def op_COPY_FREE_VARS(self, state, inst): + state.append(inst) + + def op_MAKE_CELL(self, state, inst): + state.append(inst) + + def op_LOAD_DEREF(self, state, inst): + res = state.make_temp() + state.append(inst, res=res) + state.push(res) + + def op_LOAD_CONST(self, state, inst): + # append const index for interpreter to read the const value + res = state.make_temp("const") + f".{inst.arg}" + state.push(res) + state.append(inst, res=res) + + if PYVERSION in ((3, 14), ): + # New in 3.14 + def op_LOAD_SMALL_INT(self, state, inst): + assert 0 <= inst.arg < 256 + res = state.make_temp("const") + f".{inst.arg}" + state.push(res) + state.append(inst, res=res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_LOAD_ATTR(self, state, inst): + item = state.pop() + res = state.make_temp() + if PYVERSION in ((3, 13), (3, 14)): + state.push(res) # the attr + if inst.arg & 1: + state.push(state.make_null()) + elif PYVERSION in ((3, 12),): + if inst.arg & 1: + state.push(state.make_null()) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11)): + state.push(res) + else: + raise NotImplementedError(PYVERSION) + state.append(inst, item=item, res=res) + + def op_LOAD_FAST(self, state, inst): + if PYVERSION in ((3, 13), (3, 14)): + try: + name = state.get_varname(inst) + except IndexError: # oparg is out of range + # Handle this like a LOAD_DEREF + # Assume MAKE_CELL and COPY_FREE_VARS has correctly setup the + # states. + # According to https://github.com/python/cpython/blob/9ac606080a0074cdf7589d9b7c9413a73e0ddf37/Objects/codeobject.c#L730C9-L759 # noqa E501 + # localsplus is locals + cells + freevars + bc = state._bytecode + num_varnames = len(bc.co_varnames) + num_freevars = len(bc.co_freevars) + num_cellvars = len(bc.co_cellvars) + max_fast_local = num_cellvars + num_freevars + assert 0 <= inst.arg - num_varnames < max_fast_local + res = state.make_temp() + state.append(inst, res=res, as_load_deref=True) + state.push(res) + return + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + name = state.get_varname(inst) + else: + raise NotImplementedError(PYVERSION) + res = state.make_temp(name) + state.append(inst, res=res) + state.push(res) + + if PYVERSION in ((3, 13), (3, 14)): + def op_LOAD_FAST_LOAD_FAST(self, state, inst): + oparg = inst.arg + oparg1 = oparg >> 4 + oparg2 = oparg & 15 + name1 = state.get_varname_by_arg(oparg1) + name2 = state.get_varname_by_arg(oparg2) + res1 = state.make_temp(name1) + res2 = state.make_temp(name2) + state.append(inst, res1=res1, res2=res2) + state.push(res1) + state.push(res2) + + def op_STORE_FAST_LOAD_FAST(self, state, inst): + oparg = inst.arg + # oparg1 = oparg >> 4 # not needed + oparg2 = oparg & 15 + store_value = state.pop() + load_name = state.get_varname_by_arg(oparg2) + load_res = state.make_temp(load_name) + state.append(inst, store_value=store_value, load_res=load_res) + state.push(load_res) + + def op_STORE_FAST_STORE_FAST(self, state, inst): + value1 = state.pop() + value2 = state.pop() + state.append(inst, value1=value1, value2=value2) + + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + op_LOAD_FAST_CHECK = op_LOAD_FAST + op_LOAD_FAST_AND_CLEAR = op_LOAD_FAST + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14),): + # New in 3.14. + op_LOAD_FAST_BORROW = op_LOAD_FAST + op_LOAD_FAST_BORROW_LOAD_FAST_BORROW = op_LOAD_FAST_LOAD_FAST + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_DELETE_FAST(self, state, inst): + state.append(inst) + + def op_DELETE_ATTR(self, state, inst): + target = state.pop() + state.append(inst, target=target) + + def op_STORE_ATTR(self, state, inst): + target = state.pop() + value = state.pop() + state.append(inst, target=target, value=value) + + def op_STORE_DEREF(self, state, inst): + value = state.pop() + state.append(inst, value=value) + + def op_STORE_FAST(self, state, inst): + value = state.pop() + state.append(inst, value=value) + + def op_SLICE_1(self, state, inst): + """ + TOS = TOS1[TOS:] + """ + tos = state.pop() + tos1 = state.pop() + res = state.make_temp() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + start=tos, + res=res, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + state.push(res) + + def op_SLICE_2(self, state, inst): + """ + TOS = TOS1[:TOS] + """ + tos = state.pop() + tos1 = state.pop() + res = state.make_temp() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + stop=tos, + res=res, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + state.push(res) + + def op_SLICE_3(self, state, inst): + """ + TOS = TOS2[TOS1:TOS] + """ + tos = state.pop() + tos1 = state.pop() + tos2 = state.pop() + res = state.make_temp() + slicevar = state.make_temp() + indexvar = state.make_temp() + state.append( + inst, + base=tos2, + start=tos1, + stop=tos, + res=res, + slicevar=slicevar, + indexvar=indexvar, + ) + state.push(res) + + def op_STORE_SLICE_0(self, state, inst): + """ + TOS[:] = TOS1 + """ + tos = state.pop() + value = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos, + value=value, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + + def op_STORE_SLICE_1(self, state, inst): + """ + TOS1[TOS:] = TOS2 + """ + tos = state.pop() + tos1 = state.pop() + value = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + start=tos, + slicevar=slicevar, + value=value, + indexvar=indexvar, + nonevar=nonevar, + ) + + def op_STORE_SLICE_2(self, state, inst): + """ + TOS1[:TOS] = TOS2 + """ + tos = state.pop() + tos1 = state.pop() + value = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + stop=tos, + value=value, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + + def op_STORE_SLICE_3(self, state, inst): + """ + TOS2[TOS1:TOS] = TOS3 + """ + tos = state.pop() + tos1 = state.pop() + tos2 = state.pop() + value = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + state.append( + inst, + base=tos2, + start=tos1, + stop=tos, + value=value, + slicevar=slicevar, + indexvar=indexvar, + ) + + def op_DELETE_SLICE_0(self, state, inst): + """ + del TOS[:] + """ + tos = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, base=tos, slicevar=slicevar, indexvar=indexvar, + nonevar=nonevar, + ) + + def op_DELETE_SLICE_1(self, state, inst): + """ + del TOS1[TOS:] + """ + tos = state.pop() + tos1 = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + start=tos, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + + def op_DELETE_SLICE_2(self, state, inst): + """ + del TOS1[:TOS] + """ + tos = state.pop() + tos1 = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + nonevar = state.make_temp() + state.append( + inst, + base=tos1, + stop=tos, + slicevar=slicevar, + indexvar=indexvar, + nonevar=nonevar, + ) + + def op_DELETE_SLICE_3(self, state, inst): + """ + del TOS2[TOS1:TOS] + """ + tos = state.pop() + tos1 = state.pop() + tos2 = state.pop() + slicevar = state.make_temp() + indexvar = state.make_temp() + state.append( + inst, base=tos2, start=tos1, stop=tos, slicevar=slicevar, + indexvar=indexvar + ) + + def op_BUILD_SLICE(self, state, inst): + """ + slice(TOS1, TOS) or slice(TOS2, TOS1, TOS) + """ + argc = inst.arg + if argc == 2: + tos = state.pop() + tos1 = state.pop() + start = tos1 + stop = tos + step = None + elif argc == 3: + tos = state.pop() + tos1 = state.pop() + tos2 = state.pop() + start = tos2 + stop = tos1 + step = tos + else: + raise Exception("unreachable") + slicevar = state.make_temp() + res = state.make_temp() + state.append( + inst, start=start, stop=stop, step=step, res=res, slicevar=slicevar + ) + state.push(res) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_BINARY_SLICE(self, state, inst): + end = state.pop() + start = state.pop() + container = state.pop() + temp_res = state.make_temp() + res = state.make_temp() + slicevar = state.make_temp() + state.append( + inst, start=start, end=end, container=container, res=res, + slicevar=slicevar, temp_res=temp_res + ) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_STORE_SLICE(self, state, inst): + end = state.pop() + start = state.pop() + container = state.pop() + value = state.pop() + + slicevar = state.make_temp() + res = state.make_temp() + state.append( + inst, start=start, end=end, container=container, value=value, + res=res, slicevar=slicevar, + ) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def _op_POP_JUMP_IF(self, state, inst): + pred = state.pop() + state.append(inst, pred=pred) + + target_inst = inst.get_jump_target() + next_inst = inst.next + # if the next inst and the jump target are the same location, issue one + # fork else issue a fork for the next and the target. + state.fork(pc=next_inst) + if target_inst != next_inst: + state.fork(pc=target_inst) + + op_POP_JUMP_IF_TRUE = _op_POP_JUMP_IF + op_POP_JUMP_IF_FALSE = _op_POP_JUMP_IF + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + op_POP_JUMP_IF_NONE = _op_POP_JUMP_IF + op_POP_JUMP_IF_NOT_NONE = _op_POP_JUMP_IF + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def _op_JUMP_IF_OR_POP(self, state, inst): + pred = state.get_tos() + state.append(inst, pred=pred) + state.fork(pc=inst.next, npop=1) + state.fork(pc=inst.get_jump_target()) + + op_JUMP_IF_FALSE_OR_POP = _op_JUMP_IF_OR_POP + op_JUMP_IF_TRUE_OR_POP = _op_JUMP_IF_OR_POP + + def op_POP_JUMP_FORWARD_IF_NONE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_FORWARD_IF_NOT_NONE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_BACKWARD_IF_NONE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_BACKWARD_IF_NOT_NONE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_FORWARD_IF_FALSE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_FORWARD_IF_TRUE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_BACKWARD_IF_FALSE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_POP_JUMP_BACKWARD_IF_TRUE(self, state, inst): + self._op_POP_JUMP_IF(state, inst) + + def op_JUMP_FORWARD(self, state, inst): + state.append(inst) + state.fork(pc=inst.get_jump_target()) + + def op_JUMP_BACKWARD(self, state, inst): + state.append(inst) + state.fork(pc=inst.get_jump_target()) + + op_JUMP_BACKWARD_NO_INTERRUPT = op_JUMP_BACKWARD + + def op_JUMP_ABSOLUTE(self, state, inst): + state.append(inst) + state.fork(pc=inst.get_jump_target()) + + def op_BREAK_LOOP(self, state, inst): + # NOTE: bytecode removed since py3.8 + end = state.get_top_block('LOOP')['end'] + state.append(inst, end=end) + state.pop_block() + state.fork(pc=end) + + def op_RETURN_VALUE(self, state, inst): + state.append(inst, retval=state.pop(), castval=state.make_temp()) + state.terminate() + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_RETURN_CONST(self, state, inst): + res = state.make_temp("const") + state.append(inst, retval=res, castval=state.make_temp()) + state.terminate() + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_YIELD_VALUE(self, state, inst): + val = state.pop() + res = state.make_temp() + state.append(inst, value=val, res=res) + state.push(res) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_RAISE_VARARGS(self, state, inst): + if inst.arg == 0: + exc = None + # No re-raising within a try-except block. + # But we allow bare reraise. + if state.has_active_try(): + raise UnsupportedBytecodeError( + "The re-raising of an exception is not yet supported.", + loc=self.get_debug_loc(inst.lineno), + ) + elif inst.arg == 1: + exc = state.pop() + else: + raise ValueError("Multiple argument raise is not supported.") + state.append(inst, exc=exc) + + if state.has_active_try(): + self._adjust_except_stack(state) + else: + state.terminate() + + elif PYVERSION in ((3, 10),): + def op_RAISE_VARARGS(self, state, inst): + in_exc_block = any([ + state.get_top_block("EXCEPT") is not None, + state.get_top_block("FINALLY") is not None + ]) + if inst.arg == 0: + exc = None + if in_exc_block: + raise UnsupportedBytecodeError( + "The re-raising of an exception is not yet supported.", + loc=self.get_debug_loc(inst.lineno), + ) + elif inst.arg == 1: + exc = state.pop() + else: + raise ValueError("Multiple argument raise is not supported.") + state.append(inst, exc=exc) + state.terminate() + else: + raise NotImplementedError(PYVERSION) + + def op_BEGIN_FINALLY(self, state, inst): + temps = [] + for i in range(_EXCEPT_STACK_OFFSET): + tmp = state.make_temp() + temps.append(tmp) + state.push(tmp) + state.append(inst, temps=temps) + + def op_END_FINALLY(self, state, inst): + blk = state.pop_block() + state.reset_stack(blk['entry_stack']) + + if PYVERSION in ((3, 13), (3, 14)): + def op_END_FOR(self, state, inst): + state.pop() + elif PYVERSION in ((3, 12),): + def op_END_FOR(self, state, inst): + state.pop() + state.pop() + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_POP_FINALLY(self, state, inst): + # we don't emulate the exact stack behavior + if inst.arg != 0: + msg = ('Unsupported use of a bytecode related to try..finally' + ' or a with-context') + raise UnsupportedBytecodeError(msg, + loc=self.get_debug_loc(inst.lineno)) + + def op_CALL_FINALLY(self, state, inst): + pass + + def op_WITH_EXCEPT_START(self, state, inst): + state.terminate() # do not support + + def op_WITH_CLEANUP_START(self, state, inst): + # we don't emulate the exact stack behavior + state.append(inst) + + def op_WITH_CLEANUP_FINISH(self, state, inst): + # we don't emulate the exact stack behavior + state.append(inst) + + def op_SETUP_LOOP(self, state, inst): + # NOTE: bytecode removed since py3.8 + state.push_block( + state.make_block( + kind='LOOP', + end=inst.get_jump_target(), + ) + ) + if PYVERSION in ((3, 14), ): + # Replaced by LOAD_SPECIAL in 3.14. + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_BEFORE_WITH(self, state, inst): + # Almost the same as py3.10 SETUP_WITH just lacking the finally + # block. + cm = state.pop() # the context-manager + + yielded = state.make_temp() + exitfn = state.make_temp(prefix='setup_with_exitfn') + + state.push(exitfn) + state.push(yielded) + + # Gather all exception entries for this WITH. There maybe multiple + # entries; esp. for nested WITHs. + bc = state._bytecode + ehhead = bc.find_exception_entry(inst.next) + ehrelated = [ehhead] + for eh in bc.exception_entries: + if eh.target == ehhead.target: + ehrelated.append(eh) + end = max(eh.end for eh in ehrelated) + state.append(inst, contextmanager=cm, exitfn=exitfn, end=end) + + state.push_block( + state.make_block( + kind='WITH', + end=end, + ) + ) + # Forces a new block + state.fork(pc=inst.next) + else: + raise NotImplementedError(PYVERSION) + + def op_SETUP_WITH(self, state, inst): + cm = state.pop() # the context-manager + + yielded = state.make_temp() + exitfn = state.make_temp(prefix='setup_with_exitfn') + state.append(inst, contextmanager=cm, exitfn=exitfn) + + state.push(exitfn) + state.push(yielded) + + state.push_block( + state.make_block( + kind='WITH', + end=inst.get_jump_target(), + ) + ) + # Forces a new block + state.fork(pc=inst.next) + + def _setup_try(self, kind, state, next, end): + # Forces a new block + # Fork to the body of the finally + handler_block = state.make_block( + kind=kind, + end=None, + reset_stack=False, + ) + # Forces a new block + # Fork to the body of the finally + state.fork( + pc=next, + extra_block=state.make_block( + kind='TRY', + end=end, + reset_stack=False, + handler=handler_block, + ) + ) + + def op_PUSH_EXC_INFO(self, state, inst): + tos = state.pop() + state.push(state.make_temp("exception")) + state.push(tos) + + def op_SETUP_FINALLY(self, state, inst): + state.append(inst) + self._setup_try( + 'FINALLY', state, next=inst.next, end=inst.get_jump_target(), + ) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_POP_EXCEPT(self, state, inst): + state.pop() + + elif PYVERSION in ((3, 10),): + def op_POP_EXCEPT(self, state, inst): + blk = state.pop_block() + if blk['kind'] not in {BlockKind('EXCEPT'), BlockKind('FINALLY')}: + raise UnsupportedBytecodeError( + f"POP_EXCEPT got an unexpected block: {blk['kind']}", + loc=self.get_debug_loc(inst.lineno), + ) + state.pop() + state.pop() + state.pop() + # Forces a new block + state.fork(pc=inst.next) + else: + raise NotImplementedError(PYVERSION) + + def op_POP_BLOCK(self, state, inst): + blk = state.pop_block() + if blk['kind'] == BlockKind('TRY'): + state.append(inst, kind='try') + elif blk['kind'] == BlockKind('WITH'): + state.append(inst, kind='with') + state.fork(pc=inst.next) + + if PYVERSION in ((3, 14),): + # Removed in 3.14 -- replaced with BINARY_OP and [] + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_BINARY_SUBSCR(self, state, inst): + index = state.pop() + target = state.pop() + res = state.make_temp() + state.append(inst, index=index, target=target, res=res) + state.push(res) + else: + raise NotImplementedError(PYVERSION) + + def op_STORE_SUBSCR(self, state, inst): + index = state.pop() + target = state.pop() + value = state.pop() + state.append(inst, target=target, index=index, value=value) + + def op_DELETE_SUBSCR(self, state, inst): + index = state.pop() + target = state.pop() + state.append(inst, target=target, index=index) + + def op_CALL(self, state, inst): + narg = inst.arg + args = list(reversed([state.pop() for _ in range(narg)])) + if PYVERSION in ((3, 13), (3, 14)): + null_or_self = state.pop() + # position of the callable is fixed + callable = state.pop() + if not _is_null_temp_reg(null_or_self): + args = [null_or_self, *args] + kw_names = None + elif PYVERSION < (3, 13): + callable_or_firstarg = state.pop() + null_or_callable = state.pop() + if _is_null_temp_reg(null_or_callable): + callable = callable_or_firstarg + else: + callable = null_or_callable + args = [callable_or_firstarg, *args] + kw_names = state.pop_kw_names() + res = state.make_temp() + + state.append(inst, func=callable, args=args, kw_names=kw_names, res=res) + state.push(res) + + def op_KW_NAMES(self, state, inst): + state.set_kw_names(inst.arg) + + def op_CALL_FUNCTION(self, state, inst): + narg = inst.arg + args = list(reversed([state.pop() for _ in range(narg)])) + func = state.pop() + + res = state.make_temp() + state.append(inst, func=func, args=args, res=res) + state.push(res) + + def op_CALL_FUNCTION_KW(self, state, inst): + narg = inst.arg + names = state.pop() # tuple of names + args = list(reversed([state.pop() for _ in range(narg)])) + func = state.pop() + + res = state.make_temp() + state.append(inst, func=func, args=args, names=names, res=res) + state.push(res) + + if PYVERSION in ((3, 13), (3, 14)): + def op_CALL_KW(self, state, inst): + narg = inst.arg + kw_names = state.pop() + args = list(reversed([state.pop() for _ in range(narg)])) + null_or_firstarg = state.pop() + callable = state.pop() + if not _is_null_temp_reg(null_or_firstarg): + args = [null_or_firstarg, *args] + + res = state.make_temp() + state.append(inst, func=callable, args=args, kw_names=kw_names, + res=res) + state.push(res) + + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14), ): + def op_CALL_FUNCTION_EX(self, state, inst): + # (func, unused, callargs, kwargs -- result)) + # In 3.14 CALL_FUNCTION_EX always take a kwargs argument + # https://github.com/python/cpython/pull/129226 + varkwarg = state.pop() + if _is_null_temp_reg(varkwarg): + varkwarg = None + vararg = state.pop() + state.pop() # unused + func = state.pop() + + res = state.make_temp() + state.append(inst, func=func, vararg=vararg, varkwarg=varkwarg, + res=res) + state.push(res) + elif PYVERSION in ((3, 13), ): + def op_CALL_FUNCTION_EX(self, state, inst): + # (func, unused, callargs, kwargs if (oparg & 1) -- result)) + if inst.arg & 1: + varkwarg = state.pop() + else: + varkwarg = None + + vararg = state.pop() + state.pop() # unused + func = state.pop() + + res = state.make_temp() + state.append(inst, func=func, vararg=vararg, varkwarg=varkwarg, + res=res) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + def op_CALL_FUNCTION_EX(self, state, inst): + if inst.arg & 1: + varkwarg = state.pop() + else: + varkwarg = None + vararg = state.pop() + func = state.pop() + + if PYVERSION in ((3, 11), (3, 12)): + if _is_null_temp_reg(state.peek(1)): + state.pop() # pop NULL, it's not used + elif PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(PYVERSION) + + res = state.make_temp() + state.append(inst, func=func, vararg=vararg, varkwarg=varkwarg, + res=res) + state.push(res) + else: + raise NotImplementedError(PYVERSION) + + def _dup_topx(self, state, inst, count): + orig = [state.pop() for _ in range(count)] + orig.reverse() + # We need to actually create new temporaries if we want the + # IR optimization pass to work correctly (see issue #580) + duped = [state.make_temp() for _ in range(count)] + state.append(inst, orig=orig, duped=duped) + for val in orig: + state.push(val) + for val in duped: + state.push(val) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_CALL_INTRINSIC_1(self, state, inst): + # See https://github.com/python/cpython/blob/v3.12.0rc2/Include/ + # internal/pycore_intrinsics.h#L3-L17C36 + try: + operand = CALL_INTRINSIC_1_Operand(inst.arg) + except TypeError: + msg = f"op_CALL_INTRINSIC_1({inst.arg})" + loc = self.get_debug_loc(inst.lineno) + raise UnsupportedBytecodeError(msg, loc=loc) + if operand == ci1op.INTRINSIC_STOPITERATION_ERROR: + state.append(inst, operand=operand) + state.terminate() + return + elif operand == ci1op.UNARY_POSITIVE: + val = state.pop() + res = state.make_temp() + state.append(inst, operand=operand, + value=val, res=res) + state.push(res) + return + elif operand == ci1op.INTRINSIC_LIST_TO_TUPLE: + tos = state.pop() + res = state.make_temp() + state.append(inst, operand=operand, + const_list=tos, res=res) + state.push(res) + return + else: + raise NotImplementedError(operand) + + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_DUP_TOPX(self, state, inst): + count = inst.arg + assert 1 <= count <= 5, "Invalid DUP_TOPX count" + self._dup_topx(state, inst, count) + + def op_DUP_TOP(self, state, inst): + self._dup_topx(state, inst, count=1) + + def op_DUP_TOP_TWO(self, state, inst): + self._dup_topx(state, inst, count=2) + + def op_COPY(self, state, inst): + state.push(state.peek(inst.arg)) + + def op_SWAP(self, state, inst): + state.swap(inst.arg) + + def op_ROT_TWO(self, state, inst): + first = state.pop() + second = state.pop() + state.push(first) + state.push(second) + + def op_ROT_THREE(self, state, inst): + first = state.pop() + second = state.pop() + third = state.pop() + state.push(first) + state.push(third) + state.push(second) + + def op_ROT_FOUR(self, state, inst): + first = state.pop() + second = state.pop() + third = state.pop() + forth = state.pop() + state.push(first) + state.push(forth) + state.push(third) + state.push(second) + + def op_UNPACK_SEQUENCE(self, state, inst): + count = inst.arg + iterable = state.pop() + stores = [state.make_temp() for _ in range(count)] + tupleobj = state.make_temp() + state.append(inst, iterable=iterable, stores=stores, tupleobj=tupleobj) + for st in reversed(stores): + state.push(st) + + def op_BUILD_TUPLE(self, state, inst): + count = inst.arg + items = list(reversed([state.pop() for _ in range(count)])) + tup = state.make_temp() + state.append(inst, items=items, res=tup) + state.push(tup) + + def _build_tuple_unpack(self, state, inst): + # Builds tuple from other tuples on the stack + tuples = list(reversed([state.pop() for _ in range(inst.arg)])) + temps = [state.make_temp() for _ in range(len(tuples) - 1)] + + # if the unpack is assign-like, e.g. x = (*y,), it needs handling + # differently. + is_assign = len(tuples) == 1 + if is_assign: + temps = [state.make_temp(),] + + state.append(inst, tuples=tuples, temps=temps, is_assign=is_assign) + # The result is in the last temp var + state.push(temps[-1]) + + def op_BUILD_TUPLE_UNPACK_WITH_CALL(self, state, inst): + # just unpack the input tuple, call inst will be handled afterwards + self._build_tuple_unpack(state, inst) + + def op_BUILD_TUPLE_UNPACK(self, state, inst): + self._build_tuple_unpack(state, inst) + + def op_LIST_TO_TUPLE(self, state, inst): + # "Pops a list from the stack and pushes a tuple containing the same + # values." + tos = state.pop() + res = state.make_temp() # new tuple var + state.append(inst, const_list=tos, res=res) + state.push(res) + + def op_BUILD_CONST_KEY_MAP(self, state, inst): + keys = state.pop() + vals = list(reversed([state.pop() for _ in range(inst.arg)])) + keytmps = [state.make_temp() for _ in range(inst.arg)] + res = state.make_temp() + state.append(inst, keys=keys, keytmps=keytmps, values=vals, res=res) + state.push(res) + + def op_BUILD_LIST(self, state, inst): + count = inst.arg + items = list(reversed([state.pop() for _ in range(count)])) + lst = state.make_temp() + state.append(inst, items=items, res=lst) + state.push(lst) + + def op_LIST_APPEND(self, state, inst): + value = state.pop() + index = inst.arg + target = state.peek(index) + appendvar = state.make_temp() + res = state.make_temp() + state.append(inst, target=target, value=value, appendvar=appendvar, + res=res) + + def op_LIST_EXTEND(self, state, inst): + value = state.pop() + index = inst.arg + target = state.peek(index) + extendvar = state.make_temp() + res = state.make_temp() + state.append(inst, target=target, value=value, extendvar=extendvar, + res=res) + + def op_BUILD_MAP(self, state, inst): + dct = state.make_temp() + count = inst.arg + items = [] + # In 3.5+, BUILD_MAP takes pairs from the stack + for i in range(count): + v, k = state.pop(), state.pop() + items.append((k, v)) + state.append(inst, items=items[::-1], size=count, res=dct) + state.push(dct) + + def op_MAP_ADD(self, state, inst): + TOS = state.pop() + TOS1 = state.pop() + key, value = (TOS1, TOS) + index = inst.arg + target = state.peek(index) + setitemvar = state.make_temp() + res = state.make_temp() + state.append(inst, target=target, key=key, value=value, + setitemvar=setitemvar, res=res) + + def op_BUILD_SET(self, state, inst): + count = inst.arg + # Note: related python bug http://bugs.python.org/issue26020 + items = list(reversed([state.pop() for _ in range(count)])) + res = state.make_temp() + state.append(inst, items=items, res=res) + state.push(res) + + def op_SET_ADD(self, state, inst): + value = state.pop() + target = state.get_tos() + addvar = state.make_temp() + res = state.make_temp() + state.append(inst, value=value, target=target, addvar=addvar, res=res) + + def op_SET_UPDATE(self, state, inst): + value = state.pop() + index = inst.arg + target = state.peek(index) + updatevar = state.make_temp() + res = state.make_temp() + state.append(inst, target=target, value=value, updatevar=updatevar, + res=res) + + def op_DICT_UPDATE(self, state, inst): + value = state.pop() + index = inst.arg + target = state.peek(index) + updatevar = state.make_temp() + res = state.make_temp() + state.append(inst, target=target, value=value, updatevar=updatevar, + res=res) + + def op_GET_ITER(self, state, inst): + value = state.pop() + res = state.make_temp() + state.append(inst, value=value, res=res) + state.push(res) + + def op_FOR_ITER(self, state, inst): + iterator = state.get_tos() + pair = state.make_temp() + indval = state.make_temp() + pred = state.make_temp() + state.append(inst, iterator=iterator, pair=pair, indval=indval, + pred=pred) + state.push(indval) + end = inst.get_jump_target() + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + # Changed in version 3.12: Up until 3.11 the iterator was + # popped when it was exhausted. Now this is handled using END_FOR + # op code. + state.fork(pc=end) + elif PYVERSION in ((3, 10), (3, 11)): + state.fork(pc=end, npop=2) + else: + raise NotImplementedError(PYVERSION) + state.fork(pc=inst.next) + + def op_GEN_START(self, state, inst): + """Pops TOS. If TOS was not None, raises an exception. The kind + operand corresponds to the type of generator or coroutine and + determines the error message. The legal kinds are 0 for generator, + 1 for coroutine, and 2 for async generator. + + New in version 3.10. + """ + # no-op in Numba + pass + + def op_BINARY_OP(self, state, inst): + op = dis._nb_ops[inst.arg][1] + rhs = state.pop() + lhs = state.pop() + if op == '[]': + # Special case 3.14 -- body of BINARY_SUBSCR now here + assert PYVERSION == (3, 14) + res = state.make_temp() + state.append(inst, op=op, lhs=lhs, rhs=rhs, res=res) + state.push(res) + else: + op_name = ALL_BINOPS_TO_OPERATORS[op].__name__ + res = state.make_temp(prefix=f"binop_{op_name}") + state.append(inst, op=op, lhs=lhs, rhs=rhs, res=res) + state.push(res) + + def _unaryop(self, state, inst): + val = state.pop() + res = state.make_temp() + state.append(inst, value=val, res=res) + state.push(res) + + op_UNARY_NEGATIVE = _unaryop + op_UNARY_POSITIVE = _unaryop + op_UNARY_NOT = _unaryop + op_UNARY_INVERT = _unaryop + + def _binaryop(self, state, inst): + rhs = state.pop() + lhs = state.pop() + res = state.make_temp() + state.append(inst, lhs=lhs, rhs=rhs, res=res) + state.push(res) + + op_COMPARE_OP = _binaryop + op_IS_OP = _binaryop + op_CONTAINS_OP = _binaryop + + op_INPLACE_ADD = _binaryop + op_INPLACE_SUBTRACT = _binaryop + op_INPLACE_MULTIPLY = _binaryop + op_INPLACE_DIVIDE = _binaryop + op_INPLACE_TRUE_DIVIDE = _binaryop + op_INPLACE_FLOOR_DIVIDE = _binaryop + op_INPLACE_MODULO = _binaryop + op_INPLACE_POWER = _binaryop + op_INPLACE_MATRIX_MULTIPLY = _binaryop + + op_INPLACE_LSHIFT = _binaryop + op_INPLACE_RSHIFT = _binaryop + op_INPLACE_AND = _binaryop + op_INPLACE_OR = _binaryop + op_INPLACE_XOR = _binaryop + + op_BINARY_ADD = _binaryop + op_BINARY_SUBTRACT = _binaryop + op_BINARY_MULTIPLY = _binaryop + op_BINARY_DIVIDE = _binaryop + op_BINARY_TRUE_DIVIDE = _binaryop + op_BINARY_FLOOR_DIVIDE = _binaryop + op_BINARY_MODULO = _binaryop + op_BINARY_POWER = _binaryop + op_BINARY_MATRIX_MULTIPLY = _binaryop + + op_BINARY_LSHIFT = _binaryop + op_BINARY_RSHIFT = _binaryop + op_BINARY_AND = _binaryop + op_BINARY_OR = _binaryop + op_BINARY_XOR = _binaryop + + def op_MAKE_FUNCTION(self, state, inst, MAKE_CLOSURE=False): + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + # https://github.com/python/cpython/commit/2f180ce + # name set via co_qualname + name = None + elif PYVERSION in ((3, 10),): + name = state.pop() + else: + raise NotImplementedError(PYVERSION) + code = state.pop() + closure = annotations = annotate = kwdefaults = defaults = None + if PYVERSION in ((3, 13), (3, 14)): + assert inst.arg is None + # SET_FUNCTION_ATTRIBUTE is responsible for setting + # closure, annotations, annotate, kwdefaults and defaults. + else: + if inst.arg & 0x8: + closure = state.pop() + if inst.arg & 0x4: + annotations = state.pop() + if inst.arg & 0x2: + kwdefaults = state.pop() + if inst.arg & 0x1: + defaults = state.pop() + res = state.make_temp() + state.append( + inst, + name=name, + code=code, + closure=closure, + annotations=annotations, + annotate=annotate, + kwdefaults=kwdefaults, + defaults=defaults, + res=res, + ) + state.push(res) + + def op_SET_FUNCTION_ATTRIBUTE(self, state, inst): + assert PYVERSION in ((3, 13), (3, 14)) + make_func_stack = state.pop() + data = state.pop() + if inst.arg & 0x01: + # 0x01 a tuple of default values for positional-only and + # positional-or-keyword parameters in positional order + state.set_function_attribute(make_func_stack, defaults=data) + elif inst.arg & 0x02: + # 0x02 a tuple of strings containing parameters’ annotations + state.set_function_attribute(make_func_stack, kwdefaults=data) + elif inst.arg & 0x04: + # 0x04 a tuple of strings containing parameters’ annotations + state.set_function_attribute(make_func_stack, annotations=data) + elif inst.arg & 0x08: + # 0x08 a tuple containing cells for free variables, making a closure + state.set_function_attribute(make_func_stack, closure=data) + elif inst.arg & 0x10: + # In 3.14 a new flag was added it has the value 0x10/16 + # Numba report: https://github.com/numba/numba/issues/10319 + state.set_function_attribute(make_func_stack, annotate=data) + else: + raise AssertionError("unreachable") + state.push(make_func_stack) + + def op_MAKE_CLOSURE(self, state, inst): + self.op_MAKE_FUNCTION(state, inst, MAKE_CLOSURE=True) + + def op_LOAD_CLOSURE(self, state, inst): + res = state.make_temp() + state.append(inst, res=res) + state.push(res) + + if PYVERSION in ((3, 14), ): + # Removed in 3.14 + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_LOAD_ASSERTION_ERROR(self, state, inst): + res = state.make_temp("assertion_error") + state.append(inst, res=res) + state.push(res) + else: + raise NotImplementedError(PYVERSION) + + def op_CHECK_EXC_MATCH(self, state, inst): + pred = state.make_temp("predicate") + tos = state.pop() + tos1 = state.get_tos() + state.append(inst, pred=pred, tos=tos, tos1=tos1) + state.push(pred) + + def op_JUMP_IF_NOT_EXC_MATCH(self, state, inst): + # Tests whether the second value on the stack is an exception matching + # TOS, and jumps if it is not. Pops two values from the stack. + pred = state.make_temp("predicate") + tos = state.pop() + tos1 = state.pop() + state.append(inst, pred=pred, tos=tos, tos1=tos1) + state.fork(pc=inst.next) + state.fork(pc=inst.get_jump_target()) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3,14)): + def op_RERAISE(self, state, inst): + # This isn't handled, but the state is set up anyway + exc = state.pop() + if inst.arg != 0: + state.pop() # lasti + state.append(inst, exc=exc) + + if state.has_active_try(): + self._adjust_except_stack(state) + else: + state.terminate() + + elif PYVERSION in ((3, 10),): + def op_RERAISE(self, state, inst): + # This isn't handled, but the state is set up anyway + exc = state.pop() + state.append(inst, exc=exc) + state.terminate() + else: + raise NotImplementedError(PYVERSION) + + # NOTE: Please see notes in `interpreter.py` surrounding the implementation + # of LOAD_METHOD and CALL_METHOD. + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + # LOAD_METHOD has become a pseudo-instruction in 3.12 + pass + elif PYVERSION in ((3, 11), ): + def op_LOAD_METHOD(self, state, inst): + item = state.pop() + extra = state.make_null() + state.push(extra) + res = state.make_temp() + state.append(inst, item=item, res=res) + state.push(res) + elif PYVERSION in ((3, 10),): + def op_LOAD_METHOD(self, state, inst): + self.op_LOAD_ATTR(state, inst) + else: + raise NotImplementedError(PYVERSION) + + def op_CALL_METHOD(self, state, inst): + self.op_CALL_FUNCTION(state, inst) + + if PYVERSION in ((3, 14), ): + # New in 3.14, replaces BEFORE_WITH. + def op_LOAD_SPECIAL(self, state, inst): + + # The "special" methods mapping for LOAD_SPECIAL is: + # + # special_methods = { + # 0: '__enter__', + # 1: '__exit__', + # 2: '__aenter__', + # 3: '__aexit__', + # } + if (dis._special_method_names[inst.arg] + not in ['__enter__', '__exit__']): + raise NotImplementedError( + "async special methods not supported") + + # This implementation of LOAD_SPECIAL is somewhat unusual for a + # Numba bytecode handler. + # + # Essentially this comes from the insight, that with Python 3.14 + # the bytecode `BEFORE_WITH` is replaced by `LOAD_SPECIAL`. But + # this is not a simple replacement. In fact, the single + # `BEFORE_WITH` is replaced by the following sequence of bytecodes: + # + # COPY(arg=1, lineno=X) + # LOAD_SPECIAL(arg=1, lineno=X) -- loading __exit__ -- + # SWAP(arg=2, lineno=X) + # SWAP(arg=3, lineno=X) + # LOAD_SPECIAL(arg=0, lineno=X) -- loading __enter__ -- + # CALL(arg=0, lineno=X) -- calling __enter__ -- + # POP_TOP(arg=None, lineno=X) + # + # Basically, after seeing the first `LOAD_SPECIAL` we can consume + # all the bytecodes up until the `POP_TOP` and leave the stack + # with a single copy of current TOS + the temp var to denote the + # `__exit__` function. We can also reject syntax of the form: + # + # with context as c: + # pass + # + # Using the fact that the `CALL` to `__enter__` must be followed by + # as POP_TOP, otherwise it's using `with as`. + + # Pop top of stack once for first LOAD_SPECIAL + tos = state.pop() + # Pop top of stack second time for second LOAD_SPECIAL + _ = state.pop() + + # Fake an exit method, will not be called and removed from Numba IR + # before final processing is complete. Only need this such that the + # `CALL` op when closing the with-block can be simulated as a stack + # effect. + method = state.make_temp(prefix='setup_with_exitfn') + # Cache current instruction (the LOAD_SPECIAL). + old_inst = inst + + # Now we need to consume the instructions in the known sequence. + for i,a in (('SWAP', 2), + ('SWAP', 3), + ('LOAD_SPECIAL', 0), + ('CALL', 0), + ): + state.advance_pc() + inst = state.get_inst() + if (inst.opname != i or inst.arg != a): + raise UnsupportedBytecodeError( + "Unsupported bytecode pattern for 'LOAD_SPECIAL'.") + + # POP_TOP + state.advance_pc() + inst = state.get_inst() + # Special case, the `CALL` must be followed by a `POP_TOP`. + # Otherwise this is an unsupported construct. + # + # See: `_guard_with_as` for how this is handled for 3.13 and below. + if inst.opname != 'POP_TOP': + msg = ("The 'with (context manager) as " + "(variable):' construct is not " + "supported.") + raise UnsupportedBytecodeError(msg) + assert inst.arg is None + + # Finished consuming bytecode pattern. + + # Find the end of the with-block using the exception tables using + # the instruction offset of the `POP_TOP` instruction. + bc = state._bytecode + ehhead = bc.find_exception_entry(inst.offset) + ehrelated = [ehhead] + for eh in bc.exception_entries: + if eh.target == ehhead.target: + ehrelated.append(eh) + end = max(eh.end for eh in ehrelated) + + # Push the `__exit__` method (or null) to the stack, + # followed by the original tos (which is the instatiated context + # manager). This is such that the `CALL` after the with-block can + # be simulated. + state.push(method) + state.push(tos) + # Record the instruction. + state.append(old_inst, contextmanager=tos, exit_method=method, + block_end=end) + + # Insert WITH-block. + state.push_block( + state.make_block( + kind='WITH', + end=end, + ) + ) + # And fork to force a new block. + state.fork(pc=inst.next) + + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14), ): + def op_LOAD_COMMON_CONSTANT(self, state, inst): + oparg = inst.arg + if dis._common_constants[oparg] == AssertionError: + name = 'assertion_error' + else: + raise NotImplementedError + res = state.make_temp(name) + state.append(inst, res=res, idx=oparg) + state.push(res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + +@total_ordering +class _State(object): + """State of the trace + """ + def __init__(self, bytecode, pc, nstack, blockstack, nullvals=()): + """ + Parameters + ---------- + bytecode : numba.bytecode.ByteCode + function bytecode + pc : int + program counter + nstack : int + stackdepth at entry + blockstack : Sequence[Dict] + A sequence of dictionary denoting entries on the blockstack. + """ + self._bytecode = bytecode + self._pc_initial = pc + self._pc = pc + self._nstack_initial = nstack + self._stack = [] + self._blockstack_initial = tuple(blockstack) + self._blockstack = list(blockstack) + self._temp_registers = [] + self._insts = [] + self._outedges = [] + self._terminated = False + self._phis = {} + self._outgoing_phis = UniqueDict() + self._used_regs = set() + for i in range(nstack): + if i in nullvals: + phi = self.make_temp("null$") + else: + phi = self.make_temp("phi") + self._phis[phi] = i + self.push(phi) + + def __repr__(self): + return "State(pc_initial={} nstack_initial={})".format( + self._pc_initial, self._nstack_initial + ) + + def get_identity(self): + return (self._pc_initial, self._nstack_initial) + + def __hash__(self): + return hash(self.get_identity()) + + def __lt__(self, other): + return self.get_identity() < other.get_identity() + + def __eq__(self, other): + return self.get_identity() == other.get_identity() + + @property + def pc_initial(self): + """The starting bytecode offset of this State. + The PC given to the constructor. + """ + return self._pc_initial + + @property + def instructions(self): + """The list of instructions information as a 2-tuple of + ``(pc : int, register_map : Dict)`` + """ + return self._insts + + @property + def outgoing_edges(self): + """The list of outgoing edges. + + Returns + ------- + edges : List[State] + """ + return self._outedges + + @property + def outgoing_phis(self): + """The dictionary of outgoing phi nodes. + + The keys are the name of the PHI nodes. + The values are the outgoing states. + """ + return self._outgoing_phis + + @property + def blockstack_initial(self): + """A copy of the initial state of the blockstack + """ + return self._blockstack_initial + + @property + def stack_depth(self): + """The current size of the stack + + Returns + ------- + res : int + """ + return len(self._stack) + + def find_initial_try_block(self): + """Find the initial *try* block. + """ + for blk in reversed(self._blockstack_initial): + if blk['kind'] == BlockKind('TRY'): + return blk + + def has_terminated(self): + return self._terminated + + def get_inst(self): + return self._bytecode[self._pc] + + def advance_pc(self): + inst = self.get_inst() + self._pc = inst.next + + def make_temp(self, prefix=""): + if not prefix: + name = "${prefix}{offset}{opname}.{tempct}".format( + prefix=prefix, + offset=self._pc, + opname=self.get_inst().opname.lower(), + tempct=len(self._temp_registers), + ) + else: + name = "${prefix}{offset}.{tempct}".format( + prefix=prefix, + offset=self._pc, + tempct=len(self._temp_registers), + ) + + self._temp_registers.append(name) + return name + + def append(self, inst, **kwargs): + """Append new inst""" + self._insts.append((inst.offset, kwargs)) + self._used_regs |= set(_flatten_inst_regs(kwargs.values())) + + def get_tos(self): + return self.peek(1) + + def peek(self, k): + """Return the k'th element on the stack + """ + return self._stack[-k] + + def push(self, item): + """Push to stack""" + self._stack.append(item) + + def pop(self): + """Pop the stack""" + return self._stack.pop() + + def swap(self, idx): + """Swap stack[idx] with the tos""" + s = self._stack + s[-1], s[-idx] = s[-idx], s[-1] + + def push_block(self, synblk): + """Push a block to blockstack + """ + assert 'stack_depth' in synblk + self._blockstack.append(synblk) + + def reset_stack(self, depth): + """Reset the stack to the given stack depth. + Returning the popped items. + """ + self._stack, popped = self._stack[:depth], self._stack[depth:] + return popped + + def make_block(self, kind, end, reset_stack=True, handler=None): + """Make a new block + """ + d = { + 'kind': BlockKind(kind), + 'end': end, + 'entry_stack': len(self._stack), + } + if reset_stack: + d['stack_depth'] = len(self._stack) + else: + d['stack_depth'] = None + d['handler'] = handler + return d + + def pop_block(self): + """Pop a block and unwind the stack + """ + b = self._blockstack.pop() + self.reset_stack(b['stack_depth']) + return b + + def pop_block_and_above(self, blk): + """Find *blk* in the blockstack and remove it and all blocks above it + from the stack. + """ + idx = self._blockstack.index(blk) + assert 0 <= idx < len(self._blockstack) + self._blockstack = self._blockstack[:idx] + + def get_top_block(self, kind): + """Find the first block that matches *kind* + """ + kind = BlockKind(kind) + for bs in reversed(self._blockstack): + if bs['kind'] == kind: + return bs + + def get_top_block_either(self, *kinds): + """Find the first block that matches *kind* + """ + kinds = {BlockKind(kind) for kind in kinds} + for bs in reversed(self._blockstack): + if bs['kind'] in kinds: + return bs + + def has_active_try(self): + """Returns a boolean indicating if the top-block is a *try* block + """ + return self.get_top_block('TRY') is not None + + def get_varname(self, inst): + """Get referenced variable name from the instruction's oparg + """ + return self.get_varname_by_arg(inst.arg) + + def get_varname_by_arg(self, oparg: int): + """Get referenced variable name from the oparg + """ + return self._bytecode.co_varnames[oparg] + + def terminate(self): + """Mark block as terminated + """ + self._terminated = True + + def fork(self, pc, npop=0, npush=0, extra_block=None): + """Fork the state + """ + # Handle changes on the stack + stack = list(self._stack) + if npop: + assert 0 <= npop <= len(self._stack) + nstack = len(self._stack) - npop + stack = stack[:nstack] + if npush: + assert 0 <= npush + for i in range(npush): + stack.append(self.make_temp()) + # Handle changes on the blockstack + blockstack = list(self._blockstack) + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + # pop expired block in destination pc + while blockstack: + top = blockstack[-1] + end = top.get('end_offset') or top['end'] + if pc >= end: + blockstack.pop() + else: + break + elif PYVERSION in ((3, 10),): + pass # intentionally bypass + else: + raise NotImplementedError(PYVERSION) + + if extra_block: + blockstack.append(extra_block) + self._outedges.append(Edge( + pc=pc, stack=tuple(stack), npush=npush, + blockstack=tuple(blockstack), + )) + self.terminate() + + def split_new_block(self): + """Split the state + """ + self.fork(pc=self._pc) + + def get_outgoing_states(self): + """Get states for each outgoing edges + """ + # Should only call once + assert not self._outgoing_phis + ret = [] + for edge in self._outedges: + state = State(bytecode=self._bytecode, pc=edge.pc, + nstack=len(edge.stack), blockstack=edge.blockstack, + nullvals=[i for i, v in enumerate(edge.stack) + if _is_null_temp_reg(v)]) + ret.append(state) + # Map outgoing_phis + for phi, i in state._phis.items(): + self._outgoing_phis[phi] = edge.stack[i] + return ret + + def get_outgoing_edgepushed(self): + """ + Returns + ------- + Dict[int, int] + where keys are the PC + values are the edge-pushed stack values + """ + + return {edge.pc: tuple(edge.stack[-edge.npush:]) + for edge in self._outedges} + + +class StatePy311(_State): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._kw_names = None + + def pop_kw_names(self): + out = self._kw_names + self._kw_names = None + return out + + def set_kw_names(self, val): + assert self._kw_names is None + self._kw_names = val + + def is_in_exception(self): + bc = self._bytecode + return bc.find_exception_entry(self._pc) is not None + + def get_exception(self): + bc = self._bytecode + return bc.find_exception_entry(self._pc) + + def in_with(self): + for ent in self._blockstack_initial: + if ent["kind"] == BlockKind("WITH"): + return True + + def make_null(self): + return self.make_temp(prefix="null$") + + +class StatePy313(StatePy311): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._make_func_attrs = defaultdict(dict) + + def set_function_attribute(self, make_func_res, **kwargs): + self._make_func_attrs[make_func_res].update(kwargs) + + def get_function_attributes(self, make_func_res): + return self._make_func_attrs[make_func_res] + + +if PYVERSION in ((3, 13), (3, 14)): + State = StatePy313 +elif PYVERSION in ((3, 11), (3, 12)): + State = StatePy311 +elif PYVERSION < (3, 11): + State = _State +else: + raise NotImplementedError(PYVERSION) + + +Edge = namedtuple("Edge", ["pc", "stack", "blockstack", "npush"]) + + +class AdaptDFA(object): + """Adapt Flow to the old DFA class expected by Interpreter + """ + def __init__(self, flow): + self._flow = flow + + @property + def infos(self): + return self._flow.block_infos + + +AdaptBlockInfo = namedtuple( + "AdaptBlockInfo", + ["insts", "outgoing_phis", "blockstack", "active_try_block", + "outgoing_edgepushed"], +) + + +def adapt_state_infos(state): + def process_function_attributes(inst_pair): + offset, data = inst_pair + inst = state._bytecode[offset] + if inst.opname == "MAKE_FUNCTION": + data.update(state.get_function_attributes(data['res'])) + return offset, data + if PYVERSION in ((3, 13), (3, 14)): + insts = tuple(map(process_function_attributes, state.instructions)) + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + insts = tuple(state.instructions) + else: + raise NotImplementedError(PYVERSION) + return AdaptBlockInfo( + insts=insts, + outgoing_phis=state.outgoing_phis, + blockstack=state.blockstack_initial, + active_try_block=state.find_initial_try_block(), + outgoing_edgepushed=state.get_outgoing_edgepushed(), + ) + + +def _flatten_inst_regs(iterable): + """Flatten an iterable of registers used in an instruction + """ + for item in iterable: + if isinstance(item, str): + yield item + elif isinstance(item, (tuple, list)): + for x in _flatten_inst_regs(item): + yield x + + +class AdaptCFA(object): + """Adapt Flow to the old CFA class expected by Interpreter + """ + def __init__(self, flow): + self._flow = flow + self._blocks = {} + for offset, blockinfo in flow.block_infos.items(): + self._blocks[offset] = AdaptCFBlock(blockinfo, offset) + backbone = self._flow.cfgraph.backbone() + + graph = flow.cfgraph + # Find backbone + backbone = graph.backbone() + # Filter out in loop blocks (Assuming no other cyclic control blocks) + # This is to unavoid variables defined in loops being considered as + # function scope. + inloopblocks = set() + for b in self.blocks.keys(): + if graph.in_loops(b): + inloopblocks.add(b) + self._backbone = backbone - inloopblocks + + @property + def graph(self): + return self._flow.cfgraph + + @property + def backbone(self): + return self._backbone + + @property + def blocks(self): + return self._blocks + + def iterliveblocks(self): + for b in sorted(self.blocks): + yield self.blocks[b] + + def dump(self): + self._flow.cfgraph.dump() + + +class AdaptCFBlock(object): + def __init__(self, blockinfo, offset): + self.offset = offset + self.body = tuple(i for i, _ in blockinfo.insts) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/caching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/caching.py new file mode 100644 index 0000000000000000000000000000000000000000..98cf1bc77096ac4e3451421c4c9289cececd22b3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/caching.py @@ -0,0 +1,817 @@ +""" +Caching mechanism for compiled functions. +""" + + +from abc import ABCMeta, abstractmethod +import contextlib +import errno +import hashlib +import importlib +import inspect +import itertools +from math import floor +import os +import pickle +import sys +import tempfile +import uuid +import warnings + +from numba.misc.appdirs import AppDirs +import zipfile +from pathlib import Path + +import numba +from numba.core.errors import NumbaWarning +from numba.core.base import BaseContext +from numba.core.codegen import CodeLibrary +from numba.core.compiler import CompileResult +from numba.core import config, compiler +from numba.core.serialize import dumps + + +def _cache_log(msg, *args): + if config.DEBUG_CACHE: + msg = msg % args + print(msg) + + +class _Cache(metaclass=ABCMeta): + + @property + @abstractmethod + def cache_path(self): + """ + The base filesystem path of this cache (for example its root folder). + """ + + @abstractmethod + def load_overload(self, sig, target_context): + """ + Load an overload for the given signature using the target context. + The saved object must be returned if successful, None if not found + in the cache. + """ + + @abstractmethod + def save_overload(self, sig, data): + """ + Save the overload for the given signature. + """ + + @abstractmethod + def enable(self): + """ + Enable the cache. + """ + + @abstractmethod + def disable(self): + """ + Disable the cache. + """ + + @abstractmethod + def flush(self): + """ + Flush the cache. + """ + + +class NullCache(_Cache): + @property + def cache_path(self): + return None + + def load_overload(self, sig, target_context): + pass + + def save_overload(self, sig, cres): + pass + + def enable(self): + pass + + def disable(self): + pass + + def flush(self): + pass + + +class _CacheLocator(metaclass=ABCMeta): + """ + A filesystem locator for caching a given function. + """ + + def ensure_cache_path(self): + path = self.get_cache_path() + os.makedirs(path, exist_ok=True) + # Ensure the directory is writable by trying to write a temporary file + tempfile.TemporaryFile(dir=path).close() + + @abstractmethod + def get_cache_path(self): + """ + Return the directory the function is cached in. + """ + + @abstractmethod + def get_source_stamp(self): + """ + Get a timestamp representing the source code's freshness. + Can return any picklable Python object. + """ + + @abstractmethod + def get_disambiguator(self): + """ + Get a string disambiguator for this locator's function. + It should allow disambiguating different but similarly-named functions. + """ + + @classmethod + def from_function(cls, py_func, py_file): + """ + Create a locator instance for the given function located in the + given file. + """ + raise NotImplementedError + + @classmethod + def get_suitable_cache_subpath(cls, py_file): + """Given the Python file path, compute a suitable path inside the + cache directory. + + This will reduce a file path that is too long, which can be a problem + on some operating system (i.e. Windows 7). + """ + path = os.path.abspath(py_file) + subpath = os.path.dirname(path) + parentdir = os.path.split(subpath)[-1] + # Use SHA1 to reduce path length. + # Note: windows doesn't like long path. + hashed = hashlib.sha1(subpath.encode()).hexdigest() + # Retain parent directory name for easier debugging + return '_'.join([parentdir, hashed]) + + +class _SourceFileBackedLocatorMixin(object): + """ + A cache locator mixin for functions which are backed by a well-known + Python source file. + """ + + def get_source_stamp(self): + if getattr(sys, 'frozen', False): + st = os.stat(sys.executable) + else: + st = os.stat(self._py_file) + # We use both timestamp and size as some filesystems only have second + # granularity. + return st.st_mtime, st.st_size + + def get_disambiguator(self): + return str(self._lineno) + + @classmethod + def from_function(cls, py_func, py_file): + if not os.path.exists(py_file): + # Perhaps a placeholder (e.g. "") + return + self = cls(py_func, py_file) + try: + self.ensure_cache_path() + except OSError: + # Cannot ensure the cache directory exists or is writable + return + return self + + +class UserProvidedCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator that always point to the user provided directory in + `numba.config.CACHE_DIR` + """ + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + cache_subpath = self.get_suitable_cache_subpath(py_file) + self._cache_path = os.path.join(config.CACHE_DIR, cache_subpath) + + def get_cache_path(self): + return self._cache_path + + @classmethod + def from_function(cls, py_func, py_file): + if not config.CACHE_DIR: + return + parent = super(UserProvidedCacheLocator, cls) + return parent.from_function(py_func, py_file) + + +class InTreeCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator for functions backed by a regular Python module with a + writable __pycache__ directory. + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + self._cache_path = os.path.join(os.path.dirname(self._py_file), '__pycache__') + + def get_cache_path(self): + return self._cache_path + + +class InTreeCacheLocatorFsAgnostic(InTreeCacheLocator): + """ + A locator for functions backed by a regular Python module with a + writable __pycache__ directory. This version is agnostic to filesystem differences, + e.g. timestamp precision with milliseconds. + """ + + def get_source_stamp(self): + st = super().get_source_stamp() + return floor(st[0]), st[1] + + +class UserWideCacheLocator(_SourceFileBackedLocatorMixin, _CacheLocator): + """ + A locator for functions backed by a regular Python module or a + frozen executable, cached into a user-wide cache directory. + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + self._lineno = py_func.__code__.co_firstlineno + appdirs = AppDirs(appname="numba", appauthor=False) + cache_dir = appdirs.user_cache_dir + cache_subpath = self.get_suitable_cache_subpath(py_file) + self._cache_path = os.path.join(cache_dir, cache_subpath) + + def get_cache_path(self): + return self._cache_path + + @classmethod + def from_function(cls, py_func, py_file): + if not (os.path.exists(py_file) or getattr(sys, 'frozen', False)): + # Perhaps a placeholder (e.g. "") + # stop function exit if frozen, since it uses a temp placeholder + return + self = cls(py_func, py_file) + try: + self.ensure_cache_path() + except OSError: + # Cannot ensure the cache directory exists or is writable + return + return self + + +class IPythonCacheLocator(_CacheLocator): + """ + A locator for functions entered at the IPython prompt (notebook or other). + """ + + def __init__(self, py_func, py_file): + self._py_file = py_file + # Note IPython enhances the linecache module to be able to + # inspect source code of functions defined on the interactive prompt. + source = inspect.getsource(py_func) + if isinstance(source, bytes): + self._bytes_source = source + else: + self._bytes_source = source.encode('utf-8') + + def get_cache_path(self): + # We could also use jupyter_core.paths.jupyter_runtime_dir() + # In both cases this is a user-wide directory, so we need to + # be careful when disambiguating if we don't want too many + # conflicts (see below). + try: + from IPython.paths import get_ipython_cache_dir + except ImportError: + # older IPython version + from IPython.utils.path import get_ipython_cache_dir + return os.path.join(get_ipython_cache_dir(), 'numba_cache') + + def get_source_stamp(self): + return hashlib.sha256(self._bytes_source).hexdigest() + + def get_disambiguator(self): + # Heuristic: we don't want too many variants being saved, but + # we don't want similar named functions (e.g. "f") to compete + # for the cache, so we hash the first two lines of the function + # source (usually this will be the @jit decorator + the function + # signature). + firstlines = b''.join(self._bytes_source.splitlines(True)[:2]) + return hashlib.sha256(firstlines).hexdigest()[:10] + + @classmethod + def from_function(cls, py_func, py_file): + if not ( + py_file.startswith("' can appear in the qualname (e.g. '') but + # are forbidden in Windows filenames + fixed_fullname = fullname.replace('<', '').replace('>', '') + fmt = '%s-%s.py%d%d%s' + return fmt % (fixed_fullname, self.locator.get_disambiguator(), + sys.version_info[0], sys.version_info[1], abiflags) + + @property + def filename_base(self): + return self._filename_base + + @property + def locator(self): + return self._locator + + @abstractmethod + def reduce(self, data): + "Returns the serialized form the data" + pass + + @abstractmethod + def rebuild(self, target_context, reduced_data): + "Returns the de-serialized form of the *reduced_data*" + pass + + @abstractmethod + def check_cachable(self, data): + "Returns True if the given data is cachable; otherwise, returns False." + pass + + +class CompileResultCacheImpl(CacheImpl): + """ + Implements the logic to cache CompileResult objects. + """ + + def reduce(self, cres): + """ + Returns a serialized CompileResult + """ + return cres._reduce() + + def rebuild(self, target_context, payload): + """ + Returns the unserialized CompileResult + """ + return compiler.CompileResult._rebuild(target_context, *payload) + + def check_cachable(self, cres): + """ + Check cachability of the given compile result. + """ + cannot_cache = None + if any(not x.can_cache for x in cres.lifted): + cannot_cache = "as it uses lifted code" + elif cres.library.has_dynamic_globals: + cannot_cache = ("as it uses dynamic globals " + "(such as ctypes pointers and large global arrays)") + if cannot_cache: + msg = ('Cannot cache compiled function "%s" %s' + % (cres.fndesc.qualname.split('.')[-1], cannot_cache)) + warnings.warn_explicit(msg, NumbaWarning, + self._locator._py_file, self._lineno) + return False + return True + + +class CodeLibraryCacheImpl(CacheImpl): + """ + Implements the logic to cache CodeLibrary objects. + """ + + _filename_prefix = None # must be overridden + + def reduce(self, codelib): + """ + Returns a serialized CodeLibrary + """ + return codelib.serialize_using_object_code() + + def rebuild(self, target_context, payload): + """ + Returns the unserialized CodeLibrary + """ + return target_context.codegen().unserialize_library(payload) + + def check_cachable(self, codelib): + """ + Check cachability of the given CodeLibrary. + """ + return not codelib.has_dynamic_globals + + def get_filename_base(self, fullname, abiflags): + parent = super(CodeLibraryCacheImpl, self) + res = parent.get_filename_base(fullname, abiflags) + return '-'.join([self._filename_prefix, res]) + + +class IndexDataCacheFile(object): + """ + Implements the logic for the index file and data file used by a cache. + """ + def __init__(self, cache_path, filename_base, source_stamp): + self._cache_path = cache_path + self._index_name = '%s.nbi' % (filename_base,) + self._index_path = os.path.join(self._cache_path, self._index_name) + self._data_name_pattern = '%s.{number:d}.nbc' % (filename_base,) + self._source_stamp = source_stamp + self._version = numba.__version__ + + def flush(self): + self._save_index({}) + + def save(self, key, data): + """ + Save a new cache entry with *key* and *data*. + """ + overloads = self._load_index() + try: + # If key already exists, we will overwrite the file + data_name = overloads[key] + except KeyError: + # Find an available name for the data file + existing = set(overloads.values()) + for i in itertools.count(1): + data_name = self._data_name(i) + if data_name not in existing: + break + overloads[key] = data_name + self._save_index(overloads) + self._save_data(data_name, data) + + def load(self, key): + """ + Load a cache entry with *key*. + """ + overloads = self._load_index() + data_name = overloads.get(key) + if data_name is None: + return + try: + return self._load_data(data_name) + except OSError: + # File could have been removed while the index still refers it. + return + + def _load_index(self): + """ + Load the cache index and return it as a dictionary (possibly + empty if cache is empty or obsolete). + """ + try: + with open(self._index_path, "rb") as f: + version = pickle.load(f) + data = f.read() + except FileNotFoundError: + # Index doesn't exist yet? + return {} + if version != self._version: + # This is another version. Avoid trying to unpickling the + # rest of the stream, as that may fail. + return {} + stamp, overloads = pickle.loads(data) + _cache_log("[cache] index loaded from %r", self._index_path) + if stamp != self._source_stamp: + # Cache is not fresh. Stale data files will be eventually + # overwritten, since they are numbered in incrementing order. + return {} + else: + return overloads + + def _save_index(self, overloads): + data = self._source_stamp, overloads + data = self._dump(data) + with self._open_for_write(self._index_path) as f: + pickle.dump(self._version, f, protocol=-1) + f.write(data) + _cache_log("[cache] index saved to %r", self._index_path) + + def _load_data(self, name): + path = self._data_path(name) + with open(path, "rb") as f: + data = f.read() + tup = pickle.loads(data) + _cache_log("[cache] data loaded from %r", path) + return tup + + def _save_data(self, name, data): + data = self._dump(data) + path = self._data_path(name) + with self._open_for_write(path) as f: + f.write(data) + _cache_log("[cache] data saved to %r", path) + + def _data_name(self, number): + return self._data_name_pattern.format(number=number) + + def _data_path(self, name): + return os.path.join(self._cache_path, name) + + def _dump(self, obj): + return dumps(obj) + + @contextlib.contextmanager + def _open_for_write(self, filepath): + """ + Open *filepath* for writing in a race condition-free way (hopefully). + uuid4 is used to try and avoid name collisions on a shared filesystem. + """ + uid = uuid.uuid4().hex[:16] # avoid long paths + tmpname = '%s.tmp.%s' % (filepath, uid) + try: + with open(tmpname, "wb") as f: + yield f + os.replace(tmpname, filepath) + except Exception: + # In case of error, remove dangling tmp file + try: + os.unlink(tmpname) + except OSError: + pass + raise + + +class Cache(_Cache): + """ + A per-function compilation cache. The cache saves data in separate + data files and maintains information in an index file. + + There is one index file per function and Python version + ("function_name-.pyXY.nbi") which contains a mapping of + signatures and architectures to data files. + It is prefixed by a versioning key and a timestamp of the Python source + file containing the function. + + There is one data file ("function_name-.pyXY..nbc") + per function, function signature, target architecture and Python version. + + Separate index and data files per Python version avoid pickle + compatibility problems. + + Note: + This contains the driver logic only. The core logic is provided + by a subclass of ``CacheImpl`` specified as *_impl_class* in the subclass. + """ + + # The following class variables must be overridden by subclass. + _impl_class = None + + def __init__(self, py_func): + self._name = repr(py_func) + self._py_func = py_func + self._impl = self._impl_class(py_func) + self._cache_path = self._impl.locator.get_cache_path() + # This may be a bit strict but avoids us maintaining a magic number + source_stamp = self._impl.locator.get_source_stamp() + filename_base = self._impl.filename_base + self._cache_file = IndexDataCacheFile(cache_path=self._cache_path, + filename_base=filename_base, + source_stamp=source_stamp) + self.enable() + + def __repr__(self): + return "<%s py_func=%r>" % (self.__class__.__name__, self._name) + + @property + def cache_path(self): + return self._cache_path + + def enable(self): + self._enabled = True + + def disable(self): + self._enabled = False + + def flush(self): + self._cache_file.flush() + + def load_overload(self, sig, target_context): + """ + Load and recreate the cached object for the given signature, + using the *target_context*. + """ + # Refresh the context to ensure it is initialized + target_context.refresh() + with self._guard_against_spurious_io_errors(): + return self._load_overload(sig, target_context) + # None returned if the `with` block swallows an exception + + def _load_overload(self, sig, target_context): + if not self._enabled: + return + key = self._index_key(sig, target_context.codegen()) + data = self._cache_file.load(key) + if data is not None: + data = self._impl.rebuild(target_context, data) + return data + + def save_overload(self, sig, data): + """ + Save the data for the given signature in the cache. + """ + with self._guard_against_spurious_io_errors(): + self._save_overload(sig, data) + + def _save_overload(self, sig, data): + if not self._enabled: + return + if not self._impl.check_cachable(data): + return + self._impl.locator.ensure_cache_path() + key = self._index_key(sig, data.codegen) + data = self._impl.reduce(data) + self._cache_file.save(key, data) + + @contextlib.contextmanager + def _guard_against_spurious_io_errors(self): + if os.name == 'nt': + # Guard against permission errors due to accessing the file + # from several processes (see #2028) + try: + yield + except OSError as e: + if e.errno != errno.EACCES: + raise + else: + # No such conditions under non-Windows OSes + yield + + def _index_key(self, sig, codegen): + """ + Compute index key for the given signature and codegen. + It includes a description of the OS, target architecture and hashes of + the bytecode for the function and, if the function has a __closure__, + a hash of the cell_contents. + """ + codebytes = self._py_func.__code__.co_code + if self._py_func.__closure__ is not None: + cvars = tuple([x.cell_contents for x in self._py_func.__closure__]) + # Note: cloudpickle serializes a function differently depending + # on how the process is launched; e.g. multiprocessing.Process + cvarbytes = dumps(cvars) + else: + cvarbytes = b'' + + hasher = lambda x: hashlib.sha256(x).hexdigest() + return (sig, codegen.magic_tuple(), (hasher(codebytes), + hasher(cvarbytes),)) + + +class FunctionCache(Cache): + """ + Implements Cache that saves and loads CompileResult objects. + """ + _impl_class = CompileResultCacheImpl + + +# Remember used cache filename prefixes. +_lib_cache_prefixes = set(['']) + + +def make_library_cache(prefix): + """ + Create a Cache class for additional compilation features to cache their + result for reuse. The cache is saved in filename pattern like + in ``FunctionCache`` but with additional *prefix* as specified. + """ + # avoid cache prefix reuse + assert prefix not in _lib_cache_prefixes + _lib_cache_prefixes.add(prefix) + + class CustomCodeLibraryCacheImpl(CodeLibraryCacheImpl): + _filename_prefix = prefix + + class LibraryCache(Cache): + """ + Implements Cache that saves and loads CodeLibrary objects for additional + feature for the specified python function. + """ + _impl_class = CustomCodeLibraryCacheImpl + + return LibraryCache + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callconv.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callconv.py new file mode 100644 index 0000000000000000000000000000000000000000..a15e0b5165bcf7a4840b91b48a1a98342ec159b4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callconv.py @@ -0,0 +1,963 @@ +""" +Calling conventions for Numba-compiled functions. +""" + +from collections import namedtuple +from collections.abc import Iterable +import itertools +import hashlib + +from llvmlite import ir + +from numba.core import types, cgutils, errors +from numba.core.base import PYOBJECT, GENERIC_POINTER + + +TryStatus = namedtuple('TryStatus', ['in_try', 'excinfo']) + + +Status = namedtuple("Status", + ("code", + # If the function returned ok (a value or None) + "is_ok", + # If the function returned None + "is_none", + # If the function errored out (== not is_ok) + "is_error", + # If the generator exited with StopIteration + "is_stop_iteration", + # If the function errored with an already set exception + "is_python_exc", + # If the function errored with a user exception + "is_user_exc", + # The pointer to the exception info structure (for user + # exceptions) + "excinfoptr", + )) + +int32_t = ir.IntType(32) +int64_t = ir.IntType(64) +errcode_t = int32_t + + +def _const_int(code): + return ir.Constant(errcode_t, code) + + +RETCODE_OK = _const_int(0) +RETCODE_EXC = _const_int(-1) +RETCODE_NONE = _const_int(-2) +# StopIteration +RETCODE_STOPIT = _const_int(-3) + +FIRST_USEREXC = 1 + +RETCODE_USEREXC = _const_int(FIRST_USEREXC) + + +class BaseCallConv(object): + + def __init__(self, context): + self.context = context + + def return_optional_value(self, builder, retty, valty, value): + if valty == types.none: + # Value is none + self.return_native_none(builder) + + elif retty == valty: + # Value is an optional, need a runtime switch + optval = self.context.make_helper(builder, retty, value=value) + + validbit = cgutils.as_bool_bit(builder, optval.valid) + with builder.if_then(validbit): + retval = self.context.get_return_value(builder, retty.type, + optval.data) + self.return_value(builder, retval) + + self.return_native_none(builder) + + elif not isinstance(valty, types.Optional): + # Value is not an optional, need a cast + if valty != retty.type: + value = self.context.cast(builder, value, fromty=valty, + toty=retty.type) + retval = self.context.get_return_value(builder, retty.type, value) + self.return_value(builder, retval) + + else: + raise NotImplementedError("returning {0} for {1}".format(valty, + retty)) + + def return_native_none(self, builder): + self._return_errcode_raw(builder, RETCODE_NONE) + + def return_exc(self, builder): + self._return_errcode_raw(builder, RETCODE_EXC) + + def return_stop_iteration(self, builder): + self._return_errcode_raw(builder, RETCODE_STOPIT) + + def get_return_type(self, ty): + """ + Get the actual type of the return argument for Numba type *ty*. + """ + restype = self.context.data_model_manager[ty].get_return_type() + return restype.as_pointer() + + def init_call_helper(self, builder): + """ + Initialize and return a call helper object for the given builder. + """ + ch = self._make_call_helper(builder) + builder.__call_helper = ch + return ch + + def _get_call_helper(self, builder): + return builder.__call_helper + + def unpack_exception(self, builder, pyapi, status): + return pyapi.unserialize(status.excinfoptr) + + def raise_error(self, builder, pyapi, status): + """ + Given a non-ok *status*, raise the corresponding Python exception. + """ + bbend = builder.function.append_basic_block() + + with builder.if_then(status.is_user_exc): + # Unserialize user exception. + # Make sure another error may not interfere. + pyapi.err_clear() + exc = self.unpack_exception(builder, pyapi, status) + with cgutils.if_likely(builder, + cgutils.is_not_null(builder, exc)): + pyapi.raise_object(exc) # steals ref + builder.branch(bbend) + + with builder.if_then(status.is_stop_iteration): + pyapi.err_set_none("PyExc_StopIteration") + builder.branch(bbend) + + with builder.if_then(status.is_python_exc): + # Error already raised => nothing to do + builder.branch(bbend) + + pyapi.err_set_string("PyExc_SystemError", + "unknown error when calling native function") + builder.branch(bbend) + + builder.position_at_end(bbend) + + def decode_arguments(self, builder, argtypes, func): + """ + Get the decoded (unpacked) Python arguments with *argtypes* + from LLVM function *func*. A tuple of LLVM values is returned. + """ + raw_args = self.get_arguments(func) + arginfo = self._get_arg_packer(argtypes) + return arginfo.from_arguments(builder, raw_args) + + def _get_arg_packer(self, argtypes): + """ + Get an argument packer for the given argument types. + """ + return self.context.get_arg_packer(argtypes) + + +class MinimalCallConv(BaseCallConv): + """ + A minimal calling convention, suitable for e.g. GPU targets. + The implemented function signature is: + + retcode_t (*, ... ) + + The return code will be one of the RETCODE_* constants or a + function-specific user exception id (>= RETCODE_USEREXC). + + Caller is responsible for allocating a slot for the return value + (passed as a pointer in the first argument). + """ + + def _make_call_helper(self, builder): + return _MinimalCallHelper() + + def return_value(self, builder, retval): + retptr = builder.function.args[0] + assert retval.type == retptr.type.pointee, \ + (str(retval.type), str(retptr.type.pointee)) + builder.store(retval, retptr) + self._return_errcode_raw(builder, RETCODE_OK) + + def return_user_exc(self, builder, exc, exc_args=None, loc=None, + func_name=None): + if exc is not None and not issubclass(exc, BaseException): + raise TypeError("exc should be None or exception class, got %r" + % (exc,)) + if exc_args is not None and not isinstance(exc_args, tuple): + raise TypeError("exc_args should be None or tuple, got %r" + % (exc_args,)) + + # Build excinfo struct + if loc is not None: + fname = loc._raw_function_name() + if fname is None: + # could be exec() or REPL, try func_name + fname = func_name + + locinfo = (fname, loc.filename, loc.line) + if None in locinfo: + locinfo = None + else: + locinfo = None + + call_helper = self._get_call_helper(builder) + exc_id = call_helper._add_exception(exc, exc_args, locinfo) + self._return_errcode_raw(builder, _const_int(exc_id)) + + def return_status_propagate(self, builder, status): + self._return_errcode_raw(builder, status.code) + + def _return_errcode_raw(self, builder, code): + if isinstance(code, int): + code = _const_int(code) + builder.ret(code) + + def _get_return_status(self, builder, code): + """ + Given a return *code*, get a Status instance. + """ + norm = builder.icmp_signed('==', code, RETCODE_OK) + none = builder.icmp_signed('==', code, RETCODE_NONE) + ok = builder.or_(norm, none) + err = builder.not_(ok) + exc = builder.icmp_signed('==', code, RETCODE_EXC) + is_stop_iteration = builder.icmp_signed('==', code, RETCODE_STOPIT) + is_user_exc = builder.icmp_signed('>=', code, RETCODE_USEREXC) + + status = Status(code=code, + is_ok=ok, + is_error=err, + is_python_exc=exc, + is_none=none, + is_user_exc=is_user_exc, + is_stop_iteration=is_stop_iteration, + excinfoptr=None) + return status + + def get_function_type(self, restype, argtypes): + """ + Get the implemented Function type for *restype* and *argtypes*. + """ + arginfo = self._get_arg_packer(argtypes) + argtypes = list(arginfo.argument_types) + resptr = self.get_return_type(restype) + fnty = ir.FunctionType(errcode_t, [resptr] + argtypes) + return fnty + + def decorate_function(self, fn, args, fe_argtypes, noalias=False): + """ + Set names and attributes of function arguments. + """ + assert not noalias + arginfo = self._get_arg_packer(fe_argtypes) + arginfo.assign_names(self.get_arguments(fn), + ['arg.' + a for a in args]) + fn.args[0].name = ".ret" + + def get_arguments(self, func): + """ + Get the Python-level arguments of LLVM *func*. + """ + return func.args[1:] + + def call_function(self, builder, callee, resty, argtys, args): + """ + Call the Numba-compiled *callee*. + """ + retty = callee.args[0].type.pointee + retvaltmp = cgutils.alloca_once(builder, retty) + # initialize return value + builder.store(cgutils.get_null_value(retty), retvaltmp) + + arginfo = self._get_arg_packer(argtys) + args = arginfo.as_arguments(builder, args) + realargs = [retvaltmp] + list(args) + code = builder.call(callee, realargs) + status = self._get_return_status(builder, code) + retval = builder.load(retvaltmp) + out = self.context.get_returned_value(builder, resty, retval) + return status, out + + +class _MinimalCallHelper(object): + """ + A call helper object for the "minimal" calling convention. + User exceptions are represented as integer codes and stored in + a mapping for retrieval from the caller. + """ + + def __init__(self): + self.exceptions = {} + + def _add_exception(self, exc, exc_args, locinfo): + """ + Add a new user exception to this helper. Returns an integer that can be + used to refer to the added exception in future. + + Parameters + ---------- + exc : + exception type + exc_args : None or tuple + exception args + locinfo : tuple + location information + """ + exc_id = len(self.exceptions) + FIRST_USEREXC + self.exceptions[exc_id] = exc, exc_args, locinfo + return exc_id + + def get_exception(self, exc_id): + """ + Get information about a user exception. Returns a tuple of + (exception type, exception args, location information). + + Parameters + ---------- + id : integer + The ID of the exception to look up + """ + try: + return self.exceptions[exc_id] + except KeyError: + msg = "unknown error %d in native function" % exc_id + exc = SystemError + exc_args = (msg,) + locinfo = None + return exc, exc_args, locinfo + + +# The structure type constructed by PythonAPI.serialize_uncached() +# i.e a {i8* pickle_buf, i32 pickle_bufsz, i8* hash_buf, i8* fn, i32 alloc_flag} +PICKLE_BUF_IDX = 0 +PICKLE_BUFSZ_IDX = 1 +HASH_BUF_IDX = 2 +UNWRAP_FUNC_IDX = 3 +ALLOC_FLAG_IDX = 4 +excinfo_t = ir.LiteralStructType( + [GENERIC_POINTER, int32_t, GENERIC_POINTER, GENERIC_POINTER, int32_t]) +excinfo_ptr_t = ir.PointerType(excinfo_t) + + +class CPUCallConv(BaseCallConv): + """ + The calling convention for CPU targets. + The implemented function signature is: + + retcode_t (*, excinfo **, ... ) + + The return code will be one of the RETCODE_* constants. + If RETCODE_USEREXC, the exception info pointer will be filled with + a pointer to a constant struct describing the raised exception. + + Caller is responsible for allocating slots for the return value + and the exception info pointer (passed as first and second arguments, + respectively). + """ + _status_ids = itertools.count(1) + + def _make_call_helper(self, builder): + return None + + def return_value(self, builder, retval): + retptr = self._get_return_argument(builder.function) + assert retval.type == retptr.type.pointee, \ + (str(retval.type), str(retptr.type.pointee)) + builder.store(retval, retptr) + self._return_errcode_raw(builder, RETCODE_OK) + + def build_excinfo_struct(self, exc, exc_args, loc, func_name): + # Build excinfo struct + if loc is not None: + fname = loc._raw_function_name() + if fname is None: + # could be exec() or REPL, try func_name + fname = func_name + + locinfo = (fname, loc.filename, loc.line) + if None in locinfo: + locinfo = None + else: + locinfo = None + + exc = (exc, exc_args, locinfo) + return exc + + def set_static_user_exc(self, builder, exc, exc_args=None, loc=None, + func_name=None): + if exc is not None and not issubclass(exc, BaseException): + raise TypeError("exc should be None or exception class, got %r" + % (exc,)) + if exc_args is not None and not isinstance(exc_args, tuple): + raise TypeError("exc_args should be None or tuple, got %r" + % (exc_args,)) + # None is indicative of no args, set the exc_args to an empty tuple + # as PyObject_CallObject(exc, exc_args) requires the second argument to + # be a tuple (or nullptr, but doing this makes it consistent) + if exc_args is None: + exc_args = tuple() + + # An exception in Numba is defined as the excinfo_t struct defined + # above. Some arguments in this struct are not used, depending on + # which kind of exception is being raised. A static exception uses + # only the first three members whilst a dynamic exception uses all + # members: + # + # static exc - last 2 args are NULL and 0 + # vvv vvv vvv + # excinfo_t: {i8*, i32, i8*, i8*, i32} + # ^^^ ^^^ ^^^ + # dynamic exc only - first 2 args are used for + # static info + # + # Comment below details how the struct is used in the case of a dynamic + # exception. For dynamic exceptions, see + # CPUCallConv::set_dynamic_user_exc + # + # {i8*, ___, ___, ___, ___} + # ^ serialized info about the exception (loc, kind, compile time + # args) + # + # {___, i32, ___, ___, ___} + # ^ len(serialized_exception) + # + # {___, ___, i8*, ___, ___} + # ^ Store a list of native values in a dynamic exception. + # Or a hash(serialized_exception) in a static exc. + # + # {___, ___, ___, i8*, ___} + # ^ "NULL" as this member is not used in a static exc + # + # {___, ___, ___, ___, i32} + # ^ Number of dynamic args in the exception. For + # static exceptions, this value is "0" + + pyapi = self.context.get_python_api(builder) + exc = self.build_excinfo_struct(exc, exc_args, loc, func_name) + struct_gv = pyapi.serialize_object(exc) + excptr = self._get_excinfo_argument(builder.function) + store = builder.store(struct_gv, excptr) + md = builder.module.add_metadata([ir.IntType(1)(1)]) + store.set_metadata("numba_exception_output", md) + + def return_user_exc(self, builder, exc, exc_args=None, loc=None, + func_name=None): + try_info = getattr(builder, '_in_try_block', False) + self.set_static_user_exc(builder, exc, exc_args=exc_args, + loc=loc, func_name=func_name) + self.check_try_status(builder) + if try_info: + # This is a hack for old-style impl. + # We will branch directly to the exception handler. + builder.branch(try_info['target']) + else: + # Return from the current function + self._return_errcode_raw(builder, RETCODE_USEREXC) + + def unpack_dynamic_exception(self, builder, pyapi, status): + excinfo_ptr = status.excinfoptr + + # load the serialized exception buffer from the module and create + # a python bytes object + picklebuf = builder.extract_value( + builder.load(excinfo_ptr), PICKLE_BUF_IDX) + picklebuf_sz = builder.extract_value( + builder.load(excinfo_ptr), PICKLE_BUFSZ_IDX) + static_exc_bytes = pyapi.bytes_from_string_and_size( + picklebuf, builder.sext(picklebuf_sz, pyapi.py_ssize_t)) + + # Load dynamic args (i8*) and the unwrap function + dyn_args = builder.extract_value( + builder.load(excinfo_ptr), HASH_BUF_IDX) + func_ptr = builder.extract_value( + builder.load(excinfo_ptr), UNWRAP_FUNC_IDX) + + # Convert the unwrap function to a function pointer and call it. + # Function returns a python tuple with dynamic arguments converted to + # CPython objects + fnty = ir.FunctionType(PYOBJECT, [GENERIC_POINTER]) + fn = builder.bitcast(func_ptr, fnty.as_pointer()) + py_tuple = builder.call(fn, [dyn_args]) + + # We check at this stage if creating the Python tuple was successful + # or not. Note the exception is raised by calling PyErr_SetString + # directly as the current function is the CPython wrapper. + failed = cgutils.is_null(builder, py_tuple) + with cgutils.if_unlikely(builder, failed): + msg = ('Error creating Python tuple from runtime exception ' + 'arguments') + pyapi.err_set_string("PyExc_RuntimeError", msg) + # Return NULL to indicate an error was raised + fnty = builder.function.function_type + if not isinstance(fnty.return_type, ir.VoidType): + # in some ufuncs, the return type is void + builder.ret(cgutils.get_null_value(fnty.return_type)) + else: + builder.ret_void() + + # merge static and dynamic variables + excinfo = pyapi.build_dynamic_excinfo_struct(static_exc_bytes, py_tuple) + + # At this point, one can free the entire excinfo_ptr struct + if self.context.enable_nrt: + # One can safely emit a free instruction as it is only executed + # if its in a dynamic exception branch + self.context.nrt.free( + builder, builder.bitcast(excinfo_ptr, pyapi.voidptr)) + return excinfo + + def unpack_exception(self, builder, pyapi, status): + # Emit code that checks the alloc flag (last excinfo member) + # if alloc_flag > 0: + # (dynamic) unpack the exception to retrieve runtime information + # and merge with static info + # else: + # (static) unserialize the exception using pythonapi.unserialize + + excinfo_ptr = status.excinfoptr + alloc_flag = builder.extract_value(builder.load(excinfo_ptr), + ALLOC_FLAG_IDX) + gt = builder.icmp_signed('>', alloc_flag, int32_t(0)) + with builder.if_else(gt) as (then, otherwise): + with then: + dyn_exc = self.unpack_dynamic_exception(builder, pyapi, status) + bb_then = builder.block + with otherwise: + static_exc = pyapi.unserialize(excinfo_ptr) + bb_else = builder.block + phi = builder.phi(static_exc.type) + phi.add_incoming(dyn_exc, bb_then) + phi.add_incoming(static_exc, bb_else) + return phi + + def emit_unwrap_dynamic_exception_fn(self, module, st_type, nb_types): + # Create a function that converts a list of runtime arguments to a tuple + # of PyObjects. i.e.: + # + # @njit('void(float, int64)') + # def func(a, b): + # raise ValueError(a, 123, b) + # + # The last three arguments of the exception info structure will hold: + # {___, ___, i8*, i8*, i32} + # ^ A ptr to a {f32, i64} struct + # ^ function ptr that converts i8* -> {f32, i64}* -> + # python tuple + # ^ Number of dynamic arguments = 2 + # + + _hash = hashlib.sha1(str(st_type).encode()).hexdigest() + name = f'__excinfo_unwrap_args{_hash}' + if name in module.globals: + return module.globals.get(name) + + fnty = ir.FunctionType(GENERIC_POINTER, [GENERIC_POINTER]) + fn = ir.Function(module, fnty, name) + # Linkage is changed to linkonce_odr for PYCC. External is the default. + fn.linkage = "external" + + # prevent the function from being inlined + fn.attributes.add('nounwind') + fn.attributes.add('noinline') + + bb_entry = fn.append_basic_block('') + builder = ir.IRBuilder(bb_entry) + pyapi = self.context.get_python_api(builder) + + # i8* -> {native arg1 type, native arg2 type, ...} + st_type_ptr = st_type.as_pointer() + st_ptr = builder.bitcast(fn.args[0], st_type_ptr) + # compile time values are stored as None + nb_types = [typ for typ in nb_types if typ is not None] + + # convert native values into CPython objects + objs = [] + env_manager = self.context.get_env_manager(builder, + return_pyobject=True) + for i, typ in enumerate(nb_types): + val = builder.extract_value(builder.load(st_ptr), i) + obj = pyapi.from_native_value(typ, val, env_manager=env_manager) + + # If object cannot be boxed, raise an exception + if obj == cgutils.get_null_value(obj.type): + # When not supported, abort compilation + msg = f'Cannot convert native {typ} to a Python object.' + raise errors.TypingError(msg) + + objs.append(obj) + + # at this point, a pointer to the list of runtime values can be freed + self.context.nrt.free(builder, + self._get_return_argument(builder.function)) + + # Create a tuple of CPython objects + tup = pyapi.tuple_pack(objs) + builder.ret(tup) + + return fn + + def emit_wrap_args_insts(self, builder, pyapi, struct_type, exc_args): + """ + Create an anonymous struct containing the given LLVM *values*. + """ + st_size = pyapi.py_ssize_t(self.context.get_abi_sizeof(struct_type)) + + st_ptr = builder.bitcast( + self.context.nrt.allocate(builder, st_size), + struct_type.as_pointer()) + + # skip compile-time values + exc_args = [arg for arg in exc_args if isinstance(arg, ir.Value)] + + zero = int32_t(0) + for idx, arg in enumerate(exc_args): + builder.store(arg, builder.gep(st_ptr, [zero, int32_t(idx)])) + + return st_ptr + + def set_dynamic_user_exc(self, builder, exc, exc_args, nb_types, loc=None, + func_name=None): + """ + Compute the required bits to emit an exception with dynamic (runtime) + values + """ + if not issubclass(exc, BaseException): + raise TypeError("exc should be an exception class, got %r" + % (exc,)) + if exc_args is not None and not isinstance(exc_args, tuple): + raise TypeError("exc_args should be None or tuple, got %r" + % (exc_args,)) + + # An exception in Numba is defined as the excinfo_t struct defined + # above. Some arguments in this struct are not used, depending on + # which kind of exception is being raised. A static exception uses + # only the first three members whilst a dynamic exception uses all + # members: + # + # static exc - last 2 args are NULL and 0 + # vvv vvv vvv + # excinfo_t: {i8*, i32, i8*, i8*, i32} + # ^^^ ^^^ ^^^ + # dynamic exc only - first 2 args are used for + # static info + # + # Comment below details how the struct is used in the case of a dynamic + # exception. For static exception, see CPUCallConv::set_static_user_exc + # + # {i8*, ___, ___, ___, ___} + # ^ serialized info about the exception (loc, kind, compile time + # args) + # + # {___, i32, ___, ___, ___} + # ^ len(serialized_exception) + # + # {___, ___, i8*, ___, ___} + # ^ Store a list of native values in a dynamic exception. + # Or a hash(serialized_exception) in a static exc. + # + # {___, ___, ___, i8*, ___} + # ^ Pointer to function that convert native values + # into PyObject*. NULL in the case of a static + # exception + # + # {___, ___, ___, ___, i32} + # ^ Number of dynamic args in the exception. + # Default is "0" + # + # The following code will: + # 1) Serialize compile time information and store them in the first + # two args {i8*, i32, ___, ___, ___} of excinfo_t + # 2) Emit the required code for converting native values to CPython + # objects. Those objects are stored in the last three args + # {___, ___, i8*, i8*, i32} of excinfo_t + # 3) Allocate a new excinfo_t struct + # 4) Fill excinfo_t struct and copy the pointer to the excinfo** arg + + # serialize comp. time args + pyapi = self.context.get_python_api(builder) + dummy = self.context.get_dummy_value() + exc_args_static = tuple( + [dummy if isinstance(arg, ir.Value) else arg for arg in exc_args]) + exc = self.build_excinfo_struct(exc, exc_args_static, loc, func_name) + excinfo_pp = self._get_excinfo_argument(builder.function) + struct_gv = builder.load(pyapi.serialize_object(exc)) + + # Create the struct for runtime args and emit a function to convert it + # into a Python tuple + struct_type = ir.LiteralStructType([arg.type for arg in exc_args if + isinstance(arg, ir.Value)]) + st_ptr = self.emit_wrap_args_insts(builder, pyapi, struct_type, + exc_args) + unwrap_fn = self.emit_unwrap_dynamic_exception_fn( + builder.module, struct_type, nb_types) + + # allocate the excinfo struct + exc_size = pyapi.py_ssize_t(self.context.get_abi_sizeof(excinfo_t)) + excinfo_p = builder.bitcast( + self.context.nrt.allocate(builder, exc_size), + excinfo_ptr_t) + + # fill the args + zero = int32_t(0) + exc_fields = (builder.extract_value(struct_gv, PICKLE_BUF_IDX), + builder.extract_value(struct_gv, PICKLE_BUFSZ_IDX), + builder.bitcast(st_ptr, GENERIC_POINTER), + builder.bitcast(unwrap_fn, GENERIC_POINTER), + int32_t(len(struct_type))) + for idx, arg in enumerate(exc_fields): + builder.store(arg, builder.gep(excinfo_p, [zero, int32_t(idx)])) + builder.store(excinfo_p, excinfo_pp) + + def return_dynamic_user_exc(self, builder, exc, exc_args, nb_types, + loc=None, func_name=None): + """ + Same as ::return_user_exc but for dynamic exceptions + """ + self.set_dynamic_user_exc(builder, exc, exc_args, nb_types, + loc=loc, func_name=func_name) + self._return_errcode_raw(builder, RETCODE_USEREXC) + + def _get_try_state(self, builder): + try: + return builder.__eh_try_state + except AttributeError: + ptr = cgutils.alloca_once( + builder, cgutils.intp_t, name='try_state', zfill=True, + ) + builder.__eh_try_state = ptr + return ptr + + def check_try_status(self, builder): + try_state_ptr = self._get_try_state(builder) + try_depth = builder.load(try_state_ptr) + # try_depth > 0 + in_try = builder.icmp_unsigned('>', try_depth, try_depth.type(0)) + + excinfoptr = self._get_excinfo_argument(builder.function) + excinfo = builder.load(excinfoptr) + + return TryStatus(in_try=in_try, excinfo=excinfo) + + def set_try_status(self, builder): + try_state_ptr = self._get_try_state(builder) + # Increment try depth + old = builder.load(try_state_ptr) + new = builder.add(old, old.type(1)) + builder.store(new, try_state_ptr) + + def unset_try_status(self, builder): + try_state_ptr = self._get_try_state(builder) + # Decrement try depth + old = builder.load(try_state_ptr) + new = builder.sub(old, old.type(1)) + builder.store(new, try_state_ptr) + + # Needs to reset the exception state so that the exception handler + # will run normally. + excinfoptr = self._get_excinfo_argument(builder.function) + null = cgutils.get_null_value(excinfoptr.type.pointee) + builder.store(null, excinfoptr) + + def return_status_propagate(self, builder, status): + trystatus = self.check_try_status(builder) + excptr = self._get_excinfo_argument(builder.function) + builder.store(status.excinfoptr, excptr) + with builder.if_then(builder.not_(trystatus.in_try)): + self._return_errcode_raw(builder, status.code) + + def _return_errcode_raw(self, builder, code): + builder.ret(code) + + def _get_return_status(self, builder, code, excinfoptr): + """ + Given a return *code* and *excinfoptr*, get a Status instance. + """ + norm = builder.icmp_signed('==', code, RETCODE_OK) + none = builder.icmp_signed('==', code, RETCODE_NONE) + exc = builder.icmp_signed('==', code, RETCODE_EXC) + is_stop_iteration = builder.icmp_signed('==', code, RETCODE_STOPIT) + ok = builder.or_(norm, none) + err = builder.not_(ok) + is_user_exc = builder.icmp_signed('>=', code, RETCODE_USEREXC) + excinfoptr = builder.select(is_user_exc, excinfoptr, + ir.Constant(excinfo_ptr_t, ir.Undefined)) + + status = Status(code=code, + is_ok=ok, + is_error=err, + is_python_exc=exc, + is_none=none, + is_user_exc=is_user_exc, + is_stop_iteration=is_stop_iteration, + excinfoptr=excinfoptr) + return status + + def get_function_type(self, restype, argtypes): + """ + Get the implemented Function type for *restype* and *argtypes*. + """ + arginfo = self._get_arg_packer(argtypes) + argtypes = list(arginfo.argument_types) + resptr = self.get_return_type(restype) + fnty = ir.FunctionType(errcode_t, + [resptr, ir.PointerType(excinfo_ptr_t)] + + argtypes) + return fnty + + def decorate_function(self, fn, args, fe_argtypes, noalias=False): + """ + Set names of function arguments, and add useful attributes to them. + """ + arginfo = self._get_arg_packer(fe_argtypes) + arginfo.assign_names(self.get_arguments(fn), + ['arg.' + a for a in args]) + retarg = self._get_return_argument(fn) + retarg.name = "retptr" + retarg.add_attribute("nocapture") + retarg.add_attribute("noalias") + excarg = self._get_excinfo_argument(fn) + excarg.name = "excinfo" + excarg.add_attribute("nocapture") + excarg.add_attribute("noalias") + + if noalias: + args = self.get_arguments(fn) + for a in args: + if isinstance(a.type, ir.PointerType): + a.add_attribute("nocapture") + a.add_attribute("noalias") + + # Add metadata to mark functions that may need NRT + # thus disabling aggressive refct pruning in removerefctpass.py + def type_may_always_need_nrt(ty): + # Returns True if it's a non-Array type that is contains MemInfo + if not isinstance(ty, types.Array): + dmm = self.context.data_model_manager + if dmm[ty].contains_nrt_meminfo(): + return True + return False + + args_may_always_need_nrt = any( + map(type_may_always_need_nrt, fe_argtypes) + ) + + if args_may_always_need_nrt: + nmd = fn.module.add_named_metadata( + 'numba_args_may_always_need_nrt', + ) + nmd.add(fn.module.add_metadata([fn])) + + def get_arguments(self, func): + """ + Get the Python-level arguments of LLVM *func*. + """ + return func.args[2:] + + def _get_return_argument(self, func): + return func.args[0] + + def _get_excinfo_argument(self, func): + return func.args[1] + + def call_function(self, builder, callee, resty, argtys, args, + attrs=None): + """ + Call the Numba-compiled *callee*. + Parameters: + ----------- + attrs: LLVM style string or iterable of individual attributes, default + is None which specifies no attributes. Examples: + LLVM style string: "noinline fast" + Equivalent iterable: ("noinline", "fast") + """ + retty = self.get_return_type(resty).pointee + actual_retty = self._get_return_argument(callee.function_type).pointee + if retty != actual_retty: + m = f"Function type returns {actual_retty} but resty={retty}" + raise ValueError(m) + + retvaltmp = cgutils.alloca_once(builder, retty) + # initialize return value to zeros + builder.store(cgutils.get_null_value(retty), retvaltmp) + + excinfoptr = cgutils.alloca_once(builder, ir.PointerType(excinfo_t), + name="excinfo") + + arginfo = self._get_arg_packer(argtys) + args = list(arginfo.as_arguments(builder, args)) + realargs = [retvaltmp, excinfoptr] + args + # deal with attrs, it's fine to specify a load in a string like + # "noinline fast" as per LLVM or equally as an iterable of individual + # attributes. + if attrs is None: + _attrs = () + elif isinstance(attrs, Iterable) and not isinstance(attrs, str): + _attrs = tuple(attrs) + else: + raise TypeError("attrs must be an iterable of strings or None") + code = builder.call(callee, realargs, attrs=_attrs) + status = self._get_return_status(builder, code, + builder.load(excinfoptr)) + retval = builder.load(retvaltmp) + out = self.context.get_returned_value(builder, resty, retval) + return status, out + + +class ErrorModel(object): + + def __init__(self, call_conv): + self.call_conv = call_conv + + def fp_zero_division(self, builder, exc_args=None, loc=None): + if self.raise_on_fp_zero_division: + self.call_conv.return_user_exc(builder, ZeroDivisionError, exc_args, + loc) + return True + else: + return False + + +class PythonErrorModel(ErrorModel): + """ + The Python error model. Any invalid FP input raises an exception. + """ + raise_on_fp_zero_division = True + + +class NumpyErrorModel(ErrorModel): + """ + In the Numpy error model, floating-point errors don't raise an + exception. The FPU exception state is inspected by Numpy at the + end of a ufunc's execution and a warning is raised if appropriate. + + Note there's no easy way to set the FPU exception state from LLVM. + Instructions known to set an FP exception can be optimized away: + https://llvm.org/bugs/show_bug.cgi?id=6050 + http://lists.llvm.org/pipermail/llvm-dev/2014-September/076918.html + http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20140929/237997.html + """ + raise_on_fp_zero_division = False + + +error_models = { + 'python': PythonErrorModel, + 'numpy': NumpyErrorModel, +} + + +def create_error_model(model_name, context): + """ + Create an error model instance for the given target context. + """ + return error_models[model_name](context.call_conv) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callwrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callwrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..5508aa38e516b92d89f1c97c01c2ec861a612cc0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/callwrapper.py @@ -0,0 +1,226 @@ +from llvmlite.ir import Constant, IRBuilder +import llvmlite.ir + +from numba.core import types, config, cgutils + + +class _ArgManager(object): + """ + A utility class to handle argument unboxing and cleanup + """ + def __init__(self, context, builder, api, env_manager, endblk, nargs): + self.context = context + self.builder = builder + self.api = api + self.env_manager = env_manager + self.arg_count = 0 # how many function arguments have been processed + self.cleanups = [] + self.nextblk = endblk + + def add_arg(self, obj, ty): + """ + Unbox argument and emit code that handles any error during unboxing. + Args are cleaned up in reverse order of the parameter list, and + cleanup begins as soon as unboxing of any argument fails. E.g. failure + on arg2 will result in control flow going through: + + arg2.err -> arg1.err -> arg0.err -> arg.end (returns) + """ + # Unbox argument + native = self.api.to_native_value(ty, obj) + + # If an error occurred, go to the cleanup block for + # the previous argument + with cgutils.if_unlikely(self.builder, native.is_error): + self.builder.branch(self.nextblk) + + # Define the cleanup function for the argument + def cleanup_arg(): + # Native value reflection + self.api.reflect_native_value(ty, native.value, self.env_manager) + + # Native value cleanup + if native.cleanup is not None: + native.cleanup() + + # NRT cleanup + # (happens after the native value cleanup as the latter + # may need the native value) + if self.context.enable_nrt: + self.context.nrt.decref(self.builder, ty, native.value) + + self.cleanups.append(cleanup_arg) + + # Write the on-error cleanup block for this argument + cleanupblk = self.builder.append_basic_block( + "arg%d.err" % self.arg_count) + with self.builder.goto_block(cleanupblk): + cleanup_arg() + # Go to next cleanup block + self.builder.branch(self.nextblk) + + self.nextblk = cleanupblk + self.arg_count += 1 + return native.value + + def emit_cleanup(self): + """ + Emit the cleanup code after returning from the wrapped function. + """ + for dtor in self.cleanups: + dtor() + + +class _GilManager(object): + """ + A utility class to handle releasing the GIL and then re-acquiring it + again. + """ + + def __init__(self, builder, api, argman): + self.builder = builder + self.api = api + self.argman = argman + self.thread_state = api.save_thread() + + def emit_cleanup(self): + self.api.restore_thread(self.thread_state) + self.argman.emit_cleanup() + + +class PyCallWrapper(object): + def __init__(self, context, module, func, fndesc, env, call_helper, + release_gil): + self.context = context + self.module = module + self.func = func + self.fndesc = fndesc + self.env = env + self.release_gil = release_gil + + def build(self): + wrapname = self.fndesc.llvm_cpython_wrapper_name + + # This is the signature of PyCFunctionWithKeywords + # (see CPython's methodobject.h) + pyobj = self.context.get_argument_type(types.pyobject) + wrapty = llvmlite.ir.FunctionType(pyobj, [pyobj, pyobj, pyobj]) + wrapper = llvmlite.ir.Function(self.module, wrapty, name=wrapname) + + builder = IRBuilder(wrapper.append_basic_block('entry')) + + # - `closure` will receive the `self` pointer stored in the + # PyCFunction object (see _dynfunc.c) + # - `args` and `kws` will receive the tuple and dict objects + # of positional and keyword arguments, respectively. + closure, args, kws = wrapper.args + closure.name = 'py_closure' + args.name = 'py_args' + kws.name = 'py_kws' + + api = self.context.get_python_api(builder) + self.build_wrapper(api, builder, closure, args, kws) + + return wrapper, api + + def build_wrapper(self, api, builder, closure, args, kws): + nargs = len(self.fndesc.argtypes) + + objs = [api.alloca_obj() for _ in range(nargs)] + parseok = api.unpack_tuple(args, self.fndesc.qualname, + nargs, nargs, *objs) + + pred = builder.icmp_unsigned( + '==', + parseok, + Constant(parseok.type, None)) + with cgutils.if_unlikely(builder, pred): + builder.ret(api.get_null_object()) + + # Block that returns after erroneous argument unboxing/cleanup + endblk = builder.append_basic_block("arg.end") + with builder.goto_block(endblk): + builder.ret(api.get_null_object()) + + # Get the Environment object + env_manager = self.get_env(api, builder) + + cleanup_manager = _ArgManager(self.context, builder, api, + env_manager, endblk, nargs) + + # Compute the arguments to the compiled Numba function. + innerargs = [] + for obj, ty in zip(objs, self.fndesc.argtypes): + if isinstance(ty, types.Omitted): + # It's an omitted value => ignore dummy Python object + innerargs.append(None) + else: + val = cleanup_manager.add_arg(builder.load(obj), ty) + innerargs.append(val) + + if self.release_gil: + cleanup_manager = _GilManager(builder, api, cleanup_manager) + + # We elect to not inline the top level user function into the call + # wrapper, this incurs an overhead of a function call, however, it + # increases optimisation stability in that the optimised user function + # is what will actually be run and it is this function that all the + # inspection tools "see". Further, this makes optimisation "stable" in + # that calling the user function from e.g. C or from this wrapper will + # result in the same code executing, were inlining permitted this may + # not be the case as the inline could trigger additional optimisation + # as the function goes into the wrapper, this resulting in the executing + # instruction stream being different from that of the instruction stream + # present in the user function. + status, retval = self.context.call_conv.call_function( + builder, self.func, self.fndesc.restype, self.fndesc.argtypes, + innerargs, attrs=('noinline',)) + # Do clean up + self.debug_print(builder, "# callwrapper: emit_cleanup") + cleanup_manager.emit_cleanup() + self.debug_print(builder, "# callwrapper: emit_cleanup end") + + # Determine return status + with builder.if_then(status.is_ok, likely=True): + # Ok => return boxed Python value + with builder.if_then(status.is_none): + api.return_none() + + retty = self._simplified_return_type() + obj = api.from_native_return(retty, retval, env_manager) + builder.ret(obj) + + # Error out + self.context.call_conv.raise_error(builder, api, status) + builder.ret(api.get_null_object()) + + def get_env(self, api, builder): + """Get the Environment object which is declared as a global + in the module of the wrapped function. + """ + envname = self.context.get_env_name(self.fndesc) + gvptr = self.context.declare_env_global(builder.module, envname) + envptr = builder.load(gvptr) + + env_body = self.context.get_env_body(builder, envptr) + + api.emit_environment_sentry(envptr, return_pyobject=True, + debug_msg=self.fndesc.env_name) + env_manager = api.get_env_manager(self.env, env_body, envptr) + return env_manager + + def _simplified_return_type(self): + """ + The NPM callconv has already converted simplified optional types. + We can simply use the value type from it. + """ + restype = self.fndesc.restype + # Optional type + if isinstance(restype, types.Optional): + return restype.type + else: + return restype + + def debug_print(self, builder, msg): + if config.DEBUG_JIT: + self.context.debug_print(builder, "DEBUGJIT: {0}".format(msg)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ccallback.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..b68d0efb5f4831233f56fecfc79af50cc2791064 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ccallback.py @@ -0,0 +1,135 @@ +""" +Implementation of compiled C callbacks (@cfunc). +""" + + +import ctypes +from functools import cached_property + +from numba.core import compiler, registry +from numba.core.caching import NullCache, FunctionCache +from numba.core.dispatcher import _FunctionCompiler +from numba.core.typing import signature +from numba.core.typing.ctypes_utils import to_ctypes +from numba.core.compiler_lock import global_compiler_lock + + +class _CFuncCompiler(_FunctionCompiler): + + def _customize_flags(self, flags): + flags.no_cpython_wrapper = True + flags.no_cfunc_wrapper = False + # Disable compilation of the IR module, because we first want to + # add the cfunc wrapper. + flags.no_compile = True + # Object mode is not currently supported in C callbacks + # (no reliable way to get the environment) + flags.enable_pyobject = False + if flags.force_pyobject: + raise NotImplementedError("object mode not allowed in C callbacks") + return flags + + +class CFunc(object): + """ + A compiled C callback, as created by the @cfunc decorator. + """ + _targetdescr = registry.cpu_target + + def __init__(self, pyfunc, sig, locals, options, + pipeline_class=compiler.Compiler): + args, return_type = sig + if return_type is None: + raise TypeError("C callback needs an explicit return type") + self.__name__ = pyfunc.__name__ + self.__qualname__ = getattr(pyfunc, '__qualname__', self.__name__) + self.__wrapped__ = pyfunc + + self._pyfunc = pyfunc + self._sig = signature(return_type, *args) + self._compiler = _CFuncCompiler(pyfunc, self._targetdescr, + options, locals, + pipeline_class=pipeline_class) + + self._wrapper_name = None + self._wrapper_address = None + self._cache = NullCache() + self._cache_hits = 0 + + def enable_caching(self): + self._cache = FunctionCache(self._pyfunc) + + @global_compiler_lock + def compile(self): + # Try to load from cache + cres = self._cache.load_overload(self._sig, + self._targetdescr.target_context) + if cres is None: + cres = self._compile_uncached() + self._cache.save_overload(self._sig, cres) + else: + self._cache_hits += 1 + + self._library = cres.library + self._wrapper_name = cres.fndesc.llvm_cfunc_wrapper_name + self._wrapper_address = self._library.get_pointer_to_function( + self._wrapper_name) + + def _compile_uncached(self): + sig = self._sig + + # Compile native function as well as cfunc wrapper + return self._compiler.compile(sig.args, sig.return_type) + + @property + def native_name(self): + """ + The process-wide symbol the C callback is exposed as. + """ + # Note from our point of view, the C callback is the wrapper around + # the native function. + return self._wrapper_name + + @property + def address(self): + """ + The address of the C callback. + """ + return self._wrapper_address + + @cached_property + def cffi(self): + """ + A cffi function pointer representing the C callback. + """ + import cffi + ffi = cffi.FFI() + # cffi compares types by name, so using precise types would risk + # spurious mismatches (such as "int32_t" vs. "int"). + return ffi.cast("void *", self.address) + + @cached_property + def ctypes(self): + """ + A ctypes function object representing the C callback. + """ + ctypes_args = [to_ctypes(ty) for ty in self._sig.args] + ctypes_restype = to_ctypes(self._sig.return_type) + functype = ctypes.CFUNCTYPE(ctypes_restype, *ctypes_args) + return functype(self.address) + + def inspect_llvm(self): + """ + Return the LLVM IR of the C callback definition. + """ + return self._library.get_llvm_str() + + @property + def cache_hits(self): + return self._cache_hits + + def __repr__(self): + return "" % (self.__qualname__,) + + def __call__(self, *args, **kwargs): + return self._pyfunc(*args, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cgutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cgutils.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fc7ef203a8a57d4690db2cc61c80b4e5168530 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cgutils.py @@ -0,0 +1,1241 @@ +""" +Generic helpers for LLVM code generation. +""" + + +import collections +from contextlib import contextmanager, ExitStack +import functools + +from llvmlite import ir + +from numba.core import utils, types, config, debuginfo +import numba.core.datamodel + + +bool_t = ir.IntType(1) +int8_t = ir.IntType(8) +int32_t = ir.IntType(32) +intp_t = ir.IntType(utils.MACHINE_BITS) +voidptr_t = int8_t.as_pointer() + +true_bit = bool_t(1) +false_bit = bool_t(0) +true_byte = int8_t(1) +false_byte = int8_t(0) + + +def as_bool_bit(builder, value): + return builder.icmp_unsigned('!=', value, value.type(0)) + + +def make_anonymous_struct(builder, values, struct_type=None): + """ + Create an anonymous struct containing the given LLVM *values*. + """ + if struct_type is None: + struct_type = ir.LiteralStructType([v.type for v in values]) + struct_val = struct_type(ir.Undefined) + for i, v in enumerate(values): + struct_val = builder.insert_value(struct_val, v, i) + return struct_val + + +def make_bytearray(buf): + """ + Make a byte array constant from *buf*. + """ + b = bytearray(buf) + n = len(b) + return ir.Constant(ir.ArrayType(ir.IntType(8), n), b) + + +_struct_proxy_cache = {} + + +def create_struct_proxy(fe_type, kind='value'): + """ + Returns a specialized StructProxy subclass for the given fe_type. + """ + cache_key = (fe_type, kind) + res = _struct_proxy_cache.get(cache_key) + if res is None: + base = {'value': ValueStructProxy, + 'data': DataStructProxy, + }[kind] + clsname = base.__name__ + '_' + str(fe_type) + bases = (base,) + clsmembers = dict(_fe_type=fe_type) + res = type(clsname, bases, clsmembers) + + _struct_proxy_cache[cache_key] = res + return res + + +def copy_struct(dst, src, repl=None): + """ + Copy structure from *src* to *dst* with replacement from *repl*. + """ + if repl is None: + repl = {} + repl = repl.copy() + # copy data from src or use those in repl + for k in src._datamodel._fields: + v = repl.pop(k, getattr(src, k)) + setattr(dst, k, v) + # use remaining key-values in repl + for k, v in repl.items(): + setattr(dst, k, v) + return dst + + +class _StructProxy(object): + """ + Creates a `Structure` like interface that is constructed with information + from DataModel instance. FE type must have a data model that is a + subclass of StructModel. + """ + # The following class members must be overridden by subclass + _fe_type = None + + def __init__(self, context, builder, value=None, ref=None): + self._context = context + self._datamodel = self._context.data_model_manager[self._fe_type] + if not isinstance(self._datamodel, numba.core.datamodel.StructModel): + raise TypeError( + "Not a structure model: {0}".format(self._datamodel)) + self._builder = builder + + self._be_type = self._get_be_type(self._datamodel) + assert not is_pointer(self._be_type) + + outer_ref, ref = self._make_refs(ref) + if ref.type.pointee != self._be_type: + raise AssertionError("bad ref type: expected %s, got %s" + % (self._be_type.as_pointer(), ref.type)) + + if value is not None: + if value.type != outer_ref.type.pointee: + raise AssertionError("bad value type: expected %s, got %s" + % (outer_ref.type.pointee, value.type)) + self._builder.store(value, outer_ref) + + self._value = ref + self._outer_ref = outer_ref + + def _make_refs(self, ref): + """ + Return an (outer ref, value ref) pair. By default, these are + the same pointers, but a derived class may override this. + """ + if ref is None: + ref = alloca_once(self._builder, self._be_type, zfill=True) + return ref, ref + + def _get_be_type(self, datamodel): + raise NotImplementedError + + def _cast_member_to_value(self, index, val): + raise NotImplementedError + + def _cast_member_from_value(self, index, val): + raise NotImplementedError + + def _get_ptr_by_index(self, index): + return gep_inbounds(self._builder, self._value, 0, index) + + def _get_ptr_by_name(self, attrname): + index = self._datamodel.get_field_position(attrname) + return self._get_ptr_by_index(index) + + def __getattr__(self, field): + """ + Load the LLVM value of the named *field*. + """ + if not field.startswith('_'): + return self[self._datamodel.get_field_position(field)] + else: + raise AttributeError(field) + + def __setattr__(self, field, value): + """ + Store the LLVM *value* into the named *field*. + """ + if field.startswith('_'): + return super(_StructProxy, self).__setattr__(field, value) + self[self._datamodel.get_field_position(field)] = value + + def __getitem__(self, index): + """ + Load the LLVM value of the field at *index*. + """ + member_val = self._builder.load(self._get_ptr_by_index(index)) + return self._cast_member_to_value(index, member_val) + + def __setitem__(self, index, value): + """ + Store the LLVM *value* into the field at *index*. + """ + ptr = self._get_ptr_by_index(index) + value = self._cast_member_from_value(index, value) + if value.type != ptr.type.pointee: + if (is_pointer(value.type) and is_pointer(ptr.type.pointee) + and value.type.pointee == ptr.type.pointee.pointee): + # Differ by address-space only + # Auto coerce it + value = self._context.addrspacecast(self._builder, + value, + ptr.type.pointee.addrspace) + else: + raise TypeError("Invalid store of {value.type} to " + "{ptr.type.pointee} in " + "{self._datamodel} " + "(trying to write member #{index})" + .format(value=value, ptr=ptr, self=self, + index=index)) + self._builder.store(value, ptr) + + def __len__(self): + """ + Return the number of fields. + """ + return self._datamodel.field_count + + def _getpointer(self): + """ + Return the LLVM pointer to the underlying structure. + """ + return self._outer_ref + + def _getvalue(self): + """ + Load and return the value of the underlying LLVM structure. + """ + return self._builder.load(self._outer_ref) + + def _setvalue(self, value): + """ + Store the value in this structure. + """ + assert not is_pointer(value.type) + assert value.type == self._be_type, (value.type, self._be_type) + self._builder.store(value, self._value) + + +class ValueStructProxy(_StructProxy): + """ + Create a StructProxy suitable for accessing regular values + (e.g. LLVM values or alloca slots). + """ + def _get_be_type(self, datamodel): + return datamodel.get_value_type() + + def _cast_member_to_value(self, index, val): + return val + + def _cast_member_from_value(self, index, val): + return val + + +class DataStructProxy(_StructProxy): + """ + Create a StructProxy suitable for accessing data persisted in memory. + """ + def _get_be_type(self, datamodel): + return datamodel.get_data_type() + + def _cast_member_to_value(self, index, val): + model = self._datamodel.get_model(index) + return model.from_data(self._builder, val) + + def _cast_member_from_value(self, index, val): + model = self._datamodel.get_model(index) + return model.as_data(self._builder, val) + + +class Structure(object): + """ + A high-level object wrapping a alloca'ed LLVM structure, including + named fields and attribute access. + """ + + # XXX Should this warrant several separate constructors? + def __init__(self, context, builder, value=None, ref=None, cast_ref=False): + self._type = context.get_struct_type(self) + self._context = context + self._builder = builder + if ref is None: + self._value = alloca_once(builder, self._type, zfill=True) + if value is not None: + assert not is_pointer(value.type) + assert value.type == self._type, (value.type, self._type) + builder.store(value, self._value) + else: + assert value is None + assert is_pointer(ref.type) + if self._type != ref.type.pointee: + if cast_ref: + ref = builder.bitcast(ref, self._type.as_pointer()) + else: + raise TypeError( + "mismatching pointer type: got %s, expected %s" + % (ref.type.pointee, self._type)) + self._value = ref + + self._namemap = {} + self._fdmap = [] + self._typemap = [] + base = int32_t(0) + for i, (k, tp) in enumerate(self._fields): + self._namemap[k] = i + self._fdmap.append((base, int32_t(i))) + self._typemap.append(tp) + + def _get_ptr_by_index(self, index): + ptr = self._builder.gep(self._value, self._fdmap[index], inbounds=True) + return ptr + + def _get_ptr_by_name(self, attrname): + return self._get_ptr_by_index(self._namemap[attrname]) + + def __getattr__(self, field): + """ + Load the LLVM value of the named *field*. + """ + if not field.startswith('_'): + return self[self._namemap[field]] + else: + raise AttributeError(field) + + def __setattr__(self, field, value): + """ + Store the LLVM *value* into the named *field*. + """ + if field.startswith('_'): + return super(Structure, self).__setattr__(field, value) + self[self._namemap[field]] = value + + def __getitem__(self, index): + """ + Load the LLVM value of the field at *index*. + """ + + return self._builder.load(self._get_ptr_by_index(index)) + + def __setitem__(self, index, value): + """ + Store the LLVM *value* into the field at *index*. + """ + ptr = self._get_ptr_by_index(index) + if ptr.type.pointee != value.type: + fmt = "Type mismatch: __setitem__(%d, ...) expected %r but got %r" + raise AssertionError(fmt % (index, + str(ptr.type.pointee), + str(value.type))) + self._builder.store(value, ptr) + + def __len__(self): + """ + Return the number of fields. + """ + return len(self._namemap) + + def _getpointer(self): + """ + Return the LLVM pointer to the underlying structure. + """ + return self._value + + def _getvalue(self): + """ + Load and return the value of the underlying LLVM structure. + """ + return self._builder.load(self._value) + + def _setvalue(self, value): + """Store the value in this structure""" + assert not is_pointer(value.type) + assert value.type == self._type, (value.type, self._type) + self._builder.store(value, self._value) + + # __iter__ is derived by Python from __len__ and __getitem__ + + +def alloca_once(builder, ty, size=None, name='', zfill=False): + """Allocate stack memory at the entry block of the current function + pointed by ``builder`` with llvm type ``ty``. The optional ``size`` arg + set the number of element to allocate. The default is 1. The optional + ``name`` arg set the symbol name inside the llvm IR for debugging. + If ``zfill`` is set, fill the memory with zeros at the current + use-site location. Note that the memory is always zero-filled after the + ``alloca`` at init-site (the entry block). + """ + if isinstance(size, int): + size = ir.Constant(intp_t, size) + # suspend debug metadata emission else it links up python source lines with + # alloca in the entry block as well as their actual location and it makes + # the debug info "jump about". + with debuginfo.suspend_emission(builder): + with builder.goto_entry_block(): + ptr = builder.alloca(ty, size=size, name=name) + # Always zero-fill at init-site. This is safe. + builder.store(ty(None), ptr) + # Also zero-fill at the use-site + if zfill: + builder.store(ptr.type.pointee(None), ptr) + return ptr + + +def sizeof(builder, ptr_type): + """Compute sizeof using GEP + """ + null = ptr_type(None) + offset = null.gep([int32_t(1)]) + return builder.ptrtoint(offset, intp_t) + + +def alloca_once_value(builder, value, name='', zfill=False): + """ + Like alloca_once(), but passing a *value* instead of a type. The + type is inferred and the allocated slot is also initialized with the + given value. + """ + storage = alloca_once(builder, value.type, zfill=zfill) + builder.store(value, storage) + return storage + + +def insert_pure_function(module, fnty, name): + """ + Insert a pure function (in the functional programming sense) in the + given module. + """ + fn = get_or_insert_function(module, fnty, name) + fn.attributes.add("readonly") + fn.attributes.add("nounwind") + return fn + + +def get_or_insert_function(module, fnty, name): + """ + Get the function named *name* with type *fnty* from *module*, or insert it + if it doesn't exist. + """ + fn = module.globals.get(name, None) + if fn is None: + fn = ir.Function(module, fnty, name) + return fn + + +def get_or_insert_named_metadata(module, name): + try: + return module.get_named_metadata(name) + except KeyError: + return module.add_named_metadata(name) + + +def add_global_variable(module, ty, name, addrspace=0): + unique_name = module.get_unique_name(name) + return ir.GlobalVariable(module, ty, unique_name, addrspace) + + +def terminate(builder, bbend): + bb = builder.basic_block + if bb.terminator is None: + builder.branch(bbend) + + +def get_null_value(ltype): + return ltype(None) + + +def is_null(builder, val): + null = get_null_value(val.type) + return builder.icmp_unsigned('==', null, val) + + +def is_not_null(builder, val): + null = get_null_value(val.type) + return builder.icmp_unsigned('!=', null, val) + + +def if_unlikely(builder, pred): + return builder.if_then(pred, likely=False) + + +def if_likely(builder, pred): + return builder.if_then(pred, likely=True) + + +def ifnot(builder, pred): + return builder.if_then(builder.not_(pred)) + + +def increment_index(builder, val): + """ + Increment an index *val*. + """ + one = val.type(1) + # We pass the "nsw" flag in the hope that LLVM understands the index + # never changes sign. Unfortunately this doesn't always work + # (e.g. ndindex()). + return builder.add(val, one, flags=['nsw']) + + +Loop = collections.namedtuple('Loop', ('index', 'do_break')) + + +@contextmanager +def for_range(builder, count, start=None, intp=None): + """ + Generate LLVM IR for a for-loop in [start, count). + *start* is equal to 0 by default. + + Yields a Loop namedtuple with the following members: + - `index` is the loop index's value + - `do_break` is a no-argument callable to break out of the loop + """ + if intp is None: + intp = count.type + if start is None: + start = intp(0) + stop = count + + bbcond = builder.append_basic_block("for.cond") + bbbody = builder.append_basic_block("for.body") + bbend = builder.append_basic_block("for.end") + + def do_break(): + builder.branch(bbend) + + bbstart = builder.basic_block + builder.branch(bbcond) + + with builder.goto_block(bbcond): + index = builder.phi(intp, name="loop.index") + pred = builder.icmp_signed('<', index, stop) + builder.cbranch(pred, bbbody, bbend) + + with builder.goto_block(bbbody): + yield Loop(index, do_break) + # Update bbbody as a new basic block may have been activated + bbbody = builder.basic_block + incr = increment_index(builder, index) + terminate(builder, bbcond) + + index.add_incoming(start, bbstart) + index.add_incoming(incr, bbbody) + + builder.position_at_end(bbend) + + +@contextmanager +def for_range_slice(builder, start, stop, step, intp=None, inc=True): + """ + Generate LLVM IR for a for-loop based on a slice. Yields a + (index, count) tuple where `index` is the slice index's value + inside the loop, and `count` the iteration count. + + Parameters + ------------- + builder : object + IRBuilder object + start : int + The beginning value of the slice + stop : int + The end value of the slice + step : int + The step value of the slice + intp : + The data type + inc : boolean, optional + Signals whether the step is positive (True) or negative (False). + + Returns + ----------- + None + """ + if intp is None: + intp = start.type + + bbcond = builder.append_basic_block("for.cond") + bbbody = builder.append_basic_block("for.body") + bbend = builder.append_basic_block("for.end") + bbstart = builder.basic_block + builder.branch(bbcond) + + with builder.goto_block(bbcond): + index = builder.phi(intp, name="loop.index") + count = builder.phi(intp, name="loop.count") + if (inc): + pred = builder.icmp_signed('<', index, stop) + else: + pred = builder.icmp_signed('>', index, stop) + builder.cbranch(pred, bbbody, bbend) + + with builder.goto_block(bbbody): + yield index, count + bbbody = builder.basic_block + incr = builder.add(index, step) + next_count = increment_index(builder, count) + terminate(builder, bbcond) + + index.add_incoming(start, bbstart) + index.add_incoming(incr, bbbody) + count.add_incoming(ir.Constant(intp, 0), bbstart) + count.add_incoming(next_count, bbbody) + builder.position_at_end(bbend) + + +@contextmanager +def for_range_slice_generic(builder, start, stop, step): + """ + A helper wrapper for for_range_slice(). This is a context manager which + yields two for_range_slice()-alike context managers, the first for + the positive step case, the second for the negative step case. + + Use: + with for_range_slice_generic(...) as (pos_range, neg_range): + with pos_range as (idx, count): + ... + with neg_range as (idx, count): + ... + """ + intp = start.type + is_pos_step = builder.icmp_signed('>=', step, ir.Constant(intp, 0)) + + pos_for_range = for_range_slice(builder, start, stop, step, intp, inc=True) + neg_for_range = for_range_slice(builder, start, stop, step, intp, inc=False) + + @contextmanager + def cm_cond(cond, inner_cm): + with cond: + with inner_cm as value: + yield value + + with builder.if_else(is_pos_step, likely=True) as (then, otherwise): + yield cm_cond(then, pos_for_range), cm_cond(otherwise, neg_for_range) + + +@contextmanager +def loop_nest(builder, shape, intp, order='C'): + """ + Generate a loop nest walking a N-dimensional array. + Yields a tuple of N indices for use in the inner loop body, + iterating over the *shape* space. + + If *order* is 'C' (the default), indices are incremented inside-out + (i.e. (0,0), (0,1), (0,2), (1,0) etc.). + If *order* is 'F', they are incremented outside-in + (i.e. (0,0), (1,0), (2,0), (0,1) etc.). + This has performance implications when walking an array as it impacts + the spatial locality of memory accesses. + """ + assert order in 'CF' + if not shape: + # 0-d array + yield () + else: + if order == 'F': + _swap = lambda x: x[::-1] + else: + _swap = lambda x: x + with _loop_nest(builder, _swap(shape), intp) as indices: + assert len(indices) == len(shape) + yield _swap(indices) + + +@contextmanager +def _loop_nest(builder, shape, intp): + with for_range(builder, shape[0], intp=intp) as loop: + if len(shape) > 1: + with _loop_nest(builder, shape[1:], intp) as indices: + yield (loop.index,) + indices + else: + yield (loop.index,) + + +def pack_array(builder, values, ty=None): + """ + Pack a sequence of values in a LLVM array. *ty* should be given + if the array may be empty, in which case the type can't be inferred + from the values. + """ + n = len(values) + if ty is None: + ty = values[0].type + ary = ir.ArrayType(ty, n)(ir.Undefined) + for i, v in enumerate(values): + ary = builder.insert_value(ary, v, i) + return ary + + +def pack_struct(builder, values): + """ + Pack a sequence of values into a LLVM struct. + """ + structty = ir.LiteralStructType([v.type for v in values]) + st = structty(ir.Undefined) + for i, v in enumerate(values): + st = builder.insert_value(st, v, i) + return st + + +def unpack_tuple(builder, tup, count=None): + """ + Unpack an array or structure of values, return a Python tuple. + """ + if count is None: + # Assuming *tup* is an aggregate + count = len(tup.type.elements) + vals = [builder.extract_value(tup, i) + for i in range(count)] + return vals + + +def get_item_pointer(context, builder, aryty, ary, inds, wraparound=False, + boundscheck=False): + # Set boundscheck=True for any pointer access that should be + # boundschecked. do_boundscheck() will handle enabling or disabling the + # actual boundschecking based on the user config. + shapes = unpack_tuple(builder, ary.shape, count=aryty.ndim) + strides = unpack_tuple(builder, ary.strides, count=aryty.ndim) + return get_item_pointer2(context, builder, data=ary.data, shape=shapes, + strides=strides, layout=aryty.layout, inds=inds, + wraparound=wraparound, boundscheck=boundscheck) + + +def do_boundscheck(context, builder, ind, dimlen, axis=None): + def _dbg(): + # Remove this when we figure out how to include this information + # in the error message. + if axis is not None: + if isinstance(axis, int): + printf(builder, "debug: IndexError: index %d is out of bounds " + "for axis {} with size %d\n".format(axis), ind, dimlen) + else: + printf(builder, "debug: IndexError: index %d is out of bounds " + "for axis %d with size %d\n", ind, axis, + dimlen) + else: + printf(builder, + "debug: IndexError: index %d is out of bounds for size %d\n", + ind, dimlen) + + msg = "index is out of bounds" + out_of_bounds_upper = builder.icmp_signed('>=', ind, dimlen) + with if_unlikely(builder, out_of_bounds_upper): + if config.FULL_TRACEBACKS: + _dbg() + context.call_conv.return_user_exc(builder, IndexError, (msg,)) + out_of_bounds_lower = builder.icmp_signed('<', ind, ind.type(0)) + with if_unlikely(builder, out_of_bounds_lower): + if config.FULL_TRACEBACKS: + _dbg() + context.call_conv.return_user_exc(builder, IndexError, (msg,)) + + +def get_item_pointer2(context, builder, data, shape, strides, layout, inds, + wraparound=False, boundscheck=False): + # Set boundscheck=True for any pointer access that should be + # boundschecked. do_boundscheck() will handle enabling or disabling the + # actual boundschecking based on the user config. + if wraparound: + # Wraparound + indices = [] + for ind, dimlen in zip(inds, shape): + negative = builder.icmp_signed('<', ind, ind.type(0)) + wrapped = builder.add(dimlen, ind) + selected = builder.select(negative, wrapped, ind) + indices.append(selected) + else: + indices = inds + if boundscheck: + for axis, (ind, dimlen) in enumerate(zip(indices, shape)): + do_boundscheck(context, builder, ind, dimlen, axis) + + if not indices: + # Indexing with empty tuple + return builder.gep(data, [int32_t(0)]) + intp = indices[0].type + # Indexing code + if layout in 'CF': + steps = [] + # Compute steps for each dimension + if layout == 'C': + # C contiguous + for i in range(len(shape)): + last = intp(1) + for j in shape[i + 1:]: + last = builder.mul(last, j) + steps.append(last) + elif layout == 'F': + # F contiguous + for i in range(len(shape)): + last = intp(1) + for j in shape[:i]: + last = builder.mul(last, j) + steps.append(last) + else: + raise Exception("unreachable") + + # Compute index + loc = intp(0) + for i, s in zip(indices, steps): + tmp = builder.mul(i, s) + loc = builder.add(loc, tmp) + ptr = builder.gep(data, [loc]) + return ptr + else: + # Any layout + dimoffs = [builder.mul(s, i) for s, i in zip(strides, indices)] + offset = functools.reduce(builder.add, dimoffs) + return pointer_add(builder, data, offset) + + +def _scalar_pred_against_zero(builder, value, fpred, icond): + nullval = value.type(0) + if isinstance(value.type, (ir.FloatType, ir.DoubleType)): + isnull = fpred(value, nullval) + elif isinstance(value.type, ir.IntType): + isnull = builder.icmp_signed(icond, value, nullval) + else: + raise TypeError("unexpected value type %s" % (value.type,)) + return isnull + + +def is_scalar_zero(builder, value): + """ + Return a predicate representing whether *value* is equal to zero. + """ + return _scalar_pred_against_zero( + builder, value, functools.partial(builder.fcmp_ordered, '=='), '==') + + +def is_not_scalar_zero(builder, value): + """ + Return a predicate representing whether a *value* is not equal to zero. + (not exactly "not is_scalar_zero" because of nans) + """ + return _scalar_pred_against_zero( + builder, value, functools.partial(builder.fcmp_unordered, '!='), '!=') + + +def is_scalar_zero_or_nan(builder, value): + """ + Return a predicate representing whether *value* is equal to either zero + or NaN. + """ + return _scalar_pred_against_zero( + builder, value, functools.partial(builder.fcmp_unordered, '=='), '==') + + +is_true = is_not_scalar_zero +is_false = is_scalar_zero + + +def is_scalar_neg(builder, value): + """ + Is *value* negative? Assumes *value* is signed. + """ + return _scalar_pred_against_zero( + builder, value, functools.partial(builder.fcmp_ordered, '<'), '<') + + +@contextmanager +def early_exit_if(builder, stack: ExitStack, cond): + """ + The Python code:: + + with contextlib.ExitStack() as stack: + with early_exit_if(builder, stack, cond): + cleanup() + body() + + emits the code:: + + if (cond) { + + } + else { + + } + + This can be useful for generating code with lots of early exits, without + having to increase the indentation each time. + """ + then, otherwise = stack.enter_context(builder.if_else(cond, likely=False)) + with then: + yield + stack.enter_context(otherwise) + + +def early_exit_if_null(builder, stack, obj): + """ + A convenience wrapper for :func:`early_exit_if`, for the common case where + the CPython API indicates an error by returning ``NULL``. + """ + return early_exit_if(builder, stack, is_null(builder, obj)) + + +def guard_null(context, builder, value, exc_tuple): + """ + Guard against *value* being null or zero. + *exc_tuple* should be a (exception type, arguments...) tuple. + """ + with builder.if_then(is_scalar_zero(builder, value), likely=False): + exc = exc_tuple[0] + exc_args = exc_tuple[1:] or None + context.call_conv.return_user_exc(builder, exc, exc_args) + + +def guard_memory_error(context, builder, pointer, msg=None): + """ + Guard against *pointer* being NULL (and raise a MemoryError). + """ + assert isinstance(pointer.type, ir.PointerType), pointer.type + exc_args = (msg,) if msg else () + with builder.if_then(is_null(builder, pointer), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, exc_args) + + +@contextmanager +def if_zero(builder, value, likely=False): + """ + Execute the given block if the scalar value is zero. + """ + with builder.if_then(is_scalar_zero(builder, value), likely=likely): + yield + + +guard_zero = guard_null + + +def is_pointer(ltyp): + """ + Whether the LLVM type *typ* is a struct type. + """ + return isinstance(ltyp, ir.PointerType) + + +def get_record_member(builder, record, offset, typ): + pval = gep_inbounds(builder, record, 0, offset) + assert not is_pointer(pval.type.pointee) + return builder.bitcast(pval, typ.as_pointer()) + + +def is_neg_int(builder, val): + return builder.icmp_signed('<', val, val.type(0)) + + +def gep_inbounds(builder, ptr, *inds, **kws): + """ + Same as *gep*, but add the `inbounds` keyword. + """ + return gep(builder, ptr, *inds, inbounds=True, **kws) + + +def gep(builder, ptr, *inds, **kws): + """ + Emit a getelementptr instruction for the given pointer and indices. + The indices can be LLVM values or Python int constants. + """ + name = kws.pop('name', '') + inbounds = kws.pop('inbounds', False) + assert not kws + idx = [] + for i in inds: + if isinstance(i, int): + # NOTE: llvm only accepts int32 inside structs, not int64 + ind = int32_t(i) + else: + ind = i + idx.append(ind) + return builder.gep(ptr, idx, name=name, inbounds=inbounds) + + +def pointer_add(builder, ptr, offset, return_type=None): + """ + Add an integral *offset* to pointer *ptr*, and return a pointer + of *return_type* (or, if omitted, the same type as *ptr*). + + Note the computation is done in bytes, and ignores the width of + the pointed item type. + """ + intptr = builder.ptrtoint(ptr, intp_t) + if isinstance(offset, int): + offset = intp_t(offset) + intptr = builder.add(intptr, offset) + return builder.inttoptr(intptr, return_type or ptr.type) + + +def memset(builder, ptr, size, value): + """ + Fill *size* bytes starting from *ptr* with *value*. + """ + fn = builder.module.declare_intrinsic('llvm.memset', (voidptr_t, size.type)) + ptr = builder.bitcast(ptr, voidptr_t) + if isinstance(value, int): + value = int8_t(value) + builder.call(fn, [ptr, value, size, bool_t(0)]) + + +def memset_padding(builder, ptr): + """ + Fill padding bytes of the pointee with zeros. + """ + # Load existing value + val = builder.load(ptr) + # Fill pointee with zeros + memset(builder, ptr, sizeof(builder, ptr.type), 0) + # Store value back + builder.store(val, ptr) + + +def global_constant(builder_or_module, name, value, linkage='internal'): + """ + Get or create a (LLVM module-)global constant with *name* or *value*. + """ + if isinstance(builder_or_module, ir.Module): + module = builder_or_module + else: + module = builder_or_module.module + data = add_global_variable(module, value.type, name) + data.linkage = linkage + data.global_constant = True + data.initializer = value + return data + + +def divmod_by_constant(builder, val, divisor): + """ + Compute the (quotient, remainder) of *val* divided by the constant + positive *divisor*. The semantics reflects those of Python integer + floor division, rather than C's / LLVM's signed division and modulo. + The difference lies with a negative *val*. + """ + assert divisor > 0 + divisor = val.type(divisor) + one = val.type(1) + + quot = alloca_once(builder, val.type) + + with builder.if_else(is_neg_int(builder, val)) as (if_neg, if_pos): + with if_pos: + # quot = val / divisor + quot_val = builder.sdiv(val, divisor) + builder.store(quot_val, quot) + with if_neg: + # quot = -1 + (val + 1) / divisor + val_plus_one = builder.add(val, one) + quot_val = builder.sdiv(val_plus_one, divisor) + builder.store(builder.sub(quot_val, one), quot) + + # rem = val - quot * divisor + # (should be slightly faster than a separate modulo operation) + quot_val = builder.load(quot) + rem_val = builder.sub(val, builder.mul(quot_val, divisor)) + return quot_val, rem_val + + +def cbranch_or_continue(builder, cond, bbtrue): + """ + Branch conditionally or continue. + + Note: a new block is created and builder is moved to the end of the new + block. + """ + bbcont = builder.append_basic_block('.continue') + builder.cbranch(cond, bbtrue, bbcont) + builder.position_at_end(bbcont) + return bbcont + + +def memcpy(builder, dst, src, count): + """ + Emit a memcpy to the builder. + + Copies each element of dst to src. Unlike the C equivalent, each element + can be any LLVM type. + + Assumes + ------- + * dst.type == src.type + * count is positive + """ + # Note this does seem to be optimized as a raw memcpy() by LLVM + # whenever possible... + assert dst.type == src.type + with for_range(builder, count, intp=count.type) as loop: + out_ptr = builder.gep(dst, [loop.index]) + in_ptr = builder.gep(src, [loop.index]) + builder.store(builder.load(in_ptr), out_ptr) + + +def _raw_memcpy(builder, func_name, dst, src, count, itemsize, align): + size_t = count.type + if isinstance(itemsize, int): + itemsize = ir.Constant(size_t, itemsize) + + memcpy = builder.module.declare_intrinsic(func_name, + [voidptr_t, voidptr_t, size_t]) + is_volatile = false_bit + builder.call(memcpy, [builder.bitcast(dst, voidptr_t), + builder.bitcast(src, voidptr_t), + builder.mul(count, itemsize), + is_volatile]) + + +def raw_memcpy(builder, dst, src, count, itemsize, align=1): + """ + Emit a raw memcpy() call for `count` items of size `itemsize` + from `src` to `dest`. + """ + return _raw_memcpy(builder, 'llvm.memcpy', dst, src, count, itemsize, align) + + +def raw_memmove(builder, dst, src, count, itemsize, align=1): + """ + Emit a raw memmove() call for `count` items of size `itemsize` + from `src` to `dest`. + """ + return _raw_memcpy(builder, 'llvm.memmove', dst, src, count, + itemsize, align) + + +def muladd_with_overflow(builder, a, b, c): + """ + Compute (a * b + c) and return a (result, overflow bit) pair. + The operands must be signed integers. + """ + p = builder.smul_with_overflow(a, b) + prod = builder.extract_value(p, 0) + prod_ovf = builder.extract_value(p, 1) + s = builder.sadd_with_overflow(prod, c) + res = builder.extract_value(s, 0) + ovf = builder.or_(prod_ovf, builder.extract_value(s, 1)) + return res, ovf + + +def printf(builder, format, *args): + """ + Calls printf(). + Argument `format` is expected to be a Python string. + Values to be printed are listed in `args`. + + Note: There is no checking to ensure there is correct number of values + in `args` and there type matches the declaration in the format string. + """ + assert isinstance(format, str) + mod = builder.module + # Make global constant for format string + cstring = voidptr_t + fmt_bytes = make_bytearray((format + '\00').encode('ascii')) + global_fmt = global_constant(mod, "printf_format", fmt_bytes) + fnty = ir.FunctionType(int32_t, [cstring], var_arg=True) + # Insert printf() + try: + fn = mod.get_global('printf') + except KeyError: + fn = ir.Function(mod, fnty, name="printf") + # Call + ptr_fmt = builder.bitcast(global_fmt, cstring) + return builder.call(fn, [ptr_fmt] + list(args)) + + +def snprintf(builder, buffer, bufsz, format, *args): + """Calls libc snprintf(buffer, bufsz, format, ...args) + """ + assert isinstance(format, str) + mod = builder.module + # Make global constant for format string + cstring = voidptr_t + fmt_bytes = make_bytearray((format + '\00').encode('ascii')) + global_fmt = global_constant(mod, "snprintf_format", fmt_bytes) + fnty = ir.FunctionType( + int32_t, [cstring, intp_t, cstring], var_arg=True, + ) + # Actual symbol name of snprintf is different on win32. + symbol = 'snprintf' + if config.IS_WIN32: + symbol = '_' + symbol + # Insert snprintf() + try: + fn = mod.get_global(symbol) + except KeyError: + fn = ir.Function(mod, fnty, name=symbol) + # Call + ptr_fmt = builder.bitcast(global_fmt, cstring) + return builder.call(fn, [buffer, bufsz, ptr_fmt] + list(args)) + + +def snprintf_stackbuffer(builder, bufsz, format, *args): + """Similar to `snprintf()` but the buffer is stack allocated to size + *bufsz*. + + Returns the buffer pointer as i8*. + """ + assert isinstance(bufsz, int) + spacety = ir.ArrayType(ir.IntType(8), bufsz) + space = alloca_once(builder, spacety, zfill=True) + buffer = builder.bitcast(space, voidptr_t) + snprintf(builder, buffer, intp_t(bufsz), format, *args) + return buffer + + +def normalize_ir_text(text): + """ + Normalize the given string to latin1 compatible encoding that is + suitable for use in LLVM IR. + """ + # Just re-encoding to latin1 is enough + return text.encode('utf8').decode('latin1') + + +def hexdump(builder, ptr, nbytes): + """Debug print the memory region in *ptr* to *ptr + nbytes* + as hex. + """ + bytes_per_line = 16 + nbytes = builder.zext(nbytes, intp_t) + printf(builder, "hexdump p=%p n=%zu", + ptr, nbytes) + byte_t = ir.IntType(8) + ptr = builder.bitcast(ptr, byte_t.as_pointer()) + # Loop to print the bytes in *ptr* as hex + with for_range(builder, nbytes) as idx: + div_by = builder.urem(idx.index, intp_t(bytes_per_line)) + do_new_line = builder.icmp_unsigned("==", div_by, intp_t(0)) + with builder.if_then(do_new_line): + printf(builder, "\n") + + offset = builder.gep(ptr, [idx.index]) + val = builder.load(offset) + printf(builder, " %02x", val) + printf(builder, "\n") + + +def is_nonelike(ty): + """ returns if 'ty' is none """ + return ( + ty is None or + isinstance(ty, types.NoneType) or + isinstance(ty, types.Omitted) + ) + + +def is_empty_tuple(ty): + """ returns if 'ty' is an empty tuple """ + return ( + isinstance(ty, types.Tuple) and + len(ty.types) == 0 + ) + + +def create_constant_array(ty, val): + """ + Create an LLVM-constant of a fixed-length array from Python values. + + The type provided is the type of the elements. + """ + return ir.Constant(ir.ArrayType(ty, len(val)), val) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/codegen.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..39f32fe7d33b08654b3e6a5c0f372f261b462f73 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/codegen.py @@ -0,0 +1,1445 @@ +import warnings +import functools +import locale +import weakref +import ctypes +import html +import textwrap + +import llvmlite.binding as ll +import llvmlite.ir as llvmir + +from abc import abstractmethod, ABCMeta +from numba.core import utils, config, cgutils +from numba.core.llvm_bindings import create_pass_builder +from numba.core.runtime.nrtopt import remove_redundant_nrt_refct +from numba.core.runtime import rtsys +from numba.core.compiler_lock import require_global_compiler_lock +from numba.core.errors import NumbaInvalidConfigWarning +from numba.misc.inspection import disassemble_elf_to_cfg +from numba.misc.llvm_pass_timings import PassTimingsCollection + + +_x86arch = frozenset(['x86', 'i386', 'i486', 'i586', 'i686', 'i786', + 'i886', 'i986']) + + +def _is_x86(triple): + arch = triple.split('-')[0] + return arch in _x86arch + + +def _parse_refprune_flags(): + """Parse refprune flags from the `config`. + + Invalid values are ignored an warn via a `NumbaInvalidConfigWarning` + category. + + Returns + ------- + flags : llvmlite.binding.RefPruneSubpasses + """ + flags = config.LLVM_REFPRUNE_FLAGS.split(',') + if not flags: + return 0 + val = 0 + for item in flags: + item = item.strip() + try: + val |= getattr(ll.RefPruneSubpasses, item.upper()) + except AttributeError: + warnings.warn(f"invalid refprune flags {item!r}", + NumbaInvalidConfigWarning) + return val + + +def dump(header, body, lang): + if config.HIGHLIGHT_DUMPS: + try: + import pygments + except ImportError: + msg = "Please install pygments to see highlighted dumps" + raise ValueError(msg) + else: + from pygments import highlight + from pygments.lexers import GasLexer as gas_lexer + from pygments.lexers import LlvmLexer as llvm_lexer + from pygments.formatters import Terminal256Formatter + from numba.misc.dump_style import by_colorscheme + + lexer_map = {'llvm': llvm_lexer, 'asm': gas_lexer} + lexer = lexer_map[lang] + def printer(arg): + print(highlight(arg, lexer(), + Terminal256Formatter(style=by_colorscheme()))) + else: + printer = print + print('=' * 80) + print(header.center(80, '-')) + printer(body) + print('=' * 80) + + +class _CFG(object): + """ + Wraps the CFG graph for different display method. + + Instance of the class can be stringified (``__repr__`` is defined) to get + the graph in DOT format. The ``.display()`` method plots the graph in + PDF. If in IPython notebook, the returned image can be inlined. + """ + def __init__(self, cres, name, py_func, **kwargs): + self.cres = cres + self.name = name + self.py_func = py_func + fn = cres.get_function(name) + self.dot = ll.get_function_cfg(fn) + self.kwargs = kwargs + + def pretty_printer(self, filename=None, view=None, render_format=None, + highlight=True, + interleave=False, strip_ir=False, show_key=True, + fontsize=10): + """ + "Pretty" prints the DOT graph of the CFG. + For explanation of the parameters see the docstring for + numba.core.dispatcher::inspect_cfg. + """ + import graphviz as gv + import re + import json + import inspect + from llvmlite import binding as ll + from numba.typed import List + from types import SimpleNamespace + from collections import defaultdict + + _default = False + _highlight = SimpleNamespace(incref=_default, + decref=_default, + returns=_default, + raises=_default, + meminfo=_default, + branches=_default, + llvm_intrin_calls=_default, + function_calls=_default,) + _interleave = SimpleNamespace(python=_default, lineinfo=_default) + + def parse_config(_config, kwarg): + """ Parses the kwarg into a consistent format for use in configuring + the Digraph rendering. _config is the configuration instance to + update, kwarg is the kwarg on which to base the updates. + """ + if isinstance(kwarg, bool): + for attr in _config.__dict__: + setattr(_config, attr, kwarg) + elif isinstance(kwarg, dict): + for k, v in kwarg.items(): + if k not in _config.__dict__: + raise ValueError("Unexpected key in kwarg: %s" % k) + if isinstance(v, bool): + setattr(_config, k, v) + else: + msg = "Unexpected value for key: %s, got:%s" + raise ValueError(msg % (k, v)) + elif isinstance(kwarg, set): + for item in kwarg: + if item not in _config.__dict__: + raise ValueError("Unexpected key in kwarg: %s" % item) + else: + setattr(_config, item, True) + else: + msg = "Unhandled configuration type for kwarg %s" + raise ValueError(msg % type(kwarg)) + + parse_config(_highlight, highlight) + parse_config(_interleave, interleave) + + # This is the colour scheme. The graphviz HTML label renderer only takes + # names for colours: https://www.graphviz.org/doc/info/shapes.html#html + cs = defaultdict(lambda: 'white') # default bg colour is white + cs['marker'] = 'orange' + cs['python'] = 'yellow' + cs['truebr'] = 'green' + cs['falsebr'] = 'red' + cs['incref'] = 'cyan' + cs['decref'] = 'turquoise' + cs['raise'] = 'lightpink' + cs['meminfo'] = 'lightseagreen' + cs['return'] = 'purple' + cs['llvm_intrin_calls'] = 'rosybrown' + cs['function_calls'] = 'tomato' + + # Get the raw dot format information from LLVM and the LLVM IR + fn = self.cres.get_function(self.name) + #raw_dot = ll.get_function_cfg(fn).replace('\\l...', '') + llvm_str = self.cres.get_llvm_str() + + def get_metadata(llvm_str): + """ Gets the metadata entries from the LLVM IR, these look something + like '!123 = INFORMATION'. Returns a map of metadata key to metadata + value, i.e. from the example {'!123': INFORMATION}""" + md = {} + metadata_entry = re.compile(r'(^[!][0-9]+)(\s+=\s+.*)') + for x in llvm_str.splitlines(): + match = metadata_entry.match(x) + if match is not None: + g = match.groups() + if g is not None: + assert len(g) == 2 + md[g[0]] = g[1] + return md + + md = get_metadata(llvm_str) + + # setup digraph with initial properties + def init_digraph(name, fname, fontsize): + # name and fname are arbitrary graph and file names, they appear in + # some rendering formats, the fontsize determines the output + # fontsize. + + # truncate massive mangled names as file names as it causes OSError + # when trying to render to pdf + cmax = 200 + if len(fname) > cmax: + wstr = (f'CFG output filename "{fname}" exceeds maximum ' + f'supported length, it will be truncated.') + warnings.warn(wstr, NumbaInvalidConfigWarning) + fname = fname[:cmax] + f = gv.Digraph(name, filename=fname) + f.attr(rankdir='TB') + f.attr('node', shape='none', fontsize='%s' % str(fontsize)) + return f + + f = init_digraph(self.name, self.name, fontsize) + + # A lot of regex is needed to parse the raw dot output. This output + # contains a mix of LLVM IR in the labels, and also DOT markup. + + # DOT syntax, matches a "port" (where the tail of an edge starts) + port_match = re.compile('.*{(.*)}.*') + # DOT syntax, matches the "port" value from a found "port_match" + port_jmp_match = re.compile('.*<(.*)>(.*)') + # LLVM syntax, matches a LLVM debug marker + metadata_marker = re.compile(r'.*!dbg\s+(![0-9]+).*') + # LLVM syntax, matches a location entry + location_expr = (r'.*!DILocation\(line:\s+([0-9]+),' + r'\s+column:\s+([0-9]),.*') + location_entry = re.compile(location_expr) + # LLVM syntax, matches LLVMs internal debug value calls + dbg_value = re.compile(r'.*call void @llvm.dbg.value.*') + # LLVM syntax, matches tokens for highlighting + nrt_incref = re.compile(r"@NRT_incref\b") + nrt_decref = re.compile(r"@NRT_decref\b") + nrt_meminfo = re.compile("@NRT_MemInfo") + ll_intrin_calls = re.compile(r".*call.*@llvm\..*") + ll_function_call = re.compile(r".*call.*@.*") + ll_raise = re.compile(r"store .*\!numba_exception_output.*") + ll_return = re.compile("ret i32 [^1],?.*") + + # wrapper function for line wrapping LLVM lines + def wrap(s): + return textwrap.wrap(s, width=120, subsequent_indent='... ') + + # function to fix (sometimes escaped for DOT!) LLVM IR etc that needs to + # be HTML escaped + def clean(s): + # Grab first 300 chars only, 1. this should be enough to identify + # the token and it keeps names short. 2. graphviz/dot has a maximum + # buffer size near 585?!, with additional transforms it's hard to + # know if this would be exceeded. 3. hash of the token string is + # written into the rendering to permit exact identification against + # e.g. LLVM IR dump if necessary. + n = 300 + if len(s) > n: + hs = str(hash(s)) + s = '{}...'.format(s[:n], hs) + s = html.escape(s) # deals with &, < and > + s = s.replace('\\{', "{") + s = s.replace('\\}', "}") + s = s.replace('\\', "\") + s = s.replace('%', "%") + s = s.replace('!', "!") + return s + + # These hold the node and edge ids from the raw dot information. They + # are used later to wire up a new DiGraph that has the same structure + # as the raw dot but with new nodes. + node_ids = {} + edge_ids = {} + + # Python source lines, used if python source interleave is requested + if _interleave.python: + src_code, firstlineno = inspect.getsourcelines(self.py_func) + + # This is the dot info from LLVM, it's in DOT form and has continuation + # lines, strip them and then re-parse into `dot_json` form for use in + # producing a formatted output. + raw_dot = ll.get_function_cfg(fn).replace('\\l...', '') + json_bytes = gv.Source(raw_dot).pipe(format='dot_json') + jzon = json.loads(json_bytes.decode('utf-8')) + + idc = 0 + # Walk the "objects" (nodes) in the DOT output + for obj in jzon['objects']: + # These are used to keep tabs on the current line and column numbers + # as per the markers. They are tracked so as to make sure a marker + # is only emitted if there's a change in the marker. + cur_line, cur_col = -1, -1 + label = obj['label'] + name = obj['name'] + gvid = obj['_gvid'] + node_ids[gvid] = name + # Label is DOT format, it needs the head and tail removing and then + # splitting for walking. + label = label[1:-1] + lines = label.split('\\l') + + # Holds the new lines + new_lines = [] + + # Aim is to produce an HTML table a bit like this: + # + # |------------| + # | HEADER | <-- this is the block header + # |------------| + # | LLVM SRC | <-- + # | Marker? | < this is the label/block body + # | Python src?| <-- + # |------------| + # | T | F | <-- this is the "ports", also determines col_span + # -------------- + # + + # This is HTML syntax, its the column span. If there's a switch or a + # branch at the bottom of the node this is rendered as multiple + # columns in a table. First job is to go and render that and work + # out how many columns are needed as that dictates how many columns + # the rest of the source lines must span. In DOT syntax the places + # that edges join nodes are referred to as "ports". Syntax in DOT + # is like `node:port`. + col_span = 1 + + # First see if there is a port entry for this node + port_line = '' + matched = port_match.match(lines[-1]) + sliced_lines = lines + if matched is not None: + # There is a port + ports = matched.groups()[0] + ports_tokens = ports.split('|') + col_span = len(ports_tokens) + # Generate HTML table data cells, one for each port. If the + # ports correspond to a branch then they can optionally + # highlighted based on T/F. + tdfmt = ('{}') + tbl_data = [] + if _highlight.branches: + colors = {'T': cs['truebr'], 'F': cs['falsebr']} + else: + colors = {} + for tok in ports_tokens: + target, value = port_jmp_match.match(tok).groups() + color = colors.get(value, 'white') + tbl_data.append(tdfmt.format(color, target, value)) + port_line = ''.join(tbl_data) + # Drop the last line from the rest of the parse as it's the port + # and just been dealt with. + sliced_lines = lines[:-1] + + # loop peel the block header, it needs a HTML border + fmtheader = ('{}') + new_lines.append(fmtheader.format(cs['default'], col_span, + clean(sliced_lines[0].strip()))) + + # process rest of block creating the table row at a time. + fmt = ('{}') + + def metadata_interleave(l, new_lines): + """ + Search line `l` for metadata associated with python or line info + and inject it into `new_lines` if requested. + """ + matched = metadata_marker.match(l) + if matched is not None: + # there's a metadata marker + g = matched.groups() + if g is not None: + assert len(g) == 1, g + marker = g[0] + debug_data = md.get(marker, None) + if debug_data is not None: + # and the metadata marker has a corresponding piece + # of metadata + ld = location_entry.match(debug_data) + if ld is not None: + # and the metadata is line info... proceed + assert len(ld.groups()) == 2, ld + line, col = ld.groups() + # only emit a new marker if the line number in + # the metadata is "new". + if line != cur_line or col != cur_col: + if _interleave.lineinfo: + mfmt = 'Marker %s, Line %s, column %s' + mark_line = mfmt % (marker, line, col) + ln = fmt.format(cs['marker'], col_span, + clean(mark_line)) + new_lines.append(ln) + if _interleave.python: + # TODO: + # +1 for decorator, this probably needs + # the same thing doing as for the + # error messages where the decorator + # is scanned for, its not always +1! + lidx = int(line) - (firstlineno + 1) + source_line = src_code[lidx + 1] + ln = fmt.format(cs['python'], col_span, + clean(source_line)) + new_lines.append(ln) + return line, col + + for l in sliced_lines[1:]: + + # Drop LLVM debug call entries + if dbg_value.match(l): + continue + + # if requested generate interleaving of markers or python from + # metadata + if _interleave.lineinfo or _interleave.python: + updated_lineinfo = metadata_interleave(l, new_lines) + if updated_lineinfo is not None: + cur_line, cur_col = updated_lineinfo + + # Highlight other LLVM features if requested, HTML BGCOLOR + # property is set by this. + if _highlight.incref and nrt_incref.search(l): + colour = cs['incref'] + elif _highlight.decref and nrt_decref.search(l): + colour = cs['decref'] + elif _highlight.meminfo and nrt_meminfo.search(l): + colour = cs['meminfo'] + elif _highlight.raises and ll_raise.search(l): + # search for raise as its more specific than exit + colour = cs['raise'] + elif _highlight.returns and ll_return.search(l): + colour = cs['return'] + elif _highlight.llvm_intrin_calls and ll_intrin_calls.search(l): + colour = cs['llvm_intrin_calls'] + elif _highlight.function_calls and ll_function_call.search(l): + colour = cs['function_calls'] + else: + colour = cs['default'] + + # Use the default coloring as a flag to force printing if a + # special token print was requested AND LLVM ir stripping is + # required + if colour is not cs['default'] or not strip_ir: + for x in wrap(clean(l)): + new_lines.append(fmt.format(colour, col_span, x)) + + # add in the port line at the end of the block if it was present + # (this was built right at the top of the parse) + if port_line: + new_lines.append('{}'.format(port_line)) + + # If there was data, create a table, else don't! + dat = ''.join(new_lines) + if dat: + tab = (('%s
') % (idc, + dat)) + label = '<{}>'.format(tab) + else: + label = '' + + # finally, add a replacement node for the original with a new marked + # up label. + f.node(name, label=label) + + # Parse the edge data + if 'edges' in jzon: # might be a single block, no edges + for edge in jzon['edges']: + gvid = edge['_gvid'] + tp = edge.get('tailport', None) + edge_ids[gvid] = (edge['head'], edge['tail'], tp) + + # Write in the edge wiring with respect to the new nodes:ports. + for gvid, edge in edge_ids.items(): + tail = node_ids[edge[1]] + head = node_ids[edge[0]] + port = edge[2] + if port is not None: + tail += ':%s' % port + f.edge(tail, head) + + # Add a key to the graph if requested. + if show_key: + key_tab = [] + for k, v in cs.items(): + key_tab.append(('{}').format(v, k)) + # The first < and last > are DOT syntax, rest is DOT HTML. + f.node("Key", label=('<{}
' + 'Key:
>').format(''.join(key_tab))) + + # Render if required + if filename is not None or view is not None: + f.render(filename=filename, view=view, format=render_format) + + # Else pipe out a SVG + return f.pipe(format='svg') + + def display(self, filename=None, format='pdf', view=False): + """ + Plot the CFG. In IPython notebook, the return image object can be + inlined. + + The *filename* option can be set to a specific path for the rendered + output to write to. If *view* option is True, the plot is opened by + the system default application for the image format (PDF). *format* can + be any valid format string accepted by graphviz, default is 'pdf'. + """ + rawbyt = self.pretty_printer(filename=filename, view=view, + render_format=format, **self.kwargs) + return rawbyt.decode('utf-8') + + def _repr_svg_(self): + return self.pretty_printer(**self.kwargs).decode('utf-8') + + def __repr__(self): + return self.dot + + +class CodeLibrary(metaclass=ABCMeta): + """ + An interface for bundling LLVM code together and compiling it. + It is tied to a *codegen* instance (e.g. JITCPUCodegen) that will + determine how the LLVM code is transformed and linked together. + """ + + _finalized = False + _object_caching_enabled = False + _disable_inspection = False + + def __init__(self, codegen: "CPUCodegen", name: str): + self._codegen = codegen + self._name = name + ptc_name = f"{self.__class__.__name__}({self._name!r})" + self._recorded_timings = PassTimingsCollection(ptc_name) + # Track names of the dynamic globals + self._dynamic_globals = [] + + self._reload_init = set() + + @property + def has_dynamic_globals(self): + self._ensure_finalized() + return len(self._dynamic_globals) > 0 + + @property + def recorded_timings(self): + return self._recorded_timings + + @property + def codegen(self): + """ + The codegen object owning this library. + """ + return self._codegen + + @property + def name(self): + return self._name + + def __repr__(self): + return "" % (self.name, id(self)) + + def _raise_if_finalized(self): + if self._finalized: + raise RuntimeError("operation impossible on finalized object %r" + % (self,)) + + def _ensure_finalized(self): + if not self._finalized: + self.finalize() + + def create_ir_module(self, name): + """ + Create an LLVM IR module for use by this library. + """ + self._raise_if_finalized() + ir_module = self._codegen._create_empty_module(name) + return ir_module + + @abstractmethod + def add_linking_library(self, library): + """ + Add a library for linking into this library, without losing + the original library. + """ + + @abstractmethod + def add_ir_module(self, ir_module): + """ + Add an LLVM IR module's contents to this library. + """ + + @abstractmethod + def finalize(self): + """ + Finalize the library. After this call, nothing can be added anymore. + Finalization involves various stages of code optimization and + linking. + """ + + @abstractmethod + def get_function(self, name): + """ + Return the function named ``name``. + """ + + @abstractmethod + def get_llvm_str(self): + """ + Get the human-readable form of the LLVM module. + """ + + @abstractmethod + def get_asm_str(self): + """ + Get the human-readable assembly. + """ + + # + # Object cache hooks and serialization + # + + def enable_object_caching(self): + self._object_caching_enabled = True + self._compiled_object = None + self._compiled = False + + def _get_compiled_object(self): + if not self._object_caching_enabled: + raise ValueError("object caching not enabled in %s" % (self,)) + if self._compiled_object is None: + raise RuntimeError("no compiled object yet for %s" % (self,)) + return self._compiled_object + + def _set_compiled_object(self, value): + if not self._object_caching_enabled: + raise ValueError("object caching not enabled in %s" % (self,)) + if self._compiled: + raise ValueError("library already compiled: %s" % (self,)) + self._compiled_object = value + self._disable_inspection = True + + +class CPUCodeLibrary(CodeLibrary): + + def __init__(self, codegen, name): + super().__init__(codegen, name) + self._linking_libraries = [] # maintain insertion order + self._final_module = ll.parse_assembly( + str(self._codegen._create_empty_module(self.name))) + self._final_module.name = cgutils.normalize_ir_text(self.name) + self._shared_module = None + + def _optimize_functions(self, ll_module): + """ + Internal: run function-level optimizations inside *ll_module*. + """ + # Enforce data layout to enable layout-specific optimizations + ll_module.data_layout = self._codegen._data_layout + for func in ll_module.functions: + # Run function-level optimizations to reduce memory usage and improve + # module-level optimization. + fpm, pb = self._codegen._function_pass_manager() + k = f"Function passes on {func.name!r}" + with self._recorded_timings.record(k, pb): + fpm.run(func, pb) + + def _optimize_final_module(self): + + """ + Internal: optimize this library's final module. + """ + + mpm_cheap, mpb_cheap = self._codegen._module_pass_manager( + loop_vectorize=self._codegen._loopvect, + slp_vectorize=False, + opt=self._codegen._opt_level, + cost="cheap") + + mpm_full, mpb_full = self._codegen._module_pass_manager() + cheap_name = "Module passes (cheap optimization for refprune)" + with self._recorded_timings.record(cheap_name, mpb_cheap): + # A cheaper optimisation pass is run first to try and get as many + # refops into the same function as possible via inlining + mpm_cheap.run(self._final_module, mpb_cheap) + # Refop pruning is then run on the heavily inlined function + if not config.LLVM_REFPRUNE_PASS: + self._final_module = remove_redundant_nrt_refct(self._final_module) + full_name = "Module passes (full optimization)" + with self._recorded_timings.record(full_name, mpb_full): + # The full optimisation suite is then run on the refop pruned IR + mpm_full.run(self._final_module, mpb_full) + + def _get_module_for_linking(self): + """ + Internal: get a LLVM module suitable for linking multiple times + into another library. Exported functions are made "linkonce_odr" + to allow for multiple definitions, inlining, and removal of + unused exports. + + See discussion in https://github.com/numba/numba/pull/890 + """ + self._ensure_finalized() + if self._shared_module is not None: + return self._shared_module + mod = self._final_module + to_fix = [] + nfuncs = 0 + for fn in mod.functions: + nfuncs += 1 + if not fn.is_declaration and fn.linkage == ll.Linkage.external: + to_fix.append(fn.name) + if nfuncs == 0: + # This is an issue which can occur if loading a module + # from an object file and trying to link with it, so detect it + # here to make debugging easier. + raise RuntimeError("library unfit for linking: " + "no available functions in %s" + % (self,)) + if to_fix: + mod = mod.clone() + for name in to_fix: + # NOTE: this will mark the symbol WEAK if serialized + # to an ELF file + mod.get_function(name).linkage = 'linkonce_odr' + self._shared_module = mod + return mod + + def add_linking_library(self, library): + library._ensure_finalized() + self._linking_libraries.append(library) + + def add_ir_module(self, ir_module): + self._raise_if_finalized() + assert isinstance(ir_module, llvmir.Module) + ir = cgutils.normalize_ir_text(str(ir_module)) + ll_module = ll.parse_assembly(ir) + ll_module.name = ir_module.name + ll_module.verify() + self.add_llvm_module(ll_module) + + def add_llvm_module(self, ll_module): + self._optimize_functions(ll_module) + # TODO: we shouldn't need to recreate the LLVM module object + if not config.LLVM_REFPRUNE_PASS: + ll_module = remove_redundant_nrt_refct(ll_module) + self._final_module.link_in(ll_module) + + def finalize(self): + require_global_compiler_lock() + + # Report any LLVM-related problems to the user + self._codegen._check_llvm_bugs() + + self._raise_if_finalized() + + if config.DUMP_FUNC_OPT: + dump("FUNCTION OPTIMIZED DUMP %s" % self.name, + self.get_llvm_str(), 'llvm') + + # Link libraries for shared code + seen = set() + for library in self._linking_libraries: + if library not in seen: + # Parent inherits reload_init + self._reload_init.update(library._reload_init) + seen.add(library) + self._final_module.link_in( + library._get_module_for_linking(), preserve=True, + ) + + # Optimize the module after all dependences are linked in above, + # to allow for inlining. + self._optimize_final_module() + + self._final_module.verify() + self._finalize_final_module() + + def _finalize_dynamic_globals(self): + # Scan for dynamic globals + for gv in self._final_module.global_variables: + if gv.name.startswith('numba.dynamic.globals'): + self._dynamic_globals.append(gv.name) + + def _verify_declare_only_symbols(self): + # Verify that no declare-only function compiled by numba. + for fn in self._final_module.functions: + # We will only check for symbol name starting with '_ZN5numba' + if fn.is_declaration and fn.name.startswith('_ZN5numba'): + msg = 'Symbol {} not linked properly' + raise AssertionError(msg.format(fn.name)) + + def _finalize_final_module(self): + """ + Make the underlying LLVM module ready to use. + """ + self._finalize_dynamic_globals() + self._verify_declare_only_symbols() + + # Remember this on the module, for the object cache hooks + self._final_module.__library = weakref.proxy(self) + + # It seems add_module() must be done only here and not before + # linking in other modules, otherwise get_pointer_to_function() + # could fail. + cleanup = self._codegen._add_module(self._final_module) + if cleanup: + weakref.finalize(self, cleanup) + self._finalize_specific() + + self._finalized = True + + if config.DUMP_OPTIMIZED: + dump("OPTIMIZED DUMP %s" % self.name, self.get_llvm_str(), 'llvm') + + if config.DUMP_ASSEMBLY: + dump("ASSEMBLY %s" % self.name, self.get_asm_str(), 'asm') + + def get_defined_functions(self): + """ + Get all functions defined in the library. The library must have + been finalized. + """ + mod = self._final_module + for fn in mod.functions: + if not fn.is_declaration: + yield fn + + def get_function(self, name): + return self._final_module.get_function(name) + + def _sentry_cache_disable_inspection(self): + if self._disable_inspection: + warnings.warn('Inspection disabled for cached code. ' + 'Invalid result is returned.') + + def get_llvm_str(self): + self._sentry_cache_disable_inspection() + return str(self._final_module) + + def get_asm_str(self): + self._sentry_cache_disable_inspection() + return str(self._codegen._tm.emit_assembly(self._final_module)) + + def get_function_cfg(self, name, py_func=None, **kwargs): + """ + Get control-flow graph of the LLVM function + """ + self._sentry_cache_disable_inspection() + return _CFG(self, name, py_func, **kwargs) + + def get_disasm_cfg(self, mangled_name): + """ + Get the CFG of the disassembly of the ELF object at symbol mangled_name. + + Requires python package: r2pipe + Requires radare2 binary on $PATH. + Notebook rendering requires python package: graphviz + Optionally requires a compiler toolchain (via pycc) to link the ELF to + get better disassembly results. + """ + elf = self._get_compiled_object() + return disassemble_elf_to_cfg(elf, mangled_name) + + @classmethod + def _dump_elf(cls, buf): + """ + Dump the symbol table of an ELF file. + Needs pyelftools (https://github.com/eliben/pyelftools) + """ + from elftools.elf.elffile import ELFFile + from elftools.elf import descriptions + from io import BytesIO + f = ELFFile(BytesIO(buf)) + print("ELF file:") + for sec in f.iter_sections(): + if sec['sh_type'] == 'SHT_SYMTAB': + symbols = sorted(sec.iter_symbols(), key=lambda sym: sym.name) + print(" symbols:") + for sym in symbols: + if not sym.name: + continue + print(" - %r: size=%d, value=0x%x, type=%s, bind=%s" + % (sym.name.decode(), + sym['st_size'], + sym['st_value'], + descriptions.describe_symbol_type(sym['st_info']['type']), + descriptions.describe_symbol_bind(sym['st_info']['bind']), + )) + print() + + @classmethod + def _object_compiled_hook(cls, ll_module, buf): + """ + `ll_module` was compiled into object code `buf`. + """ + try: + self = ll_module.__library + except AttributeError: + return + if self._object_caching_enabled: + self._compiled = True + self._compiled_object = buf + + @classmethod + def _object_getbuffer_hook(cls, ll_module): + """ + Return a cached object code for `ll_module`. + """ + try: + self = ll_module.__library + except AttributeError: + return + if self._object_caching_enabled and self._compiled_object: + buf = self._compiled_object + self._compiled_object = None + return buf + + def serialize_using_bitcode(self): + """ + Serialize this library using its bitcode as the cached representation. + """ + self._ensure_finalized() + return (self.name, 'bitcode', self._final_module.as_bitcode()) + + def serialize_using_object_code(self): + """ + Serialize this library using its object code as the cached + representation. We also include its bitcode for further inlining + with other libraries. + """ + self._ensure_finalized() + data = (self._get_compiled_object(), + self._get_module_for_linking().as_bitcode()) + return (self.name, 'object', data) + + @classmethod + def _unserialize(cls, codegen, state): + name, kind, data = state + self = codegen.create_library(name) + assert isinstance(self, cls) + if kind == 'bitcode': + # No need to re-run optimizations, just make the module ready + self._final_module = ll.parse_bitcode(data) + self._finalize_final_module() + return self + elif kind == 'object': + object_code, shared_bitcode = data + self.enable_object_caching() + self._set_compiled_object(object_code) + self._shared_module = ll.parse_bitcode(shared_bitcode) + self._finalize_final_module() + # Load symbols from cache + self._codegen._engine._load_defined_symbols(self._shared_module) + return self + else: + raise ValueError("unsupported serialization kind %r" % (kind,)) + + +class AOTCodeLibrary(CPUCodeLibrary): + + def emit_native_object(self): + """ + Return this library as a native object (a bytestring) -- for example + ELF under Linux. + + This function implicitly calls .finalize(). + """ + self._ensure_finalized() + return self._codegen._tm.emit_object(self._final_module) + + def emit_bitcode(self): + """ + Return this library as LLVM bitcode (a bytestring). + + This function implicitly calls .finalize(). + """ + self._ensure_finalized() + return self._final_module.as_bitcode() + + def _finalize_specific(self): + pass + + +class JITCodeLibrary(CPUCodeLibrary): + + def get_pointer_to_function(self, name): + """ + Generate native code for function named *name* and return a pointer + to the start of the function (as an integer). + + This function implicitly calls .finalize(). + + Returns + ------- + pointer : int + - zero (null) if no symbol of *name* is defined by this code + library. + - non-zero if the symbol is defined. + """ + self._ensure_finalized() + ee = self._codegen._engine + if not ee.is_symbol_defined(name): + return 0 + else: + return self._codegen._engine.get_function_address(name) + + def _finalize_specific(self): + self._codegen._scan_and_fix_unresolved_refs(self._final_module) + with self._recorded_timings.record_legacy("Finalize object"): + self._codegen._engine.finalize_object() + + +class RuntimeLinker(object): + """ + For tracking unresolved symbols generated at runtime due to recursion. + """ + PREFIX = '.numba.unresolved$' + + def __init__(self): + self._unresolved = utils.UniqueDict() + self._defined = set() + self._resolved = [] + + def scan_unresolved_symbols(self, module, engine): + """ + Scan and track all unresolved external symbols in the module and + allocate memory for it. + """ + prefix = self.PREFIX + + for gv in module.global_variables: + if gv.name.startswith(prefix): + sym = gv.name[len(prefix):] + # Avoid remapping to existing GV + if engine.is_symbol_defined(gv.name): + continue + # Allocate a memory space for the pointer + abortfn = rtsys.library.get_pointer_to_function("nrt_unresolved_abort") + ptr = ctypes.c_void_p(abortfn) + engine.add_global_mapping(gv, ctypes.addressof(ptr)) + self._unresolved[sym] = ptr + + def scan_defined_symbols(self, module): + """ + Scan and track all defined symbols. + """ + for fn in module.functions: + if not fn.is_declaration: + self._defined.add(fn.name) + + def resolve(self, engine): + """ + Fix unresolved symbols if they are defined. + """ + # An iterator to get all unresolved but available symbols + pending = [name for name in self._unresolved if name in self._defined] + # Resolve pending symbols + for name in pending: + # Get runtime address + fnptr = engine.get_function_address(name) + # Fix all usage + ptr = self._unresolved[name] + ptr.value = fnptr + self._resolved.append((name, ptr)) # keep ptr alive + # Delete resolved + del self._unresolved[name] + +def _proxy(old): + @functools.wraps(old) + def wrapper(self, *args, **kwargs): + return old(self._ee, *args, **kwargs) + return wrapper + + +class JitEngine(object): + """Wraps an ExecutionEngine to provide custom symbol tracking. + Since the symbol tracking is incomplete (doesn't consider + loaded code object), we are not putting it in llvmlite. + """ + def __init__(self, ee): + self._ee = ee + # Track symbol defined via codegen'd Module + # but not any cached object. + # NOTE: `llvm::ExecutionEngine` will catch duplicated symbols and + # we are not going to protect against that. A proper duplicated + # symbol detection will need a more logic to check for the linkage + # (e.g. like `weak` linkage symbol can override). This + # `_defined_symbols` set will be just enough to tell if a symbol + # exists and will not cause the `EE` symbol lookup to `exit(1)` + # when symbol-not-found. + self._defined_symbols = set() + + def is_symbol_defined(self, name): + """Is the symbol defined in this session? + """ + return name in self._defined_symbols + + def _load_defined_symbols(self, mod): + """Extract symbols from the module + """ + for gsets in (mod.functions, mod.global_variables): + self._defined_symbols |= {gv.name for gv in gsets + if not gv.is_declaration} + + def add_module(self, module): + """Override ExecutionEngine.add_module + to keep info about defined symbols. + """ + self._load_defined_symbols(module) + return self._ee.add_module(module) + + def add_global_mapping(self, gv, addr): + """Override ExecutionEngine.add_global_mapping + to keep info about defined symbols. + """ + self._defined_symbols.add(gv.name) + return self._ee.add_global_mapping(gv, addr) + + # + # The remaining methods are re-export of the ExecutionEngine APIs + # + set_object_cache = _proxy(ll.ExecutionEngine.set_object_cache) + finalize_object = _proxy(ll.ExecutionEngine.finalize_object) + get_function_address = _proxy(ll.ExecutionEngine.get_function_address) + get_global_value_address = _proxy( + ll.ExecutionEngine.get_global_value_address + ) + + +class Codegen(metaclass=ABCMeta): + """ + Base Codegen class. It is expected that subclasses set the class attribute + ``_library_class``, indicating the CodeLibrary class for the target. + + Subclasses should also initialize: + + ``self._data_layout``: the data layout for the target. + ``self._target_data``: the binding layer ``TargetData`` for the target. + """ + + @abstractmethod + def _create_empty_module(self, name): + """ + Create a new empty module suitable for the target. + """ + + @abstractmethod + def _add_module(self, module): + """ + Add a module to the execution engine. Ownership of the module is + transferred to the engine. + """ + + @property + def target_data(self): + """ + The LLVM "target data" object for this codegen instance. + """ + return self._target_data + + def create_library(self, name, **kwargs): + """ + Create a :class:`CodeLibrary` object for use with this codegen + instance. + """ + return self._library_class(self, name, **kwargs) + + def unserialize_library(self, serialized): + return self._library_class._unserialize(self, serialized) + + +class CPUCodegen(Codegen): + + def __init__(self, module_name): + initialize_llvm() + + self._data_layout = None + self._llvm_module = ll.parse_assembly( + str(self._create_empty_module(module_name))) + self._llvm_module.name = "global_codegen_module" + self._rtlinker = RuntimeLinker() + self._init(self._llvm_module) + + def _init(self, llvm_module): + assert list(llvm_module.global_variables) == [], "Module isn't empty" + + target = ll.Target.from_triple(ll.get_process_triple()) + tm_options = dict(opt=config.OPT) + self._tm_features = self._customize_tm_features() + self._customize_tm_options(tm_options) + tm = target.create_target_machine(**tm_options) + use_lmm = config.USE_LLVMLITE_MEMORY_MANAGER + engine = ll.create_mcjit_compiler(llvm_module, tm, use_lmm=use_lmm) + + if config.ENABLE_PROFILING: + engine.enable_jit_events() + + self._tm = tm + self._engine = JitEngine(engine) + self._target_data = engine.target_data + self._data_layout = str(self._target_data) + + if config.OPT.is_opt_max: + # If the OPT level is set to 'max' then the user is requesting that + # compilation time is traded for potential performance gain. This + # currently manifests as running the "cheap" pass at -O3 + # optimisation level with loop-vectorization enabled. There's no + # guarantee that this will increase runtime performance, it may + # detriment it, this is here to give the user an easily accessible + # option to try. + self._loopvect = True + self._opt_level = 3 + else: + # The default behaviour is to do an opt=0 pass to try and inline as + # much as possible with the cheapest cost of doing so. This is so + # that the ref-op pruner pass that runs after the cheap pass will + # have the largest possible scope for working on pruning references. + self._loopvect = False + self._opt_level = 0 + + self._engine.set_object_cache(self._library_class._object_compiled_hook, + self._library_class._object_getbuffer_hook) + + def _create_empty_module(self, name): + ir_module = llvmir.Module(cgutils.normalize_ir_text(name)) + ir_module.triple = ll.get_process_triple() + if self._data_layout: + ir_module.data_layout = self._data_layout + return ir_module + + def _module_pass_manager(self, **kwargs): + cost = kwargs.pop("cost", None) + pb = self._pass_builder(**kwargs) + pm = pb.getModulePassManager() + # If config.OPT==0 do not include these extra passes to help with + # vectorization. + if cost is not None and cost == "cheap" and config.OPT != 0: + # This knocks loops into rotated form early to reduce the likelihood + # of vectorization failing due to unknown PHI nodes. + pm.add_loop_rotate_pass() + # These passes are required to get SVML to vectorize tests + pm.add_instruction_combine_pass() + pm.add_jump_threading_pass() + + if config.LLVM_REFPRUNE_PASS: + pm.add_refprune_pass(_parse_refprune_flags()) + return pm, pb + + def _function_pass_manager(self, **kwargs): + pb = self._pass_builder(**kwargs) + pm = pb.getFunctionPassManager() + if config.LLVM_REFPRUNE_PASS: + pm.add_refprune_pass(_parse_refprune_flags()) + return pm, pb + + def _pass_builder(self, **kwargs): + opt_level = kwargs.pop('opt', config.OPT) + loop_vectorize = kwargs.pop('loop_vectorize', config.LOOP_VECTORIZE) + slp_vectorize = kwargs.pop('slp_vectorize', config.SLP_VECTORIZE) + + pb = create_pass_builder(self._tm, opt=opt_level, + loop_vectorize=loop_vectorize, + slp_vectorize=slp_vectorize, + **kwargs) + + return pb + + def _check_llvm_bugs(self): + """ + Guard against some well-known LLVM bug(s). + """ + # Check the locale bug at https://github.com/numba/numba/issues/1569 + # Note we can't cache the result as locale settings can change + # across a process's lifetime. Also, for this same reason, + # the check here is a mere heuristic (there may be a race condition + # between now and actually compiling IR). + ir = """ + define double @func() + { + ret double 1.23e+01 + } + """ + mod = ll.parse_assembly(ir) + ir_out = str(mod) + if "12.3" in ir_out or "1.23" in ir_out: + # Everything ok + return + if "1.0" in ir_out: + loc = locale.getlocale() + raise RuntimeError( + "LLVM will produce incorrect floating-point code " + "in the current locale %s.\nPlease read " + "https://numba.readthedocs.io/en/stable/user/faq.html#llvm-locale-bug " + "for more information." + % (loc,)) + raise AssertionError("Unexpected IR:\n%s\n" % (ir_out,)) + + def magic_tuple(self): + """ + Return a tuple unambiguously describing the codegen behaviour. + """ + return (self._llvm_module.triple, self._get_host_cpu_name(), + self._tm_features) + + def _scan_and_fix_unresolved_refs(self, module): + self._rtlinker.scan_unresolved_symbols(module, self._engine) + self._rtlinker.scan_defined_symbols(module) + self._rtlinker.resolve(self._engine) + + def insert_unresolved_ref(self, builder, fnty, name): + voidptr = llvmir.IntType(8).as_pointer() + ptrname = self._rtlinker.PREFIX + name + llvm_mod = builder.module + try: + fnptr = llvm_mod.get_global(ptrname) + except KeyError: + # Not defined? + fnptr = llvmir.GlobalVariable(llvm_mod, voidptr, name=ptrname) + fnptr.linkage = 'external' + return builder.bitcast(builder.load(fnptr), fnty.as_pointer()) + + def _get_host_cpu_name(self): + return (ll.get_host_cpu_name() + if config.CPU_NAME is None + else config.CPU_NAME) + + def _get_host_cpu_features(self): + if config.CPU_FEATURES is not None: + return config.CPU_FEATURES + return get_host_cpu_features() + + +class AOTCPUCodegen(CPUCodegen): + """ + A codegen implementation suitable for Ahead-Of-Time compilation + (e.g. generation of object files). + """ + + _library_class = AOTCodeLibrary + + def __init__(self, module_name, cpu_name=None): + # By default, use generic cpu model for the arch + self._cpu_name = cpu_name or '' + CPUCodegen.__init__(self, module_name) + + def _customize_tm_options(self, options): + cpu_name = self._cpu_name + if cpu_name == 'host': + cpu_name = self._get_host_cpu_name() + options['cpu'] = cpu_name + options['reloc'] = 'pic' + options['codemodel'] = 'default' + options['features'] = self._tm_features + + def _customize_tm_features(self): + # ISA features are selected according to the requested CPU model + # in _customize_tm_options() + return '' + + def _add_module(self, module): + pass + + +class JITCPUCodegen(CPUCodegen): + """ + A codegen implementation suitable for Just-In-Time compilation. + """ + + _library_class = JITCodeLibrary + + def _customize_tm_options(self, options): + # As long as we don't want to ship the code to another machine, + # we can specialize for this CPU. + options['cpu'] = self._get_host_cpu_name() + # LLVM 7 change: # https://reviews.llvm.org/D47211#inline-425406 + # JIT needs static relocation on x86* + # native target is already initialized from base class __init__ + arch = ll.Target.from_default_triple().name + if arch.startswith('x86'): # one of x86 or x86_64 + reloc_model = 'static' + elif arch.startswith('ppc'): + reloc_model = 'pic' + else: + reloc_model = 'default' + options['reloc'] = reloc_model + options['codemodel'] = 'jitdefault' + + # Set feature attributes (such as ISA extensions) + # This overrides default feature selection by CPU model above + options['features'] = self._tm_features + + # Deal with optional argument to ll.Target.create_target_machine + sig = utils.pysignature(ll.Target.create_target_machine) + if 'jit' in sig.parameters: + # Mark that this is making a JIT engine + options['jit'] = True + + def _customize_tm_features(self): + # For JIT target, we will use LLVM to get the feature map + return self._get_host_cpu_features() + + def _add_module(self, module): + self._engine.add_module(module) + # XXX: disabling remove module due to MCJIT engine leakage in + # removeModule. The removeModule causes consistent access + # violation with certain test combinations. + # # Early bind the engine method to avoid keeping a reference to self. + # return functools.partial(self._engine.remove_module, module) + + def set_env(self, env_name, env): + """Set the environment address. + + Update the GlobalVariable named *env_name* to the address of *env*. + """ + gvaddr = self._engine.get_global_value_address(env_name) + envptr = (ctypes.c_void_p * 1).from_address(gvaddr) + envptr[0] = ctypes.c_void_p(id(env)) + + +def initialize_llvm(): + """Safe to use multiple times. + """ + ll.initialize_native_target() + ll.initialize_native_asmprinter() + + +def get_host_cpu_features(): + """Get host CPU features using LLVM. + + The features may be modified due to user setting. + See numba.config.ENABLE_AVX. + """ + try: + features = ll.get_host_cpu_features() + except RuntimeError: + return '' + else: + if not config.ENABLE_AVX: + # Disable all features with name starting with 'avx' + for k in features: + if k.startswith('avx'): + features[k] = False + + # Set feature attributes + return features.flatten() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d4259f555262dfd1170683835b4e0cdb74859f52 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler.py @@ -0,0 +1,813 @@ +from collections import namedtuple +import copy +import warnings +from numba.core.tracing import event + +from numba.core import (errors, interpreter, bytecode, postproc, config, + callconv, cpu) +from numba.parfors.parfor import ParforDiagnostics +from numba.core.errors import CompilerError +from numba.core.environment import lookup_environment + +from numba.core.compiler_machinery import PassManager + +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, + FixupArgs, IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, + InlineClosureLikes, GenericRewrites, + WithLifting, InlineInlinables, + FindLiterallyCalls, + MakeFunctionToJitFunction, + CanonicalizeLoopExit, + CanonicalizeLoopEntry, LiteralUnroll, + ReconstructSSA, RewriteDynamicRaises, + LiteralPropagationSubPipelinePass, + ) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, PreParforPass, + ParforPass, DumpParforDiagnostics, + IRLegalization, NoPythonBackend, + InlineOverloads, PreLowerStripPhis, + NativeLowering, NativeParforLowering, + NoPythonSupportedFeatureValidation, + ParforFusionPass, ParforPreLoweringPass + ) + +from numba.core.object_mode_passes import (ObjectModeFrontEnd, + ObjectModeBackEnd) +from numba.core.targetconfig import TargetConfig, Option, ConfigStack + + +class Flags(TargetConfig): + __slots__ = () + + enable_looplift = Option( + type=bool, + default=False, + doc="Enable loop-lifting", + ) + enable_pyobject = Option( + type=bool, + default=False, + doc="Enable pyobject mode (in general)", + ) + enable_pyobject_looplift = Option( + type=bool, + default=False, + doc="Enable pyobject mode inside lifted loops", + ) + enable_ssa = Option( + type=bool, + default=True, + doc="Enable SSA", + ) + force_pyobject = Option( + type=bool, + default=False, + doc="Force pyobject mode inside the whole function", + ) + release_gil = Option( + type=bool, + default=False, + doc="Release GIL inside the native function", + ) + no_compile = Option( + type=bool, + default=False, + doc="TODO", + ) + debuginfo = Option( + type=bool, + default=False, + doc="TODO", + ) + boundscheck = Option( + type=bool, + default=False, + doc="TODO", + ) + forceinline = Option( + type=bool, + default=False, + doc="Force inlining of the function. Overrides _dbg_optnone.", + ) + no_cpython_wrapper = Option( + type=bool, + default=False, + doc="TODO", + ) + no_cfunc_wrapper = Option( + type=bool, + default=False, + doc="TODO", + ) + auto_parallel = Option( + type=cpu.ParallelOptions, + default=cpu.ParallelOptions(False), + doc="""Enable automatic parallel optimization, can be fine-tuned by +taking a dictionary of sub-options instead of a boolean, see parfor.py for +detail""", + ) + nrt = Option( + type=bool, + default=False, + doc="TODO", + ) + no_rewrites = Option( + type=bool, + default=False, + doc="TODO", + ) + error_model = Option( + type=str, + default="python", + doc="TODO", + ) + fastmath = Option( + type=cpu.FastMathOptions, + default=cpu.FastMathOptions(False), + doc="TODO", + ) + noalias = Option( + type=bool, + default=False, + doc="TODO", + ) + inline = Option( + type=cpu.InlineOptions, + default=cpu.InlineOptions("never"), + doc="TODO", + ) + + dbg_extend_lifetimes = Option( + type=bool, + default=False, + doc=("Extend variable lifetime for debugging. " + "This automatically turns on with debug=True."), + ) + + dbg_optnone = Option( + type=bool, + default=False, + doc=("Disable optimization for debug. " + "Equivalent to adding optnone attribute in the LLVM Function.") + ) + + dbg_directives_only = Option( + type=bool, + default=False, + doc=("Make debug emissions directives-only. " + "Used when generating lineinfo.") + ) + + +DEFAULT_FLAGS = Flags() +DEFAULT_FLAGS.nrt = True + + +CR_FIELDS = ["typing_context", + "target_context", + "entry_point", + "typing_error", + "type_annotation", + "signature", + "objectmode", + "lifted", + "fndesc", + "library", + "call_helper", + "environment", + "metadata", + # List of functions to call to initialize on unserialization + # (i.e cache load). + "reload_init", + "referenced_envs", + ] + + +class CompileResult(namedtuple("_CompileResult", CR_FIELDS)): + """ + A structure holding results from the compilation of a function. + """ + + __slots__ = () + + def _reduce(self): + """ + Reduce a CompileResult to picklable components. + """ + libdata = self.library.serialize_using_object_code() + # Make it (un)picklable efficiently + typeann = str(self.type_annotation) + fndesc = self.fndesc + # Those don't need to be pickled and may fail + fndesc.typemap = fndesc.calltypes = None + # Include all referenced environments + referenced_envs = self._find_referenced_environments() + return (libdata, self.fndesc, self.environment, self.signature, + self.objectmode, self.lifted, typeann, self.reload_init, + tuple(referenced_envs)) + + def _find_referenced_environments(self): + """Returns a list of referenced environments + """ + mod = self.library._final_module + # Find environments + referenced_envs = [] + for gv in mod.global_variables: + gvn = gv.name + if gvn.startswith("_ZN08NumbaEnv"): + env = lookup_environment(gvn) + if env is not None: + if env.can_cache(): + referenced_envs.append(env) + return referenced_envs + + @classmethod + def _rebuild(cls, target_context, libdata, fndesc, env, + signature, objectmode, lifted, typeann, + reload_init, referenced_envs): + if reload_init: + # Re-run all + for fn in reload_init: + fn() + + library = target_context.codegen().unserialize_library(libdata) + cfunc = target_context.get_executable(library, fndesc, env) + cr = cls(target_context=target_context, + typing_context=target_context.typing_context, + library=library, + environment=env, + entry_point=cfunc, + fndesc=fndesc, + type_annotation=typeann, + signature=signature, + objectmode=objectmode, + lifted=lifted, + typing_error=None, + call_helper=None, + metadata=None, # Do not store, arbitrary & potentially large! + reload_init=reload_init, + referenced_envs=referenced_envs, + ) + + # Load Environments + for env in referenced_envs: + library.codegen.set_env(env.env_name, env) + + return cr + + @property + def codegen(self): + return self.target_context.codegen() + + def dump(self, tab=''): + print(f'{tab}DUMP {type(self).__name__} {self.entry_point}') + self.signature.dump(tab=tab + ' ') + print(f'{tab}END DUMP') + + +_LowerResult = namedtuple("_LowerResult", [ + "fndesc", + "call_helper", + "cfunc", + "env", +]) + + +def sanitize_compile_result_entries(entries): + keys = set(entries.keys()) + fieldset = set(CR_FIELDS) + badnames = keys - fieldset + if badnames: + raise NameError(*badnames) + missing = fieldset - keys + for k in missing: + entries[k] = None + # Avoid keeping alive traceback variables + err = entries['typing_error'] + if err is not None: + entries['typing_error'] = err.with_traceback(None) + return entries + + +def compile_result(**entries): + entries = sanitize_compile_result_entries(entries) + return CompileResult(**entries) + + +def run_frontend(func, inline_closures=False, emit_dels=False): + """ + Run the compiler frontend over the given Python function, and return + the function's canonical Numba IR. + + If inline_closures is Truthy then closure inlining will be run + If emit_dels is Truthy the ir.Del nodes will be emitted appropriately + """ + # XXX make this a dedicated Pipeline? + func_id = bytecode.FunctionIdentity.from_function(func) + interp = interpreter.Interpreter(func_id) + bc = bytecode.ByteCode(func_id=func_id) + func_ir = interp.interpret(bc) + if inline_closures: + from numba.core.inline_closurecall import InlineClosureCallPass + inline_pass = InlineClosureCallPass(func_ir, cpu.ParallelOptions(False), + {}, False) + inline_pass.run() + post_proc = postproc.PostProcessor(func_ir) + post_proc.run(emit_dels) + return func_ir + + +class _CompileStatus(object): + """ + Describes the state of compilation. Used like a C record. + """ + __slots__ = ['fail_reason', 'can_fallback'] + + def __init__(self, can_fallback): + self.fail_reason = None + self.can_fallback = can_fallback + + def __repr__(self): + vals = [] + for k in self.__slots__: + vals.append("{k}={v}".format(k=k, v=getattr(self, k))) + return ', '.join(vals) + + +class _EarlyPipelineCompletion(Exception): + """ + Raised to indicate that a pipeline has completed early + """ + + def __init__(self, result): + self.result = result + + +class StateDict(dict): + """ + A dictionary that has an overloaded getattr and setattr to permit getting + and setting key/values through the use of attributes. + """ + + def __getattr__(self, attr): + try: + return self[attr] + except KeyError: + raise AttributeError(attr) + + def __setattr__(self, attr, value): + self[attr] = value + + +def _make_subtarget(targetctx, flags): + """ + Make a new target context from the given target context and flags. + """ + subtargetoptions = {} + if flags.debuginfo: + subtargetoptions['enable_debuginfo'] = True + if flags.boundscheck: + subtargetoptions['enable_boundscheck'] = True + if flags.nrt: + subtargetoptions['enable_nrt'] = True + if flags.auto_parallel: + subtargetoptions['auto_parallel'] = flags.auto_parallel + if flags.fastmath: + subtargetoptions['fastmath'] = flags.fastmath + error_model = callconv.create_error_model(flags.error_model, targetctx) + subtargetoptions['error_model'] = error_model + + return targetctx.subtarget(**subtargetoptions) + + +class CompilerBase(object): + """ + Stores and manages states for the compiler + """ + + def __init__(self, typingctx, targetctx, library, args, return_type, flags, + locals): + # Make sure the environment is reloaded + config.reload_config() + typingctx.refresh() + targetctx.refresh() + + self.state = StateDict() + + self.state.typingctx = typingctx + self.state.targetctx = _make_subtarget(targetctx, flags) + self.state.library = library + self.state.args = args + self.state.return_type = return_type + self.state.flags = flags + self.state.locals = locals + + # Results of various steps of the compilation pipeline + self.state.bc = None + self.state.func_id = None + self.state.func_ir = None + self.state.lifted = None + self.state.lifted_from = None + self.state.typemap = None + self.state.calltypes = None + self.state.type_annotation = None + # holds arbitrary inter-pipeline stage meta data + self.state.metadata = {} + self.state.reload_init = [] + # hold this for e.g. with_lifting, null out on exit + self.state.pipeline = self + + # parfor diagnostics info, add to metadata + self.state.parfor_diagnostics = ParforDiagnostics() + self.state.metadata['parfor_diagnostics'] = \ + self.state.parfor_diagnostics + self.state.metadata['parfors'] = {} + + self.state.status = _CompileStatus( + can_fallback=self.state.flags.enable_pyobject + ) + + def compile_extra(self, func): + self.state.func_id = bytecode.FunctionIdentity.from_function(func) + ExtractByteCode().run_pass(self.state) + + self.state.lifted = () + self.state.lifted_from = None + return self._compile_bytecode() + + def compile_ir(self, func_ir, lifted=(), lifted_from=None): + self.state.func_id = func_ir.func_id + self.state.lifted = lifted + self.state.lifted_from = lifted_from + self.state.func_ir = func_ir + self.state.nargs = self.state.func_ir.arg_count + + FixupArgs().run_pass(self.state) + return self._compile_ir() + + def define_pipelines(self): + """Child classes override this to customize the pipelines in use. + """ + raise NotImplementedError() + + def _compile_core(self): + """ + Populate and run compiler pipeline + """ + with ConfigStack().enter(self.state.flags.copy()): + pms = self.define_pipelines() + for pm in pms: + pipeline_name = pm.pipeline_name + func_name = "%s.%s" % (self.state.func_id.modname, + self.state.func_id.func_qualname) + + event("Pipeline: %s for %s" % (pipeline_name, func_name)) + self.state.metadata['pipeline_times'] = {pipeline_name: + pm.exec_times} + is_final_pipeline = pm == pms[-1] + res = None + try: + pm.run(self.state) + if self.state.cr is not None: + break + except _EarlyPipelineCompletion as e: + res = e.result + break + except Exception as e: + if not isinstance(e, errors.NumbaError): + raise e + self.state.status.fail_reason = e + if is_final_pipeline: + raise e + else: + raise CompilerError("All available pipelines exhausted") + + # Pipeline is done, remove self reference to release refs to user + # code + self.state.pipeline = None + + # organise a return + if res is not None: + # Early pipeline completion + return res + else: + assert self.state.cr is not None + return self.state.cr + + def _compile_bytecode(self): + """ + Populate and run pipeline for bytecode input + """ + assert self.state.func_ir is None + return self._compile_core() + + def _compile_ir(self): + """ + Populate and run pipeline for IR input + """ + assert self.state.func_ir is not None + return self._compile_core() + + +class Compiler(CompilerBase): + """The default compiler + """ + + def define_pipelines(self): + if self.state.flags.force_pyobject: + # either object mode + return [DefaultPassBuilder.define_objectmode_pipeline(self.state),] + else: + # or nopython mode + return [DefaultPassBuilder.define_nopython_pipeline(self.state),] + + +class DefaultPassBuilder(object): + """ + This is the default pass builder, it contains the "classic" default + pipelines as pre-canned PassManager instances: + - nopython + - objectmode + - interpreted + - typed + - untyped + - nopython lowering + """ + @staticmethod + def define_nopython_pipeline(state, name='nopython'): + """Returns an nopython mode pipeline based PassManager + """ + # compose pipeline from untyped, typed and lowering parts + dpb = DefaultPassBuilder + pm = PassManager(name) + untyped_passes = dpb.define_untyped_pipeline(state) + pm.passes.extend(untyped_passes.passes) + + typed_passes = dpb.define_typed_pipeline(state) + pm.passes.extend(typed_passes.passes) + + lowering_passes = dpb.define_nopython_lowering_pipeline(state) + pm.passes.extend(lowering_passes.passes) + + pm.finalize() + return pm + + @staticmethod + def define_nopython_lowering_pipeline(state, name='nopython_lowering'): + pm = PassManager(name) + # legalise + pm.add_pass(NoPythonSupportedFeatureValidation, + "ensure features that are in use are in a valid form") + pm.add_pass(IRLegalization, + "ensure IR is legal prior to lowering") + # Annotate only once legalized + pm.add_pass(AnnotateTypes, "annotate types") + # lower + if state.flags.auto_parallel.enabled: + pm.add_pass(NativeParforLowering, "native parfor lowering") + else: + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.add_pass(DumpParforDiagnostics, "dump parfor diagnostics") + pm.finalize() + return pm + + @staticmethod + def define_parfor_gufunc_nopython_lowering_pipeline( + state, name='parfor_gufunc_nopython_lowering'): + pm = PassManager(name) + # legalise + pm.add_pass(NoPythonSupportedFeatureValidation, + "ensure features that are in use are in a valid form") + pm.add_pass(IRLegalization, + "ensure IR is legal prior to lowering") + # Annotate only once legalized + pm.add_pass(AnnotateTypes, "annotate types") + # lower + if state.flags.auto_parallel.enabled: + pm.add_pass(NativeParforLowering, "native parfor lowering") + else: + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.finalize() + return pm + + @staticmethod + def define_typed_pipeline(state, name="typed"): + """Returns the typed part of the nopython pipeline""" + pm = PassManager(name) + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + # strip phis + pm.add_pass(PreLowerStripPhis, "remove phis nodes") + + # optimisation + pm.add_pass(InlineOverloads, "inline overloaded functions") + if state.flags.auto_parallel.enabled: + pm.add_pass(PreParforPass, "Preprocessing for parfors") + if not state.flags.no_rewrites: + pm.add_pass(NopythonRewrites, "nopython rewrites") + if state.flags.auto_parallel.enabled: + pm.add_pass(ParforPass, "convert to parfors") + pm.add_pass(ParforFusionPass, "fuse parfors") + pm.add_pass(ParforPreLoweringPass, "parfor prelowering") + + pm.finalize() + return pm + + @staticmethod + def define_parfor_gufunc_pipeline(state, name="parfor_gufunc_typed"): + """Returns the typed part of the nopython pipeline""" + pm = PassManager(name) + assert state.func_ir + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(NopythonTypeInference, "nopython frontend") + pm.add_pass(ParforPreLoweringPass, "parfor prelowering") + + pm.finalize() + return pm + + @staticmethod + def define_untyped_pipeline(state, name='untyped'): + """Returns an untyped part of the nopython pipeline""" + pm = PassManager(name) + if state.func_ir is None: + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(WithLifting, "Handle with contexts") + + # inline closures early in case they are using nonlocal's + # see issue #6585. + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + + # pre typing + if not state.flags.no_rewrites: + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(GenericRewrites, "nopython rewrites") + + pm.add_pass(RewriteDynamicRaises, "rewrite dynamic raises") + + # convert any remaining closures into functions + pm.add_pass(MakeFunctionToJitFunction, + "convert make_function into JIT functions") + # inline functions that have been determined as inlinable and rerun + # branch pruning, this needs to be run after closures are inlined as + # the IR repr of a closure masks call sites if an inlinable is called + # inside a closure + pm.add_pass(InlineInlinables, "inline inlinable functions") + if not state.flags.no_rewrites: + pm.add_pass(DeadBranchPrune, "dead branch pruning") + + pm.add_pass(FindLiterallyCalls, "find literally calls") + pm.add_pass(LiteralUnroll, "handles literal_unroll") + + if state.flags.enable_ssa: + pm.add_pass(ReconstructSSA, "ssa") + + if not state.flags.no_rewrites: + pm.add_pass(DeadBranchPrune, "dead branch pruning") + + pm.add_pass(LiteralPropagationSubPipelinePass, "Literal propagation") + + pm.finalize() + return pm + + @staticmethod + def define_objectmode_pipeline(state, name='object'): + """Returns an object-mode pipeline based PassManager + """ + pm = PassManager(name) + if state.func_ir is None: + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + else: + # Reaches here if it's a fallback from nopython mode. + # Strip the phi nodes. + pm.add_pass(PreLowerStripPhis, "remove phis nodes") + pm.add_pass(IRProcessing, "processing IR") + + # The following passes are needed to adjust for looplifting + pm.add_pass(CanonicalizeLoopEntry, "canonicalize loop entry") + pm.add_pass(CanonicalizeLoopExit, "canonicalize loop exit") + + pm.add_pass(ObjectModeFrontEnd, "object mode frontend") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # convert any remaining closures into functions + pm.add_pass(MakeFunctionToJitFunction, + "convert make_function into JIT functions") + pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering") + pm.add_pass(AnnotateTypes, "annotate types") + pm.add_pass(ObjectModeBackEnd, "object mode backend") + pm.finalize() + return pm + + +def compile_extra(typingctx, targetctx, func, args, return_type, flags, + locals, library=None, pipeline_class=Compiler): + """Compiler entry point + + Parameter + --------- + typingctx : + typing context + targetctx : + target context + func : function + the python function to be compiled + args : tuple, list + argument types + return_type : + Use ``None`` to indicate void return + flags : numba.compiler.Flags + compiler flags + library : numba.codegen.CodeLibrary + Used to store the compiled code. + If it is ``None``, a new CodeLibrary is used. + pipeline_class : type like numba.compiler.CompilerBase + compiler pipeline + """ + pipeline = pipeline_class(typingctx, targetctx, library, + args, return_type, flags, locals) + return pipeline.compile_extra(func) + + +def compile_ir(typingctx, targetctx, func_ir, args, return_type, flags, + locals, lifted=(), lifted_from=None, is_lifted_loop=False, + library=None, pipeline_class=Compiler): + """ + Compile a function with the given IR. + + For internal use only. + """ + + # This is a special branch that should only run on IR from a lifted loop + if is_lifted_loop: + # This code is pessimistic and costly, but it is a not often trodden + # path and it will go away once IR is made immutable. The problem is + # that the rewrite passes can mutate the IR into a state that makes + # it possible for invalid tokens to be transmitted to lowering which + # then trickle through into LLVM IR and causes RuntimeErrors as LLVM + # cannot compile it. As a result the following approach is taken: + # 1. Create some new flags that copy the original ones but switch + # off rewrites. + # 2. Compile with 1. to get a compile result + # 3. Try and compile another compile result but this time with the + # original flags (and IR being rewritten). + # 4. If 3 was successful, use the result, else use 2. + + # create flags with no rewrites + norw_flags = copy.deepcopy(flags) + norw_flags.no_rewrites = True + + def compile_local(the_ir, the_flags): + pipeline = pipeline_class(typingctx, targetctx, library, + args, return_type, the_flags, locals) + return pipeline.compile_ir(func_ir=the_ir, lifted=lifted, + lifted_from=lifted_from) + + # compile with rewrites off, IR shouldn't be mutated irreparably + norw_cres = compile_local(func_ir.copy(), norw_flags) + + # try and compile with rewrites on if no_rewrites was not set in the + # original flags, IR might get broken but we've got a CompileResult + # that's usable from above. + rw_cres = None + if not flags.no_rewrites: + # Suppress warnings in compilation retry + with warnings.catch_warnings(): + warnings.simplefilter("ignore", errors.NumbaWarning) + try: + rw_cres = compile_local(func_ir.copy(), flags) + except Exception: + pass + # if the rewrite variant of compilation worked, use it, else use + # the norewrites backup + if rw_cres is not None: + cres = rw_cres + else: + cres = norw_cres + return cres + + else: + pipeline = pipeline_class(typingctx, targetctx, library, + args, return_type, flags, locals) + return pipeline.compile_ir(func_ir=func_ir, lifted=lifted, + lifted_from=lifted_from) + + +def compile_internal(typingctx, targetctx, library, + func, args, return_type, flags, locals): + """ + For internal use only. + """ + pipeline = Compiler(typingctx, targetctx, library, + args, return_type, flags, locals) + return pipeline.compile_extra(func) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_lock.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..874fced9fd9924d549655b55caec96d7518182f4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_lock.py @@ -0,0 +1,56 @@ +import threading +import functools +import numba.core.event as ev + + +# Lock for the preventing multiple compiler execution +class _CompilerLock(object): + def __init__(self): + self._lock = threading.RLock() + + def acquire(self): + ev.start_event("numba:compiler_lock") + self._lock.acquire() + + def release(self): + self._lock.release() + ev.end_event("numba:compiler_lock") + + def __enter__(self): + self.acquire() + + def __exit__(self, exc_val, exc_type, traceback): + self.release() + + def is_locked(self): + is_owned = getattr(self._lock, '_is_owned') + if not callable(is_owned): + is_owned = self._is_owned + return is_owned() + + def __call__(self, func): + @functools.wraps(func) + def _acquire_compile_lock(*args, **kwargs): + with self: + return func(*args, **kwargs) + return _acquire_compile_lock + + def _is_owned(self): + # This method is borrowed from threading.Condition. + # Return True if lock is owned by current_thread. + # This method is called only if _lock doesn't have _is_owned(). + if self._lock.acquire(0): + self._lock.release() + return False + else: + return True + + +global_compiler_lock = _CompilerLock() + + +def require_global_compiler_lock(): + """Sentry that checks the global_compiler_lock is acquired. + """ + # Use assert to allow turning off this check + assert global_compiler_lock.is_locked() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_machinery.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_machinery.py new file mode 100644 index 0000000000000000000000000000000000000000..286d4d2ba0c1dbde623e3f9720eb6090d821796a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/compiler_machinery.py @@ -0,0 +1,462 @@ +import timeit +from abc import abstractmethod, ABCMeta +from collections import namedtuple, OrderedDict +import inspect + + +from numba.core.compiler_lock import global_compiler_lock +from numba.core import errors, config, transforms, utils +from numba.core.tracing import event +from numba.core.postproc import PostProcessor +from numba.core.ir_utils import enforce_no_dels, legalize_single_scope +import numba.core.event as ev + +# terminal color markup +_termcolor = errors.termcolor() + + +class SimpleTimer(object): + """ + A simple context managed timer + """ + + def __enter__(self): + self.ts = timeit.default_timer() + return self + + def __exit__(self, *exc): + self.elapsed = timeit.default_timer() - self.ts + + +class CompilerPass(metaclass=ABCMeta): + """ The base class for all compiler passes. + """ + + @abstractmethod + def __init__(self, *args, **kwargs): + self._analysis = None + self._pass_id = None + + @classmethod + def name(cls): + """ + Returns the name of the pass + """ + return cls._name + + @property + def pass_id(self): + """ + The ID of the pass + """ + return self._pass_id + + @pass_id.setter + def pass_id(self, val): + """ + Sets the ID of the pass + """ + self._pass_id = val + + @property + def analysis(self): + """ + Analysis data for the pass + """ + return self._analysis + + @analysis.setter + def analysis(self, val): + """ + Set the analysis data for the pass + """ + self._analysis = val + + def run_initialization(self, *args, **kwargs): + """ + Runs the initialization sequence for the pass, will run before + `run_pass`. + """ + return False + + @abstractmethod + def run_pass(self, *args, **kwargs): + """ + Runs the pass itself. Must return True/False depending on whether + statement level modification took place. + """ + pass + + def run_finalizer(self, *args, **kwargs): + """ + Runs the initialization sequence for the pass, will run before + `run_pass`. + """ + return False + + def get_analysis_usage(self, AU): + """ Override to set analysis usage + """ + pass + + def get_analysis(self, pass_name): + """ + Gets the analysis from a given pass + """ + return self._analysis[pass_name] + + +class SSACompliantMixin(object): + """ Mixin to indicate a pass is SSA form compliant. Nothing is asserted + about this condition at present. + """ + pass + + +class FunctionPass(CompilerPass): + """ Base class for function passes + """ + pass + + +class AnalysisPass(CompilerPass): + """ Base class for analysis passes (no modification made to state) + """ + pass + + +class LoweringPass(CompilerPass): + """ Base class for lowering passes + """ + pass + + +class AnalysisUsage(object): + """This looks and behaves like LLVM's AnalysisUsage because its like that. + """ + + def __init__(self): + self._required = set() + self._preserved = set() + + def get_required_set(self): + return self._required + + def get_preserved_set(self): + return self._preserved + + def add_required(self, pss): + self._required.add(pss) + + def add_preserved(self, pss): + self._preserved.add(pss) + + def __str__(self): + return "required: %s\n" % self._required + + +_DEBUG = False + + +def debug_print(*args, **kwargs): + if _DEBUG: + print(*args, **kwargs) + + +pass_timings = namedtuple('pass_timings', 'init run finalize') + + +class PassManager(object): + """ + The PassManager is a named instance of a particular compilation pipeline + """ + # TODO: Eventually enable this, it enforces self consistency after each pass + _ENFORCING = False + + def __init__(self, pipeline_name): + """ + Create a new pipeline with name "pipeline_name" + """ + self.passes = [] + self.exec_times = OrderedDict() + self._finalized = False + self._analysis = None + self._print_after = None + self.pipeline_name = pipeline_name + + def _validate_pass(self, pass_cls): + if (not (isinstance(pass_cls, str) or + (inspect.isclass(pass_cls) and + issubclass(pass_cls, CompilerPass)))): + msg = ("Pass must be referenced by name or be a subclass of a " + "CompilerPass. Have %s" % pass_cls) + raise TypeError(msg) + if isinstance(pass_cls, str): + pass_cls = _pass_registry.find_by_name(pass_cls) + else: + if not _pass_registry.is_registered(pass_cls): + raise ValueError("Pass %s is not registered" % pass_cls) + + def add_pass(self, pss, description=""): + """ + Append a pass to the PassManager's compilation pipeline + """ + self._validate_pass(pss) + func_desc_tuple = (pss, description) + self.passes.append(func_desc_tuple) + self._finalized = False + + def add_pass_after(self, pass_cls, location): + """ + Add a pass `pass_cls` to the PassManager's compilation pipeline after + the pass `location`. + """ + assert self.passes + self._validate_pass(pass_cls) + self._validate_pass(location) + for idx, (x, _) in enumerate(self.passes): + if x == location: + break + else: + raise ValueError("Could not find pass %s" % location) + self.passes.insert(idx + 1, (pass_cls, str(pass_cls))) + # if a pass has been added, it's not finalized + self._finalized = False + + def _debug_init(self): + # determine after which passes IR dumps should take place + def parse(conf_item): + print_passes = [] + if conf_item != "none": + if conf_item == "all": + print_passes = [x.name() for (x, _) in self.passes] + else: + # we don't validate whether the named passes exist in this + # pipeline the compiler may be used reentrantly and + # different pipelines may contain different passes + splitted = conf_item.split(',') + print_passes = [x.strip() for x in splitted] + return print_passes + ret = (parse(config.DEBUG_PRINT_AFTER), + parse(config.DEBUG_PRINT_BEFORE), + parse(config.DEBUG_PRINT_WRAP),) + return ret + + def finalize(self): + """ + Finalize the PassManager, after which no more passes may be added + without re-finalization. + """ + self._analysis = self.dependency_analysis() + self._print_after, self._print_before, self._print_wrap = \ + self._debug_init() + self._finalized = True + + @property + def finalized(self): + return self._finalized + + def _patch_error(self, desc, exc): + """ + Patches the error to show the stage that it arose in. + """ + newmsg = "{desc}\n{exc}".format(desc=desc, exc=exc) + exc.args = (newmsg,) + return exc + + @global_compiler_lock # this need a lock, likely calls LLVM + def _runPass(self, index, pss, internal_state): + mutated = False + + def check(func, compiler_state): + mangled = func(compiler_state) + if mangled not in (True, False): + msg = ("CompilerPass implementations should return True/False. " + "CompilerPass with name '%s' did not.") + raise ValueError(msg % pss.name()) + return mangled + + def debug_print(pass_name, print_condition, printable_condition): + if pass_name in print_condition: + fid = internal_state.func_id + args = (fid.modname, fid.func_qualname, self.pipeline_name, + printable_condition, pass_name) + print(("%s.%s: %s: %s %s" % args).center(120, '-')) + if internal_state.func_ir is not None: + internal_state.func_ir.dump() + else: + print("func_ir is None") + + # debug print before this pass? + debug_print(pss.name(), self._print_before + self._print_wrap, "BEFORE") + + # wire in the analysis info so it's accessible + pss.analysis = self._analysis + + qualname = internal_state.func_id.func_qualname + + ev_details = dict( + name=f"{pss.name()} [{qualname}]", + qualname=qualname, + module=internal_state.func_id.modname, + flags=utils._lazy_pformat(internal_state.flags.values()), + args=str(internal_state.args), + return_type=str(internal_state.return_type), + ) + errctx = errors.new_error_context("Pass {name}", name=pss.name()) + with ev.trigger_event("numba:run_pass", data=ev_details), errctx: + with SimpleTimer() as init_time: + mutated |= check(pss.run_initialization, internal_state) + with SimpleTimer() as pass_time: + mutated |= check(pss.run_pass, internal_state) + with SimpleTimer() as finalize_time: + mutated |= check(pss.run_finalizer, internal_state) + + # Check that if the pass is an instance of a FunctionPass that it hasn't + # emitted ir.Dels. + if isinstance(pss, FunctionPass): + enforce_no_dels(internal_state.func_ir) + + if self._ENFORCING: + # TODO: Add in self consistency enforcement for + # `func_ir._definitions` etc + if _pass_registry.get(pss.__class__).mutates_CFG: + if mutated: # block level changes, rebuild all + PostProcessor(internal_state.func_ir).run() + else: # CFG level changes rebuild CFG + internal_state.func_ir.blocks = transforms.canonicalize_cfg( + internal_state.func_ir.blocks) + # Check the func_ir has exactly one Scope instance + if not legalize_single_scope(internal_state.func_ir.blocks): + raise errors.CompilerError( + f"multiple scope in func_ir detected in {pss}", + ) + # inject runtimes + pt = pass_timings(init_time.elapsed, pass_time.elapsed, + finalize_time.elapsed) + self.exec_times["%s_%s" % (index, pss.name())] = pt + + # debug print after this pass? + debug_print(pss.name(), self._print_after + self._print_wrap, "AFTER") + + def run(self, state): + """ + Run the defined pipelines on the state. + """ + from numba.core.compiler import _EarlyPipelineCompletion + if not self.finalized: + raise RuntimeError("Cannot run non-finalised pipeline") + + # walk the passes and run them + for idx, (pss, pass_desc) in enumerate(self.passes): + try: + event("-- %s" % pass_desc) + pass_inst = _pass_registry.get(pss).pass_inst + if isinstance(pass_inst, CompilerPass): + self._runPass(idx, pass_inst, state) + else: + raise BaseException("Legacy pass in use") + except _EarlyPipelineCompletion as e: + raise e + except Exception as e: + if not isinstance(e, errors.NumbaError): + raise e + msg = "Failed in %s mode pipeline (step: %s)" % \ + (self.pipeline_name, pass_desc) + patched_exception = self._patch_error(msg, e) + raise patched_exception + + def dependency_analysis(self): + """ + Computes dependency analysis + """ + deps = dict() + for (pss, _) in self.passes: + x = _pass_registry.get(pss).pass_inst + au = AnalysisUsage() + x.get_analysis_usage(au) + deps[type(x)] = au + + requires_map = dict() + for k, v in deps.items(): + requires_map[k] = v.get_required_set() + + def resolve_requires(key, rmap): + def walk(lkey, rmap): + dep_set = rmap[lkey] if lkey in rmap else set() + if dep_set: + for x in dep_set: + dep_set |= (walk(x, rmap)) + return dep_set + else: + return set() + ret = set() + for k in key: + ret |= walk(k, rmap) + return ret + + dep_chain = dict() + for k, v in requires_map.items(): + dep_chain[k] = set(v) | (resolve_requires(v, requires_map)) + + return dep_chain + + +pass_info = namedtuple('pass_info', 'pass_inst mutates_CFG analysis_only') + + +class PassRegistry(object): + """ + Pass registry singleton class. + """ + + _id = 0 + + _registry = dict() + + def register(self, mutates_CFG, analysis_only): + def make_festive(pass_class): + assert not self.is_registered(pass_class) + assert not self._does_pass_name_alias(pass_class.name()) + pass_class.pass_id = self._id + self._id += 1 + self._registry[pass_class] = pass_info(pass_class(), mutates_CFG, + analysis_only) + return pass_class + return make_festive + + def is_registered(self, clazz): + return clazz in self._registry.keys() + + def get(self, clazz): + assert self.is_registered(clazz) + return self._registry[clazz] + + def _does_pass_name_alias(self, check): + for k, v in self._registry.items(): + if v.pass_inst.name == check: + return True + return False + + def find_by_name(self, class_name): + assert isinstance(class_name, str) + for k, v in self._registry.items(): + if v.pass_inst.name == class_name: + return v + else: + raise ValueError("No pass with name %s is registered" % class_name) + + def dump(self): + for k, v in self._registry.items(): + print("%s: %s" % (k, v)) + + +_pass_registry = PassRegistry() +del PassRegistry + + +""" +register_pass is used to register a compiler pass class for use with PassManager +instances. +""" +register_pass = _pass_registry.register diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/config.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a4a352cc49f669b1ce5cc5a87c57a2d4daacaa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/config.py @@ -0,0 +1,597 @@ +import platform +import sys +import os +import re +import shutil +import warnings +import traceback + +# YAML needed to use file based Numba config +try: + import yaml + _HAVE_YAML = True +except ImportError: + _HAVE_YAML = False + + +import llvmlite.binding as ll + + +IS_WIN32 = sys.platform.startswith('win32') +IS_OSX = sys.platform.startswith('darwin') +MACHINE_BITS = tuple.__itemsize__ * 8 +IS_32BITS = MACHINE_BITS == 32 +# Python version in (major, minor) tuple +PYVERSION = sys.version_info[:2] + +# this is the name of the user supplied configuration file +_config_fname = '.numba_config.yaml' + + +def _parse_cc(text): + """ + Parse CUDA compute capability version string. + """ + if not text: + return None + else: + m = re.match(r'(\d+)\.(\d+)', text) + if not m: + raise ValueError("Compute capability must be specified as a " + "string of \"major.minor\" where major " + "and minor are decimals") + grp = m.groups() + return int(grp[0]), int(grp[1]) + + +def _os_supports_avx(): + """ + Whether the current OS supports AVX, regardless of the CPU. + + This is necessary because the user may be running a very old Linux + kernel (e.g. CentOS 5) on a recent CPU. + """ + if (not sys.platform.startswith('linux') + or platform.machine() not in ('i386', 'i586', 'i686', 'x86_64')): + return True + # Executing the CPUID instruction may report AVX available even though + # the kernel doesn't support it, so parse /proc/cpuinfo instead. + try: + f = open('/proc/cpuinfo', 'r') + except OSError: + # If /proc isn't available, assume yes + return True + with f: + for line in f: + head, _, body = line.partition(':') + if head.strip() == 'flags' and 'avx' in body.split(): + return True + else: + return False + + +class _OptLevel(int): + """This class holds the "optimisation level" set in `NUMBA_OPT`. As this env + var can be an int or a string, but is almost always interpreted as an int, + this class subclasses int so as to get the common behaviour but stores the + actual value as a `_raw_value` member. The value "max" is a special case + and the property `is_opt_max` can be queried to find if the optimisation + level (supplied value at construction time) is "max".""" + + def __new__(cls, *args, **kwargs): + assert len(args) == 1 + (value,) = args + _int_value = 3 if value == 'max' else int(value) + # the int ctor is always called with an appropriate integer value + new = super().__new__(cls, _int_value, **kwargs) + # raw value is max or int + new._raw_value = value if value == 'max' else _int_value + return new + + @property + def is_opt_max(self): + """Returns True if the optimisation level is "max" False + otherwise.""" + return self._raw_value == "max" + + def __repr__(self): + if isinstance(self._raw_value, str): + arg = f"'{self._raw_value}'" + else: + arg = self._raw_value + return f"_OptLevel({arg})" + + +def _process_opt_level(opt_level): + + if opt_level not in ('0', '1', '2', '3', 'max'): + msg = ("Environment variable `NUMBA_OPT` is set to an unsupported " + f"value '{opt_level}', supported values are 0, 1, 2, 3, and " + "'max'") + raise ValueError(msg) + else: + return _OptLevel(opt_level) + + +class _EnvReloader(object): + + def __init__(self): + self.reset() + + def reset(self): + self.old_environ = {} + self.update(force=True) + + def update(self, force=False): + new_environ = {} + + # first check if there's a .numba_config.yaml and use values from that + if os.path.exists(_config_fname) and os.path.isfile(_config_fname): + if not _HAVE_YAML: + msg = ("A Numba config file is found but YAML parsing " + "capabilities appear to be missing. " + "To use this feature please install `pyyaml`. e.g. " + "`conda install pyyaml`.") + warnings.warn(msg) + else: + with open(_config_fname, 'rt') as f: + y_conf = yaml.safe_load(f) + if y_conf is not None: + for k, v in y_conf.items(): + new_environ['NUMBA_' + k.upper()] = v + + # clobber file based config with any locally defined env vars + for name, value in os.environ.items(): + if name.startswith('NUMBA_'): + new_environ[name] = value + # We update the config variables if at least one NUMBA environment + # variable was modified. This lets the user modify values + # directly in the config module without having them when + # reload_config() is called by the compiler. + if force or self.old_environ != new_environ: + self.process_environ(new_environ) + # Store a copy + self.old_environ = dict(new_environ) + + self.validate() + + def validate(self): + global CUDA_USE_NVIDIA_BINDING + + if CUDA_USE_NVIDIA_BINDING: # noqa: F821 + try: + import cuda # noqa: F401 + except ImportError as ie: + msg = ("CUDA Python bindings requested (the environment " + "variable NUMBA_CUDA_USE_NVIDIA_BINDING is set), " + f"but they are not importable: {ie.msg}.") + warnings.warn(msg) + + CUDA_USE_NVIDIA_BINDING = False + + if CUDA_PER_THREAD_DEFAULT_STREAM: # noqa: F821 + warnings.warn("PTDS support is handled by CUDA Python when " + "using the NVIDIA binding. Please set the " + "environment variable " + "CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAM to 1 " + "instead.") + + def process_environ(self, environ): + def _readenv(name, ctor, default): + value = environ.get(name) + if value is None: + return default() if callable(default) else default + try: + return ctor(value) + except Exception: + warnings.warn(f"Environment variable '{name}' is defined but " + f"its associated value '{value}' could not be " + "parsed.\nThe parse failed with exception:\n" + f"{traceback.format_exc()}", + RuntimeWarning) + return default + + def optional_str(x): + return str(x) if x is not None else None + + # developer mode produces full tracebacks, disables help instructions + DEVELOPER_MODE = _readenv("NUMBA_DEVELOPER_MODE", int, 0) + + # disable performance warnings, will switch of the generation of + # warnings of the class NumbaPerformanceWarning + DISABLE_PERFORMANCE_WARNINGS = _readenv( + "NUMBA_DISABLE_PERFORMANCE_WARNINGS", int, 0) + + # Flag to enable full exception reporting + FULL_TRACEBACKS = _readenv( + "NUMBA_FULL_TRACEBACKS", int, DEVELOPER_MODE) + + # Show help text when an error occurs + SHOW_HELP = _readenv("NUMBA_SHOW_HELP", int, 0) + + # The color scheme to use for error messages, default is no color + # just bold fonts in use. + COLOR_SCHEME = _readenv("NUMBA_COLOR_SCHEME", str, "no_color") + + # Whether to globally enable bounds checking. The default None means + # to use the value of the flag to @njit. 0 or 1 overrides the flag + # globally. + BOUNDSCHECK = _readenv("NUMBA_BOUNDSCHECK", int, None) + + # Whether to always warn about potential uninitialized variables + # because static controlflow analysis cannot find a definition + # in one or more of the incoming paths. + ALWAYS_WARN_UNINIT_VAR = _readenv( + "NUMBA_ALWAYS_WARN_UNINIT_VAR", int, 0, + ) + + # Whether to warn about kernel launches where the grid size will + # under utilize the GPU due to low occupancy. On by default. + CUDA_LOW_OCCUPANCY_WARNINGS = _readenv( + "NUMBA_CUDA_LOW_OCCUPANCY_WARNINGS", int, 1) + + # Whether to use the official CUDA Python API Bindings + CUDA_USE_NVIDIA_BINDING = _readenv( + "NUMBA_CUDA_USE_NVIDIA_BINDING", int, 0) + + # Debug flag to control compiler debug print + DEBUG = _readenv("NUMBA_DEBUG", int, 0) + + # DEBUG print IR after pass names + DEBUG_PRINT_AFTER = _readenv("NUMBA_DEBUG_PRINT_AFTER", str, "none") + + # DEBUG print IR before pass names + DEBUG_PRINT_BEFORE = _readenv("NUMBA_DEBUG_PRINT_BEFORE", str, "none") + + # DEBUG print IR before and after pass names + DEBUG_PRINT_WRAP = _readenv("NUMBA_DEBUG_PRINT_WRAP", str, "none") + + # Highlighting in intermediate dumps + HIGHLIGHT_DUMPS = _readenv("NUMBA_HIGHLIGHT_DUMPS", int, 0) + + # JIT Debug flag to trigger IR instruction print + DEBUG_JIT = _readenv("NUMBA_DEBUG_JIT", int, 0) + + # Enable debugging of front-end operation + # (up to and including IR generation) + DEBUG_FRONTEND = _readenv("NUMBA_DEBUG_FRONTEND", int, 0) + + # Enable debug prints in nrtdynmod and use of "safe" API functions + DEBUG_NRT = _readenv("NUMBA_DEBUG_NRT", int, 0) + + # Enable NRT statistics counters + NRT_STATS = _readenv("NUMBA_NRT_STATS", int, 0) + + # How many recently deserialized functions to retain regardless + # of external references + FUNCTION_CACHE_SIZE = _readenv("NUMBA_FUNCTION_CACHE_SIZE", int, 128) + + # Maximum tuple size that parfors will unpack and pass to + # internal gufunc. + PARFOR_MAX_TUPLE_SIZE = _readenv("NUMBA_PARFOR_MAX_TUPLE_SIZE", + int, 100) + + # Enable logging of cache operation + DEBUG_CACHE = _readenv("NUMBA_DEBUG_CACHE", int, DEBUG) + + # Redirect cache directory + # Contains path to the directory + CACHE_DIR = _readenv("NUMBA_CACHE_DIR", str, "") + + # Override default cache locators list including their order + # Comma separated list of locator class names, + # see _locator_classes in caching submodule + CACHE_LOCATOR_CLASSES = _readenv("NUMBA_CACHE_LOCATOR_CLASSES", str, "") + + # Enable tracing support + TRACE = _readenv("NUMBA_TRACE", int, 0) + + # Enable chrome tracing support + CHROME_TRACE = _readenv("NUMBA_CHROME_TRACE", str, "") + + # Enable debugging of type inference + DEBUG_TYPEINFER = _readenv("NUMBA_DEBUG_TYPEINFER", int, 0) + + # Disable caching of failed type inferences. + # Use this to isolate problems due to the fail cache. + DISABLE_TYPEINFER_FAIL_CACHE = _readenv( + "NUMBA_DISABLE_TYPEINFER_FAIL_CACHE", int, 0) + + # Configure compilation target to use the specified CPU name + # and CPU feature as the host information. + # Note: this overrides "host" option for AOT compilation. + CPU_NAME = _readenv("NUMBA_CPU_NAME", optional_str, None) + CPU_FEATURES = _readenv("NUMBA_CPU_FEATURES", optional_str, + ("" if str(CPU_NAME).lower() == 'generic' + else None)) + # Optimization level + OPT = _readenv("NUMBA_OPT", _process_opt_level, _OptLevel(3)) + + # Force dump of Python bytecode + DUMP_BYTECODE = _readenv("NUMBA_DUMP_BYTECODE", int, DEBUG_FRONTEND) + + # Force dump of control flow graph + DUMP_CFG = _readenv("NUMBA_DUMP_CFG", int, DEBUG_FRONTEND) + + # Force dump of Numba IR + DUMP_IR = _readenv("NUMBA_DUMP_IR", int, + DEBUG_FRONTEND) + + # Force dump of Numba IR in SSA form + DUMP_SSA = _readenv("NUMBA_DUMP_SSA", int, + DEBUG_FRONTEND or DEBUG_TYPEINFER) + + # print debug info of analysis and optimization on array operations + DEBUG_ARRAY_OPT = _readenv("NUMBA_DEBUG_ARRAY_OPT", int, 0) + + # insert debug stmts to print information at runtime + DEBUG_ARRAY_OPT_RUNTIME = _readenv( + "NUMBA_DEBUG_ARRAY_OPT_RUNTIME", int, 0) + + # print stats about parallel for-loops + DEBUG_ARRAY_OPT_STATS = _readenv("NUMBA_DEBUG_ARRAY_OPT_STATS", int, 0) + + # prints user friendly information about parallel + PARALLEL_DIAGNOSTICS = _readenv("NUMBA_PARALLEL_DIAGNOSTICS", int, 0) + + # print debug info of inline closure pass + DEBUG_INLINE_CLOSURE = _readenv("NUMBA_DEBUG_INLINE_CLOSURE", int, 0) + + # Force dump of LLVM IR + DUMP_LLVM = _readenv("NUMBA_DUMP_LLVM", int, DEBUG) + + # Force dump of Function optimized LLVM IR + DUMP_FUNC_OPT = _readenv("NUMBA_DUMP_FUNC_OPT", int, DEBUG) + + # Force dump of Optimized LLVM IR + DUMP_OPTIMIZED = _readenv("NUMBA_DUMP_OPTIMIZED", int, DEBUG) + + # Force disable loop vectorize + LOOP_VECTORIZE = _readenv("NUMBA_LOOP_VECTORIZE", int, 1) + + # Enable superword-level parallelism vectorization, default is off + # since #8705 (miscompilation). + SLP_VECTORIZE = _readenv("NUMBA_SLP_VECTORIZE", int, 0) + + # Force dump of generated assembly + DUMP_ASSEMBLY = _readenv("NUMBA_DUMP_ASSEMBLY", int, DEBUG) + + # Force dump of type annotation + ANNOTATE = _readenv("NUMBA_DUMP_ANNOTATION", int, 0) + + # Dump IR in such as way as to aid in "diff"ing. + DIFF_IR = _readenv("NUMBA_DIFF_IR", int, 0) + + # Dump type annotation in html format + def fmt_html_path(path): + if path is None: + return path + else: + return os.path.abspath(path) + + HTML = _readenv("NUMBA_DUMP_HTML", fmt_html_path, None) + + # x86-64 specific + # Enable AVX on supported platforms where it won't degrade performance. + def avx_default(): + if not _os_supports_avx(): + return False + else: + # There are various performance issues with AVX and LLVM + # on some CPUs (list at + # http://llvm.org/bugs/buglist.cgi?quicksearch=avx). + # For now we'd rather disable it, since it can pessimize code + cpu_name = CPU_NAME or ll.get_host_cpu_name() + disabled_cpus = {'corei7-avx', 'core-avx-i', + 'sandybridge', 'ivybridge'} + # Disable known baseline CPU names that virtual machines may + # incorrectly report as having AVX support. + # This can cause problems with the SVML-pass's use of AVX512. + # See https://github.com/numba/numba/issues/9582 + disabled_cpus |= {'nocona'} + return cpu_name not in disabled_cpus + + ENABLE_AVX = _readenv("NUMBA_ENABLE_AVX", int, avx_default) + + # if set and SVML is available, it will be disabled + # By default, it's disabled on 32-bit platforms. + DISABLE_INTEL_SVML = _readenv( + "NUMBA_DISABLE_INTEL_SVML", int, IS_32BITS) + + # Disable jit for debugging + DISABLE_JIT = _readenv("NUMBA_DISABLE_JIT", int, 0) + + # choose parallel backend to use + THREADING_LAYER_PRIORITY = _readenv( + "NUMBA_THREADING_LAYER_PRIORITY", + lambda string: string.split(), + ['tbb', 'omp', 'workqueue'], + ) + THREADING_LAYER = _readenv("NUMBA_THREADING_LAYER", str, 'default') + + # CUDA Configs + + # Whether to warn about kernel launches where a host array + # is used as a parameter, forcing a copy to and from the device. + # On by default. + CUDA_WARN_ON_IMPLICIT_COPY = _readenv( + "NUMBA_CUDA_WARN_ON_IMPLICIT_COPY", int, 1) + + # Force CUDA compute capability to a specific version + FORCE_CUDA_CC = _readenv("NUMBA_FORCE_CUDA_CC", _parse_cc, None) + + # The default compute capability to target when compiling to PTX. + CUDA_DEFAULT_PTX_CC = _readenv("NUMBA_CUDA_DEFAULT_PTX_CC", _parse_cc, + (5, 0)) + + # Disable CUDA support + DISABLE_CUDA = _readenv("NUMBA_DISABLE_CUDA", + int, int(MACHINE_BITS == 32)) + + # Enable CUDA simulator + ENABLE_CUDASIM = _readenv("NUMBA_ENABLE_CUDASIM", int, 0) + + # CUDA logging level + # Any level name from the *logging* module. Case insensitive. + # Defaults to CRITICAL if not set or invalid. + # Note: This setting only applies when logging is not configured. + # Any existing logging configuration is preserved. + CUDA_LOG_LEVEL = _readenv("NUMBA_CUDA_LOG_LEVEL", str, '') + + # Include argument values in the CUDA Driver API logs + CUDA_LOG_API_ARGS = _readenv("NUMBA_CUDA_LOG_API_ARGS", int, 0) + + # Maximum number of pending CUDA deallocations (default: 10) + CUDA_DEALLOCS_COUNT = _readenv("NUMBA_CUDA_MAX_PENDING_DEALLOCS_COUNT", + int, 10) + + # Maximum ratio of pending CUDA deallocations to capacity (default: 0.2) + CUDA_DEALLOCS_RATIO = _readenv("NUMBA_CUDA_MAX_PENDING_DEALLOCS_RATIO", + float, 0.2) + + CUDA_ARRAY_INTERFACE_SYNC = _readenv("NUMBA_CUDA_ARRAY_INTERFACE_SYNC", + int, 1) + + # Path of the directory that the CUDA driver libraries are located + CUDA_DRIVER = _readenv("NUMBA_CUDA_DRIVER", str, '') + + # Buffer size for logs produced by CUDA driver operations (e.g. + # linking) + CUDA_LOG_SIZE = _readenv("NUMBA_CUDA_LOG_SIZE", int, 1024) + + # Whether to generate verbose log messages when JIT linking + CUDA_VERBOSE_JIT_LOG = _readenv("NUMBA_CUDA_VERBOSE_JIT_LOG", int, 1) + + # Whether the default stream is the per-thread default stream + CUDA_PER_THREAD_DEFAULT_STREAM = _readenv( + "NUMBA_CUDA_PER_THREAD_DEFAULT_STREAM", int, 0) + + CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY = _readenv( + "NUMBA_CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY", int, 0) + + # Location of the CUDA include files + if IS_WIN32: + cuda_path = os.environ.get('CUDA_PATH') + if cuda_path: + default_cuda_include_path = os.path.join(cuda_path, "include") + else: + default_cuda_include_path = "cuda_include_not_found" + else: + default_cuda_include_path = os.path.join(os.sep, 'usr', 'local', + 'cuda', 'include') + CUDA_INCLUDE_PATH = _readenv("NUMBA_CUDA_INCLUDE_PATH", str, + default_cuda_include_path) + + # Threading settings + + # The default number of threads to use. + def num_threads_default(): + try: + sched_getaffinity = os.sched_getaffinity + except AttributeError: + pass + else: + return max(1, len(sched_getaffinity(0))) + + cpu_count = os.cpu_count() + if cpu_count is not None: + return max(1, cpu_count) + + return 1 + + NUMBA_DEFAULT_NUM_THREADS = num_threads_default() + + # Numba thread pool size (defaults to number of CPUs on the system). + _NUMBA_NUM_THREADS = _readenv("NUMBA_NUM_THREADS", int, + NUMBA_DEFAULT_NUM_THREADS) + if ('NUMBA_NUM_THREADS' in globals() + and globals()['NUMBA_NUM_THREADS'] != _NUMBA_NUM_THREADS): + + from numba.np.ufunc import parallel + if parallel._is_initialized: + raise RuntimeError("Cannot set NUMBA_NUM_THREADS to a " + "different value once the threads have been " + "launched (currently have %s, " + "trying to set %s)" % + (_NUMBA_NUM_THREADS, + globals()['NUMBA_NUM_THREADS'])) + + NUMBA_NUM_THREADS = _NUMBA_NUM_THREADS + del _NUMBA_NUM_THREADS + + # sys.monitoring support + ENABLE_SYS_MONITORING = _readenv("NUMBA_ENABLE_SYS_MONITORING", + int, 0) + + # Profiling support + + # Indicates if a profiler detected. Only VTune can be detected for now + RUNNING_UNDER_PROFILER = 'VS_PROFILER' in os.environ + + # Enables jit events in LLVM to support profiling of dynamic code + ENABLE_PROFILING = _readenv( + "NUMBA_ENABLE_PROFILING", int, int(RUNNING_UNDER_PROFILER)) + + # Debug Info + + # The default value for the `debug` flag + DEBUGINFO_DEFAULT = _readenv("NUMBA_DEBUGINFO", int, ENABLE_PROFILING) + CUDA_DEBUGINFO_DEFAULT = _readenv("NUMBA_CUDA_DEBUGINFO", int, 0) + + EXTEND_VARIABLE_LIFETIMES = _readenv("NUMBA_EXTEND_VARIABLE_LIFETIMES", + int, 0) + + # gdb binary location + def which_gdb(path_or_bin): + gdb = shutil.which(path_or_bin) + return gdb if gdb is not None else path_or_bin + + GDB_BINARY = _readenv("NUMBA_GDB_BINARY", which_gdb, 'gdb') + + # CUDA Memory management + CUDA_MEMORY_MANAGER = _readenv("NUMBA_CUDA_MEMORY_MANAGER", str, + 'default') + + # Experimental refprune pass + LLVM_REFPRUNE_PASS = _readenv( + "NUMBA_LLVM_REFPRUNE_PASS", int, 1, + ) + LLVM_REFPRUNE_FLAGS = _readenv( + "NUMBA_LLVM_REFPRUNE_FLAGS", str, + "all" if LLVM_REFPRUNE_PASS else "", + ) + + # llvmlite memory manager + USE_LLVMLITE_MEMORY_MANAGER = _readenv( + "NUMBA_USE_LLVMLITE_MEMORY_MANAGER", int, None + ) + + # Timing support. + + # LLVM_PASS_TIMINGS enables LLVM recording of pass timings. + LLVM_PASS_TIMINGS = _readenv( + "NUMBA_LLVM_PASS_TIMINGS", int, 0, + ) + + # Coverage support. + + # JIT_COVERAGE (bool) controls whether the compiler report compiled + # lines to coverage tools. Defaults to off. + JIT_COVERAGE = _readenv( + "NUMBA_JIT_COVERAGE", int, 0, + ) + + # Inject the configuration values into the module globals + for name, value in locals().copy().items(): + if name.isupper(): + globals()[name] = value + + +_env_reloader = _EnvReloader() + + +def reload_config(): + """ + Reload the configuration from environment variables, if necessary. + """ + _env_reloader.update() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/consts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/consts.py new file mode 100644 index 0000000000000000000000000000000000000000..d062b320893e5902ff828f68bc7d8b4221a8a9a1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/consts.py @@ -0,0 +1,118 @@ +from types import ModuleType + +import weakref + +from numba.core.errors import ConstantInferenceError, NumbaError +from numba.core import ir + + +class ConstantInference(object): + """ + A constant inference engine for a given interpreter. + Inference inspects the IR to try and compute a compile-time constant for + a variable. + + This shouldn't be used directly, instead call Interpreter.infer_constant(). + """ + + def __init__(self, func_ir): + # Avoid cyclic references as some user-visible objects may be + # held alive in the cache + self._func_ir = weakref.proxy(func_ir) + self._cache = {} + + def infer_constant(self, name, loc=None): + """ + Infer a constant value for the given variable *name*. + If no value can be inferred, numba.errors.ConstantInferenceError + is raised. + """ + if name not in self._cache: + try: + self._cache[name] = (True, self._do_infer(name)) + except ConstantInferenceError as exc: + # Store the exception args only, to avoid keeping + # a whole traceback alive. + self._cache[name] = (False, (exc.__class__, exc.args)) + success, val = self._cache[name] + if success: + return val + else: + exc, args = val + if issubclass(exc, NumbaError): + raise exc(*args, loc=loc) + else: + raise exc(*args) + + def _fail(self, val): + # The location here is set to None because `val` is the ir.Var name + # and not the actual offending use of the var. When this is raised it is + # caught in the flow control of `infer_constant` and the class and args + # (the message) are captured and then raised again but with the location + # set to the expression that caused the constant inference error. + raise ConstantInferenceError( + "Constant inference not possible for: %s" % (val,), loc=None) + + def _do_infer(self, name): + if not isinstance(name, str): + raise TypeError("infer_constant() called with non-str %r" + % (name,)) + try: + defn = self._func_ir.get_definition(name) + except KeyError: + raise ConstantInferenceError( + "no single definition for %r" % (name,)) + try: + const = defn.infer_constant() + except ConstantInferenceError: + if isinstance(defn, ir.Expr): + return self._infer_expr(defn) + self._fail(defn) + return const + + def _infer_expr(self, expr): + # Infer an expression: handle supported cases + if expr.op == 'call': + func = self.infer_constant(expr.func.name, loc=expr.loc) + return self._infer_call(func, expr) + elif expr.op == 'getattr': + value = self.infer_constant(expr.value.name, loc=expr.loc) + return self._infer_getattr(value, expr) + elif expr.op == 'build_list': + return [self.infer_constant(i.name, loc=expr.loc) for i in + expr.items] + elif expr.op == 'build_tuple': + return tuple(self.infer_constant(i.name, loc=expr.loc) for i in + expr.items) + self._fail(expr) + + def _infer_call(self, func, expr): + if expr.kws or expr.vararg: + self._fail(expr) + # Check supported callables + _slice = func in (slice,) + _exc = isinstance(func, type) and issubclass(func, BaseException) + if _slice or _exc: + args = [self.infer_constant(a.name, loc=expr.loc) for a in + expr.args] + if _slice: + return func(*args) + elif _exc: + # If the exception class is user defined it may implement a ctor + # that does not pass the args to the super. Therefore return the + # raw class and the args so this can be instantiated at the call + # site in the way the user source expects it to be. + return func, args + else: + assert 0, 'Unreachable' + + self._fail(expr) + + def _infer_getattr(self, value, expr): + if isinstance(value, (ModuleType, type)): + # Allow looking up a constant on a class or module + try: + return getattr(value, expr.attr) + except AttributeError: + pass + self._fail(expr) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/controlflow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/controlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..32a0f2d7e194deeba5161247bc964237e0814809 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/controlflow.py @@ -0,0 +1,979 @@ +import collections +import functools +import sys + +from numba.core.ir import Loc +from numba.core.errors import UnsupportedError +from numba.core.utils import PYVERSION + +# List of bytecodes creating a new block in the control flow graph +# (in addition to explicit jump labels). +if PYVERSION in ((3, 14),): + NEW_BLOCKERS = frozenset([ + 'SETUP_LOOP', 'FOR_ITER', 'SETUP_WITH', 'BEFORE_WITH', 'LOAD_SPECIAL' + ]) +elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + NEW_BLOCKERS = frozenset([ + 'SETUP_LOOP', 'FOR_ITER', 'SETUP_WITH', 'BEFORE_WITH' + ]) +else: + raise NotImplementedError(PYVERSION) + + +class CFBlock(object): + + def __init__(self, offset): + self.offset = offset + self.body = [] + # A map of jumps to outgoing blocks (successors): + # { offset of outgoing block -> number of stack pops } + self.outgoing_jumps = {} + # A map of jumps to incoming blocks (predecessors): + # { offset of incoming block -> number of stack pops } + self.incoming_jumps = {} + self.terminating = False + + def __repr__(self): + args = (self.offset, + sorted(self.outgoing_jumps), + sorted(self.incoming_jumps)) + return "block(offset:%d, outgoing: %s, incoming: %s)" % args + + def __iter__(self): + return iter(self.body) + + +class Loop(collections.namedtuple("Loop", + ("entries", "exits", "header", "body"))): + """ + A control flow loop, as detected by a CFGraph object. + """ + + __slots__ = () + + # The loop header is enough to detect that two loops are really + # the same, assuming they belong to the same graph. + # (note: in practice, only one loop instance is created per graph + # loop, so identity would be fine) + + def __eq__(self, other): + return isinstance(other, Loop) and other.header == self.header + + def __hash__(self): + return hash(self.header) + + +class _DictOfContainers(collections.defaultdict): + """A defaultdict with customized equality checks that ignore empty values. + + Non-empty value is checked by: `bool(value_item) == True`. + """ + + def __eq__(self, other): + if isinstance(other, _DictOfContainers): + mine = self._non_empty_items() + theirs = other._non_empty_items() + return mine == theirs + + return NotImplemented + + def __ne__(self, other): + ret = self.__eq__(other) + if ret is NotImplemented: + return ret + else: + return not ret + + def _non_empty_items(self): + return [(k, vs) for k, vs in sorted(self.items()) if vs] + + +class CFGraph(object): + """ + Generic (almost) implementation of a Control Flow Graph. + """ + + def __init__(self): + self._nodes = set() + self._preds = _DictOfContainers(set) + self._succs = _DictOfContainers(set) + self._edge_data = {} + self._entry_point = None + + def add_node(self, node): + """ + Add *node* to the graph. This is necessary before adding any + edges from/to the node. *node* can be any hashable object. + """ + self._nodes.add(node) + + def add_edge(self, src, dest, data=None): + """ + Add an edge from node *src* to node *dest*, with optional + per-edge *data*. + If such an edge already exists, it is replaced (duplicate edges + are not possible). + """ + if src not in self._nodes: + raise ValueError("Cannot add edge as src node %s not in nodes %s" % + (src, self._nodes)) + if dest not in self._nodes: + raise ValueError("Cannot add edge as dest node %s not in nodes %s" % + (dest, self._nodes)) + self._add_edge(src, dest, data) + + def successors(self, src): + """ + Yield (node, data) pairs representing the successors of node *src*. + (*data* will be None if no data was specified when adding the edge) + """ + for dest in self._succs[src]: + yield dest, self._edge_data[src, dest] + + def predecessors(self, dest): + """ + Yield (node, data) pairs representing the predecessors of node *dest*. + (*data* will be None if no data was specified when adding the edge) + """ + for src in self._preds[dest]: + yield src, self._edge_data[src, dest] + + def set_entry_point(self, node): + """ + Set the entry point of the graph to *node*. + """ + assert node in self._nodes + self._entry_point = node + + def process(self): + """ + Compute essential properties of the control flow graph. The graph + must have been fully populated, and its entry point specified. Other + graph properties are computed on-demand. + """ + if self._entry_point is None: + raise RuntimeError("no entry point defined!") + self._eliminate_dead_blocks() + + def dominators(self): + """ + Return a dictionary of {node -> set(nodes)} mapping each node to + the nodes dominating it. + + A node D dominates a node N when any path leading to N must go through D + """ + return self._doms + + def post_dominators(self): + """ + Return a dictionary of {node -> set(nodes)} mapping each node to + the nodes post-dominating it. + + A node P post-dominates a node N when any path starting from N must go + through P. + """ + return self._post_doms + + def immediate_dominators(self): + """ + Return a dictionary of {node -> node} mapping each node to its + immediate dominator (idom). + + The idom(B) is the closest strict dominator of V + """ + return self._idom + + def dominance_frontier(self): + """ + Return a dictionary of {node -> set(nodes)} mapping each node to + the nodes in its dominance frontier. + + The dominance frontier _df(N) is the set of all nodes that are + immediate successors to blocks dominated by N but which aren't + strictly dominated by N + """ + return self._df + + def dominator_tree(self): + """ + return a dictionary of {node -> set(nodes)} mapping each node to + the set of nodes it immediately dominates + + The domtree(B) is the closest strict set of nodes that B dominates + """ + return self._domtree + + @functools.cached_property + def _exit_points(self): + return self._find_exit_points() + + @functools.cached_property + def _doms(self): + return self._find_dominators() + + @functools.cached_property + def _back_edges(self): + return self._find_back_edges() + + @functools.cached_property + def _topo_order(self): + return self._find_topo_order() + + @functools.cached_property + def _descs(self): + return self._find_descendents() + + @functools.cached_property + def _loops(self): + return self._find_loops() + + @functools.cached_property + def _in_loops(self): + return self._find_in_loops() + + @functools.cached_property + def _post_doms(self): + return self._find_post_dominators() + + @functools.cached_property + def _idom(self): + return self._find_immediate_dominators() + + @functools.cached_property + def _df(self): + return self._find_dominance_frontier() + + @functools.cached_property + def _domtree(self): + return self._find_dominator_tree() + + def descendents(self, node): + """ + Return the set of descendents of the given *node*, in topological + order (ignoring back edges). + """ + return self._descs[node] + + def entry_point(self): + """ + Return the entry point node. + """ + assert self._entry_point is not None + return self._entry_point + + def exit_points(self): + """ + Return the computed set of exit nodes (may be empty). + """ + return self._exit_points + + def backbone(self): + """ + Return the set of nodes constituting the graph's backbone. + (i.e. the nodes that every path starting from the entry point + must go through). By construction, it is non-empty: it contains + at least the entry point. + """ + return self._post_doms[self._entry_point] + + def loops(self): + """ + Return a dictionary of {node -> loop} mapping each loop header + to the loop (a Loop instance) starting with it. + """ + return self._loops + + def in_loops(self, node): + """ + Return the list of Loop objects the *node* belongs to, + from innermost to outermost. + """ + return [self._loops[x] for x in self._in_loops.get(node, ())] + + def dead_nodes(self): + """ + Return the set of dead nodes (eliminated from the graph). + """ + return self._dead_nodes + + def nodes(self): + """ + Return the set of live nodes. + """ + return self._nodes + + def topo_order(self): + """ + Return the sequence of nodes in topological order (ignoring back + edges). + """ + return self._topo_order + + def topo_sort(self, nodes, reverse=False): + """ + Iterate over the *nodes* in topological order (ignoring back edges). + The sort isn't guaranteed to be stable. + """ + nodes = set(nodes) + it = self._topo_order + if reverse: + it = reversed(it) + for n in it: + if n in nodes: + yield n + + def dump(self, file=None): + """ + Dump extensive debug information. + """ + import pprint + file = file or sys.stdout + if 1: + print("CFG adjacency lists:", file=file) + self._dump_adj_lists(file) + print("CFG dominators:", file=file) + pprint.pprint(self._doms, stream=file) + print("CFG post-dominators:", file=file) + pprint.pprint(self._post_doms, stream=file) + print("CFG back edges:", sorted(self._back_edges), file=file) + print("CFG loops:", file=file) + pprint.pprint(self._loops, stream=file) + print("CFG node-to-loops:", file=file) + pprint.pprint(self._in_loops, stream=file) + print("CFG backbone:", file=file) + pprint.pprint(self.backbone(), stream=file) + + def render_dot(self, filename="numba_cfg.dot"): + """Render the controlflow graph with GraphViz DOT via the + ``graphviz`` python binding. + + Returns + ------- + g : graphviz.Digraph + Use `g.view()` to open the graph in the default PDF application. + """ + + try: + import graphviz as gv + except ImportError: + raise ImportError( + "The feature requires `graphviz` but it is not available. " + "Please install with `pip install graphviz`" + ) + g = gv.Digraph(filename=filename) + # Populate the nodes + for n in self._nodes: + g.node(str(n)) + # Populate the edges + for n in self._nodes: + for edge in self._succs[n]: + g.edge(str(n), str(edge)) + return g + + # Internal APIs + + def _add_edge(self, from_, to, data=None): + # This internal version allows adding edges to/from unregistered + # (ghost) nodes. + self._preds[to].add(from_) + self._succs[from_].add(to) + self._edge_data[from_, to] = data + + def _remove_node_edges(self, node): + for succ in self._succs.pop(node, ()): + self._preds[succ].remove(node) + del self._edge_data[node, succ] + for pred in self._preds.pop(node, ()): + self._succs[pred].remove(node) + del self._edge_data[pred, node] + + def _dfs(self, entries=None): + if entries is None: + entries = (self._entry_point,) + seen = set() + stack = list(entries) + while stack: + node = stack.pop() + if node not in seen: + yield node + seen.add(node) + for succ in self._succs[node]: + stack.append(succ) + + def _eliminate_dead_blocks(self): + """ + Eliminate all blocks not reachable from the entry point, and + stash them into self._dead_nodes. + """ + live = set() + for node in self._dfs(): + live.add(node) + self._dead_nodes = self._nodes - live + self._nodes = live + # Remove all edges leading from dead nodes + for dead in self._dead_nodes: + self._remove_node_edges(dead) + + def _find_exit_points(self): + """ + Compute the graph's exit points. + """ + exit_points = set() + for n in self._nodes: + if not self._succs.get(n): + exit_points.add(n) + return exit_points + + def _find_postorder(self): + succs = self._succs + back_edges = self._back_edges + post_order = [] + seen = set() + + post_order = [] + + # DFS + def dfs_rec(node): + if node not in seen: + seen.add(node) + stack.append((post_order.append, node)) + for dest in succs[node]: + if (node, dest) not in back_edges: + stack.append((dfs_rec, dest)) + + stack = [(dfs_rec, self._entry_point)] + while stack: + cb, data = stack.pop() + cb(data) + + return post_order + + def _find_immediate_dominators(self): + # The algorithm implemented computes the immediate dominator + # for each node in the CFG which is equivalent to build a dominator tree + # Based on the implementation from NetworkX + # library - nx.immediate_dominators + # https://github.com/networkx/networkx/blob/858e7cb183541a78969fed0cbcd02346f5866c02/networkx/algorithms/dominance.py # noqa: E501 + # References: + # Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy + # A Simple, Fast Dominance Algorithm + # https://www.cs.rice.edu/~keith/EMBED/dom.pdf + def intersect(u, v): + while u != v: + while idx[u] < idx[v]: + u = idom[u] + while idx[u] > idx[v]: + v = idom[v] + return u + + entry = self._entry_point + preds_table = self._preds + + order = self._find_postorder() + idx = {e: i for i, e in enumerate(order)} # index of each node + idom = {entry : entry} + order.pop() + order.reverse() + + changed = True + while changed: + changed = False + for u in order: + new_idom = functools.reduce(intersect, + (v for v in preds_table[u] + if v in idom)) + if u not in idom or idom[u] != new_idom: + idom[u] = new_idom + changed = True + + return idom + + def _find_dominator_tree(self): + idom = self._idom + domtree = _DictOfContainers(set) + + for u, v in idom.items(): + # v dominates u + if u not in domtree: + domtree[u] = set() + if u != v: + domtree[v].add(u) + + return domtree + + def _find_dominance_frontier(self): + idom = self._idom + preds_table = self._preds + df = {u: set() for u in idom} + + for u in idom: + if len(preds_table[u]) < 2: + continue + for v in preds_table[u]: + while v != idom[u]: + df[v].add(u) + v = idom[v] + + return df + + def _find_dominators_internal(self, post=False): + # See theoretical description in + # http://en.wikipedia.org/wiki/Dominator_%28graph_theory%29 + # The algorithm implemented here uses a todo-list as described + # in http://pages.cs.wisc.edu/~fischer/cs701.f08/finding.loops.html + if post: + entries = set(self._exit_points) + preds_table = self._succs + succs_table = self._preds + else: + entries = set([self._entry_point]) + preds_table = self._preds + succs_table = self._succs + + if not entries: + raise RuntimeError("no entry points: dominator algorithm " + "cannot be seeded") + + doms = {} + for e in entries: + doms[e] = set([e]) + + todo = [] + for n in self._nodes: + if n not in entries: + doms[n] = set(self._nodes) + todo.append(n) + + while todo: + n = todo.pop() + if n in entries: + continue + new_doms = set([n]) + preds = preds_table[n] + if preds: + new_doms |= functools.reduce(set.intersection, + [doms[p] for p in preds]) + if new_doms != doms[n]: + assert len(new_doms) < len(doms[n]) + doms[n] = new_doms + todo.extend(succs_table[n]) + return doms + + def _find_dominators(self): + return self._find_dominators_internal(post=False) + + def _find_post_dominators(self): + # To handle infinite loops correctly, we need to add a dummy + # exit point, and link members of infinite loops to it. + dummy_exit = object() + self._exit_points.add(dummy_exit) + for loop in self._loops.values(): + if not loop.exits: + for b in loop.body: + self._add_edge(b, dummy_exit) + pdoms = self._find_dominators_internal(post=True) + # Fix the _post_doms table to make no reference to the dummy exit + del pdoms[dummy_exit] + for doms in pdoms.values(): + doms.discard(dummy_exit) + self._remove_node_edges(dummy_exit) + self._exit_points.remove(dummy_exit) + return pdoms + + # Finding loops and back edges: see + # http://pages.cs.wisc.edu/~fischer/cs701.f08/finding.loops.html + + def _find_back_edges(self, stats=None): + """ + Find back edges. An edge (src, dest) is a back edge if and + only if *dest* dominates *src*. + """ + # Prepare stats to capture execution information + if stats is not None: + if not isinstance(stats, dict): + raise TypeError(f"*stats* must be a dict; got {type(stats)}") + stats.setdefault('iteration_count', 0) + + # Uses a simple DFS to find back-edges. + # The new algorithm is faster than the previous dominator based + # algorithm. + back_edges = set() + # stack: keeps track of the traversal path + stack = [] + # succs_state: keep track of unvisited successors of a node + succs_state = {} + entry_point = self.entry_point() + + checked = set() + + def push_state(node): + stack.append(node) + succs_state[node] = [dest for dest in self._succs[node]] + + push_state(entry_point) + + # Keep track for iteration count for debugging + iter_ct = 0 + while stack: + iter_ct += 1 + tos = stack[-1] + tos_succs = succs_state[tos] + # Are there successors not checked? + if tos_succs: + # Check the next successor + cur_node = tos_succs.pop() + # Is it in our traversal path? + if cur_node in stack: + # Yes, it's a backedge + back_edges.add((tos, cur_node)) + elif cur_node not in checked: + # Push + push_state(cur_node) + else: + # Checked all successors. Pop + stack.pop() + checked.add(tos) + + if stats is not None: + stats['iteration_count'] += iter_ct + return back_edges + + def _find_topo_order(self): + succs = self._succs + back_edges = self._back_edges + post_order = [] + seen = set() + + def _dfs_rec(node): + if node not in seen: + seen.add(node) + for dest in succs[node]: + if (node, dest) not in back_edges: + _dfs_rec(dest) + post_order.append(node) + + _dfs_rec(self._entry_point) + post_order.reverse() + return post_order + + def _find_descendents(self): + descs = {} + for node in reversed(self._topo_order): + descs[node] = node_descs = set() + for succ in self._succs[node]: + if (node, succ) not in self._back_edges: + node_descs.add(succ) + node_descs.update(descs[succ]) + return descs + + def _find_loops(self): + """ + Find the loops defined by the graph's back edges. + """ + bodies = {} + for src, dest in self._back_edges: + # The destination of the back edge is the loop header + header = dest + # Build up the loop body from the back edge's source node, + # up to the source header. + body = set([header]) + queue = [src] + while queue: + n = queue.pop() + if n not in body: + body.add(n) + queue.extend(self._preds[n]) + # There can be several back edges to a given loop header; + # if so, merge the resulting body fragments. + if header in bodies: + bodies[header].update(body) + else: + bodies[header] = body + + # Create a Loop object for each header. + loops = {} + for header, body in bodies.items(): + entries = set() + exits = set() + for n in body: + entries.update(self._preds[n] - body) + exits.update(self._succs[n] - body) + loop = Loop(header=header, body=body, entries=entries, exits=exits) + loops[header] = loop + return loops + + def _find_in_loops(self): + loops = self._loops + # Compute the loops to which each node belongs. + in_loops = dict((n, []) for n in self._nodes) + # Sort loops from longest to shortest + # This ensures that outer loops will come before inner loops + for loop in sorted(loops.values(), key=lambda loop: len(loop.body)): + for n in loop.body: + in_loops[n].append(loop.header) + return in_loops + + def _dump_adj_lists(self, file): + adj_lists = dict((src, sorted(list(dests))) + for src, dests in self._succs.items()) + import pprint + pprint.pprint(adj_lists, stream=file) + + def __eq__(self, other): + if not isinstance(other, CFGraph): + return NotImplemented + + for x in ['_nodes', '_edge_data', '_entry_point', '_preds', '_succs']: + this = getattr(self, x, None) + that = getattr(other, x, None) + if this != that: + return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + +class ControlFlowAnalysis(object): + """ + Attributes + ---------- + - bytecode + + - blocks + + - blockseq + + - doms: dict of set + Dominators + + - backbone: set of block offsets + The set of block that is common to all possible code path. + + """ + def __init__(self, bytecode): + self.bytecode = bytecode + self.blocks = {} + self.liveblocks = {} + self.blockseq = [] + self.doms = None + self.backbone = None + # Internal temp states + self._force_new_block = True + self._curblock = None + self._blockstack = [] + self._loops = [] + self._withs = [] + + def iterblocks(self): + """ + Return all blocks in sequence of occurrence + """ + for i in self.blockseq: + yield self.blocks[i] + + def iterliveblocks(self): + """ + Return all live blocks in sequence of occurrence + """ + for i in self.blockseq: + if i in self.liveblocks: + yield self.blocks[i] + + def incoming_blocks(self, block): + """ + Yield (incoming block, number of stack pops) pairs for *block*. + """ + for i, pops in block.incoming_jumps.items(): + if i in self.liveblocks: + yield self.blocks[i], pops + + def dump(self, file=None): + self.graph.dump(file=None) + + def run(self): + for inst in self._iter_inst(): + fname = "op_%s" % inst.opname + fn = getattr(self, fname, None) + if fn is not None: + fn(inst) + elif inst.is_jump: + # this catches e.g. try... except + l = Loc(self.bytecode.func_id.filename, inst.lineno) + if inst.opname in {"SETUP_FINALLY"}: + msg = "'try' block not supported until python3.7 or later" + else: + msg = "Use of unsupported opcode (%s) found" % inst.opname + raise UnsupportedError(msg, loc=l) + else: + # Non-jump instructions are ignored + pass # intentionally + + # Close all blocks + for cur, nxt in zip(self.blockseq, self.blockseq[1:]): + blk = self.blocks[cur] + if not blk.outgoing_jumps and not blk.terminating: + blk.outgoing_jumps[nxt] = 0 + + graph = CFGraph() + for b in self.blocks: + graph.add_node(b) + for b in self.blocks.values(): + for out, pops in b.outgoing_jumps.items(): + graph.add_edge(b.offset, out, pops) + graph.set_entry_point(min(self.blocks)) + graph.process() + self.graph = graph + + # Fill incoming + for b in self.blocks.values(): + for out, pops in b.outgoing_jumps.items(): + self.blocks[out].incoming_jumps[b.offset] = pops + + # Find liveblocks + self.liveblocks = dict((i, self.blocks[i]) + for i in self.graph.nodes()) + + for lastblk in reversed(self.blockseq): + if lastblk in self.liveblocks: + break + else: + raise AssertionError("No live block that exits!?") + + # Find backbone + backbone = self.graph.backbone() + # Filter out in loop blocks (Assuming no other cyclic control blocks) + # This is to unavoid variable defined in loops to be considered as + # function scope. + inloopblocks = set() + + for b in self.blocks.keys(): + if self.graph.in_loops(b): + inloopblocks.add(b) + + self.backbone = backbone - inloopblocks + + def jump(self, target, pops=0): + """ + Register a jump (conditional or not) to *target* offset. + *pops* is the number of stack pops implied by the jump (default 0). + """ + self._curblock.outgoing_jumps[target] = pops + + def _iter_inst(self): + for inst in self.bytecode: + if self._use_new_block(inst): + self._guard_with_as(inst) + self._start_new_block(inst) + self._curblock.body.append(inst.offset) + yield inst + + def _use_new_block(self, inst): + if inst.offset in self.bytecode.labels: + res = True + elif inst.opname in NEW_BLOCKERS: + res = True + else: + res = self._force_new_block + + self._force_new_block = False + return res + + def _start_new_block(self, inst): + self._curblock = CFBlock(inst.offset) + self.blocks[inst.offset] = self._curblock + self.blockseq.append(inst.offset) + + def _guard_with_as(self, current_inst): + """Checks if the next instruction after a SETUP_WITH is something other + than a POP_TOP, if it is something else it'll be some sort of store + which is not supported (this corresponds to `with CTXMGR as VAR(S)`).""" + if current_inst.opname == "SETUP_WITH": + next_op = self.bytecode[current_inst.next].opname + if next_op != "POP_TOP": + msg = ("The 'with (context manager) as " + "(variable):' construct is not " + "supported.") + raise UnsupportedError(msg) + + def op_SETUP_LOOP(self, inst): + end = inst.get_jump_target() + self._blockstack.append(end) + self._loops.append((inst.offset, end)) + # TODO: Looplifting requires the loop entry be its own block. + # Forcing a new block here is the simplest solution for now. + # But, we should consider other less ad-hoc ways. + self.jump(inst.next) + self._force_new_block = True + + def op_SETUP_WITH(self, inst): + end = inst.get_jump_target() + self._blockstack.append(end) + self._withs.append((inst.offset, end)) + # TODO: WithLifting requires the loop entry be its own block. + # Forcing a new block here is the simplest solution for now. + # But, we should consider other less ad-hoc ways. + self.jump(inst.next) + self._force_new_block = True + + def op_POP_BLOCK(self, inst): + self._blockstack.pop() + + def op_FOR_ITER(self, inst): + self.jump(inst.get_jump_target()) + self.jump(inst.next) + self._force_new_block = True + + def _op_ABSOLUTE_JUMP_IF(self, inst): + self.jump(inst.get_jump_target()) + self.jump(inst.next) + self._force_new_block = True + + op_POP_JUMP_IF_FALSE = _op_ABSOLUTE_JUMP_IF + op_POP_JUMP_IF_TRUE = _op_ABSOLUTE_JUMP_IF + op_JUMP_IF_FALSE = _op_ABSOLUTE_JUMP_IF + op_JUMP_IF_TRUE = _op_ABSOLUTE_JUMP_IF + + op_POP_JUMP_FORWARD_IF_FALSE = _op_ABSOLUTE_JUMP_IF + op_POP_JUMP_BACKWARD_IF_FALSE = _op_ABSOLUTE_JUMP_IF + op_POP_JUMP_FORWARD_IF_TRUE = _op_ABSOLUTE_JUMP_IF + op_POP_JUMP_BACKWARD_IF_TRUE = _op_ABSOLUTE_JUMP_IF + + def _op_ABSOLUTE_JUMP_OR_POP(self, inst): + self.jump(inst.get_jump_target()) + self.jump(inst.next, pops=1) + self._force_new_block = True + + op_JUMP_IF_FALSE_OR_POP = _op_ABSOLUTE_JUMP_OR_POP + op_JUMP_IF_TRUE_OR_POP = _op_ABSOLUTE_JUMP_OR_POP + + def op_JUMP_ABSOLUTE(self, inst): + self.jump(inst.get_jump_target()) + self._force_new_block = True + + def op_JUMP_FORWARD(self, inst): + self.jump(inst.get_jump_target()) + self._force_new_block = True + + op_JUMP_BACKWARD = op_JUMP_FORWARD + + def op_RETURN_VALUE(self, inst): + self._curblock.terminating = True + self._force_new_block = True + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_RETURN_CONST(self, inst): + self._curblock.terminating = True + self._force_new_block = True + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_RAISE_VARARGS(self, inst): + self._curblock.terminating = True + self._force_new_block = True + + def op_BREAK_LOOP(self, inst): + self.jump(self._blockstack[-1]) + self._force_new_block = True diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..3c13b098fa312f329837a6dc2e8cc47c0eb3b8cf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu.py @@ -0,0 +1,362 @@ +import platform + +import llvmlite.binding as ll +from llvmlite import ir + +from numba import _dynfunc +from numba.core.callwrapper import PyCallWrapper +from numba.core.base import BaseContext +from numba.core import (utils, types, config, cgutils, callconv, codegen, + externals, fastmathpass, intrinsics) +from numba.core.options import TargetOptions, include_default_options +from numba.core.runtime import rtsys +from numba.core.compiler_lock import global_compiler_lock +import numba.core.entrypoints +# Re-export these options, they are used from the cpu module throughout the code +# base. +from numba.core.cpu_options import (ParallelOptions, # noqa F401 + FastMathOptions, InlineOptions) # noqa F401 +from numba.np import ufunc_db + +# Keep those structures in sync with _dynfunc.c. + + +class ClosureBody(cgutils.Structure): + _fields = [('env', types.pyobject)] + + +class EnvBody(cgutils.Structure): + _fields = [ + ('globals', types.pyobject), + ('consts', types.pyobject), + ] + + +class CPUContext(BaseContext): + """ + Changes BaseContext calling convention + """ + allow_dynamic_globals = True + + def __init__(self, typingctx, target='cpu'): + super().__init__(typingctx, target) + + # Overrides + def create_module(self, name): + return self._internal_codegen._create_empty_module(name) + + @global_compiler_lock + def init(self): + self.is32bit = (utils.MACHINE_BITS == 32) + self._internal_codegen = codegen.JITCPUCodegen("numba.exec") + + # Add s390x ABI functions from libgcc_s + if platform.machine() == 's390x': + ll.load_library_permanently('libgcc_s.so.1') + + # Map external C functions. + externals.c_math_functions.install(self) + + def apply_target_attributes(self, llvm_func, argtypes=None, restype=None): + """ + Implementation of caller Type Promotions for s390x ABI requirement. + See https://github.com/numba/numba/issues/9640 + + On s390x, the ABI requires that any integer argument or return + value smaller than 64 bits must be promoted to 64 bits by the caller. + The callee can then safely assume the high-order bits of the register + are correctly filled (sign-extended or zero-extended). + Without these attributes, LLVM may leave garbage in the high bits, + leading to undefined behavior (e.g., segfaults) when the callee + performs 64-bit operations on 32-bit values. + """ + if self.address_size == 64 and platform.machine() == 's390x': + def get_ext_attr(numba_ty): + """ + Map Numba types to LLVM extension attributes. + Signed integers -> signext (sign extension) + Unsigned/Booleans -> zeroext (zero extension) + """ + if isinstance(numba_ty, types.Integer): + return 'signext' if numba_ty.signed else 'zeroext' + return 'signext' # Default fallback + + # Handle Arguments: i32 and smaller must be extended to 64-bit + for i, arg in enumerate(llvm_func.args): + if isinstance(arg.type, ir.IntType) and arg.type.width < 64: + n_ty = None + if argtypes and i < len(argtypes): + n_ty = argtypes[i] + arg.add_attribute(get_ext_attr(n_ty)) + + # Handle Return Value + retty = llvm_func.return_value.type + if isinstance(retty, ir.IntType) and retty.width < 64: + llvm_func.return_value.add_attribute(get_ext_attr(restype)) + + def load_additional_registries(self): + # Only initialize the NRT once something is about to be compiled. The + # "initialized" state doesn't need to be threadsafe, there's a lock + # around the internal compilation and the rtsys.initialize call can be + # made multiple times, worse case init just gets called a bit more often + # than optimal. + rtsys.initialize(self) + + # Add implementations that work via import + from numba.cpython import (builtins, charseq, enumimpl, # noqa F401 + hashing, heapq, iterators, # noqa F401 + listobj, numbers, rangeobj, # noqa F401 + setobj, slicing, tupleobj, # noqa F401 + unicode,) # noqa F401 + from numba.core import optional, inline_closurecall # noqa F401 + from numba.misc import gdb_hook, literal # noqa F401 + from numba.np import linalg, arraymath, arrayobj # noqa F401 + from numba.np.random import generator_core, generator_methods # noqa F401 + from numba.np.polynomial import polynomial_core, polynomial_functions # noqa F401 + from numba.typed import typeddict, dictimpl # noqa F401 + from numba.typed import typedlist, listobject # noqa F401 + from numba.experimental import jitclass, function_type # noqa F401 + from numba.np import npdatetime # noqa F401 + + # Add target specific implementations + from numba.np import npyimpl + from numba.cpython import cmathimpl, mathimpl, printimpl, randomimpl + from numba.misc import cffiimpl + from numba.experimental.jitclass.base import ClassBuilder as \ + jitclassimpl + self.install_registry(cmathimpl.registry) + self.install_registry(cffiimpl.registry) + self.install_registry(mathimpl.registry) + self.install_registry(npyimpl.registry) + self.install_registry(printimpl.registry) + self.install_registry(randomimpl.registry) + self.install_registry(jitclassimpl.class_impl_registry) + + # load 3rd party extensions + numba.core.entrypoints.init_all() + + # fix for #8940 + from numba.np.unsafe import ndarray # noqa F401 + + @property + def target_data(self): + return self._internal_codegen.target_data + + def with_aot_codegen(self, name, **aot_options): + aot_codegen = codegen.AOTCPUCodegen(name, **aot_options) + return self.subtarget(_internal_codegen=aot_codegen, + aot_mode=True) + + def codegen(self): + return self._internal_codegen + + @property + def call_conv(self): + return callconv.CPUCallConv(self) + + def get_env_body(self, builder, envptr): + """ + From the given *envptr* (a pointer to a _dynfunc.Environment object), + get a EnvBody allowing structured access to environment fields. + """ + body_ptr = cgutils.pointer_add( + builder, envptr, _dynfunc._impl_info['offsetof_env_body']) + return EnvBody(self, builder, ref=body_ptr, cast_ref=True) + + def get_env_manager(self, builder, return_pyobject=False): + envgv = self.declare_env_global(builder.module, + self.get_env_name(self.fndesc)) + envarg = builder.load(envgv) + pyapi = self.get_python_api(builder) + pyapi.emit_environment_sentry( + envarg, + return_pyobject=return_pyobject, + debug_msg=self.fndesc.env_name, + ) + env_body = self.get_env_body(builder, envarg) + return pyapi.get_env_manager(self.environment, env_body, envarg) + + def get_generator_state(self, builder, genptr, return_type): + """ + From the given *genptr* (a pointer to a _dynfunc.Generator object), + get a pointer to its state area. + """ + return cgutils.pointer_add( + builder, genptr, _dynfunc._impl_info['offsetof_generator_state'], + return_type=return_type) + + def build_list(self, builder, list_type, items): + """ + Build a list from the Numba *list_type* and its initial *items*. + """ + from numba.cpython import listobj + return listobj.build_list(self, builder, list_type, items) + + def build_set(self, builder, set_type, items): + """ + Build a set from the Numba *set_type* and its initial *items*. + """ + from numba.cpython import setobj + return setobj.build_set(self, builder, set_type, items) + + def build_map(self, builder, dict_type, item_types, items): + from numba.typed import dictobject + + return dictobject.build_map(self, builder, dict_type, item_types, items) + + def post_lowering(self, mod, library): + if self.fastmath: + fastmathpass.rewrite_module(mod, self.fastmath) + + if self.is32bit: + # 32-bit machine needs to replace all 64-bit div/rem to avoid + # calls to compiler-rt + intrinsics.fix_divmod(mod) + + library.add_linking_library(rtsys.library) + + def create_cpython_wrapper(self, library, fndesc, env, call_helper, + release_gil=False): + wrapper_module = self.create_module("wrapper") + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + wrapper_callee = ir.Function(wrapper_module, fnty, + fndesc.llvm_func_name) + builder = PyCallWrapper(self, wrapper_module, wrapper_callee, + fndesc, env, call_helper=call_helper, + release_gil=release_gil) + builder.build() + library.add_ir_module(wrapper_module) + + def create_cfunc_wrapper(self, library, fndesc, env, call_helper): + wrapper_module = self.create_module("cfunc_wrapper") + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + wrapper_callee = ir.Function(wrapper_module, fnty, + fndesc.llvm_func_name) + + ll_argtypes = [self.get_value_type(ty) for ty in fndesc.argtypes] + ll_return_type = self.get_value_type(fndesc.restype) + wrapty = ir.FunctionType(ll_return_type, ll_argtypes) + wrapfn = ir.Function(wrapper_module, wrapty, + fndesc.llvm_cfunc_wrapper_name) + builder = ir.IRBuilder(wrapfn.append_basic_block('entry')) + + status, out = self.call_conv.call_function( + builder, wrapper_callee, fndesc.restype, fndesc.argtypes, + wrapfn.args, attrs=('noinline',)) + + with builder.if_then(status.is_error, likely=False): + # If (and only if) an error occurred, acquire the GIL + # and use the interpreter to write out the exception. + pyapi = self.get_python_api(builder) + gil_state = pyapi.gil_ensure() + self.call_conv.raise_error(builder, pyapi, status) + cstr = self.insert_const_string(builder.module, repr(self)) + strobj = pyapi.string_from_string(cstr) + pyapi.err_write_unraisable(strobj) + pyapi.decref(strobj) + pyapi.gil_release(gil_state) + + builder.ret(out) + library.add_ir_module(wrapper_module) + + def get_executable(self, library, fndesc, env): + """ + Returns + ------- + (cfunc, fnptr) + + - cfunc + callable function (Can be None) + - fnptr + callable function address + - env + an execution environment (from _dynfunc) + """ + # Code generation + fnptr = library.get_pointer_to_function( + fndesc.llvm_cpython_wrapper_name) + + # Note: we avoid reusing the original docstring to avoid encoding + # issues on Python 2, see issue #1908 + doc = "compiled wrapper for %r" % (fndesc.qualname,) + cfunc = _dynfunc.make_function(fndesc.lookup_module(), + fndesc.qualname.split('.')[-1], + doc, fnptr, env, + # objects to keepalive with the function + (library,) + ) + library.codegen.set_env(self.get_env_name(fndesc), env) + return cfunc + + def calc_array_sizeof(self, ndim): + ''' + Calculate the size of an array struct on the CPU target + ''' + aryty = types.Array(types.int32, ndim, 'A') + return self.get_abi_sizeof(self.get_value_type(aryty)) + + # Overrides + def get_ufunc_info(self, ufunc_key): + return ufunc_db.get_ufunc_info(ufunc_key) + + +# ---------------------------------------------------------------------------- +# TargetOptions + +_options_mixin = include_default_options( + "nopython", + "forceobj", + "looplift", + "_nrt", + "debug", + "boundscheck", + "nogil", + "no_rewrites", + "no_cpython_wrapper", + "no_cfunc_wrapper", + "parallel", + "fastmath", + "error_model", + "inline", + "forceinline", + "_dbg_extend_lifetimes", + "_dbg_optnone", +) + + +class CPUTargetOptions(_options_mixin, TargetOptions): + def finalize(self, flags, options): + if not flags.is_set("enable_pyobject"): + flags.enable_pyobject = True + + if not flags.is_set("enable_looplift"): + flags.enable_looplift = True + + flags.inherit_if_not_set("nrt", default=True) + + if not flags.is_set("debuginfo"): + flags.debuginfo = config.DEBUGINFO_DEFAULT + + if not flags.is_set("dbg_extend_lifetimes"): + if flags.debuginfo: + # auto turn on extend-lifetimes if debuginfo is on and + # dbg_extend_lifetimes is not set + flags.dbg_extend_lifetimes = True + else: + # set flag using env-var config + flags.dbg_extend_lifetimes = config.EXTEND_VARIABLE_LIFETIMES + + if not flags.is_set("boundscheck"): + flags.boundscheck = flags.debuginfo + + flags.enable_pyobject_looplift = True + + flags.inherit_if_not_set("fastmath") + + flags.inherit_if_not_set("error_model", default="python") + + flags.inherit_if_not_set("forceinline") + + if flags.forceinline: + # forceinline turns off optnone, just like clang. + flags.dbg_optnone = False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu_options.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu_options.py new file mode 100644 index 0000000000000000000000000000000000000000..e2136c3194b44542072d69d9f5d8cd2736171886 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/cpu_options.py @@ -0,0 +1,181 @@ +""" +Defines CPU Options for use in the CPU target +""" +from abc import ABCMeta, abstractmethod + + +class AbstractOptionValue(metaclass=ABCMeta): + """Abstract base class for custom option values. + """ + @abstractmethod + def encode(self) -> str: + """Returns an encoding of the values + """ + ... + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.encode()})" + + +class FastMathOptions(AbstractOptionValue): + """ + Options for controlling fast math optimization. + """ + + def __init__(self, value): + # https://releases.llvm.org/7.0.0/docs/LangRef.html#fast-math-flags + valid_flags = { + 'fast', + 'nnan', 'ninf', 'nsz', 'arcp', + 'contract', 'afn', 'reassoc', + } + + if isinstance(value, FastMathOptions): + self.flags = value.flags.copy() + elif value is True: + self.flags = {'fast'} + elif value is False: + self.flags = set() + elif isinstance(value, set): + invalid = value - valid_flags + if invalid: + raise ValueError("Unrecognized fastmath flags: %s" % invalid) + self.flags = value + elif isinstance(value, dict): + invalid = set(value.keys()) - valid_flags + if invalid: + raise ValueError("Unrecognized fastmath flags: %s" % invalid) + self.flags = {v for v, enable in value.items() if enable} + else: + msg = "Expected fastmath option(s) to be either a bool, dict or set" + raise ValueError(msg) + + def __bool__(self): + return bool(self.flags) + + __nonzero__ = __bool__ + + def encode(self) -> str: + return str(self.flags) + + def __eq__(self, other): + if type(other) is type(self): + return self.flags == other.flags + return NotImplemented + + +class ParallelOptions(AbstractOptionValue): + """ + Options for controlling auto parallelization. + """ + __slots__ = ("enabled", "comprehension", "reduction", "inplace_binop", + "setitem", "numpy", "stencil", "fusion", "prange") + + def __init__(self, value): + if isinstance(value, bool): + self.enabled = value + self.comprehension = value + self.reduction = value + self.inplace_binop = value + self.setitem = value + self.numpy = value + self.stencil = value + self.fusion = value + self.prange = value + elif isinstance(value, dict): + self.enabled = True + self.comprehension = value.pop('comprehension', True) + self.reduction = value.pop('reduction', True) + self.inplace_binop = value.pop('inplace_binop', True) + self.setitem = value.pop('setitem', True) + self.numpy = value.pop('numpy', True) + self.stencil = value.pop('stencil', True) + self.fusion = value.pop('fusion', True) + self.prange = value.pop('prange', True) + if value: + msg = "Unrecognized parallel options: %s" % value.keys() + raise NameError(msg) + elif isinstance(value, ParallelOptions): + self.enabled = value.enabled + self.comprehension = value.comprehension + self.reduction = value.reduction + self.inplace_binop = value.inplace_binop + self.setitem = value.setitem + self.numpy = value.numpy + self.stencil = value.stencil + self.fusion = value.fusion + self.prange = value.prange + else: + msg = "Expect parallel option to be either a bool or a dict" + raise ValueError(msg) + + def _get_values(self): + """Get values as dictionary. + """ + return {k: getattr(self, k) for k in self.__slots__} + + def __eq__(self, other): + if type(other) is type(self): + return self._get_values() == other._get_values() + return NotImplemented + + def encode(self) -> str: + return ", ".join(f"{k}={v}" for k, v in self._get_values().items()) + + +class InlineOptions(AbstractOptionValue): + """ + Options for controlling inlining + """ + + def __init__(self, value): + ok = False + if isinstance(value, str): + if value in ('always', 'never'): + ok = True + else: + ok = hasattr(value, '__call__') + + if ok: + self._inline = value + else: + msg = ("kwarg 'inline' must be one of the strings 'always' or " + "'never', or it can be a callable that returns True/False. " + "Found value %s" % value) + raise ValueError(msg) + + @property + def is_never_inline(self): + """ + True if never inline + """ + return self._inline == 'never' + + @property + def is_always_inline(self): + """ + True if always inline + """ + return self._inline == 'always' + + @property + def has_cost_model(self): + """ + True if a cost model is provided + """ + return not (self.is_always_inline or self.is_never_inline) + + @property + def value(self): + """ + The raw value + """ + return self._inline + + def __eq__(self, other): + if type(other) is type(self): + return self.value == other.value + return NotImplemented + + def encode(self) -> str: + return repr(self._inline) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/debuginfo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/debuginfo.py new file mode 100644 index 0000000000000000000000000000000000000000..7970fc8e626995814def48ffe524e133e11477d6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/debuginfo.py @@ -0,0 +1,456 @@ +""" +Implements helpers to build LLVM debuginfo. +""" + + +import abc +import os.path +from contextlib import contextmanager + +from llvmlite import ir +from numba.core import cgutils, types +from numba.core.datamodel.models import ComplexModel, UniTupleModel +from numba.core import config + + +@contextmanager +def suspend_emission(builder): + """Suspends the emission of debug_metadata for the duration of the context + managed block.""" + ref = builder.debug_metadata + builder.debug_metadata = None + try: + yield + finally: + builder.debug_metadata = ref + + +class AbstractDIBuilder(metaclass=abc.ABCMeta): + @abc.abstractmethod + def mark_variable(self, builder, allocavalue, name, lltype, size, line, + datamodel=None, argidx=None): + """Emit debug info for the variable. + """ + pass + + @abc.abstractmethod + def mark_location(self, builder, line): + """Emit source location information to the given IRBuilder. + """ + pass + + @abc.abstractmethod + def mark_subprogram(self, function, qualname, argnames, argtypes, line): + """Emit source location information for the given function. + """ + pass + + @abc.abstractmethod + def initialize(self): + """Initialize the debug info. An opportunity for the debuginfo to + prepare any necessary data structures. + """ + + @abc.abstractmethod + def finalize(self): + """Finalize the debuginfo by emitting all necessary metadata. + """ + pass + + +class DummyDIBuilder(AbstractDIBuilder): + + def __init__(self, module, filepath, cgctx, directives_only): + pass + + def mark_variable(self, builder, allocavalue, name, lltype, size, line, + datamodel=None, argidx=None): + pass + + def mark_location(self, builder, line): + pass + + def mark_subprogram(self, function, qualname, argnames, argtypes, line): + pass + + def initialize(self): + pass + + def finalize(self): + pass + + +_BYTE_SIZE = 8 + + +class DIBuilder(AbstractDIBuilder): + DWARF_VERSION = 4 + DEBUG_INFO_VERSION = 3 + DBG_CU_NAME = 'llvm.dbg.cu' + _DEBUG = False + + def __init__(self, module, filepath, cgctx, directives_only): + self.module = module + self.filepath = os.path.abspath(filepath) + self.difile = self._di_file() + self.subprograms = [] + self.cgctx = cgctx + + if directives_only: + self.emission_kind = 'DebugDirectivesOnly' + else: + self.emission_kind = 'FullDebug' + + self.initialize() + + def initialize(self): + # Create the compile unit now because it is referenced when + # constructing subprograms + self.dicompileunit = self._di_compile_unit() + + def _var_type(self, lltype, size, datamodel=None): + if self._DEBUG: + print("-->", lltype, size, datamodel, + getattr(datamodel, 'fe_type', 'NO FE TYPE')) + m = self.module + bitsize = _BYTE_SIZE * size + + int_type = ir.IntType, + real_type = ir.FloatType, ir.DoubleType + # For simple numeric types, choose the closest encoding. + # We treat all integers as unsigned when there's no known datamodel. + if isinstance(lltype, int_type + real_type): + if datamodel is None: + # This is probably something like an `i8*` member of a struct + name = str(lltype) + if isinstance(lltype, int_type): + ditok = 'DW_ATE_unsigned' + else: + ditok = 'DW_ATE_float' + else: + # This is probably a known int/float scalar type + name = str(datamodel.fe_type) + if isinstance(datamodel.fe_type, types.Integer): + if datamodel.fe_type.signed: + ditok = 'DW_ATE_signed' + else: + ditok = 'DW_ATE_unsigned' + else: + ditok = 'DW_ATE_float' + mdtype = m.add_debug_info('DIBasicType', { + 'name': name, + 'size': bitsize, + 'encoding': ir.DIToken(ditok), + }) + elif isinstance(datamodel, ComplexModel): + # TODO: Is there a better way of determining "this is a complex + # number"? + # + # NOTE: Commented below is the way to generate the metadata for a + # C99 complex type that's directly supported by DWARF. Numba however + # generates a struct with real/imag cf. CPython to give a more + # pythonic feel to inspection. + # + # mdtype = m.add_debug_info('DIBasicType', { + # 'name': f"{datamodel.fe_type} ({str(lltype)})", + # 'size': bitsize, + # 'encoding': ir.DIToken('DW_ATE_complex_float'), + #}) + meta = [] + offset = 0 + for ix, name in enumerate(('real', 'imag')): + component = lltype.elements[ix] + component_size = self.cgctx.get_abi_sizeof(component) + component_basetype = m.add_debug_info('DIBasicType', { + 'name': str(component), + 'size': _BYTE_SIZE * component_size, # bits + 'encoding': ir.DIToken('DW_ATE_float'), + }) + derived_type = m.add_debug_info('DIDerivedType', { + 'tag': ir.DIToken('DW_TAG_member'), + 'name': name, + 'baseType': component_basetype, + 'size': _BYTE_SIZE * component_size, # DW_TAG_member size is in bits + 'offset': offset, + }) + meta.append(derived_type) + offset += (_BYTE_SIZE * component_size) # offset is in bits + mdtype = m.add_debug_info('DICompositeType', { + 'tag': ir.DIToken('DW_TAG_structure_type'), + 'name': f"{datamodel.fe_type} ({str(lltype)})", + 'identifier': str(lltype), + 'elements': m.add_metadata(meta), + 'size': offset, + }, is_distinct=True) + elif isinstance(datamodel, UniTupleModel): + element = lltype.element + el_size = self.cgctx.get_abi_sizeof(element) + basetype = self._var_type(element, el_size) + name = f"{datamodel.fe_type} ({str(lltype)})" + count = size // el_size + mdrange = m.add_debug_info('DISubrange', { + 'count': count, + }) + mdtype = m.add_debug_info('DICompositeType', { + 'tag': ir.DIToken('DW_TAG_array_type'), + 'baseType': basetype, + 'name': name, + 'size': bitsize, + 'identifier': str(lltype), + 'elements': m.add_metadata([mdrange]), + }) + elif isinstance(lltype, ir.PointerType): + model = getattr(datamodel, '_pointee_model', None) + basetype = self._var_type(lltype.pointee, + self.cgctx.get_abi_sizeof(lltype.pointee), + model) + mdtype = m.add_debug_info('DIDerivedType', { + 'tag': ir.DIToken('DW_TAG_pointer_type'), + 'baseType': basetype, + 'size': _BYTE_SIZE * self.cgctx.get_abi_sizeof(lltype) + }) + elif isinstance(lltype, ir.LiteralStructType): + # Struct type + meta = [] + offset = 0 + if datamodel is None or not datamodel.inner_models(): + name = f"Anonymous struct ({str(lltype)})" + for field_id, element in enumerate(lltype.elements): + size = self.cgctx.get_abi_sizeof(element) + basetype = self._var_type(element, size) + derived_type = m.add_debug_info('DIDerivedType', { + 'tag': ir.DIToken('DW_TAG_member'), + 'name': f'', + 'baseType': basetype, + 'size': _BYTE_SIZE * size, # DW_TAG_member size is in bits + 'offset': offset, + }) + meta.append(derived_type) + offset += (_BYTE_SIZE * size) # offset is in bits + else: + name = f"{datamodel.fe_type} ({str(lltype)})" + for element, field, model in zip(lltype.elements, + datamodel._fields, + datamodel.inner_models()): + size = self.cgctx.get_abi_sizeof(element) + basetype = self._var_type(element, size, datamodel=model) + derived_type = m.add_debug_info('DIDerivedType', { + 'tag': ir.DIToken('DW_TAG_member'), + 'name': field, + 'baseType': basetype, + 'size': _BYTE_SIZE * size, # DW_TAG_member size is in bits + 'offset': offset, + }) + meta.append(derived_type) + offset += (_BYTE_SIZE * size) # offset is in bits + + mdtype = m.add_debug_info('DICompositeType', { + 'tag': ir.DIToken('DW_TAG_structure_type'), + 'name': name, + 'identifier': str(lltype), + 'elements': m.add_metadata(meta), + 'size': offset, + }, is_distinct=True) + elif isinstance(lltype, ir.ArrayType): + element = lltype.element + el_size = self.cgctx.get_abi_sizeof(element) + basetype = self._var_type(element, el_size) + count = size // el_size + mdrange = m.add_debug_info('DISubrange', { + 'count': count, + }) + mdtype = m.add_debug_info('DICompositeType', { + 'tag': ir.DIToken('DW_TAG_array_type'), + 'baseType': basetype, + 'name': str(lltype), + 'size': bitsize, + 'identifier': str(lltype), + 'elements': m.add_metadata([mdrange]), + }) + else: + # For all other types, describe it as sequence of bytes + count = size + mdrange = m.add_debug_info('DISubrange', { + 'count': count, + }) + mdbase = m.add_debug_info('DIBasicType', { + 'name': 'byte', + 'size': _BYTE_SIZE, + 'encoding': ir.DIToken('DW_ATE_unsigned_char'), + }) + mdtype = m.add_debug_info('DICompositeType', { + 'tag': ir.DIToken('DW_TAG_array_type'), + 'baseType': mdbase, + 'name': str(lltype), + 'size': bitsize, + 'identifier': str(lltype), + 'elements': m.add_metadata([mdrange]), + }) + + return mdtype + + def mark_variable(self, builder, allocavalue, name, lltype, size, line, + datamodel=None, argidx=None): + + arg_index = 0 if argidx is None else argidx + m = self.module + fnty = ir.FunctionType(ir.VoidType(), [ir.MetaDataType()] * 3) + decl = cgutils.get_or_insert_function(m, fnty, 'llvm.dbg.declare') + + mdtype = self._var_type(lltype, size, datamodel=datamodel) + name = name.replace('.', '$') # for gdb to work correctly + mdlocalvar = m.add_debug_info('DILocalVariable', { + 'name': name, + 'arg': arg_index, + 'scope': self.subprograms[-1], + 'file': self.difile, + 'line': line, + 'type': mdtype, + }) + mdexpr = m.add_debug_info('DIExpression', {}) + + return builder.call(decl, [allocavalue, mdlocalvar, mdexpr]) + + def mark_location(self, builder, line): + builder.debug_metadata = self._add_location(line) + + def mark_subprogram(self, function, qualname, argnames, argtypes, line): + name = qualname + argmap = dict(zip(argnames, argtypes)) + di_subp = self._add_subprogram(name=name, linkagename=function.name, + line=line, function=function, + argmap=argmap) + function.set_metadata("dbg", di_subp) + + def finalize(self): + dbgcu = cgutils.get_or_insert_named_metadata(self.module, self.DBG_CU_NAME) + dbgcu.add(self.dicompileunit) + self._set_module_flags() + + # + # Internal APIs + # + + def _set_module_flags(self): + """Set the module flags metadata + """ + module = self.module + mflags = cgutils.get_or_insert_named_metadata(module, 'llvm.module.flags') + # Set *require* behavior to warning + # See http://llvm.org/docs/LangRef.html#module-flags-metadata + require_warning_behavior = self._const_int(2) + if self.DWARF_VERSION is not None: + dwarf_version = module.add_metadata([ + require_warning_behavior, + "Dwarf Version", + self._const_int(self.DWARF_VERSION) + ]) + if dwarf_version not in mflags.operands: + mflags.add(dwarf_version) + debuginfo_version = module.add_metadata([ + require_warning_behavior, + "Debug Info Version", + self._const_int(self.DEBUG_INFO_VERSION) + ]) + if debuginfo_version not in mflags.operands: + mflags.add(debuginfo_version) + + def _add_subprogram(self, name, linkagename, line, function, argmap): + """Emit subprogram metadata + """ + subp = self._di_subprogram(name, linkagename, line, function, argmap) + self.subprograms.append(subp) + return subp + + def _add_location(self, line): + """Emit location metatdaa + """ + loc = self._di_location(line) + return loc + + @classmethod + def _const_int(cls, num, bits=32): + """Util to create constant int in metadata + """ + return ir.IntType(bits)(num) + + @classmethod + def _const_bool(cls, boolean): + """Util to create constant boolean in metadata + """ + return ir.IntType(1)(boolean) + + # + # Helpers to emit the metadata nodes + # + + def _di_file(self): + return self.module.add_debug_info('DIFile', { + 'directory': os.path.dirname(self.filepath), + 'filename': os.path.basename(self.filepath), + }) + + def _di_compile_unit(self): + return self.module.add_debug_info('DICompileUnit', { + 'language': ir.DIToken('DW_LANG_C_plus_plus'), + 'file': self.difile, + # Numba has to pretend to be clang to ensure the prologue is skipped + # correctly in gdb. See: + # https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/amd64-tdep.c;h=e563d369d8cb3eb3c2f732c2fa850ec70ba8d63b;hb=a4b0231e179607e47b1cdf1fe15c5dc25e482fad#l2521 + # Note the "producer_is_llvm" call to specialise the prologue + # handling, this is defined here: + # https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/producer.c;h=cdfd80d904c09394febd18749bb90359b2d128cc;hb=a4b0231e179607e47b1cdf1fe15c5dc25e482fad#l124 + # and to get a match for this condition the 'producer' must start + # with "clang ", hence the following... + 'producer': 'clang (Numba)', + 'runtimeVersion': 0, + 'isOptimized': config.OPT != 0, + 'emissionKind': ir.DIToken(self.emission_kind), + }, is_distinct=True) + + def _di_subroutine_type(self, line, function, argmap): + # The function call conv needs encoding. + llfunc = function + md = [] + + for idx, llarg in enumerate(llfunc.args): + if not llarg.name.startswith('arg.'): + name = llarg.name.replace('.', '$') # for gdb to work correctly + lltype = llarg.type + size = self.cgctx.get_abi_sizeof(lltype) + mdtype = self._var_type(lltype, size, datamodel=None) + md.append(mdtype) + + for idx, (name, nbtype) in enumerate(argmap.items()): + name = name.replace('.', '$') # for gdb to work correctly + datamodel = self.cgctx.data_model_manager[nbtype] + lltype = self.cgctx.get_value_type(nbtype) + size = self.cgctx.get_abi_sizeof(lltype) + mdtype = self._var_type(lltype, size, datamodel=datamodel) + md.append(mdtype) + + return self.module.add_debug_info('DISubroutineType', { + 'types': self.module.add_metadata(md), + }) + + def _di_subprogram(self, name, linkagename, line, function, argmap): + return self.module.add_debug_info('DISubprogram', { + 'name': name, + 'linkageName': linkagename, + 'scope': self.difile, + 'file': self.difile, + 'line': line, + 'type': self._di_subroutine_type(line, function, argmap), + 'isLocal': False, + 'isDefinition': True, + 'scopeLine': line, + 'isOptimized': config.OPT != 0, + 'unit': self.dicompileunit, + }, is_distinct=True) + + def _di_location(self, line): + return self.module.add_debug_info('DILocation', { + 'line': line, + 'column': 1, + 'scope': self.subprograms[-1], + }) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/decorators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..d70af739a2550eeb06b96b056ac2e124516c7f2e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/decorators.py @@ -0,0 +1,305 @@ +""" +Define @jit and related decorators. +""" + + +import sys +import warnings +import inspect +import logging +from types import MappingProxyType + +from numba.core.errors import DeprecationError, NumbaDeprecationWarning +from numba.stencils.stencil import stencil +from numba.core import config, extending, sigutils, registry + +_logger = logging.getLogger(__name__) + + +# ----------------------------------------------------------------------------- +# Decorators + +_msg_deprecated_signature_arg = ("Deprecated keyword argument `{0}`. " + "Signatures should be passed as the first " + "positional argument.") + + +def jit(signature_or_function=None, locals=MappingProxyType({}), cache=False, + pipeline_class=None, boundscheck=None, **options): + """ + This decorator is used to compile a Python function into native code. + + Args + ----- + signature_or_function: + The (optional) signature or list of signatures to be compiled. + If not passed, required signatures will be compiled when the + decorated function is called, depending on the argument values. + As a convenience, you can directly pass the function to be compiled + instead. + + locals: dict + Mapping of local variable names to Numba types. Used to override the + types deduced by Numba's type inference engine. + + pipeline_class: type numba.compiler.CompilerBase + The compiler pipeline type for customizing the compilation stages. + + options: + For a cpu target, valid options are: + nopython: bool + Set to True to disable the use of PyObjects and Python API + calls. The default behavior is to allow the use of PyObjects + and Python API. Default value is True. + + forceobj: bool + Set to True to force the use of PyObjects for every value. + Default value is False. + + looplift: bool + Set to True to enable jitting loops in nopython mode while + leaving surrounding code in object mode. This allows functions + to allocate NumPy arrays and use Python objects, while the + tight loops in the function can still be compiled in nopython + mode. Any arrays that the tight loop uses should be created + before the loop is entered. Default value is True. + + error_model: str + The error-model affects divide-by-zero behavior. + Valid values are 'python' and 'numpy'. The 'python' model + raises exception. The 'numpy' model sets the result to + *+/-inf* or *nan*. Default value is 'python'. + + inline: str or callable + The inline option will determine whether a function is inlined + at into its caller if called. String options are 'never' + (default) which will never inline, and 'always', which will + always inline. If a callable is provided it will be called with + the call expression node that is requesting inlining, the + caller's IR and callee's IR as arguments, it is expected to + return Truthy as to whether to inline. + NOTE: This inlining is performed at the Numba IR level and is in + no way related to LLVM inlining. + + boundscheck: bool or None + Set to True to enable bounds checking for array indices. Out + of bounds accesses will raise IndexError. The default is to + not do bounds checking. If False, bounds checking is disabled, + out of bounds accesses can produce garbage results or segfaults. + However, enabling bounds checking will slow down typical + functions, so it is recommended to only use this flag for + debugging. You can also set the NUMBA_BOUNDSCHECK environment + variable to 0 or 1 to globally override this flag. The default + value is None, which under normal execution equates to False, + but if debug is set to True then bounds checking will be + enabled. + + Returns + -------- + A callable usable as a compiled function. Actual compiling will be + done lazily if no explicit signatures are passed. + + Examples + -------- + The function can be used in the following ways: + + 1) jit(signatures, **targetoptions) -> jit(function) + + Equivalent to: + + d = dispatcher(function, targetoptions) + for signature in signatures: + d.compile(signature) + + Create a dispatcher object for a python function. Then, compile + the function with the given signature(s). + + Example: + + @jit("int32(int32, int32)") + def foo(x, y): + return x + y + + @jit(["int32(int32, int32)", "float32(float32, float32)"]) + def bar(x, y): + return x + y + + 2) jit(function, **targetoptions) -> dispatcher + + Create a dispatcher function object that specializes at call site. + + Examples: + + @jit + def foo(x, y): + return x + y + + @jit(nopython=True) + def bar(x, y): + return x + y + + """ + locals = dict(locals) + forceobj = options.get('forceobj', False) + if 'argtypes' in options: + raise DeprecationError(_msg_deprecated_signature_arg.format('argtypes')) + if 'restype' in options: + raise DeprecationError(_msg_deprecated_signature_arg.format('restype')) + nopython = options.get('nopython', None) + if nopython is not None: + assert type(nopython) is bool, "nopython option must be a bool" + if nopython is True and forceobj: + raise ValueError("Only one of 'nopython' or 'forceobj' can be True.") + target = options.pop('_target', 'cpu') + + if nopython is False: + msg = ("The keyword argument 'nopython=False' was supplied. From " + "Numba 0.59.0 the default is True and supplying this argument " + "has no effect.") + warnings.warn(msg, NumbaDeprecationWarning) + # nopython is True by default since 0.59.0, but if `forceobj` is set + # `nopython` needs to set to False so that things like typing of args in the + # dispatcher layer continues to work. + if forceobj: + options['nopython'] = False + else: + options['nopython'] = True + + options['boundscheck'] = boundscheck + + # Handle signature + if signature_or_function is None: + # No signature, no function + pyfunc = None + sigs = None + elif isinstance(signature_or_function, list): + # A list of signatures is passed + pyfunc = None + sigs = signature_or_function + elif sigutils.is_signature(signature_or_function): + # A single signature is passed + pyfunc = None + sigs = [signature_or_function] + else: + # A function is passed + pyfunc = signature_or_function + sigs = None + + dispatcher_args = {} + if pipeline_class is not None: + dispatcher_args['pipeline_class'] = pipeline_class + wrapper = _jit(sigs, locals=locals, target=target, cache=cache, + targetoptions=options, **dispatcher_args) + if pyfunc is not None: + return wrapper(pyfunc) + else: + return wrapper + + +def _jit(sigs, locals, target, cache, targetoptions, **dispatcher_args): + + from numba.core.target_extension import resolve_dispatcher_from_str + dispatcher = resolve_dispatcher_from_str(target) + + def wrapper(func): + if extending.is_jitted(func): + raise TypeError( + "A jit decorator was called on an already jitted function " + f"{func}. If trying to access the original python " + f"function, use the {func}.py_func attribute." + ) + + if not inspect.isfunction(func): + raise TypeError( + "The decorated object is not a function (got type " + f"{type(func)})." + ) + + if config.ENABLE_CUDASIM and target == 'cuda': + from numba import cuda + return cuda.jit(func) + if config.DISABLE_JIT and not target == 'npyufunc': + return func + disp = dispatcher(py_func=func, locals=locals, + targetoptions=targetoptions, + **dispatcher_args) + if cache: + disp.enable_caching() + if sigs is not None: + # Register the Dispatcher to the type inference mechanism, + # even though the decorator hasn't returned yet. + from numba.core import typeinfer + with typeinfer.register_dispatcher(disp): + for sig in sigs: + disp.compile(sig) + disp.disable_compile() + return disp + + return wrapper + + +def njit(*args, **kws): + """ + Equivalent to jit(nopython=True) + + See documentation for jit function/decorator for full description. + """ + if 'nopython' in kws: + warnings.warn('nopython is set for njit and is ignored', RuntimeWarning) + if 'forceobj' in kws: + warnings.warn('forceobj is set for njit and is ignored', RuntimeWarning) + del kws['forceobj'] + kws.update({'nopython': True}) + return jit(*args, **kws) + + +def cfunc(sig, locals=MappingProxyType({}), cache=False, pipeline_class=None, **options): + """ + This decorator is used to compile a Python function into a C callback + usable with foreign C libraries. + + Usage:: + @cfunc("float64(float64, float64)", nopython=True, cache=True) + def add(a, b): + return a + b + + """ + locals = dict(locals) + sig = sigutils.normalize_signature(sig) + + def wrapper(func): + from numba.core.ccallback import CFunc + additional_args = {} + if pipeline_class is not None: + additional_args['pipeline_class'] = pipeline_class + res = CFunc(func, sig, locals=locals, options=options, **additional_args) + if cache: + res.enable_caching() + res.compile() + return res + + return wrapper + + +def jit_module(**kwargs): + """ Automatically ``jit``-wraps functions defined in a Python module + + Note that ``jit_module`` should only be called at the end of the module to + be jitted. In addition, only functions which are defined in the module + ``jit_module`` is called from are considered for automatic jit-wrapping. + See the Numba documentation for more information about what can/cannot be + jitted. + + :param kwargs: Keyword arguments to pass to ``jit`` such as ``nopython`` + or ``error_model``. + + """ + # Get the module jit_module is being called from + frame = inspect.stack()[1] + module = inspect.getmodule(frame[0]) + # Replace functions in module with jit-wrapped versions + for name, obj in module.__dict__.items(): + if inspect.isfunction(obj) and inspect.getmodule(obj) == module: + _logger.debug("Auto decorating function {} from module {} with jit " + "and options: {}".format(obj, module.__name__, kwargs)) + module.__dict__[name] = jit(obj, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/descriptors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/descriptors.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0c367e9c99dc2799cfdb738e62cbd85d93f8eb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/descriptors.py @@ -0,0 +1,21 @@ +""" +Target Descriptors +""" + +from abc import ABCMeta, abstractmethod + + +class TargetDescriptor(metaclass=ABCMeta): + + def __init__(self, target_name): + self._target_name = target_name + + @property + @abstractmethod + def typing_context(self): + ... + + @property + @abstractmethod + def target_context(self): + ... diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/dispatcher.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..be44165ddb9679f3394ee631296487d6171b4eff --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/dispatcher.py @@ -0,0 +1,1331 @@ +# -*- coding: utf-8 -*- + + +import collections +import functools +import sys +import types as pytypes +import uuid +import weakref +from contextlib import ExitStack +from abc import abstractmethod + +from numba import _dispatcher +from numba.core import ( + utils, types, errors, typing, serialize, config, compiler, sigutils +) +from numba.core.compiler_lock import global_compiler_lock +from numba.core.typeconv.rules import default_type_manager +from numba.core.typing.templates import fold_arguments +from numba.core.typing.typeof import Purpose, typeof +from numba.core.bytecode import get_code_object +from numba.core.caching import NullCache, FunctionCache +from numba.core import entrypoints +import numba.core.event as ev + + +class OmittedArg(object): + """ + A placeholder for omitted arguments with a default value. + """ + + def __init__(self, value): + self.value = value + + def __repr__(self): + return "omitted arg(%r)" % (self.value,) + + @property + def _numba_type_(self): + return types.Omitted(self.value) + + +class _FunctionCompiler(object): + def __init__(self, py_func, targetdescr, targetoptions, locals, + pipeline_class): + self.py_func = py_func + self.targetdescr = targetdescr + self.targetoptions = targetoptions + self.locals = locals + self.pysig = utils.pysignature(self.py_func) + self.pipeline_class = pipeline_class + # Remember key=(args, return_type) combinations that will fail + # compilation to avoid compilation attempt on them. The values are + # the exceptions. + self._failed_cache = {} + + def fold_argument_types(self, args, kws): + """ + Given positional and named argument types, fold keyword arguments + and resolve defaults by inserting types.Omitted() instances. + + A (pysig, argument types) tuple is returned. + """ + def normal_handler(index, param, value): + return value + + def default_handler(index, param, default): + return types.Omitted(default) + + def stararg_handler(index, param, values): + return types.StarArgTuple(values) + # For now, we take argument values from the @jit function + args = fold_arguments(self.pysig, args, kws, + normal_handler, + default_handler, + stararg_handler) + return self.pysig, args + + def compile(self, args, return_type): + status, retval = self._compile_cached(args, return_type) + if status: + return retval + else: + raise retval + + def _compile_cached(self, args, return_type): + key = tuple(args), return_type + try: + return False, self._failed_cache[key] + except KeyError: + pass + + try: + retval = self._compile_core(args, return_type) + except errors.TypingError as e: + self._failed_cache[key] = e + return False, e + else: + return True, retval + + def _compile_core(self, args, return_type): + flags = compiler.Flags() + self.targetdescr.options.parse_as_flags(flags, self.targetoptions) + flags = self._customize_flags(flags) + + impl = self._get_implementation(args, {}) + cres = compiler.compile_extra(self.targetdescr.typing_context, + self.targetdescr.target_context, + impl, + args=args, return_type=return_type, + flags=flags, locals=self.locals, + pipeline_class=self.pipeline_class) + # Check typing error if object mode is used + if cres.typing_error is not None and not flags.enable_pyobject: + raise cres.typing_error + return cres + + def get_globals_for_reduction(self): + return serialize._get_function_globals_for_reduction(self.py_func) + + def _get_implementation(self, args, kws): + return self.py_func + + def _customize_flags(self, flags): + return flags + + +class _GeneratedFunctionCompiler(_FunctionCompiler): + + def __init__(self, py_func, targetdescr, targetoptions, locals, + pipeline_class): + super(_GeneratedFunctionCompiler, self).__init__( + py_func, targetdescr, targetoptions, locals, pipeline_class) + self.impls = set() + + def get_globals_for_reduction(self): + # This will recursively get the globals used by any nested + # implementation function. + return serialize._get_function_globals_for_reduction(self.py_func) + + def _get_implementation(self, args, kws): + impl = self.py_func(*args, **kws) + # Check the generating function and implementation signatures are + # compatible, otherwise compiling would fail later. + pysig = utils.pysignature(self.py_func) + implsig = utils.pysignature(impl) + ok = len(pysig.parameters) == len(implsig.parameters) + if ok: + for pyparam, implparam in zip(pysig.parameters.values(), + implsig.parameters.values()): + # We allow the implementation to omit default values, but + # if it mentions them, they should have the same value... + if (pyparam.name != implparam.name or + pyparam.kind != implparam.kind or + (implparam.default is not implparam.empty and + implparam.default != pyparam.default)): + ok = False + if not ok: + raise TypeError("generated implementation %s should be compatible " + "with signature '%s', but has signature '%s'" + % (impl, pysig, implsig)) + self.impls.add(impl) + return impl + + +_CompileStats = collections.namedtuple( + '_CompileStats', ('cache_path', 'cache_hits', 'cache_misses')) + + +class CompilingCounter(object): + """ + A simple counter that increment in __enter__ and decrement in __exit__. + """ + + def __init__(self): + self.counter = 0 + + def __enter__(self): + assert self.counter >= 0 + self.counter += 1 + + def __exit__(self, *args, **kwargs): + self.counter -= 1 + assert self.counter >= 0 + + def __bool__(self): + return self.counter > 0 + + __nonzero__ = __bool__ + + +class _DispatcherBase(_dispatcher.Dispatcher): + """ + Common base class for dispatcher Implementations. + """ + + __numba__ = "py_func" + + def __init__(self, arg_count, py_func, pysig, can_fallback, + exact_match_required): + self._tm = default_type_manager + + # A mapping of signatures to compile results + self.overloads = collections.OrderedDict() + + self.py_func = py_func + # other parts of Numba assume the old Python 2 name for code object + self.func_code = get_code_object(py_func) + # but newer python uses a different name + self.__code__ = self.func_code + # a place to keep an active reference to the types of the active call + self._types_active_call = set() + # Default argument values match the py_func + self.__defaults__ = py_func.__defaults__ + + argnames = tuple(pysig.parameters) + default_values = self.py_func.__defaults__ or () + defargs = tuple(OmittedArg(val) for val in default_values) + try: + lastarg = list(pysig.parameters.values())[-1] + except IndexError: + has_stararg = False + else: + has_stararg = lastarg.kind == lastarg.VAR_POSITIONAL + _dispatcher.Dispatcher.__init__(self, self._tm.get_pointer(), + arg_count, self._fold_args, + argnames, defargs, + can_fallback, + has_stararg, + exact_match_required) + + self.doc = py_func.__doc__ + self._compiling_counter = CompilingCounter() + self._enable_sysmon = bool(config.ENABLE_SYS_MONITORING) + weakref.finalize(self, self._make_finalizer()) + + def _compilation_chain_init_hook(self): + """ + This will be called ahead of any part of compilation taking place (this + even includes being ahead of working out the types of the arguments). + This permits activities such as initialising extension entry points so + that the compiler knows about additional externally defined types etc + before it does anything. + """ + entrypoints.init_all() + + def _reset_overloads(self): + self._clear() + self.overloads.clear() + + def _make_finalizer(self): + """ + Return a finalizer function that will release references to + related compiled functions. + """ + overloads = self.overloads + targetctx = self.targetctx + + # Early-bind utils.shutting_down() into the function's local namespace + # (see issue #689) + def finalizer(shutting_down=utils.shutting_down): + # The finalizer may crash at shutdown, skip it (resources + # will be cleared by the process exiting, anyway). + if shutting_down(): + return + # This function must *not* hold any reference to self: + # we take care to bind the necessary objects in the closure. + for cres in overloads.values(): + try: + targetctx.remove_user_function(cres.entry_point) + except KeyError: + pass + + return finalizer + + @property + def signatures(self): + """ + Returns a list of compiled function signatures. + """ + return list(self.overloads) + + @property + def nopython_signatures(self): + return [cres.signature for cres in self.overloads.values() + if not cres.objectmode] + + def disable_compile(self, val=True): + """Disable the compilation of new signatures at call time. + """ + # If disabling compilation then there must be at least one signature + assert (not val) or len(self.signatures) > 0 + self._can_compile = not val + + def add_overload(self, cres): + args = tuple(cres.signature.args) + sig = [a._code for a in args] + self._insert(sig, cres.entry_point, cres.objectmode) + self.overloads[args] = cres + + def fold_argument_types(self, args, kws): + return self._compiler.fold_argument_types(args, kws) + + def get_call_template(self, args, kws): + """ + Get a typing.ConcreteTemplate for this dispatcher and the given + *args* and *kws* types. This allows to resolve the return type. + + A (template, pysig, args, kws) tuple is returned. + """ + # XXX how about a dispatcher template class automating the + # following? + + # Fold keyword arguments and resolve default values + pysig, args = self._compiler.fold_argument_types(args, kws) + kws = {} + # Ensure an overload is available + if self._can_compile: + self.compile(tuple(args)) + + # Create function type for typing + func_name = self.py_func.__name__ + name = "CallTemplate({0})".format(func_name) + # The `key` isn't really used except for diagnosis here, + # so avoid keeping a reference to `cfunc`. + call_template = typing.make_concrete_template( + name, key=func_name, signatures=self.nopython_signatures) + return call_template, pysig, args, kws + + def get_overload(self, sig): + """ + Return the compiled function for the given signature. + """ + args, return_type = sigutils.normalize_signature(sig) + return self.overloads[tuple(args)].entry_point + + @property + def is_compiling(self): + """ + Whether a specialization is currently being compiled. + """ + return self._compiling_counter + + def _compile_for_args(self, *args, **kws): + """ + For internal use. Compile a specialized version of the function + for the given *args* and *kws*, and return the resulting callable. + """ + assert not kws + # call any initialisation required for the compilation chain (e.g. + # extension point registration). + self._compilation_chain_init_hook() + + def error_rewrite(e, issue_type): + """ + Rewrite and raise Exception `e` with help supplied based on the + specified issue_type. + """ + if config.SHOW_HELP: + help_msg = errors.error_extras[issue_type] + e.patch_message('\n'.join((str(e).rstrip(), help_msg))) + if config.FULL_TRACEBACKS: + raise e + else: + raise e.with_traceback(None) + + argtypes = [] + for a in args: + if isinstance(a, OmittedArg): + argtypes.append(types.Omitted(a.value)) + else: + argtypes.append(self.typeof_pyval(a)) + + return_val = None + try: + return_val = self.compile(tuple(argtypes)) + except errors.ForceLiteralArg as e: + # Received request for compiler re-entry with the list of arguments + # indicated by e.requested_args. + # First, check if any of these args are already Literal-ized + already_lit_pos = [i for i in e.requested_args + if isinstance(args[i], types.Literal)] + if already_lit_pos: + # Abort compilation if any argument is already a Literal. + # Letting this continue will cause infinite compilation loop. + m = ("Repeated literal typing request.\n" + "{}.\n" + "This is likely caused by an error in typing. " + "Please see nested and suppressed exceptions.") + info = ', '.join('Arg #{} is {}'.format(i, args[i]) + for i in sorted(already_lit_pos)) + raise errors.CompilerError(m.format(info)) + # Convert requested arguments into a Literal. + args = [(types.literal + if i in e.requested_args + else lambda x: x)(args[i]) + for i, v in enumerate(args)] + # Re-enter compilation with the Literal-ized arguments + return_val = self._compile_for_args(*args) + + except errors.TypingError as e: + # Intercept typing error that may be due to an argument + # that failed inferencing as a Numba type + failed_args = [] + for i, arg in enumerate(args): + val = arg.value if isinstance(arg, OmittedArg) else arg + try: + tp = typeof(val, Purpose.argument) + except (errors.NumbaValueError, ValueError) as typeof_exc: + failed_args.append((i, str(typeof_exc))) + else: + if tp is None: + failed_args.append( + (i, f"cannot determine Numba type of value {val}")) + if failed_args: + # Patch error message to ease debugging + args_str = "\n".join( + f"- argument {i}: {err}" for i, err in failed_args + ) + msg = (f"{str(e).rstrip()} \n\nThis error may have been caused " + f"by the following argument(s):\n{args_str}\n") + e.patch_message(msg) + + error_rewrite(e, 'typing') + except errors.UnsupportedError as e: + # Something unsupported is present in the user code, add help info + error_rewrite(e, 'unsupported_error') + except (errors.NotDefinedError, errors.RedefinedError, + errors.VerificationError) as e: + # These errors are probably from an issue with either the code + # supplied being syntactically or otherwise invalid + error_rewrite(e, 'interpreter') + except errors.ConstantInferenceError as e: + # this is from trying to infer something as constant when it isn't + # or isn't supported as a constant + error_rewrite(e, 'constant_inference') + except Exception as e: + if config.SHOW_HELP: + if hasattr(e, 'patch_message'): + help_msg = errors.error_extras['reportable'] + e.patch_message('\n'.join((str(e).rstrip(), help_msg))) + # ignore the FULL_TRACEBACKS config, this needs reporting! + raise e + finally: + self._types_active_call.clear() + return return_val + + def inspect_llvm(self, signature=None): + """Get the LLVM intermediate representation generated by compilation. + + Parameters + ---------- + signature : tuple of numba types, optional + Specify a signature for which to obtain the LLVM IR. If None, the + IR is returned for all available signatures. + + Returns + ------- + llvm : dict[signature, str] or str + Either the LLVM IR string for the specified signature, or, if no + signature was given, a dictionary mapping signatures to LLVM IR + strings. + """ + if signature is not None: + lib = self.overloads[signature].library + return lib.get_llvm_str() + + return dict((sig, self.inspect_llvm(sig)) for sig in self.signatures) + + def inspect_asm(self, signature=None): + """Get the generated assembly code. + + Parameters + ---------- + signature : tuple of numba types, optional + Specify a signature for which to obtain the assembly code. If + None, the assembly code is returned for all available signatures. + + Returns + ------- + asm : dict[signature, str] or str + Either the assembly code for the specified signature, or, if no + signature was given, a dictionary mapping signatures to assembly + code. + """ + if signature is not None: + lib = self.overloads[signature].library + return lib.get_asm_str() + + return dict((sig, self.inspect_asm(sig)) for sig in self.signatures) + + def inspect_types(self, file=None, signature=None, + pretty=False, style='default', **kwargs): + """Print/return Numba intermediate representation (IR)-annotated code. + + Parameters + ---------- + file : file-like object, optional + File to which to print. Defaults to sys.stdout if None. Must be + None if ``pretty=True``. + signature : tuple of numba types, optional + Print/return the intermediate representation for only the given + signature. If None, the IR is printed for all available signatures. + pretty : bool, optional + If True, an Annotate object will be returned that can render the + IR with color highlighting in Jupyter and IPython. ``file`` must + be None if ``pretty`` is True. Additionally, the ``pygments`` + library must be installed for ``pretty=True``. + style : str, optional + Choose a style for rendering. Ignored if ``pretty`` is ``False``. + This is directly consumed by ``pygments`` formatters. To see a + list of available styles, import ``pygments`` and run + ``list(pygments.styles.get_all_styles())``. + + Returns + ------- + annotated : Annotate object, optional + Only returned if ``pretty=True``, otherwise this function is only + used for its printing side effect. If ``pretty=True``, an Annotate + object is returned that can render itself in Jupyter and IPython. + """ + overloads = self.overloads + if signature is not None: + overloads = {signature: self.overloads[signature]} + + if not pretty: + if file is None: + file = sys.stdout + + for ver, res in overloads.items(): + print("%s %s" % (self.py_func.__name__, ver), file=file) + print('-' * 80, file=file) + print(res.type_annotation, file=file) + print('=' * 80, file=file) + else: + if file is not None: + raise ValueError("`file` must be None if `pretty=True`") + from numba.core.annotations.pretty_annotate import Annotate + return Annotate(self, signature=signature, style=style) + + def inspect_cfg(self, signature=None, show_wrapper=None, **kwargs): + """ + For inspecting the CFG of the function. + + By default the CFG of the user function is shown. The *show_wrapper* + option can be set to "python" or "cfunc" to show the python wrapper + function or the *cfunc* wrapper function, respectively. + + Parameters accepted in kwargs + ----------------------------- + filename : string, optional + the name of the output file, if given this will write the output to + filename + view : bool, optional + whether to immediately view the optional output file + highlight : bool, set, dict, optional + what, if anything, to highlight, options are: + { incref : bool, # highlight NRT_incref calls + decref : bool, # highlight NRT_decref calls + returns : bool, # highlight exits which are normal returns + raises : bool, # highlight exits which are from raise + meminfo : bool, # highlight calls to NRT*meminfo + branches : bool, # highlight true/false branches + } + Default is True which sets all of the above to True. Supplying a set + of strings is also accepted, these are interpreted as key:True with + respect to the above dictionary. e.g. {'incref', 'decref'} would + switch on highlighting on increfs and decrefs. + interleave: bool, set, dict, optional + what, if anything, to interleave in the LLVM IR, options are: + { python: bool # interleave python source code with the LLVM IR + lineinfo: bool # interleave line information markers with the LLVM + # IR + } + Default is True which sets all of the above to True. Supplying a set + of strings is also accepted, these are interpreted as key:True with + respect to the above dictionary. e.g. {'python',} would + switch on interleaving of python source code in the LLVM IR. + strip_ir : bool, optional + Default is False. If set to True all LLVM IR that is superfluous to + that requested in kwarg `highlight` will be removed. + show_key : bool, optional + Default is True. Create a "key" for the highlighting in the rendered + CFG. + fontsize : int, optional + Default is 8. Set the fontsize in the output to this value. + """ + if signature is not None: + cres = self.overloads[signature] + lib = cres.library + if show_wrapper == 'python': + fname = cres.fndesc.llvm_cpython_wrapper_name + elif show_wrapper == 'cfunc': + fname = cres.fndesc.llvm_cfunc_wrapper_name + else: + fname = cres.fndesc.mangled_name + return lib.get_function_cfg(fname, py_func=self.py_func, **kwargs) + + return dict((sig, self.inspect_cfg(sig, show_wrapper=show_wrapper)) + for sig in self.signatures) + + def inspect_disasm_cfg(self, signature=None): + """ + For inspecting the CFG of the disassembly of the function. + + Requires python package: r2pipe + Requires radare2 binary on $PATH. + Notebook rendering requires python package: graphviz + + signature : tuple of Numba types, optional + Print/return the disassembly CFG for only the given signatures. + If None, the IR is printed for all available signatures. + """ + if signature is not None: + cres = self.overloads[signature] + lib = cres.library + return lib.get_disasm_cfg(cres.fndesc.mangled_name) + + return dict((sig, self.inspect_disasm_cfg(sig)) + for sig in self.signatures) + + def get_annotation_info(self, signature=None): + """ + Gets the annotation information for the function specified by + signature. If no signature is supplied a dictionary of signature to + annotation information is returned. + """ + signatures = self.signatures if signature is None else [signature] + out = collections.OrderedDict() + for sig in signatures: + cres = self.overloads[sig] + ta = cres.type_annotation + key = (ta.func_id.filename + ':' + str(ta.func_id.firstlineno + 1), + ta.signature) + out[key] = ta.annotate_raw()[key] + return out + + def _explain_ambiguous(self, *args, **kws): + """ + Callback for the C _Dispatcher object. + """ + assert not kws, "kwargs not handled" + args = tuple([self.typeof_pyval(a) for a in args]) + # The order here must be deterministic for testing purposes, which + # is ensured by the OrderedDict. + sigs = self.nopython_signatures + # This will raise + self.typingctx.resolve_overload(self.py_func, sigs, args, kws, + allow_ambiguous=False) + + def _explain_matching_error(self, *args, **kws): + """ + Callback for the C _Dispatcher object. + """ + assert not kws, "kwargs not handled" + args = [self.typeof_pyval(a) for a in args] + msg = ("No matching definition for argument type(s) %s" + % ', '.join(map(str, args))) + raise TypeError(msg) + + def _search_new_conversions(self, *args, **kws): + """ + Callback for the C _Dispatcher object. + Search for approximately matching signatures for the given arguments, + and ensure the corresponding conversions are registered in the C++ + type manager. + """ + assert not kws, "kwargs not handled" + args = [self.typeof_pyval(a) for a in args] + found = False + for sig in self.nopython_signatures: + conv = self.typingctx.install_possible_conversions(args, sig.args) + if conv: + found = True + return found + + def __repr__(self): + return "%s(%s)" % (type(self).__name__, self.py_func) + + def typeof_pyval(self, val): + """ + Resolve the Numba type of Python value *val*. + This is called from numba._dispatcher as a fallback if the native code + cannot decide the type. + """ + try: + tp = typeof(val, Purpose.argument) + except (errors.NumbaValueError, ValueError): + tp = types.pyobject + else: + if tp is None: + tp = types.pyobject + self._types_active_call.add(tp) + return tp + + def _callback_add_timer(self, duration, cres, lock_name): + md = cres.metadata + # md can be None when code is loaded from cache + if md is not None: + timers = md.setdefault("timers", {}) + if lock_name not in timers: + # Only write if the metadata does not exist + timers[lock_name] = duration + else: + msg = f"'{lock_name} metadata is already defined." + raise AssertionError(msg) + + def _callback_add_compiler_timer(self, duration, cres): + return self._callback_add_timer(duration, cres, + lock_name="compiler_lock") + + def _callback_add_llvm_timer(self, duration, cres): + return self._callback_add_timer(duration, cres, + lock_name="llvm_lock") + + +class _MemoMixin: + __uuid = None + # A {uuid -> instance} mapping, for deserialization + _memo = weakref.WeakValueDictionary() + # hold refs to last N functions deserialized, retaining them in _memo + # regardless of whether there is another reference + _recent = collections.deque(maxlen=config.FUNCTION_CACHE_SIZE) + + @property + def _uuid(self): + """ + An instance-specific UUID, to avoid multiple deserializations of + a given instance. + + Note: this is lazily-generated, for performance reasons. + """ + u = self.__uuid + if u is None: + u = str(uuid.uuid4()) + self._set_uuid(u) + return u + + def _set_uuid(self, u): + assert self.__uuid is None + self.__uuid = u + self._memo[u] = self + self._recent.append(self) + + +class Dispatcher(serialize.ReduceMixin, _MemoMixin, _DispatcherBase): + """ + Implementation of user-facing dispatcher objects (i.e. created using + the @jit decorator). + This is an abstract base class. Subclasses should define the targetdescr + class attribute. + """ + _fold_args = True + + __numba__ = 'py_func' + + def __init__(self, py_func, locals=None, targetoptions=None, + pipeline_class=compiler.Compiler): + """ + Parameters + ---------- + py_func: function object to be compiled + locals: dict, optional + Mapping of local variable names to Numba types. Used to override + the types deduced by the type inference engine. + targetoptions: dict, optional + Target-specific config options. + pipeline_class: type numba.compiler.CompilerBase + The compiler pipeline type. + """ + if locals is None: + locals = {} + if targetoptions is None: + targetoptions = {} + self.typingctx = self.targetdescr.typing_context + self.targetctx = self.targetdescr.target_context + + pysig = utils.pysignature(py_func) + arg_count = len(pysig.parameters) + can_fallback = not targetoptions.get('nopython', False) + + _DispatcherBase.__init__(self, arg_count, py_func, pysig, can_fallback, + exact_match_required=False) + + functools.update_wrapper(self, py_func) + + self.targetoptions = targetoptions + self.locals = locals + self._cache = NullCache() + compiler_class = _FunctionCompiler + self._compiler = compiler_class(py_func, self.targetdescr, + targetoptions, locals, pipeline_class) + self._cache_hits = collections.Counter() + self._cache_misses = collections.Counter() + + self._type = types.Dispatcher(self) + self.typingctx.insert_global(self, self._type) + + def dump(self, tab=''): + print(f'{tab}DUMP {type(self).__name__}[{self.py_func.__name__}' + f', type code={self._type._code}]') + for cres in self.overloads.values(): + cres.dump(tab=tab + ' ') + print(f'{tab}END DUMP {type(self).__name__}[{self.py_func.__name__}]') + + @property + def _numba_type_(self): + return types.Dispatcher(self) + + def enable_caching(self): + self._cache = FunctionCache(self.py_func) + + def __get__(self, obj, objtype=None): + '''Allow a JIT function to be bound as a method to an object''' + if obj is None: # Unbound method + return self + else: # Bound method + return pytypes.MethodType(self, obj) + + def _reduce_states(self): + """ + Reduce the instance for pickling. This will serialize + the original function as well the compilation options and + compiled signatures, but not the compiled code itself. + + NOTE: part of ReduceMixin protocol + """ + if self._can_compile: + sigs = [] + else: + sigs = [cr.signature for cr in self.overloads.values()] + + return dict( + uuid=str(self._uuid), + py_func=self.py_func, + locals=self.locals, + targetoptions=self.targetoptions, + can_compile=self._can_compile, + sigs=sigs, + ) + + @classmethod + def _rebuild(cls, uuid, py_func, locals, targetoptions, + can_compile, sigs): + """ + Rebuild an Dispatcher instance after it was __reduce__'d. + + NOTE: part of ReduceMixin protocol + """ + try: + return cls._memo[uuid] + except KeyError: + pass + self = cls(py_func, locals, targetoptions) + # Make sure this deserialization will be merged with subsequent ones + self._set_uuid(uuid) + for sig in sigs: + self.compile(sig) + self._can_compile = can_compile + return self + + def compile(self, sig): + with ExitStack() as scope: + cres = None + + def cb_compiler(dur): + if cres is not None: + self._callback_add_compiler_timer(dur, cres) + + def cb_llvm(dur): + if cres is not None: + self._callback_add_llvm_timer(dur, cres) + + scope.enter_context(ev.install_timer("numba:compiler_lock", + cb_compiler)) + scope.enter_context(ev.install_timer("numba:llvm_lock", cb_llvm)) + scope.enter_context(global_compiler_lock) + + if not self._can_compile: + raise RuntimeError("compilation disabled") + # Use counter to track recursion compilation depth + with self._compiling_counter: + args, return_type = sigutils.normalize_signature(sig) + # Don't recompile if signature already exists + existing = self.overloads.get(tuple(args)) + if existing is not None: + return existing.entry_point + # Try to load from disk cache + cres = self._cache.load_overload(sig, self.targetctx) + if cres is not None: + self._cache_hits[sig] += 1 + # XXX fold this in add_overload()? (also see compiler.py) + if not cres.objectmode: + self.targetctx.insert_user_function(cres.entry_point, + cres.fndesc, + [cres.library]) + self.add_overload(cres) + return cres.entry_point + + self._cache_misses[sig] += 1 + ev_details = dict( + dispatcher=self, + args=args, + return_type=return_type, + ) + with ev.trigger_event("numba:compile", data=ev_details): + try: + cres = self._compiler.compile(args, return_type) + except errors.ForceLiteralArg as e: + def folded(args, kws): + return self._compiler.fold_argument_types(args, + kws)[1] + raise e.bind_fold_arguments(folded) + self.add_overload(cres) + self._cache.save_overload(sig, cres) + return cres.entry_point + + def get_compile_result(self, sig): + """Compile (if needed) and return the compilation result with the + given signature. + + Returns ``CompileResult``. + Raises ``NumbaError`` if the signature is incompatible. + """ + atypes = tuple(sig.args) + if atypes not in self.overloads: + if self._can_compile: + # Compiling may raise any NumbaError + self.compile(atypes) + else: + msg = f"{sig} not available and compilation disabled" + raise errors.TypingError(msg) + return self.overloads[atypes] + + def recompile(self): + """ + Recompile all signatures afresh. + """ + sigs = list(self.overloads) + old_can_compile = self._can_compile + # Ensure the old overloads are disposed of, + # including compiled functions. + self._make_finalizer()() + self._reset_overloads() + self._cache.flush() + self._can_compile = True + try: + for sig in sigs: + self.compile(sig) + finally: + self._can_compile = old_can_compile + + @property + def stats(self): + return _CompileStats( + cache_path=self._cache.cache_path, + cache_hits=self._cache_hits, + cache_misses=self._cache_misses, + ) + + def parallel_diagnostics(self, signature=None, level=1): + """ + Print parallel diagnostic information for the given signature. If no + signature is present it is printed for all known signatures. level is + used to adjust the verbosity, level=1 (default) is minimal verbosity, + and 2, 3, and 4 provide increasing levels of verbosity. + """ + def dump(sig): + ol = self.overloads[sig] + pfdiag = ol.metadata.get('parfor_diagnostics', None) + if pfdiag is None: + msg = "No parfors diagnostic available, is 'parallel=True' set?" + raise ValueError(msg) + pfdiag.dump(level) + if signature is not None: + dump(signature) + else: + [dump(sig) for sig in self.signatures] + + def get_metadata(self, signature=None): + """ + Obtain the compilation metadata for a given signature. + """ + if signature is not None: + return self.overloads[signature].metadata + else: + return dict( + (sig,self.overloads[sig].metadata) for sig in self.signatures + ) + + def get_function_type(self): + """Return unique function type of dispatcher when possible, otherwise + return None. + + A Dispatcher instance has unique function type when it + contains exactly one compilation result and its compilation + has been disabled (via its disable_compile method). + """ + if not self._can_compile and len(self.overloads) == 1: + cres = tuple(self.overloads.values())[0] + return types.FunctionType(cres.signature) + + +class LiftedCode(serialize.ReduceMixin, _MemoMixin, _DispatcherBase): + """ + Implementation of the hidden dispatcher objects used for lifted code + (a lifted loop is really compiled as a separate function). + """ + _fold_args = False + can_cache = False + + def __init__(self, func_ir, typingctx, targetctx, flags, locals): + self.func_ir = func_ir + self.lifted_from = None + + self.typingctx = typingctx + self.targetctx = targetctx + self.flags = flags + self.locals = locals + + _DispatcherBase.__init__(self, self.func_ir.arg_count, + self.func_ir.func_id.func, + self.func_ir.func_id.pysig, + can_fallback=True, + exact_match_required=False) + + def _reduce_states(self): + """ + Reduce the instance for pickling. This will serialize + the original function as well the compilation options and + compiled signatures, but not the compiled code itself. + + NOTE: part of ReduceMixin protocol + """ + return dict( + uuid=self._uuid, func_ir=self.func_ir, flags=self.flags, + locals=self.locals, extras=self._reduce_extras(), + ) + + def _reduce_extras(self): + """ + NOTE: sub-class can override to add extra states + """ + return {} + + @classmethod + def _rebuild(cls, uuid, func_ir, flags, locals, extras): + """ + Rebuild an Dispatcher instance after it was __reduce__'d. + + NOTE: part of ReduceMixin protocol + """ + try: + return cls._memo[uuid] + except KeyError: + pass + + # NOTE: We are assuming that this is must be cpu_target, which is true + # for now. + # TODO: refactor this to not assume on `cpu_target` + + from numba.core import registry + typingctx = registry.cpu_target.typing_context + targetctx = registry.cpu_target.target_context + + self = cls(func_ir, typingctx, targetctx, flags, locals, **extras) + self._set_uuid(uuid) + return self + + def get_source_location(self): + """Return the starting line number of the loop. + """ + return self.func_ir.loc.line + + def _pre_compile(self, args, return_type, flags): + """Pre-compile actions + """ + pass + + @abstractmethod + def compile(self, sig): + """Lifted code should implement a compilation method that will return + a CompileResult.entry_point for the given signature.""" + pass + + def _get_dispatcher_for_current_target(self): + # Lifted code does not honor the target switch currently. + # No work has been done to check if this can be allowed. + return self + + +class LiftedLoop(LiftedCode): + def _pre_compile(self, args, return_type, flags): + assert not flags.enable_looplift, "Enable looplift flags is on" + + def compile(self, sig): + with ExitStack() as scope: + cres = None + + def cb_compiler(dur): + if cres is not None: + self._callback_add_compiler_timer(dur, cres) + + def cb_llvm(dur): + if cres is not None: + self._callback_add_llvm_timer(dur, cres) + + scope.enter_context(ev.install_timer("numba:compiler_lock", + cb_compiler)) + scope.enter_context(ev.install_timer("numba:llvm_lock", cb_llvm)) + scope.enter_context(global_compiler_lock) + + # Use counter to track recursion compilation depth + with self._compiling_counter: + # XXX this is mostly duplicated from Dispatcher. + flags = self.flags + args, return_type = sigutils.normalize_signature(sig) + + # Don't recompile if signature already exists + # (e.g. if another thread compiled it before we got the lock) + existing = self.overloads.get(tuple(args)) + if existing is not None: + return existing.entry_point + + self._pre_compile(args, return_type, flags) + + # copy the flags, use nopython first + npm_loop_flags = flags.copy() + npm_loop_flags.force_pyobject = False + + pyobject_loop_flags = flags.copy() + pyobject_loop_flags.force_pyobject = True + + # Clone IR to avoid (some of the) mutation in the rewrite pass + cloned_func_ir_npm = self.func_ir.copy() + cloned_func_ir_fbk = self.func_ir.copy() + + ev_details = dict( + dispatcher=self, + args=args, + return_type=return_type, + ) + with ev.trigger_event("numba:compile", data=ev_details): + # this emulates "object mode fall-back", try nopython, if it + # fails, then try again in object mode. + try: + cres = compiler.compile_ir(typingctx=self.typingctx, + targetctx=self.targetctx, + func_ir=cloned_func_ir_npm, + args=args, + return_type=return_type, + flags=npm_loop_flags, + locals=self.locals, + lifted=(), + lifted_from=self.lifted_from, + is_lifted_loop=True,) + except errors.TypingError: + cres = compiler.compile_ir(typingctx=self.typingctx, + targetctx=self.targetctx, + func_ir=cloned_func_ir_fbk, + args=args, + return_type=return_type, + flags=pyobject_loop_flags, + locals=self.locals, + lifted=(), + lifted_from=self.lifted_from, + is_lifted_loop=True,) + # Check typing error if object mode is used + if (cres.typing_error is not None): + raise cres.typing_error + self.add_overload(cres) + return cres.entry_point + + +class LiftedWith(LiftedCode): + + can_cache = True + + def _reduce_extras(self): + return dict(output_types=self.output_types) + + @property + def _numba_type_(self): + return types.Dispatcher(self) + + def get_call_template(self, args, kws): + """ + Get a typing.ConcreteTemplate for this dispatcher and the given + *args* and *kws* types. This enables the resolving of the return type. + + A (template, pysig, args, kws) tuple is returned. + """ + # Ensure an overload is available + if self._can_compile: + self.compile(tuple(args)) + + pysig = None + # Create function type for typing + func_name = self.py_func.__name__ + name = "CallTemplate({0})".format(func_name) + # The `key` isn't really used except for diagnosis here, + # so avoid keeping a reference to `cfunc`. + call_template = typing.make_concrete_template( + name, key=func_name, signatures=self.nopython_signatures) + return call_template, pysig, args, kws + + def compile(self, sig): + # this is similar to LiftedLoop's compile but does not have the + # "fallback" to object mode part. + with ExitStack() as scope: + cres = None + + def cb_compiler(dur): + if cres is not None: + self._callback_add_compiler_timer(dur, cres) + + def cb_llvm(dur): + if cres is not None: + self._callback_add_llvm_timer(dur, cres) + + scope.enter_context(ev.install_timer("numba:compiler_lock", + cb_compiler)) + scope.enter_context(ev.install_timer("numba:llvm_lock", cb_llvm)) + scope.enter_context(global_compiler_lock) + + # Use counter to track recursion compilation depth + with self._compiling_counter: + # XXX this is mostly duplicated from Dispatcher. + flags = self.flags + args, return_type = sigutils.normalize_signature(sig) + + # Don't recompile if signature already exists + # (e.g. if another thread compiled it before we got the lock) + existing = self.overloads.get(tuple(args)) + if existing is not None: + return existing.entry_point + + self._pre_compile(args, return_type, flags) + + # Clone IR to avoid (some of the) mutation in the rewrite pass + cloned_func_ir = self.func_ir.copy() + + ev_details = dict( + dispatcher=self, + args=args, + return_type=return_type, + ) + with ev.trigger_event("numba:compile", data=ev_details): + cres = compiler.compile_ir(typingctx=self.typingctx, + targetctx=self.targetctx, + func_ir=cloned_func_ir, + args=args, + return_type=return_type, + flags=flags, locals=self.locals, + lifted=(), + lifted_from=self.lifted_from, + is_lifted_loop=True,) + + # Check typing error if object mode is used + if (cres.typing_error is not None and + not flags.enable_pyobject): + raise cres.typing_error + self.add_overload(cres) + return cres.entry_point + + +class ObjModeLiftedWith(LiftedWith): + def __init__(self, *args, **kwargs): + self.output_types = kwargs.pop('output_types', None) + super(LiftedWith, self).__init__(*args, **kwargs) + if not self.flags.force_pyobject: + raise ValueError("expecting `flags.force_pyobject`") + if self.output_types is None: + raise TypeError('`output_types` must be provided') + # switch off rewrites, they have no effect + self.flags.no_rewrites = True + + @property + def _numba_type_(self): + return types.ObjModeDispatcher(self) + + def get_call_template(self, args, kws): + """ + Get a typing.ConcreteTemplate for this dispatcher and the given + *args* and *kws* types. This enables the resolving of the return type. + + A (template, pysig, args, kws) tuple is returned. + """ + assert not kws + self._legalize_arg_types(args) + # Coerce to object mode + args = [types.ffi_forced_object] * len(args) + + if self._can_compile: + self.compile(tuple(args)) + + signatures = [typing.signature(self.output_types, *args)] + pysig = None + func_name = self.py_func.__name__ + name = "CallTemplate({0})".format(func_name) + call_template = typing.make_concrete_template( + name, key=func_name, signatures=signatures) + + return call_template, pysig, args, kws + + def _legalize_arg_types(self, args): + for i, a in enumerate(args, start=1): + if isinstance(a, types.List): + msg = ( + 'Does not support list type inputs into ' + 'with-context for arg {}' + ) + raise errors.TypingError(msg.format(i)) + elif isinstance(a, types.Dispatcher): + msg = ( + 'Does not support function type inputs into ' + 'with-context for arg {}' + ) + raise errors.TypingError(msg.format(i)) + + @global_compiler_lock + def compile(self, sig): + args, _ = sigutils.normalize_signature(sig) + sig = (types.ffi_forced_object,) * len(args) + return super().compile(sig) + + +# Initialize typeof machinery +_dispatcher.typeof_init( + OmittedArg, + dict((str(t), t._code) for t in types.number_domain)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/entrypoints.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/entrypoints.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb0de4e3fcc66dfefa32d6c5b99752aac0f8757 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/entrypoints.py @@ -0,0 +1,46 @@ +import logging +import warnings + +from importlib import metadata as importlib_metadata + + +_already_initialized = False +logger = logging.getLogger(__name__) + + +def init_all(): + """Execute all `numba_extensions` entry points with the name `init` + + If extensions have already been initialized, this function does nothing. + """ + global _already_initialized + if _already_initialized: + return + + # Must put this here to avoid extensions re-triggering initialization + _already_initialized = True + + def load_ep(entry_point): + """Loads a given entry point. Warns and logs on failure. + """ + logger.debug('Loading extension: %s', entry_point) + try: + func = entry_point.load() + func() + except Exception as e: + msg = (f"Numba extension module '{entry_point.module}' " + f"failed to load due to '{type(e).__name__}({str(e)})'.") + warnings.warn(msg, stacklevel=3) + logger.debug('Extension loading failed for: %s', entry_point) + + eps = importlib_metadata.entry_points() + # Split, Python 3.10+ and importlib_metadata 3.6+ have the "selectable" + # interface, versions prior to that do not. See "compatibility note" in: + # https://docs.python.org/3.10/library/importlib.metadata.html#entry-points + if hasattr(eps, 'select'): + for entry_point in eps.select(group="numba_extensions", name="init"): + load_ep(entry_point) + else: + for entry_point in eps.get("numba_extensions", ()): + if entry_point.name == "init": + load_ep(entry_point) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/environment.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc5feb59defcbabc02fd96d728a94d307e84c4a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/environment.py @@ -0,0 +1,64 @@ +import weakref +import importlib + +from numba import _dynfunc + + +class Environment(_dynfunc.Environment): + """Stores globals and constant pyobjects for runtime. + + It is often needed to convert b/w nopython objects and pyobjects. + """ + __slots__ = ('env_name', '__weakref__') + # A weak-value dictionary to store live environment with env_name as the + # key. + _memo = weakref.WeakValueDictionary() + + @classmethod + def from_fndesc(cls, fndesc): + try: + # Avoid creating new Env + return cls._memo[fndesc.env_name] + except KeyError: + inst = cls(fndesc.lookup_globals()) + inst.env_name = fndesc.env_name + cls._memo[fndesc.env_name] = inst + return inst + + def can_cache(self): + is_dyn = '__name__' not in self.globals + return not is_dyn + + def __reduce__(self): + return _rebuild_env, ( + self.globals.get('__name__'), + self.consts, + self.env_name, + ) + + def __del__(self): + return + + def __repr__(self): + return f"" + + +def _rebuild_env(modname, consts, env_name): + env = lookup_environment(env_name) + if env is not None: + return env + + mod = importlib.import_module(modname) + env = Environment(mod.__dict__) + env.consts[:] = consts + env.env_name = env_name + # Cache loaded object + Environment._memo[env_name] = env + return env + + +def lookup_environment(env_name): + """Returns the Environment object for the given name; + or None if not found + """ + return Environment._memo.get(env_name) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/errors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..f41893aae1df628d1e19500db17b850e8ba30fe4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/errors.py @@ -0,0 +1,875 @@ +""" +Numba-specific errors and warnings. +""" + + +import abc +import contextlib +import os +import warnings +import numba.core.config +import numpy as np +from collections import defaultdict +from functools import wraps +from abc import abstractmethod + +# Filled at the end +__all__ = [] + + +def _is_numba_core_config_loaded(): + """ + To detect if numba.core.config has been initialized due to circular imports. + """ + try: + numba.core.config + except AttributeError: + return False + else: + return True + + +class NumbaWarning(Warning): + """ + Base category for all Numba compiler warnings. + """ + + def __init__(self, msg, loc=None, highlighting=True, ): + self.msg = msg + self.loc = loc + + # If a warning is emitted inside validation of env-vars in + # numba.core.config. Highlighting will not be available. + if highlighting and _is_numba_core_config_loaded(): + highlight = termcolor().errmsg + else: + def highlight(x): + return x + if loc: + super(NumbaWarning, self).__init__( + highlight("%s\n%s\n" % (msg, loc.strformat()))) + else: + super(NumbaWarning, self).__init__(highlight("%s" % (msg,))) + + +class NumbaPerformanceWarning(NumbaWarning): + """ + Warning category for when an operation might not be + as fast as expected. + """ + + +class NumbaDeprecationWarning(NumbaWarning, DeprecationWarning): + """ + Warning category for use of a deprecated feature. + """ + + +class NumbaPendingDeprecationWarning(NumbaWarning, PendingDeprecationWarning): + """ + Warning category for use of a feature that is pending deprecation. + """ + + +class NumbaParallelSafetyWarning(NumbaWarning): + """ + Warning category for when an operation in a prange + might not have parallel semantics. + """ + + +class NumbaTypeSafetyWarning(NumbaWarning): + """ + Warning category for unsafe casting operations. + """ + + +class NumbaExperimentalFeatureWarning(NumbaWarning): + """ + Warning category for using an experimental feature. + """ + + +class NumbaInvalidConfigWarning(NumbaWarning): + """ + Warning category for using an invalid configuration. + """ + + +class NumbaPedanticWarning(NumbaWarning): + """ + Warning category for reporting pedantic messages. + """ + def __init__(self, msg, **kwargs): + super().__init__(f"{msg}\n{pedantic_warning_info}") + + +class NumbaIRAssumptionWarning(NumbaPedanticWarning): + """ + Warning category for reporting an IR assumption violation. + """ + + +class NumbaDebugInfoWarning(NumbaWarning): + """ + Warning category for an issue with the emission of debug information. + """ + + +class NumbaSystemWarning(NumbaWarning): + """ + Warning category for an issue with the system configuration. + """ + +# These are needed in the color formatting of errors setup + + +class _ColorScheme(metaclass=abc.ABCMeta): + + @abstractmethod + def code(self, msg): + pass + + @abstractmethod + def errmsg(self, msg): + pass + + @abstractmethod + def filename(self, msg): + pass + + @abstractmethod + def indicate(self, msg): + pass + + @abstractmethod + def highlight(self, msg): + pass + + @abstractmethod + def reset(self, msg): + pass + + +class _DummyColorScheme(_ColorScheme): + + def __init__(self, theme=None): + pass + + def code(self, msg): + pass + + def errmsg(self, msg): + pass + + def filename(self, msg): + pass + + def indicate(self, msg): + pass + + def highlight(self, msg): + pass + + def reset(self, msg): + pass + + +# holds reference to the instance of the terminal color scheme in use +_termcolor_inst = None + +try: + import colorama + + # If the colorama version is < 0.3.9 it can break stdout/stderr in some + # situations, as a result if this condition is met colorama is disabled and + # the user is warned. Note that early versions did not have a __version__. + colorama_version = getattr(colorama, '__version__', '0.0.0') + + if tuple([int(x) for x in colorama_version.split('.')]) < (0, 3, 9): + msg = ("Insufficiently recent colorama version found. " + "Numba requires colorama >= 0.3.9") + # warn the user + warnings.warn(msg) + # trip the exception to disable color errors + raise ImportError + + # If Numba is running in testsuite mode then do not use error message + # coloring so CI system output is consistently readable without having + # to read between shell escape characters. + if os.environ.get('NUMBA_DISABLE_ERROR_MESSAGE_HIGHLIGHTING', None): + raise ImportError # just to trigger the exception handler below + +except ImportError: + + class NOPColorScheme(_DummyColorScheme): + def __init__(self, theme=None): + if theme is not None: + raise ValueError("specifying a theme has no effect") + _DummyColorScheme.__init__(self, theme=theme) + + def code(self, msg): + return msg + + def errmsg(self, msg): + return msg + + def filename(self, msg): + return msg + + def indicate(self, msg): + return msg + + def highlight(self, msg): + return msg + + def reset(self, msg): + return msg + + def termcolor(): + global _termcolor_inst + if _termcolor_inst is None: + _termcolor_inst = NOPColorScheme() + return _termcolor_inst + +else: + + from colorama import init, reinit, deinit, Fore, Style + + class ColorShell(object): + _has_initialized = False + + def __init__(self): + init() + self._has_initialized = True + + def __enter__(self): + if self._has_initialized: + reinit() + + def __exit__(self, *exc_detail): + Style.RESET_ALL + deinit() + + class reset_terminal(object): + def __init__(self): + self._buf = bytearray(b'') + + def __enter__(self): + return self._buf + + def __exit__(self, *exc_detail): + self._buf += bytearray(Style.RESET_ALL.encode('utf-8')) + + # define some default themes, if more are added, update the envvars docs! + themes = {} + + # No color added, just bold weighting + themes['no_color'] = {'code': None, + 'errmsg': None, + 'filename': None, + 'indicate': None, + 'highlight': None, + 'reset': None, } + + # suitable for terminals with a dark background + themes['dark_bg'] = {'code': Fore.BLUE, + 'errmsg': Fore.YELLOW, + 'filename': Fore.WHITE, + 'indicate': Fore.GREEN, + 'highlight': Fore.RED, + 'reset': Style.RESET_ALL, } + + # suitable for terminals with a light background + themes['light_bg'] = {'code': Fore.BLUE, + 'errmsg': Fore.BLACK, + 'filename': Fore.MAGENTA, + 'indicate': Fore.BLACK, + 'highlight': Fore.RED, + 'reset': Style.RESET_ALL, } + + # suitable for terminals with a blue background + themes['blue_bg'] = {'code': Fore.WHITE, + 'errmsg': Fore.YELLOW, + 'filename': Fore.MAGENTA, + 'indicate': Fore.CYAN, + 'highlight': Fore.RED, + 'reset': Style.RESET_ALL, } + + # suitable for use in jupyter notebooks + themes['jupyter_nb'] = {'code': Fore.BLACK, + 'errmsg': Fore.BLACK, + 'filename': Fore.GREEN, + 'indicate': Fore.CYAN, + 'highlight': Fore.RED, + 'reset': Style.RESET_ALL, } + + default_theme = themes['no_color'] + + class HighlightColorScheme(_DummyColorScheme): + def __init__(self, theme=default_theme): + self._code = theme['code'] + self._errmsg = theme['errmsg'] + self._filename = theme['filename'] + self._indicate = theme['indicate'] + self._highlight = theme['highlight'] + self._reset = theme['reset'] + _DummyColorScheme.__init__(self, theme=theme) + + def _markup(self, msg, color=None, style=Style.BRIGHT): + features = '' + if color: + features += color + if style: + features += style + with ColorShell(): + with reset_terminal() as mu: + mu += features.encode('utf-8') + mu += (msg).encode('utf-8') + return mu.decode('utf-8') + + def code(self, msg): + return self._markup(msg, self._code) + + def errmsg(self, msg): + return self._markup(msg, self._errmsg) + + def filename(self, msg): + return self._markup(msg, self._filename) + + def indicate(self, msg): + return self._markup(msg, self._indicate) + + def highlight(self, msg): + return self._markup(msg, self._highlight) + + def reset(self, msg): + return self._markup(msg, self._reset) + + def termcolor(): + global _termcolor_inst + if _termcolor_inst is None: + scheme = themes[numba.core.config.COLOR_SCHEME] + _termcolor_inst = HighlightColorScheme(scheme) + return _termcolor_inst + + +pedantic_warning_info = """ +This warning came from an internal pedantic check. Please report the warning +message and traceback, along with a minimal reproducer at: +https://github.com/numba/numba/issues/new?template=bug_report.md +""" + +feedback_details = """ +Please report the error message and traceback, along with a minimal reproducer +at: https://github.com/numba/numba/issues/new?template=bug_report.md + +If more help is needed please feel free to speak to the Numba core developers +directly at: https://gitter.im/numba/numba + +Thanks in advance for your help in improving Numba! +""" + +unsupported_error_info = """ +Unsupported functionality was found in the code Numba was trying to compile. + +If this functionality is important to you please file a feature request at: +https://github.com/numba/numba/issues/new?template=feature_request.md +""" + +interpreter_error_info = """ +Unsupported Python functionality was found in the code Numba was trying to +compile. This error could be due to invalid code, does the code work +without Numba? (To temporarily disable Numba JIT, set the `NUMBA_DISABLE_JIT` +environment variable to non-zero, and then rerun the code). + +If the code is valid and the unsupported functionality is important to you +please file a feature request at: +https://github.com/numba/numba/issues/new?template=feature_request.md + +To see Python/NumPy features supported by the latest release of Numba visit: +https://numba.readthedocs.io/en/stable/reference/pysupported.html +and +https://numba.readthedocs.io/en/stable/reference/numpysupported.html +""" + +constant_inference_info = """ +Numba could not make a constant out of something that it decided should be +a constant. This could well be a current limitation in Numba's internals, +however please first check that your code is valid for compilation, +particularly with respect to string interpolation (not supported!) and +the requirement of compile time constants as arguments to exceptions: +https://numba.readthedocs.io/en/stable/reference/pysupported.html?highlight=exceptions#constructs + +If the code is valid and the unsupported functionality is important to you +please file a feature request at: +https://github.com/numba/numba/issues/new?template=feature_request.md + +If you think your code should work with Numba. %s +""" % feedback_details + +typing_error_info = """ +This is not usually a problem with Numba itself but instead often caused by +the use of unsupported features or an issue in resolving types. + +To see Python/NumPy features supported by the latest release of Numba visit: +https://numba.readthedocs.io/en/stable/reference/pysupported.html +and +https://numba.readthedocs.io/en/stable/reference/numpysupported.html + +For more information about typing errors and how to debug them visit: +https://numba.readthedocs.io/en/stable/user/troubleshoot.html#my-code-doesn-t-compile + +If you think your code should work with Numba, please report the error message +and traceback, along with a minimal reproducer at: +https://github.com/numba/numba/issues/new?template=bug_report.md +""" + +reportable_issue_info = """ +------------------------------------------------------------------------------- +This should not have happened, a problem has occurred in Numba's internals. +You are currently using Numba version %s. +%s +""" % (numba.__version__, feedback_details) + +error_extras = dict() +error_extras['unsupported_error'] = unsupported_error_info +error_extras['typing'] = typing_error_info +error_extras['reportable'] = reportable_issue_info +error_extras['interpreter'] = interpreter_error_info +error_extras['constant_inference'] = constant_inference_info + + +def deprecated(arg): + """Define a deprecation decorator. + An optional string should refer to the new API to be used instead. + + Example: + @deprecated + def old_func(): ... + + @deprecated('new_func') + def old_func(): ...""" + + subst = arg if isinstance(arg, str) else None + + def decorator(func): + def wrapper(*args, **kwargs): + msg = "Call to deprecated function \"{}\"." + if subst: + msg += "\n Use \"{}\" instead." + warnings.warn(msg.format(func.__name__, subst), + category=DeprecationWarning, stacklevel=2) + return func(*args, **kwargs) + + return wraps(func)(wrapper) + + if not subst: + return decorator(arg) + else: + return decorator + + +class WarningsFixer(object): + """ + An object "fixing" warnings of a given category caught during + certain phases. The warnings can have their filename and lineno fixed, + and they are deduplicated as well. + + When used as a context manager, any warnings caught by `.catch_warnings()` + will be flushed at the exit of the context manager. + """ + + def __init__(self, category): + self._category = category + # {(filename, lineno, category) -> messages} + self._warnings = defaultdict(set) + + @contextlib.contextmanager + def catch_warnings(self, filename=None, lineno=None): + """ + Store warnings and optionally fix their filename and lineno. + """ + with warnings.catch_warnings(record=True) as wlist: + warnings.simplefilter('always', self._category) + yield + + for w in wlist: + msg = str(w.message) + if issubclass(w.category, self._category): + # Store warnings of this category for deduplication + filename = filename or w.filename + lineno = lineno or w.lineno + self._warnings[filename, lineno, w.category].add(msg) + else: + # Simply emit other warnings again + warnings.warn_explicit(msg, w.category, + w.filename, w.lineno) + + def flush(self): + """ + Emit all stored warnings. + """ + def key(arg): + # It is possible through codegen to create entirely identical + # warnings, this leads to comparing types when sorting which breaks + # on Python 3. Key as str() and if the worse happens then `id` + # creates some uniqueness + return str(arg) + str(id(arg)) + + for (filename, lineno, category), messages in sorted( + self._warnings.items(), key=key): + for msg in sorted(messages): + warnings.warn_explicit(msg, category, filename, lineno) + self._warnings.clear() + + def __enter__(self): + return + + def __exit__(self, exc_type, exc_value, traceback): + self.flush() + + +class NumbaError(Exception): + def __init__(self, msg, loc=None, highlighting=True): + self.msg = msg + self.loc = loc + if highlighting: + highlight = termcolor().errmsg + else: + def highlight(x): + return x + + if loc: + new_msg = "%s\n%s\n" % (msg, loc.strformat()) + else: + new_msg = "%s" % (msg,) + super(NumbaError, self).__init__(highlight(new_msg)) + + @property + def contexts(self): + try: + return self._contexts + except AttributeError: + self._contexts = lst = [] + return lst + + def add_context(self, msg): + """ + Add contextual info. The exception message is expanded with the new + contextual information. + """ + if msg in self.contexts: + # avoid duplicating contexts + return self + self.contexts.append(msg) + f = termcolor().errmsg('{0}\n') + termcolor().filename('During: {1}') + newmsg = f.format(self, msg) + self.args = (newmsg,) + return self + + def patch_message(self, new_message): + """ + Change the error message to the given new message. + """ + self.args = (new_message,) + self.args[1:] + + +class UnsupportedError(NumbaError): + """ + Numba does not have an implementation for this functionality. + """ + + +class UnsupportedBytecodeError(Exception): + """Unsupported bytecode is non-recoverable + """ + def __init__(self, msg, loc=None): + super().__init__(f"{msg}. Raised from {loc}") + + +class UnsupportedRewriteError(UnsupportedError): + """UnsupportedError from rewrite passes + """ + pass + + +class IRError(NumbaError): + """ + An error occurred during Numba IR generation. + """ + pass + + +class RedefinedError(IRError): + """ + An error occurred during interpretation of IR due to variable redefinition. + """ + pass + + +class NotDefinedError(IRError): + """ + An undefined variable is encountered during interpretation of IR. + """ + + def __init__(self, name, loc=None): + self.name = name + msg = ("The compiler failed to analyze the bytecode. " + "Variable '%s' is not defined." % name) + super(NotDefinedError, self).__init__(msg, loc=loc) + + +class VerificationError(IRError): + """ + An error occurred during IR verification. Once Numba's internal + representation (IR) is constructed it is then verified to ensure that + terminators are both present and in the correct places within the IR. If + it is the case that this condition is not met, a VerificationError is + raised. + """ + pass + + +class DeprecationError(NumbaError): + """ + Functionality is deprecated. + """ + pass + + +class LoweringError(NumbaError): + """ + An error occurred during lowering. + """ + + def __init__(self, msg, loc=None): + super(LoweringError, self).__init__(msg, loc=loc) + + +class UnsupportedParforsError(NumbaError): + """ + An error occurred because parfors is not supported on the platform. + """ + pass + + +class ForbiddenConstruct(LoweringError): + """ + A forbidden Python construct was encountered (e.g. use of locals()). + """ + pass + + +class TypingError(NumbaError): + """ + A type inference failure. + """ + pass + + +class UntypedAttributeError(TypingError): + def __init__(self, value, attr, loc=None): + module = getattr(value, 'pymod', None) + if module is not None and module == np: + # unsupported numpy feature. + msg = ("Use of unsupported NumPy function 'numpy.%s' " + "or unsupported use of the function.") % attr + else: + msg = "Unknown attribute '{attr}' of type {type}" + msg = msg.format(type=value, attr=attr) + super(UntypedAttributeError, self).__init__(msg, loc=loc) + + +class ByteCodeSupportError(NumbaError): + """ + Failure to extract the bytecode of the user's function. + """ + + def __init__(self, msg, loc=None): + super(ByteCodeSupportError, self).__init__(msg, loc=loc) + + +class CompilerError(NumbaError): + """ + Some high-level error in the compiler. + """ + pass + + +class ConstantInferenceError(NumbaError): + """ + Failure during constant inference. + """ + + def __init__(self, value, loc=None): + super(ConstantInferenceError, self).__init__(value, loc=loc) + + +class InternalError(NumbaError): + """ + For wrapping internal error occurred within the compiler + """ + + def __init__(self, exception): + super(InternalError, self).__init__(str(exception)) + self.old_exception = exception + + +class InternalTargetMismatchError(InternalError): + """For signalling a target mismatch error occurred internally within the + compiler. + """ + def __init__(self, kind, target_hw, hw_clazz): + msg = (f"{kind.title()} being resolved on a target from which it does " + f"not inherit. Local target is {target_hw}, declared " + f"target class is {hw_clazz}.") + super().__init__(msg) + + +class NonexistentTargetError(InternalError): + """For signalling that a target that does not exist was requested. + """ + pass + + +class RequireLiteralValue(TypingError): + """ + For signalling that a function's typing requires a constant value for + some of its arguments. + """ + pass + + +class ForceLiteralArg(NumbaError): + """A Pseudo-exception to signal the dispatcher to type an argument literally + + Attributes + ---------- + requested_args : frozenset[int] + requested positions of the arguments. + """ + def __init__(self, arg_indices, fold_arguments=None, loc=None): + """ + Parameters + ---------- + arg_indices : Sequence[int] + requested positions of the arguments. + fold_arguments: callable + A function ``(tuple, dict) -> tuple`` that binds and flattens + the ``args`` and ``kwargs``. + loc : numba.ir.Loc or None + """ + super(ForceLiteralArg, self).__init__( + "Pseudo-exception to force literal arguments in the dispatcher", + loc=loc, + ) + self.requested_args = frozenset(arg_indices) + self.fold_arguments = fold_arguments + + def bind_fold_arguments(self, fold_arguments): + """Bind the fold_arguments function + """ + # to avoid circular import + from numba.core.utils import chain_exception + + e = ForceLiteralArg(self.requested_args, fold_arguments, + loc=self.loc) + return chain_exception(e, self) + + def combine(self, other): + """Returns a new instance by or'ing the requested_args. + """ + if not isinstance(other, ForceLiteralArg): + m = '*other* must be a {} but got a {} instead' + raise TypeError(m.format(ForceLiteralArg, type(other))) + return ForceLiteralArg(self.requested_args | other.requested_args) + + def __or__(self, other): + """Same as self.combine(other) + """ + return self.combine(other) + + +class LiteralTypingError(TypingError): + """ + Failure in typing a Literal type + """ + pass + + +# These Exception classes are just Numba copies of their Python equivalents for +# use internally in cases where we want e.g. type inference to keep on trying. +# Exceptions extending from NumbaError are considered "special" by Numba's +# internals and are treated differently to standard Python exceptions which are +# permitted to just propagate up the stack. + +class NumbaValueError(TypingError): + pass + + +class NumbaTypeError(TypingError): + pass + + +class NumbaAttributeError(TypingError): + pass + + +class NumbaAssertionError(TypingError): + pass + + +class NumbaNotImplementedError(TypingError): + pass + + +class NumbaKeyError(TypingError): + pass + + +class NumbaIndexError(TypingError): + pass + + +class NumbaRuntimeError(NumbaError): + pass + + +def _format_msg(fmt, args, kwargs): + # If no formatting arguments are supplied, return the string unchanged. + # This avoids KeyError when fmt contains curly braces, which can be + # interpreted as format fields. + if not args and not kwargs: + return fmt + return fmt.format(*args, **kwargs) + + +_numba_path = os.path.dirname(__file__) +loc_info = {} + + +@contextlib.contextmanager +def new_error_context(fmt_, *args, **kwargs): + """ + A contextmanager that prepend contextual information to any exception + raised within. + + The first argument is a message that describes the context. It can be a + format string. If there are additional arguments, it will be used as + ``fmt_.format(*args, **kwargs)`` to produce the final message string. + """ + loc = kwargs.get('loc', None) + if loc is not None and not loc.filename.startswith(_numba_path): + loc_info.update(kwargs) + + try: + yield + except NumbaError as e: + e.add_context(_format_msg(fmt_, args, kwargs)) + raise + + +__all__ += [name for (name, value) in globals().items() + if not name.startswith('_') and isinstance(value, type) + and issubclass(value, (Exception, Warning))] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/event.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/event.py new file mode 100644 index 0000000000000000000000000000000000000000..7190db75b28454ede95bcac9de7e4a504209ba86 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/event.py @@ -0,0 +1,485 @@ +""" +The ``numba.core.event`` module provides a simple event system for applications +to register callbacks to listen to specific compiler events. + +The following events are built in: + +- ``"numba:compile"`` is broadcast when a dispatcher is compiling. Events of + this kind have ``data`` defined to be a ``dict`` with the following + key-values: + + - ``"dispatcher"``: the dispatcher object that is compiling. + - ``"args"``: the argument types. + - ``"return_type"``: the return type. + +- ``"numba:compiler_lock"`` is broadcast when the internal compiler-lock is + acquired. This is mostly used internally to measure time spent with the lock + acquired. + +- ``"numba:llvm_lock"`` is broadcast when the internal LLVM-lock is acquired. + This is used internally to measure time spent with the lock acquired. + +- ``"numba:run_pass"`` is broadcast when a compiler pass is running. + + - ``"name"``: pass name. + - ``"qualname"``: qualified name of the function being compiled. + - ``"module"``: module name of the function being compiled. + - ``"flags"``: compilation flags. + - ``"args"``: argument types. + - ``"return_type"`` return type. + +Applications can register callbacks that are listening for specific events using +``register(kind: str, listener: Listener)``, where ``listener`` is an instance +of ``Listener`` that defines custom actions on occurrence of the specific event. +""" + +import os +import json +import atexit +import abc +import enum +import time +import threading +from timeit import default_timer as timer +from contextlib import contextmanager, ExitStack +from collections import defaultdict + +from numba.core import config, utils + + +class EventStatus(enum.Enum): + """Status of an event. + """ + START = enum.auto() + END = enum.auto() + + +# Builtin event kinds. +_builtin_kinds = frozenset([ + "numba:compiler_lock", + "numba:compile", + "numba:llvm_lock", + "numba:run_pass", +]) + + +def _guard_kind(kind): + """Guard to ensure that an event kind is valid. + + All event kinds with a "numba:" prefix must be defined in the pre-defined + ``numba.core.event._builtin_kinds``. + Custom event kinds are allowed by not using the above prefix. + + Parameters + ---------- + kind : str + + Return + ------ + res : str + """ + if kind.startswith("numba:") and kind not in _builtin_kinds: + msg = (f"{kind} is not a valid event kind, " + "it starts with the reserved prefix 'numba:'") + raise ValueError(msg) + return kind + + +class Event: + """An event. + + Parameters + ---------- + kind : str + status : EventStatus + data : any; optional + Additional data for the event. + exc_details : 3-tuple; optional + Same 3-tuple for ``__exit__``. + """ + def __init__(self, kind, status, data=None, exc_details=None): + self._kind = _guard_kind(kind) + self._status = status + self._data = data + self._exc_details = (None + if exc_details is None or exc_details[0] is None + else exc_details) + + @property + def kind(self): + """Event kind + + Returns + ------- + res : str + """ + return self._kind + + @property + def status(self): + """Event status + + Returns + ------- + res : EventStatus + """ + return self._status + + @property + def data(self): + """Event data + + Returns + ------- + res : object + """ + return self._data + + @property + def is_start(self): + """Is it a *START* event? + + Returns + ------- + res : bool + """ + return self._status == EventStatus.START + + @property + def is_end(self): + """Is it an *END* event? + + Returns + ------- + res : bool + """ + return self._status == EventStatus.END + + @property + def is_failed(self): + """Is the event carrying an exception? + + This is used for *END* event. This method will never return ``True`` + in a *START* event. + + Returns + ------- + res : bool + """ + return self._exc_details is None + + def __str__(self): + data = (f"{type(self.data).__qualname__}" + if self.data is not None else "None") + return f"Event({self._kind}, {self._status}, data: {data})" + + __repr__ = __str__ + + +_registered = defaultdict(list) + + +def register(kind, listener): + """Register a listener for a given event kind. + + Parameters + ---------- + kind : str + listener : Listener + """ + assert isinstance(listener, Listener) + kind = _guard_kind(kind) + _registered[kind].append(listener) + + +def unregister(kind, listener): + """Unregister a listener for a given event kind. + + Parameters + ---------- + kind : str + listener : Listener + """ + assert isinstance(listener, Listener) + kind = _guard_kind(kind) + lst = _registered[kind] + lst.remove(listener) + + +def broadcast(event): + """Broadcast an event to all registered listeners. + + Parameters + ---------- + event : Event + """ + for listener in _registered[event.kind]: + listener.notify(event) + + +class Listener(abc.ABC): + """Base class for all event listeners. + """ + @abc.abstractmethod + def on_start(self, event): + """Called when there is a *START* event. + + Parameters + ---------- + event : Event + """ + pass + + @abc.abstractmethod + def on_end(self, event): + """Called when there is a *END* event. + + Parameters + ---------- + event : Event + """ + pass + + def notify(self, event): + """Notify this Listener with the given Event. + + Parameters + ---------- + event : Event + """ + if event.is_start: + self.on_start(event) + elif event.is_end: + self.on_end(event) + else: + raise AssertionError("unreachable") + + +class TimingListener(Listener): + """A listener that measures the total time spent between *START* and + *END* events during the time this listener is active. + """ + def __init__(self): + self._depth = 0 + + def on_start(self, event): + if self._depth == 0: + self._ts = timer() + self._depth += 1 + + def on_end(self, event): + self._depth -= 1 + if self._depth == 0: + last = getattr(self, "_duration", 0) + self._duration = (timer() - self._ts) + last + + @property + def done(self): + """Returns a ``bool`` indicating whether a measurement has been made. + + When this returns ``False``, the matching event has never fired. + If and only if this returns ``True``, ``.duration`` can be read without + error. + """ + return hasattr(self, "_duration") + + @property + def duration(self): + """Returns the measured duration. + + This may raise ``AttributeError``. Users can use ``.done`` to check + that a measurement has been made. + """ + return self._duration + + +class RecordingListener(Listener): + """A listener that records all events and stores them in the ``.buffer`` + attribute as a list of 2-tuple ``(float, Event)``, where the first element + is the time the event occurred as returned by ``time.time()`` and the second + element is the event. + """ + def __init__(self): + self.buffer = [] + + def on_start(self, event): + self.buffer.append((time.time(), event)) + + def on_end(self, event): + self.buffer.append((time.time(), event)) + + +@contextmanager +def install_listener(kind, listener): + """Install a listener for event "kind" temporarily within the duration of + the context. + + Returns + ------- + res : Listener + The *listener* provided. + + Examples + -------- + + >>> with install_listener("numba:compile", listener): + >>> some_code() # listener will be active here. + >>> other_code() # listener will be unregistered by this point. + + """ + register(kind, listener) + try: + yield listener + finally: + unregister(kind, listener) + + +@contextmanager +def install_timer(kind, callback): + """Install a TimingListener temporarily to measure the duration of + an event. + + If the context completes successfully, the *callback* function is executed. + The *callback* function is expected to take a float argument for the + duration in seconds. + + Returns + ------- + res : TimingListener + + Examples + -------- + + This is equivalent to: + + >>> with install_listener(kind, TimingListener()) as res: + >>> ... + """ + tl = TimingListener() + with install_listener(kind, tl): + yield tl + + if tl.done: + callback(tl.duration) + + +@contextmanager +def install_recorder(kind): + """Install a RecordingListener temporarily to record all events. + + Once the context is closed, users can use ``RecordingListener.buffer`` + to access the recorded events. + + Returns + ------- + res : RecordingListener + + Examples + -------- + + This is equivalent to: + + >>> with install_listener(kind, RecordingListener()) as res: + >>> ... + """ + rl = RecordingListener() + with install_listener(kind, rl): + yield rl + + +def start_event(kind, data=None): + """Trigger the start of an event of *kind* with *data*. + + Parameters + ---------- + kind : str + Event kind. + data : any; optional + Extra event data. + """ + evt = Event(kind=kind, status=EventStatus.START, data=data) + broadcast(evt) + + +def end_event(kind, data=None, exc_details=None): + """Trigger the end of an event of *kind*, *exc_details*. + + Parameters + ---------- + kind : str + Event kind. + data : any; optional + Extra event data. + exc_details : 3-tuple; optional + Same 3-tuple for ``__exit__``. Or, ``None`` if no error. + """ + evt = Event( + kind=kind, status=EventStatus.END, data=data, exc_details=exc_details, + ) + broadcast(evt) + + +@contextmanager +def trigger_event(kind, data=None): + """A context manager to trigger the start and end events of *kind* with + *data*. The start event is triggered when entering the context. + The end event is triggered when exiting the context. + + Parameters + ---------- + kind : str + Event kind. + data : any; optional + Extra event data. + """ + with ExitStack() as scope: + @scope.push + def on_exit(*exc_details): + end_event(kind, data=data, exc_details=exc_details) + + start_event(kind, data=data) + yield + + +def _prepare_chrome_trace_data(listener: RecordingListener): + """Prepare events in `listener` for serializing as chrome trace data. + """ + # The spec for the trace event format can be found at: + # https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit # noqa + # This code only uses the JSON Array Format for simplicity. + pid = os.getpid() + tid = threading.get_native_id() + evs = [] + for ts, rec in listener.buffer: + data = rec.data + cat = str(rec.kind) + ts_scaled = ts * 1_000_000 # scale to microseconds + ph = 'B' if rec.is_start else 'E' + name = data['name'] + args = data + ev = dict( + cat=cat, pid=pid, tid=tid, ts=ts_scaled, ph=ph, name=name, + args=args, + ) + evs.append(ev) + return evs + + +def _setup_chrome_trace_exit_handler(): + """Setup a RecordingListener and an exit handler to write the captured + events to file. + """ + listener = RecordingListener() + register("numba:run_pass", listener) + filename = config.CHROME_TRACE + + @atexit.register + def _write_chrome_trace(): + # The following output file is not multi-process safe. + evs = _prepare_chrome_trace_data(listener) + with open(filename, "w") as out: + json.dump(evs, out, cls=utils._LazyJSONEncoder) + + +if config.CHROME_TRACE: + _setup_chrome_trace_exit_handler() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.py new file mode 100644 index 0000000000000000000000000000000000000000..31a6b5157eeb1b0a9b8673108b57f1e378d794a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.py @@ -0,0 +1,596 @@ +import os +import uuid +import weakref +import collections +import functools +from types import MappingProxyType + +import numba +from numba.core import types, errors, utils, config + +# Exported symbols +from numba.core.typing.typeof import typeof_impl # noqa: F401 +from numba.core.typing.asnumbatype import as_numba_type # noqa: F401 +from numba.core.typing.templates import infer, infer_getattr # noqa: F401 +from numba.core.imputils import ( # noqa: F401 + lower_builtin, lower_getattr, lower_getattr_generic, # noqa: F401 + lower_setattr, lower_setattr_generic, lower_cast) # noqa: F401 +from numba.core.datamodel import models # noqa: F401 +from numba.core.datamodel import register_default as register_model # noqa: F401, E501 +from numba.core.pythonapi import box, unbox, reflect, NativeValue # noqa: F401 +from numba._helperlib import _import_cython_function # noqa: F401 +from numba.core.serialize import ReduceMixin + + +def type_callable(func): + """ + Decorate a function as implementing typing for the callable *func*. + *func* can be a callable object (probably a global) or a string + denoting a built-in operation (such 'getitem' or '__array_wrap__') + """ + from numba.core.typing.templates import (CallableTemplate, infer, + infer_global) + if not callable(func) and not isinstance(func, str): + raise TypeError("`func` should be a function or string") + try: + func_name = func.__name__ + except AttributeError: + func_name = str(func) + + def decorate(typing_func): + def generic(self): + return typing_func(self.context) + + name = "%s_CallableTemplate" % (func_name,) + bases = (CallableTemplate,) + class_dict = dict(key=func, generic=generic) + template = type(name, bases, class_dict) + infer(template) + if callable(func): + infer_global(func, types.Function(template)) + return typing_func + + return decorate + + +# By default, an *overload* does not have a cpython wrapper because it is not +# callable from python. It also has `nopython=True`, this has been default since +# its inception! +_overload_default_jit_options = {'no_cpython_wrapper': True, + 'nopython':True} + + +def overload( + func, + jit_options=MappingProxyType({}), + strict=True, + inline='never', + prefer_literal=False, + **kwargs, +): + """ + A decorator marking the decorated function as typing and implementing + *func* in nopython mode. + + The decorated function will have the same formal parameters as *func* + and be passed the Numba types of those parameters. It should return + a function implementing *func* for the given types. + + Here is an example implementing len() for tuple types:: + + @overload(len) + def tuple_len(seq): + if isinstance(seq, types.BaseTuple): + n = len(seq) + def len_impl(seq): + return n + return len_impl + + Compiler options can be passed as an dictionary using the **jit_options** + argument. + + Overloading strictness (that the typing and implementing signatures match) + is enforced by the **strict** keyword argument, it is recommended that this + is set to True (default). + + To handle a function that accepts imprecise types, an overload + definition can return 2-tuple of ``(signature, impl_function)``, where + the ``signature`` is a ``typing.Signature`` specifying the precise + signature to be used; and ``impl_function`` is the same implementation + function as in the simple case. + + If the kwarg inline determines whether the overload is inlined in the + calling function and can be one of three values: + * 'never' (default) - the overload is never inlined. + * 'always' - the overload is always inlined. + * a function that takes two arguments, both of which are instances of a + namedtuple with fields: + * func_ir + * typemap + * calltypes + * signature + The first argument holds the information from the caller, the second + holds the information from the callee. The function should return Truthy + to determine whether to inline, this essentially permitting custom + inlining rules (typical use might be cost models). + + The *prefer_literal* option allows users to control if literal types should + be tried first or last. The default (`False`) is to use non-literal types. + Implementations that can specialize based on literal values should set the + option to `True`. Note, this option maybe expanded in the near future to + allow for more control (e.g. disabling non-literal types). + + **kwargs prescribes additional arguments passed through to the overload + template. The only accepted key at present is 'target' which is a string + corresponding to the target that this overload should be bound against. + """ + from numba.core.typing.templates import make_overload_template, infer_global + + # set default options + jit_options = dict(jit_options) + opts = _overload_default_jit_options.copy() + opts.update(jit_options) # let user options override + + # TODO: abort now if the kwarg 'target' relates to an unregistered target, + # this requires sorting out the circular imports first. + + def decorate(overload_func): + template = make_overload_template(func, overload_func, opts, strict, + inline, prefer_literal, **kwargs) + infer(template) + if callable(func): + infer_global(func, types.Function(template)) + return overload_func + + return decorate + + +def register_jitable(*args, **kwargs): + """ + Register a regular python function that can be executed by the python + interpreter and can be compiled into a nopython function when referenced + by other jit'ed functions. Can be used as:: + + @register_jitable + def foo(x, y): + return x + y + + Or, with compiler options:: + + @register_jitable(_nrt=False) # disable runtime allocation + def foo(x, y): + return x + y + + """ + def wrap(fn): + # It is just a wrapper for @overload + inline = kwargs.pop('inline', 'never') + + @overload(fn, jit_options=kwargs, inline=inline, strict=False) + def ov_wrap(*args, **kwargs): + return fn + return fn + + if kwargs: + return wrap + else: + return wrap(*args) + + +def overload_attribute(typ, attr, **kwargs): + """ + A decorator marking the decorated function as typing and implementing + attribute *attr* for the given Numba type in nopython mode. + + *kwargs* are passed to the underlying `@overload` call. + + Here is an example implementing .nbytes for array types:: + + @overload_attribute(types.Array, 'nbytes') + def array_nbytes(arr): + def get(arr): + return arr.size * arr.itemsize + return get + """ + # TODO implement setters + from numba.core.typing.templates import make_overload_attribute_template + + def decorate(overload_func): + template = make_overload_attribute_template( + typ, attr, overload_func, + **kwargs + ) + infer_getattr(template) + overload(overload_func, **kwargs)(overload_func) + return overload_func + + return decorate + + +def _overload_method_common(typ, attr, **kwargs): + """Common code for overload_method and overload_classmethod + """ + from numba.core.typing.templates import make_overload_method_template + + def decorate(overload_func): + copied_kwargs = kwargs.copy() # avoid mutating parent dict + template = make_overload_method_template( + typ, attr, overload_func, + inline=copied_kwargs.pop('inline', 'never'), + prefer_literal=copied_kwargs.pop('prefer_literal', False), + **copied_kwargs, + ) + infer_getattr(template) + overload(overload_func, **kwargs)(overload_func) + return overload_func + + return decorate + + +def overload_method(typ, attr, **kwargs): + """ + A decorator marking the decorated function as typing and implementing + method *attr* for the given Numba type in nopython mode. + + *kwargs* are passed to the underlying `@overload` call. + + Here is an example implementing .take() for array types:: + + @overload_method(types.Array, 'take') + def array_take(arr, indices): + if isinstance(indices, types.Array): + def take_impl(arr, indices): + n = indices.shape[0] + res = np.empty(n, arr.dtype) + for i in range(n): + res[i] = arr[indices[i]] + return res + return take_impl + """ + return _overload_method_common(typ, attr, **kwargs) + + +def overload_classmethod(typ, attr, **kwargs): + """ + A decorator marking the decorated function as typing and implementing + classmethod *attr* for the given Numba type in nopython mode. + + + Similar to ``overload_method``. + + + Here is an example implementing a classmethod on the Array type to call + ``np.arange()``:: + + @overload_classmethod(types.Array, "make") + def ov_make(cls, nitems): + def impl(cls, nitems): + return np.arange(nitems) + return impl + + The above code will allow the following to work in jit-compiled code:: + + @njit + def foo(n): + return types.Array.make(n) + """ + return _overload_method_common(types.TypeRef(typ), attr, **kwargs) + + +def make_attribute_wrapper(typeclass, struct_attr, python_attr): + """ + Make an automatic attribute wrapper exposing member named *struct_attr* + as a read-only attribute named *python_attr*. + The given *typeclass*'s model must be a StructModel subclass. + """ + from numba.core.typing.templates import AttributeTemplate + from numba.core.datamodel import default_manager + from numba.core.datamodel.models import StructModel + from numba.core.imputils import impl_ret_borrowed + from numba.core import cgutils + + if not isinstance(typeclass, type) or not issubclass(typeclass, types.Type): + raise TypeError("typeclass should be a Type subclass, got %s" + % (typeclass,)) + + def get_attr_fe_type(typ): + """ + Get the Numba type of member *struct_attr* in *typ*. + """ + model = default_manager.lookup(typ) + if not isinstance(model, StructModel): + raise TypeError("make_struct_attribute_wrapper() needs a type " + "with a StructModel, but got %s" % (model,)) + return model.get_member_fe_type(struct_attr) + + @infer_getattr + class StructAttribute(AttributeTemplate): + key = typeclass + + def generic_resolve(self, typ, attr): + if attr == python_attr: + return get_attr_fe_type(typ) + + @lower_getattr(typeclass, python_attr) + def struct_getattr_impl(context, builder, typ, val): + val = cgutils.create_struct_proxy(typ)(context, builder, value=val) + attrty = get_attr_fe_type(typ) + attrval = getattr(val, struct_attr) + return impl_ret_borrowed(context, builder, attrty, attrval) + + +class _Intrinsic(ReduceMixin): + """ + Dummy callable for intrinsic + """ + _memo: weakref.WeakValueDictionary = weakref.WeakValueDictionary() + __cache_size = config.FUNCTION_CACHE_SIZE # type: ignore + # hold refs to last N functions deserialized, retaining them in _memo + # regardless of whether there is another reference + _recent: collections.deque = collections.deque(maxlen=__cache_size) + + __uuid = None + + def __init__(self, name, defn, prefer_literal=False, **kwargs): + self._ctor_kwargs = kwargs + self._name = name + self._defn = defn + self._prefer_literal = prefer_literal + functools.update_wrapper(self, defn) + + @property + def _uuid(self): + """ + An instance-specific UUID, to avoid multiple deserializations of + a given instance. + + Note this is lazily-generated, for performance reasons. + """ + u = self.__uuid + if u is None: + u = str(uuid.uuid1()) + self._set_uuid(u) + return u + + def _set_uuid(self, u): + assert self.__uuid is None + self.__uuid = u + self._memo[u] = self + self._recent.append(self) + + def _register(self): + # _ctor_kwargs + from numba.core.typing.templates import (make_intrinsic_template, + infer_global) + + template = make_intrinsic_template(self, self._defn, self._name, + prefer_literal=self._prefer_literal, + kwargs=self._ctor_kwargs) + infer(template) + infer_global(self, types.Function(template)) + + def __call__(self, *args, **kwargs): + """ + This is only defined to pretend to be a callable from CPython. + """ + msg = '{0} is not usable in pure-python'.format(self) + raise NotImplementedError(msg) + + def __repr__(self): + return "".format(self._name) + + def __deepcopy__(self, memo): + # NOTE: Intrinsic are immutable and we don't need to copy. + # This is triggered from deepcopy of statements. + return self + + def _reduce_states(self): + """ + NOTE: part of ReduceMixin protocol + """ + return dict(uuid=self._uuid, name=self._name, defn=self._defn) + + @classmethod + def _rebuild(cls, uuid, name, defn): + """ + NOTE: part of ReduceMixin protocol + """ + try: + return cls._memo[uuid] + except KeyError: + llc = cls(name=name, defn=defn) + llc._register() + llc._set_uuid(uuid) + return llc + + +def intrinsic(*args, **kwargs): + """ + A decorator marking the decorated function as typing and implementing + *func* in nopython mode using the llvmlite IRBuilder API. This is an escape + hatch for expert users to build custom LLVM IR that will be inlined to + the caller. + + The first argument to *func* is the typing context. The rest of the + arguments corresponds to the type of arguments of the decorated function. + These arguments are also used as the formal argument of the decorated + function. If *func* has the signature ``foo(typing_context, arg0, arg1)``, + the decorated function will have the signature ``foo(arg0, arg1)``. + + The return values of *func* should be a 2-tuple of expected type signature, + and a code-generation function that will passed to ``lower_builtin``. + For unsupported operation, return None. + + Here is an example implementing a ``cast_int_to_byte_ptr`` that cast + any integer to a byte pointer:: + + @intrinsic + def cast_int_to_byte_ptr(typingctx, src): + # check for accepted types + if isinstance(src, types.Integer): + # create the expected type signature + result_type = types.CPointer(types.uint8) + sig = result_type(types.uintp) + # defines the custom code generation + def codegen(context, builder, signature, args): + # llvm IRBuilder code here + [src] = args + rtype = signature.return_type + llrtype = context.get_value_type(rtype) + return builder.inttoptr(src, llrtype) + return sig, codegen + """ + # Make inner function for the actual work + def _intrinsic(func): + name = getattr(func, '__name__', str(func)) + llc = _Intrinsic(name, func, **kwargs) + llc._register() + return llc + + if not kwargs: + # No option is given + return _intrinsic(*args) + else: + # options are given, create a new callable to recv the + # definition function + def wrapper(func): + return _intrinsic(func) + return wrapper + + +def get_cython_function_address(module_name, function_name): + """ + Get the address of a Cython function. + + Args + ---- + module_name: + Name of the Cython module + function_name: + Name of the Cython function + + Returns + ------- + A Python int containing the address of the function + + """ + return _import_cython_function(module_name, function_name) + + +def include_path(): + """Returns the C include directory path. + """ + include_dir = os.path.dirname(os.path.dirname(numba.__file__)) + path = os.path.abspath(include_dir) + return path + + +def sentry_literal_args(pysig, literal_args, args, kwargs): + """Ensures that the given argument types (in *args* and *kwargs*) are + literally typed for a function with the python signature *pysig* and the + list of literal argument names in *literal_args*. + + Alternatively, this is the same as:: + + SentryLiteralArgs(literal_args).for_pysig(pysig).bind(*args, **kwargs) + """ + boundargs = pysig.bind(*args, **kwargs) + + # Find literal argument positions and whether it is satisfied. + request_pos = set() + missing = False + for i, (k, v) in enumerate(boundargs.arguments.items()): + if k in literal_args: + request_pos.add(i) + if not isinstance(v, types.Literal): + missing = True + if missing: + # Yes, there are missing required literal arguments + e = errors.ForceLiteralArg(request_pos) + + # A helper function to fold arguments + def folded(args, kwargs): + out = pysig.bind(*args, **kwargs).arguments.values() + return tuple(out) + + raise e.bind_fold_arguments(folded) + + +class SentryLiteralArgs(collections.namedtuple( + '_SentryLiteralArgs', ['literal_args'])): + """ + Parameters + ---------- + literal_args : Sequence[str] + A sequence of names for literal arguments + + Examples + -------- + + The following line: + + >>> SentryLiteralArgs(literal_args).for_pysig(pysig).bind(*args, **kwargs) + + is equivalent to: + + >>> sentry_literal_args(pysig, literal_args, args, kwargs) + """ + def for_function(self, func): + """Bind the sentry to the signature of *func*. + + Parameters + ---------- + func : Function + A python function. + + Returns + ------- + obj : BoundLiteralArgs + """ + return self.for_pysig(utils.pysignature(func)) + + def for_pysig(self, pysig): + """Bind the sentry to the given signature *pysig*. + + Parameters + ---------- + pysig : inspect.Signature + + + Returns + ------- + obj : BoundLiteralArgs + """ + return BoundLiteralArgs( + pysig=pysig, + literal_args=self.literal_args, + ) + + +class BoundLiteralArgs(collections.namedtuple( + 'BoundLiteralArgs', ['pysig', 'literal_args'])): + """ + This class is usually created by SentryLiteralArgs. + """ + def bind(self, *args, **kwargs): + """Bind to argument types. + """ + return sentry_literal_args( + self.pysig, + self.literal_args, + args, + kwargs, + ) + + +def is_jitted(function): + """Returns True if a function is wrapped by one of the Numba @jit + decorators, for example: numba.jit, numba.njit + + The purpose of this function is to provide a means to check if a function is + already JIT decorated. + """ + + # don't want to export this so import locally + from numba.core.dispatcher import Dispatcher + return isinstance(function, Dispatcher) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.pyi b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d7c7eba9710cfe596f4077ae9c7cdf936ea55ffc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/extending.pyi @@ -0,0 +1,128 @@ +import collections +import sys +import weakref + +from numba.core.serialize import ReduceMixin + + +def type_callable(func): + ... + + +def overload(func, jit_options={}, strict=True, inline='never', + prefer_literal=False, **kwargs): + ... + + +def register_jitable(*args, **kwargs): + ... + + +def overload_attribute(typ, attr, **kwargs): + ... + + +def _overload_method_common(typ, attr, **kwargs): + ... + + +def overload_method(typ, attr, **kwargs): + ... + + +def overload_classmethod(typ, attr, **kwargs): + ... + + +def make_attribute_wrapper(typeclass, struct_attr, python_attr): + ... + + +class _Intrinsic(ReduceMixin, Generic[P, R]): + _memo: weakref.WeakValueDictionary + _recent: collections.deque + + def __init__( + self, + name, + defn: Callable[Concatenate[object, P], R], + prefer_literal=False, + **kwargs + ): + ... + + @property + def _uuid(self): + ... + + def _set_uuid(self, u): + ... + + def _register(self): + ... + + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: + ... + + def __repr__(self): + ... + + def __deepcopy__(self, memo): + ... + + def _reduce_states(self): + ... + + @classmethod + def _rebuild(cls, uuid, name, defn): + ... + + +if sys.version_info >= (3, 10): + from typing import Callable, Concatenate, Generic, ParamSpec, TypeVar + + # Type of the parameters of the function being converted to an intrinsic, + # excluding the typing context parameter. + P = ParamSpec("P") + # Return type of the function being converted to an intrinsic + R = TypeVar("R") + + def intrinsic(*args, **kwargs) -> Callable[ + [Callable[Concatenate[object, P], R]], + Callable[P, R] + ]: + ... +else: + def intrinsic(*args, **kwargs): + ... + + +def get_cython_function_address(module_name, function_name): + ... + + +def include_path(): + ... + + +def sentry_literal_args(pysig, literal_args, args, kwargs): + ... + + +class SentryLiteralArgs(collections.namedtuple( + '_SentryLiteralArgs', ['literal_args'])): + def for_function(self, func): + ... + + def for_pysig(self, pysig): + ... + + +class BoundLiteralArgs(collections.namedtuple( + 'BoundLiteralArgs', ['pysig', 'literal_args'])): + def bind(self, *args, **kwargs): + ... + + +def is_jitted(function): + ... diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/externals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/externals.py new file mode 100644 index 0000000000000000000000000000000000000000..e181b5f43d9d8dda06a84ba93a176058cc5b1543 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/externals.py @@ -0,0 +1,155 @@ +""" +Register external C functions necessary for Numba code generation. +""" + +import sys + +from llvmlite import ir +import llvmlite.binding as ll + +from numba.core import utils, intrinsics +from numba import _helperlib + + +def _add_missing_symbol(symbol, addr): + """Add missing symbol into LLVM internal symtab + """ + if not ll.address_of_symbol(symbol): + ll.add_symbol(symbol, addr) + + +def _get_msvcrt_symbol(symbol): + """ + Under Windows, look up a symbol inside the C runtime + and return the raw pointer value as an integer. + """ + from ctypes import cdll, cast, c_void_p + f = getattr(cdll.msvcrt, symbol) + return cast(f, c_void_p).value + + +def compile_multi3(context): + """ + Compile the multi3() helper function used by LLVM + for 128-bit multiplication on 32-bit platforms. + """ + codegen = context.codegen() + library = codegen.create_library("multi3") + + ir_mod = library.create_ir_module("multi3") + + i64 = ir.IntType(64) + i128 = ir.IntType(128) + lower_mask = ir.Constant(i64, 0xffffffff) + _32 = ir.Constant(i64, 32) + _64 = ir.Constant(i128, 64) + + fn_type = ir.FunctionType(i128, [i128, i128]) + fn = ir.Function(ir_mod, fn_type, name="multi3") + + a, b = fn.args + bb = fn.append_basic_block() + builder = ir.IRBuilder(bb) + + # This implementation mimics compiler-rt's. + al = builder.trunc(a, i64) + bl = builder.trunc(b, i64) + ah = builder.trunc(builder.ashr(a, _64), i64) + bh = builder.trunc(builder.ashr(b, _64), i64) + + # Compute {rh, rl} = al * bl (unsigned 64-bit multiplication) + # rl = (al & 0xffffffff) * (bl & 0xffffffff) + rl = builder.mul(builder.and_(al, lower_mask), builder.and_(bl, lower_mask)) + # t = rl >> 32 + t = builder.lshr(rl, _32) + # rl &= 0xffffffff + rl = builder.and_(rl, lower_mask) + # t += (al >> 32) * (bl & 0xffffffff) + t = builder.add(t, builder.mul(builder.lshr(al, _32), + builder.and_(bl, lower_mask))) + # rl += t << 32 + rl = builder.add(rl, builder.shl(t, _32)) + # rh = t >> 32 + rh = builder.lshr(t, _32) + # t = rl >> 32 + t = builder.lshr(rl, _32) + # rl &= 0xffffffff + rl = builder.and_(rl, lower_mask) + # t += (bl >> 32) * (al & 0xffffffff) + t = builder.add(t, builder.mul(builder.lshr(bl, _32), + builder.and_(al, lower_mask))) + # rl += t << 32 + rl = builder.add(rl, builder.shl(t, _32)) + # rh += t >> 32 + rh = builder.add(rh, builder.lshr(t, _32)) + # rh += (al >> 32) * (bl >> 32) + rh = builder.add(rh, builder.mul(builder.lshr(al, _32), + builder.lshr(bl, _32))) + + # rh += (bh * al) + (bl * ah) + rh = builder.add(rh, builder.mul(bh, al)) + rh = builder.add(rh, builder.mul(bl, ah)) + + # r = rl + (rh << 64) + r = builder.zext(rl, i128) + r = builder.add(r, builder.shl(builder.zext(rh, i128), _64)) + builder.ret(r) + + library.add_ir_module(ir_mod) + library.finalize() + + return library + + +class _Installer(object): + + _installed = False + + def install(self, context): + """ + Install the functions into LLVM. This only needs to be done once, + as the mappings are persistent during the process lifetime. + """ + if not self._installed: + self._do_install(context) + self._installed = True + + +class _ExternalMathFunctions(_Installer): + """ + Map the math functions from the C runtime library into the LLVM + execution environment. + """ + + def _do_install(self, context): + is32bit = utils.MACHINE_BITS == 32 + c_helpers = _helperlib.c_helpers + + if sys.platform.startswith('win32') and is32bit: + # For Windows XP _ftol2 is not defined, we will just use + # _ftol as a replacement. + # On Windows 7, this is not necessary but will work anyway. + ftol = _get_msvcrt_symbol("_ftol") + _add_missing_symbol("_ftol2", ftol) + + elif sys.platform.startswith('linux') and is32bit: + _add_missing_symbol("__fixunsdfdi", c_helpers["fptoui"]) + _add_missing_symbol("__fixunssfdi", c_helpers["fptouif"]) + + if is32bit: + # Make the library immortal + self._multi3_lib = compile_multi3(context) + ptr = self._multi3_lib.get_pointer_to_function("multi3") + assert ptr + _add_missing_symbol("__multi3", ptr) + + # List available C-math + for fname in intrinsics.INTR_MATH: + # Force binding from CPython's C runtime library. + # (under Windows, different versions of the C runtime can + # be loaded at the same time, for example msvcrt100 by + # CPython and msvcrt120 by LLVM) + ll.add_symbol(fname, c_helpers[fname]) + + +c_math_functions = _ExternalMathFunctions() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/fastmathpass.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/fastmathpass.py new file mode 100644 index 0000000000000000000000000000000000000000..d6dd1b89c20cb78cd9b819663aa21ce270ce4bbe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/fastmathpass.py @@ -0,0 +1,44 @@ +from llvmlite import ir +from llvmlite.ir.transforms import Visitor, CallVisitor + + +class FastFloatBinOpVisitor(Visitor): + """ + A pass to add fastmath flag to float-binop instruction if they don't have + any flags. + """ + float_binops = frozenset(['fadd', 'fsub', 'fmul', 'fdiv', 'frem', 'fcmp']) + + def __init__(self, flags): + self.flags = flags + + def visit_Instruction(self, instr): + if instr.opname in self.float_binops: + if not instr.flags: + for flag in self.flags: + instr.flags.append(flag) + + +class FastFloatCallVisitor(CallVisitor): + """ + A pass to change all float function calls to use fastmath. + """ + + def __init__(self, flags): + self.flags = flags + + def visit_Call(self, instr): + # Add to any call that has float/double return type + if instr.type in (ir.FloatType(), ir.DoubleType()): + for flag in self.flags: + instr.fastmath.add(flag) + + +def rewrite_module(mod, options): + """ + Rewrite the given LLVM module to use fastmath everywhere. + """ + flags = options.flags + FastFloatBinOpVisitor(flags).visit(mod) + FastFloatCallVisitor(flags).visit(mod) + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/funcdesc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/funcdesc.py new file mode 100644 index 0000000000000000000000000000000000000000..0508a3aaeed8d5746d5f76f731620d6056a190b5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/funcdesc.py @@ -0,0 +1,230 @@ +""" +Function descriptors. +""" + +from collections import defaultdict +import importlib + +from numba.core import types, itanium_mangler +from numba.core.utils import _dynamic_modname, _dynamic_module + + +def default_mangler(name, argtypes, *, abi_tags=(), uid=None): + return itanium_mangler.mangle(name, argtypes, abi_tags=abi_tags, uid=uid) + + +def qualifying_prefix(modname, qualname): + """ + Returns a new string that is used for the first half of the mangled name. + """ + # XXX choose a different convention for object mode + return '{}.{}'.format(modname, qualname) if modname else qualname + + +class FunctionDescriptor(object): + """ + Base class for function descriptors: an object used to carry + useful metadata about a natively callable function. + + Note that while `FunctionIdentity` denotes a Python function + which is being concretely compiled by Numba, `FunctionDescriptor` + may be more "abstract". + """ + __slots__ = ('native', 'modname', 'qualname', 'doc', 'typemap', + 'calltypes', 'args', 'kws', 'restype', 'argtypes', + 'mangled_name', 'unique_name', 'env_name', 'global_dict', + 'inline', 'noalias', 'abi_tags', 'uid') + + def __init__(self, native, modname, qualname, unique_name, doc, + typemap, restype, calltypes, args, kws, mangler=None, + argtypes=None, inline=False, noalias=False, env_name=None, + global_dict=None, abi_tags=(), uid=None): + self.native = native + self.modname = modname + self.global_dict = global_dict + self.qualname = qualname + self.unique_name = unique_name + self.doc = doc + # XXX typemap and calltypes should be on the compile result, + # not the FunctionDescriptor + self.typemap = typemap + self.calltypes = calltypes + self.args = args + self.kws = kws + self.restype = restype + # Argument types + if argtypes is not None: + assert isinstance(argtypes, tuple), argtypes + self.argtypes = argtypes + else: + # Get argument types from the type inference result + # (note the "arg.FOO" convention as used in typeinfer + self.argtypes = tuple(self.typemap['arg.' + a] for a in args) + mangler = default_mangler if mangler is None else mangler + # The mangled name *must* be unique, else the wrong function can + # be chosen at link time. + qualprefix = qualifying_prefix(self.modname, self.qualname) + self.uid = uid + self.mangled_name = mangler( + qualprefix, self.argtypes, abi_tags=abi_tags, uid=uid, + ) + if env_name is None: + env_name = mangler(".NumbaEnv.{}".format(qualprefix), + self.argtypes, abi_tags=abi_tags, uid=uid) + self.env_name = env_name + self.inline = inline + self.noalias = noalias + self.abi_tags = abi_tags + + def lookup_globals(self): + """ + Return the global dictionary of the function. + It may not match the Module's globals if the function is created + dynamically (i.e. exec) + """ + return self.global_dict or self.lookup_module().__dict__ + + def lookup_module(self): + """ + Return the module in which this function is supposed to exist. + This may be a dummy module if the function was dynamically + generated or the module can't be found. + """ + if self.modname == _dynamic_modname: + return _dynamic_module + else: + try: + # ensure module exist + return importlib.import_module(self.modname) + except ImportError: + return _dynamic_module + + def lookup_function(self): + """ + Return the original function object described by this object. + """ + return getattr(self.lookup_module(), self.qualname) + + @property + def llvm_func_name(self): + """ + The LLVM-registered name for the raw function. + """ + return self.mangled_name + + # XXX refactor this + + @property + def llvm_cpython_wrapper_name(self): + """ + The LLVM-registered name for a CPython-compatible wrapper of the + raw function (i.e. a PyCFunctionWithKeywords). + """ + return itanium_mangler.prepend_namespace(self.mangled_name, + ns='cpython') + + @property + def llvm_cfunc_wrapper_name(self): + """ + The LLVM-registered name for a C-compatible wrapper of the + raw function. + """ + return 'cfunc.' + self.mangled_name + + def __repr__(self): + return "" % (self.unique_name) + + @classmethod + def _get_function_info(cls, func_ir): + """ + Returns + ------- + qualname, unique_name, modname, doc, args, kws, globals + + ``unique_name`` must be a unique name. + """ + func = func_ir.func_id.func + qualname = func_ir.func_id.func_qualname + # XXX to func_id + modname = func.__module__ + doc = func.__doc__ or '' + args = tuple(func_ir.arg_names) + kws = () # TODO + global_dict = None + + if modname is None: + # Dynamically generated function. + modname = _dynamic_modname + # Retain a reference to the dictionary of the function. + # This disables caching, serialization and pickling. + global_dict = func_ir.func_id.func.__globals__ + + unique_name = func_ir.func_id.unique_name + + return qualname, unique_name, modname, doc, args, kws, global_dict + + @classmethod + def _from_python_function(cls, func_ir, typemap, restype, + calltypes, native, mangler=None, + inline=False, noalias=False, abi_tags=()): + (qualname, unique_name, modname, doc, args, kws, global_dict, + ) = cls._get_function_info(func_ir) + + self = cls(native, modname, qualname, unique_name, doc, + typemap, restype, calltypes, + args, kws, mangler=mangler, inline=inline, noalias=noalias, + global_dict=global_dict, abi_tags=abi_tags, + uid=func_ir.func_id.unique_id) + return self + + +class PythonFunctionDescriptor(FunctionDescriptor): + """ + A FunctionDescriptor subclass for Numba-compiled functions. + """ + __slots__ = () + + @classmethod + def from_specialized_function(cls, func_ir, typemap, restype, calltypes, + mangler, inline, noalias, abi_tags): + """ + Build a FunctionDescriptor for a given specialization of a Python + function (in nopython mode). + """ + return cls._from_python_function(func_ir, typemap, restype, calltypes, + native=True, mangler=mangler, + inline=inline, noalias=noalias, + abi_tags=abi_tags) + + @classmethod + def from_object_mode_function(cls, func_ir): + """ + Build a FunctionDescriptor for an object mode variant of a Python + function. + """ + typemap = defaultdict(lambda: types.pyobject) + calltypes = typemap.copy() + restype = types.pyobject + return cls._from_python_function(func_ir, typemap, restype, calltypes, + native=False) + + +class ExternalFunctionDescriptor(FunctionDescriptor): + """ + A FunctionDescriptor subclass for opaque external functions + (e.g. raw C functions). + """ + __slots__ = () + + def __init__(self, name, restype, argtypes): + args = ["arg%d" % i for i in range(len(argtypes))] + + def mangler(a, x, abi_tags, uid=None): + return a + super(ExternalFunctionDescriptor, self + ).__init__(native=True, modname=None, qualname=name, + unique_name=name, doc='', typemap=None, + restype=restype, calltypes=None, args=args, + kws=None, + mangler=mangler, + argtypes=argtypes) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/generators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/generators.py new file mode 100644 index 0000000000000000000000000000000000000000..88456bdabb0639d10d993156d24ebf30c6eb9b8c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/generators.py @@ -0,0 +1,360 @@ +""" +Support for lowering generators. +""" + +import llvmlite.ir +from llvmlite.ir import Constant, IRBuilder + +from numba.core import types, config, cgutils +from numba.core.funcdesc import FunctionDescriptor + + +class GeneratorDescriptor(FunctionDescriptor): + """ + The descriptor for a generator's next function. + """ + __slots__ = () + + @classmethod + def from_generator_fndesc(cls, func_ir, fndesc, gentype, mangler): + """ + Build a GeneratorDescriptor for the generator returned by the + function described by *fndesc*, with type *gentype*. + + The generator inherits the env_name from the *fndesc*. + All emitted functions for the generator shares the same Env. + """ + assert isinstance(gentype, types.Generator) + restype = gentype.yield_type + args = ['gen'] + argtypes = (gentype,) + qualname = fndesc.qualname + '.next' + unique_name = fndesc.unique_name + '.next' + self = cls(fndesc.native, fndesc.modname, qualname, unique_name, + fndesc.doc, fndesc.typemap, restype, fndesc.calltypes, + args, fndesc.kws, argtypes=argtypes, mangler=mangler, + inline=False, env_name=fndesc.env_name) + return self + + @property + def llvm_finalizer_name(self): + """ + The LLVM name of the generator's finalizer function + (if .has_finalizer is true). + """ + return 'finalize_' + self.mangled_name + + +class BaseGeneratorLower(object): + """ + Base support class for lowering generators. + """ + + def __init__(self, lower): + self.context = lower.context + self.fndesc = lower.fndesc + self.library = lower.library + self.func_ir = lower.func_ir + self.lower = lower + + self.geninfo = lower.generator_info + self.gentype = self.get_generator_type() + self.gendesc = GeneratorDescriptor.from_generator_fndesc( + lower.func_ir, self.fndesc, self.gentype, self.context.mangler) + # Helps packing non-omitted arguments into a structure + self.arg_packer = self.context.get_data_packer(self.fndesc.argtypes) + + self.resume_blocks = {} + + @property + def call_conv(self): + return self.lower.call_conv + + def get_args_ptr(self, builder, genptr): + return cgutils.gep_inbounds(builder, genptr, 0, 1) + + def get_resume_index_ptr(self, builder, genptr): + return cgutils.gep_inbounds(builder, genptr, 0, 0, + name='gen.resume_index') + + def get_state_ptr(self, builder, genptr): + return cgutils.gep_inbounds(builder, genptr, 0, 2, + name='gen.state') + + def lower_init_func(self, lower): + """ + Lower the generator's initialization function (which will fill up + the passed-by-reference generator structure). + """ + lower.setup_function(self.fndesc) + + builder = lower.builder + + # Insert the generator into the target context in order to allow + # calling from other Numba-compiled functions. + lower.context.insert_generator(self.gentype, self.gendesc, + [self.library]) + + # Init argument values + lower.extract_function_arguments() + + lower.pre_lower() + + # Initialize the return structure (i.e. the generator structure). + retty = self.context.get_return_type(self.gentype) + # Structure index #0: the initial resume index (0 == start of generator) + resume_index = self.context.get_constant(types.int32, 0) + # Structure index #1: the function arguments + argsty = retty.elements[1] + statesty = retty.elements[2] + + lower.debug_print("# low_init_func incref") + # Incref all NRT arguments before storing into generator states + if self.context.enable_nrt: + for argty, argval in zip(self.fndesc.argtypes, lower.fnargs): + self.context.nrt.incref(builder, argty, argval) + + # Filter out omitted arguments + argsval = self.arg_packer.as_data(builder, lower.fnargs) + + # Zero initialize states + statesval = Constant(statesty, None) + gen_struct = cgutils.make_anonymous_struct(builder, + [resume_index, argsval, + statesval], + retty) + + retval = self.box_generator_struct(lower, gen_struct) + + lower.debug_print("# low_init_func before return") + self.call_conv.return_value(builder, retval) + lower.post_lower() + + def lower_next_func(self, lower): + """ + Lower the generator's next() function (which takes the + passed-by-reference generator structure and returns the next + yielded value). + """ + lower.setup_function(self.gendesc) + lower.debug_print("# lower_next_func: {0}".format(self.gendesc.unique_name)) + assert self.gendesc.argtypes[0] == self.gentype + builder = lower.builder + function = lower.function + + # Extract argument values and other information from generator struct + genptr, = self.call_conv.get_arguments(function) + self.arg_packer.load_into(builder, + self.get_args_ptr(builder, genptr), + lower.fnargs) + + self.resume_index_ptr = self.get_resume_index_ptr(builder, genptr) + self.gen_state_ptr = self.get_state_ptr(builder, genptr) + + prologue = function.append_basic_block("generator_prologue") + + # Lower the generator's Python code + entry_block_tail = lower.lower_function_body() + + # Add block for StopIteration on entry + stop_block = function.append_basic_block("stop_iteration") + builder.position_at_end(stop_block) + self.call_conv.return_stop_iteration(builder) + + # Add prologue switch to resume blocks + builder.position_at_end(prologue) + # First Python block is also the resume point on first next() call + first_block = self.resume_blocks[0] = lower.blkmap[lower.firstblk] + + # Create front switch to resume points + switch = builder.switch(builder.load(self.resume_index_ptr), + stop_block) + for index, block in self.resume_blocks.items(): + switch.add_case(index, block) + + # Close tail of entry block + builder.position_at_end(entry_block_tail) + builder.branch(prologue) + + def lower_finalize_func(self, lower): + """ + Lower the generator's finalizer. + """ + fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), + [self.context.get_value_type(self.gentype)]) + function = cgutils.get_or_insert_function( + lower.module, fnty, self.gendesc.llvm_finalizer_name) + entry_block = function.append_basic_block('entry') + builder = IRBuilder(entry_block) + + genptrty = self.context.get_value_type(self.gentype) + genptr = builder.bitcast(function.args[0], genptrty) + self.lower_finalize_func_body(builder, genptr) + + def return_from_generator(self, lower): + """ + Emit a StopIteration at generator end and mark the generator exhausted. + """ + indexval = Constant(self.resume_index_ptr.type.pointee, -1) + lower.builder.store(indexval, self.resume_index_ptr) + self.call_conv.return_stop_iteration(lower.builder) + + def create_resumption_block(self, lower, index): + block_name = "generator_resume%d" % (index,) + block = lower.function.append_basic_block(block_name) + lower.builder.position_at_end(block) + self.resume_blocks[index] = block + + def debug_print(self, builder, msg): + if config.DEBUG_JIT: + self.context.debug_print(builder, "DEBUGJIT: {0}".format(msg)) + +class GeneratorLower(BaseGeneratorLower): + """ + Support class for lowering nopython generators. + """ + + def get_generator_type(self): + return self.fndesc.restype + + def box_generator_struct(self, lower, gen_struct): + return gen_struct + + def lower_finalize_func_body(self, builder, genptr): + """ + Lower the body of the generator's finalizer: decref all live + state variables. + """ + self.debug_print(builder, "# generator: finalize") + if self.context.enable_nrt: + + # Always dereference all arguments + # self.debug_print(builder, "# generator: clear args") + args_ptr = self.get_args_ptr(builder, genptr) + for ty, val in self.arg_packer.load(builder, args_ptr): + self.context.nrt.decref(builder, ty, val) + + self.debug_print(builder, "# generator: finalize end") + builder.ret_void() + +class PyGeneratorLower(BaseGeneratorLower): + """ + Support class for lowering object mode generators. + """ + + def get_generator_type(self): + """ + Compute the actual generator type (the generator function's return + type is simply "pyobject"). + """ + return types.Generator( + gen_func=self.func_ir.func_id.func, + yield_type=types.pyobject, + arg_types=(types.pyobject,) * self.func_ir.arg_count, + state_types=(types.pyobject,) * len(self.geninfo.state_vars), + has_finalizer=True, + ) + + def box_generator_struct(self, lower, gen_struct): + """ + Box the raw *gen_struct* as a Python object. + """ + gen_ptr = cgutils.alloca_once_value(lower.builder, gen_struct) + return lower.pyapi.from_native_generator(gen_ptr, self.gentype, lower.envarg) + + def init_generator_state(self, lower): + """ + NULL-initialize all generator state variables, to avoid spurious + decref's on cleanup. + """ + lower.builder.store(Constant(self.gen_state_ptr.type.pointee, None), + self.gen_state_ptr) + + def lower_finalize_func_body(self, builder, genptr): + """ + Lower the body of the generator's finalizer: decref all live + state variables. + """ + pyapi = self.context.get_python_api(builder) + resume_index_ptr = self.get_resume_index_ptr(builder, genptr) + resume_index = builder.load(resume_index_ptr) + # If resume_index is 0, next() was never called + # If resume_index is -1, generator terminated cleanly + # (note function arguments are saved in state variables, + # so they don't need a separate cleanup step) + need_cleanup = builder.icmp_signed( + '>', resume_index, Constant(resume_index.type, 0)) + + with cgutils.if_unlikely(builder, need_cleanup): + # Decref all live vars (some may be NULL) + gen_state_ptr = self.get_state_ptr(builder, genptr) + for state_index in range(len(self.gentype.state_types)): + state_slot = cgutils.gep_inbounds(builder, gen_state_ptr, + 0, state_index) + ty = self.gentype.state_types[state_index] + val = self.context.unpack_value(builder, ty, state_slot) + pyapi.decref(val) + + builder.ret_void() + + +class LowerYield(object): + """ + Support class for lowering a particular yield point. + """ + + def __init__(self, lower, yield_point, live_vars): + self.lower = lower + self.context = lower.context + self.builder = lower.builder + self.genlower = lower.genlower + self.gentype = self.genlower.gentype + + self.gen_state_ptr = self.genlower.gen_state_ptr + self.resume_index_ptr = self.genlower.resume_index_ptr + self.yp = yield_point + self.inst = self.yp.inst + self.live_vars = live_vars + self.live_var_indices = [lower.generator_info.state_vars.index(v) + for v in live_vars] + + def lower_yield_suspend(self): + self.lower.debug_print("# generator suspend") + # Save live vars in state + for state_index, name in zip(self.live_var_indices, self.live_vars): + state_slot = cgutils.gep_inbounds(self.builder, self.gen_state_ptr, + 0, state_index) + ty = self.gentype.state_types[state_index] + # The yield might be in a loop, in which case the state might + # contain a predicate var that branches back to the loop head, in + # this case the var is live but in sequential lowering won't have + # been alloca'd yet, so do this here. + fetype = self.lower.typeof(name) + self.lower._alloca_var(name, fetype) + val = self.lower.loadvar(name) + # IncRef newly stored value + if self.context.enable_nrt: + self.context.nrt.incref(self.builder, ty, val) + + self.context.pack_value(self.builder, ty, val, state_slot) + # Save resume index + indexval = Constant(self.resume_index_ptr.type.pointee, + self.inst.index) + self.builder.store(indexval, self.resume_index_ptr) + self.lower.debug_print("# generator suspend end") + + def lower_yield_resume(self): + # Emit resumption point + self.genlower.create_resumption_block(self.lower, self.inst.index) + self.lower.debug_print("# generator resume") + # Reload live vars from state + for state_index, name in zip(self.live_var_indices, self.live_vars): + state_slot = cgutils.gep_inbounds(self.builder, self.gen_state_ptr, + 0, state_index) + ty = self.gentype.state_types[state_index] + val = self.context.unpack_value(self.builder, ty, state_slot) + self.lower.storevar(val, name) + # Previous storevar is making an extra incref + if self.context.enable_nrt: + self.context.nrt.decref(self.builder, ty, val) + self.lower.debug_print("# generator resume end") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/imputils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/imputils.py new file mode 100644 index 0000000000000000000000000000000000000000..06c35abb9cf99389b6015755fb9aec7048c8387f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/imputils.py @@ -0,0 +1,469 @@ +""" +Utilities to simplify the boilerplate for native lowering. +""" + + +import collections +import contextlib +import inspect +import functools +from enum import Enum + +from numba.core import typing, types, utils, cgutils +from numba.core.typing.templates import BaseRegistryLoader + + +class Registry(object): + """ + A registry of function and attribute implementations. + """ + def __init__(self, name='unspecified'): + self.name = name + self.functions = [] + self.getattrs = [] + self.setattrs = [] + self.casts = [] + self.constants = [] + + def lower(self, func, *argtys): + """ + Decorate an implementation of *func* for the given argument types. + *func* may be an actual global function object, or any + pseudo-function supported by Numba, such as "getitem". + + The decorated implementation has the signature + (context, builder, sig, args). + """ + def decorate(impl): + self.functions.append((impl, func, argtys)) + return impl + return decorate + + def _decorate_attr(self, impl, ty, attr, impl_list, decorator): + real_impl = decorator(impl, ty, attr) + impl_list.append((real_impl, attr, real_impl.signature)) + return impl + + def lower_getattr(self, ty, attr): + """ + Decorate an implementation of __getattr__ for type *ty* and + the attribute *attr*. + + The decorated implementation will have the signature + (context, builder, typ, val). + """ + def decorate(impl): + return self._decorate_attr(impl, ty, attr, self.getattrs, + _decorate_getattr) + return decorate + + def lower_getattr_generic(self, ty): + """ + Decorate the fallback implementation of __getattr__ for type *ty*. + + The decorated implementation will have the signature + (context, builder, typ, val, attr). The implementation is + called for attributes which haven't been explicitly registered + with lower_getattr(). + """ + return self.lower_getattr(ty, None) + + def lower_setattr(self, ty, attr): + """ + Decorate an implementation of __setattr__ for type *ty* and + the attribute *attr*. + + The decorated implementation will have the signature + (context, builder, sig, args). + """ + def decorate(impl): + return self._decorate_attr(impl, ty, attr, self.setattrs, + _decorate_setattr) + return decorate + + def lower_setattr_generic(self, ty): + """ + Decorate the fallback implementation of __setattr__ for type *ty*. + + The decorated implementation will have the signature + (context, builder, sig, args, attr). The implementation is + called for attributes which haven't been explicitly registered + with lower_setattr(). + """ + return self.lower_setattr(ty, None) + + def lower_cast(self, fromty, toty): + """ + Decorate the implementation of implicit conversion between + *fromty* and *toty*. + + The decorated implementation will have the signature + (context, builder, fromty, toty, val). + """ + def decorate(impl): + self.casts.append((impl, (fromty, toty))) + return impl + return decorate + + def lower_constant(self, ty): + """ + Decorate the implementation for creating a constant of type *ty*. + + The decorated implementation will have the signature + (context, builder, ty, pyval). + """ + def decorate(impl): + self.constants.append((impl, (ty,))) + return impl + return decorate + + def __repr__(self): + return f"Lowering Registry<{self.name}>" + + +class RegistryLoader(BaseRegistryLoader): + """ + An incremental loader for a target registry. + """ + registry_items = ('functions', 'getattrs', 'setattrs', 'casts', 'constants') + + +# Global registry for implementations of builtin operations +# (functions, attributes, type casts) +builtin_registry = Registry('builtin_registry') + +lower_builtin = builtin_registry.lower +lower_getattr = builtin_registry.lower_getattr +lower_getattr_generic = builtin_registry.lower_getattr_generic +lower_setattr = builtin_registry.lower_setattr +lower_setattr_generic = builtin_registry.lower_setattr_generic +lower_cast = builtin_registry.lower_cast +lower_constant = builtin_registry.lower_constant + + +def _decorate_getattr(impl, ty, attr): + real_impl = impl + + if attr is not None: + def res(context, builder, typ, value, attr): + return real_impl(context, builder, typ, value) + else: + def res(context, builder, typ, value, attr): + return real_impl(context, builder, typ, value, attr) + + res.signature = (ty,) + res.attr = attr + return res + +def _decorate_setattr(impl, ty, attr): + real_impl = impl + + if attr is not None: + def res(context, builder, sig, args, attr): + return real_impl(context, builder, sig, args) + else: + def res(context, builder, sig, args, attr): + return real_impl(context, builder, sig, args, attr) + + res.signature = (ty, types.Any) + res.attr = attr + return res + + +def fix_returning_optional(context, builder, sig, status, retval): + # Reconstruct optional return type + if isinstance(sig.return_type, types.Optional): + value_type = sig.return_type.type + optional_none = context.make_optional_none(builder, value_type) + retvalptr = cgutils.alloca_once_value(builder, optional_none) + with builder.if_then(builder.not_(status.is_none)): + optional_value = context.make_optional_value( + builder, value_type, retval, + ) + builder.store(optional_value, retvalptr) + retval = builder.load(retvalptr) + return retval + +def user_function(fndesc, libs): + """ + A wrapper inserting code calling Numba-compiled *fndesc*. + """ + + def imp(context, builder, sig, args): + func = context.declare_function(builder.module, fndesc) + # env=None assumes this is a nopython function + status, retval = context.call_conv.call_function( + builder, func, fndesc.restype, fndesc.argtypes, args) + with cgutils.if_unlikely(builder, status.is_error): + context.call_conv.return_status_propagate(builder, status) + assert sig.return_type == fndesc.restype + # Reconstruct optional return type + retval = fix_returning_optional(context, builder, sig, status, retval) + # If the data representations don't match up + if retval.type != context.get_value_type(sig.return_type): + msg = "function returned {0} but expect {1}" + raise TypeError(msg.format(retval.type, sig.return_type)) + + return impl_ret_new_ref(context, builder, fndesc.restype, retval) + + imp.signature = fndesc.argtypes + imp.libs = tuple(libs) + return imp + + +def user_generator(gendesc, libs): + """ + A wrapper inserting code calling Numba-compiled *gendesc*. + """ + + def imp(context, builder, sig, args): + func = context.declare_function(builder.module, gendesc) + # env=None assumes this is a nopython function + status, retval = context.call_conv.call_function( + builder, func, gendesc.restype, gendesc.argtypes, args) + # Return raw status for caller to process StopIteration + return status, retval + + imp.libs = tuple(libs) + return imp + + +def iterator_impl(iterable_type, iterator_type): + """ + Decorator a given class as implementing *iterator_type* + (by providing an `iternext()` method). + """ + + def wrapper(cls): + # These are unbound methods + iternext = cls.iternext + + @iternext_impl(RefType.BORROWED) + def iternext_wrapper(context, builder, sig, args, result): + (value,) = args + iterobj = cls(context, builder, value) + return iternext(iterobj, context, builder, result) + + lower_builtin('iternext', iterator_type)(iternext_wrapper) + return cls + + return wrapper + + +class _IternextResult(object): + """ + A result wrapper for iteration, passed by iternext_impl() into the + wrapped function. + """ + __slots__ = ('_context', '_builder', '_pairobj') + + def __init__(self, context, builder, pairobj): + self._context = context + self._builder = builder + self._pairobj = pairobj + + def set_exhausted(self): + """ + Mark the iterator as exhausted. + """ + self._pairobj.second = self._context.get_constant(types.boolean, False) + + def set_valid(self, is_valid=True): + """ + Mark the iterator as valid according to *is_valid* (which must + be either a Python boolean or a LLVM inst). + """ + if is_valid in (False, True): + is_valid = self._context.get_constant(types.boolean, is_valid) + self._pairobj.second = is_valid + + def yield_(self, value): + """ + Mark the iterator as yielding the given *value* (a LLVM inst). + """ + self._pairobj.first = value + + def is_valid(self): + """ + Return whether the iterator is marked valid. + """ + return self._context.get_argument_value(self._builder, + types.boolean, + self._pairobj.second) + + def yielded_value(self): + """ + Return the iterator's yielded value, if any. + """ + return self._pairobj.first + +class RefType(Enum): + """ + Enumerate the reference type + """ + """ + A new reference + """ + NEW = 1 + """ + A borrowed reference + """ + BORROWED = 2 + """ + An untracked reference + """ + UNTRACKED = 3 + +def iternext_impl(ref_type=None): + """ + Wrap the given iternext() implementation so that it gets passed + an _IternextResult() object easing the returning of the iternext() + result pair. + + ref_type: a numba.targets.imputils.RefType value, the reference type used is + that specified through the RefType enum. + + The wrapped function will be called with the following signature: + (context, builder, sig, args, iternext_result) + """ + if ref_type not in [x for x in RefType]: + raise ValueError("ref_type must be an enum member of imputils.RefType") + + def outer(func): + def wrapper(context, builder, sig, args): + pair_type = sig.return_type + pairobj = context.make_helper(builder, pair_type) + func(context, builder, sig, args, + _IternextResult(context, builder, pairobj)) + if ref_type == RefType.NEW: + impl_ret = impl_ret_new_ref + elif ref_type == RefType.BORROWED: + impl_ret = impl_ret_borrowed + elif ref_type == RefType.UNTRACKED: + impl_ret = impl_ret_untracked + else: + raise ValueError("Unknown ref_type encountered") + return impl_ret(context, builder, + pair_type, pairobj._getvalue()) + return wrapper + return outer + + +def call_getiter(context, builder, iterable_type, val): + """ + Call the `getiter()` implementation for the given *iterable_type* + of value *val*, and return the corresponding LLVM inst. + """ + getiter_sig = typing.signature(iterable_type.iterator_type, iterable_type) + getiter_impl = context.get_function('getiter', getiter_sig) + return getiter_impl(builder, (val,)) + + +def call_iternext(context, builder, iterator_type, val): + """ + Call the `iternext()` implementation for the given *iterator_type* + of value *val*, and return a convenience _IternextResult() object + reflecting the results. + """ + itemty = iterator_type.yield_type + pair_type = types.Pair(itemty, types.boolean) + iternext_sig = typing.signature(pair_type, iterator_type) + iternext_impl = context.get_function('iternext', iternext_sig) + val = iternext_impl(builder, (val,)) + pairobj = context.make_helper(builder, pair_type, val) + return _IternextResult(context, builder, pairobj) + + +def call_len(context, builder, ty, val): + """ + Call len() on the given value. Return None if len() isn't defined on + this type. + """ + try: + len_impl = context.get_function(len, typing.signature(types.intp, ty,)) + except NotImplementedError: + return None + else: + return len_impl(builder, (val,)) + + +_ForIterLoop = collections.namedtuple('_ForIterLoop', + ('value', 'do_break')) + + +@contextlib.contextmanager +def for_iter(context, builder, iterable_type, val): + """ + Simulate a for loop on the given iterable. Yields a namedtuple with + the given members: + - `value` is the value being yielded + - `do_break` is a callable to early out of the loop + """ + iterator_type = iterable_type.iterator_type + iterval = call_getiter(context, builder, iterable_type, val) + + bb_body = builder.append_basic_block('for_iter.body') + bb_end = builder.append_basic_block('for_iter.end') + + def do_break(): + builder.branch(bb_end) + + builder.branch(bb_body) + + with builder.goto_block(bb_body): + res = call_iternext(context, builder, iterator_type, iterval) + with builder.if_then(builder.not_(res.is_valid()), likely=False): + builder.branch(bb_end) + yield _ForIterLoop(res.yielded_value(), do_break) + builder.branch(bb_body) + + builder.position_at_end(bb_end) + if context.enable_nrt: + context.nrt.decref(builder, iterator_type, iterval) + + +def impl_ret_new_ref(ctx, builder, retty, ret): + """ + The implementation returns a new reference. + """ + return ret + + +def impl_ret_borrowed(ctx, builder, retty, ret): + """ + The implementation returns a borrowed reference. + This function automatically incref so that the implementation is + returning a new reference. + """ + if ctx.enable_nrt: + ctx.nrt.incref(builder, retty, ret) + return ret + + +def impl_ret_untracked(ctx, builder, retty, ret): + """ + The return type is not a NRT object. + """ + return ret + + +@contextlib.contextmanager +def force_error_model(context, model_name='numpy'): + """ + Temporarily change the context's error model. + """ + from numba.core import callconv + + old_error_model = context.error_model + context.error_model = callconv.create_error_model(model_name, context) + try: + yield + finally: + context.error_model = old_error_model + + +def numba_typeref_ctor(*args, **kwargs): + """A stub for use internally by Numba when a call is emitted + on a TypeRef. + """ + raise NotImplementedError("This function should not be executed.") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/inline_closurecall.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/inline_closurecall.py new file mode 100644 index 0000000000000000000000000000000000000000..2be68b2fb4c9fd2798402b2ff0c921c10c5362db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/inline_closurecall.py @@ -0,0 +1,1684 @@ +import types as pytypes # avoid confusion with numba.types +import copy +import ctypes +import numba.core.analysis +from numba.core import (types, typing, errors, ir, rewrites, config, ir_utils, + cgutils) +from numba.parfors.parfor import internal_prange +from numba.core.ir_utils import ( + next_label, + add_offset_to_labels, + replace_vars, + remove_dels, + rename_labels, + find_topo_order, + merge_adjacent_blocks, + GuardException, + require, + guard, + get_definition, + find_callname, + find_build_sequence, + get_np_ufunc_typ, + get_ir_of_code, + simplify_CFG, + canonicalize_array_math, + dead_code_elimination, +) + +from numba.core.analysis import ( + compute_cfg_from_blocks, + compute_use_defs, + compute_live_variables) +from numba.core.imputils import impl_ret_untracked +from numba.core.extending import intrinsic +from numba.core.typing import signature +from numba.cpython.listobj import ListIterInstance +from numba.cpython.rangeobj import range_impl_map +from numba.np.arrayobj import make_array + +from numba.core import postproc +from numba.np.unsafe.ndarray import empty_inferred as unsafe_empty_inferred +import numpy as np +import operator +import numba.misc.special + +""" +Variable enable_inline_arraycall is only used for testing purpose. +""" +enable_inline_arraycall = True + + +def callee_ir_validator(func_ir): + """Checks the IR of a callee is supported for inlining + """ + for blk in func_ir.blocks.values(): + for stmt in blk.find_insts(ir.Assign): + if isinstance(stmt.value, ir.Yield): + msg = "The use of yield in a closure is unsupported." + raise errors.UnsupportedError(msg, loc=stmt.loc) + + +def _created_inlined_var_name(function_name, var_name): + """Creates a name for an inlined variable based on the function name and the + variable name. It does this "safely" to avoid the use of characters that are + illegal in python variable names as there are occasions when function + generation needs valid python name tokens.""" + inlined_name = f'{function_name}.{var_name}' + # Replace angle brackets, e.g. "" is replaced with "_locals_" + new_name = inlined_name.replace('<', '_').replace('>', '_') + # The version "version" of the closure function e.g. foo$2 (id 2) is + # rewritten as "foo_v2". Further "." is also replaced with "_". + new_name = new_name.replace('.', '_').replace('$', '_v') + return new_name + + +class InlineClosureCallPass(object): + """InlineClosureCallPass class looks for direct calls to locally defined + closures, and inlines the body of the closure function to the call site. + """ + + def __init__(self, func_ir, parallel_options, swapped=None, typed=False): + if swapped is None: + swapped = {} + self.func_ir = func_ir + self.parallel_options = parallel_options + self.swapped = swapped + self._processed_stencils = [] + self.typed = typed + + def run(self): + """Run inline closure call pass. + """ + # Analysis relies on ir.Del presence, strip out later + pp = postproc.PostProcessor(self.func_ir) + pp.run(True) + + modified = False + work_list = list(self.func_ir.blocks.items()) + debug_print = _make_debug_print("InlineClosureCallPass") + debug_print(f"START {self.func_ir.func_id.func_qualname}") + while work_list: + _label, block = work_list.pop() + for i, instr in enumerate(block.body): + if isinstance(instr, ir.Assign): + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + call_name = guard(find_callname, self.func_ir, expr) + func_def = guard(get_definition, self.func_ir, + expr.func) + + if guard(self._inline_reduction, + work_list, block, i, expr, call_name): + modified = True + break # because block structure changed + + if guard(self._inline_closure, + work_list, block, i, func_def): + modified = True + break # because block structure changed + + if guard(self._inline_stencil, + instr, call_name, func_def): + modified = True + + if enable_inline_arraycall: + # Identify loop structure + if modified: + # Need to do some cleanups if closure inlining kicked in + merge_adjacent_blocks(self.func_ir.blocks) + cfg = compute_cfg_from_blocks(self.func_ir.blocks) + debug_print("start inline arraycall") + _debug_dump(cfg) + loops = cfg.loops() + sized_loops = [(k, len(loops[k].body)) for k in loops.keys()] + visited = [] + # We go over all loops, bigger loops first (outer first) + for k, s in sorted(sized_loops, key=lambda tup: tup[1], + reverse=True): + visited.append(k) + if guard(_inline_arraycall, self.func_ir, cfg, visited, + loops[k], self.swapped, + self.parallel_options.comprehension, self.typed): + modified = True + if modified: + _fix_nested_array(self.func_ir) + + if modified: + # clean up now dead/unreachable blocks, e.g. unconditionally raising + # an exception in an inlined function would render some parts of the + # inliner unreachable + cfg = compute_cfg_from_blocks(self.func_ir.blocks) + for dead in cfg.dead_nodes(): + del self.func_ir.blocks[dead] + + # run dead code elimination + dead_code_elimination(self.func_ir) + # do label renaming + self.func_ir.blocks = rename_labels(self.func_ir.blocks) + + # inlining done, strip dels + remove_dels(self.func_ir.blocks) + + debug_print("END") + + def _inline_reduction(self, work_list, block, i, expr, call_name): + # only inline reduction in sequential execution, parallel handling + # is done in ParforPass. + require(not self.parallel_options.reduction) + require(call_name == ('reduce', 'builtins') or + call_name == ('reduce', '_functools')) + if len(expr.args) not in (2, 3): + raise TypeError("invalid reduce call, " + "two arguments are required (optional initial " + "value can also be specified)") + check_reduce_func(self.func_ir, expr.args[0]) + + def reduce_func(f, A, v=None): + it = iter(A) + if v is not None: + s = v + else: + s = next(it) + for a in it: + s = f(s, a) + return s + + inline_closure_call( + self.func_ir, self.func_ir.func_id.func.__globals__, + block, i, reduce_func, work_list=work_list, + callee_validator=callee_ir_validator + ) + return True + + def _inline_stencil(self, instr, call_name, func_def): + from numba.stencils.stencil import StencilFunc + lhs = instr.target + expr = instr.value + # We keep the escaping variables of the stencil kernel + # alive by adding them to the actual kernel call as extra + # keyword arguments, which is ignored anyway. + if (isinstance(func_def, ir.Global) and + func_def.name == 'stencil' and + isinstance(func_def.value, StencilFunc)): + if expr.kws: + expr.kws += func_def.value.kws + else: + expr.kws = func_def.value.kws + return True + # Otherwise we proceed to check if it is a call to numba.stencil + require(call_name == ('stencil', 'numba.stencils.stencil') or + call_name == ('stencil', 'numba')) + require(expr not in self._processed_stencils) + self._processed_stencils.append(expr) + if not len(expr.args) == 1: + raise ValueError("As a minimum Stencil requires" + " a kernel as an argument") + stencil_def = guard(get_definition, self.func_ir, expr.args[0]) + require(isinstance(stencil_def, ir.Expr) and + stencil_def.op == "make_function") + kernel_ir = get_ir_of_code(self.func_ir.func_id.func.__globals__, + stencil_def.code) + options = dict(expr.kws) + if 'neighborhood' in options: + fixed = guard(self._fix_stencil_neighborhood, options) + if not fixed: + raise ValueError( + "stencil neighborhood option should be a tuple" + " with constant structure such as ((-w, w),)" + ) + if 'index_offsets' in options: + fixed = guard(self._fix_stencil_index_offsets, options) + if not fixed: + raise ValueError( + "stencil index_offsets option should be a tuple" + " with constant structure such as (offset, )" + ) + sf = StencilFunc(kernel_ir, 'constant', options) + sf.kws = expr.kws # hack to keep variables live + sf_global = ir.Global('stencil', sf, expr.loc) + self.func_ir._definitions[lhs.name] = [sf_global] + instr.value = sf_global + return True + + def _fix_stencil_neighborhood(self, options): + """ + Extract the two-level tuple representing the stencil neighborhood + from the program IR to provide a tuple to StencilFunc. + """ + # build_tuple node with neighborhood for each dimension + dims_build_tuple = get_definition(self.func_ir, options['neighborhood']) + require(hasattr(dims_build_tuple, 'items')) + res = [] + for window_var in dims_build_tuple.items: + win_build_tuple = get_definition(self.func_ir, window_var) + require(hasattr(win_build_tuple, 'items')) + res.append(tuple(win_build_tuple.items)) + options['neighborhood'] = tuple(res) + return True + + def _fix_stencil_index_offsets(self, options): + """ + Extract the tuple representing the stencil index offsets + from the program IR to provide to StencilFunc. + """ + offset_tuple = get_definition(self.func_ir, options['index_offsets']) + require(hasattr(offset_tuple, 'items')) + options['index_offsets'] = tuple(offset_tuple.items) + return True + + def _inline_closure(self, work_list, block, i, func_def): + require(isinstance(func_def, ir.Expr) and + func_def.op == "make_function") + inline_closure_call(self.func_ir, + self.func_ir.func_id.func.__globals__, + block, i, func_def, work_list=work_list, + callee_validator=callee_ir_validator) + return True + + +def check_reduce_func(func_ir, func_var): + """Checks the function at func_var in func_ir to make sure it's amenable + for inlining. Returns the function itself""" + reduce_func = guard(get_definition, func_ir, func_var) + if reduce_func is None: + raise ValueError("Reduce function cannot be found for njit \ + analysis") + if isinstance(reduce_func, (ir.FreeVar, ir.Global)): + if not isinstance(reduce_func.value, + numba.core.registry.CPUDispatcher): + raise ValueError("Invalid reduction function") + # pull out the python function for inlining + reduce_func = reduce_func.value.py_func + elif not (hasattr(reduce_func, 'code') + or hasattr(reduce_func, '__code__')): + raise ValueError("Invalid reduction function") + f_code = (reduce_func.code + if hasattr(reduce_func, 'code') + else reduce_func.__code__) + if not f_code.co_argcount == 2: + raise TypeError("Reduction function should take 2 arguments") + return reduce_func + + +class InlineWorker(object): + """ A worker class for inlining, this is a more advanced version of + `inline_closure_call` in that it permits inlining from function type, Numba + IR and code object. It also, runs the entire untyped compiler pipeline on + the inlinee to ensure that it is transformed as though it were compiled + directly. + """ + + def __init__(self, + typingctx=None, + targetctx=None, + locals=None, + pipeline=None, + flags=None, + validator=callee_ir_validator, + typemap=None, + calltypes=None): + """ + Instantiate a new InlineWorker, all arguments are optional though some + must be supplied together for certain use cases. The methods will refuse + to run if the object isn't configured in the manner needed. Args are the + same as those in a numba.core.Compiler.state, except the validator which + is a function taking Numba IR and validating it for use when inlining + (this is optional and really to just provide better error messages about + things which the inliner cannot handle like yield in closure). + """ + def check(arg, name): + if arg is None: + raise TypeError("{} must not be None".format(name)) + + from numba.core.compiler import DefaultPassBuilder + + # check the stuff needed to run the more advanced compilation pipeline + # is valid if any of it is provided + compiler_args = (targetctx, locals, pipeline, flags) + compiler_group = [x is not None for x in compiler_args] + if any(compiler_group) and not all(compiler_group): + check(targetctx, 'targetctx') + check(locals, 'locals') + check(pipeline, 'pipeline') + check(flags, 'flags') + elif all(compiler_group): + check(typingctx, 'typingctx') + + self._compiler_pipeline = DefaultPassBuilder.define_untyped_pipeline + + self.typingctx = typingctx + self.targetctx = targetctx + self.locals = locals + self.pipeline = pipeline + self.flags = flags + self.validator = validator + self.debug_print = _make_debug_print("InlineWorker") + + # check whether this inliner can also support typemap and calltypes + # update and if what's provided is valid + pair = (typemap, calltypes) + pair_is_none = [x is None for x in pair] + if any(pair_is_none) and not all(pair_is_none): + msg = ("typemap and calltypes must both be either None or have a " + "value, got: %s, %s") + raise TypeError(msg % pair) + self._permit_update_type_and_call_maps = not all(pair_is_none) + self.typemap = typemap + self.calltypes = calltypes + + def inline_ir(self, caller_ir, block, i, callee_ir, callee_freevars, + arg_typs=None): + """ Inlines the callee_ir in the caller_ir at statement index i of block + `block`, callee_freevars are the free variables for the callee_ir. If + the callee_ir is derived from a function `func` then this is + `func.__code__.co_freevars`. If `arg_typs` is given and the InlineWorker + instance was initialized with a typemap and calltypes then they will be + appropriately updated based on the arg_typs. + """ + + # Always copy the callee IR, it gets mutated + def copy_ir(the_ir): + kernel_copy = the_ir.copy() + kernel_copy.blocks = {} + for block_label, block in the_ir.blocks.items(): + new_block = copy.deepcopy(the_ir.blocks[block_label]) + kernel_copy.blocks[block_label] = new_block + return kernel_copy + + callee_ir = copy_ir(callee_ir) + + # check that the contents of the callee IR is something that can be + # inlined if a validator is present + if self.validator is not None: + self.validator(callee_ir) + + # save an unmutated copy of the callee_ir to return + callee_ir_original = copy_ir(callee_ir) + scope = block.scope + instr = block.body[i] + call_expr = instr.value + callee_blocks = callee_ir.blocks + + # 1. relabel callee_ir by adding an offset + max_label = max( + ir_utils._the_max_label.next(), + max(caller_ir.blocks.keys()), + ) + callee_blocks = add_offset_to_labels(callee_blocks, max_label + 1) + callee_blocks = simplify_CFG(callee_blocks) + callee_ir.blocks = callee_blocks + min_label = min(callee_blocks.keys()) + max_label = max(callee_blocks.keys()) + # reset globals in ir_utils before we use it + ir_utils._the_max_label.update(max_label) + self.debug_print("After relabel") + _debug_dump(callee_ir) + + # 2. rename all local variables in callee_ir with new locals created in + # caller_ir + callee_scopes = _get_all_scopes(callee_blocks) + self.debug_print("callee_scopes = ", callee_scopes) + # one function should only have one local scope + assert (len(callee_scopes) == 1) + callee_scope = callee_scopes[0] + var_dict = {} + for var in tuple(callee_scope.localvars._con.values()): + if not (var.name in callee_freevars): + inlined_name = _created_inlined_var_name( + callee_ir.func_id.unique_name, var.name) + # Update the caller scope with the new names + new_var = scope.redefine(inlined_name, loc=var.loc) + # Also update the callee scope with the new names. Should the + # type and call maps need updating (which requires SSA form) the + # transformation to SSA is valid as the IR object is internally + # consistent. + callee_scope.redefine(inlined_name, loc=var.loc) + var_dict[var.name] = new_var + self.debug_print("var_dict = ", var_dict) + replace_vars(callee_blocks, var_dict) + self.debug_print("After local var rename") + _debug_dump(callee_ir) + + # 3. replace formal parameters with actual arguments + callee_func = callee_ir.func_id.func + args = _get_callee_args(call_expr, callee_func, block.body[i].loc, + caller_ir) + + # 4. Update typemap + if self._permit_update_type_and_call_maps: + if arg_typs is None: + raise TypeError('arg_typs should have a value not None') + self.update_type_and_call_maps(callee_ir, arg_typs) + # update_type_and_call_maps replaces blocks + callee_blocks = callee_ir.blocks + + self.debug_print("After arguments rename: ") + _debug_dump(callee_ir) + + _replace_args_with(callee_blocks, args) + # 5. split caller blocks into two + new_blocks = [] + new_block = ir.Block(scope, block.loc) + new_block.body = block.body[i + 1:] + new_label = next_label() + caller_ir.blocks[new_label] = new_block + new_blocks.append((new_label, new_block)) + block.body = block.body[:i] + block.body.append(ir.Jump(min_label, instr.loc)) + + # 6. replace Return with assignment to LHS + topo_order = find_topo_order(callee_blocks) + _replace_returns(callee_blocks, instr.target, new_label) + + # remove the old definition of instr.target too + if (instr.target.name in caller_ir._definitions + and call_expr in caller_ir._definitions[instr.target.name]): + # NOTE: target can have multiple definitions due to control flow + caller_ir._definitions[instr.target.name].remove(call_expr) + + # 7. insert all new blocks, and add back definitions + for label in topo_order: + # block scope must point to parent's + block = callee_blocks[label] + block.scope = scope + _add_definitions(caller_ir, block) + caller_ir.blocks[label] = block + new_blocks.append((label, block)) + self.debug_print("After merge in") + _debug_dump(caller_ir) + + return callee_ir_original, callee_blocks, var_dict, new_blocks + + def inline_function(self, caller_ir, block, i, function, arg_typs=None): + """ Inlines the function in the caller_ir at statement index i of block + `block`. If `arg_typs` is given and the InlineWorker instance was + initialized with a typemap and calltypes then they will be appropriately + updated based on the arg_typs. + """ + callee_ir = self.run_untyped_passes(function) + freevars = function.__code__.co_freevars + return self.inline_ir(caller_ir, block, i, callee_ir, freevars, + arg_typs=arg_typs) + + def run_untyped_passes(self, func, enable_ssa=False): + """ + Run the compiler frontend's untyped passes over the given Python + function, and return the function's canonical Numba IR. + + Disable SSA transformation by default, since the call site won't be in + SSA form and self.inline_ir depends on this being the case. + """ + from numba.core.compiler import StateDict, _CompileStatus + from numba.core.untyped_passes import ExtractByteCode + from numba.core import bytecode + from numba.parfors.parfor import ParforDiagnostics + state = StateDict() + state.func_ir = None + state.typingctx = self.typingctx + state.targetctx = self.targetctx + state.locals = self.locals + state.pipeline = self.pipeline + state.flags = self.flags + state.flags.enable_ssa = enable_ssa + + state.func_id = bytecode.FunctionIdentity.from_function(func) + + state.typemap = None + state.calltypes = None + state.type_annotation = None + state.status = _CompileStatus(False) + state.return_type = None + state.parfor_diagnostics = ParforDiagnostics() + state.metadata = {} + + ExtractByteCode().run_pass(state) + # This is a lie, just need *some* args for the case where an obj mode + # with lift is needed + state.args = len(state.bc.func_id.pysig.parameters) * (types.pyobject,) + + pm = self._compiler_pipeline(state) + + pm.finalize() + pm.run(state) + return state.func_ir + + def update_type_and_call_maps(self, callee_ir, arg_typs): + """ Updates the type and call maps based on calling callee_ir with + arguments from arg_typs""" + from numba.core.ssa import reconstruct_ssa + from numba.core.typed_passes import PreLowerStripPhis + + if not self._permit_update_type_and_call_maps: + msg = ("InlineWorker instance not configured correctly, typemap or " + "calltypes missing in initialization.") + raise ValueError(msg) + from numba.core import typed_passes + # call branch pruning to simplify IR and avoid inference errors + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + numba.core.analysis.dead_branch_prune(callee_ir, arg_typs) + # callee's typing may require SSA + callee_ir = reconstruct_ssa(callee_ir) + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + [f_typemap, + _f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + self.typingctx, self.targetctx, callee_ir, arg_typs, None, + ) + callee_ir = PreLowerStripPhis()._strip_phi_nodes(callee_ir) + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + canonicalize_array_math(callee_ir, f_typemap, + f_calltypes, self.typingctx) + # remove argument entries like arg.a from typemap + arg_names = [vname for vname in f_typemap if vname.startswith("arg.")] + for a in arg_names: + f_typemap.pop(a) + self.typemap.update(f_typemap) + self.calltypes.update(f_calltypes) + + +def inline_closure_call(func_ir, glbls, block, i, callee, typingctx=None, + targetctx=None, arg_typs=None, typemap=None, + calltypes=None, work_list=None, callee_validator=None, + replace_freevars=True): + """Inline the body of `callee` at its callsite (`i`-th instruction of + `block`) + + `func_ir` is the func_ir object of the caller function and `glbls` is its + global variable environment (func_ir.func_id.func.__globals__). + `block` is the IR block of the callsite and `i` is the index of the + callsite's node. `callee` is either the called function or a + make_function node. `typingctx`, `typemap` and `calltypes` are typing + data structures of the caller, available if we are in a typed pass. + `arg_typs` includes the types of the arguments at the callsite. + `callee_validator` is an optional callable which can be used to validate the + IR of the callee to ensure that it contains IR supported for inlining, it + takes one argument, the func_ir of the callee + + Returns IR blocks of the callee and the variable renaming dictionary used + for them to facilitate further processing of new blocks. + """ + scope = block.scope + instr = block.body[i] + call_expr = instr.value + debug_print = _make_debug_print("inline_closure_call") + debug_print("Found closure call: ", instr, " with callee = ", callee) + # support both function object and make_function Expr + callee_code = callee.code if hasattr(callee, 'code') else callee.__code__ + callee_closure = (callee.closure + if hasattr(callee, 'closure') else callee.__closure__) + # first, get the IR of the callee + if isinstance(callee, pytypes.FunctionType): + from numba.core import compiler + callee_ir = compiler.run_frontend(callee, inline_closures=True) + else: + callee_ir = get_ir_of_code(glbls, callee_code) + + # check that the contents of the callee IR is something that can be inlined + # if a validator is supplied + if callee_validator is not None: + callee_validator(callee_ir) + + callee_blocks = callee_ir.blocks + + # 1. relabel callee_ir by adding an offset + max_label = max(ir_utils._the_max_label.next(), max(func_ir.blocks.keys())) + callee_blocks = add_offset_to_labels(callee_blocks, max_label + 1) + callee_blocks = simplify_CFG(callee_blocks) + callee_ir.blocks = callee_blocks + min_label = min(callee_blocks.keys()) + max_label = max(callee_blocks.keys()) + # reset globals in ir_utils before we use it + ir_utils._the_max_label.update(max_label) + debug_print("After relabel") + _debug_dump(callee_ir) + + # 2. rename all local variables in callee_ir with new locals created in + # func_ir + callee_scopes = _get_all_scopes(callee_blocks) + debug_print("callee_scopes = ", callee_scopes) + # one function should only have one local scope + assert (len(callee_scopes) == 1) + callee_scope = callee_scopes[0] + var_dict = {} + for var in callee_scope.localvars._con.values(): + if not (var.name in callee_code.co_freevars): + inlined_name = _created_inlined_var_name( + callee_ir.func_id.unique_name, var.name) + new_var = scope.redefine(inlined_name, loc=var.loc) + var_dict[var.name] = new_var + debug_print("var_dict = ", var_dict) + replace_vars(callee_blocks, var_dict) + debug_print("After local var rename") + _debug_dump(callee_ir) + + # 3. replace formal parameters with actual arguments + args = _get_callee_args(call_expr, callee, block.body[i].loc, func_ir) + + debug_print("After arguments rename: ") + _debug_dump(callee_ir) + + # 4. replace freevar with actual closure var + if callee_closure and replace_freevars: + closure = func_ir.get_definition(callee_closure) + debug_print("callee's closure = ", closure) + if isinstance(closure, tuple): + cellget = ctypes.pythonapi.PyCell_Get + cellget.restype = ctypes.py_object + cellget.argtypes = (ctypes.py_object,) + items = tuple(cellget(x) for x in closure) + else: + assert (isinstance(closure, ir.Expr) + and closure.op == 'build_tuple') + items = closure.items + assert (len(callee_code.co_freevars) == len(items)) + _replace_freevars(callee_blocks, items) + debug_print("After closure rename") + _debug_dump(callee_ir) + + if typingctx: + from numba.core import typed_passes + # call branch pruning to simplify IR and avoid inference errors + callee_ir._definitions = ir_utils.build_definitions(callee_ir.blocks) + numba.core.analysis.dead_branch_prune(callee_ir, arg_typs) + try: + [f_typemap, f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + typingctx, targetctx, callee_ir, arg_typs, None) + except Exception: + [f_typemap, f_return_type, + f_calltypes, _] = typed_passes.type_inference_stage( + typingctx, targetctx, callee_ir, arg_typs, None) + canonicalize_array_math(callee_ir, f_typemap, + f_calltypes, typingctx) + # remove argument entries like arg.a from typemap + arg_names = [vname for vname in f_typemap if vname.startswith("arg.")] + for a in arg_names: + f_typemap.pop(a) + typemap.update(f_typemap) + calltypes.update(f_calltypes) + + _replace_args_with(callee_blocks, args) + # 5. split caller blocks into two + new_blocks = [] + new_block = ir.Block(scope, block.loc) + new_block.body = block.body[i + 1:] + new_label = next_label() + func_ir.blocks[new_label] = new_block + new_blocks.append((new_label, new_block)) + block.body = block.body[:i] + block.body.append(ir.Jump(min_label, instr.loc)) + + # 6. replace Return with assignment to LHS + topo_order = find_topo_order(callee_blocks) + _replace_returns(callee_blocks, instr.target, new_label) + + # remove the old definition of instr.target too + if (instr.target.name in func_ir._definitions + and call_expr in func_ir._definitions[instr.target.name]): + # NOTE: target can have multiple definitions due to control flow + func_ir._definitions[instr.target.name].remove(call_expr) + + # 7. insert all new blocks, and add back definitions + for label in topo_order: + # block scope must point to parent's + block = callee_blocks[label] + block.scope = scope + _add_definitions(func_ir, block) + func_ir.blocks[label] = block + new_blocks.append((label, block)) + debug_print("After merge in") + _debug_dump(func_ir) + + if work_list is not None: + for block in new_blocks: + work_list.append(block) + return callee_blocks, var_dict + + +def _get_callee_args(call_expr, callee, loc, func_ir): + """Get arguments for calling 'callee', including the default arguments. + keyword arguments are currently only handled when 'callee' is a function. + """ + if call_expr.op == 'call': + args = list(call_expr.args) + if call_expr.vararg: + msg = "Calling a closure with *args is unsupported." + raise errors.UnsupportedError(msg, call_expr.loc) + elif call_expr.op == 'getattr': + args = [call_expr.value] + elif ir_utils.is_operator_or_getitem(call_expr): + args = call_expr.list_vars() + else: + raise TypeError("Unsupported ir.Expr.{}".format(call_expr.op)) + + debug_print = _make_debug_print("inline_closure_call default handling") + + # handle defaults and kw arguments using pysignature if callee is function + if isinstance(callee, pytypes.FunctionType): + pysig = numba.core.utils.pysignature(callee) + normal_handler = lambda index, param, default: default + default_handler = lambda index, param, default: ir.Const(default, loc) + + # Throw error for stararg + # TODO: handle stararg + def stararg_handler(index, param, default): + raise NotImplementedError( + "Stararg not supported in inliner for arg {} {}".format( + index, param)) + if call_expr.op == 'call': + kws = dict(call_expr.kws) + else: + kws = {} + return numba.core.typing.fold_arguments( + pysig, args, kws, normal_handler, default_handler, + stararg_handler) + else: + # TODO: handle arguments for make_function case similar to function + # case above + callee_defaults = (callee.defaults if hasattr(callee, 'defaults') + else callee.__defaults__) + if callee_defaults: + debug_print("defaults = ", callee_defaults) + if isinstance(callee_defaults, tuple): # Python 3.5 + defaults_list = [] + for x in callee_defaults: + if isinstance(x, ir.Var): + defaults_list.append(x) + else: + # this branch is predominantly for kwargs from + # inlinable functions + defaults_list.append(ir.Const(value=x, loc=loc)) + args = args + defaults_list + elif (isinstance(callee_defaults, ir.Var) + or isinstance(callee_defaults, str)): + default_tuple = func_ir.get_definition(callee_defaults) + assert (isinstance(default_tuple, ir.Expr)) + assert (default_tuple.op == "build_tuple") + const_vals = [func_ir.get_definition(x) for + x in default_tuple.items] + args = args + const_vals + else: + raise NotImplementedError( + "Unsupported defaults to make_function: {}".format( + callee_defaults)) + return args + + +def _make_debug_print(prefix): + def debug_print(*args): + if config.DEBUG_INLINE_CLOSURE: + print(prefix + ": " + "".join(str(x) for x in args)) + return debug_print + + +def _debug_dump(func_ir): + if config.DEBUG_INLINE_CLOSURE: + func_ir.dump() + + +def _get_all_scopes(blocks): + """Get all block-local scopes from an IR. + """ + all_scopes = [] + for label, block in blocks.items(): + if not (block.scope in all_scopes): + all_scopes.append(block.scope) + return all_scopes + + +def _replace_args_with(blocks, args): + """ + Replace ir.Arg(...) with real arguments from call site + """ + for label, block in blocks.items(): + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + if isinstance(stmt.value, ir.Arg): + idx = stmt.value.index + assert (idx < len(args)) + stmt.value = args[idx] + + +def _replace_freevars(blocks, args): + """ + Replace ir.FreeVar(...) with real variables from parent function + """ + for label, block in blocks.items(): + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + if isinstance(stmt.value, ir.FreeVar): + idx = stmt.value.index + assert (idx < len(args)) + if isinstance(args[idx], ir.Var): + stmt.value = args[idx] + else: + stmt.value = ir.Const(args[idx], stmt.loc) + + +def _replace_returns(blocks, target, return_label): + """ + Return return statement by assigning directly to target, and a jump. + """ + for label, block in blocks.items(): + casts = [] + for i in range(len(block.body)): + stmt = block.body[i] + if isinstance(stmt, ir.Return): + assert (i + 1 == len(block.body)) + block.body[i] = ir.Assign(stmt.value, target, stmt.loc) + block.body.append(ir.Jump(return_label, stmt.loc)) + # remove cast of the returned value + for cast in casts: + if cast.target.name == stmt.value.name: + cast.value = cast.value.value + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Expr) and + stmt.value.op == 'cast'): + casts.append(stmt) + + +def _add_definitions(func_ir, block): + """ + Add variable definitions found in a block to parent func_ir. + """ + definitions = func_ir._definitions + assigns = block.find_insts(ir.Assign) + for stmt in assigns: + definitions[stmt.target.name].append(stmt.value) + + +def _find_arraycall(func_ir, block): + """Look for statement like "x = numpy.array(y)" or "x[..] = y" + immediately after the closure call that creates list y (the i-th + statement in block). Return the statement index if found, or + raise GuardException. + """ + array_var = None + list_var_dead_after_array_call = False + list_var = None + + i = 0 + while i < len(block.body): + instr = block.body[i] + if isinstance(instr, ir.Del): + # Stop the process if list_var becomes dead + if list_var and array_var and instr.value == list_var.name: + list_var_dead_after_array_call = True + break + pass + elif isinstance(instr, ir.Assign): + # Found array_var = array(list_var) + lhs = instr.target + expr = instr.value + if (guard(find_callname, func_ir, expr) == ('array', 'numpy') and + isinstance(expr.args[0], ir.Var)): + list_var = expr.args[0] + array_var = lhs + array_stmt_index = i + array_kws = dict(expr.kws) + elif (isinstance(instr, ir.SetItem) and + isinstance(instr.value, ir.Var) and + not list_var): + list_var = instr.value + # Found array_var[..] = list_var, the case for nested array + array_var = instr.target + array_def = get_definition(func_ir, array_var) + require(guard(_find_unsafe_empty_inferred, func_ir, array_def)) + array_stmt_index = i + array_kws = {} + else: + # Bail out otherwise + break + i = i + 1 + # require array_var is found, and list_var is dead after array_call. + require(array_var and list_var_dead_after_array_call) + _make_debug_print("find_array_call")(block.body[array_stmt_index]) + return list_var, array_stmt_index, array_kws + + +def _find_iter_range(func_ir, range_iter_var, swapped): + """Find the iterator's actual range if it is either range(n), or + range(m, n), otherwise return raise GuardException. + """ + debug_print = _make_debug_print("find_iter_range") + range_iter_def = get_definition(func_ir, range_iter_var) + debug_print("range_iter_var = ", range_iter_var, " def = ", range_iter_def) + require(isinstance(range_iter_def, ir.Expr) and + range_iter_def.op == 'getiter') + range_var = range_iter_def.value + range_def = get_definition(func_ir, range_var) + debug_print("range_var = ", range_var, " range_def = ", range_def) + require(isinstance(range_def, ir.Expr) and range_def.op == 'call') + func_var = range_def.func + func_def = get_definition(func_ir, func_var) + debug_print("func_var = ", func_var, " func_def = ", func_def) + require(isinstance(func_def, ir.Global) and + (func_def.value == range or + func_def.value == numba.misc.special.prange)) + nargs = len(range_def.args) + swapping = [('"array comprehension"', 'closure of'), range_def.func.loc] + if nargs == 1: + swapped[range_def.func.name] = swapping + stop = get_definition(func_ir, range_def.args[0], lhs_only=True) + return (0, range_def.args[0], func_def) + elif nargs == 2: + swapped[range_def.func.name] = swapping + start = get_definition(func_ir, range_def.args[0], lhs_only=True) + stop = get_definition(func_ir, range_def.args[1], lhs_only=True) + return (start, stop, func_def) + else: + raise GuardException + + +@intrinsic +def length_of_iterator(typingctx, val): + """ + An implementation of len(iter) for internal use. + Primary use is for array comprehensions (see inline_closurecall). + """ + if isinstance(val, types.RangeIteratorType): + val_type = val.yield_type + + def codegen(context, builder, sig, args): + (value,) = args + iter_type = range_impl_map[val_type][1] + iterobj = cgutils.create_struct_proxy(iter_type)(context, builder, + value) + int_type = iterobj.count.type + return impl_ret_untracked(context, builder, int_type, + builder.load(iterobj.count)) + return signature(val_type, val), codegen + elif isinstance(val, types.ListIter): + def codegen(context, builder, sig, args): + (value,) = args + intp_t = context.get_value_type(types.intp) + iterobj = ListIterInstance(context, builder, sig.args[0], value) + return impl_ret_untracked(context, builder, intp_t, iterobj.size) + return signature(types.intp, val), codegen + elif isinstance(val, types.ArrayIterator): + def codegen(context, builder, sig, args): + (iterty,) = sig.args + (value,) = args + intp_t = context.get_value_type(types.intp) + iterobj = context.make_helper(builder, iterty, value=value) + arrayty = iterty.array_type + ary = make_array(arrayty)(context, builder, value=iterobj.array) + shape = cgutils.unpack_tuple(builder, ary.shape) + # array iterates along the outer dimension + return impl_ret_untracked(context, builder, intp_t, shape[0]) + return signature(types.intp, val), codegen + elif isinstance(val, types.UniTupleIter): + def codegen(context, builder, sig, args): + (iterty,) = sig.args + tuplety = iterty.container + intp_t = context.get_value_type(types.intp) + count_const = intp_t(tuplety.count) + return impl_ret_untracked(context, builder, intp_t, count_const) + + return signature(types.intp, val), codegen + elif isinstance(val, types.ListTypeIteratorType): + def codegen(context, builder, sig, args): + (value,) = args + intp_t = context.get_value_type(types.intp) + from numba.typed.listobject import ListIterInstance + iterobj = ListIterInstance(context, builder, sig.args[0], value) + return impl_ret_untracked(context, builder, intp_t, iterobj.size) + return signature(types.intp, val), codegen + else: + msg = ('Unsupported iterator found in array comprehension, try ' + 'preallocating the array and filling manually.') + raise errors.TypingError(msg) + + +def _inline_arraycall(func_ir, cfg, visited, loop, swapped, enable_prange=False, + typed=False): + """Look for array(list) call in the exit block of a given loop, and turn + list operations into array operations in the loop if the following + conditions are met: + 1. The exit block contains an array call on the list; + 2. The list variable is no longer live after array call; + 3. The list is created in the loop entry block; + 4. The loop is created from an range iterator whose length is known prior + to the loop; + 5. There is only one list_append operation on the list variable in the + loop body; + 6. The block that contains list_append dominates the loop head, which + ensures list length is the same as loop length; + If any condition check fails, no modification will be made to the incoming + IR. + """ + debug_print = _make_debug_print("inline_arraycall") + # There should only be one loop exit + require(len(loop.exits) == 1) + exit_block = next(iter(loop.exits)) + list_var, array_call_index, array_kws = _find_arraycall( + func_ir, func_ir.blocks[exit_block], + ) + + # check if dtype is present in array call + dtype_def = None + dtype_mod_def = None + if 'dtype' in array_kws: + require(isinstance(array_kws['dtype'], ir.Var)) + # We require that dtype argument to be a constant of getattr Expr, and + # we'll remember its definition for later use. + dtype_def = get_definition(func_ir, array_kws['dtype']) + require(isinstance(dtype_def, ir.Expr) and dtype_def.op == 'getattr') + dtype_mod_def = get_definition(func_ir, dtype_def.value) + + list_var_def = get_definition(func_ir, list_var) + debug_print("list_var = ", list_var, " def = ", list_var_def) + if isinstance(list_var_def, ir.Expr) and list_var_def.op == 'cast': + list_var_def = get_definition(func_ir, list_var_def.value) + # Check if the definition is a build_list + require(isinstance(list_var_def, ir.Expr) and + list_var_def.op == 'build_list') + # The build_list must be empty + require(len(list_var_def.items) == 0) + + # Look for list_append in "last" block in loop body, which should be a block + # that is a post-dominator of the loop header. + list_append_stmts = [] + for label in loop.body: + # We have to consider blocks of this loop, but not sub-loops. + # To achieve this, we require the set of "in_loops" of "label" to be + # visited loops. + in_visited_loops = [l.header in visited for l in cfg.in_loops(label)] + if not all(in_visited_loops): + continue + block = func_ir.blocks[label] + debug_print("check loop body block ", label) + for stmt in block.find_insts(ir.Assign): + expr = stmt.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + func_def = get_definition(func_ir, expr.func) + if (isinstance(func_def, ir.Expr) and func_def.op == 'getattr' + and func_def.attr == 'append'): + list_def = get_definition(func_ir, func_def.value) + debug_print("list_def = ", list_def, + list_def is list_var_def) + if list_def is list_var_def: + # found matching append call + list_append_stmts.append((label, block, stmt)) + + # Require only one list_append, otherwise we won't know the indices + require(len(list_append_stmts) == 1) + append_block_label, append_block, append_stmt = list_append_stmts[0] + + # Check if append_block (besides loop entry) dominates loop header. + # Since CFG doesn't give us this info without loop entry, we approximate + # by checking if the predecessor set of the header block is the same + # as loop_entries plus append_block, which is certainly more restrictive + # than necessary, and can be relaxed if needed. + preds = set(l for l, b in cfg.predecessors(loop.header)) + debug_print("preds = ", preds, (loop.entries | set([append_block_label]))) + require(preds == (loop.entries | set([append_block_label]))) + + # Find iterator in loop header + iter_vars = [] + iter_first_vars = [] + loop_header = func_ir.blocks[loop.header] + for stmt in loop_header.find_insts(ir.Assign): + expr = stmt.value + if isinstance(expr, ir.Expr): + if expr.op == 'iternext': + iter_def = get_definition(func_ir, expr.value) + debug_print("iter_def = ", iter_def) + iter_vars.append(expr.value) + elif expr.op == 'pair_first': + iter_first_vars.append(stmt.target) + + # Require only one iterator in loop header + require(len(iter_vars) == 1 and len(iter_first_vars) == 1) + # variable that holds the iterator object + iter_var = iter_vars[0] + # variable that holds the value out of iterator + iter_first_var = iter_first_vars[0] + + # Final requirement: only one loop entry, and we're going to modify it by: + # 1. replacing the list definition with an array definition; + # 2. adding a counter for the array iteration. + require(len(loop.entries) == 1) + loop_entry = func_ir.blocks[next(iter(loop.entries))] + terminator = loop_entry.terminator + scope = loop_entry.scope + loc = loop_entry.loc + stmts = [] + removed = [] + + def is_removed(val, removed): + if isinstance(val, ir.Var): + for x in removed: + if x.name == val.name: + return True + return False + + # Skip list construction and skip terminator, add the rest to stmts + for i in range(len(loop_entry.body) - 1): + stmt = loop_entry.body[i] + if (isinstance(stmt, ir.Assign) and + (stmt.value is list_def or is_removed(stmt.value, removed))): + removed.append(stmt.target) + else: + stmts.append(stmt) + debug_print("removed variables: ", removed) + + # Define an index_var to index the array. + # If the range happens to be single step ranges like range(n), or + # range(m, n), then the index_var correlates to iterator index; otherwise + # we'll have to define a new counter. + range_def = guard(_find_iter_range, func_ir, iter_var, swapped) + index_var = scope.redefine("index", loc) + if range_def and range_def[0] == 0: + # iterator starts with 0, index_var can just be iter_first_var + index_var = iter_first_var + else: + # index_var = -1 # starting the index with -1 since it will incremented + # in loop header + stmts.append(_new_definition(func_ir, index_var, + ir.Const(value=-1, loc=loc), loc)) + + # Insert statement to get the size of the loop iterator + size_var = scope.redefine("size", loc) + if range_def: + start, stop, range_func_def = range_def + if start == 0: + size_val = stop + else: + size_val = ir.Expr.binop(fn=operator.sub, lhs=stop, rhs=start, + loc=loc) + # we can parallelize this loop if enable_prange = True, by changing + # range function from range, to prange. + if enable_prange and isinstance(range_func_def, ir.Global): + range_func_def.name = 'internal_prange' + range_func_def.value = internal_prange + + else: + # this doesn't work in objmode as it's effectively untyped + if typed: + len_func_var = scope.redefine("len_func", loc) + stmts.append(_new_definition(func_ir, len_func_var, + ir.Global('length_of_iterator', + length_of_iterator, + loc=loc), + loc)) + size_val = ir.Expr.call(len_func_var, (iter_var,), (), loc=loc) + else: + raise GuardException + + stmts.append(_new_definition(func_ir, size_var, size_val, loc)) + + size_tuple_var = scope.redefine("size_tuple", loc) + stmts.append(_new_definition(func_ir, size_tuple_var, + ir.Expr.build_tuple(items=[size_var], loc=loc), loc)) + + # Insert array allocation + array_var = scope.redefine("array", loc) + empty_func = scope.redefine("empty_func", loc) + if dtype_def and dtype_mod_def: + # when dtype is present, we'll call empty with dtype + dtype_mod_var = scope.redefine("dtype_mod", loc) + dtype_var = scope.redefine("dtype", loc) + stmts.append(_new_definition( + func_ir, dtype_mod_var, dtype_mod_def, loc)) + stmts.append(_new_definition( + func_ir, dtype_var, + ir.Expr.getattr(dtype_mod_var, dtype_def.attr, loc), loc)) + stmts.append(_new_definition( + func_ir, empty_func, ir.Global('empty', np.empty, loc=loc), loc)) + array_kws = [('dtype', dtype_var)] + else: + # this doesn't work in objmode as it's effectively untyped + if typed: + # otherwise we'll call unsafe_empty_inferred + stmts.append(_new_definition( + func_ir, empty_func, + ir.Global('unsafe_empty_inferred', unsafe_empty_inferred, + loc=loc), + loc)) + array_kws = [] + else: + raise GuardException + + # array_var = empty_func(size_tuple_var) + stmts.append(_new_definition(func_ir, array_var, + ir.Expr.call(empty_func, (size_tuple_var,), list(array_kws), + loc=loc), loc)) + + # Add back removed just in case they are used by something else + for var in removed: + stmts.append(_new_definition(func_ir, var, array_var, loc)) + + # Add back terminator + stmts.append(terminator) + # Modify loop_entry + loop_entry.body = stmts + + if range_def: + if range_def[0] != 0: + # when range doesn't start from 0, index_var becomes loop index + # (iter_first_var) minus an offset (range_def[0]) + terminator = loop_header.terminator + assert (isinstance(terminator, ir.Branch)) + # find the block in the loop body that header jumps to + block_id = terminator.truebr + blk = func_ir.blocks[block_id] + loc = blk.loc + blk.body.insert( + 0, + _new_definition( + func_ir, index_var, + ir.Expr.binop(fn=operator.sub, lhs=iter_first_var, + rhs=range_def[0], loc=loc), + loc + ) + ) + else: + # Insert index_var increment to the end of loop header + loc = loop_header.loc + terminator = loop_header.terminator + stmts = loop_header.body[0:-1] + next_index_var = scope.redefine("next_index", loc) + one = scope.redefine("one", loc) + # one = 1 + stmts.append(_new_definition(func_ir, one, + ir.Const(value=1,loc=loc), loc)) + # next_index_var = index_var + 1 + stmts.append(_new_definition(func_ir, next_index_var, + ir.Expr.binop(fn=operator.add, lhs=index_var, rhs=one, + loc=loc), loc)) + # index_var = next_index_var + stmts.append(_new_definition(func_ir, index_var, next_index_var, loc)) + stmts.append(terminator) + loop_header.body = stmts + + # In append_block, change list_append into array assign + for i in range(len(append_block.body)): + if append_block.body[i] is append_stmt: + debug_print("Replace append with SetItem") + append_block.body[i] = ir.SetItem( + target=array_var, index=index_var, + value=append_stmt.value.args[0], loc=append_stmt.loc) + + # replace array call, by changing "a = array(b)" to "a = b" + stmt = func_ir.blocks[exit_block].body[array_call_index] + # stmt can be either array call or SetItem, we only replace array call + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + stmt.value = array_var + func_ir._definitions[stmt.target.name] = [stmt.value] + + return True + + +def _find_unsafe_empty_inferred(func_ir, expr): + unsafe_empty_inferred + require(isinstance(expr, ir.Expr) and expr.op == 'call') + callee = expr.func + callee_def = get_definition(func_ir, callee) + require(isinstance(callee_def, ir.Global)) + _make_debug_print("_find_unsafe_empty_inferred")(callee_def.value) + return callee_def.value == unsafe_empty_inferred + + +def _fix_nested_array(func_ir): + """Look for assignment like: a[..] = b, where both a and b are numpy arrays, + and try to eliminate array b by expanding a with an extra dimension. + """ + blocks = func_ir.blocks + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + empty_deadmap = dict([(label, set()) for label in blocks.keys()]) + livemap = compute_live_variables(cfg, blocks, usedefs.defmap, empty_deadmap) + + def find_array_def(arr): + """Find numpy array definition such as + arr = numba.unsafe.ndarray.empty_inferred(...). + If it is arr = b[...], find array definition of b recursively. + """ + arr_def = get_definition(func_ir, arr) + _make_debug_print("find_array_def")(arr, arr_def) + if isinstance(arr_def, ir.Expr): + if guard(_find_unsafe_empty_inferred, func_ir, arr_def): + return arr_def + elif arr_def.op == 'getitem': + return find_array_def(arr_def.value) + raise GuardException + + def fix_dependencies(expr, varlist): + """Double check if all variables in varlist are defined before + expr is used. Try to move constant definition when the check fails. + Bails out by raising GuardException if it can't be moved. + """ + debug_print = _make_debug_print("fix_dependencies") + for label, block in blocks.items(): + scope = block.scope + body = block.body + defined = set() + for i in range(len(body)): + inst = body[i] + if isinstance(inst, ir.Assign): + defined.add(inst.target.name) + if inst.value is expr: + new_varlist = [] + for var in varlist: + # var must be defined before this inst, or live + # and not later defined. + if (var.name in defined or + (var.name in livemap[label] and + not (var.name in usedefs.defmap[label]))): + debug_print(var.name, " already defined") + new_varlist.append(var) + else: + debug_print(var.name, " not yet defined") + var_def = get_definition(func_ir, var.name) + if isinstance(var_def, ir.Const): + loc = var.loc + new_var = scope.redefine("new_var", loc) + new_const = ir.Const(var_def.value, loc) + new_vardef = _new_definition( + func_ir, new_var, new_const, loc) + new_body = [] + new_body.extend(body[:i]) + new_body.append(new_vardef) + new_body.extend(body[i:]) + block.body = new_body + new_varlist.append(new_var) + else: + raise GuardException + return new_varlist + # when expr is not found in block + raise GuardException + + def fix_array_assign(stmt): + """For assignment like lhs[idx] = rhs, where both lhs and rhs are + arrays, do the following: + 1. find the definition of rhs, which has to be a call to + numba.unsafe.ndarray.empty_inferred + 2. find the source array creation for lhs, insert an extra dimension of + size of b. + 3. replace the definition of + rhs = numba.unsafe.ndarray.empty_inferred(...) with rhs = lhs[idx] + """ + require(isinstance(stmt, ir.SetItem)) + require(isinstance(stmt.value, ir.Var)) + debug_print = _make_debug_print("fix_array_assign") + debug_print("found SetItem: ", stmt) + lhs = stmt.target + # Find the source array creation of lhs + lhs_def = find_array_def(lhs) + debug_print("found lhs_def: ", lhs_def) + rhs_def = get_definition(func_ir, stmt.value) + debug_print("found rhs_def: ", rhs_def) + require(isinstance(rhs_def, ir.Expr)) + if rhs_def.op == 'cast': + rhs_def = get_definition(func_ir, rhs_def.value) + require(isinstance(rhs_def, ir.Expr)) + require(_find_unsafe_empty_inferred(func_ir, rhs_def)) + # Find the array dimension of rhs + dim_def = get_definition(func_ir, rhs_def.args[0]) + require(isinstance(dim_def, ir.Expr) and dim_def.op == 'build_tuple') + debug_print("dim_def = ", dim_def) + extra_dims = [get_definition(func_ir, x, lhs_only=True) + for x in dim_def.items ] + debug_print("extra_dims = ", extra_dims) + # Expand size tuple when creating lhs_def with extra_dims + size_tuple_def = get_definition(func_ir, lhs_def.args[0]) + require(isinstance(size_tuple_def, ir.Expr) and + size_tuple_def.op == 'build_tuple') + debug_print("size_tuple_def = ", size_tuple_def) + extra_dims = fix_dependencies(size_tuple_def, extra_dims) + size_tuple_def.items += extra_dims + # In-place modify rhs_def to be getitem + rhs_def.op = 'getitem' + rhs_def.fn = operator.getitem + rhs_def.value = get_definition(func_ir, lhs, lhs_only=True) + rhs_def.index = stmt.index + del rhs_def._kws['func'] + del rhs_def._kws['args'] + del rhs_def._kws['vararg'] + del rhs_def._kws['kws'] + # success + return True + + for label in find_topo_order(func_ir.blocks): + block = func_ir.blocks[label] + for stmt in block.body: + if guard(fix_array_assign, stmt): + block.body.remove(stmt) + + +def _new_definition(func_ir, var, value, loc): + func_ir._definitions[var.name] = [value] + return ir.Assign(value=value, target=var, loc=loc) + + +@rewrites.register_rewrite('after-inference') +class RewriteArrayOfConsts(rewrites.Rewrite): + '''The RewriteArrayOfConsts class is responsible for finding + 1D array creations from a constant list, and rewriting it into + direct initialization of array elements without creating the list. + ''' + def __init__(self, state, *args, **kws): + self.typingctx = state.typingctx + super(RewriteArrayOfConsts, self).__init__(*args, **kws) + + def match(self, func_ir, block, typemap, calltypes): + if len(calltypes) == 0: + return False + self.crnt_block = block + self.new_body = guard(_inline_const_arraycall, block, func_ir, + self.typingctx, typemap, calltypes) + return self.new_body is not None + + def apply(self): + self.crnt_block.body = self.new_body + return self.crnt_block + + +def _inline_const_arraycall(block, func_ir, context, typemap, calltypes): + """Look for array(list) call where list is a constant list created by + build_list, and turn them into direct array creation and initialization, if + the following conditions are met: + 1. The build_list call immediate precedes the array call; + 2. The list variable is no longer live after array call; + If any condition check fails, no modification will be made. + """ + debug_print = _make_debug_print("inline_const_arraycall") + scope = block.scope + + def inline_array(array_var, expr, stmts, list_vars, dels): + """Check to see if the given "array_var" is created from a list + of constants, and try to inline the list definition as array + initialization. + + Extra statements produced with be appended to "stmts". + """ + callname = guard(find_callname, func_ir, expr) + require(callname and callname[1] == 'numpy' and callname[0] == 'array') + require(expr.args[0].name in list_vars) + ret_type = calltypes[expr].return_type + require(isinstance(ret_type, types.ArrayCompatible) and + ret_type.ndim == 1) + loc = expr.loc + list_var = expr.args[0] + # Get the type of the array to be created. + array_typ = typemap[array_var.name] + debug_print("inline array_var = ", array_var, " list_var = ", list_var) + # Get the element type of the array to be created. + dtype = array_typ.dtype + # Get the sequence of operations to provide values to the new array. + seq, _ = find_build_sequence(func_ir, list_var) + size = len(seq) + # Create a tuple to pass to empty below to specify the new array size. + size_var = scope.redefine("size", loc) + size_tuple_var = scope.redefine("size_tuple", loc) + size_typ = types.intp + size_tuple_typ = types.UniTuple(size_typ, 1) + typemap[size_var.name] = size_typ + typemap[size_tuple_var.name] = size_tuple_typ + stmts.append( + _new_definition(func_ir, size_var, + ir.Const(size, loc=loc), loc)) + stmts.append( + _new_definition(func_ir, size_tuple_var, + ir.Expr.build_tuple(items=[size_var], loc=loc), + loc)) + + # The general approach is to create an empty array and then fill + # the elements in one-by-one from their specification. + + # Get the numpy type to pass to empty. + nptype = types.DType(dtype) + + # Create a variable to hold the numpy empty function. + empty_func = scope.redefine("empty_func", loc) + fnty = get_np_ufunc_typ(np.empty, context) + context.resolve_function_type(fnty, (size_typ,), {'dtype': nptype}) + + typemap[empty_func.name] = fnty + + stmts.append( + _new_definition(func_ir, empty_func, + ir.Global('empty', np.empty, loc=loc), loc)) + + # We pass two arguments to empty, first the size tuple and second + # the dtype of the new array. Here, we created typ_var which is + # the dtype argument of the new array. typ_var in turn is created + # by getattr of the dtype string on the numpy module. + + # Create var for numpy module. + g_np_var = scope.redefine("$np_g_var", loc) + typemap[g_np_var.name] = types.misc.Module(np) + g_np = ir.Global('np', np, loc) + stmts.append(_new_definition(func_ir, g_np_var, g_np, loc)) + + # Create var for result of numpy.. + typ_var = scope.redefine("$np_typ_var", loc) + typemap[typ_var.name] = nptype + dtype_str = str(dtype) + if dtype_str == 'bool': + dtype_str = 'bool_' + # Get dtype attribute of numpy module. + np_typ_getattr = ir.Expr.getattr(g_np_var, dtype_str, loc) + stmts.append(_new_definition(func_ir, typ_var, np_typ_getattr, loc)) + + # Create the call to numpy.empty passing the size tuple and dtype var. + empty_call = ir.Expr.call(empty_func, [size_var, typ_var], {}, loc=loc) + calltypes[empty_call] = typing.signature(array_typ, size_typ, nptype) + stmts.append(_new_definition(func_ir, array_var, empty_call, loc)) + + # Fill in the new empty array one-by-one. + for i in range(size): + index_var = scope.redefine("index", loc) + index_typ = types.intp + typemap[index_var.name] = index_typ + stmts.append( + _new_definition(func_ir, index_var, ir.Const(i, loc), loc)) + setitem = ir.SetItem(array_var, index_var, seq[i], loc) + calltypes[setitem] = typing.signature(types.none, array_typ, + index_typ, dtype) + stmts.append(setitem) + + stmts.extend(dels) + return True + + class State(object): + """ + This class is used to hold the state in the following loop so as to make + it easy to reset the state of the variables tracking the various + statement kinds + """ + + def __init__(self): + # list_vars keep track of the variable created from the latest + # build_list instruction, as well as its synonyms. + self.list_vars = [] + # dead_vars keep track of those in list_vars that are considered + # dead. + self.dead_vars = [] + # list_items keep track of the elements used in build_list. + self.list_items = [] + self.stmts = [] + # dels keep track of the deletion of list_items, which will need to + # be moved after array initialization. + self.dels = [] + # tracks if a modification has taken place + self.modified = False + + def reset(self): + """ + Resets the internal state of the variables used for tracking + """ + self.list_vars = [] + self.dead_vars = [] + self.list_items = [] + self.dels = [] + + def list_var_used(self, inst): + """ + Returns True if the list being analysed is used between the + build_list and the array call. + """ + return any([x.name in self.list_vars for x in inst.list_vars()]) + + state = State() + + for inst in block.body: + if isinstance(inst, ir.Assign): + if isinstance(inst.value, ir.Var): + if inst.value.name in state.list_vars: + state.list_vars.append(inst.target.name) + state.stmts.append(inst) + continue + elif isinstance(inst.value, ir.Expr): + expr = inst.value + if expr.op == 'build_list': + # new build_list encountered, reset state + state.reset() + state.list_items = [x.name for x in expr.items] + state.list_vars = [inst.target.name] + state.stmts.append(inst) + continue + elif expr.op == 'call' and expr in calltypes: + if guard(inline_array, inst.target, expr, + state.stmts, state.list_vars, state.dels): + state.modified = True + continue + elif isinstance(inst, ir.Del): + removed_var = inst.value + if removed_var in state.list_items: + state.dels.append(inst) + continue + elif removed_var in state.list_vars: + # one of the list_vars is considered dead. + state.dead_vars.append(removed_var) + state.list_vars.remove(removed_var) + state.stmts.append(inst) + if state.list_vars == []: + # if all list_vars are considered dead, we need to filter + # them out from existing stmts to completely remove + # build_list. + # Note that if a translation didn't take place, dead_vars + # will also be empty when we reach this point. + body = [] + for inst in state.stmts: + if ((isinstance(inst, ir.Assign) and + inst.target.name in state.dead_vars) or + (isinstance(inst, ir.Del) and + inst.value in state.dead_vars)): + continue + body.append(inst) + state.stmts = body + state.dead_vars = [] + state.modified = True + continue + state.stmts.append(inst) + + # If the list is used in any capacity between build_list and array + # call, then we must call off the translation for this list because + # it could be mutated and list_items would no longer be applicable. + if state.list_var_used(inst): + state.reset() + + return state.stmts if state.modified else None diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/interpreter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..9b679d7f82ff9a6bdcb3f87ed4fcd730acd546d0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/interpreter.py @@ -0,0 +1,3558 @@ +import builtins +import collections +import dis +import operator +import logging +import textwrap + +from numba.core import errors, ir, config +from numba.core.errors import ( + NotDefinedError, + UnsupportedBytecodeError, + error_extras, +) +from numba.core.ir_utils import get_definition, guard +from numba.core.utils import (PYVERSION, BINOPS_TO_OPERATORS, + INPLACE_BINOPS_TO_OPERATORS, _lazy_pformat,) +from numba.core.byteflow import Flow, AdaptDFA, AdaptCFA, BlockKind +from numba.core.unsafe import eh +from numba.cpython.unsafe.tuple import unpack_single_tuple + + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + # Operands for CALL_INTRINSIC_1 + from numba.core.byteflow import CALL_INTRINSIC_1_Operand as ci1op +elif PYVERSION in ((3, 10), (3, 11)): + pass +else: + raise NotImplementedError(PYVERSION) + + +class _UNKNOWN_VALUE(object): + """Represents an unknown value, this is for ease of debugging purposes only. + """ + + def __init__(self, varname): + self._varname = varname + + def __repr__(self): + return "_UNKNOWN_VALUE({})".format(self._varname) + + +_logger = logging.getLogger(__name__) + + +class Assigner(object): + """ + This object keeps track of potential assignment simplifications + inside a code block. + For example `$O.1 = x` followed by `y = $0.1` can be simplified + into `y = x`, but it's not possible anymore if we have `x = z` + in-between those two instructions. + + NOTE: this is not only an optimization, but is actually necessary + due to certain limitations of Numba - such as only accepting the + returning of an array passed as function argument. + """ + + def __init__(self): + # { destination variable name -> source Var object } + self.dest_to_src = {} + # Basically a reverse mapping of dest_to_src: + # { source variable name -> all destination names in dest_to_src } + self.src_invalidate = collections.defaultdict(list) + self.unused_dests = set() + + def assign(self, srcvar, destvar): + """ + Assign *srcvar* to *destvar*. Return either *srcvar* or a possible + simplified assignment source (earlier assigned to *srcvar*). + """ + srcname = srcvar.name + destname = destvar.name + if destname in self.src_invalidate: + # destvar will change, invalidate all previously known + # simplifications + for d in self.src_invalidate.pop(destname): + self.dest_to_src.pop(d) + if srcname in self.dest_to_src: + srcvar = self.dest_to_src[srcname] + if destvar.is_temp: + self.dest_to_src[destname] = srcvar + self.src_invalidate[srcname].append(destname) + self.unused_dests.add(destname) + return srcvar + + def get_assignment_source(self, destname): + """ + Get a possible assignment source (a ir.Var instance) to replace + *destname*, otherwise None. + """ + if destname in self.dest_to_src: + return self.dest_to_src[destname] + self.unused_dests.discard(destname) + return None + + +def _remove_assignment_definition(old_body, idx, func_ir, already_deleted_defs): + """ + Deletes the definition defined for old_body at index idx + from func_ir. We assume this stmt will be deleted from + new_body. + + In some optimizations we may update the same variable multiple times. + In this situation, we only need to delete a particular definition once, + this is tracked in already_deleted_def, which is a map from + assignment name to the set of values that have already been + deleted. + """ + lhs = old_body[idx].target.name + rhs = old_body[idx].value + if rhs in func_ir._definitions[lhs]: + func_ir._definitions[lhs].remove(rhs) + already_deleted_defs[lhs].add(rhs) + elif rhs not in already_deleted_defs[lhs]: + raise UnsupportedBytecodeError( + "Inconsistency found in the definitions while executing" + " a peephole optimization. This suggests an internal" + " error or inconsistency elsewhere in the compiler." + ) + + +def _call_function_ex_replace_kws_small( + old_body, + keyword_expr, + new_body, + buildmap_idx, + func_ir, + already_deleted_defs +): + """ + Extracts the kws args passed as varkwarg + for CALL_FUNCTION_EX. This pass is taken when + n_kws <= 15 and the bytecode looks like: + + # Start for each argument + LOAD_FAST # Load each argument. + # End for each argument + ... + BUILD_CONST_KEY_MAP # Build a map + + In the generated IR, the varkwarg refers + to a single build_map that contains all of the + kws. In addition to returning the kws, this + function updates new_body to remove all usage + of the map. + """ + kws = keyword_expr.items.copy() + # kws are required to have constant keys. + # We update these with the value_indexes + value_indexes = keyword_expr.value_indexes + for key, index in value_indexes.items(): + kws[index] = (key, kws[index][1]) + # Remove the build_map by setting the list + # index to None. Nones will be removed later. + new_body[buildmap_idx] = None + # Remove the definition. + _remove_assignment_definition( + old_body, buildmap_idx, func_ir, already_deleted_defs + ) + return kws + + +def _call_function_ex_replace_kws_large( + old_body, + buildmap_name, + buildmap_idx, + search_end, + new_body, + func_ir, + errmsg, + already_deleted_defs +): + """ + Extracts the kws args passed as varkwarg + for CALL_FUNCTION_EX. This pass is taken when + n_kws > 15 and the bytecode looks like: + + BUILD_MAP # Construct the map + # Start for each argument + LOAD_CONST # Load a constant for the name of the argument + LOAD_FAST # Load each argument. + MAP_ADD # Append the (key, value) pair to the map + # End for each argument + + In the IR generated, the initial build map is empty and a series + of setitems are applied afterwards. THE IR looks like: + + $build_map_var = build_map(items=[]) + $constvar = const(str, ...) # create the const key + # CREATE THE ARGUMENT, This may take multiple lines. + $created_arg = ... + $var = getattr( + value=$build_map_var, + attr=__setitem__, + ) + $unused_var = call $var($constvar, $created_arg) + + We iterate through the IR, deleting all usages of the buildmap + from the new_body, and adds the kws to a new kws list. + """ + # Remove the build_map from the body. + new_body[buildmap_idx] = None + # Remove the definition. + _remove_assignment_definition( + old_body, buildmap_idx, func_ir, already_deleted_defs + ) + kws = [] + search_start = buildmap_idx + 1 + while search_start <= search_end: + # The first value must be a constant. + const_stmt = old_body[search_start] + if not ( + isinstance(const_stmt, ir.Assign) + and isinstance(const_stmt.value, ir.Const) + ): + # We cannot handle this format so raise the + # original error message. + raise UnsupportedBytecodeError(errmsg) + key_var_name = const_stmt.target.name + key_val = const_stmt.value.value + search_start += 1 + # Now we need to search for a getattr with setitem + found_getattr = False + while ( + search_start <= search_end + and not found_getattr + ): + getattr_stmt = old_body[search_start] + if ( + isinstance(getattr_stmt, ir.Assign) + and isinstance(getattr_stmt.value, ir.Expr) + and getattr_stmt.value.op == "getattr" + and ( + getattr_stmt.value.value.name + == buildmap_name + ) + and getattr_stmt.value.attr == "__setitem__" + ): + found_getattr = True + else: + # If the argument is "created" in JIT, then there + # will be intermediate operations in between setitems. + # For example we have arg5=pow(arg5, 2), + # then the IR would look like: + # + # # Creation of the constant key. + # $const44.26 = const(str, arg5) + # + # # Argument creation. This is the section we are skipping + # $46load_global.27 = global(pow: ) + # $const50.29 = const(int, 2) + # $call.30 = call $46load_global.27(arg5, $const50.29) + # + # # Setitem with arg5 + # $54map_add.31 = getattr(value=$map.2, attr=__setitem__) + # $54map_add.32 = call $54map_add.31($const44.26, $call.30) + search_start += 1 + if ( + not found_getattr + or search_start == search_end + ): + # We cannot handle this format so raise the + # original error message. + raise UnsupportedBytecodeError(errmsg) + setitem_stmt = old_body[search_start + 1] + if not ( + isinstance(setitem_stmt, ir.Assign) + and isinstance(setitem_stmt.value, ir.Expr) + and setitem_stmt.value.op == "call" + and ( + setitem_stmt.value.func.name + == getattr_stmt.target.name + ) + and len(setitem_stmt.value.args) == 2 + and ( + setitem_stmt.value.args[0].name + == key_var_name + ) + ): + # A call statement should always immediately follow the + # getattr. If for some reason this doesn't match the code + # format, we raise the original error message. This check + # is meant as a precaution. + raise UnsupportedBytecodeError(errmsg) + arg_var = setitem_stmt.value.args[1] + # Append the (key, value) pair. + kws.append((key_val, arg_var)) + # Remove the __setitem__ getattr and call + new_body[search_start] = None + new_body[search_start + 1] = None + # Remove the definitions. + _remove_assignment_definition( + old_body, search_start, func_ir, already_deleted_defs + ) + _remove_assignment_definition( + old_body, search_start + 1, func_ir, already_deleted_defs + ) + search_start += 2 + return kws + + +def _call_function_ex_replace_args_small( + old_body, + tuple_expr, + new_body, + buildtuple_idx, + func_ir, + already_deleted_defs +): + """ + Extracts the args passed as vararg + for CALL_FUNCTION_EX. This pass is taken when + n_args <= 30 and the bytecode looks like: + + # Start for each argument + LOAD_FAST # Load each argument. + # End for each argument + ... + BUILD_TUPLE # Create a tuple of the arguments + + In the IR generated, the vararg refer + to a single build_tuple that contains all of the + args. In addition to returning the args, this + function updates new_body to remove all usage + of the tuple. + """ + # Delete the build tuple + new_body[buildtuple_idx] = None + # Remove the definition. + _remove_assignment_definition( + old_body, buildtuple_idx, func_ir, already_deleted_defs + ) + # Return the args. + return tuple_expr.items + + +def _call_function_ex_replace_args_large( + old_body, + vararg_stmt, + new_body, + search_end, + func_ir, + errmsg, + already_deleted_defs +): + """ + Extracts the args passed as vararg + for CALL_FUNCTION_EX. This pass is taken when + n_args > 30 and the bytecode looks like: + + BUILD_TUPLE # Create a list to append to + # Start for each argument + LOAD_FAST # Load each argument. + LIST_APPEND # Add the argument to the list + # End for each argument + ... + LIST_TO_TUPLE # Convert the args to a tuple. + + In the IR generated, the tuple is created by concatenating + together several 1 element tuples to an initial empty tuple. + We traverse backwards in the IR, collecting args, until we + find the original empty tuple. For example, the IR might + look like: + + $orig_tuple = build_tuple(items=[]) + $first_var = build_tuple(items=[Var(arg0, test.py:6)]) + $next_tuple = $orig_tuple + $first_var + ... + $final_var = build_tuple(items=[Var(argn, test.py:6)]) + $final_tuple = $prev_tuple + $final_var + $varargs_var = $final_tuple + """ + # We traverse to the front of the block to look for the original + # tuple. + search_start = 0 + total_args = [] + if ( + isinstance(vararg_stmt, ir.Assign) + and isinstance(vararg_stmt.value, ir.Var) + ): + target_name = vararg_stmt.value.name + # If there is an initial assignment, delete it + new_body[search_end] = None + # Remove the definition. + _remove_assignment_definition( + old_body, search_end, func_ir, already_deleted_defs + ) + search_end -= 1 + else: + # There must always be an initial assignment + # https://github.com/numba/numba/blob/59fa2e335be68148b3bd72a29de3ff011430038d/numba/core/interpreter.py#L259-L260 + # If this changes we may need to support this branch. + raise AssertionError("unreachable") + # Traverse backwards to find all concatenations + # until eventually reaching the original empty tuple. + while search_end >= search_start: + concat_stmt = old_body[search_end] + if ( + isinstance(concat_stmt, ir.Assign) + and concat_stmt.target.name == target_name + and isinstance(concat_stmt.value, ir.Expr) + and concat_stmt.value.op == "build_tuple" + and not concat_stmt.value.items + ): + new_body[search_end] = None + # Remove the definition. + _remove_assignment_definition( + old_body, search_end, func_ir, already_deleted_defs + ) + # If we have reached the build_tuple we exit. + break + else: + # We expect to find another arg to append. + # The first stmt must be a binop "add" + if (search_end == search_start) or not ( + isinstance(concat_stmt, ir.Assign) + and ( + concat_stmt.target.name + == target_name + ) + and isinstance( + concat_stmt.value, ir.Expr + ) + and concat_stmt.value.op == "binop" + and concat_stmt.value.fn == operator.add + ): + # We cannot handle this format. + raise UnsupportedBytecodeError(errmsg) + lhs_name = concat_stmt.value.lhs.name + rhs_name = concat_stmt.value.rhs.name + # The previous statement should be a + # build_tuple containing the arg. + arg_tuple_stmt = old_body[search_end - 1] + if not ( + isinstance(arg_tuple_stmt, ir.Assign) + and isinstance( + arg_tuple_stmt.value, ir.Expr + ) + and ( + arg_tuple_stmt.value.op + == "build_tuple" + ) + and len(arg_tuple_stmt.value.items) == 1 + ): + # We cannot handle this format. + raise UnsupportedBytecodeError(errmsg) + if arg_tuple_stmt.target.name == lhs_name: + # The tuple should always be generated on the RHS. + raise AssertionError("unreachable") + elif arg_tuple_stmt.target.name == rhs_name: + target_name = lhs_name + else: + # We cannot handle this format. + raise UnsupportedBytecodeError(errmsg) + total_args.append( + arg_tuple_stmt.value.items[0] + ) + new_body[search_end] = None + new_body[search_end - 1] = None + # Remove the definitions. + _remove_assignment_definition( + old_body, search_end, func_ir, already_deleted_defs + ) + _remove_assignment_definition( + old_body, search_end - 1, func_ir, already_deleted_defs + ) + search_end -= 2 + # Avoid any space between appends + keep_looking = True + while search_end >= search_start and keep_looking: + next_stmt = old_body[search_end] + if ( + isinstance(next_stmt, ir.Assign) + and ( + next_stmt.target.name + == target_name + ) + ): + keep_looking = False + else: + # If the argument is "created" in JIT, then there + # will be intermediate operations in between appends. + # For example if the next arg after arg4 is pow(arg5, 2), + # then the IR would look like: + # + # # Appending arg4 + # $arg4_tup = build_tuple(items=[arg4]) + # $append_var.5 = $append_var.4 + $arg4_tup + # + # # Creation of arg5. + # # This is the section that we are skipping. + # $32load_global.20 = global(pow: ) + # $const36.22 = const(int, 2) + # $call.23 = call $32load_global.20(arg5, $const36.22) + # + # # Appending arg5 + # $arg5_tup = build_tuple(items=[$call.23]) + # $append_var.6 = $append_var.5 + $arg5_tup + search_end -= 1 + if search_end == search_start: + # If we reached the start we never found the build_tuple. + # We cannot handle this format so raise the + # original error message. + raise UnsupportedBytecodeError(errmsg) + # Reverse the arguments so we get the correct order. + return total_args[::-1] + + +def peep_hole_call_function_ex_to_call_function_kw(func_ir): + """ + This peephole rewrites a bytecode sequence unique to Python 3.10 + where CALL_FUNCTION_EX is used instead of CALL_FUNCTION_KW because of + stack limitations set by CPython. This limitation is imposed whenever + a function call has too many arguments or keyword arguments. + + https://github.com/python/cpython/blob/a58ebcc701dd6c43630df941481475ff0f615a81/Python/compile.c#L55 + https://github.com/python/cpython/blob/a58ebcc701dd6c43630df941481475ff0f615a81/Python/compile.c#L4442 + + In particular, this change is imposed whenever (n_args / 2) + n_kws > 15. + + Different bytecode is generated for args depending on if n_args > 30 + or n_args <= 30 and similarly if n_kws > 15 or n_kws <= 15. + + This function unwraps the *args and **kwargs in the function call + and places these values directly into the args and kwargs of the call. + """ + # All changes are local to the a single block + # so it can be traversed in any order. + errmsg = textwrap.dedent(""" + CALL_FUNCTION_EX with **kwargs not supported. + If you are not using **kwargs this may indicate that + you have a large number of kwargs and are using inlined control + flow. You can resolve this issue by moving the control flow out of + the function call. For example, if you have + + f(a=1 if flag else 0, ...) + + Replace that with: + + a_val = 1 if flag else 0 + f(a=a_val, ...)""") + + # Track which definitions have already been deleted + already_deleted_defs = collections.defaultdict(set) + for blk in func_ir.blocks.values(): + blk_changed = False + new_body = [] + for i, stmt in enumerate(blk.body): + if ( + isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == "call" + and stmt.value.varkwarg is not None + ): + blk_changed = True + call = stmt.value + args = call.args + kws = call.kws + # We need to check the call expression contents if + # it contains either vararg or varkwarg. If it contains + # varkwarg we need to update the IR. If it just contains + # vararg we don't need to update the IR, but we need to + # check if peep_hole_list_to_tuple failed to replace the + # vararg list with a tuple. If so, we output an error + # message with suggested code changes. + vararg = call.vararg + varkwarg = call.varkwarg + start_search = i - 1 + # varkwarg should be defined second so we start there. + varkwarg_loc = start_search + keyword_def = None + found = False + while varkwarg_loc >= 0 and not found: + keyword_def = blk.body[varkwarg_loc] + if ( + isinstance(keyword_def, ir.Assign) + and keyword_def.target.name == varkwarg.name + ): + found = True + else: + varkwarg_loc -= 1 + if ( + kws + or not found + or not ( + isinstance(keyword_def.value, ir.Expr) + and keyword_def.value.op == "build_map" + ) + ): + # If we couldn't find where the kwargs are created + # then it should be a normal **kwargs call + # so we produce an unsupported message. + raise UnsupportedBytecodeError(errmsg) + # Determine the kws + if keyword_def.value.items: + # n_kws <= 15 case. + # Here the IR looks like a series of + # constants, then the arguments and finally + # a build_map that contains all of the pairs. + # For Example: + # + # $const_n = const("arg_name") + # $arg_n = ... + # $kwargs_var = build_map(items=[ + # ($const_0, $arg_0), + # ..., + # ($const_n, $arg_n),]) + kws = _call_function_ex_replace_kws_small( + blk.body, + keyword_def.value, + new_body, + varkwarg_loc, + func_ir, + already_deleted_defs, + ) + else: + # n_kws > 15 case. + # Here the IR is an initial empty build_map + # followed by a series of setitems with a constant + # key and then the argument. + # For example: + # + # $kwargs_var = build_map(items=[]) + # $const_0 = const("arg_name") + # $arg_0 = ... + # $my_attr = getattr(const_0, attr=__setitem__) + # $unused_var = call $my_attr($const_0, $arg_0) + # ... + kws = _call_function_ex_replace_kws_large( + blk.body, + varkwarg.name, + varkwarg_loc, + i - 1, + new_body, + func_ir, + errmsg, + already_deleted_defs, + ) + start_search = varkwarg_loc + # Vararg isn't required to be provided. + if vararg is not None: + if args: + # If we have vararg then args is expected to + # be an empty list. + raise UnsupportedBytecodeError(errmsg) + vararg_loc = start_search + args_def = None + found = False + while vararg_loc >= 0 and not found: + args_def = blk.body[vararg_loc] + if ( + isinstance(args_def, ir.Assign) + and args_def.target.name == vararg.name + ): + found = True + else: + vararg_loc -= 1 + if not found: + # If we couldn't find where the args are created + # then we can't handle this format. + raise UnsupportedBytecodeError(errmsg) + if ( + isinstance(args_def.value, ir.Expr) + and args_def.value.op == "build_tuple" + ): + # n_args <= 30 case. + # Here the IR is a simple build_tuple containing + # all of the args. + # For example: + # + # $arg_n = ... + # $varargs = build_tuple( + # items=[$arg_0, ..., $arg_n] + # ) + args = _call_function_ex_replace_args_small( + blk.body, + args_def.value, + new_body, + vararg_loc, + func_ir, + already_deleted_defs, + ) + elif ( + isinstance(args_def.value, ir.Expr) + and args_def.value.op == "list_to_tuple" + ): + # If there is a call with vararg we need to check + # if the list -> tuple conversion failed and if so + # throw an error. + raise UnsupportedBytecodeError(errmsg) + else: + # Here the IR is an initial empty build_tuple. + # Then for each arg, a new tuple with a single + # element is created and one by one these are + # added to a growing tuple. + # For example: + # + # $combo_tup_0 = build_tuple(items=[]) + # $arg0 = ... + # $arg0_tup = build_tuple(items=[$arg0]) + # $combo_tup_1 = $combo_tup_0 + $arg0_tup + # $arg1 = ... + # $arg1_tup = build_tuple(items=[$arg1]) + # $combo_tup_2 = $combo_tup_1 + $arg1_tup + # ... + # $combo_tup_n = $combo_tup_{n-1} + $argn_tup + # + # In addition, the IR contains a final + # assignment for the varargs that looks like: + # + # $varargs_var = $combo_tup_n + # + # Here args_def is expected to be a simple assignment. + args = _call_function_ex_replace_args_large( + blk.body, + args_def, + new_body, + vararg_loc, + func_ir, + errmsg, + already_deleted_defs, + ) + # Create a new call updating the args and kws + new_call = ir.Expr.call( + call.func, args, kws, call.loc, target=call.target + ) + # Drop the existing definition for this stmt. + _remove_assignment_definition( + blk.body, i, func_ir, already_deleted_defs + ) + # Update the statement + stmt = ir.Assign(new_call, stmt.target, stmt.loc) + # Update the definition + func_ir._definitions[stmt.target.name].append(new_call) + elif ( + isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == "call" + and stmt.value.vararg is not None + ): + # If there is a call with vararg we need to check + # if the list -> tuple conversion failed and if so + # throw an error. + call = stmt.value + vararg_name = call.vararg.name + if ( + vararg_name in func_ir._definitions + and len(func_ir._definitions[vararg_name]) == 1 + ): + # If this value is still a list to tuple raise the + # exception. + expr = func_ir._definitions[vararg_name][0] + if isinstance(expr, ir.Expr) and expr.op == "list_to_tuple": + raise UnsupportedBytecodeError(errmsg) + + new_body.append(stmt) + # Replace the block body if we changed the IR + if blk_changed: + blk.body.clear() + blk.body.extend([x for x in new_body if x is not None]) + return func_ir + + +def peep_hole_list_to_tuple(func_ir): + """ + This peephole rewrites a bytecode sequence new to Python 3.9 that looks + like e.g.: + + def foo(a): + return (*a,) + + 41 0 BUILD_LIST 0 + 2 LOAD_FAST 0 (a) + 4 LIST_EXTEND 1 + 6 LIST_TO_TUPLE + 8 RETURN_VAL + + essentially, the unpacking of tuples is written as a list which is appended + to/extended and then "magicked" into a tuple by the new LIST_TO_TUPLE + opcode. + + This peephole repeatedly analyses the bytecode in a block looking for a + window between a `LIST_TO_TUPLE` and `BUILD_LIST` and... + + 1. Turns the BUILD_LIST into a BUILD_TUPLE + 2. Sets an accumulator's initial value as the target of the BUILD_TUPLE + 3. Searches for 'extend' on the original list and turns these into binary + additions on the accumulator. + 4. Searches for 'append' on the original list and turns these into a + `BUILD_TUPLE` which is then appended via binary addition to the + accumulator. + 5. Assigns the accumulator to the variable that exits the peephole and the + rest of the block/code refers to as the result of the unpack operation. + 6. Patches up + """ + _DEBUG = False + + # For all blocks + for offset, blk in func_ir.blocks.items(): + # keep doing the peephole rewrite until nothing is left that matches + while True: + # first try and find a matching region + # i.e. BUILD_LIST......LIST_TO_TUPLE + def find_postive_region(): + found = False + for idx in reversed(range(len(blk.body))): + stmt = blk.body[idx] + if isinstance(stmt, ir.Assign): + value = stmt.value + if (isinstance(value, ir.Expr) and + value.op == 'list_to_tuple'): + target_list = value.info[0] + found = True + bt = (idx, stmt) + if found: + if isinstance(stmt, ir.Assign): + if stmt.target.name == target_list: + region = (bt, (idx, stmt)) + return region + + region = find_postive_region() + # if there's a peep hole region then do something with it + if region is not None: + peep_hole = blk.body[region[1][0] : region[0][0]] + if _DEBUG: + print("\nWINDOW:") + for x in peep_hole: + print(x) + print("") + + appends = [] + extends = [] + init = region[1][1] + const_list = init.target.name + # Walk through the peep_hole and find things that are being + # "extend"ed and "append"ed to the BUILD_LIST + for x in peep_hole: + if isinstance(x, ir.Assign): + if isinstance(x.value, ir.Expr): + expr = x.value + if (expr.op == 'getattr' and + expr.value.name == const_list): + # it's not strictly necessary to split out + # extends and appends, but it helps with + # debugging to do so! + if expr.attr == 'extend': + extends.append(x.target.name) + elif expr.attr == 'append': + appends.append(x.target.name) + else: + assert 0 + # go back through the peep hole build new IR based on it. + new_hole = [] + + def append_and_fix(x): + """ Adds to the new_hole and fixes up definitions""" + new_hole.append(x) + if x.target.name in func_ir._definitions: + # if there's already a definition, drop it, should only + # be 1 as the way cpython emits the sequence for + # `list_to_tuple` should ensure this. + assert len(func_ir._definitions[x.target.name]) == 1 + func_ir._definitions[x.target.name].clear() + func_ir._definitions[x.target.name].append(x.value) + + the_build_list = init.target + + # Do the transform on the peep hole + if _DEBUG: + print("\nBLOCK:") + blk.dump() + + # This section basically accumulates list appends and extends + # as binop(+) on tuples, it drops all the getattr() for extend + # and append as they are now dead and replaced with binop(+). + # It also switches out the build_list for a build_tuple and then + # ensures everything is wired up and defined ok. + t2l_agn = region[0][1] + acc = the_build_list + for x in peep_hole: + if isinstance(x, ir.Assign): + if isinstance(x.value, ir.Expr): + expr = x.value + if expr.op == 'getattr': + if (x.target.name in extends or + x.target.name in appends): + # drop definition, it's being wholesale + # replaced. + func_ir._definitions.pop(x.target.name) + continue + else: + # a getattr on something we're not + # interested in + new_hole.append(x) + elif expr.op == 'call': + fname = expr.func.name + if fname in extends or fname in appends: + arg = expr.args[0] + if isinstance(arg, ir.Var): + tmp_name = "%s_var_%s" % (fname, + arg.name) + if fname in appends: + bt = ir.Expr.build_tuple([arg,], + expr.loc) + else: + # Extend as tuple + gv_tuple = ir.Global( + name="tuple", value=tuple, + loc=expr.loc, + ) + tuple_var = arg.scope.redefine( + "$_list_extend_gv_tuple", + loc=expr.loc, + ) + new_hole.append( + ir.Assign( + target=tuple_var, + value=gv_tuple, + loc=expr.loc, + ), + ) + bt = ir.Expr.call( + tuple_var, (arg,), (), + loc=expr.loc, + ) + var = ir.Var(arg.scope, tmp_name, + expr.loc) + asgn = ir.Assign(bt, var, expr.loc) + append_and_fix(asgn) + arg = var + + # this needs to be a binary add + new = ir.Expr.binop(fn=operator.add, + lhs=acc, + rhs=arg, + loc=x.loc) + asgn = ir.Assign(new, x.target, expr.loc) + append_and_fix(asgn) + acc = asgn.target + else: + # there could be a call in the unpack, like + # *(a, x.append(y)) + new_hole.append(x) + elif (expr.op == 'build_list' and + x.target.name == const_list): + new = ir.Expr.build_tuple(expr.items, expr.loc) + asgn = ir.Assign(new, x.target, expr.loc) + # Not a temporary any more + append_and_fix(asgn) + else: + new_hole.append(x) + else: + new_hole.append(x) + + else: + # stick everything else in as-is + new_hole.append(x) + # Finally write the result back into the original build list as + # everything refers to it. + append_and_fix(ir.Assign(acc, t2l_agn.target, + the_build_list.loc)) + if _DEBUG: + print("\nNEW HOLE:") + for x in new_hole: + print(x) + + # and then update the block body with the modified region + cpy = blk.body[:] + head = cpy[:region[1][0]] + tail = blk.body[region[0][0] + 1:] + tmp = head + new_hole + tail + blk.body.clear() + blk.body.extend(tmp) + + if _DEBUG: + print("\nDUMP post hole:") + blk.dump() + + else: + # else escape + break + + return func_ir + + +def peep_hole_delete_with_exit(func_ir): + """ + This rewrite removes variables used to store the `__exit__` function + loaded by SETUP_WITH. + """ + dead_vars = set() + + for blk in func_ir.blocks.values(): + for stmt in blk.body: + # Any statement that uses a variable with the '$setup_with_exitfn' + # prefix is considered dead. + used = set(stmt.list_vars()) + for v in used: + if v.name.startswith('$setup_with_exitfn'): + dead_vars.add(v) + # Any assignment that uses any of the dead variable is considered + # dead. + if used & dead_vars: + if isinstance(stmt, ir.Assign): + dead_vars.add(stmt.target) + + new_body = [] + for stmt in blk.body: + # Skip any statements that uses anyone of the dead variable. + if not (set(stmt.list_vars()) & dead_vars): + new_body.append(stmt) + blk.body.clear() + blk.body.extend(new_body) + + return func_ir + + +def peep_hole_fuse_dict_add_updates(func_ir): + """ + This rewrite removes d1._update_from_bytecode(d2) + calls that are between two dictionaries, d1 and d2, + in the same basic block. This pattern can appear as a + result of Python 3.10 bytecode emission changes, which + prevent large constant literal dictionaries + (> 15 elements) from being constant. If both dictionaries + are constant dictionaries defined in the same block and + neither is used between the update call, then we replace d1 + with a new definition that combines the two dictionaries. At + the bytecode translation stage we convert DICT_UPDATE into + _update_from_bytecode, so we know that _update_from_bytecode + always comes from the bytecode change and not user code. + + Python 3.10 may also rewrite the individual dictionaries + as an empty build_map + many map_add. Here we again look + for an _update_from_bytecode, and if so we replace these + with a single constant dictionary. + + When running this algorithm we can always safely remove d2. + + This is the relevant section of the CPython 3.10 that causes + this bytecode change: + https://github.com/python/cpython/blob/3.10/Python/compile.c#L4048 + """ + + # This algorithm fuses build_map expressions into the largest + # possible build map before use. For example, if we have an + # IR that looks like this: + # + # $d1 = build_map([]) + # $key = const("a") + # $value = const(2) + # $setitem_func = getattr($d1, "__setitem__") + # $unused1 = call (setitem_func, ($key, $value)) + # $key2 = const("b") + # $value2 = const(3) + # $d2 = build_map([($key2, $value2)]) + # $update_func = getattr($d1, "_update_from_bytecode") + # $unused2 = call ($update_func, ($d2,)) + # $othervar = None + # $retvar = cast($othervar) + # return $retvar + # + # Then the IR is rewritten such that any __setitem__ and + # _update_from_bytecode operations are fused into the original buildmap. + # The new buildmap is then added to the + # last location where it had previously had encountered a __setitem__, + # _update_from_bytecode, or build_map before any other uses. + # The new IR would look like: + # + # $key = const("a") + # $value = const(2) + # $key2 = const("b") + # $value2 = const(3) + # $d1 = build_map([($key, $value), ($key2, $value2)]) + # $othervar = None + # $retvar = cast($othervar) + # return $retvar + # + # Note that we don't push $d1 to the bottom of the block. This is because + # some values may be found below this block (e.g pop_block) that are pattern + # matched in other locations, such as objmode handling. It should be safe to + # move a map to the last location at which there was _update_from_bytecode. + + errmsg = textwrap.dedent(""" + A DICT_UPDATE op-code was encountered that could not be replaced. + If you have created a large constant dictionary, this may + be an an indication that you are using inlined control + flow. You can resolve this issue by moving the control flow out of + the dicitonary constructor. For example, if you have + + d = {a: 1 if flag else 0, ...) + + Replace that with: + + a_val = 1 if flag else 0 + d = {a: a_val, ...)""") + + already_deleted_defs = collections.defaultdict(set) + for blk in func_ir.blocks.values(): + new_body = [] + # literal map var name -> block idx of the original build_map + lit_map_def_idx = {} + # literal map var name -> list(map_uses) + # This is the index of every build_map or __setitem__ + # in the IR that will need to be removed if the map + # is updated. + lit_map_use_idx = collections.defaultdict(list) + # literal map var name -> list of key/value items for build map + map_updates = {} + blk_changed = False + + for i, stmt in enumerate(blk.body): + # What instruction should we append + new_inst = stmt + # Name that should be skipped when tracking used + # vars in statement. This is always the lhs with + # a build_map. + stmt_build_map_out = None + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + if stmt.value.op == "build_map": + # Skip the output build_map when looking for used vars. + stmt_build_map_out = stmt.target.name + # If we encounter a build map add it to the + # tracked maps. + lit_map_def_idx[stmt.target.name] = i + lit_map_use_idx[stmt.target.name].append(i) + map_updates[stmt.target.name] = stmt.value.items.copy() + elif stmt.value.op == "call" and i > 0: + # If we encounter a call we may need to replace + # the body + func_name = stmt.value.func.name + # If we have an update or a setitem + # it will be the previous expression. + getattr_stmt = blk.body[i - 1] + args = stmt.value.args + if ( + isinstance(getattr_stmt, ir.Assign) + and getattr_stmt.target.name == func_name + and isinstance(getattr_stmt.value, ir.Expr) + and getattr_stmt.value.op == "getattr" + and getattr_stmt.value.attr in ( + "__setitem__", "_update_from_bytecode" + ) + ): + update_map_name = getattr_stmt.value.value.name + attr = getattr_stmt.value.attr + if (attr == "__setitem__" + and update_map_name in lit_map_use_idx): + # If we have a setitem, update the lists + map_updates[update_map_name].append(args) + # Update the list of instructions that would + # need to be removed to include the setitem + # and the getattr + lit_map_use_idx[update_map_name].extend([i - 1, i]) + elif attr == "_update_from_bytecode": + d2_map_name = args[0].name + if (update_map_name in lit_map_use_idx + and d2_map_name in lit_map_use_idx): + # If we have an update and the arg is also + # a literal dictionary, fuse the lists. + map_updates[update_map_name].extend( + map_updates[d2_map_name] + ) + # Delete the old IR for d1 and d2 + lit_map_use_idx[update_map_name].extend( + lit_map_use_idx[d2_map_name] + ) + lit_map_use_idx[update_map_name].append(i - 1) + for linenum in lit_map_use_idx[update_map_name]: + # Drop the existing definition. + _remove_assignment_definition( + blk.body, + linenum, + func_ir, + already_deleted_defs, + ) + # Delete it from the new block + new_body[linenum] = None + # Delete the maps from dicts + del lit_map_def_idx[d2_map_name] + del lit_map_use_idx[d2_map_name] + del map_updates[d2_map_name] + # Add d1 as the new instruction, removing the + # old definition. + _remove_assignment_definition( + blk.body, i, func_ir, already_deleted_defs + ) + new_inst = _build_new_build_map( + func_ir, + update_map_name, + blk.body, + lit_map_def_idx[update_map_name], + map_updates[update_map_name], + ) + # Update d1 in lit_map_use_idx to just the new + # definition and clear the previous list. + lit_map_use_idx[update_map_name].clear() + lit_map_use_idx[update_map_name].append(i) + # Mark that this block has been modified + blk_changed = True + else: + # If we cannot remove _update_from_bytecode + # Then raise an error for the user. + raise UnsupportedBytecodeError(errmsg) + + # Check if we need to drop any maps from being tracked. + # Skip the setitem/_update_from_bytecode getattr that + # will be removed when handling their call in the next + # iteration. + if not ( + isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == "getattr" + and stmt.value.value.name in lit_map_use_idx + and stmt.value.attr in ("__setitem__", "_update_from_bytecode") + ): + for var in stmt.list_vars(): + # If a map is used it cannot be fused later in + # the block. As a result we delete it from + # the dicitonaries + if ( + var.name in lit_map_use_idx + and var.name != stmt_build_map_out + ): + del lit_map_def_idx[var.name] + del lit_map_use_idx[var.name] + del map_updates[var.name] + + # Append the instruction to the new block + new_body.append(new_inst) + + if blk_changed: + # If the block is changed replace the block body. + blk.body.clear() + blk.body.extend([x for x in new_body if x is not None]) + + return func_ir + + +def peep_hole_split_at_pop_block(func_ir): + """ + Split blocks that contain ir.PopBlock. + + This rewrite restores the IR structure to pre 3.11 so that withlifting + can work correctly. + """ + new_block_map = {} + sorted_blocks = sorted(func_ir.blocks.items()) + for blk_idx, (label, blk) in enumerate(sorted_blocks): + # Gather locations of PopBlock + pop_block_locs = [] + for i, inst in enumerate(blk.body): + if isinstance(inst, ir.PopBlock): + pop_block_locs.append(i) + # Rewrite block with PopBlock + if pop_block_locs: + new_blocks = [] + for i in pop_block_locs: + before_blk = ir.Block(blk.scope, loc=blk.loc) + before_blk.body.extend(blk.body[:i]) + new_blocks.append(before_blk) + + popblk_blk = ir.Block(blk.scope, loc=blk.loc) + popblk_blk.body.append(blk.body[i]) + new_blocks.append(popblk_blk) + # Add jump instructions + prev_label = label + for newblk in new_blocks: + new_block_map[prev_label] = newblk + next_label = prev_label + 1 + newblk.body.append(ir.Jump(next_label, loc=blk.loc)) + prev_label = next_label + # Check prev_label does not exceed current new block label + if blk_idx + 1 < len(sorted_blocks): + if prev_label >= sorted_blocks[blk_idx + 1][0]: + # Panic! Due to heuristic in with-lifting, block labels + # must be monotonically increasing. We cannot continue if we + # run out of usable label between the two blocks. + raise errors.InternalError("POP_BLOCK peephole failed") + # Add tail block, which will get the original terminator + tail_blk = ir.Block(blk.scope, loc=blk.loc) + tail_blk.body.extend(blk.body[pop_block_locs[-1] + 1:]) + new_block_map[prev_label] = tail_blk + + func_ir.blocks.update(new_block_map) + return func_ir + + +def _build_new_build_map(func_ir, name, old_body, old_lineno, new_items): + """ + Create a new build_map with a new set of key/value items + but all the other info the same. + """ + old_assign = old_body[old_lineno] + old_target = old_assign.target + old_bm = old_assign.value + # Build the literals + literal_keys = [] + # Track the constant key/values to set the literal_value + # field of build_map properly + values = [] + for pair in new_items: + k, v = pair + key_def = guard(get_definition, func_ir, k) + if isinstance(key_def, (ir.Const, ir.Global, ir.FreeVar)): + literal_keys.append(key_def.value) + value_def = guard(get_definition, func_ir, v) + if isinstance(value_def, (ir.Const, ir.Global, ir.FreeVar)): + values.append(value_def.value) + else: + # Append unknown value if not a literal. + values.append(_UNKNOWN_VALUE(v.name)) + + value_indexes = {} + if len(literal_keys) == len(new_items): + # All keys must be literals to have any literal values. + literal_value = {x: y for x, y in zip(literal_keys, values)} + for i, k in enumerate(literal_keys): + value_indexes[k] = i + else: + literal_value = None + + # Construct a new build map. + new_bm = ir.Expr.build_map( + items=new_items, + size=len(new_items), + literal_value=literal_value, + value_indexes=value_indexes, + loc=old_bm.loc, + ) + + # The previous definition has already been removed + # when updating the IR in peep_hole_fuse_dict_add_updates + func_ir._definitions[name].append(new_bm) + + # Return a new assign. + return ir.Assign( + new_bm, ir.Var(old_target.scope, name, old_target.loc), new_bm.loc + ) + + +class Interpreter(object): + """A bytecode interpreter that builds up the IR. + """ + + _DEBUG_PRINT = False + + def __init__(self, func_id): + self.func_id = func_id + if self._DEBUG_PRINT: + print(func_id.func) + self.arg_count = func_id.arg_count + self.arg_names = func_id.arg_names + self.loc = self.first_loc = ir.Loc.from_function_id(func_id) + self.is_generator = func_id.is_generator + + # { inst offset : ir.Block } + self.blocks = {} + # { name: [definitions] } of local variables + self.definitions = collections.defaultdict(list) + # A set to keep track of all exception variables. + # To be used in _legalize_exception_vars() + self._exception_vars = set() + + def interpret(self, bytecode): + """ + Generate IR for this bytecode. + """ + self.bytecode = bytecode + + self.scopes = [] + global_scope = ir.Scope(parent=None, loc=self.loc) + self.scopes.append(global_scope) + + flow = Flow(bytecode) + flow.run() + self.dfa = AdaptDFA(flow) + self.cfa = AdaptCFA(flow) + if config.DUMP_CFG: + self.cfa.dump() + + # Temp states during interpretation + self.current_block = None + self.current_block_offset = None + last_active_offset = 0 + for _, inst_blocks in self.cfa.blocks.items(): + if inst_blocks.body: + last_active_offset = max(last_active_offset, + max(inst_blocks.body)) + self.last_active_offset = last_active_offset + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + self.active_exception_entries = tuple( + [entry for entry in self.bytecode.exception_entries + if entry.start < self.last_active_offset]) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + self.syntax_blocks = [] + self.dfainfo = None + + self.scopes.append(ir.Scope(parent=self.current_scope, loc=self.loc)) + + # Interpret loop + for inst, kws in self._iter_inst(): + self._dispatch(inst, kws) + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + # Insert end of try markers + self._end_try_blocks() + elif PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(PYVERSION) + self._legalize_exception_vars() + # Prepare FunctionIR + func_ir = ir.FunctionIR(self.blocks, self.is_generator, self.func_id, + self.first_loc, self.definitions, + self.arg_count, self.arg_names) + _logger.debug(_lazy_pformat(func_ir, + lazy_func=lambda x: x.dump_to_string())) + + # post process the IR to rewrite opcodes/byte sequences that are too + # involved to risk handling as part of direct interpretation + peepholes = [] + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + peepholes.append(peep_hole_split_at_pop_block) + if PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13), (3, 14)): + peepholes.append(peep_hole_list_to_tuple) + peepholes.append(peep_hole_delete_with_exit) + if PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13), (3, 14)): + # peep_hole_call_function_ex_to_call_function_kw + # depends on peep_hole_list_to_tuple converting + # any large number of arguments from a list to a + # tuple. + peepholes.append(peep_hole_call_function_ex_to_call_function_kw) + peepholes.append(peep_hole_fuse_dict_add_updates) + + post_processed_ir = self.post_process(peepholes, func_ir) + + return post_processed_ir + + def post_process(self, peepholes, func_ir): + for peep in peepholes: + func_ir = peep(func_ir) + return func_ir + + def _end_try_blocks(self): + """Closes all try blocks by inserting the required marker at the + exception handler + + This is only needed for py3.11 because of the changes in exception + handling. This merely maps the new py3.11 semantics back to the old way. + + What the code does: + + - For each block, compute the difference of blockstack to its incoming + blocks' blockstack. + - If the incoming blockstack has an extra TRY, the current block must + be the EXCEPT block and we need to insert a marker. + + See also: _insert_try_block_end + """ + assert PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)) + graph = self.cfa.graph + for offset, block in self.blocks.items(): + # Get current blockstack + cur_bs = self.dfa.infos[offset].blockstack + # Check blockstack of the incoming blocks + for inc, _ in graph.predecessors(offset): + inc_bs = self.dfa.infos[inc].blockstack + + # find first diff in the blockstack + for i, (x, y) in enumerate(zip(cur_bs, inc_bs)): + if x != y: + break + else: + i = min(len(cur_bs), len(inc_bs)) + + def do_change(remain): + while remain: + ent = remain.pop() + if ent['kind'] == BlockKind('TRY'): + # Extend block with marker for end of try + self.current_block = block + oldbody = list(block.body) + block.body.clear() + self._insert_try_block_end() + block.body.extend(oldbody) + return True + + if do_change(list(inc_bs[i:])): + break + + def _legalize_exception_vars(self): + """Search for unsupported use of exception variables. + Note, they cannot be stored into user variable. + """ + # Build a set of exception variables + excvars = self._exception_vars.copy() + # Propagate the exception variables to LHS of assignment + for varname, defnvars in self.definitions.items(): + for v in defnvars: + if isinstance(v, ir.Var): + k = v.name + if k in excvars: + excvars.add(varname) + # Filter out the user variables. + uservar = list(filter(lambda x: not x.startswith('$'), excvars)) + if uservar: + # Complain about the first user-variable storing an exception + first = uservar[0] + loc = self.current_scope.get(first).loc + msg = "Exception object cannot be stored into variable ({})." + raise errors.UnsupportedBytecodeError(msg.format(first), loc=loc) + + def init_first_block(self): + # Define variables receiving the function arguments + for index, name in enumerate(self.arg_names): + val = ir.Arg(index=index, name=name, loc=self.loc) + self.store(val, name) + + def _iter_inst(self): + for blkct, block in enumerate(self.cfa.iterliveblocks()): + firstinst = self.bytecode[block.offset] + # If its an END_FOR instruction, the start location of block + # is set to start of the FOR loop, so take the location of + # next instruction. This only affects the source location + # marking and has no impact to semantic. + if firstinst.opname == 'END_FOR': + firstinst = self.bytecode[firstinst.next] + self.loc = self.loc.with_lineno(firstinst.lineno) + self._start_new_block(block.offset) + if blkct == 0: + # Is first block + self.init_first_block() + for offset, kws in self.dfainfo.insts: + inst = self.bytecode[offset] + self.loc = self.loc.with_lineno(inst.lineno) + yield inst, kws + self._end_current_block() + + def _start_new_block(self, offset): + oldblock = self.current_block + self.insert_block(offset) + + tryblk = self.dfainfo.active_try_block if self.dfainfo else None + # Ensure the last block is terminated + if oldblock is not None and not oldblock.is_terminated: + # Handle ending try block. + # If there's an active try-block and the handler block is live. + if tryblk is not None and tryblk['end'] in self.cfa.graph.nodes(): + # We are in a try-block, insert a branch to except-block. + # This logic cannot be in self._end_current_block() + # because we don't know the non-raising next block-offset. + branch = ir.Branch( + cond=self.get('$exception_check'), + truebr=tryblk['end'], + falsebr=offset, + loc=self.loc, + ) + oldblock.append(branch) + # Handle normal case + else: + jmp = ir.Jump(offset, loc=self.loc) + oldblock.append(jmp) + + # Get DFA block info + self.dfainfo = self.dfa.infos[self.current_block_offset] + self.assigner = Assigner() + # Check out-of-scope syntactic-block + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + # This is recreating pre-3.11 code structure + while self.syntax_blocks: + if offset >= self.syntax_blocks[-1].exit: + synblk = self.syntax_blocks.pop() + if isinstance(synblk, ir.With): + self.current_block.append(ir.PopBlock(self.loc)) + else: + break + # inject try block: + newtryblk = self.dfainfo.active_try_block + if newtryblk is not None: + if newtryblk is not tryblk: + self._insert_try_block_begin() + elif PYVERSION in ((3, 10),): + while self.syntax_blocks: + if offset >= self.syntax_blocks[-1].exit: + self.syntax_blocks.pop() + else: + break + else: + raise NotImplementedError(PYVERSION) + + def _end_current_block(self): + # Handle try block + if not self.current_block.is_terminated: + tryblk = self.dfainfo.active_try_block + if tryblk is not None: + self._insert_exception_check() + # Handle normal block cleanup + self._remove_unused_temporaries() + self._insert_outgoing_phis() + + def _inject_call(self, func, gv_name, res_name=None): + """A helper function to inject a call to *func* which is a python + function. + Parameters + ---------- + func : callable + The function object to be called. + gv_name : str + The variable name to be used to store the function object. + res_name : str; optional + The variable name to be used to store the call result. + If ``None``, a name is created automatically. + """ + gv_fn = ir.Global(gv_name, func, loc=self.loc) + self.store(value=gv_fn, name=gv_name, redefine=True) + callres = ir.Expr.call(self.get(gv_name), (), (), loc=self.loc) + res_name = res_name or '$callres_{}'.format(gv_name) + self.store(value=callres, name=res_name, redefine=True) + + def _insert_try_block_begin(self): + """Insert IR-nodes to mark the start of a `try` block. + """ + self._inject_call(eh.mark_try_block, 'mark_try_block') + + def _insert_try_block_end(self): + """Insert IR-nodes to mark the end of a `try` block. + """ + self._inject_call(eh.end_try_block, 'end_try_block') + + def _insert_exception_variables(self): + """Insert IR-nodes to initialize the exception variables. + """ + tryblk = self.dfainfo.active_try_block + # Get exception variables + endblk = tryblk['end'] + edgepushed = self.dfainfo.outgoing_edgepushed.get(endblk) + # Note: the last value on the stack is the exception value + # Note: due to the current limitation, all exception variables are None + if edgepushed: + const_none = ir.Const(value=None, loc=self.loc) + # For each variable going to the handler block. + for var in edgepushed: + if var in self.definitions: + raise AssertionError( + "exception variable CANNOT be defined by other code", + ) + self.store(value=const_none, name=var) + self._exception_vars.add(var) + + def _insert_exception_check(self): + """Called before the end of a block to inject checks if raised. + """ + self._insert_exception_variables() + # Do exception check + self._inject_call(eh.exception_check, 'exception_check', + '$exception_check') + + def _remove_unused_temporaries(self): + """ + Remove assignments to unused temporary variables from the + current block. + """ + new_body = [] + replaced_var = {} + for inst in self.current_block.body: + # the same temporary is assigned to multiple variables in cases + # like a = b[i] = 1, so need to handle replaced temporaries in + # later setitem/setattr nodes + if (isinstance(inst, (ir.SetItem, ir.SetAttr)) + and inst.value.name in replaced_var): + inst.value = replaced_var[inst.value.name] + elif isinstance(inst, ir.Assign): + if (inst.target.is_temp + and inst.target.name in self.assigner.unused_dests): + continue + # the same temporary is assigned to multiple variables in cases + # like a = b = 1, so need to handle replaced temporaries in + # later assignments + if (isinstance(inst.value, ir.Var) + and inst.value.name in replaced_var): + inst.value = replaced_var[inst.value.name] + new_body.append(inst) + continue + # chained unpack cases may reuse temporary + # e.g. a = (b, c) = (x, y) + if (isinstance(inst.value, ir.Expr) + and inst.value.op == "exhaust_iter" + and inst.value.value.name in replaced_var): + inst.value.value = replaced_var[inst.value.value.name] + new_body.append(inst) + continue + # eliminate temporary variables that are assigned to user + # variables right after creation. E.g.: + # $1 = f(); a = $1 -> a = f() + # the temporary variable is not reused elsewhere since CPython + # bytecode is stack-based and this pattern corresponds to a pop + if (isinstance(inst.value, ir.Var) and inst.value.is_temp + and new_body and isinstance(new_body[-1], ir.Assign)): + prev_assign = new_body[-1] + # _var_used_in_binop check makes sure we don't create a new + # inplace binop operation which can fail + # (see TestFunctionType.test_in_iter_func_call) + if (prev_assign.target.name == inst.value.name + and not self._var_used_in_binop( + inst.target.name, prev_assign.value)): + replaced_var[inst.value.name] = inst.target + prev_assign.target = inst.target + # replace temp var definition in target with proper defs + self.definitions[inst.target.name].remove(inst.value) + self.definitions[inst.target.name].extend( + self.definitions.pop(inst.value.name) + ) + continue + + new_body.append(inst) + + self.current_block.body = new_body + + def _var_used_in_binop(self, varname, expr): + """return True if 'expr' is a binary expression and 'varname' is used + in it as an argument + """ + return (isinstance(expr, ir.Expr) + and expr.op in ("binop", "inplace_binop") + and (varname == expr.lhs.name or varname == expr.rhs.name)) + + def _insert_outgoing_phis(self): + """ + Add assignments to forward requested outgoing values + to subsequent blocks. + """ + for phiname, varname in self.dfainfo.outgoing_phis.items(): + target = self.current_scope.get_or_define(phiname, + loc=self.loc) + try: + val = self.get(varname) + except ir.NotDefinedError: + # Hack to make sure exception variables are defined + assert PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)), \ + "unexpected missing definition" + val = ir.Const(value=None, loc=self.loc) + stmt = ir.Assign(value=val, target=target, + loc=self.loc) + self.definitions[target.name].append(stmt.value) + if not self.current_block.is_terminated: + self.current_block.append(stmt) + else: + self.current_block.insert_before_terminator(stmt) + + def get_global_value(self, name): + """ + Get a global value from the func_global (first) or + as a builtins (second). If both failed, return a ir.UNDEFINED. + """ + try: + return self.func_id.func.__globals__[name] + except KeyError: + return getattr(builtins, name, ir.UNDEFINED) + + def get_closure_value(self, index): + """ + Get a value from the cell contained in this function's closure. + If not set, return a ir.UNDEFINED. + """ + cell = self.func_id.func.__closure__[index] + try: + return cell.cell_contents + except ValueError: + return ir.UNDEFINED + + @property + def current_scope(self): + return self.scopes[-1] + + @property + def code_consts(self): + return self.bytecode.co_consts + + @property + def code_locals(self): + return self.bytecode.co_varnames + + @property + def code_names(self): + return self.bytecode.co_names + + @property + def code_cellvars(self): + return self.bytecode.co_cellvars + + @property + def code_freevars(self): + return self.bytecode.co_freevars + + def _dispatch(self, inst, kws): + if self._DEBUG_PRINT: + print(inst) + assert self.current_block is not None + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + if self.syntax_blocks: + top = self.syntax_blocks[-1] + if isinstance(top, ir.With) : + if inst.offset >= top.exit: + self.current_block.append(ir.PopBlock(loc=self.loc)) + self.syntax_blocks.pop() + elif PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(PYVERSION) + + fname = "op_%s" % inst.opname.replace('+', '_') + try: + fn = getattr(self, fname) + except AttributeError: + raise NotImplementedError(inst) + else: + try: + return fn(inst, **kws) + except errors.NotDefinedError as e: + if e.loc is None: + loc = self.loc + else: + loc = e.loc + + err = errors.NotDefinedError(e.name, loc=loc) + if not config.FULL_TRACEBACKS: + raise err from None + else: + m = f"handling op: {inst} | offset: {inst.offset}" + err.add_context(m) + err.add_context(self.bytecode.dump()) + raise err + + # --- Scope operations --- + + def store(self, value, name, redefine=False): + """ + Store *value* (a Expr or Var instance) into the variable named *name* + (a str object). Returns the target variable. + """ + if redefine or self.current_block_offset in self.cfa.backbone: + rename = not (name in self.code_cellvars) + target = self.current_scope.redefine(name, loc=self.loc, + rename=rename) + else: + target = self.current_scope.get_or_define(name, loc=self.loc) + if isinstance(value, ir.Var): + value = self.assigner.assign(value, target) + stmt = ir.Assign(value=value, target=target, loc=self.loc) + self.current_block.append(stmt) + self.definitions[target.name].append(value) + return target + + def get(self, name): + """ + Get the variable (a Var instance) with the given *name*. + """ + # Implicit argument for comprehension starts with '.' + # See Parameter class in inspect.py (from Python source) + if name[0] == '.' and name[1:].isdigit(): + name = 'implicit{}'.format(name[1:]) + + # Try to simplify the variable lookup by returning an earlier + # variable assigned to *name*. + var = self.assigner.get_assignment_source(name) + if var is None: + var = self.current_scope.get(name) + return var + + # --- Block operations --- + + def insert_block(self, offset, scope=None, loc=None): + scope = scope or self.current_scope + loc = loc or self.loc + blk = ir.Block(scope=scope, loc=loc) + self.blocks[offset] = blk + self.current_block = blk + self.current_block_offset = offset + return blk + + # --- Bytecode handlers --- + + def op_NOP(self, inst): + pass + + if PYVERSION in ((3, 14), ): + # New in 3.14 + op_NOT_TAKEN = op_NOP + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_RESUME(self, inst): + pass + + def op_CACHE(self, inst): + pass + + def op_PRECALL(self, inst): + pass + + def op_PUSH_NULL(self, inst): + pass + + def op_RETURN_GENERATOR(self, inst): + pass + + def op_PRINT_ITEM(self, inst, item, printvar, res): + item = self.get(item) + printgv = ir.Global("print", print, loc=self.loc) + self.store(value=printgv, name=printvar) + call = ir.Expr.call(self.get(printvar), (item,), (), loc=self.loc) + self.store(value=call, name=res) + + def op_PRINT_NEWLINE(self, inst, printvar, res): + printgv = ir.Global("print", print, loc=self.loc) + self.store(value=printgv, name=printvar) + call = ir.Expr.call(self.get(printvar), (), (), loc=self.loc) + self.store(value=call, name=res) + + def op_UNPACK_SEQUENCE(self, inst, iterable, stores, tupleobj): + count = len(stores) + # Exhaust the iterable into a tuple-like object + tup = ir.Expr.exhaust_iter(value=self.get(iterable), loc=self.loc, + count=count) + self.store(name=tupleobj, value=tup) + + # then index the tuple-like object to extract the values + for i, st in enumerate(stores): + expr = ir.Expr.static_getitem(self.get(tupleobj), + index=i, index_var=None, + loc=self.loc) + self.store(expr, st) + + def op_FORMAT_SIMPLE(self, inst, value, res, strvar): + # Same as FORMAT_VALUE + return self.op_FORMAT_VALUE(inst, value, res, strvar) + + def op_FORMAT_VALUE(self, inst, value, res, strvar): + """ + FORMAT_VALUE(flags): flags argument specifies format spec which is not + supported yet. Currently, str() is simply called on the value. + https://docs.python.org/3/library/dis.html#opcode-FORMAT_VALUE + """ + value = self.get(value) + strgv = ir.Global("str", str, loc=self.loc) + self.store(value=strgv, name=strvar) + call = ir.Expr.call(self.get(strvar), (value,), (), loc=self.loc) + self.store(value=call, name=res) + + def op_BUILD_STRING(self, inst, strings, tmps): + """ + BUILD_STRING(count): Concatenates count strings. + Required for supporting f-strings. + https://docs.python.org/3/library/dis.html#opcode-BUILD_STRING + """ + count = inst.arg + # corner case: f"" + if count == 0: + const = ir.Const("", loc=self.loc) + self.store(const, tmps[-1]) + return + + prev = self.get(strings[0]) + for other, tmp in zip(strings[1:], tmps): + other = self.get(other) + expr = ir.Expr.binop( + operator.add, lhs=prev, rhs=other, loc=self.loc + ) + self.store(expr, tmp) + prev = self.get(tmp) + + def op_BUILD_SLICE(self, inst, start, stop, step, res, slicevar): + start = self.get(start) + stop = self.get(stop) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + if step is None: + sliceinst = ir.Expr.call(self.get(slicevar), (start, stop), (), + loc=self.loc) + else: + step = self.get(step) + sliceinst = ir.Expr.call(self.get(slicevar), (start, stop, step), + (), loc=self.loc) + self.store(value=sliceinst, name=res) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_BINARY_SLICE(self, inst, start, end, container, res, slicevar, + temp_res): + start = self.get(start) + end = self.get(end) + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + sliceinst = ir.Expr.call(self.get(slicevar), (start, end), (), + loc=self.loc) + self.store(value=sliceinst, name=temp_res) + index = self.get(temp_res) + target = self.get(container) + expr = ir.Expr.getitem(target, index=index, loc=self.loc) + self.store(expr, res) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_STORE_SLICE(self, inst, start, end, container, value, res, + slicevar): + start = self.get(start) + end = self.get(end) + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + sliceinst = ir.Expr.call(self.get(slicevar), (start, end), (), + loc=self.loc) + self.store(value=sliceinst, name=res) + index = self.get(res) + target = self.get(container) + value = self.get(value) + + stmt = ir.SetItem(target=target, index=index, value=value, + loc=self.loc) + self.current_block.append(stmt) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_SLICE_0(self, inst, base, res, slicevar, indexvar, nonevar): + base = self.get(base) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + index = ir.Expr.call(self.get(slicevar), (none, none), (), loc=self.loc) + self.store(value=index, name=indexvar) + + expr = ir.Expr.getitem(base, self.get(indexvar), loc=self.loc) + self.store(value=expr, name=res) + + def op_SLICE_1(self, inst, base, start, nonevar, res, slicevar, indexvar): + base = self.get(base) + start = self.get(start) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, none), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + expr = ir.Expr.getitem(base, self.get(indexvar), loc=self.loc) + self.store(value=expr, name=res) + + def op_SLICE_2(self, inst, base, nonevar, stop, res, slicevar, indexvar): + base = self.get(base) + stop = self.get(stop) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (none, stop,), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + expr = ir.Expr.getitem(base, self.get(indexvar), loc=self.loc) + self.store(value=expr, name=res) + + def op_SLICE_3(self, inst, base, start, stop, res, slicevar, indexvar): + base = self.get(base) + start = self.get(start) + stop = self.get(stop) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, stop), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + expr = ir.Expr.getitem(base, self.get(indexvar), loc=self.loc) + self.store(value=expr, name=res) + + def op_STORE_SLICE_0(self, inst, base, value, slicevar, indexvar, nonevar): + base = self.get(base) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + index = ir.Expr.call(self.get(slicevar), (none, none), (), loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.SetItem(base, self.get(indexvar), self.get(value), + loc=self.loc) + self.current_block.append(stmt) + + def op_STORE_SLICE_1(self, inst, base, start, nonevar, value, slicevar, + indexvar): + base = self.get(base) + start = self.get(start) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, none), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.SetItem(base, self.get(indexvar), self.get(value), + loc=self.loc) + self.current_block.append(stmt) + + def op_STORE_SLICE_2(self, inst, base, nonevar, stop, value, slicevar, + indexvar): + base = self.get(base) + stop = self.get(stop) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (none, stop,), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.SetItem(base, self.get(indexvar), self.get(value), + loc=self.loc) + self.current_block.append(stmt) + + def op_STORE_SLICE_3(self, inst, base, start, stop, value, slicevar, + indexvar): + base = self.get(base) + start = self.get(start) + stop = self.get(stop) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, stop), (), + loc=self.loc) + self.store(value=index, name=indexvar) + stmt = ir.SetItem(base, self.get(indexvar), self.get(value), + loc=self.loc) + self.current_block.append(stmt) + + def op_DELETE_SLICE_0(self, inst, base, slicevar, indexvar, nonevar): + base = self.get(base) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + index = ir.Expr.call(self.get(slicevar), (none, none), (), loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.DelItem(base, self.get(indexvar), loc=self.loc) + self.current_block.append(stmt) + + def op_DELETE_SLICE_1(self, inst, base, start, nonevar, slicevar, indexvar): + base = self.get(base) + start = self.get(start) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, none), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.DelItem(base, self.get(indexvar), loc=self.loc) + self.current_block.append(stmt) + + def op_DELETE_SLICE_2(self, inst, base, nonevar, stop, slicevar, indexvar): + base = self.get(base) + stop = self.get(stop) + + nonegv = ir.Const(None, loc=self.loc) + self.store(value=nonegv, name=nonevar) + none = self.get(nonevar) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (none, stop,), (), + loc=self.loc) + self.store(value=index, name=indexvar) + + stmt = ir.DelItem(base, self.get(indexvar), loc=self.loc) + self.current_block.append(stmt) + + def op_DELETE_SLICE_3(self, inst, base, start, stop, slicevar, indexvar): + base = self.get(base) + start = self.get(start) + stop = self.get(stop) + + slicegv = ir.Global("slice", slice, loc=self.loc) + self.store(value=slicegv, name=slicevar) + + index = ir.Expr.call(self.get(slicevar), (start, stop), (), + loc=self.loc) + self.store(value=index, name=indexvar) + stmt = ir.DelItem(base, self.get(indexvar), loc=self.loc) + self.current_block.append(stmt) + + def _op_LOAD_FAST(self, inst, res): + srcname = self.code_locals[inst.arg] + self.store(value=self.get(srcname), name=res) + + if PYVERSION in ((3, 13), (3, 14)): + def op_LOAD_FAST(self, inst, res, as_load_deref=False): + if as_load_deref: + self.op_LOAD_DEREF(inst, res) + else: + self._op_LOAD_FAST(inst, res) + + else: + op_LOAD_FAST = _op_LOAD_FAST + + if PYVERSION in ((3, 13), (3, 14)): + def op_LOAD_FAST_LOAD_FAST(self, inst, res1, res2): + oparg = inst.arg + oparg1 = oparg >> 4 + oparg2 = oparg & 15 + src1 = self.get(self.code_locals[oparg1]) + src2 = self.get(self.code_locals[oparg2]) + self.store(value=src1, name=res1) + self.store(value=src2, name=res2) + + def op_STORE_FAST_LOAD_FAST(self, inst, store_value, load_res): + oparg = inst.arg + oparg1 = oparg >> 4 + oparg2 = oparg & 15 + + dstname = self.code_locals[oparg1] + dst_value = self.get(store_value) + self.store(value=dst_value, name=dstname) + + src_value = self.get(self.code_locals[oparg2]) + self.store(value=src_value, name=load_res) + + def op_STORE_FAST_STORE_FAST(self, inst, value1, value2): + oparg = inst.arg + oparg1 = oparg >> 4 + oparg2 = oparg & 15 + + dstname = self.code_locals[oparg1] + self.store(value=self.get(value1), name=dstname) + dstname = self.code_locals[oparg2] + self.store(value=self.get(value2), name=dstname) + + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + op_LOAD_FAST_CHECK = op_LOAD_FAST + + def op_LOAD_FAST_AND_CLEAR(self, inst, res): + try: + # try the regular LOAD_FAST logic + srcname = self.code_locals[inst.arg] + self.store(value=self.get(srcname), name=res) + except NotDefinedError: + # If the variable is not in the scope, set it to `undef` + undef = ir.Expr.undef(loc=self.loc) + self.store(undef, name=res) + + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14),): + # New in 3.14. + op_LOAD_FAST_BORROW = op_LOAD_FAST + op_LOAD_FAST_BORROW_LOAD_FAST_BORROW = op_LOAD_FAST_LOAD_FAST + + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_STORE_FAST(self, inst, value): + dstname = self.code_locals[inst.arg] + value = self.get(value) + self.store(value=value, name=dstname) + + def op_DELETE_FAST(self, inst): + dstname = self.code_locals[inst.arg] + self.current_block.append(ir.Del(dstname, loc=self.loc)) + + def op_DUP_TOPX(self, inst, orig, duped): + for src, dst in zip(orig, duped): + self.store(value=self.get(src), name=dst) + + op_DUP_TOP = op_DUP_TOPX + op_DUP_TOP_TWO = op_DUP_TOPX + + def op_STORE_ATTR(self, inst, target, value): + attr = self.code_names[inst.arg] + sa = ir.SetAttr(target=self.get(target), value=self.get(value), + attr=attr, loc=self.loc) + self.current_block.append(sa) + + def op_DELETE_ATTR(self, inst, target): + attr = self.code_names[inst.arg] + sa = ir.DelAttr(target=self.get(target), attr=attr, loc=self.loc) + self.current_block.append(sa) + + def op_LOAD_ATTR(self, inst, item, res): + item = self.get(item) + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + attr = self.code_names[inst.arg >> 1] + elif PYVERSION in ((3, 10), (3, 11)): + attr = self.code_names[inst.arg] + else: + raise NotImplementedError(PYVERSION) + getattr = ir.Expr.getattr(item, attr, loc=self.loc) + self.store(getattr, res) + + def op_LOAD_CONST(self, inst, res): + # New in 3.14: slice is loaded via LOAD_CONST. The value is the + # slice object itself, so we get the start, stop and step from it + # directly and then proceed with the code in `BUILD_SLICE`. It may also + # be a tuple containing a slice, so we need to account for that too. + def process_slice(value): + start = self.store(ir.Const(value.start, loc=self.loc), + name=f'$const_{value.start}', redefine=True) + stop = self.store(ir.Const(value.stop, loc=self.loc), + name=f'$const_{value.stop}', redefine=True) + + slicevar = self.store(value=ir.Global("slice", slice, + loc=self.loc), + name='$const_slice', redefine=True) + + if value.step is None: + params = (start, stop) + else: + step = self.store(ir.Const(value.step, loc=self.loc), + name=f'$const_{value.step}', redefine=True) + params = (start, stop, step) + + return ir.Expr.call(slicevar, params, (), loc=self.loc) + + def process_args(value): + st = [] + for x in value: + if isinstance(x, slice): + st.append(self.store(process_slice(x), + name='$const_my_slice', + redefine=True)) + else: + st.append(self.store(ir.Const(x, loc=self.loc), + name=f'$const_{x}', + redefine=True)) + return st + + value = self.code_consts[inst.arg] + + if isinstance(value, tuple): + const = ir.Expr.build_tuple(process_args(value), loc=self.loc) + elif isinstance(value, frozenset): + const = ir.Expr.build_set(process_args(value), loc=self.loc) + elif isinstance(value, slice): + const = process_slice(value) + else: + const = ir.Const(value, loc=self.loc) + self.store(const, res) + + if PYVERSION in ((3, 14), ): + # New in 3.14 + def op_LOAD_SMALL_INT(self, inst, res): + value = inst.arg + const = ir.Const(value, loc=self.loc) + self.store(const, res) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_LOAD_GLOBAL(self, inst, idx, res): + name = self.code_names[idx] + value = self.get_global_value(name) + gl = ir.Global(name, value, loc=self.loc) + self.store(gl, res) + elif PYVERSION in ((3, 10),): + def op_LOAD_GLOBAL(self, inst, res): + name = self.code_names[inst.arg] + value = self.get_global_value(name) + gl = ir.Global(name, value, loc=self.loc) + self.store(gl, res) + else: + raise NotImplementedError(PYVERSION) + + def op_COPY_FREE_VARS(self, inst): + pass + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_LOAD_DEREF(self, inst, res): + name = self.func_id.func.__code__._varname_from_oparg(inst.arg) + if name in self.code_cellvars: + try: + gl = self.get(name) + except NotDefinedError: + msg = "Unsupported use of cell variable encountered" + raise NotImplementedError(msg) + elif name in self.code_freevars: + idx = self.code_freevars.index(name) + value = self.get_closure_value(idx) + gl = ir.FreeVar(idx, name, value, loc=self.loc) + self.store(gl, res) + elif PYVERSION in ((3, 10),): + def op_LOAD_DEREF(self, inst, res): + n_cellvars = len(self.code_cellvars) + if inst.arg < n_cellvars: + name = self.code_cellvars[inst.arg] + gl = self.get(name) + else: + idx = inst.arg - n_cellvars + name = self.code_freevars[idx] + value = self.get_closure_value(idx) + gl = ir.FreeVar(idx, name, value, loc=self.loc) + self.store(gl, res) + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_MAKE_CELL(self, inst): + pass # ignored bytecode + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_STORE_DEREF(self, inst, value): + name = self.func_id.func.__code__._varname_from_oparg(inst.arg) + value = self.get(value) + self.store(value=value, name=name) + elif PYVERSION in ((3, 10),): + def op_STORE_DEREF(self, inst, value): + n_cellvars = len(self.code_cellvars) + if inst.arg < n_cellvars: + dstname = self.code_cellvars[inst.arg] + else: + dstname = self.code_freevars[inst.arg - n_cellvars] + value = self.get(value) + self.store(value=value, name=dstname) + else: + raise NotImplementedError(PYVERSION) + + def op_SETUP_LOOP(self, inst): + assert self.blocks[inst.offset] is self.current_block + loop = ir.Loop(inst.offset, exit=(inst.next + inst.arg)) + self.syntax_blocks.append(loop) + + def op_SETUP_WITH(self, inst, contextmanager, exitfn=None): + assert self.blocks[inst.offset] is self.current_block + # Handle with + exitpt = inst.next + inst.arg + + wth = ir.With(inst.offset, exit=exitpt) + self.syntax_blocks.append(wth) + ctxmgr = self.get(contextmanager) + self.current_block.append(ir.EnterWith(contextmanager=ctxmgr, + begin=inst.offset, + end=exitpt, loc=self.loc,)) + + # Store exit fn + exit_fn_obj = ir.Const(None, loc=self.loc) + self.store(value=exit_fn_obj, name=exitfn) + + if PYVERSION in ((3, 14), ): + # Replaced by LOAD_SPECIAL in 3.14. + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_BEFORE_WITH(self, inst, contextmanager, exitfn, end): + assert self.blocks[inst.offset] is self.current_block + if PYVERSION in ((3, 12), (3, 13)): + # Python 3.12 hack for handling nested with blocks + if end > self.last_active_offset: + # Use exception entries to figure out end of syntax block + end = max([ex.end for ex in self.active_exception_entries + if ex.target == end]) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + # Handle with + wth = ir.With(inst.offset, exit=end) + self.syntax_blocks.append(wth) + ctxmgr = self.get(contextmanager) + self.current_block.append(ir.EnterWith(contextmanager=ctxmgr, + begin=inst.offset, + end=end, loc=self.loc,)) + + # Store exit function + exit_fn_obj = ir.Const(None, loc=self.loc) + self.store(value=exit_fn_obj, name=exitfn) + else: + raise NotImplementedError(PYVERSION) + + def op_SETUP_FINALLY(self, inst): + # Removed since python3.11 + self._insert_try_block_begin() + + def op_WITH_CLEANUP(self, inst): + "no-op" + + def op_WITH_CLEANUP_START(self, inst): + "no-op" + + def op_WITH_CLEANUP_FINISH(self, inst): + "no-op" + + def op_END_FINALLY(self, inst): + "no-op" + + def op_BEGIN_FINALLY(self, inst, temps): + # The *temps* are the exception variables + const_none = ir.Const(None, loc=self.loc) + for tmp in temps: + # Set to None for now + self.store(const_none, name=tmp) + self._exception_vars.add(tmp) + + def op_CALL(self, inst, func, args, kw_names, res): + func = self.get(func) + args = [self.get(x) for x in args] + if kw_names is not None: + assert PYVERSION < (3, 13) + names = self.code_consts[kw_names] + kwargs = list(zip(names, args[-len(names):])) + args = args[:-len(names)] + else: + kwargs = () + expr = ir.Expr.call(func, args, kwargs, loc=self.loc) + self.store(expr, res) + + if PYVERSION in ((3, 13), (3, 14)): + def op_CALL_KW(self, inst, func, args, kw_names, res): + func = self.get(func) + args = [self.get(x) for x in args] + consti = int(kw_names.rsplit('.', 2)[-1]) + names = self.code_consts[consti] + kwargs = list(zip(names, args[-len(names):])) + args = args[:-len(names)] + expr = ir.Expr.call(func, args, kwargs, loc=self.loc) + self.store(expr, res) + else: + assert PYVERSION < (3, 13) + + def op_CALL_FUNCTION(self, inst, func, args, res): + func = self.get(func) + args = [self.get(x) for x in args] + expr = ir.Expr.call(func, args, (), loc=self.loc) + self.store(expr, res) + + def op_CALL_FUNCTION_KW(self, inst, func, args, names, res): + func = self.get(func) + args = [self.get(x) for x in args] + # Find names const + names = self.get(names) + for inst in self.current_block.body: + if isinstance(inst, ir.Assign) and inst.target is names: + self.current_block.remove(inst) + # scan up the block looking for the values, remove them + # and find their name strings + named_items = [] + for x in inst.value.items: + for y in self.current_block.body[::-1]: + if x == y.target: + self.current_block.remove(y) + named_items.append(y.value.value) + break + keys = named_items + break + + nkeys = len(keys) + posvals = args[:-nkeys] + kwvals = args[-nkeys:] + keyvalues = list(zip(keys, kwvals)) + + expr = ir.Expr.call(func, posvals, keyvalues, loc=self.loc) + self.store(expr, res) + + def op_CALL_FUNCTION_EX(self, inst, func, vararg, varkwarg, res): + func = self.get(func) + vararg = self.get(vararg) + if varkwarg is not None: + varkwarg = self.get(varkwarg) + expr = ir.Expr.call( + func, [], [], loc=self.loc, vararg=vararg, varkwarg=varkwarg + ) + self.store(expr, res) + + def _build_tuple_unpack(self, inst, tuples, temps, is_assign): + first = self.get(tuples[0]) + if is_assign: + # it's assign-like, defer handling to an intrinsic that will have + # type information. + # Can deal with tuples only, i.e. y = (*x,). where x = + gv_name = "unpack_single_tuple" + gv_fn = ir.Global(gv_name, unpack_single_tuple, loc=self.loc,) + self.store(value=gv_fn, name=gv_name, redefine=True) + exc = ir.Expr.call(self.get(gv_name), args=(first,), kws=(), + loc=self.loc,) + self.store(exc, temps[0]) + else: + loc = self.loc + for other, tmp in zip(map(self.get, tuples[1:]), temps): + # Emit as `first + tuple(other)` + gv_tuple = ir.Global( + name="tuple", value=tuple, + loc=loc, + ) + tuple_var = self.store( + gv_tuple, "$_list_extend_gv_tuple", redefine=True, + ) + tuplify_val = ir.Expr.call( + tuple_var, (other,), (), + loc=loc, + ) + tuplify_var = self.store(tuplify_val, "$_tuplify", + redefine=True) + out = ir.Expr.binop( + fn=operator.add, lhs=first, rhs=self.get(tuplify_var.name), + loc=self.loc, + ) + self.store(out, tmp) + first = self.get(tmp) + + def op_BUILD_TUPLE_UNPACK_WITH_CALL(self, inst, tuples, temps, is_assign): + # just unpack the input tuple, call inst will be handled afterwards + self._build_tuple_unpack(inst, tuples, temps, is_assign) + + def op_BUILD_TUPLE_UNPACK(self, inst, tuples, temps, is_assign): + self._build_tuple_unpack(inst, tuples, temps, is_assign) + + def op_LIST_TO_TUPLE(self, inst, const_list, res): + expr = ir.Expr.dummy('list_to_tuple', (const_list,), loc=self.loc) + self.store(expr, res) + + def op_BUILD_CONST_KEY_MAP(self, inst, keys, keytmps, values, res): + # Unpack the constant key-tuple and reused build_map which takes + # a sequence of (key, value) pair. + keyvar = self.get(keys) + # TODO: refactor this pattern. occurred several times. + for inst in self.current_block.body: + if isinstance(inst, ir.Assign) and inst.target is keyvar: + self.current_block.remove(inst) + # scan up the block looking for the values, remove them + # and find their name strings + named_items = [] + for x in inst.value.items: + for y in self.current_block.body[::-1]: + if x == y.target: + self.current_block.remove(y) + named_items.append(y.value.value) + break + keytup = named_items + break + assert len(keytup) == len(values) + keyconsts = [ir.Const(value=x, loc=self.loc) for x in keytup] + for kval, tmp in zip(keyconsts, keytmps): + self.store(kval, tmp) + items = list(zip(map(self.get, keytmps), map(self.get, values))) + + # sort out literal values + literal_items = [] + for v in values: + defns = self.definitions[v] + if len(defns) != 1: + break + defn = defns[0] + if not isinstance(defn, ir.Const): + break + literal_items.append(defn.value) + + def resolve_const(v): + defns = self.definitions[v] + if len(defns) != 1: + return _UNKNOWN_VALUE(self.get(v).name) + defn = defns[0] + if not isinstance(defn, ir.Const): + return _UNKNOWN_VALUE(self.get(v).name) + return defn.value + + if len(literal_items) != len(values): + literal_dict = {x: resolve_const(y) for x, y in + zip(keytup, values)} + else: + literal_dict = {x:y for x, y in zip(keytup, literal_items)} + + # to deal with things like {'a': 1, 'a': 'cat', 'b': 2, 'a': 2j} + # store the index of the actual used value for a given key, this is + # used when lowering to pull the right value out into the tuple repr + # of a mixed value type dictionary. + value_indexes = {} + for i, k in enumerate(keytup): + value_indexes[k] = i + + expr = ir.Expr.build_map(items=items, + size=2, + literal_value=literal_dict, + value_indexes=value_indexes, + loc=self.loc) + + self.store(expr, res) + + def op_GET_ITER(self, inst, value, res): + expr = ir.Expr.getiter(value=self.get(value), loc=self.loc) + self.store(expr, res) + + def op_FOR_ITER(self, inst, iterator, pair, indval, pred): + """ + Assign new block other this instruction. + """ + assert inst.offset in self.blocks, "FOR_ITER must be block head" + + # Emit code + val = self.get(iterator) + + pairval = ir.Expr.iternext(value=val, loc=self.loc) + self.store(pairval, pair) + + iternext = ir.Expr.pair_first(value=self.get(pair), loc=self.loc) + self.store(iternext, indval) + + isvalid = ir.Expr.pair_second(value=self.get(pair), loc=self.loc) + self.store(isvalid, pred) + + # Conditional jump + br = ir.Branch(cond=self.get(pred), truebr=inst.next, + falsebr=inst.get_jump_target(), + loc=self.loc) + self.current_block.append(br) + + if PYVERSION in ((3, 14),): + # Removed in 3.14 -- replaced with BINARY_OP and [] + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_BINARY_SUBSCR(self, inst, target, index, res): + index = self.get(index) + target = self.get(target) + expr = ir.Expr.getitem(target, index=index, loc=self.loc) + self.store(expr, res) + else: + raise NotImplementedError(PYVERSION) + + def op_STORE_SUBSCR(self, inst, target, index, value): + index = self.get(index) + target = self.get(target) + value = self.get(value) + stmt = ir.SetItem(target=target, index=index, value=value, + loc=self.loc) + self.current_block.append(stmt) + + def op_DELETE_SUBSCR(self, inst, target, index): + index = self.get(index) + target = self.get(target) + stmt = ir.DelItem(target=target, index=index, loc=self.loc) + self.current_block.append(stmt) + + def op_BUILD_TUPLE(self, inst, items, res): + expr = ir.Expr.build_tuple(items=[self.get(x) for x in items], + loc=self.loc) + self.store(expr, res) + + def op_BUILD_LIST(self, inst, items, res): + expr = ir.Expr.build_list(items=[self.get(x) for x in items], + loc=self.loc) + self.store(expr, res) + + def op_BUILD_SET(self, inst, items, res): + expr = ir.Expr.build_set(items=[self.get(x) for x in items], + loc=self.loc) + self.store(expr, res) + + def op_SET_ADD(self, inst, value, target, addvar, res): + value = self.get(value) + target = self.get(target) + addattr = ir.Expr.getattr(target, 'add', loc=self.loc) + self.store(value=addattr, name=addvar) + addinst = ir.Expr.call(self.get(addvar), (value, ), (), loc=self.loc) + self.store(value=addinst, name=res) + + def op_SET_UPDATE(self, inst, target, value, updatevar, res): + target = self.get(target) + value = self.get(value) + updateattr = ir.Expr.getattr(target, 'update', loc=self.loc) + self.store(value=updateattr, name=updatevar) + updateinst = ir.Expr.call(self.get(updatevar), (value,), (), + loc=self.loc) + self.store(value=updateinst, name=res) + + def op_DICT_UPDATE(self, inst, target, value, updatevar, res): + target = self.get(target) + value = self.get(value) + # We generate _update_from_bytecode instead of update so we can + # differentiate between user .update() calls and those from the + # bytecode. This is then used to recombine dictionaries in peephole + # optimizations. See the dicussion in this PR about why: + # https://github.com/numba/numba/pull/7964/files#r868229306 + updateattr = ir.Expr.getattr( + target, '_update_from_bytecode', loc=self.loc + ) + self.store(value=updateattr, name=updatevar) + updateinst = ir.Expr.call(self.get(updatevar), (value,), (), + loc=self.loc) + self.store(value=updateinst, name=res) + + def op_BUILD_MAP(self, inst, items, size, res): + got_items = [(self.get(k), self.get(v)) for k, v in items] + + # sort out literal values, this is a bit contrived but is to handle + # situations like `{1: 10, 1: 10}` where the size of the literal dict + # is smaller than the definition + def get_literals(target): + literal_items = [] + values = [self.get(v.name) for v in target] + for v in values: + defns = self.definitions[v.name] + if len(defns) != 1: + break + defn = defns[0] + if not isinstance(defn, ir.Const): + break + literal_items.append(defn.value) + return literal_items + + literal_keys = get_literals(x[0] for x in got_items) + literal_values = get_literals(x[1] for x in got_items) + + has_literal_keys = len(literal_keys) == len(got_items) + has_literal_values = len(literal_values) == len(got_items) + + value_indexes = {} + if not has_literal_keys and not has_literal_values: + literal_dict = None + elif has_literal_keys and not has_literal_values: + literal_dict = {x: _UNKNOWN_VALUE(y[1]) for x, y in + zip(literal_keys, got_items)} + for i, k in enumerate(literal_keys): + value_indexes[k] = i + else: + literal_dict = {x: y for x, y in zip(literal_keys, literal_values)} + for i, k in enumerate(literal_keys): + value_indexes[k] = i + + expr = ir.Expr.build_map(items=got_items, size=size, + literal_value=literal_dict, + value_indexes=value_indexes, + loc=self.loc) + self.store(expr, res) + + def op_STORE_MAP(self, inst, dct, key, value): + stmt = ir.StoreMap(dct=self.get(dct), key=self.get(key), + value=self.get(value), loc=self.loc) + self.current_block.append(stmt) + + def op_UNARY_NEGATIVE(self, inst, value, res): + value = self.get(value) + expr = ir.Expr.unary('-', value=value, loc=self.loc) + return self.store(expr, res) + + def op_UNARY_POSITIVE(self, inst, value, res): + value = self.get(value) + expr = ir.Expr.unary('+', value=value, loc=self.loc) + return self.store(expr, res) + + def op_UNARY_INVERT(self, inst, value, res): + value = self.get(value) + expr = ir.Expr.unary('~', value=value, loc=self.loc) + return self.store(expr, res) + + def op_UNARY_NOT(self, inst, value, res): + value = self.get(value) + expr = ir.Expr.unary('not', value=value, loc=self.loc) + return self.store(expr, res) + + def _binop(self, op, lhs, rhs, res): + op = BINOPS_TO_OPERATORS[op] + lhs = self.get(lhs) + rhs = self.get(rhs) + expr = ir.Expr.binop(op, lhs=lhs, rhs=rhs, loc=self.loc) + self.store(expr, res) + + def _inplace_binop(self, op, lhs, rhs, res): + immuop = BINOPS_TO_OPERATORS[op] + op = INPLACE_BINOPS_TO_OPERATORS[op + '='] + lhs = self.get(lhs) + rhs = self.get(rhs) + expr = ir.Expr.inplace_binop(op, immuop, lhs=lhs, rhs=rhs, + loc=self.loc) + self.store(expr, res) + + def op_BINARY_OP(self, inst, op, lhs, rhs, res): + if op == "[]": + # Special case 3.14 -- body of BINARY_SUBSCR now here + lhs = self.get(lhs) + rhs = self.get(rhs) + expr = ir.Expr.getitem(lhs, index=rhs, loc=self.loc) + self.store(expr, res) + elif "=" in op: + self._inplace_binop(op[:-1], lhs, rhs, res) + else: + self._binop(op, lhs, rhs, res) + + def op_BINARY_ADD(self, inst, lhs, rhs, res): + self._binop('+', lhs, rhs, res) + + def op_BINARY_SUBTRACT(self, inst, lhs, rhs, res): + self._binop('-', lhs, rhs, res) + + def op_BINARY_MULTIPLY(self, inst, lhs, rhs, res): + self._binop('*', lhs, rhs, res) + + def op_BINARY_DIVIDE(self, inst, lhs, rhs, res): + self._binop('/?', lhs, rhs, res) + + def op_BINARY_TRUE_DIVIDE(self, inst, lhs, rhs, res): + self._binop('/', lhs, rhs, res) + + def op_BINARY_FLOOR_DIVIDE(self, inst, lhs, rhs, res): + self._binop('//', lhs, rhs, res) + + def op_BINARY_MODULO(self, inst, lhs, rhs, res): + self._binop('%', lhs, rhs, res) + + def op_BINARY_POWER(self, inst, lhs, rhs, res): + self._binop('**', lhs, rhs, res) + + def op_BINARY_MATRIX_MULTIPLY(self, inst, lhs, rhs, res): + self._binop('@', lhs, rhs, res) + + def op_BINARY_LSHIFT(self, inst, lhs, rhs, res): + self._binop('<<', lhs, rhs, res) + + def op_BINARY_RSHIFT(self, inst, lhs, rhs, res): + self._binop('>>', lhs, rhs, res) + + def op_BINARY_AND(self, inst, lhs, rhs, res): + self._binop('&', lhs, rhs, res) + + def op_BINARY_OR(self, inst, lhs, rhs, res): + self._binop('|', lhs, rhs, res) + + def op_BINARY_XOR(self, inst, lhs, rhs, res): + self._binop('^', lhs, rhs, res) + + def op_INPLACE_ADD(self, inst, lhs, rhs, res): + self._inplace_binop('+', lhs, rhs, res) + + def op_INPLACE_SUBTRACT(self, inst, lhs, rhs, res): + self._inplace_binop('-', lhs, rhs, res) + + def op_INPLACE_MULTIPLY(self, inst, lhs, rhs, res): + self._inplace_binop('*', lhs, rhs, res) + + def op_INPLACE_DIVIDE(self, inst, lhs, rhs, res): + self._inplace_binop('/?', lhs, rhs, res) + + def op_INPLACE_TRUE_DIVIDE(self, inst, lhs, rhs, res): + self._inplace_binop('/', lhs, rhs, res) + + def op_INPLACE_FLOOR_DIVIDE(self, inst, lhs, rhs, res): + self._inplace_binop('//', lhs, rhs, res) + + def op_INPLACE_MODULO(self, inst, lhs, rhs, res): + self._inplace_binop('%', lhs, rhs, res) + + def op_INPLACE_POWER(self, inst, lhs, rhs, res): + self._inplace_binop('**', lhs, rhs, res) + + def op_INPLACE_MATRIX_MULTIPLY(self, inst, lhs, rhs, res): + self._inplace_binop('@', lhs, rhs, res) + + def op_INPLACE_LSHIFT(self, inst, lhs, rhs, res): + self._inplace_binop('<<', lhs, rhs, res) + + def op_INPLACE_RSHIFT(self, inst, lhs, rhs, res): + self._inplace_binop('>>', lhs, rhs, res) + + def op_INPLACE_AND(self, inst, lhs, rhs, res): + self._inplace_binop('&', lhs, rhs, res) + + def op_INPLACE_OR(self, inst, lhs, rhs, res): + self._inplace_binop('|', lhs, rhs, res) + + def op_INPLACE_XOR(self, inst, lhs, rhs, res): + self._inplace_binop('^', lhs, rhs, res) + + def op_JUMP_ABSOLUTE(self, inst): + jmp = ir.Jump(inst.get_jump_target(), loc=self.loc) + self.current_block.append(jmp) + + def op_JUMP_FORWARD(self, inst): + jmp = ir.Jump(inst.get_jump_target(), loc=self.loc) + self.current_block.append(jmp) + + def op_JUMP_BACKWARD(self, inst): + jmp = ir.Jump(inst.get_jump_target(), loc=self.loc) + self.current_block.append(jmp) + + op_JUMP_BACKWARD_NO_INTERRUPT = op_JUMP_BACKWARD + + def op_POP_BLOCK(self, inst, kind=None): + if kind is None: + self.syntax_blocks.pop() + elif kind == 'with': + d = ir.PopBlock(loc=self.loc) + self.current_block.append(d) + elif kind == 'try': + self._insert_try_block_end() + + def op_RETURN_VALUE(self, inst, retval, castval): + self.store(ir.Expr.cast(self.get(retval), loc=self.loc), castval) + ret = ir.Return(self.get(castval), loc=self.loc) + self.current_block.append(ret) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_RETURN_CONST(self, inst, retval, castval): + value = self.code_consts[inst.arg] + const = ir.Const(value, loc=self.loc) + self.store(const, retval) + self.store(ir.Expr.cast(self.get(retval), loc=self.loc), castval) + ret = ir.Return(self.get(castval), loc=self.loc) + self.current_block.append(ret) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 13), (3, 14)): + def op_TO_BOOL(self, inst, val, res): + self.store(self.get(val), res) # TODO: just a lazy hack + + elif PYVERSION in ((3, 10), (3, 11), (3, 12)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_COMPARE_OP(self, inst, lhs, rhs, res): + if PYVERSION in ((3, 13), (3, 14)): + op = dis.cmp_op[inst.arg >> 5] + # TODO: fifth lowest bit now indicates a forced version to bool. + elif PYVERSION in ((3, 12),): + op = dis.cmp_op[inst.arg >> 4] + elif PYVERSION in ((3, 10), (3, 11)): + op = dis.cmp_op[inst.arg] + else: + raise NotImplementedError(PYVERSION) + if op == 'in' or op == 'not in': + lhs, rhs = rhs, lhs + + if op == 'not in': + self._binop('in', lhs, rhs, res) + tmp = self.get(res) + out = ir.Expr.unary('not', value=tmp, loc=self.loc) + self.store(out, res) + elif op == 'exception match': + gv_fn = ir.Global( + "exception_match", eh.exception_match, loc=self.loc, + ) + exc_match_name = '$exc_match' + self.store(value=gv_fn, name=exc_match_name, redefine=True) + lhs = self.get(lhs) + rhs = self.get(rhs) + exc = ir.Expr.call( + self.get(exc_match_name), args=(lhs, rhs), kws=(), loc=self.loc, + ) + self.store(exc, res) + else: + self._binop(op, lhs, rhs, res) + + def op_IS_OP(self, inst, lhs, rhs, res): + # invert if op case is 1 + op = 'is not' if inst.arg == 1 else 'is' + self._binop(op, lhs, rhs, res) + + def op_CONTAINS_OP(self, inst, lhs, rhs, res): + lhs, rhs = rhs, lhs + self._binop('in', lhs, rhs, res) + # invert if op case is 1 + if inst.arg == 1: + tmp = self.get(res) + out = ir.Expr.unary('not', value=tmp, loc=self.loc) + self.store(out, res) + + def op_BREAK_LOOP(self, inst, end=None): + if end is None: + loop = self.syntax_blocks[-1] + assert isinstance(loop, ir.Loop) + end = loop.exit + jmp = ir.Jump(target=end, loc=self.loc) + self.current_block.append(jmp) + + def _op_JUMP_IF(self, inst, pred, iftrue): + brs = { + True: inst.get_jump_target(), + False: inst.next, + } + truebr = brs[iftrue] + falsebr = brs[not iftrue] + + name = "$bool%s" % (inst.offset) + gv_fn = ir.Global("bool", bool, loc=self.loc) + self.store(value=gv_fn, name=name) + + callres = ir.Expr.call(self.get(name), (self.get(pred),), (), + loc=self.loc) + + pname = "$%spred" % (inst.offset) + predicate = self.store(value=callres, name=pname) + bra = ir.Branch(cond=predicate, truebr=truebr, falsebr=falsebr, + loc=self.loc) + self.current_block.append(bra) + + def op_JUMP_IF_FALSE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=False) + + def op_JUMP_IF_TRUE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=True) + + def _jump_if_none(self, inst, pred, iftrue): + # branch pruning assumes true falls through and false is jump + truebr = inst.next + falsebr = inst.get_jump_target() + + # this seems strange + if not iftrue: + op = BINOPS_TO_OPERATORS["is"] + else: + op = BINOPS_TO_OPERATORS["is not"] + + rhs = self.store(value=ir.Const(None, loc=self.loc), + name=f"$constNone{inst.offset}") + lhs = self.get(pred) + isnone = ir.Expr.binop(op, lhs=lhs, rhs=rhs, loc=self.loc) + + maybeNone = f"$maybeNone{inst.offset}" + self.store(value=isnone, name=maybeNone) + + name = f"$bool{inst.offset}" + gv_fn = ir.Global("bool", bool, loc=self.loc) + self.store(value=gv_fn, name=name) + + callres = ir.Expr.call(self.get(name), (self.get(maybeNone),), (), + loc=self.loc) + + pname = f"$pred{inst.offset}" + predicate = self.store(value=callres, name=pname) + branch = ir.Branch(cond=predicate, + truebr=truebr, + falsebr=falsebr, + loc=self.loc) + self.current_block.append(branch) + + def op_POP_JUMP_FORWARD_IF_NONE(self, inst, pred): + self._jump_if_none(inst, pred, True) + + def op_POP_JUMP_FORWARD_IF_NOT_NONE(self, inst, pred): + self._jump_if_none(inst, pred, False) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_POP_JUMP_IF_NONE(self, inst, pred): + self._jump_if_none(inst, pred, True) + + def op_POP_JUMP_IF_NOT_NONE(self, inst, pred): + self._jump_if_none(inst, pred, False) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + def op_POP_JUMP_BACKWARD_IF_NONE(self, inst, pred): + self._jump_if_none(inst, pred, True) + + def op_POP_JUMP_BACKWARD_IF_NOT_NONE(self, inst, pred): + self._jump_if_none(inst, pred, False) + + def op_POP_JUMP_FORWARD_IF_FALSE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=False) + + def op_POP_JUMP_FORWARD_IF_TRUE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=True) + + def op_POP_JUMP_BACKWARD_IF_FALSE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=False) + + def op_POP_JUMP_BACKWARD_IF_TRUE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=True) + + def op_POP_JUMP_IF_FALSE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=False) + + def op_POP_JUMP_IF_TRUE(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=True) + + def op_JUMP_IF_FALSE_OR_POP(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=False) + + def op_JUMP_IF_TRUE_OR_POP(self, inst, pred): + self._op_JUMP_IF(inst, pred=pred, iftrue=True) + + def op_CHECK_EXC_MATCH(self, inst, pred, tos, tos1): + gv_fn = ir.Global( + "exception_match", eh.exception_match, loc=self.loc, + ) + exc_match_name = '$exc_match' + self.store(value=gv_fn, name=exc_match_name, redefine=True) + lhs = self.get(tos1) + rhs = self.get(tos) + exc = ir.Expr.call( + self.get(exc_match_name), args=(lhs, rhs), kws=(), loc=self.loc, + ) + self.store(exc, pred) + + def op_JUMP_IF_NOT_EXC_MATCH(self, inst, pred, tos, tos1): + truebr = inst.next + falsebr = inst.get_jump_target() + gv_fn = ir.Global( + "exception_match", eh.exception_match, loc=self.loc, + ) + exc_match_name = '$exc_match' + self.store(value=gv_fn, name=exc_match_name, redefine=True) + lhs = self.get(tos1) + rhs = self.get(tos) + exc = ir.Expr.call( + self.get(exc_match_name), args=(lhs, rhs), kws=(), loc=self.loc, + ) + predicate = self.store(exc, pred) + bra = ir.Branch(cond=predicate, truebr=truebr, falsebr=falsebr, + loc=self.loc) + self.current_block.append(bra) + + def op_RERAISE(self, inst, exc): + tryblk = self.dfainfo.active_try_block + if tryblk is not None: + stmt = ir.TryRaise(exception=None, loc=self.loc) + self.current_block.append(stmt) + self._insert_try_block_end() + self.current_block.append(ir.Jump(tryblk['end'], loc=self.loc)) + else: + # Numba can't handle this case and it's caught else where, this is a + # runtime guard in case this is reached by unknown means. + msg = (f"Unreachable condition reached (op code RERAISE executed)" + f"{error_extras['reportable']}") + stmt = ir.StaticRaise(AssertionError, (msg,), self.loc) + self.current_block.append(stmt) + + def op_RAISE_VARARGS(self, inst, exc): + if exc is not None: + exc = self.get(exc) + tryblk = self.dfainfo.active_try_block + if tryblk is not None: + # In a try block + stmt = ir.TryRaise(exception=exc, loc=self.loc) + self.current_block.append(stmt) + self._insert_try_block_end() + self.current_block.append(ir.Jump(tryblk['end'], loc=self.loc)) + else: + # Not in a try block + stmt = ir.Raise(exception=exc, loc=self.loc) + self.current_block.append(stmt) + + def op_YIELD_VALUE(self, inst, value, res): + # initialize index to None. it's being set later in post-processing + index = None + inst = ir.Yield(value=self.get(value), index=index, loc=self.loc) + return self.store(inst, res) + + def op_MAKE_FUNCTION(self, inst, name, code, closure, annotations, + annotate, kwdefaults, defaults, res): + # annotations are ignored by numba but useful for static analysis + # re. https://github.com/numba/numba/issues/7269 + # annotate is ignored too + # re. https://github.com/numba/numba/pull/10321 + if kwdefaults is not None: + msg = "op_MAKE_FUNCTION with kwdefaults is not implemented" + raise NotImplementedError(msg) + if defaults: + if isinstance(defaults, tuple): + defaults = tuple([self.get(name) for name in defaults]) + else: + defaults = self.get(defaults) + + assume_code_const = self.definitions[code][0] + if not isinstance(assume_code_const, ir.Const): + msg = ( + "Unsupported use of closure. " + "Probably caused by complex control-flow constructs; " + "e.g. try-except" + ) + raise errors.UnsupportedBytecodeError(msg, loc=self.loc) + fcode = assume_code_const.value + if name: + name = self.get(name) + if closure: + closure = self.get(closure) + expr = ir.Expr.make_function(name, fcode, closure, defaults, self.loc) + self.store(expr, res) + + def op_MAKE_CLOSURE(self, inst, name, code, closure, annotations, + kwdefaults, defaults, res): + self.op_MAKE_FUNCTION(inst, name, code, closure, annotations, + kwdefaults, defaults, res) + + if PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + def op_LOAD_CLOSURE(self, inst, res): + name = self.func_id.func.__code__._varname_from_oparg(inst.arg) + if name in self.code_cellvars: + try: + gl = self.get(name) + except NotDefinedError: + msg = "Unsupported use of cell variable encountered" + raise NotImplementedError(msg) + elif name in self.code_freevars: + idx = self.code_freevars.index(name) + value = self.get_closure_value(idx) + gl = ir.FreeVar(idx, name, value, loc=self.loc) + else: + assert 0, "unreachable" + self.store(gl, res) + + elif PYVERSION in ((3, 10),): + def op_LOAD_CLOSURE(self, inst, res): + n_cellvars = len(self.code_cellvars) + if inst.arg < n_cellvars: + name = self.code_cellvars[inst.arg] + try: + gl = self.get(name) + except NotDefinedError: + msg = "Unsupported use of cell variable encountered" + raise NotImplementedError(msg) + else: + idx = inst.arg - n_cellvars + name = self.code_freevars[idx] + value = self.get_closure_value(idx) + gl = ir.FreeVar(idx, name, value, loc=self.loc) + self.store(gl, res) + else: + raise NotImplementedError(PYVERSION) + + def op_LIST_APPEND(self, inst, target, value, appendvar, res): + target = self.get(target) + value = self.get(value) + appendattr = ir.Expr.getattr(target, 'append', loc=self.loc) + self.store(value=appendattr, name=appendvar) + appendinst = ir.Expr.call(self.get(appendvar), (value,), (), + loc=self.loc) + self.store(value=appendinst, name=res) + + def op_LIST_EXTEND(self, inst, target, value, extendvar, res): + target = self.get(target) + value = self.get(value) + # If the statements between the current instruction and the target + # are N * consts followed by build_tuple AND the target has no items, + # it's a situation where a list is being statically initialised, rewrite + # the build_tuple as a build_list, drop the extend, and wire up the + # target as the result from the build_tuple that's been rewritten. + + # See if this is the first statement in a block, if so its probably from + # control flow in a tuple unpack like: + # `(*(1, (2,) if predicate else (3,)))` + # this cannot be handled as present so raise + msg = ("An unsupported bytecode sequence has been encountered: " + "op_LIST_EXTEND at the start of a block.\n\nThis could be " + "due to the use of a branch in a tuple unpacking statement.") + if not self.current_block.body: + raise errors.UnsupportedBytecodeError(msg) + + # is last emitted statement a build_tuple? + stmt = self.current_block.body[-1] + ok = isinstance(stmt.value, ir.Expr) and stmt.value.op == "build_tuple" + # check statements from self.current_block.body[-1] through to target, + # make sure they are consts + build_empty_list = None + if ok: + for stmt in reversed(self.current_block.body[:-1]): + if not isinstance(stmt, ir.Assign): + ok = False + break + # if its not a const, it needs to be the `build_list` for the + # target, else it's something else we don't know about so just + # bail + if isinstance(stmt.value, ir.Const): + continue + + # it's not a const, check for target + elif isinstance(stmt.value, ir.Expr) and stmt.target == target: + build_empty_list = stmt + # it's only ok to do this if the target has no initializer + # already + ok = not stmt.value.items + break + else: + ok = False + break + if ok and build_empty_list is None: + raise errors.UnsupportedBytecodeError(msg) + if ok: + stmts = self.current_block.body + build_tuple_asgn = self.current_block.body[-1] + # move build list to last issued statement + stmts.append(stmts.pop(stmts.index(build_empty_list))) + # fix the build list + build_tuple = build_tuple_asgn.value + build_list = build_empty_list.value + build_list.items = build_tuple.items + else: + # it's just a list extend with no static init, let it be + extendattr = ir.Expr.getattr(target, 'extend', loc=self.loc) + self.store(value=extendattr, name=extendvar) + extendinst = ir.Expr.call(self.get(extendvar), (value,), (), + loc=self.loc) + self.store(value=extendinst, name=res) + + def op_MAP_ADD(self, inst, target, key, value, setitemvar, res): + target = self.get(target) + key = self.get(key) + value = self.get(value) + setitemattr = ir.Expr.getattr(target, '__setitem__', loc=self.loc) + self.store(value=setitemattr, name=setitemvar) + appendinst = ir.Expr.call(self.get(setitemvar), (key, value,), (), + loc=self.loc) + self.store(value=appendinst, name=res) + + if PYVERSION in ((3, 14), ): + # Removed in 3.14 + pass + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + def op_LOAD_ASSERTION_ERROR(self, inst, res): + gv_fn = ir.Global("AssertionError", AssertionError, loc=self.loc) + self.store(value=gv_fn, name=res) + else: + raise NotImplementedError(PYVERSION) + + # NOTE: The LOAD_METHOD opcode is implemented as a LOAD_ATTR for ease, + # however this means a new object (the bound-method instance) could be + # created. Conversely, using a pure LOAD_METHOD no intermediary is present + # and it is essentially like a pointer grab and forward to CALL_METHOD. The + # net outcome is that the implementation in Numba produces the same result, + # but in object mode it may be that it runs more slowly than it would if + # run in CPython. + + def op_LOAD_METHOD(self, *args, **kws): + self.op_LOAD_ATTR(*args, **kws) + + def op_CALL_METHOD(self, *args, **kws): + self.op_CALL_FUNCTION(*args, **kws) + + if PYVERSION in ((3, 12), (3, 13), (3, 14)): + def op_CALL_INTRINSIC_1(self, inst, operand, **kwargs): + if operand == ci1op.INTRINSIC_STOPITERATION_ERROR: + stmt = ir.StaticRaise(INTRINSIC_STOPITERATION_ERROR, (), + self.loc) + self.current_block.append(stmt) + return + elif operand == ci1op.UNARY_POSITIVE: + self.op_UNARY_POSITIVE(inst, **kwargs) + return + elif operand == ci1op.INTRINSIC_LIST_TO_TUPLE: + self.op_LIST_TO_TUPLE(inst, **kwargs) + return + else: + raise NotImplementedError(operand) + elif PYVERSION in ((3, 10), (3, 11)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14), ): + # New in 3.14, replaces BEFORE_WITH. + def op_LOAD_SPECIAL(self, inst, contextmanager, exit_method, block_end): + assert self.blocks[inst.offset] is self.current_block + + # Python 3.12 hack for handling nested with blocks + if block_end > self.last_active_offset: + # Use exception entries to figure out end of syntax block + block_end = max([ex.end for ex in self.active_exception_entries + if ex.target == block_end]) + + # Handle with + wth = ir.With(inst.offset, exit=block_end) + self.syntax_blocks.append(wth) + ctxmgr = self.get(contextmanager) + self.current_block.append( + ir.EnterWith(contextmanager=ctxmgr, + begin=inst.offset, + end=block_end, loc=self.loc,)) + + # Store exit function + exit_fn_obj = ir.Const(None, loc=self.loc) + self.store(value=exit_fn_obj, name=exit_method) + + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + if PYVERSION in ((3, 14), ): + def op_LOAD_COMMON_CONSTANT(self, inst, res, idx): + if dis._common_constants[idx] == AssertionError: + gv_fn = ir.Global("AssertionError", + AssertionError, + loc=self.loc) + self.store(value=gv_fn, name=res) + else: + raise NotImplementedError + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + pass + else: + raise NotImplementedError(PYVERSION) + + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + class INTRINSIC_STOPITERATION_ERROR(AssertionError): + pass +elif PYVERSION in ((3, 10), (3, 11)): + pass +else: + raise NotImplementedError(PYVERSION) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/intrinsics.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/intrinsics.py new file mode 100644 index 0000000000000000000000000000000000000000..8e85bb35400e7770c1746fb375afc248cb0fe35d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/intrinsics.py @@ -0,0 +1,101 @@ +""" +LLVM pass that converts intrinsic into other math calls +""" + +from llvmlite import ir + + +class _DivmodFixer(ir.Visitor): + def visit_Instruction(self, instr): + if instr.type == ir.IntType(64): + if instr.opname in ['srem', 'urem', 'sdiv', 'udiv']: + name = 'numba_{op}'.format(op=instr.opname) + fn = self.module.globals.get(name) + # Declare the function if it doesn't already exist + if fn is None: + opty = instr.type + sdivfnty = ir.FunctionType(opty, [opty, opty]) + fn = ir.Function(self.module, sdivfnty, name=name) + # Replace the operation with a call to the builtin + repl = ir.CallInstr(parent=instr.parent, func=fn, + args=instr.operands, name=instr.name) + instr.parent.replace(instr, repl) + + +def fix_divmod(mod): + """Replace division and reminder instructions to builtins calls + """ + _DivmodFixer().visit(mod) + + +INTR_TO_CMATH = { + "llvm.pow.f32": "powf", + "llvm.pow.f64": "pow", + + "llvm.sin.f32": "sinf", + "llvm.sin.f64": "sin", + + "llvm.cos.f32": "cosf", + "llvm.cos.f64": "cos", + + "llvm.sqrt.f32": "sqrtf", + "llvm.sqrt.f64": "sqrt", + + "llvm.exp.f32": "expf", + "llvm.exp.f64": "exp", + + "llvm.log.f32": "logf", + "llvm.log.f64": "log", + + "llvm.log10.f32": "log10f", + "llvm.log10.f64": "log10", + + "llvm.fabs.f32": "fabsf", + "llvm.fabs.f64": "fabs", + + "llvm.floor.f32": "floorf", + "llvm.floor.f64": "floor", + + "llvm.ceil.f32": "ceilf", + "llvm.ceil.f64": "ceil", + + "llvm.trunc.f32": "truncf", + "llvm.trunc.f64": "trunc", +} + +OTHER_CMATHS = ''' +tan +tanf +sinh +sinhf +cosh +coshf +tanh +tanhf +asin +asinf +acos +acosf +atan +atanf +atan2 +atan2f +asinh +asinhf +acosh +acoshf +atanh +atanhf +expm1 +expm1f +log1p +log1pf +log10 +log10f +fmod +fmodf +round +roundf +'''.split() + +INTR_MATH = frozenset(INTR_TO_CMATH.values()) | frozenset(OTHER_CMATHS) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir.py new file mode 100644 index 0000000000000000000000000000000000000000..c7efe4017e83f3de6e8cb83a969bb0d1754c6dd8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir.py @@ -0,0 +1,1702 @@ +from collections import defaultdict +import copy +import itertools +import os +import linecache +import pprint +import re +import sys +import operator +from types import FunctionType, BuiltinFunctionType +from functools import total_ordering +from io import StringIO + +from numba.core import errors, config +from numba.core.utils import (BINOPS_TO_OPERATORS, INPLACE_BINOPS_TO_OPERATORS, + UNARY_BUITINS_TO_OPERATORS, OPERATORS_TO_BUILTINS) +from numba.core.errors import (NotDefinedError, RedefinedError, + VerificationError, ConstantInferenceError) +from numba.core import consts + +# terminal color markup +_termcolor = errors.termcolor() + + +class Loc(object): + """Source location + + """ + _defmatcher = re.compile(r'def\s+(\w+)') + + def __init__(self, filename, line, col=None, maybe_decorator=False): + """ Arguments: + filename - name of the file + line - line in file + col - column + maybe_decorator - Set to True if location is likely a jit decorator + """ + self.filename = filename + self.line = line + self.col = col + self.lines = None # the source lines from the linecache + self.maybe_decorator = maybe_decorator + + def __eq__(self, other): + # equivalence is solely based on filename, line and col + if type(self) is not type(other): return False + if self.filename != other.filename: return False + if self.line != other.line: return False + if self.col != other.col: return False + return True + + def __ne__(self, other): + return not self.__eq__(other) + + @classmethod + def from_function_id(cls, func_id): + return cls(func_id.filename, func_id.firstlineno, maybe_decorator=True) + + def __repr__(self): + return "Loc(filename=%s, line=%s, col=%s)" % (self.filename, + self.line, self.col) + + def __str__(self): + if self.col is not None: + return "%s (%s:%s)" % (self.filename, self.line, self.col) + else: + return "%s (%s)" % (self.filename, self.line) + + def _find_definition(self): + # try and find a def, go backwards from error line + fn_name = None + lines = self.get_lines() + for x in reversed(lines[:self.line - 1]): + # the strip and startswith is to handle user code with commented out + # 'def' or use of 'def' in a docstring. + if x.strip().startswith('def '): + fn_name = x + break + + return fn_name + + def _raw_function_name(self): + defn = self._find_definition() + if defn: + m = self._defmatcher.match(defn.strip()) + if m: + return m.groups()[0] + # Probably exec() or REPL. + return None + + def get_lines(self): + if self.lines is None: + path = self._get_path() + # Avoid reading from dynamic string. They are most likely + # overridden. Problem started with Python 3.13. "" seems + # to be something from multiprocessing. + lns = [] if path == "" else linecache.getlines(path) + self.lines = lns + return self.lines + + def _get_path(self): + path = None + try: + # Try to get a relative path + # ipython/jupyter input just returns as self.filename + path = os.path.relpath(self.filename) + except ValueError: + # Fallback to absolute path if error occurred in getting the + # relative path. + # This may happen on windows if the drive is different + path = os.path.abspath(self.filename) + return path + + + def strformat(self, nlines_up=2): + + lines = self.get_lines() + + use_line = self.line + + if self.maybe_decorator: + # try and sort out a better `loc`, if it's suspected that this loc + # points at a jit decorator by virtue of + # `__code__.co_firstlineno` + + # get lines, add a dummy entry at the start as lines count from + # 1 but list index counts from 0 + tmplines = [''] + lines + + if lines and use_line and 'def ' not in tmplines[use_line]: + # look forward 10 lines, unlikely anyone managed to stretch + # a jit call declaration over >10 lines?! + min_line = max(0, use_line) + max_line = use_line + 10 + selected = tmplines[min_line : max_line] + index = 0 + for idx, x in enumerate(selected): + if 'def ' in x: + index = idx + break + use_line = use_line + index + + + ret = [] # accumulates output + if lines and use_line > 0: + + def count_spaces(string): + spaces = 0 + for x in itertools.takewhile(str.isspace, str(string)): + spaces += 1 + return spaces + + # A few places in the code still use no `loc` or default to line 1 + # this is often in places where exceptions are used for the purposes + # of flow control. As a result max is in use to prevent slice from + # `[negative: positive]` + selected = lines[max(0, use_line - nlines_up):use_line] + + # see if selected contains a definition + def_found = False + for x in selected: + if 'def ' in x: + def_found = True + + # no definition found, try and find one + if not def_found: + # try and find a def, go backwards from error line + fn_name = None + for x in reversed(lines[:use_line - 1]): + if 'def ' in x: + fn_name = x + break + if fn_name: + ret.append(fn_name) + spaces = count_spaces(x) + ret.append(' '*(4 + spaces) + '\n') + + if selected: + ret.extend(selected[:-1]) + ret.append(_termcolor.highlight(selected[-1])) + + # point at the problem with a caret + spaces = count_spaces(selected[-1]) + ret.append(' '*(spaces) + _termcolor.indicate("^")) + + # if in the REPL source may not be available + if not ret: + if not lines: + ret = "" + elif use_line <= 0: + ret = "" + + + err = _termcolor.filename('\nFile "%s", line %d:')+'\n%s' + tmp = err % (self._get_path(), use_line, _termcolor.code(''.join(ret))) + return tmp + + def with_lineno(self, line, col=None): + """ + Return a new Loc with this line number. + """ + return type(self)(self.filename, line, col) + + def short(self): + """ + Returns a short string + """ + shortfilename = os.path.basename(self.filename) + return "%s:%s" % (shortfilename, self.line) + + +# Used for annotating errors when source location is unknown. +unknown_loc = Loc("unknown location", 0, 0) + + +@total_ordering +class SlotEqualityCheckMixin(object): + # some ir nodes are __dict__ free using __slots__ instead, this mixin + # should not trigger the unintended creation of __dict__. + __slots__ = tuple() + + def __eq__(self, other): + if type(self) is type(other): + for name in self.__slots__: + if getattr(self, name) != getattr(other, name): + return False + else: + return True + return False + + def __le__(self, other): + return str(self) <= str(other) + + def __hash__(self): + return id(self) + + +@total_ordering +class EqualityCheckMixin(object): + """ Mixin for basic equality checking """ + + def __eq__(self, other): + if type(self) is type(other): + def fixup(adict): + bad = ('loc', 'scope') + d = dict(adict) + for x in bad: + d.pop(x, None) + return d + d1 = fixup(self.__dict__) + d2 = fixup(other.__dict__) + if d1 == d2: + return True + return False + + def __le__(self, other): + return str(self) < str(other) + + def __hash__(self): + return id(self) + + +class VarMap(object): + def __init__(self): + self._con = {} + + def define(self, name, var): + if name in self._con: + raise RedefinedError(name) + else: + self._con[name] = var + + def get(self, name): + try: + return self._con[name] + except KeyError: + raise NotDefinedError(name) + + def __contains__(self, name): + return name in self._con + + def __len__(self): + return len(self._con) + + def __repr__(self): + return pprint.pformat(self._con) + + def __hash__(self): + return hash(self.name) + + def __iter__(self): + return self._con.iterkeys() + + def __eq__(self, other): + if type(self) is type(other): + # check keys only, else __eq__ ref cycles, scope -> varmap -> var + return self._con.keys() == other._con.keys() + return False + + def __ne__(self, other): + return not self.__eq__(other) + + +class AbstractRHS(object): + """Abstract base class for anything that can be the RHS of an assignment. + This class **does not** define any methods. + """ + + +class Inst(EqualityCheckMixin, AbstractRHS): + """ + Base class for all IR instructions. + """ + + def list_vars(self): + """ + List the variables used (read or written) by the instruction. + """ + raise NotImplementedError + + def _rec_list_vars(self, val): + """ + A recursive helper used to implement list_vars() in subclasses. + """ + if isinstance(val, Var): + return [val] + elif isinstance(val, Inst): + return val.list_vars() + elif isinstance(val, (list, tuple)): + lst = [] + for v in val: + lst.extend(self._rec_list_vars(v)) + return lst + elif isinstance(val, dict): + lst = [] + for v in val.values(): + lst.extend(self._rec_list_vars(v)) + return lst + else: + return [] + + +class Stmt(Inst): + """ + Base class for IR statements (instructions which can appear on their + own in a Block). + """ + # Whether this statement ends its basic block (i.e. it will either jump + # to another block or exit the function). + is_terminator = False + # Whether this statement exits the function. + is_exit = False + + def list_vars(self): + return self._rec_list_vars(self.__dict__) + + +class Terminator(Stmt): + """ + IR statements that are terminators: the last statement in a block. + A terminator must either: + - exit the function + - jump to a block + + All subclass of Terminator must override `.get_targets()` to return a list + of jump targets. + """ + is_terminator = True + + def get_targets(self): + raise NotImplementedError(type(self)) + + +class Expr(Inst): + """ + An IR expression (an instruction which can only be part of a larger + statement). + """ + + def __init__(self, op, loc, **kws): + assert isinstance(op, str) + assert isinstance(loc, Loc) + self.op = op + self.loc = loc + self._kws = kws + + def __getattr__(self, name): + if name.startswith('_'): + return Inst.__getattr__(self, name) + return self._kws[name] + + def __setattr__(self, name, value): + if name in ('op', 'loc', '_kws'): + self.__dict__[name] = value + else: + self._kws[name] = value + + @classmethod + def binop(cls, fn, lhs, rhs, loc): + assert isinstance(fn, BuiltinFunctionType) + assert isinstance(lhs, Var) + assert isinstance(rhs, Var) + assert isinstance(loc, Loc) + op = 'binop' + return cls(op=op, loc=loc, fn=fn, lhs=lhs, rhs=rhs, + static_lhs=UNDEFINED, static_rhs=UNDEFINED) + + @classmethod + def inplace_binop(cls, fn, immutable_fn, lhs, rhs, loc): + assert isinstance(fn, BuiltinFunctionType) + assert isinstance(immutable_fn, BuiltinFunctionType) + assert isinstance(lhs, Var) + assert isinstance(rhs, Var) + assert isinstance(loc, Loc) + op = 'inplace_binop' + return cls(op=op, loc=loc, fn=fn, immutable_fn=immutable_fn, + lhs=lhs, rhs=rhs, + static_lhs=UNDEFINED, static_rhs=UNDEFINED) + + @classmethod + def unary(cls, fn, value, loc): + assert isinstance(value, (str, Var, FunctionType)) + assert isinstance(loc, Loc) + op = 'unary' + fn = UNARY_BUITINS_TO_OPERATORS.get(fn, fn) + return cls(op=op, loc=loc, fn=fn, value=value) + + @classmethod + def call(cls, func, args, kws, loc, vararg=None, varkwarg=None, target=None): + assert isinstance(func, Var) + assert isinstance(loc, Loc) + op = 'call' + return cls(op=op, loc=loc, func=func, args=args, kws=kws, + vararg=vararg, varkwarg=varkwarg, target=target) + + @classmethod + def build_tuple(cls, items, loc): + assert isinstance(loc, Loc) + op = 'build_tuple' + return cls(op=op, loc=loc, items=items) + + @classmethod + def build_list(cls, items, loc): + assert isinstance(loc, Loc) + op = 'build_list' + return cls(op=op, loc=loc, items=items) + + @classmethod + def build_set(cls, items, loc): + assert isinstance(loc, Loc) + op = 'build_set' + return cls(op=op, loc=loc, items=items) + + @classmethod + def build_map(cls, items, size, literal_value, value_indexes, loc): + assert isinstance(loc, Loc) + op = 'build_map' + return cls(op=op, loc=loc, items=items, size=size, + literal_value=literal_value, value_indexes=value_indexes) + + @classmethod + def pair_first(cls, value, loc): + assert isinstance(value, Var) + op = 'pair_first' + return cls(op=op, loc=loc, value=value) + + @classmethod + def pair_second(cls, value, loc): + assert isinstance(value, Var) + assert isinstance(loc, Loc) + op = 'pair_second' + return cls(op=op, loc=loc, value=value) + + @classmethod + def getiter(cls, value, loc): + assert isinstance(value, Var) + assert isinstance(loc, Loc) + op = 'getiter' + return cls(op=op, loc=loc, value=value) + + @classmethod + def iternext(cls, value, loc): + assert isinstance(value, Var) + assert isinstance(loc, Loc) + op = 'iternext' + return cls(op=op, loc=loc, value=value) + + @classmethod + def exhaust_iter(cls, value, count, loc): + assert isinstance(value, Var) + assert isinstance(count, int) + assert isinstance(loc, Loc) + op = 'exhaust_iter' + return cls(op=op, loc=loc, value=value, count=count) + + @classmethod + def getattr(cls, value, attr, loc): + assert isinstance(value, Var) + assert isinstance(attr, str) + assert isinstance(loc, Loc) + op = 'getattr' + return cls(op=op, loc=loc, value=value, attr=attr) + + @classmethod + def getitem(cls, value, index, loc): + assert isinstance(value, Var) + assert isinstance(index, Var) + assert isinstance(loc, Loc) + op = 'getitem' + fn = operator.getitem + return cls(op=op, loc=loc, value=value, index=index, fn=fn) + + @classmethod + def typed_getitem(cls, value, dtype, index, loc): + assert isinstance(value, Var) + assert isinstance(loc, Loc) + op = 'typed_getitem' + return cls(op=op, loc=loc, value=value, dtype=dtype, + index=index) + + @classmethod + def static_getitem(cls, value, index, index_var, loc): + assert isinstance(value, Var) + assert index_var is None or isinstance(index_var, Var) + assert isinstance(loc, Loc) + op = 'static_getitem' + fn = operator.getitem + return cls(op=op, loc=loc, value=value, index=index, + index_var=index_var, fn=fn) + + @classmethod + def cast(cls, value, loc): + """ + A node for implicit casting at the return statement + """ + assert isinstance(value, Var) + assert isinstance(loc, Loc) + op = 'cast' + return cls(op=op, value=value, loc=loc) + + @classmethod + def phi(cls, loc): + """Phi node + """ + assert isinstance(loc, Loc) + return cls(op='phi', incoming_values=[], incoming_blocks=[], loc=loc) + + @classmethod + def make_function(cls, name, code, closure, defaults, loc): + """ + A node for making a function object. + """ + assert isinstance(loc, Loc) + op = 'make_function' + return cls(op=op, name=name, code=code, closure=closure, defaults=defaults, loc=loc) + + @classmethod + def null(cls, loc): + """ + A node for null value. + + This node is not handled by type inference. It is only added by + post-typing passes. + """ + assert isinstance(loc, Loc) + op = 'null' + return cls(op=op, loc=loc) + + @classmethod + def undef(cls, loc): + """ + A node for undefined value specifically from LOAD_FAST_AND_CLEAR opcode. + """ + assert isinstance(loc, Loc) + op = 'undef' + return cls(op=op, loc=loc) + + @classmethod + def dummy(cls, op, info, loc): + """ + A node for a dummy value. + + This node is a place holder for carrying information through to a point + where it is rewritten into something valid. This node is not handled + by type inference or lowering. It's presence outside of the interpreter + renders IR as illegal. + """ + assert isinstance(loc, Loc) + assert isinstance(op, str) + return cls(op=op, info=info, loc=loc) + + def __repr__(self): + if self.op == 'call': + args = ', '.join(str(a) for a in self.args) + pres_order = self._kws.items() if config.DIFF_IR == 0 else sorted(self._kws.items()) + kws = ', '.join('%s=%s' % (k, v) for k, v in pres_order) + vararg = '*%s' % (self.vararg,) if self.vararg is not None else '' + arglist = ', '.join(filter(None, [args, vararg, kws])) + return 'call %s(%s)' % (self.func, arglist) + elif self.op == 'binop': + lhs, rhs = self.lhs, self.rhs + if self.fn == operator.contains: + lhs, rhs = rhs, lhs + fn = OPERATORS_TO_BUILTINS.get(self.fn, self.fn) + return '%s %s %s' % (lhs, fn, rhs) + else: + pres_order = self._kws.items() if config.DIFF_IR == 0 else sorted(self._kws.items()) + args = ('%s=%s' % (k, v) for k, v in pres_order) + return '%s(%s)' % (self.op, ', '.join(args)) + + def list_vars(self): + return self._rec_list_vars(self._kws) + + def infer_constant(self): + raise ConstantInferenceError('%s' % self, loc=self.loc) + + +class SetItem(Stmt): + """ + target[index] = value + """ + + def __init__(self, target, index, value, loc): + assert isinstance(target, Var) + assert isinstance(index, Var) + assert isinstance(value, Var) + assert isinstance(loc, Loc) + self.target = target + self.index = index + self.value = value + self.loc = loc + + def __repr__(self): + return '%s[%s] = %s' % (self.target, self.index, self.value) + + +class StaticSetItem(Stmt): + """ + target[constant index] = value + """ + + def __init__(self, target, index, index_var, value, loc): + assert isinstance(target, Var) + assert not isinstance(index, Var) + assert isinstance(index_var, Var) + assert isinstance(value, Var) + assert isinstance(loc, Loc) + self.target = target + self.index = index + self.index_var = index_var + self.value = value + self.loc = loc + + def __repr__(self): + return '%s[%r] = %s' % (self.target, self.index, self.value) + + +class DelItem(Stmt): + """ + del target[index] + """ + + def __init__(self, target, index, loc): + assert isinstance(target, Var) + assert isinstance(index, Var) + assert isinstance(loc, Loc) + self.target = target + self.index = index + self.loc = loc + + def __repr__(self): + return 'del %s[%s]' % (self.target, self.index) + + +class SetAttr(Stmt): + def __init__(self, target, attr, value, loc): + assert isinstance(target, Var) + assert isinstance(attr, str) + assert isinstance(value, Var) + assert isinstance(loc, Loc) + self.target = target + self.attr = attr + self.value = value + self.loc = loc + + def __repr__(self): + return '(%s).%s = %s' % (self.target, self.attr, self.value) + + +class DelAttr(Stmt): + def __init__(self, target, attr, loc): + assert isinstance(target, Var) + assert isinstance(attr, str) + assert isinstance(loc, Loc) + self.target = target + self.attr = attr + self.loc = loc + + def __repr__(self): + return 'del (%s).%s' % (self.target, self.attr) + + +class StoreMap(Stmt): + def __init__(self, dct, key, value, loc): + assert isinstance(dct, Var) + assert isinstance(key, Var) + assert isinstance(value, Var) + assert isinstance(loc, Loc) + self.dct = dct + self.key = key + self.value = value + self.loc = loc + + def __repr__(self): + return '%s[%s] = %s' % (self.dct, self.key, self.value) + + +class Del(Stmt): + def __init__(self, value, loc): + assert isinstance(value, str) + assert isinstance(loc, Loc) + self.value = value + self.loc = loc + + def __str__(self): + return "del %s" % self.value + + +class Raise(Terminator): + is_exit = True + + def __init__(self, exception, loc): + assert exception is None or isinstance(exception, Var) + assert isinstance(loc, Loc) + self.exception = exception + self.loc = loc + + def __str__(self): + return "raise %s" % self.exception + + def get_targets(self): + return [] + + +class StaticRaise(Terminator): + """ + Raise an exception class and arguments known at compile-time. + Note that if *exc_class* is None, a bare "raise" statement is implied + (i.e. re-raise the current exception). + """ + is_exit = True + + def __init__(self, exc_class, exc_args, loc): + assert exc_class is None or isinstance(exc_class, type) + assert isinstance(loc, Loc) + assert exc_args is None or isinstance(exc_args, tuple) + self.exc_class = exc_class + self.exc_args = exc_args + self.loc = loc + + def __str__(self): + if self.exc_class is None: + return " raise" + elif self.exc_args is None: + return " raise %s" % (self.exc_class,) + else: + return " raise %s(%s)" % (self.exc_class, + ", ".join(map(repr, self.exc_args))) + + def get_targets(self): + return [] + + +class DynamicRaise(Terminator): + """ + Raise an exception class and some argument *values* unknown at compile-time. + Note that if *exc_class* is None, a bare "raise" statement is implied + (i.e. re-raise the current exception). + """ + is_exit = True + + def __init__(self, exc_class, exc_args, loc): + assert exc_class is None or isinstance(exc_class, type) + assert isinstance(loc, Loc) + assert exc_args is None or isinstance(exc_args, tuple) + self.exc_class = exc_class + self.exc_args = exc_args + self.loc = loc + + def __str__(self): + if self.exc_class is None: + return " raise" + elif self.exc_args is None: + return " raise %s" % (self.exc_class,) + else: + return " raise %s(%s)" % (self.exc_class, + ", ".join(map(repr, self.exc_args))) + + def get_targets(self): + return [] + + +class TryRaise(Stmt): + """A raise statement inside a try-block + Similar to ``Raise`` but does not terminate. + """ + def __init__(self, exception, loc): + assert exception is None or isinstance(exception, Var) + assert isinstance(loc, Loc) + self.exception = exception + self.loc = loc + + def __str__(self): + return "try_raise %s" % self.exception + + +class StaticTryRaise(Stmt): + """A raise statement inside a try-block. + Similar to ``StaticRaise`` but does not terminate. + """ + def __init__(self, exc_class, exc_args, loc): + assert exc_class is None or isinstance(exc_class, type) + assert isinstance(loc, Loc) + assert exc_args is None or isinstance(exc_args, tuple) + self.exc_class = exc_class + self.exc_args = exc_args + self.loc = loc + + def __str__(self): + if self.exc_class is None: + return f"static_try_raise" + elif self.exc_args is None: + return f"static_try_raise {self.exc_class}" + else: + args = ", ".join(map(repr, self.exc_args)) + return f"static_try_raise {self.exc_class}({args})" + + +class DynamicTryRaise(Stmt): + """A raise statement inside a try-block. + Similar to ``DynamicRaise`` but does not terminate. + """ + def __init__(self, exc_class, exc_args, loc): + assert exc_class is None or isinstance(exc_class, type) + assert isinstance(loc, Loc) + assert exc_args is None or isinstance(exc_args, tuple) + self.exc_class = exc_class + self.exc_args = exc_args + self.loc = loc + + def __str__(self): + if self.exc_class is None: + return f"dynamic_try_raise" + elif self.exc_args is None: + return f"dynamic_try_raise {self.exc_class}" + else: + args = ", ".join(map(repr, self.exc_args)) + return f"dynamic_try_raise {self.exc_class}({args})" + + +class Return(Terminator): + """ + Return to caller. + """ + is_exit = True + + def __init__(self, value, loc): + assert isinstance(value, Var), type(value) + assert isinstance(loc, Loc) + self.value = value + self.loc = loc + + def __str__(self): + return 'return %s' % self.value + + def get_targets(self): + return [] + + +class Jump(Terminator): + """ + Unconditional branch. + """ + + def __init__(self, target, loc): + assert isinstance(loc, Loc) + self.target = target + self.loc = loc + + def __str__(self): + return 'jump %s' % self.target + + def get_targets(self): + return [self.target] + + +class Branch(Terminator): + """ + Conditional branch. + """ + + def __init__(self, cond, truebr, falsebr, loc): + assert isinstance(cond, Var) + assert isinstance(loc, Loc) + self.cond = cond + self.truebr = truebr + self.falsebr = falsebr + self.loc = loc + + def __str__(self): + return 'branch %s, %s, %s' % (self.cond, self.truebr, self.falsebr) + + def get_targets(self): + return [self.truebr, self.falsebr] + + +class Assign(Stmt): + """ + Assign to a variable. + """ + def __init__(self, value, target, loc): + assert isinstance(value, AbstractRHS) + assert isinstance(target, Var) + assert isinstance(loc, Loc) + self.value = value + self.target = target + self.loc = loc + + def __str__(self): + return '%s = %s' % (self.target, self.value) + + +class Print(Stmt): + """ + Print some values. + """ + def __init__(self, args, vararg, loc): + assert all(isinstance(x, Var) for x in args) + assert vararg is None or isinstance(vararg, Var) + assert isinstance(loc, Loc) + self.args = tuple(args) + self.vararg = vararg + # Constant-inferred arguments + self.consts = {} + self.loc = loc + + def __str__(self): + return 'print(%s)' % ', '.join(str(v) for v in self.args) + + +class Yield(Inst): + def __init__(self, value, loc, index): + assert isinstance(value, Var) + assert isinstance(loc, Loc) + self.value = value + self.loc = loc + self.index = index + + def __str__(self): + return 'yield %s' % (self.value,) + + def list_vars(self): + return [self.value] + + +class EnterWith(Stmt): + """Enter a "with" context + """ + def __init__(self, contextmanager, begin, end, loc): + """ + Parameters + ---------- + contextmanager : IR value + begin, end : int + The beginning and the ending offset of the with-body. + loc : ir.Loc instance + Source location + """ + assert isinstance(contextmanager, Var) + assert isinstance(loc, Loc) + self.contextmanager = contextmanager + self.begin = begin + self.end = end + self.loc = loc + + def __str__(self): + return 'enter_with {}'.format(self.contextmanager) + + def list_vars(self): + return [self.contextmanager] + + +class PopBlock(Stmt): + """Marker statement for a pop block op code""" + def __init__(self, loc): + assert isinstance(loc, Loc) + self.loc = loc + + def __str__(self): + return 'pop_block' + + +class Arg(EqualityCheckMixin, AbstractRHS): + def __init__(self, name, index, loc): + assert isinstance(name, str) + assert isinstance(index, int) + assert isinstance(loc, Loc) + self.name = name + self.index = index + self.loc = loc + + def __repr__(self): + return 'arg(%d, name=%s)' % (self.index, self.name) + + def infer_constant(self): + raise ConstantInferenceError('%s' % self, loc=self.loc) + + +class Const(EqualityCheckMixin, AbstractRHS): + def __init__(self, value, loc, use_literal_type=True): + assert isinstance(loc, Loc) + self.value = value + self.loc = loc + # Note: need better way to tell if this is a literal or not. + self.use_literal_type = use_literal_type + + def __repr__(self): + return 'const(%s, %s)' % (type(self.value).__name__, self.value) + + def infer_constant(self): + return self.value + + def __deepcopy__(self, memo): + # Override to not copy constant values in code + return Const( + value=self.value, loc=self.loc, + use_literal_type=self.use_literal_type, + ) + + +class Global(EqualityCheckMixin, AbstractRHS): + def __init__(self, name, value, loc): + assert isinstance(loc, Loc) + self.name = name + self.value = value + self.loc = loc + + def __str__(self): + return 'global(%s: %s)' % (self.name, self.value) + + def infer_constant(self): + return self.value + + def __deepcopy__(self, memo): + # don't copy value since it can fail (e.g. modules) + # value is readonly and doesn't need copying + return Global(self.name, self.value, copy.deepcopy(self.loc)) + + +class FreeVar(EqualityCheckMixin, AbstractRHS): + """ + A freevar, as loaded by LOAD_DECREF. + (i.e. a variable defined in an enclosing non-global scope) + """ + + def __init__(self, index, name, value, loc): + assert isinstance(index, int) + assert isinstance(name, str) + assert isinstance(loc, Loc) + # index inside __code__.co_freevars + self.index = index + # variable name + self.name = name + # frozen value + self.value = value + self.loc = loc + + def __str__(self): + return 'freevar(%s: %s)' % (self.name, self.value) + + def infer_constant(self): + return self.value + + def __deepcopy__(self, memo): + # Override to not copy constant values in code + return FreeVar(index=self.index, name=self.name, value=self.value, + loc=self.loc) + + + +class Var(EqualityCheckMixin, AbstractRHS): + """ + Attributes + ----------- + - scope: Scope + + - name: str + + - loc: Loc + Definition location + """ + + def __init__(self, scope, name, loc): + # NOTE: Use of scope=None should be removed. + assert scope is None or isinstance(scope, Scope) + assert isinstance(name, str) + assert isinstance(loc, Loc) + self.scope = scope + self.name = name + self.loc = loc + + def __repr__(self): + return 'Var(%s, %s)' % (self.name, self.loc.short()) + + def __str__(self): + return self.name + + @property + def is_temp(self): + return self.name.startswith("$") + + @property + def unversioned_name(self): + """The unversioned name of this variable, i.e. SSA renaming removed + """ + for k, redef_set in self.scope.var_redefinitions.items(): + if self.name in redef_set: + return k + return self.name + + @property + def versioned_names(self): + """Known versioned names for this variable, i.e. known variable names in + the scope that have been formed from applying SSA to this variable + """ + return self.scope.get_versions_of(self.unversioned_name) + + @property + def all_names(self): + """All known versioned and unversioned names for this variable + """ + return self.versioned_names | {self.unversioned_name,} + + def __deepcopy__(self, memo): + out = Var(copy.deepcopy(self.scope, memo), self.name, self.loc) + memo[id(self)] = out + return out + + +class Scope(EqualityCheckMixin): + """ + Attributes + ----------- + - parent: Scope + Parent scope + + - localvars: VarMap + Scope-local variable map + + - loc: Loc + Start of scope location + + """ + + def __init__(self, parent, loc): + assert parent is None or isinstance(parent, Scope) + assert isinstance(loc, Loc) + self.parent = parent + self.localvars = VarMap() + self.loc = loc + self.redefined = defaultdict(int) + self.var_redefinitions = defaultdict(set) + + def define(self, name, loc): + """ + Define a variable + """ + v = Var(scope=self, name=name, loc=loc) + self.localvars.define(v.name, v) + return v + + def get(self, name): + """ + Refer to a variable. Returns the latest version. + """ + if name in self.redefined: + name = "%s.%d" % (name, self.redefined[name]) + return self.get_exact(name) + + def get_exact(self, name): + """ + Refer to a variable. The returned variable has the exact + name (exact variable version). + """ + try: + return self.localvars.get(name) + except NotDefinedError: + if self.has_parent: + return self.parent.get(name) + else: + raise + + def get_or_define(self, name, loc): + if name in self.redefined: + name = "%s.%d" % (name, self.redefined[name]) + + if name not in self.localvars: + return self.define(name, loc) + else: + return self.localvars.get(name) + + def redefine(self, name, loc, rename=True): + """ + Redefine if the name is already defined + """ + if name not in self.localvars: + return self.define(name, loc) + elif not rename: + # Must use the same name if the variable is a cellvar, which + # means it could be captured in a closure. + return self.localvars.get(name) + else: + while True: + ct = self.redefined[name] + self.redefined[name] = ct + 1 + newname = "%s.%d" % (name, ct + 1) + try: + res = self.define(newname, loc) + except RedefinedError: + continue + else: + self.var_redefinitions[name].add(newname) + return res + + def get_versions_of(self, name): + """ + Gets all known versions of a given name + """ + vers = set() + def walk(thename): + redefs = self.var_redefinitions.get(thename, None) + if redefs: + for v in redefs: + vers.add(v) + walk(v) + walk(name) + return vers + + def make_temp(self, loc): + n = len(self.localvars) + v = Var(scope=self, name='$%d' % n, loc=loc) + self.localvars.define(v.name, v) + return v + + @property + def has_parent(self): + return self.parent is not None + + def __repr__(self): + return "Scope(has_parent=%r, num_vars=%d, %s)" % (self.has_parent, + len(self.localvars), + self.loc) + + +class Block(EqualityCheckMixin): + """A code block + + """ + + def __init__(self, scope, loc): + assert isinstance(scope, Scope) + assert isinstance(loc, Loc) + self.scope = scope + self.body = [] + self.loc = loc + + def copy(self): + block = Block(self.scope, self.loc) + block.body = self.body[:] + return block + + def find_exprs(self, op=None): + """ + Iterate over exprs of the given *op* in this block. + """ + for inst in self.body: + if isinstance(inst, Assign): + expr = inst.value + if isinstance(expr, Expr): + if op is None or expr.op == op: + yield expr + + def find_insts(self, cls=None): + """ + Iterate over insts of the given class in this block. + """ + for inst in self.body: + if isinstance(inst, cls): + yield inst + + def find_variable_assignment(self, name): + """ + Returns the assignment inst associated with variable "name", None if + it cannot be found. + """ + for x in self.find_insts(cls=Assign): + if x.target.name == name: + return x + return None + + def prepend(self, inst): + assert isinstance(inst, Stmt) + self.body.insert(0, inst) + + def append(self, inst): + assert isinstance(inst, Stmt) + self.body.append(inst) + + def remove(self, inst): + assert isinstance(inst, Stmt) + del self.body[self.body.index(inst)] + + def clear(self): + del self.body[:] + + def dump(self, file=None): + # Avoid early bind of sys.stdout as default value + file = file or sys.stdout + for inst in self.body: + if hasattr(inst, 'dump'): + inst.dump(file) + else: + inst_vars = sorted(str(v) for v in inst.list_vars()) + print(' %-40s %s' % (inst, inst_vars), file=file) + + @property + def terminator(self): + return self.body[-1] + + @property + def is_terminated(self): + return self.body and self.body[-1].is_terminator + + def verify(self): + if not self.is_terminated: + raise VerificationError("Missing block terminator") + # Only the last instruction can be a terminator + for inst in self.body[:-1]: + if inst.is_terminator: + raise VerificationError("Terminator before the last " + "instruction") + + def insert_after(self, stmt, other): + """ + Insert *stmt* after *other*. + """ + index = self.body.index(other) + self.body.insert(index + 1, stmt) + + def insert_before_terminator(self, stmt): + assert isinstance(stmt, Stmt) + assert self.is_terminated + self.body.insert(-1, stmt) + + def __repr__(self): + return "" % (self.loc,) + + +class Loop(SlotEqualityCheckMixin): + """Describes a loop-block + """ + __slots__ = "entry", "exit" + + def __init__(self, entry, exit): + self.entry = entry + self.exit = exit + + def __repr__(self): + args = self.entry, self.exit + return "Loop(entry=%s, exit=%s)" % args + + +class With(SlotEqualityCheckMixin): + """Describes a with-block + """ + __slots__ = "entry", "exit" + + def __init__(self, entry, exit): + self.entry = entry + self.exit = exit + + def __repr__(self): + args = self.entry, self.exit + return "With(entry=%s, exit=%s)" % args + + +class FunctionIR(object): + + def __init__(self, blocks, is_generator, func_id, loc, + definitions, arg_count, arg_names): + self.blocks = blocks + self.is_generator = is_generator + self.func_id = func_id + self.loc = loc + self.arg_count = arg_count + self.arg_names = arg_names + + self._definitions = definitions + + self._reset_analysis_variables() + + def equal_ir(self, other): + """ Checks that the IR contained within is equal to the IR in other. + Equality is defined by being equal in fundamental structure (blocks, + labels, IR node type and the order in which they are defined) and the + IR nodes being equal. IR node equality essentially comes down to + ensuring a node's `.__dict__` or `.__slots__` is equal, with the + exception of ignoring 'loc' and 'scope' entries. The upshot is that the + comparison is essentially location and scope invariant, but otherwise + behaves as unsurprisingly as possible. + """ + if type(self) is type(other): + return self.blocks == other.blocks + return False + + def diff_str(self, other): + """ + Compute a human readable difference in the IR, returns a formatted + string ready for printing. + """ + msg = [] + for label, block in self.blocks.items(): + other_blk = other.blocks.get(label, None) + if other_blk is not None: + if block != other_blk: + msg.append(("Block %s differs" % label).center(80, '-')) + # see if the instructions are just a permutation + block_del = [x for x in block.body if isinstance(x, Del)] + oth_del = [x for x in other_blk.body if isinstance(x, Del)] + if block_del != oth_del: + # this is a common issue, dels are all present, but + # order shuffled. + if sorted(block_del) == sorted(oth_del): + msg.append(("Block %s contains the same dels but " + "their order is different") % label) + if len(block.body) > len(other_blk.body): + msg.append("This block contains more statements") + elif len(block.body) < len(other_blk.body): + msg.append("Other block contains more statements") + + # find the indexes where they don't match + tmp = [] + for idx, stmts in enumerate(zip(block.body, + other_blk.body)): + b_s, o_s = stmts + if b_s != o_s: + tmp.append(idx) + + def get_pad(ablock, l): + pointer = '-> ' + sp = len(pointer) * ' ' + pad = [] + nstmt = len(ablock) + for i in range(nstmt): + if i in tmp: + item = pointer + elif i >= l: + item = pointer + else: + item = sp + pad.append(item) + return pad + + min_stmt_len = min(len(block.body), len(other_blk.body)) + + with StringIO() as buf: + it = [("self", block), ("other", other_blk)] + for name, _block in it: + buf.truncate(0) + _block.dump(file=buf) + stmts = buf.getvalue().splitlines() + pad = get_pad(_block.body, min_stmt_len) + title = ("%s: block %s" % (name, label)) + msg.append(title.center(80, '-')) + msg.extend(["{0}{1}".format(a, b) for a, b in + zip(pad, stmts)]) + if msg == []: + msg.append("IR is considered equivalent.") + return '\n'.join(msg) + + def _reset_analysis_variables(self): + + self._consts = consts.ConstantInference(self) + + # Will be computed by PostProcessor + self.generator_info = None + self.variable_lifetime = None + # { ir.Block: { variable names (potentially) alive at start of block } } + self.block_entry_vars = {} + + def derive(self, blocks, arg_count=None, arg_names=None, + force_non_generator=False, loc=None): + """ + Derive a new function IR from this one, using the given blocks, + and possibly modifying the argument count and generator flag. + + Post-processing will have to be run again on the new IR. + """ + firstblock = blocks[min(blocks)] + + new_ir = copy.copy(self) + new_ir.blocks = blocks + new_ir.loc = firstblock.loc if loc is None else loc + if force_non_generator: + new_ir.is_generator = False + if arg_count is not None: + new_ir.arg_count = arg_count + if arg_names is not None: + new_ir.arg_names = arg_names + new_ir._reset_analysis_variables() + # Make fresh func_id + new_ir.func_id = new_ir.func_id.derive() + return new_ir + + def copy(self): + new_ir = copy.copy(self) + blocks = {} + block_entry_vars = {} + for label, block in self.blocks.items(): + new_block = block.copy() + blocks[label] = new_block + if block in self.block_entry_vars: + block_entry_vars[new_block] = self.block_entry_vars[block] + new_ir.blocks = blocks + new_ir.block_entry_vars = block_entry_vars + return new_ir + + def get_block_entry_vars(self, block): + """ + Return a set of variable names possibly alive at the beginning of + the block. + """ + return self.block_entry_vars[block] + + def infer_constant(self, name): + """ + Try to infer the constant value of a given variable. + """ + if isinstance(name, Var): + name = name.name + return self._consts.infer_constant(name) + + def get_definition(self, value, lhs_only=False): + """ + Get the definition site for the given variable name or instance. + A Expr instance is returned by default, but if lhs_only is set + to True, the left-hand-side variable is returned instead. + """ + lhs = value + while True: + if isinstance(value, Var): + lhs = value + name = value.name + elif isinstance(value, str): + lhs = value + name = value + else: + return lhs if lhs_only else value + defs = self._definitions[name] + if len(defs) == 0: + raise KeyError("no definition for %r" + % (name,)) + if len(defs) > 1: + raise KeyError("more than one definition for %r" + % (name,)) + value = defs[0] + + def get_assignee(self, rhs_value, in_blocks=None): + """ + Finds the assignee for a given RHS value. If in_blocks is given the + search will be limited to the specified blocks. + """ + if in_blocks is None: + blocks = self.blocks.values() + elif isinstance(in_blocks, int): + blocks = [self.blocks[in_blocks]] + else: + blocks = [self.blocks[blk] for blk in list(in_blocks)] + + assert isinstance(rhs_value, AbstractRHS) + + for blk in blocks: + for assign in blk.find_insts(Assign): + if assign.value == rhs_value: + return assign.target + + raise ValueError("Could not find an assignee for %s" % rhs_value) + + + def dump(self, file=None): + nofile = file is None + # Avoid early bind of sys.stdout as default value + file = file or StringIO() + for offset, block in sorted(self.blocks.items()): + print('label %s:' % (offset,), file=file) + block.dump(file=file) + if nofile: + text = file.getvalue() + if config.HIGHLIGHT_DUMPS: + try: + import pygments + except ImportError: + msg = "Please install pygments to see highlighted dumps" + raise ValueError(msg) + else: + from pygments import highlight + from numba.misc.dump_style import NumbaIRLexer as lexer + from numba.misc.dump_style import by_colorscheme + from pygments.formatters import Terminal256Formatter + print(highlight(text, lexer(), Terminal256Formatter( + style=by_colorscheme()))) + else: + print(text) + + + def dump_to_string(self): + with StringIO() as sb: + self.dump(file=sb) + return sb.getvalue() + + def dump_generator_info(self, file=None): + file = file or sys.stdout + gi = self.generator_info + print("generator state variables:", sorted(gi.state_vars), file=file) + for index, yp in sorted(gi.yield_points.items()): + print("yield point #%d: live variables = %s, weak live variables = %s" + % (index, sorted(yp.live_vars), sorted(yp.weak_live_vars)), + file=file) + + def render_dot(self, filename_prefix="numba_ir", include_ir=True): + """Render the CFG of the IR with GraphViz DOT via the + ``graphviz`` python binding. + + Returns + ------- + g : graphviz.Digraph + Use `g.view()` to open the graph in the default PDF application. + """ + + try: + import graphviz as gv + except ImportError: + raise ImportError( + "The feature requires `graphviz` but it is not available. " + "Please install with `pip install graphviz`" + ) + g = gv.Digraph( + filename="{}{}.dot".format( + filename_prefix, + self.func_id.unique_name, + ) + ) + # Populate the nodes + for k, blk in self.blocks.items(): + with StringIO() as sb: + blk.dump(sb) + label = sb.getvalue() + if include_ir: + label = ''.join( + [r' {}\l'.format(x) for x in label.splitlines()], + ) + label = r"block {}\l".format(k) + label + g.node(str(k), label=label, shape='rect') + else: + label = r"{}\l".format(k) + g.node(str(k), label=label, shape='circle') + # Populate the edges + for src, blk in self.blocks.items(): + for dst in blk.terminator.get_targets(): + g.edge(str(src), str(dst)) + return g + + +# A stub for undefined global reference +class UndefinedType(EqualityCheckMixin): + + _singleton = None + + def __new__(cls): + obj = cls._singleton + if obj is not None: + return obj + else: + obj = object.__new__(cls) + cls._singleton = obj + return obj + + def __repr__(self): + return "Undefined" + + +UNDEFINED = UndefinedType() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8031aab223f7f7568d4eadd826e0fde25dbbd643 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ir_utils.py @@ -0,0 +1,2403 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numpy +import math + +import types as pytypes +import collections +import warnings + +import numba +from numba.core.extending import _Intrinsic +from numba.core import types, typing, ir, analysis, postproc, rewrites, config +from numba.core.typing.templates import signature +from numba.core.analysis import (compute_live_map, compute_use_defs, + compute_cfg_from_blocks) +from numba.core.errors import (TypingError, UnsupportedError, + NumbaPendingDeprecationWarning, + CompilerError) + +import copy + +_unique_var_count = 0 + + +def mk_unique_var(prefix): + global _unique_var_count + var = prefix + "." + str(_unique_var_count) + _unique_var_count = _unique_var_count + 1 + return var + + +class _MaxLabel: + def __init__(self, value=0): + self._value = value + + def next(self): + self._value += 1 + return self._value + + def update(self, newval): + self._value = max(newval, self._value) + + +_the_max_label = _MaxLabel() +del _MaxLabel + + +def get_unused_var_name(prefix, var_table): + """ Get a new var name with a given prefix and + make sure it is unused in the given variable table. + """ + cur = 0 + while True: + var = prefix + str(cur) + if var not in var_table: + return var + cur += 1 + + +def next_label(): + return _the_max_label.next() + + +def mk_alloc(typingctx, typemap, calltypes, lhs, size_var, dtype, scope, loc, + lhs_typ): + """generate an array allocation with np.empty() and return list of nodes. + size_var can be an int variable or tuple of int variables. + lhs_typ is the type of the array being allocated. + """ + out = [] + ndims = 1 + size_typ = types.intp + if isinstance(size_var, tuple): + if len(size_var) == 1: + size_var = size_var[0] + size_var = convert_size_to_var(size_var, typemap, scope, loc, out) + else: + # tuple_var = build_tuple([size_var...]) + ndims = len(size_var) + tuple_var = ir.Var(scope, mk_unique_var("$tuple_var"), loc) + if typemap: + typemap[tuple_var.name] = types.containers.UniTuple( + types.intp, ndims) + # constant sizes need to be assigned to vars + new_sizes = [convert_size_to_var(s, typemap, scope, loc, out) + for s in size_var] + tuple_call = ir.Expr.build_tuple(new_sizes, loc) + tuple_assign = ir.Assign(tuple_call, tuple_var, loc) + out.append(tuple_assign) + size_var = tuple_var + size_typ = types.containers.UniTuple(types.intp, ndims) + if hasattr(lhs_typ, "__allocate__"): + return lhs_typ.__allocate__( + typingctx, + typemap, + calltypes, + lhs, + size_var, + dtype, + scope, + loc, + lhs_typ, + size_typ, + out, + ) + # g_np_var = Global(numpy) + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + if typemap: + typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + # attr call: empty_attr = getattr(g_np_var, empty) + empty_attr_call = ir.Expr.getattr(g_np_var, "empty", loc) + attr_var = ir.Var(scope, mk_unique_var("$empty_attr_attr"), loc) + if typemap: + typemap[attr_var.name] = get_np_ufunc_typ(numpy.empty, typingctx) + attr_assign = ir.Assign(empty_attr_call, attr_var, loc) + # Assume str(dtype) returns a valid type + dtype_str = str(dtype) + # alloc call: lhs = empty_attr(size_var, typ_var) + typ_var = ir.Var(scope, mk_unique_var("$np_typ_var"), loc) + if typemap: + typemap[typ_var.name] = types.functions.NumberClass(dtype) + # If dtype is a datetime/timedelta with a unit, + # then it won't return a valid type and instead can be created + # with a string. i.e. "datetime64[ns]") + if (isinstance(dtype, (types.NPDatetime, types.NPTimedelta)) and + dtype.unit != ''): + typename_const = ir.Const(dtype_str, loc) + typ_var_assign = ir.Assign(typename_const, typ_var, loc) + else: + if dtype_str=='bool': + # empty doesn't like 'bool' sometimes (e.g. kmeans example) + dtype_str = 'bool_' + np_typ_getattr = ir.Expr.getattr(g_np_var, dtype_str, loc) + typ_var_assign = ir.Assign(np_typ_getattr, typ_var, loc) + alloc_call = ir.Expr.call(attr_var, [size_var, typ_var], (), loc) + + if calltypes: + cac = typemap[attr_var.name].get_call_type( + typingctx, [size_typ, types.functions.NumberClass(dtype)], {}) + # By default, all calls to "empty" are typed as returning a standard + # NumPy ndarray. If we are allocating a ndarray subclass here then + # just change the return type to be that of the subclass. + cac._return_type = (lhs_typ.copy(layout='C') + if lhs_typ.layout == 'F' + else lhs_typ) + calltypes[alloc_call] = cac + if lhs_typ.layout == 'F': + empty_c_typ = lhs_typ.copy(layout='C') + empty_c_var = ir.Var(scope, mk_unique_var("$empty_c_var"), loc) + if typemap: + typemap[empty_c_var.name] = lhs_typ.copy(layout='C') + empty_c_assign = ir.Assign(alloc_call, empty_c_var, loc) + + # attr call: asfortranarray = getattr(g_np_var, asfortranarray) + asfortranarray_attr_call = ir.Expr.getattr(g_np_var, "asfortranarray", loc) + afa_attr_var = ir.Var(scope, mk_unique_var("$asfortran_array_attr"), loc) + if typemap: + typemap[afa_attr_var.name] = get_np_ufunc_typ(numpy.asfortranarray, typingctx) + afa_attr_assign = ir.Assign(asfortranarray_attr_call, afa_attr_var, loc) + # call asfortranarray + asfortranarray_call = ir.Expr.call(afa_attr_var, [empty_c_var], (), loc) + if calltypes: + calltypes[asfortranarray_call] = typemap[afa_attr_var.name].get_call_type( + typingctx, [empty_c_typ], {}) + + asfortranarray_assign = ir.Assign(asfortranarray_call, lhs, loc) + + out.extend([g_np_assign, attr_assign, typ_var_assign, empty_c_assign, + afa_attr_assign, asfortranarray_assign]) + else: + alloc_assign = ir.Assign(alloc_call, lhs, loc) + out.extend([g_np_assign, attr_assign, typ_var_assign, alloc_assign]) + + return out + + +def convert_size_to_var(size_var, typemap, scope, loc, nodes): + if isinstance(size_var, int): + new_size = ir.Var(scope, mk_unique_var("$alloc_size"), loc) + if typemap: + typemap[new_size.name] = types.intp + size_assign = ir.Assign(ir.Const(size_var, loc), new_size, loc) + nodes.append(size_assign) + return new_size + assert isinstance(size_var, ir.Var) + return size_var + + +def get_np_ufunc_typ(func, typingctx): + """get type of the incoming function + + Resolve using the context for target-awareness + """ + try: + return typingctx.resolve_value_type(func) + except TypingError: + raise RuntimeError("type for func ", func, " not found") + + +def mk_range_block(typemap, start, stop, step, calltypes, scope, loc): + """make a block that initializes loop range and iteration variables. + target label in jump needs to be set. + """ + # g_range_var = Global(range) + g_range_var = ir.Var(scope, mk_unique_var("$range_g_var"), loc) + typemap[g_range_var.name] = get_global_func_typ(range) + g_range = ir.Global('range', range, loc) + g_range_assign = ir.Assign(g_range, g_range_var, loc) + arg_nodes, args = _mk_range_args(typemap, start, stop, step, scope, loc) + # range_call_var = call g_range_var(start, stop, step) + range_call = ir.Expr.call(g_range_var, args, (), loc) + calltypes[range_call] = typemap[g_range_var.name].get_call_type( + typing.Context(), [types.intp] * len(args), {}) + #signature(types.range_state64_type, types.intp) + range_call_var = ir.Var(scope, mk_unique_var("$range_c_var"), loc) + typemap[range_call_var.name] = types.iterators.RangeType(types.intp) + range_call_assign = ir.Assign(range_call, range_call_var, loc) + # iter_var = getiter(range_call_var) + iter_call = ir.Expr.getiter(range_call_var, loc) + calltype_sig = signature(types.range_iter64_type, types.range_state64_type) + calltypes[iter_call] = calltype_sig + iter_var = ir.Var(scope, mk_unique_var("$iter_var"), loc) + typemap[iter_var.name] = types.iterators.RangeIteratorType(types.intp) + iter_call_assign = ir.Assign(iter_call, iter_var, loc) + # $phi = iter_var + phi_var = ir.Var(scope, mk_unique_var("$phi"), loc) + typemap[phi_var.name] = types.iterators.RangeIteratorType(types.intp) + phi_assign = ir.Assign(iter_var, phi_var, loc) + # jump to header + jump_header = ir.Jump(-1, loc) + range_block = ir.Block(scope, loc) + range_block.body = arg_nodes + [g_range_assign, range_call_assign, + iter_call_assign, phi_assign, jump_header] + return range_block + + +def _mk_range_args(typemap, start, stop, step, scope, loc): + nodes = [] + if isinstance(stop, ir.Var): + g_stop_var = stop + else: + assert isinstance(stop, int) + g_stop_var = ir.Var(scope, mk_unique_var("$range_stop"), loc) + if typemap: + typemap[g_stop_var.name] = types.intp + stop_assign = ir.Assign(ir.Const(stop, loc), g_stop_var, loc) + nodes.append(stop_assign) + if start == 0 and step == 1: + return nodes, [g_stop_var] + + if isinstance(start, ir.Var): + g_start_var = start + else: + assert isinstance(start, int) + g_start_var = ir.Var(scope, mk_unique_var("$range_start"), loc) + if typemap: + typemap[g_start_var.name] = types.intp + start_assign = ir.Assign(ir.Const(start, loc), g_start_var, loc) + nodes.append(start_assign) + if step == 1: + return nodes, [g_start_var, g_stop_var] + + if isinstance(step, ir.Var): + g_step_var = step + else: + assert isinstance(step, int) + g_step_var = ir.Var(scope, mk_unique_var("$range_step"), loc) + if typemap: + typemap[g_step_var.name] = types.intp + step_assign = ir.Assign(ir.Const(step, loc), g_step_var, loc) + nodes.append(step_assign) + + return nodes, [g_start_var, g_stop_var, g_step_var] + + +def get_global_func_typ(func): + """get type variable for func() from builtin registry""" + for (k, v) in typing.templates.builtin_registry.globals: + if k == func: + return v + raise RuntimeError("func type not found {}".format(func)) + + +def mk_loop_header(typemap, phi_var, calltypes, scope, loc): + """make a block that is a loop header updating iteration variables. + target labels in branch need to be set. + """ + # iternext_var = iternext(phi_var) + iternext_var = ir.Var(scope, mk_unique_var("$iternext_var"), loc) + typemap[iternext_var.name] = types.containers.Pair( + types.intp, types.boolean) + iternext_call = ir.Expr.iternext(phi_var, loc) + range_iter_type = types.range_iter64_type + calltypes[iternext_call] = signature( + types.containers.Pair( + types.intp, + types.boolean), + range_iter_type) + iternext_assign = ir.Assign(iternext_call, iternext_var, loc) + # pair_first_var = pair_first(iternext_var) + pair_first_var = ir.Var(scope, mk_unique_var("$pair_first_var"), loc) + typemap[pair_first_var.name] = types.intp + pair_first_call = ir.Expr.pair_first(iternext_var, loc) + pair_first_assign = ir.Assign(pair_first_call, pair_first_var, loc) + # pair_second_var = pair_second(iternext_var) + pair_second_var = ir.Var(scope, mk_unique_var("$pair_second_var"), loc) + typemap[pair_second_var.name] = types.boolean + pair_second_call = ir.Expr.pair_second(iternext_var, loc) + pair_second_assign = ir.Assign(pair_second_call, pair_second_var, loc) + # phi_b_var = pair_first_var + phi_b_var = ir.Var(scope, mk_unique_var("$phi"), loc) + typemap[phi_b_var.name] = types.intp + phi_b_assign = ir.Assign(pair_first_var, phi_b_var, loc) + # branch pair_second_var body_block out_block + branch = ir.Branch(pair_second_var, -1, -1, loc) + header_block = ir.Block(scope, loc) + header_block.body = [iternext_assign, pair_first_assign, + pair_second_assign, phi_b_assign, branch] + return header_block + + +def legalize_names(varnames): + """returns a dictionary for conversion of variable names to legal + parameter names. + """ + var_map = {} + for var in varnames: + new_name = var.replace("_", "__").replace("$", "_").replace(".", "_") + assert new_name not in var_map + var_map[var] = new_name + return var_map + + +def get_name_var_table(blocks): + """create a mapping from variable names to their ir.Var objects""" + def get_name_var_visit(var, namevar): + namevar[var.name] = var + return var + namevar = {} + visit_vars(blocks, get_name_var_visit, namevar) + return namevar + + +def replace_var_names(blocks, namedict): + """replace variables (ir.Var to ir.Var) from dictionary (name -> name)""" + # remove identity values to avoid infinite loop + new_namedict = {} + for l, r in namedict.items(): + if l != r: + new_namedict[l] = r + + def replace_name(var, namedict): + assert isinstance(var, ir.Var) + while var.name in namedict: + var = ir.Var(var.scope, namedict[var.name], var.loc) + return var + visit_vars(blocks, replace_name, new_namedict) + + +def replace_var_callback(var, vardict): + assert isinstance(var, ir.Var) + while var.name in vardict.keys(): + assert(vardict[var.name].name != var.name) + new_var = vardict[var.name] + var = ir.Var(new_var.scope, new_var.name, new_var.loc) + return var + + +def replace_vars(blocks, vardict): + """replace variables (ir.Var to ir.Var) from dictionary (name -> ir.Var)""" + # remove identity values to avoid infinite loop + new_vardict = {} + for l, r in vardict.items(): + if l != r.name: + new_vardict[l] = r + visit_vars(blocks, replace_var_callback, new_vardict) + + +def replace_vars_stmt(stmt, vardict): + visit_vars_stmt(stmt, replace_var_callback, vardict) + + +def replace_vars_inner(node, vardict): + return visit_vars_inner(node, replace_var_callback, vardict) + + +# other packages that define new nodes add calls to visit variables in them +# format: {type:function} +visit_vars_extensions = {} + + +def visit_vars(blocks, callback, cbdata): + """go over statements of block bodies and replace variable names with + dictionary. + """ + for block in blocks.values(): + for stmt in block.body: + visit_vars_stmt(stmt, callback, cbdata) + return + + +def visit_vars_stmt(stmt, callback, cbdata): + # let external calls handle stmt if type matches + for t, f in visit_vars_extensions.items(): + if isinstance(stmt, t): + f(stmt, callback, cbdata) + return + if isinstance(stmt, ir.Assign): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.value = visit_vars_inner(stmt.value, callback, cbdata) + elif isinstance(stmt, ir.Arg): + stmt.name = visit_vars_inner(stmt.name, callback, cbdata) + elif isinstance(stmt, ir.Return): + stmt.value = visit_vars_inner(stmt.value, callback, cbdata) + elif isinstance(stmt, ir.Raise): + stmt.exception = visit_vars_inner(stmt.exception, callback, cbdata) + elif isinstance(stmt, ir.Branch): + stmt.cond = visit_vars_inner(stmt.cond, callback, cbdata) + elif isinstance(stmt, ir.Jump): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + elif isinstance(stmt, ir.Del): + # Because Del takes only a var name, we make up by + # constructing a temporary variable. + var = ir.Var(None, stmt.value, stmt.loc) + var = visit_vars_inner(var, callback, cbdata) + stmt.value = var.name + elif isinstance(stmt, ir.DelAttr): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.attr = visit_vars_inner(stmt.attr, callback, cbdata) + elif isinstance(stmt, ir.SetAttr): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.attr = visit_vars_inner(stmt.attr, callback, cbdata) + stmt.value = visit_vars_inner(stmt.value, callback, cbdata) + elif isinstance(stmt, ir.DelItem): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.index = visit_vars_inner(stmt.index, callback, cbdata) + elif isinstance(stmt, ir.StaticSetItem): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.index_var = visit_vars_inner(stmt.index_var, callback, cbdata) + stmt.value = visit_vars_inner(stmt.value, callback, cbdata) + elif isinstance(stmt, ir.SetItem): + stmt.target = visit_vars_inner(stmt.target, callback, cbdata) + stmt.index = visit_vars_inner(stmt.index, callback, cbdata) + stmt.value = visit_vars_inner(stmt.value, callback, cbdata) + elif isinstance(stmt, ir.Print): + stmt.args = [visit_vars_inner(x, callback, cbdata) for x in stmt.args] + else: + # TODO: raise NotImplementedError("no replacement for IR node: ", stmt) + pass + return + + +def visit_vars_inner(node, callback, cbdata): + if isinstance(node, ir.Var): + return callback(node, cbdata) + elif isinstance(node, list): + return [visit_vars_inner(n, callback, cbdata) for n in node] + elif isinstance(node, tuple): + return tuple([visit_vars_inner(n, callback, cbdata) for n in node]) + elif isinstance(node, ir.Expr): + # if node.op in ['binop', 'inplace_binop']: + # lhs = node.lhs.name + # rhs = node.rhs.name + # node.lhs.name = callback, cbdata.get(lhs, lhs) + # node.rhs.name = callback, cbdata.get(rhs, rhs) + for arg in node._kws.keys(): + node._kws[arg] = visit_vars_inner(node._kws[arg], callback, cbdata) + elif isinstance(node, ir.Yield): + node.value = visit_vars_inner(node.value, callback, cbdata) + return node + + +add_offset_to_labels_extensions = {} + + +def add_offset_to_labels(blocks, offset): + """add an offset to all block labels and jump/branch targets + """ + new_blocks = {} + for l, b in blocks.items(): + # some parfor last blocks might be empty + term = None + if b.body: + term = b.body[-1] + for inst in b.body: + for T, f in add_offset_to_labels_extensions.items(): + if isinstance(inst, T): + f_max = f(inst, offset) + if isinstance(term, ir.Jump): + b.body[-1] = ir.Jump(term.target + offset, term.loc) + if isinstance(term, ir.Branch): + b.body[-1] = ir.Branch(term.cond, term.truebr + offset, + term.falsebr + offset, term.loc) + new_blocks[l + offset] = b + return new_blocks + + +find_max_label_extensions = {} + + +def find_max_label(blocks): + max_label = 0 + for l, b in blocks.items(): + term = None + if b.body: + term = b.body[-1] + for inst in b.body: + for T, f in find_max_label_extensions.items(): + if isinstance(inst, T): + f_max = f(inst) + if f_max > max_label: + max_label = f_max + if l > max_label: + max_label = l + return max_label + + +def flatten_labels(blocks): + """makes the labels in range(0, len(blocks)), useful to compare CFGs + """ + # first bulk move the labels out of the rewrite range + blocks = add_offset_to_labels(blocks, find_max_label(blocks) + 1) + # order them in topo order because it's easier to read + new_blocks = {} + topo_order = find_topo_order(blocks) + l_map = dict() + idx = 0 + for x in topo_order: + l_map[x] = idx + idx += 1 + + for t_node in topo_order: + b = blocks[t_node] + # some parfor last blocks might be empty + term = None + if b.body: + term = b.body[-1] + if isinstance(term, ir.Jump): + b.body[-1] = ir.Jump(l_map[term.target], term.loc) + if isinstance(term, ir.Branch): + b.body[-1] = ir.Branch(term.cond, l_map[term.truebr], + l_map[term.falsebr], term.loc) + new_blocks[l_map[t_node]] = b + return new_blocks + + +def remove_dels(blocks): + """remove ir.Del nodes""" + for block in blocks.values(): + new_body = [] + for stmt in block.body: + if not isinstance(stmt, ir.Del): + new_body.append(stmt) + block.body = new_body + return + + +def remove_args(blocks): + """remove ir.Arg nodes""" + for block in blocks.values(): + new_body = [] + for stmt in block.body: + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Arg): + continue + new_body.append(stmt) + block.body = new_body + return + + +def dead_code_elimination(func_ir, typemap=None, alias_map=None, + arg_aliases=None): + """ Performs dead code elimination and leaves the IR in a valid state on + exit + """ + do_post_proc = False + while (remove_dead(func_ir.blocks, func_ir.arg_names, func_ir, typemap, + alias_map, arg_aliases)): + do_post_proc = True + + if do_post_proc: + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + +def remove_dead(blocks, args, func_ir, typemap=None, alias_map=None, arg_aliases=None): + """dead code elimination using liveness and CFG info. + Returns True if something has been removed, or False if nothing is removed. + """ + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + call_table, _ = get_call_table(blocks) + if alias_map is None or arg_aliases is None: + alias_map, arg_aliases = find_potential_aliases(blocks, args, typemap, + func_ir) + if config.DEBUG_ARRAY_OPT >= 1: + print("args:", args) + print("alias map:", alias_map) + print("arg_aliases:", arg_aliases) + print("live_map:", live_map) + print("usemap:", usedefs.usemap) + print("defmap:", usedefs.defmap) + # keep set for easier search + alias_set = set(alias_map.keys()) + + removed = False + for label, block in blocks.items(): + # find live variables at each statement to delete dead assignment + lives = {v.name for v in block.terminator.list_vars()} + if config.DEBUG_ARRAY_OPT >= 2: + print("remove_dead processing block", label, lives) + # find live variables at the end of block + for out_blk, _data in cfg.successors(label): + if config.DEBUG_ARRAY_OPT >= 2: + print("succ live_map", out_blk, live_map[out_blk]) + lives |= live_map[out_blk] + removed |= remove_dead_block(block, lives, call_table, arg_aliases, + alias_map, alias_set, func_ir, typemap) + + return removed + + +# other packages that define new nodes add calls to remove dead code in them +# format: {type:function} +remove_dead_extensions = {} + + +def remove_dead_block(block, lives, call_table, arg_aliases, alias_map, + alias_set, func_ir, typemap): + """remove dead code using liveness info. + Mutable arguments (e.g. arrays) that are not definitely assigned are live + after return of function. + """ + # TODO: find mutable args that are not definitely assigned instead of + # assuming all args are live after return + removed = False + + # add statements in reverse order + new_body = [block.terminator] + # for each statement in reverse order, excluding terminator + for stmt in reversed(block.body[:-1]): + if config.DEBUG_ARRAY_OPT >= 2: + print("remove_dead_block", stmt) + # aliases of lives are also live + alias_lives = set() + init_alias_lives = lives & alias_set + for v in init_alias_lives: + alias_lives |= alias_map[v] + lives_n_aliases = lives | alias_lives | arg_aliases + + # let external calls handle stmt if type matches + if type(stmt) in remove_dead_extensions: + f = remove_dead_extensions[type(stmt)] + stmt = f(stmt, lives, lives_n_aliases, arg_aliases, alias_map, func_ir, + typemap) + if stmt is None: + if config.DEBUG_ARRAY_OPT >= 2: + print("Statement was removed.") + removed = True + continue + + # ignore assignments that their lhs is not live or lhs==rhs + if isinstance(stmt, ir.Assign): + lhs = stmt.target + rhs = stmt.value + if lhs.name not in lives and has_no_side_effect( + rhs, lives_n_aliases, call_table): + if config.DEBUG_ARRAY_OPT >= 2: + print("Statement was removed.") + removed = True + continue + if isinstance(rhs, ir.Var) and lhs.name == rhs.name: + if config.DEBUG_ARRAY_OPT >= 2: + print("Statement was removed.") + removed = True + continue + # TODO: remove other nodes like SetItem etc. + + if isinstance(stmt, ir.Del): + if stmt.value not in lives: + if config.DEBUG_ARRAY_OPT >= 2: + print("Statement was removed.") + removed = True + continue + + if isinstance(stmt, ir.SetItem): + name = stmt.target.name + if name not in lives_n_aliases: + if config.DEBUG_ARRAY_OPT >= 2: + print("Statement was removed.") + continue + + if type(stmt) in analysis.ir_extension_usedefs: + def_func = analysis.ir_extension_usedefs[type(stmt)] + uses, defs = def_func(stmt) + lives -= defs + lives |= uses + else: + lives |= {v.name for v in stmt.list_vars()} + if isinstance(stmt, ir.Assign): + # make sure lhs is not used in rhs, e.g. a = g(a) + if isinstance(stmt.value, ir.Expr): + rhs_vars = {v.name for v in stmt.value.list_vars()} + if lhs.name not in rhs_vars: + lives.remove(lhs.name) + else: + lives.remove(lhs.name) + + new_body.append(stmt) + new_body.reverse() + block.body = new_body + return removed + +# list of functions +remove_call_handlers = [] + +def remove_dead_random_call(rhs, lives, call_list): + if len(call_list) == 3 and call_list[1:] == ['random', numpy]: + return call_list[0] not in {'seed', 'shuffle'} + return False + +remove_call_handlers.append(remove_dead_random_call) + +def has_no_side_effect(rhs, lives, call_table): + """ Returns True if this expression has no side effects that + would prevent re-ordering. + """ + from numba.parfors import array_analysis, parfor + from numba.misc.special import prange + if isinstance(rhs, ir.Expr) and rhs.op == 'call': + func_name = rhs.func.name + if func_name not in call_table or call_table[func_name] == []: + return False + call_list = call_table[func_name] + if (call_list == ['empty', numpy] or + call_list == [slice] or + call_list == ['stencil', numba] or + call_list == ['log', numpy] or + call_list == ['dtype', numpy] or + call_list == [array_analysis.wrap_index] or + call_list == [prange] or + call_list == ['prange', numba] or + call_list == ['pndindex', numba] or + call_list == [parfor.internal_prange] or + call_list == ['ceil', math] or + call_list == [max] or + call_list == [int]): + return True + elif (isinstance(call_list[0], _Intrinsic) and + (call_list[0]._name == 'empty_inferred' or + call_list[0]._name == 'unsafe_empty_inferred')): + return True + from numba.core.registry import CPUDispatcher + from numba.np.linalg import dot_3_mv_check_args + if isinstance(call_list[0], CPUDispatcher): + py_func = call_list[0].py_func + if py_func == dot_3_mv_check_args: + return True + for f in remove_call_handlers: + if f(rhs, lives, call_list): + return True + return False + if isinstance(rhs, ir.Expr) and rhs.op == 'inplace_binop': + return rhs.lhs.name not in lives + if isinstance(rhs, ir.Yield): + return False + if isinstance(rhs, ir.Expr) and rhs.op == 'pair_first': + # don't remove pair_first since prange looks for it + return False + return True + +is_pure_extensions = [] + +def is_pure(rhs, lives, call_table): + """ Returns True if every time this expression is evaluated it + returns the same result. This is not the case for things + like calls to numpy.random. + """ + if isinstance(rhs, ir.Expr): + if rhs.op == 'call': + func_name = rhs.func.name + if func_name not in call_table or call_table[func_name] == []: + return False + call_list = call_table[func_name] + if (call_list == [slice] or + call_list == ['log', numpy] or + call_list == ['empty', numpy] or + call_list == ['ceil', math] or + call_list == [max] or + call_list == [int]): + return True + for f in is_pure_extensions: + if f(rhs, lives, call_list): + return True + return False + elif rhs.op == 'getiter' or rhs.op == 'iternext': + return False + if isinstance(rhs, ir.Yield): + return False + return True + +def is_const_call(module_name, func_name): + # Returns True if there is no state in the given module changed by the given function. + if module_name == 'numpy': + if func_name in ['empty']: + return True + return False + +alias_analysis_extensions = {} +alias_func_extensions = {} + +def get_canonical_alias(v, alias_map): + if v not in alias_map: + return v + + v_aliases = sorted(list(alias_map[v])) + return v_aliases[0] + +def find_potential_aliases(blocks, args, typemap, func_ir, alias_map=None, + arg_aliases=None): + "find all array aliases and argument aliases to avoid remove as dead" + if alias_map is None: + alias_map = {} + if arg_aliases is None: + arg_aliases = set(a for a in args if not is_immutable_type(a, typemap)) + + # update definitions since they are not guaranteed to be up-to-date + # FIXME keep definitions up-to-date to avoid the need for rebuilding + func_ir._definitions = build_definitions(func_ir.blocks) + np_alias_funcs = ['ravel', 'transpose', 'reshape'] + + for bl in blocks.values(): + for instr in bl.body: + if type(instr) in alias_analysis_extensions: + f = alias_analysis_extensions[type(instr)] + f(instr, args, typemap, func_ir, alias_map, arg_aliases) + if isinstance(instr, ir.Assign): + expr = instr.value + lhs = instr.target.name + # only mutable types can alias + if is_immutable_type(lhs, typemap): + continue + if isinstance(expr, ir.Var) and lhs!=expr.name: + _add_alias(lhs, expr.name, alias_map, arg_aliases) + # subarrays like A = B[0] for 2D B + if (isinstance(expr, ir.Expr) and (expr.op == 'cast' or + expr.op in ['getitem', 'static_getitem'])): + _add_alias(lhs, expr.value.name, alias_map, arg_aliases) + if isinstance(expr, ir.Expr) and expr.op == 'inplace_binop': + _add_alias(lhs, expr.lhs.name, alias_map, arg_aliases) + # array attributes like A.T + if (isinstance(expr, ir.Expr) and expr.op == 'getattr' + and expr.attr in ['T', 'ctypes', 'flat']): + _add_alias(lhs, expr.value.name, alias_map, arg_aliases) + # a = b.c. a should alias b + if (isinstance(expr, ir.Expr) and expr.op == 'getattr' + and expr.attr not in ['shape'] + and expr.value.name in arg_aliases): + _add_alias(lhs, expr.value.name, alias_map, arg_aliases) + # calls that can create aliases such as B = A.ravel() + if isinstance(expr, ir.Expr) and expr.op == 'call': + fdef = guard(find_callname, func_ir, expr, typemap) + # TODO: sometimes gufunc backend creates duplicate code + # causing find_callname to fail. Example: test_argmax + # ignored here since those cases don't create aliases + # but should be fixed in general + if fdef is None: + continue + fname, fmod = fdef + if fdef in alias_func_extensions: + alias_func = alias_func_extensions[fdef] + alias_func(lhs, expr.args, alias_map, arg_aliases) + if fmod == 'numpy' and fname in np_alias_funcs: + _add_alias(lhs, expr.args[0].name, alias_map, arg_aliases) + if isinstance(fmod, ir.Var) and fname in np_alias_funcs: + _add_alias(lhs, fmod.name, alias_map, arg_aliases) + + # copy to avoid changing size during iteration + old_alias_map = copy.deepcopy(alias_map) + # combine all aliases transitively + for v in old_alias_map: + for w in old_alias_map[v]: + alias_map[v] |= alias_map[w] + for w in old_alias_map[v]: + alias_map[w] = alias_map[v] + + return alias_map, arg_aliases + +def _add_alias(lhs, rhs, alias_map, arg_aliases): + if rhs in arg_aliases: + arg_aliases.add(lhs) + else: + if rhs not in alias_map: + alias_map[rhs] = set() + if lhs not in alias_map: + alias_map[lhs] = set() + alias_map[rhs].add(lhs) + alias_map[lhs].add(rhs) + return + +def is_immutable_type(var, typemap): + # Conservatively, assume mutable if type not available + if typemap is None or var not in typemap: + return False + typ = typemap[var] + # TODO: add more immutable types + if isinstance(typ, (types.Number, types.scalars._NPDatetimeBase, + types.iterators.RangeType)): + return True + if typ==types.string: + return True + # conservatively, assume mutable + return False + +def copy_propagate(blocks, typemap): + """compute copy propagation information for each block using fixed-point + iteration on data flow equations: + in_b = intersect(predec(B)) + out_b = gen_b | (in_b - kill_b) + """ + cfg = compute_cfg_from_blocks(blocks) + entry = cfg.entry_point() + + # format: dict of block labels to copies as tuples + # label -> (l,r) + c_data = init_copy_propagate_data(blocks, entry, typemap) + (gen_copies, all_copies, kill_copies, in_copies, out_copies) = c_data + + old_point = None + new_point = copy.deepcopy(out_copies) + # comparison works since dictionary of built-in types + while old_point != new_point: + for label in blocks.keys(): + if label == entry: + continue + predecs = [i for i, _d in cfg.predecessors(label)] + # in_b = intersect(predec(B)) + in_copies[label] = out_copies[predecs[0]].copy() + for p in predecs: + in_copies[label] &= out_copies[p] + + # out_b = gen_b | (in_b - kill_b) + out_copies[label] = (gen_copies[label] + | (in_copies[label] - kill_copies[label])) + old_point = new_point + new_point = copy.deepcopy(out_copies) + if config.DEBUG_ARRAY_OPT >= 1: + print("copy propagate out_copies:", out_copies) + return in_copies, out_copies + + +def init_copy_propagate_data(blocks, entry, typemap): + """get initial condition of copy propagation data flow for each block. + """ + # gen is all definite copies, extra_kill is additional ones that may hit + # for example, parfors can have control flow so they may hit extra copies + gen_copies, extra_kill = get_block_copies(blocks, typemap) + # set of all program copies + all_copies = set() + for l, s in gen_copies.items(): + all_copies |= gen_copies[l] + kill_copies = {} + for label, gen_set in gen_copies.items(): + kill_copies[label] = set() + for lhs, rhs in all_copies: + if lhs in extra_kill[label] or rhs in extra_kill[label]: + kill_copies[label].add((lhs, rhs)) + # a copy is killed if it is not in this block and lhs or rhs are + # assigned in this block + assigned = {lhs for lhs, rhs in gen_set} + if ((lhs, rhs) not in gen_set + and (lhs in assigned or rhs in assigned)): + kill_copies[label].add((lhs, rhs)) + # set initial values + # all copies are in for all blocks except entry + in_copies = {l: all_copies.copy() for l in blocks.keys()} + in_copies[entry] = set() + out_copies = {} + for label in blocks.keys(): + # out_b = gen_b | (in_b - kill_b) + out_copies[label] = (gen_copies[label] + | (in_copies[label] - kill_copies[label])) + out_copies[entry] = gen_copies[entry] + return (gen_copies, all_copies, kill_copies, in_copies, out_copies) + + +# other packages that define new nodes add calls to get copies in them +# format: {type:function} +copy_propagate_extensions = {} + + +def get_block_copies(blocks, typemap): + """get copies generated and killed by each block + """ + block_copies = {} + extra_kill = {} + for label, block in blocks.items(): + assign_dict = {} + extra_kill[label] = set() + # assignments as dict to replace with latest value + for stmt in block.body: + for T, f in copy_propagate_extensions.items(): + if isinstance(stmt, T): + gen_set, kill_set = f(stmt, typemap) + for lhs, rhs in gen_set: + assign_dict[lhs] = rhs + # if a=b is in dict and b is killed, a is also killed + new_assign_dict = {} + for l, r in assign_dict.items(): + if l not in kill_set and r not in kill_set: + new_assign_dict[l] = r + if r in kill_set: + extra_kill[label].add(l) + assign_dict = new_assign_dict + extra_kill[label] |= kill_set + if isinstance(stmt, ir.Assign): + lhs = stmt.target.name + if isinstance(stmt.value, ir.Var): + rhs = stmt.value.name + # copy is valid only if same type (see + # TestCFunc.test_locals) + # Some transformations can produce assignments of the + # form A = A. We don't put these mapping in the + # copy propagation set because then you get cycles and + # infinite loops in the replacement phase. + if typemap[lhs] == typemap[rhs] and lhs != rhs: + assign_dict[lhs] = rhs + continue + if isinstance(stmt.value, + ir.Expr) and stmt.value.op == 'inplace_binop': + in1_var = stmt.value.lhs.name + in1_typ = typemap[in1_var] + # inplace_binop assigns first operand if mutable + if not (isinstance(in1_typ, types.Number) + or in1_typ == types.string): + extra_kill[label].add(in1_var) + # if a=b is in dict and b is killed, a is also killed + new_assign_dict = {} + for l, r in assign_dict.items(): + if l != in1_var and r != in1_var: + new_assign_dict[l] = r + if r == in1_var: + extra_kill[label].add(l) + assign_dict = new_assign_dict + extra_kill[label].add(lhs) + block_cps = set(assign_dict.items()) + block_copies[label] = block_cps + return block_copies, extra_kill + + +# other packages that define new nodes add calls to apply copy propagate in them +# format: {type:function} +apply_copy_propagate_extensions = {} + + +def apply_copy_propagate(blocks, in_copies, name_var_table, typemap, calltypes, + save_copies=None): + """apply copy propagation to IR: replace variables when copies available""" + # save_copies keeps an approximation of the copies that were applied, so + # that the variable names of removed user variables can be recovered to some + # extent. + if save_copies is None: + save_copies = [] + + for label, block in blocks.items(): + var_dict = {l: name_var_table[r] for l, r in in_copies[label]} + # assignments as dict to replace with latest value + for stmt in block.body: + if type(stmt) in apply_copy_propagate_extensions: + f = apply_copy_propagate_extensions[type(stmt)] + f(stmt, var_dict, name_var_table, + typemap, calltypes, save_copies) + # only rhs of assignments should be replaced + # e.g. if x=y is available, x in x=z shouldn't be replaced + elif isinstance(stmt, ir.Assign): + stmt.value = replace_vars_inner(stmt.value, var_dict) + else: + replace_vars_stmt(stmt, var_dict) + fix_setitem_type(stmt, typemap, calltypes) + for T, f in copy_propagate_extensions.items(): + if isinstance(stmt, T): + gen_set, kill_set = f(stmt, typemap) + for lhs, rhs in gen_set: + if rhs in name_var_table: + var_dict[lhs] = name_var_table[rhs] + for l, r in var_dict.copy().items(): + if l in kill_set or r.name in kill_set: + var_dict.pop(l) + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Var): + lhs = stmt.target.name + rhs = stmt.value.name + # rhs could be replaced with lhs from previous copies + if lhs != rhs: + # copy is valid only if same type (see + # TestCFunc.test_locals) + if typemap[lhs] == typemap[rhs] and rhs in name_var_table: + var_dict[lhs] = name_var_table[rhs] + else: + var_dict.pop(lhs, None) + # a=b kills previous t=a + lhs_kill = [] + for k, v in var_dict.items(): + if v.name == lhs: + lhs_kill.append(k) + for k in lhs_kill: + var_dict.pop(k, None) + if (isinstance(stmt, ir.Assign) + and not isinstance(stmt.value, ir.Var)): + lhs = stmt.target.name + var_dict.pop(lhs, None) + # previous t=a is killed if a is killed + lhs_kill = [] + for k, v in var_dict.items(): + if v.name == lhs: + lhs_kill.append(k) + for k in lhs_kill: + var_dict.pop(k, None) + save_copies.extend(var_dict.items()) + + return save_copies + +def fix_setitem_type(stmt, typemap, calltypes): + """Copy propagation can replace setitem target variable, which can be array + with 'A' layout. The replaced variable can be 'C' or 'F', so we update + setitem call type reflect this (from matrix power test) + """ + if not isinstance(stmt, (ir.SetItem, ir.StaticSetItem)): + return + t_typ = typemap[stmt.target.name] + s_typ = calltypes[stmt].args[0] + # test_optional t_typ can be Optional with array + if not isinstance( + s_typ, + types.npytypes.Array) or not isinstance( + t_typ, + types.npytypes.Array): + return + if s_typ.layout == 'A' and t_typ.layout != 'A': + new_s_typ = s_typ.copy(layout=t_typ.layout) + calltypes[stmt].args = ( + new_s_typ, + calltypes[stmt].args[1], + calltypes[stmt].args[2]) + return + + +def dprint_func_ir(func_ir, title, blocks=None): + """Debug print function IR, with an optional blocks argument + that may differ from the IR's original blocks. + """ + if config.DEBUG_ARRAY_OPT >= 1: + ir_blocks = func_ir.blocks + func_ir.blocks = ir_blocks if blocks == None else blocks + name = func_ir.func_id.func_qualname + print(("IR %s: %s" % (title, name)).center(80, "-")) + func_ir.dump() + print("-" * 40) + func_ir.blocks = ir_blocks + + +def find_topo_order(blocks, cfg = None): + """find topological order of blocks such that true branches are visited + first (e.g. for_break test in test_dataflow). This is written as an iterative + implementation of post order traversal to avoid recursion limit issues. + """ + if cfg is None: + cfg = compute_cfg_from_blocks(blocks) + + post_order = [] + # Has the node already added its children? + seen = set() + # Has the node already been pushed to post order? + visited = set() + stack = [cfg.entry_point()] + + while len(stack) > 0: + node = stack[-1] + if node not in visited and node not in seen: + # We haven't added a node or its children. + seen.add(node) + succs = cfg._succs[node] + last_inst = blocks[node].body[-1] + if isinstance(last_inst, ir.Branch): + succs = [last_inst.truebr, last_inst.falsebr] + for dest in succs: + if (node, dest) not in cfg._back_edges: + if dest not in seen: + stack.append(dest) + else: + # This node has already added its children. We either need + # to visit the node or it has been added multiple times in + # which case we should just skip the node. + node = stack.pop() + if node not in visited: + post_order.append(node) + visited.add(node) + if node in seen: + # Remove the node from seen if it exists to limit the memory + # usage to 1 entry per node. Otherwise the memory requirement + # can double the recursive version. + seen.remove(node) + + post_order.reverse() + return post_order + + +# other packages that define new nodes add calls to get call table +# format: {type:function} +call_table_extensions = {} + + +def get_call_table(blocks, call_table=None, reverse_call_table=None, topological_ordering=True): + """returns a dictionary of call variables and their references. + """ + # call_table example: c = np.zeros becomes c:["zeroes", np] + # reverse_call_table example: c = np.zeros becomes np_var:c + if call_table is None: + call_table = {} + if reverse_call_table is None: + reverse_call_table = {} + + if topological_ordering: + order = find_topo_order(blocks) + else: + order = list(blocks.keys()) + + for label in reversed(order): + for inst in reversed(blocks[label].body): + if isinstance(inst, ir.Assign): + lhs = inst.target.name + rhs = inst.value + if isinstance(rhs, ir.Expr) and rhs.op == 'call': + call_table[rhs.func.name] = [] + if isinstance(rhs, ir.Expr) and rhs.op == 'getattr': + if lhs in call_table: + call_table[lhs].append(rhs.attr) + reverse_call_table[rhs.value.name] = lhs + if lhs in reverse_call_table: + call_var = reverse_call_table[lhs] + call_table[call_var].append(rhs.attr) + reverse_call_table[rhs.value.name] = call_var + if isinstance(rhs, ir.Global): + if lhs in call_table: + call_table[lhs].append(rhs.value) + if lhs in reverse_call_table: + call_var = reverse_call_table[lhs] + call_table[call_var].append(rhs.value) + if isinstance(rhs, ir.FreeVar): + if lhs in call_table: + call_table[lhs].append(rhs.value) + if lhs in reverse_call_table: + call_var = reverse_call_table[lhs] + call_table[call_var].append(rhs.value) + if isinstance(rhs, ir.Var): + if lhs in call_table: + call_table[lhs].append(rhs.name) + reverse_call_table[rhs.name] = lhs + if lhs in reverse_call_table: + call_var = reverse_call_table[lhs] + call_table[call_var].append(rhs.name) + for T, f in call_table_extensions.items(): + if isinstance(inst, T): + f(inst, call_table, reverse_call_table) + return call_table, reverse_call_table + + +# other packages that define new nodes add calls to get tuple table +# format: {type:function} +tuple_table_extensions = {} + + +def get_tuple_table(blocks, tuple_table=None): + """returns a dictionary of tuple variables and their values. + """ + if tuple_table is None: + tuple_table = {} + + for block in blocks.values(): + for inst in block.body: + if isinstance(inst, ir.Assign): + lhs = inst.target.name + rhs = inst.value + if isinstance(rhs, ir.Expr) and rhs.op == 'build_tuple': + tuple_table[lhs] = rhs.items + if isinstance(rhs, ir.Const) and isinstance(rhs.value, tuple): + tuple_table[lhs] = rhs.value + for T, f in tuple_table_extensions.items(): + if isinstance(inst, T): + f(inst, tuple_table) + return tuple_table + + +def get_stmt_writes(stmt): + writes = set() + if isinstance(stmt, (ir.Assign, ir.SetItem, ir.StaticSetItem)): + writes.add(stmt.target.name) + return writes + + +def rename_labels(blocks): + """rename labels of function body blocks according to topological sort. + The set of labels of these blocks will remain unchanged. + """ + topo_order = find_topo_order(blocks) + + # make a block with return last if available (just for readability) + return_label = -1 + for l, b in blocks.items(): + if isinstance(b.body[-1], ir.Return): + return_label = l + # some cases like generators can have no return blocks + if return_label != -1: + topo_order.remove(return_label) + topo_order.append(return_label) + + label_map = {} + all_labels = sorted(topo_order, reverse=True) + for label in topo_order: + label_map[label] = all_labels.pop() + # update target labels in jumps/branches + for b in blocks.values(): + term = b.terminator + # create new IR nodes instead of mutating the existing one as copies of + # the IR may also refer to the same nodes! + if isinstance(term, ir.Jump): + b.body[-1] = ir.Jump(label_map[term.target], term.loc) + if isinstance(term, ir.Branch): + b.body[-1] = ir.Branch(term.cond, + label_map[term.truebr], + label_map[term.falsebr], + term.loc) + + + + # update blocks dictionary keys + new_blocks = {} + for k, b in blocks.items(): + new_label = label_map[k] + new_blocks[new_label] = b + + return new_blocks + + +def simplify_CFG(blocks): + """transform chains of blocks that have no loop into a single block""" + # first, inline single-branch-block to its predecessors + cfg = compute_cfg_from_blocks(blocks) + def find_single_branch(label): + block = blocks[label] + return len(block.body) == 1 and isinstance(block.body[0], ir.Branch) + single_branch_blocks = list(filter(find_single_branch, blocks.keys())) + marked_for_del = set() + for label in single_branch_blocks: + inst = blocks[label].body[0] + predecessors = cfg.predecessors(label) + delete_block = True + for (p, q) in predecessors: + block = blocks[p] + if isinstance(block.body[-1], ir.Jump): + block.body[-1] = copy.copy(inst) + else: + delete_block = False + if delete_block: + marked_for_del.add(label) + # Delete marked labels + for label in marked_for_del: + del blocks[label] + merge_adjacent_blocks(blocks) + return rename_labels(blocks) + + +arr_math = ['min', 'max', 'sum', 'prod', 'mean', 'var', 'std', + 'cumsum', 'cumprod', 'argmax', 'argmin', 'argsort', + 'nonzero', 'ravel'] + + +def canonicalize_array_math(func_ir, typemap, calltypes, typingctx): + # save array arg to call + # call_varname -> array + blocks = func_ir.blocks + saved_arr_arg = {} + topo_order = find_topo_order(blocks) + for label in topo_order: + block = blocks[label] + new_body = [] + for stmt in block.body: + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + lhs = stmt.target.name + rhs = stmt.value + # replace A.func with np.func, and save A in saved_arr_arg + if (rhs.op == 'getattr' and rhs.attr in arr_math + and isinstance( + typemap[rhs.value.name], types.npytypes.Array)): + rhs = stmt.value + arr = rhs.value + saved_arr_arg[lhs] = arr + scope = arr.scope + loc = arr.loc + # g_np_var = Global(numpy) + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + rhs.value = g_np_var + new_body.append(g_np_assign) + func_ir._definitions[g_np_var.name] = [g_np] + # update func var type + func = getattr(numpy, rhs.attr) + func_typ = get_np_ufunc_typ(func, typingctx) + typemap.pop(lhs) + typemap[lhs] = func_typ + if rhs.op == 'call' and rhs.func.name in saved_arr_arg: + # add array as first arg + arr = saved_arr_arg[rhs.func.name] + # update call type signature to include array arg + old_sig = calltypes.pop(rhs) + # argsort requires kws for typing so sig.args can't be used + # reusing sig.args since some types become Const in sig + argtyps = old_sig.args[:len(rhs.args)] + kwtyps = {name: typemap[v.name] for name, v in rhs.kws} + calltypes[rhs] = typemap[rhs.func.name].get_call_type( + typingctx, [typemap[arr.name]] + list(argtyps), kwtyps) + rhs.args = [arr] + rhs.args + + new_body.append(stmt) + block.body = new_body + return + + +# format: {type:function} +array_accesses_extensions = {} + + +def get_array_accesses(blocks, accesses=None): + """returns a set of arrays accessed and their indices. + """ + if accesses is None: + accesses = set() + + for block in blocks.values(): + for inst in block.body: + if isinstance(inst, ir.SetItem): + accesses.add((inst.target.name, inst.index.name)) + if isinstance(inst, ir.StaticSetItem): + accesses.add((inst.target.name, inst.index_var.name)) + if isinstance(inst, ir.Assign): + lhs = inst.target.name + rhs = inst.value + if isinstance(rhs, ir.Expr) and rhs.op == 'getitem': + accesses.add((rhs.value.name, rhs.index.name)) + if isinstance(rhs, ir.Expr) and rhs.op == 'static_getitem': + index = rhs.index + # slice is unhashable, so just keep the variable + if index is None or is_slice_index(index): + index = rhs.index_var.name + accesses.add((rhs.value.name, index)) + for T, f in array_accesses_extensions.items(): + if isinstance(inst, T): + f(inst, accesses) + return accesses + +def is_slice_index(index): + """see if index is a slice index or has slice in it""" + if isinstance(index, slice): + return True + if isinstance(index, tuple): + for i in index: + if isinstance(i, slice): + return True + return False + +def merge_adjacent_blocks(blocks): + cfg = compute_cfg_from_blocks(blocks) + # merge adjacent blocks + removed = set() + for label in list(blocks.keys()): + if label in removed: + continue + block = blocks[label] + succs = list(cfg.successors(label)) + while True: + if len(succs) != 1: + break + next_label = succs[0][0] + if next_label in removed: + break + preds = list(cfg.predecessors(next_label)) + succs = list(cfg.successors(next_label)) + if len(preds) != 1 or preds[0][0] != label: + break + next_block = blocks[next_label] + # XXX: commented out since scope objects are not consistent + # throughout the compiler. for example, pieces of code are compiled + # and inlined on the fly without proper scope merge. + # if block.scope != next_block.scope: + # break + # merge + block.body.pop() # remove Jump + block.body += next_block.body + del blocks[next_label] + removed.add(next_label) + label = next_label + + +def restore_copy_var_names(blocks, save_copies, typemap): + """ + restores variable names of user variables after applying copy propagation + """ + if not save_copies: + return {} + + rename_dict = {} + var_rename_map = {} + for (a, b) in save_copies: + # a is string name, b is variable + # if a is user variable and b is generated temporary and b is not + # already renamed + if (not a.startswith('$') and b.name.startswith('$') + and b.name not in rename_dict): + new_name = mk_unique_var('${}'.format(a)); + rename_dict[b.name] = new_name + var_rename_map[new_name] = a + typ = typemap.pop(b.name) + typemap[new_name] = typ + + replace_var_names(blocks, rename_dict) + return var_rename_map + + +def simplify(func_ir, typemap, calltypes, metadata): + # get copies in to blocks and out from blocks + in_cps, _ = copy_propagate(func_ir.blocks, typemap) + # table mapping variable names to ir.Var objects to help replacement + name_var_table = get_name_var_table(func_ir.blocks) + save_copies = apply_copy_propagate( + func_ir.blocks, + in_cps, + name_var_table, + typemap, + calltypes) + var_rename_map = restore_copy_var_names(func_ir.blocks, save_copies, typemap) + if "var_rename_map" not in metadata: + metadata["var_rename_map"] = {} + metadata["var_rename_map"].update(var_rename_map) + # remove dead code to enable fusion + if config.DEBUG_ARRAY_OPT >= 1: + dprint_func_ir(func_ir, "after copy prop") + remove_dead(func_ir.blocks, func_ir.arg_names, func_ir, typemap) + func_ir.blocks = simplify_CFG(func_ir.blocks) + if config.DEBUG_ARRAY_OPT >= 1: + dprint_func_ir(func_ir, "after simplify") + + +class GuardException(Exception): + pass + + +def require(cond): + """ + Raise GuardException if the given condition is False. + """ + if not cond: + raise GuardException + +def guard(func, *args, **kwargs): + """ + Run a function with given set of arguments, and guard against + any GuardException raised by the function by returning None, + or the expected return results if no such exception was raised. + """ + try: + return func(*args, **kwargs) + except GuardException: + return None + +def get_definition(func_ir, name, **kwargs): + """ + Same as func_ir.get_definition(name), but raise GuardException if + exception KeyError is caught. + """ + try: + return func_ir.get_definition(name, **kwargs) + except KeyError: + raise GuardException + +def build_definitions(blocks, definitions=None): + """Build the definitions table of the given blocks by scanning + through all blocks and instructions, useful when the definitions + table is out-of-sync. + Will return a new definition table if one is not passed. + """ + if definitions is None: + definitions = collections.defaultdict(list) + + for block in blocks.values(): + for inst in block.body: + if isinstance(inst, ir.Assign): + name = inst.target.name + definition = definitions.get(name, []) + if definition == []: + definitions[name] = definition + definition.append(inst.value) + if type(inst) in build_defs_extensions: + f = build_defs_extensions[type(inst)] + f(inst, definitions) + + return definitions + +build_defs_extensions = {} + +def find_callname(func_ir, expr, typemap=None, definition_finder=get_definition): + """Try to find a call expression's function and module names and return + them as strings for unbounded calls. If the call is a bounded call, return + the self object instead of module name. Raise GuardException if failed. + + Providing typemap can make the call matching more accurate in corner cases + such as bounded call on an object which is inside another object. + """ + require(isinstance(expr, ir.Expr) and expr.op == 'call') + callee = expr.func + callee_def = definition_finder(func_ir, callee) + attrs = [] + obj = None + while True: + if isinstance(callee_def, (ir.Global, ir.FreeVar)): + # require(callee_def.value == numpy) + # these checks support modules like numpy, numpy.random as well as + # calls like len() and intrinsics like assertEquiv + keys = ['name', '_name', '__name__'] + value = None + for key in keys: + if hasattr(callee_def.value, key): + value = getattr(callee_def.value, key) + break + if not value or not isinstance(value, str): + raise GuardException + attrs.append(value) + def_val = callee_def.value + # get the underlying definition of Intrinsic object to be able to + # find the module effectively. + # Otherwise, it will return numba.extending + if isinstance(def_val, _Intrinsic): + def_val = def_val._defn + if hasattr(def_val, '__module__'): + mod_name = def_val.__module__ + # The reason for first checking if the function is in NumPy's + # top level name space by module is that some functions are + # deprecated in NumPy but the functions' names are aliased with + # other common names. This prevents deprecation warnings on + # e.g. getattr(numpy, 'bool') were a bool the target. + # For context see #6175, impacts NumPy>=1.20. + mod_not_none = mod_name is not None + numpy_toplevel = (mod_not_none and + (mod_name == 'numpy' + or mod_name.startswith('numpy.'))) + # it might be a numpy function imported directly + if (numpy_toplevel and hasattr(numpy, value) + and def_val == getattr(numpy, value)): + attrs += ['numpy'] + # it might be a np.random function imported directly + elif (hasattr(numpy.random, value) + and def_val == getattr(numpy.random, value)): + attrs += ['random', 'numpy'] + elif mod_not_none: + attrs.append(mod_name) + else: + class_name = def_val.__class__.__name__ + if class_name == 'builtin_function_or_method': + class_name = 'builtin' + if class_name != 'module': + attrs.append(class_name) + break + elif isinstance(callee_def, ir.Expr) and callee_def.op == 'getattr': + obj = callee_def.value + attrs.append(callee_def.attr) + if typemap and obj.name in typemap: + typ = typemap[obj.name] + if not isinstance(typ, types.Module): + return attrs[0], obj + callee_def = definition_finder(func_ir, obj) + else: + # obj.func calls where obj is not np array + if obj is not None: + return '.'.join(reversed(attrs)), obj + raise GuardException + return attrs[0], '.'.join(reversed(attrs[1:])) + +def find_build_sequence(func_ir, var): + """Check if a variable is constructed via build_tuple or + build_list or build_set, and return the sequence and the + operator, or raise GuardException otherwise. + Note: only build_tuple is immutable, so use with care. + """ + require(isinstance(var, ir.Var)) + var_def = get_definition(func_ir, var) + require(isinstance(var_def, ir.Expr)) + build_ops = ['build_tuple', 'build_list', 'build_set'] + require(var_def.op in build_ops) + return var_def.items, var_def.op + +def find_const(func_ir, var): + """Check if a variable is defined as constant, and return + the constant value, or raise GuardException otherwise. + """ + require(isinstance(var, ir.Var)) + var_def = get_definition(func_ir, var) + require(isinstance(var_def, (ir.Const, ir.Global, ir.FreeVar))) + return var_def.value + +def compile_to_numba_ir(mk_func, glbls, typingctx=None, targetctx=None, + arg_typs=None, typemap=None, calltypes=None): + """ + Compile a function or a make_function node to Numba IR. + + Rename variables and + labels to avoid conflict if inlined somewhere else. Perform type inference + if typingctx and other typing inputs are available and update typemap and + calltypes. + """ + from numba.core import typed_passes + # mk_func can be actual function or make_function node, or a njit function + if hasattr(mk_func, 'code'): + code = mk_func.code + elif hasattr(mk_func, '__code__'): + code = mk_func.__code__ + else: + raise NotImplementedError("function type not recognized {}".format(mk_func)) + f_ir = get_ir_of_code(glbls, code) + remove_dels(f_ir.blocks) + + # relabel by adding an offset + f_ir.blocks = add_offset_to_labels(f_ir.blocks, _the_max_label.next()) + max_label = max(f_ir.blocks.keys()) + _the_max_label.update(max_label) + + # rename all variables to avoid conflict + var_table = get_name_var_table(f_ir.blocks) + new_var_dict = {} + for name, var in var_table.items(): + new_var_dict[name] = mk_unique_var(name) + replace_var_names(f_ir.blocks, new_var_dict) + + # perform type inference if typingctx is available and update type + # data structures typemap and calltypes + if typingctx: + f_typemap, f_return_type, f_calltypes, _ = typed_passes.type_inference_stage( + typingctx, targetctx, f_ir, arg_typs, None) + # remove argument entries like arg.a from typemap + arg_names = [vname for vname in f_typemap if vname.startswith("arg.")] + for a in arg_names: + f_typemap.pop(a) + typemap.update(f_typemap) + calltypes.update(f_calltypes) + return f_ir + +def _create_function_from_code_obj(fcode, func_env, func_arg, func_clo, glbls): + """ + Creates a function from a code object. Args: + * fcode - the code object + * func_env - string for the freevar placeholders + * func_arg - string for the function args (e.g. "a, b, c, d=None") + * func_clo - string for the closure args + * glbls - the function globals + """ + sanitized_co_name = fcode.co_name.replace('<', '_').replace('>', '_') + func_text = (f"def closure():\n{func_env}\n" + f"\tdef {sanitized_co_name}({func_arg}):\n" + f"\t\treturn ({func_clo})\n" + f"\treturn {sanitized_co_name}") + loc = {} + exec(func_text, glbls, loc) + + f = loc['closure']() + # replace the code body + f.__code__ = fcode + f.__name__ = fcode.co_name + return f + +def get_ir_of_code(glbls, fcode): + """ + Compile a code object to get its IR, ir.Del nodes are emitted + """ + nfree = len(fcode.co_freevars) + func_env = "\n".join(["\tc_%d = None" % i for i in range(nfree)]) + func_clo = ",".join(["c_%d" % i for i in range(nfree)]) + func_arg = ",".join(["x_%d" % i for i in range(fcode.co_argcount)]) + + f = _create_function_from_code_obj(fcode, func_env, func_arg, func_clo, + glbls) + + from numba.core import compiler + ir = compiler.run_frontend(f) + # we need to run the before inference rewrite pass to normalize the IR + # XXX: check rewrite pass flag? + # for example, Raise nodes need to become StaticRaise before type inference + class DummyPipeline(object): + def __init__(self, f_ir): + self.state = compiler.StateDict() + self.state.typingctx = None + self.state.targetctx = None + self.state.args = None + self.state.func_ir = f_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + state = DummyPipeline(ir).state + rewrites.rewrite_registry.apply('before-inference', state) + # call inline pass to handle cases like stencils and comprehensions + swapped = {} # TODO: get this from diagnostics store + import numba.core.inline_closurecall + inline_pass = numba.core.inline_closurecall.InlineClosureCallPass( + ir, numba.core.cpu.ParallelOptions(False), swapped) + inline_pass.run() + + # TODO: DO NOT ADD MORE THINGS HERE! + # If adding more things here is being contemplated, it really is time to + # retire this function and work on getting the InlineWorker class from + # numba.core.inline_closurecall into sufficient shape as a replacement. + # The issue with `get_ir_of_code` is that it doesn't run a full compilation + # pipeline and as a result various additional things keep needing to be + # added to create valid IR. + + # rebuild IR in SSA form + from numba.core.untyped_passes import ReconstructSSA + from numba.core.typed_passes import PreLowerStripPhis + reconstruct_ssa = ReconstructSSA() + phistrip = PreLowerStripPhis() + reconstruct_ssa.run_pass(state) + phistrip.run_pass(state) + + post_proc = postproc.PostProcessor(ir) + post_proc.run(True) + return ir + +def replace_arg_nodes(block, args): + """ + Replace ir.Arg(...) with variables + """ + for stmt in block.body: + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Arg): + idx = stmt.value.index + assert(idx < len(args)) + stmt.value = args[idx] + return + + +def replace_returns(blocks, target, return_label): + """ + Return return statement by assigning directly to target, and a jump. + """ + for block in blocks.values(): + # some blocks may be empty during transformations + if not block.body: + continue + stmt = block.terminator + if isinstance(stmt, ir.Return): + block.body.pop() # remove return + cast_stmt = block.body.pop() + assert (isinstance(cast_stmt, ir.Assign) + and isinstance(cast_stmt.value, ir.Expr) + and cast_stmt.value.op == 'cast'), "invalid return cast" + block.body.append(ir.Assign(cast_stmt.value.value, target, stmt.loc)) + block.body.append(ir.Jump(return_label, stmt.loc)) + + +def gen_np_call(func_as_str, func, lhs, args, typingctx, typemap, calltypes): + scope = args[0].scope + loc = args[0].loc + + # g_np_var = Global(numpy) + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + # attr call: _attr = getattr(g_np_var, func_as_str) + np_attr_call = ir.Expr.getattr(g_np_var, func_as_str, loc) + attr_var = ir.Var(scope, mk_unique_var("$np_attr_attr"), loc) + func_var_typ = get_np_ufunc_typ(func, typingctx) + typemap[attr_var.name] = func_var_typ + attr_assign = ir.Assign(np_attr_call, attr_var, loc) + # np call: lhs = np_attr(*args) + np_call = ir.Expr.call(attr_var, args, (), loc) + arg_types = [typemap[x.name] for x in args] + func_typ = func_var_typ.get_call_type(typingctx, arg_types, {}) + calltypes[np_call] = func_typ + np_assign = ir.Assign(np_call, lhs, loc) + return [g_np_assign, attr_assign, np_assign] + +def dump_block(label, block): + print(label, ":") + for stmt in block.body: + print(" ", stmt) + +def dump_blocks(blocks): + for label, block in blocks.items(): + dump_block(label, block) + +def is_operator_or_getitem(expr): + """true if expr is unary or binary operator or getitem""" + return (isinstance(expr, ir.Expr) + and getattr(expr, 'op', False) + and expr.op in ['unary', 'binop', 'inplace_binop', 'getitem', 'static_getitem']) + +def is_get_setitem(stmt): + """stmt is getitem assignment or setitem (and static cases)""" + return is_getitem(stmt) or is_setitem(stmt) + + +def is_getitem(stmt): + """true if stmt is a getitem or static_getitem assignment""" + return (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['getitem', 'static_getitem']) + +def is_setitem(stmt): + """true if stmt is a SetItem or StaticSetItem node""" + return isinstance(stmt, (ir.SetItem, ir.StaticSetItem)) + +def index_var_of_get_setitem(stmt): + """get index variable for getitem/setitem nodes (and static cases)""" + if is_getitem(stmt): + if stmt.value.op == 'getitem': + return stmt.value.index + else: + return stmt.value.index_var + + if is_setitem(stmt): + if isinstance(stmt, ir.SetItem): + return stmt.index + else: + return stmt.index_var + + return None + +def set_index_var_of_get_setitem(stmt, new_index): + if is_getitem(stmt): + if stmt.value.op == 'getitem': + stmt.value.index = new_index + else: + stmt.value.index_var = new_index + elif is_setitem(stmt): + if isinstance(stmt, ir.SetItem): + stmt.index = new_index + else: + stmt.index_var = new_index + else: + raise ValueError("getitem or setitem node expected but received {}".format( + stmt)) + + +def is_namedtuple_class(c): + """check if c is a namedtuple class""" + if not isinstance(c, type): + return False + # should have only tuple as superclass + bases = c.__bases__ + if len(bases) != 1 or bases[0] != tuple: + return False + # should have _make method + if not hasattr(c, '_make'): + return False + # should have _fields that is all string + fields = getattr(c, '_fields', None) + if not isinstance(fields, tuple): + return False + return all(isinstance(f, str) for f in fields) + + +def fill_block_with_call(newblock, callee, label_next, inputs, outputs): + """Fill *newblock* to call *callee* with arguments listed in *inputs*. + The returned values are unwrapped into variables in *outputs*. + The block would then jump to *label_next*. + """ + scope = newblock.scope + loc = newblock.loc + + fn = ir.Const(value=callee, loc=loc) + fnvar = scope.make_temp(loc=loc) + newblock.append(ir.Assign(target=fnvar, value=fn, loc=loc)) + # call + args = [scope.get_exact(name) for name in inputs] + callexpr = ir.Expr.call(func=fnvar, args=args, kws=(), loc=loc) + callres = scope.make_temp(loc=loc) + newblock.append(ir.Assign(target=callres, value=callexpr, loc=loc)) + # unpack return value + for i, out in enumerate(outputs): + target = scope.get_exact(out) + getitem = ir.Expr.static_getitem(value=callres, index=i, + index_var=None, loc=loc) + newblock.append(ir.Assign(target=target, value=getitem, loc=loc)) + # jump to next block + newblock.append(ir.Jump(target=label_next, loc=loc)) + return newblock + + +def fill_callee_prologue(block, inputs, label_next): + """ + Fill a new block *block* that unwraps arguments using names in *inputs* and + then jumps to *label_next*. + + Expected to use with *fill_block_with_call()* + """ + scope = block.scope + loc = block.loc + # load args + args = [ir.Arg(name=k, index=i, loc=loc) + for i, k in enumerate(inputs)] + for aname, aval in zip(inputs, args): + tmp = ir.Var(scope=scope, name=aname, loc=loc) + block.append(ir.Assign(target=tmp, value=aval, loc=loc)) + # jump to loop entry + block.append(ir.Jump(target=label_next, loc=loc)) + return block + + +def fill_callee_epilogue(block, outputs): + """ + Fill a new block *block* to prepare the return values. + This block is the last block of the function. + + Expected to use with *fill_block_with_call()* + """ + scope = block.scope + loc = block.loc + # prepare tuples to return + vals = [scope.get_exact(name=name) for name in outputs] + tupexpr = ir.Expr.build_tuple(items=vals, loc=loc) + tup = scope.make_temp(loc=loc) + block.append(ir.Assign(target=tup, value=tupexpr, loc=loc)) + # return + block.append(ir.Return(value=tup, loc=loc)) + return block + + +def find_outer_value(func_ir, var): + """Check if a variable is a global value, and return the value, + or raise GuardException otherwise. + """ + dfn = get_definition(func_ir, var) + if isinstance(dfn, (ir.Global, ir.FreeVar)): + return dfn.value + + if isinstance(dfn, ir.Expr) and dfn.op == 'getattr': + prev_val = find_outer_value(func_ir, dfn.value) + try: + val = getattr(prev_val, dfn.attr) + return val + except AttributeError: + raise GuardException + + raise GuardException + + +def raise_on_unsupported_feature(func_ir, typemap): + """ + Helper function to walk IR and raise if it finds op codes + that are unsupported. Could be extended to cover IR sequences + as well as op codes. Intended use is to call it as a pipeline + stage just prior to lowering to prevent LoweringErrors for known + unsupported features. + """ + gdb_calls = [] # accumulate calls to gdb/gdb_init + + # issue 2195: check for excessively large tuples + for arg_name in func_ir.arg_names: + if arg_name in typemap and \ + isinstance(typemap[arg_name], types.containers.UniTuple) and \ + typemap[arg_name].count > 1000: + # Raise an exception when len(tuple) > 1000. The choice of this number (1000) + # was entirely arbitrary + msg = ("Tuple '{}' length must be smaller than 1000.\n" + "Large tuples lead to the generation of a prohibitively large " + "LLVM IR which causes excessive memory pressure " + "and large compile times.\n" + "As an alternative, the use of a 'list' is recommended in " + "place of a 'tuple' as lists do not suffer from this problem.".format(arg_name)) + raise UnsupportedError(msg, func_ir.loc) + + for blk in func_ir.blocks.values(): + for stmt in blk.find_insts(ir.Assign): + # This raises on finding `make_function` + if isinstance(stmt.value, ir.Expr): + if stmt.value.op == 'make_function': + val = stmt.value + + # See if the construct name can be refined + code = getattr(val, 'code', None) + if code is not None: + # check if this is a closure, the co_name will + # be the captured function name which is not + # useful so be explicit + if getattr(val, 'closure', None) is not None: + use = '' + expr = '' + else: + use = code.co_name + expr = '(%s) ' % use + else: + use = '' + expr = '' + + msg = ("Numba encountered the use of a language " + "feature it does not support in this context: " + "%s (op code: make_function not supported). If " + "the feature is explicitly supported it is " + "likely that the result of the expression %s" + "is being used in an unsupported manner.") % \ + (use, expr) + raise UnsupportedError(msg, stmt.value.loc) + + # this checks for gdb initialization calls, only one is permitted + if isinstance(stmt.value, (ir.Global, ir.FreeVar)): + val = stmt.value + val = getattr(val, 'value', None) + if val is None: + continue + + # check global function + found = False + if isinstance(val, pytypes.FunctionType): + found = val in {numba.gdb, numba.gdb_init} + if not found: # freevar bind to intrinsic + found = getattr(val, '_name', "") == "gdb_internal" + if found: + gdb_calls.append(stmt.loc) # report last seen location + + # this checks that np. was called if view is called + if isinstance(stmt.value, ir.Expr): + if stmt.value.op == 'getattr' and stmt.value.attr == 'view': + var = stmt.value.value.name + if isinstance(typemap[var], types.Array): + continue + df = func_ir.get_definition(var) + cn = guard(find_callname, func_ir, df) + if cn and cn[1] == 'numpy': + ty = getattr(numpy, cn[0]) + if (numpy.issubdtype(ty, numpy.integer) or + numpy.issubdtype(ty, numpy.floating)): + continue + + vardescr = '' if var.startswith('$') else "'{}' ".format(var) + raise TypingError( + "'view' can only be called on NumPy dtypes, " + "try wrapping the variable {}with 'np.()'". + format(vardescr), loc=stmt.loc) + + # checks for globals that are also reflected + if isinstance(stmt.value, ir.Global): + ty = typemap[stmt.target.name] + msg = ("The use of a %s type, assigned to variable '%s' in " + "globals, is not supported as globals are considered " + "compile-time constants and there is no known way to " + "compile a %s type as a constant.") + if (getattr(ty, 'reflected', False) or + isinstance(ty, (types.DictType, types.ListType))): + raise TypingError(msg % (ty, stmt.value.name, ty), loc=stmt.loc) + + # checks for generator expressions (yield in use when func_ir has + # not been identified as a generator). + if isinstance(stmt.value, ir.Yield) and not func_ir.is_generator: + msg = "The use of generator expressions is unsupported." + raise UnsupportedError(msg, loc=stmt.loc) + + # There is more than one call to function gdb/gdb_init + if len(gdb_calls) > 1: + msg = ("Calling either numba.gdb() or numba.gdb_init() more than once " + "in a function is unsupported (strange things happen!), use " + "numba.gdb_breakpoint() to create additional breakpoints " + "instead.\n\nRelevant documentation is available here:\n" + "https://numba.readthedocs.io/en/stable/user/troubleshoot.html" + "#using-numba-s-direct-gdb-bindings-in-nopython-mode\n\n" + "Conflicting calls found at:\n %s") + buf = '\n'.join([x.strformat() for x in gdb_calls]) + raise UnsupportedError(msg % buf) + + +def warn_deprecated(func_ir, typemap): + # first pass, just walk the type map + for name, ty in typemap.items(): + # the Type Metaclass has a reflected member + if ty.reflected: + # if its an arg, report function call + if name.startswith('arg.'): + loc = func_ir.loc + arg = name.split('.')[1] + fname = func_ir.func_id.func_qualname + tyname = 'list' if isinstance(ty, types.List) else 'set' + url = ("https://numba.readthedocs.io/en/stable/reference/" + "deprecation.html#deprecation-of-reflection-for-list-and" + "-set-types") + msg = ("\nEncountered the use of a type that is scheduled for " + "deprecation: type 'reflected %s' found for argument " + "'%s' of function '%s'.\n\nFor more information visit " + "%s" % (tyname, arg, fname, url)) + warnings.warn(NumbaPendingDeprecationWarning(msg, loc=loc)) + + +def resolve_func_from_module(func_ir, node): + """ + This returns the python function that is being getattr'd from a module in + some IR, it resolves import chains/submodules recursively. Should it not be + possible to find the python function being called None will be returned. + + func_ir - the FunctionIR object + node - the IR node from which to start resolving (should be a `getattr`). + """ + getattr_chain = [] + def resolve_mod(mod): + if getattr(mod, 'op', False) == 'getattr': + getattr_chain.insert(0, mod.attr) + try: + mod = func_ir.get_definition(mod.value) + except KeyError: # multiple definitions + return None + return resolve_mod(mod) + elif isinstance(mod, (ir.Global, ir.FreeVar)): + if isinstance(mod.value, pytypes.ModuleType): + return mod + return None + + mod = resolve_mod(node) + if mod is not None: + defn = mod.value + for x in getattr_chain: + defn = getattr(defn, x, False) + if not defn: + break + else: + return defn + else: + return None + + +def enforce_no_dels(func_ir): + """ + Enforce there being no ir.Del nodes in the IR. + """ + for blk in func_ir.blocks.values(): + dels = [x for x in blk.find_insts(ir.Del)] + if dels: + msg = "Illegal IR, del found at: %s" % dels[0] + raise CompilerError(msg, loc=dels[0].loc) + +def enforce_no_phis(func_ir): + """ + Enforce there being no ir.Expr.phi nodes in the IR. + """ + for blk in func_ir.blocks.values(): + phis = [x for x in blk.find_exprs(op='phi')] + if phis: + msg = "Illegal IR, phi found at: %s" % phis[0] + raise CompilerError(msg, loc=phis[0].loc) + + +def legalize_single_scope(blocks): + """Check the given mapping of ir.Block for containing a single scope. + """ + return len({blk.scope for blk in blocks.values()}) == 1 + + +def check_and_legalize_ir(func_ir, flags: "numba.core.compiler.Flags"): + """ + This checks that the IR presented is legal + """ + enforce_no_phis(func_ir) + enforce_no_dels(func_ir) + # postprocess and emit ir.Dels + post_proc = postproc.PostProcessor(func_ir) + post_proc.run(True, extend_lifetimes=flags.dbg_extend_lifetimes) + +def convert_code_obj_to_function(code_obj, caller_ir): + """ + Converts a code object from a `make_function.code` attr in the IR into a + python function, caller_ir is the FunctionIR of the caller and is used for + the resolution of freevars. + """ + fcode = code_obj.code + nfree = len(fcode.co_freevars) + + # try and resolve freevars if they are consts in the caller's IR + # these can be baked into the new function + freevars = [] + for x in fcode.co_freevars: + # not using guard here to differentiate between multiple definition and + # non-const variable + try: + freevar_def = caller_ir.get_definition(x) + except KeyError: + msg = ("Cannot capture a constant value for variable '%s' as there " + "are multiple definitions present." % x) + raise TypingError(msg, loc=code_obj.loc) + if isinstance(freevar_def, ir.Const): + freevars.append(freevar_def.value) + else: + msg = ("Cannot capture the non-constant value associated with " + "variable '%s' in a function that may escape." % x) + raise TypingError(msg, loc=code_obj.loc) + + func_env = "\n".join(["\tc_%d = %s" % (i, x) for i, x in enumerate(freevars)]) + func_clo = ",".join(["c_%d" % i for i in range(nfree)]) + co_varnames = list(fcode.co_varnames) + + # This is horrible. The code object knows about the number of args present + # it also knows the name of the args but these are bundled in with other + # vars in `co_varnames`. The make_function IR node knows what the defaults + # are, they are defined in the IR as consts. The following finds the total + # number of args (args + kwargs with defaults), finds the default values + # and infers the number of "kwargs with defaults" from this and then infers + # the number of actual arguments from that. + n_kwargs = 0 + n_allargs = fcode.co_argcount + kwarg_defaults = caller_ir.get_definition(code_obj.defaults) + if kwarg_defaults is not None: + if isinstance(kwarg_defaults, tuple): + d = [caller_ir.get_definition(x).value for x in kwarg_defaults] + kwarg_defaults_tup = tuple(d) + else: + d = [caller_ir.get_definition(x).value + for x in kwarg_defaults.items] + kwarg_defaults_tup = tuple(d) + n_kwargs = len(kwarg_defaults_tup) + nargs = n_allargs - n_kwargs + + func_arg = ",".join(["%s" % (co_varnames[i]) for i in range(nargs)]) + if n_kwargs: + kw_const = ["%s = %s" % (co_varnames[i + nargs], kwarg_defaults_tup[i]) + for i in range(n_kwargs)] + func_arg += ", " + func_arg += ", ".join(kw_const) + + # globals are the same as those in the caller + glbls = caller_ir.func_id.func.__globals__ + + # create the function and return it + return _create_function_from_code_obj(fcode, func_env, func_arg, func_clo, + glbls) + + +def fixup_var_define_in_scope(blocks): + """Fixes the mapping of ir.Block to ensure all referenced ir.Var are + defined in every scope used by the function. Such that looking up a variable + from any scope in this function will not fail. + + Note: This is a workaround. Ideally, all the blocks should refer to the + same ir.Scope, but that property is not maintained by all the passes. + """ + # Scan for all used variables + used_var = {} + for blk in blocks.values(): + scope = blk.scope + for inst in blk.body: + for var in inst.list_vars(): + used_var[var] = inst + # Note: not all blocks share a single scope even though they should. + # Ensure the scope of each block defines all used variables. + for blk in blocks.values(): + scope = blk.scope + for var, inst in used_var.items(): + # add this variable if it's not in scope + if var.name not in scope.localvars: + # Note: using a internal method to reuse the same + scope.localvars.define(var.name, var) + + +def transfer_scope(block, scope): + """Transfer the ir.Block to use the given ir.Scope. + """ + old_scope = block.scope + if old_scope is scope: + # bypass if the block is already using the given scope + return block + # Ensure variables are defined in the new scope + for var in old_scope.localvars._con.values(): + if var.name not in scope.localvars: + scope.localvars.define(var.name, var) + # replace scope + block.scope = scope + return block + + +def is_setup_with(stmt): + return isinstance(stmt, ir.EnterWith) + + +def is_terminator(stmt): + return isinstance(stmt, ir.Terminator) + + +def is_raise(stmt): + return isinstance(stmt, ir.Raise) + + +def is_return(stmt): + return isinstance(stmt, ir.Return) + + +def is_pop_block(stmt): + return isinstance(stmt, ir.PopBlock) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/itanium_mangler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/itanium_mangler.py new file mode 100644 index 0000000000000000000000000000000000000000..f4362888c0d4f82847e6f9deece29113a9d05608 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/itanium_mangler.py @@ -0,0 +1,205 @@ +""" +Itanium CXX ABI Mangler + +Reference: https://itanium-cxx-abi.github.io/cxx-abi/abi.html + +The basics of the mangling scheme. + +We are hijacking the CXX mangling scheme for our use. We map Python modules +into CXX namespace. A `module1.submodule2.foo` is mapped to +`module1::submodule2::foo`. For parameterized numba types, we treat them as +templated types; for example, `array(int64, 1d, C)` becomes an +`array`. + +All mangled names are prefixed with "_Z". It is followed by the name of the +entity. A name contains one or more identifiers. Each identifier is encoded +as "". If the name is namespaced and, therefore, +has multiple identifiers, the entire name is encoded as "NE". + +For functions, arguments types follow. There are condensed encodings for basic +built-in types; e.g. "i" for int, "f" for float. For other types, the +previously mentioned name encoding should be used. + +For templated types, the template parameters are encoded immediately after the +name. If it is namespaced, it should be within the 'N' 'E' marker. Template +parameters are encoded in "IE", where each parameter is encoded using +the mentioned name encoding scheme. Template parameters can contain literal +values like the '1' in the array type shown earlier. There is special encoding +scheme for them to avoid leading digits. +""" + + +import re + +from numba.core import types + + +# According the scheme, valid characters for mangled names are [a-zA-Z0-9_]. +# We borrow the '_' as the escape character to encode invalid char into +# '_xx' where 'xx' is the hex codepoint. +_re_invalid_char = re.compile(r'[^a-z0-9_]', re.I) + +PREFIX = "_Z" + +# Numba types to mangled type code. These correspond with the codes listed in +# https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-builtin +N2CODE = { + types.void: 'v', + types.boolean: 'b', + types.uint8: 'h', + types.int8: 'a', + types.uint16: 't', + types.int16: 's', + types.uint32: 'j', + types.int32: 'i', + types.uint64: 'y', + types.int64: 'x', + types.float16: 'Dh', + types.float32: 'f', + types.float64: 'd' +} + + +def _escape_string(text): + """Escape the given string so that it only contains ASCII characters + of [a-zA-Z0-9_$]. + + The dollar symbol ($) and other invalid characters are escaped into + the string sequence of "$xx" where "xx" is the hex codepoint of the char. + + Multibyte characters are encoded into utf8 and converted into the above + hex format. + """ + + def repl(m): + return ''.join(('_%02x' % ch) + for ch in m.group(0).encode('utf8')) + ret = re.sub(_re_invalid_char, repl, text) + # Return str if we got a unicode (for py2) + if not isinstance(ret, str): + return ret.encode('ascii') + return ret + + +def _fix_lead_digit(text): + """ + Fix text with leading digit + """ + if text and text[0].isdigit(): + return '_' + text + else: + return text + + +def _len_encoded(string): + """ + Prefix string with digit indicating the length. + Add underscore if string is prefixed with digits. + """ + string = _fix_lead_digit(string) + return '%u%s' % (len(string), string) + + +def mangle_abi_tag(abi_tag: str) -> str: + return "B" + _len_encoded(_escape_string(abi_tag)) + + +def mangle_identifier(ident, template_params='', *, abi_tags=(), uid=None): + """ + Mangle the identifier with optional template parameters and abi_tags. + + Note: + + This treats '.' as '::' in C++. + """ + if uid is not None: + # Add uid to abi-tags + abi_tags = (f"v{uid}", *abi_tags) + parts = [_len_encoded(_escape_string(x)) for x in ident.split('.')] + enc_abi_tags = list(map(mangle_abi_tag, abi_tags)) + extras = template_params + ''.join(enc_abi_tags) + if len(parts) > 1: + return 'N%s%sE' % (''.join(parts), extras) + else: + return '%s%s' % (parts[0], extras) + + +def mangle_type_or_value(typ): + """ + Mangle type parameter and arbitrary value. + """ + # Handle numba types + if isinstance(typ, types.Type): + if typ in N2CODE: + return N2CODE[typ] + else: + return mangle_templated_ident(*typ.mangling_args) + # Handle integer literal + elif isinstance(typ, int): + return 'Li%dE' % typ + # Handle str as identifier + elif isinstance(typ, str): + return mangle_identifier(typ) + # Otherwise + else: + enc = _escape_string(str(typ)) + return _len_encoded(enc) + + +# Alias +mangle_type = mangle_type_or_value +mangle_value = mangle_type_or_value + + +def mangle_templated_ident(identifier, parameters): + """ + Mangle templated identifier. + """ + template_params = ('I%sE' % ''.join(map(mangle_type_or_value, parameters)) + if parameters else '') + return mangle_identifier(identifier, template_params) + + +def mangle_args(argtys): + """ + Mangle sequence of Numba type objects and arbitrary values. + """ + return ''.join([mangle_type_or_value(t) for t in argtys]) + + +def mangle(ident, argtys, *, abi_tags=(), uid=None): + """ + Mangle identifier with Numba type objects and abi-tags. + """ + return ''.join([PREFIX, + mangle_identifier(ident, abi_tags=abi_tags, uid=uid), + mangle_args(argtys)]) + + +def prepend_namespace(mangled, ns): + """ + Prepend namespace to mangled name. + """ + if not mangled.startswith(PREFIX): + raise ValueError('input is not a mangled name') + elif mangled.startswith(PREFIX + 'N'): + # nested + remaining = mangled[3:] + ret = PREFIX + 'N' + mangle_identifier(ns) + remaining + else: + # non-nested + remaining = mangled[2:] + head, tail = _split_mangled_ident(remaining) + ret = PREFIX + 'N' + mangle_identifier(ns) + head + 'E' + tail + return ret + + +def _split_mangled_ident(mangled): + """ + Returns `(head, tail)` where `head` is the ` + ` encoded + identifier and `tail` is the remaining. + """ + ct = int(mangled) + ctlen = len(str(ct)) + at = ctlen + ct + return mangled[:at], mangled[at:] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/llvm_bindings.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/llvm_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..fbef316cc1313d60614f81b9c5aa90ddd56f56b6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/llvm_bindings.py @@ -0,0 +1,48 @@ +""" +Useful options to debug LLVM passes + +llvm.set_option("test", "-debug-pass=Details") +llvm.set_option("test", "-debug-pass=Executions") +llvm.set_option("test", "-debug-pass=Arguments") +llvm.set_option("test", "-debug-pass=Structure") +llvm.set_option("test", "-debug-only=loop-vectorize") +llvm.set_option("test", "-help-hidden") + +""" + +from llvmlite import binding as llvm + + +def _inlining_threshold(optlevel, sizelevel=0): + """ + Compute the inlining threshold for the desired optimisation level + + Refer to http://llvm.org/docs/doxygen/html/InlineSimple_8cpp_source.html + """ + if optlevel > 2: + return 275 + + # -Os + if sizelevel == 1: + return 75 + + # -Oz + if sizelevel == 2: + return 25 + + return 225 + + +def create_pass_builder(tm, opt=2, loop_vectorize=False, + slp_vectorize=False): + """ + Create an LLVM pass builder with the desired optimisation level and options. + """ + pto = llvm.create_pipeline_tuning_options() + pto.speed_level = opt + pto.slp_vectorization = slp_vectorize + pto.loop_vectorization = loop_vectorize + + # FIXME: Enabled from llvm 16 + # pto.inlining_threshold = _inlining_threshold(opt) + return llvm.create_pass_builder(tm, pto) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/lowering.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..071f46fbe1b183bd2436a6758262ba8234c289d6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/lowering.py @@ -0,0 +1,1652 @@ +from collections import namedtuple, defaultdict +import operator +import warnings +from functools import partial + +import llvmlite.ir +from llvmlite.ir import Constant, IRBuilder + +from numba.core import (typing, utils, types, ir, debuginfo, funcdesc, + generators, config, ir_utils, cgutils, removerefctpass, + targetconfig) +from numba.core.errors import (LoweringError, new_error_context, TypingError, + LiteralTypingError, UnsupportedError, + NumbaDebugInfoWarning) +from numba.core.funcdesc import default_mangler +from numba.core.environment import Environment +from numba.core.analysis import compute_use_defs, must_use_alloca +from numba.misc.firstlinefinder import get_func_body_first_lineno +from numba.misc.coverage_support import get_registered_loc_notify + + +_VarArgItem = namedtuple("_VarArgItem", ("vararg", "index")) + + +class BaseLower(object): + """ + Lower IR to LLVM + """ + + def __init__(self, context, library, fndesc, func_ir, metadata=None): + self.library = library + self.fndesc = fndesc + self.blocks = utils.SortedMap(func_ir.blocks.items()) + self.func_ir = func_ir + self.generator_info = func_ir.generator_info + self.metadata = metadata + self.flags = targetconfig.ConfigStack.top_or_none() + + # Initialize LLVM + self.module = self.library.create_ir_module(self.fndesc.unique_name) + + # Python execution environment (will be available to the compiled + # function). + self.env = Environment.from_fndesc(self.fndesc) + + # Internal states + self.blkmap = {} + self.pending_phis = {} + self.varmap = {} + self.firstblk = min(self.blocks.keys()) + self.loc = -1 + + # Specializes the target context as seen inside the Lowerer + # This adds: + # - environment: the python execution environment + self.context = context.subtarget(environment=self.env, + fndesc=self.fndesc) + + # Debuginfo + dibuildercls = (self.context.DIBuilder + if self.context.enable_debuginfo + else debuginfo.DummyDIBuilder) + + # debuginfo def location + self.defn_loc = self._compute_def_location() + + directives_only = self.flags.dbg_directives_only + self.debuginfo = dibuildercls(module=self.module, + filepath=func_ir.loc.filename, + cgctx=context, + directives_only=directives_only) + + # Loc notify objects + self._loc_notify_registry = get_registered_loc_notify() + + # Subclass initialization + self.init() + + @property + def call_conv(self): + return self.context.call_conv + + def init(self): + pass + + def init_pyapi(self): + """ + Init the Python API and Environment Manager for the function being + lowered. + """ + if self.pyapi is not None: + return + self.pyapi = self.context.get_python_api(self.builder) + + # Store environment argument for later use + self.env_manager = self.context.get_env_manager(self.builder) + self.env_body = self.env_manager.env_body + self.envarg = self.env_manager.env_ptr + + def _compute_def_location(self): + # Debuginfo requires source to be accurate. Find it and warn if not + # found. If it's not found, use the func_ir line + 1, this assumes that + # the function definition is decorated with a 1 line jit decorator. + defn_loc = self.func_ir.loc.with_lineno(self.func_ir.loc.line + 1) + if self.context.enable_debuginfo: + fn = self.func_ir.func_id.func + optional_lno = get_func_body_first_lineno(fn) + if optional_lno is not None: + # -1 as lines start at 1 and this is an offset. + offset = optional_lno - 1 + defn_loc = self.func_ir.loc.with_lineno(offset) + else: + msg = ("Could not find source for function: " + f"{self.func_ir.func_id.func}. Debug line information " + "may be inaccurate.") + warnings.warn(NumbaDebugInfoWarning(msg)) + return defn_loc + + def pre_lower(self): + """ + Called before lowering all blocks. + """ + # A given Lower object can be used for several LL functions + # (for generators) and it's important to use a new API and + # EnvironmentManager. + self.pyapi = None + self.debuginfo.mark_subprogram(function=self.builder.function, + qualname=self.fndesc.qualname, + argnames=self.fndesc.args, + argtypes=self.fndesc.argtypes, + line=self.defn_loc.line) + + # When full debug info is enabled, disable inlining where possible, to + # improve the quality of the debug experience. 'alwaysinline' functions + # cannot have inlining disabled. + attributes = self.builder.function.attributes + full_debug = self.flags.debuginfo and not self.flags.dbg_directives_only + if full_debug and 'alwaysinline' not in attributes: + attributes.add('noinline') + + def post_lower(self): + """ + Called after all blocks are lowered + """ + self.debuginfo.finalize() + for notify in self._loc_notify_registry: + notify.close() + + def pre_block(self, block): + """ + Called before lowering a block. + """ + + def post_block(self, block): + """ + Called after lowering a block. + """ + + def return_dynamic_exception(self, exc_class, exc_args, nb_types, loc=None): + self.call_conv.return_dynamic_user_exc( + self.builder, exc_class, exc_args, nb_types, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def return_exception(self, exc_class, exc_args=None, loc=None): + """Propagate exception to the caller. + """ + self.call_conv.return_user_exc( + self.builder, exc_class, exc_args, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def set_exception(self, exc_class, exc_args=None, loc=None): + """Set exception state in the current function. + """ + self.call_conv.set_static_user_exc( + self.builder, exc_class, exc_args, + loc=loc, func_name=self.func_ir.func_id.func_name, + ) + + def emit_environment_object(self): + """Emit a pointer to hold the Environment object. + """ + # Define global for the environment and initialize it to NULL + envname = self.context.get_env_name(self.fndesc) + self.context.declare_env_global(self.module, envname) + + def lower(self): + # Emit the Env into the module + self.emit_environment_object() + if self.generator_info is None: + self.genlower = None + self.lower_normal_function(self.fndesc) + else: + self.genlower = self.GeneratorLower(self) + self.gentype = self.genlower.gentype + + self.genlower.lower_init_func(self) + self.genlower.lower_next_func(self) + if self.gentype.has_finalizer: + self.genlower.lower_finalize_func(self) + + if config.DUMP_LLVM: + utils.dump_llvm(self.fndesc, self.module) + + # Special optimization to remove NRT on functions that do not need it. + if self.context.enable_nrt and self.generator_info is None: + removerefctpass.remove_unnecessary_nrt_usage(self.function, + context=self.context, + fndesc=self.fndesc) + + # Run target specific post lowering transformation + self.context.post_lowering(self.module, self.library) + + # Materialize LLVM Module + self.library.add_ir_module(self.module) + + def extract_function_arguments(self): + self.fnargs = self.call_conv.decode_arguments(self.builder, + self.fndesc.argtypes, + self.function) + return self.fnargs + + def lower_normal_function(self, fndesc): + """ + Lower non-generator *fndesc*. + """ + self.setup_function(fndesc) + + # Init argument values + self.extract_function_arguments() + entry_block_tail = self.lower_function_body() + + # Close tail of entry block, do not emit debug metadata else the + # unconditional jump gets associated with the metadata from the function + # body end. + with debuginfo.suspend_emission(self.builder): + self.builder.position_at_end(entry_block_tail) + self.builder.branch(self.blkmap[self.firstblk]) + + def lower_function_body(self): + """ + Lower the current function's body, and return the entry block. + """ + # Init Python blocks + for offset in self.blocks: + bname = "B%s" % offset + self.blkmap[offset] = self.function.append_basic_block(bname) + + self.pre_lower() + # pre_lower() may have changed the current basic block + entry_block_tail = self.builder.basic_block + + self.debug_print("# function begin: {0}".format( + self.fndesc.unique_name)) + + # Lower all blocks + for offset, block in sorted(self.blocks.items()): + bb = self.blkmap[offset] + self.builder.position_at_end(bb) + self.debug_print(f"# lower block: {offset}") + self.lower_block(block) + self.post_lower() + return entry_block_tail + + def lower_block(self, block): + """ + Lower the given block. + """ + self.pre_block(block) + for inst in block.body: + self.loc = inst.loc + defaulterrcls = partial(LoweringError, loc=self.loc) + with new_error_context('lowering "{inst}" at {loc}', inst=inst, + loc=self.loc, errcls_=defaulterrcls): + self.lower_inst(inst) + self.post_block(block) + + def create_cpython_wrapper(self, release_gil=False): + """ + Create CPython wrapper(s) around this function (or generator). + """ + if self.genlower: + self.context.create_cpython_wrapper(self.library, + self.genlower.gendesc, + self.env, self.call_helper, + release_gil=release_gil) + self.context.create_cpython_wrapper(self.library, self.fndesc, + self.env, self.call_helper, + release_gil=release_gil) + + def create_cfunc_wrapper(self): + """ + Create C wrapper around this function. + """ + if self.genlower: + raise UnsupportedError('generator as a first-class function type') + self.context.create_cfunc_wrapper(self.library, self.fndesc, + self.env, self.call_helper) + + def setup_function(self, fndesc): + # Setup function + self.function = self.context.declare_function(self.module, fndesc) + if self.flags.dbg_optnone: + attrset = self.function.attributes + if "alwaysinline" not in attrset: + attrset.add("optnone") + attrset.add("noinline") + self.entry_block = self.function.append_basic_block('entry') + self.builder = IRBuilder(self.entry_block) + self.call_helper = self.call_conv.init_call_helper(self.builder) + + def typeof(self, varname): + return self.fndesc.typemap[varname] + + def notify_loc(self, loc: ir.Loc) -> None: + """Called when a new instruction with the given `loc` is about to be + lowered. + """ + for notify_obj in self._loc_notify_registry: + notify_obj.notify(loc) + + def debug_print(self, msg): + if config.DEBUG_JIT: + self.context.debug_print( + self.builder, f"DEBUGJIT [{self.fndesc.qualname}]: {msg}") + + def print_variable(self, msg, varname): + """Helper to emit ``print(msg, varname)`` for debugging. + + Parameters + ---------- + msg : str + Literal string to be printed. + varname : str + A variable name whose value will be printed. + """ + argtys = ( + types.literal(msg), + self.fndesc.typemap[varname] + ) + args = ( + self.context.get_dummy_value(), + self.loadvar(varname), + ) + sig = typing.signature(types.none, *argtys) + + impl = self.context.get_function(print, sig) + impl(self.builder, args) + + +class Lower(BaseLower): + GeneratorLower = generators.GeneratorLower + + def init(self): + super().init() + # find all singly assigned variables + self._find_singly_assigned_variable() + + @property + def _disable_sroa_like_opt(self): + """Flags that the SROA like optimisation that Numba performs (which + prevent alloca and subsequent load/store for locals) should be disabled. + Currently, this is conditional solely on the presence of a request for + the emission of debug information.""" + if self.flags is None: + return False + + return self.flags.debuginfo and not self.flags.dbg_directives_only + + def _find_singly_assigned_variable(self): + func_ir = self.func_ir + blocks = func_ir.blocks + + sav = set() + + if not self.func_ir.func_id.is_generator: + use_defs = compute_use_defs(blocks) + alloca_vars = must_use_alloca(blocks) + + # Compute where variables are defined + var_assign_map = defaultdict(set) + for blk, vl in use_defs.defmap.items(): + for var in vl: + var_assign_map[var].add(blk) + + # Compute where variables are used + var_use_map = defaultdict(set) + for blk, vl in use_defs.usemap.items(): + for var in vl: + var_use_map[var].add(blk) + + # Keep only variables that are defined locally and used locally + for var in var_assign_map: + if var not in alloca_vars and len(var_assign_map[var]) == 1: + # Usemap does not keep locally defined variables. + if len(var_use_map[var]) == 0: + # Ensure that the variable is not defined multiple times + # in the block + [defblk] = var_assign_map[var] + assign_stmts = self.blocks[defblk].find_insts(ir.Assign) + assigns = [stmt for stmt in assign_stmts + if stmt.target.name == var] + if len(assigns) == 1: + sav.add(var) + + self._singly_assigned_vars = sav + self._blk_local_varmap = {} + + def pre_block(self, block): + from numba.core.unsafe import eh + + super(Lower, self).pre_block(block) + self._cur_ir_block = block + + if block == self.firstblk: + # create slots for all the vars, irrespective of whether they are + # initialized, SSA will pick this up and warn users about using + # uninitialized variables. Slots are added as alloca in the first + # block + bb = self.blkmap[self.firstblk] + self.builder.position_at_end(bb) + all_names = set() + for block in self.blocks.values(): + for x in block.find_insts(ir.Del): + if x.value not in all_names: + all_names.add(x.value) + for name in all_names: + fetype = self.typeof(name) + self._alloca_var(name, fetype) + + # Detect if we are in a TRY block by looking for a call to + # `eh.exception_check`. + for call in block.find_exprs(op='call'): + defn = ir_utils.guard( + ir_utils.get_definition, self.func_ir, call.func, + ) + if defn is not None and isinstance(defn, ir.Global): + if defn.value is eh.exception_check: + if isinstance(block.terminator, ir.Branch): + targetblk = self.blkmap[block.terminator.truebr] + # NOTE: This hacks in an attribute for call_conv to + # pick up. This hack is no longer needed when + # all old-style implementations are gone. + self.builder._in_try_block = {'target': targetblk} + break + + def post_block(self, block): + # Clean-up + try: + del self.builder._in_try_block + except AttributeError: + pass + + def lower_inst(self, inst): + # Set debug location for all subsequent LL instructions + self.debuginfo.mark_location(self.builder, self.loc.line) + self.notify_loc(self.loc) + self.debug_print(str(inst)) + if isinstance(inst, ir.Assign): + ty = self.typeof(inst.target.name) + val = self.lower_assign(ty, inst) + argidx = None + # If this is a store from an arg, like x = arg.x then tell debuginfo + # that this is the arg + if isinstance(inst.value, ir.Arg): + # NOTE: debug location is the `def ` line + self.debuginfo.mark_location(self.builder, self.defn_loc.line) + argidx = inst.value.index + 1 # args start at 1 + self.storevar(val, inst.target.name, argidx=argidx) + + elif isinstance(inst, ir.Branch): + cond = self.loadvar(inst.cond.name) + tr = self.blkmap[inst.truebr] + fl = self.blkmap[inst.falsebr] + + condty = self.typeof(inst.cond.name) + pred = self.context.cast(self.builder, cond, condty, types.boolean) + assert pred.type == llvmlite.ir.IntType(1),\ + ("cond is not i1: %s" % pred.type) + self.builder.cbranch(pred, tr, fl) + + elif isinstance(inst, ir.Jump): + target = self.blkmap[inst.target] + self.builder.branch(target) + + elif isinstance(inst, ir.Return): + if self.generator_info: + # StopIteration + self.genlower.return_from_generator(self) + return + val = self.loadvar(inst.value.name) + oty = self.typeof(inst.value.name) + ty = self.fndesc.restype + if isinstance(ty, types.Optional): + # If returning an optional type + self.call_conv.return_optional_value(self.builder, ty, oty, val) + return + assert ty == oty, ( + "type '{}' does not match return type '{}'".format(oty, ty)) + retval = self.context.get_return_value(self.builder, ty, val) + self.call_conv.return_value(self.builder, retval) + + elif isinstance(inst, ir.PopBlock): + pass # this is just a marker + + elif isinstance(inst, ir.StaticSetItem): + signature = self.fndesc.calltypes[inst] + assert signature is not None + try: + impl = self.context.get_function('static_setitem', signature) + except NotImplementedError: + return self.lower_setitem(inst.target, inst.index_var, + inst.value, signature) + else: + target = self.loadvar(inst.target.name) + value = self.loadvar(inst.value.name) + valuety = self.typeof(inst.value.name) + value = self.context.cast(self.builder, value, valuety, + signature.args[2]) + return impl(self.builder, (target, inst.index, value)) + + elif isinstance(inst, ir.Print): + self.lower_print(inst) + + elif isinstance(inst, ir.SetItem): + signature = self.fndesc.calltypes[inst] + assert signature is not None + return self.lower_setitem(inst.target, inst.index, inst.value, + signature) + + elif isinstance(inst, ir.StoreMap): + signature = self.fndesc.calltypes[inst] + assert signature is not None + return self.lower_setitem(inst.dct, inst.key, inst.value, signature) + + elif isinstance(inst, ir.DelItem): + target = self.loadvar(inst.target.name) + index = self.loadvar(inst.index.name) + + targetty = self.typeof(inst.target.name) + indexty = self.typeof(inst.index.name) + + signature = self.fndesc.calltypes[inst] + assert signature is not None + + op = operator.delitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + assert targetty == signature.args[0] + index = self.context.cast(self.builder, index, indexty, + signature.args[1]) + + return impl(self.builder, (target, index)) + + elif isinstance(inst, ir.Del): + self.delvar(inst.value) + + elif isinstance(inst, ir.SetAttr): + target = self.loadvar(inst.target.name) + value = self.loadvar(inst.value.name) + signature = self.fndesc.calltypes[inst] + + targetty = self.typeof(inst.target.name) + valuety = self.typeof(inst.value.name) + assert signature is not None + assert signature.args[0] == targetty + impl = self.context.get_setattr(inst.attr, signature) + + # Convert argument to match + value = self.context.cast(self.builder, value, valuety, + signature.args[1]) + + return impl(self.builder, (target, value)) + + elif isinstance(inst, ir.DynamicRaise): + self.lower_dynamic_raise(inst) + + elif isinstance(inst, ir.DynamicTryRaise): + self.lower_try_dynamic_raise(inst) + + elif isinstance(inst, ir.StaticRaise): + self.lower_static_raise(inst) + + elif isinstance(inst, ir.StaticTryRaise): + self.lower_static_try_raise(inst) + + else: + raise NotImplementedError(type(inst)) + + def lower_setitem(self, target_var, index_var, value_var, signature): + target = self.loadvar(target_var.name) + value = self.loadvar(value_var.name) + index = self.loadvar(index_var.name) + + targetty = self.typeof(target_var.name) + valuety = self.typeof(value_var.name) + indexty = self.typeof(index_var.name) + + op = operator.setitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + # Convert argument to match + if isinstance(targetty, types.Optional): + target = self.context.cast(self.builder, target, targetty, + targetty.type) + else: + ul = types.unliteral + assert ul(targetty) == ul(signature.args[0]) + + index = self.context.cast(self.builder, index, indexty, + signature.args[1]) + value = self.context.cast(self.builder, value, valuety, + signature.args[2]) + + return impl(self.builder, (target, index, value)) + + def lower_try_dynamic_raise(self, inst): + # Numba is a bit limited in what it can do with exceptions in a try + # block. Thus, it is safe to use the same code as the static try raise. + self.lower_static_try_raise(inst) + + def lower_dynamic_raise(self, inst): + exc_args = inst.exc_args + args = [] + nb_types = [] + for exc_arg in exc_args: + if isinstance(exc_arg, ir.Var): + # dynamic values + typ = self.typeof(exc_arg.name) + val = self.loadvar(exc_arg.name) + self.incref(typ, val) + else: + typ = None + val = exc_arg + nb_types.append(typ) + args.append(val) + + self.return_dynamic_exception(inst.exc_class, tuple(args), + tuple(nb_types), loc=self.loc) + + def lower_static_raise(self, inst): + if inst.exc_class is None: + # Reraise + self.return_exception(None, loc=self.loc) + else: + self.return_exception(inst.exc_class, inst.exc_args, loc=self.loc) + + def lower_static_try_raise(self, inst): + if inst.exc_class is None: + # Reraise + self.set_exception(None, loc=self.loc) + else: + self.set_exception(inst.exc_class, inst.exc_args, loc=self.loc) + + def lower_assign(self, ty, inst): + value = inst.value + # In nopython mode, closure vars are frozen like globals + if isinstance(value, (ir.Const, ir.Global, ir.FreeVar)): + res = self.context.get_constant_generic(self.builder, ty, + value.value) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Expr): + return self.lower_expr(ty, value) + + elif isinstance(value, ir.Var): + val = self.loadvar(value.name) + oty = self.typeof(value.name) + res = self.context.cast(self.builder, val, oty, ty) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Arg): + # Suspend debug info else all the arg repacking ends up being + # associated with some line or other and it's actually just a detail + # of Numba's CC. + with debuginfo.suspend_emission(self.builder): + # Cast from the argument type to the local variable type + # (note the "arg.FOO" convention as used in typeinfer) + argty = self.typeof("arg." + value.name) + if isinstance(argty, types.Omitted): + pyval = argty.value + tyctx = self.context.typing_context + valty = tyctx.resolve_value_type_prefer_literal(pyval) + # use the type of the constant value + const = self.context.get_constant_generic( + self.builder, valty, pyval, + ) + # cast it to the variable type + res = self.context.cast(self.builder, const, valty, ty) + else: + val = self.fnargs[value.index] + res = self.context.cast(self.builder, val, argty, ty) + self.incref(ty, res) + return res + + elif isinstance(value, ir.Yield): + res = self.lower_yield(ty, value) + self.incref(ty, res) + return res + + raise NotImplementedError(type(value), value) + + def lower_yield(self, retty, inst): + yp = self.generator_info.yield_points[inst.index] + assert yp.inst is inst + y = generators.LowerYield(self, yp, yp.live_vars) + y.lower_yield_suspend() + # Yield to caller + val = self.loadvar(inst.value.name) + typ = self.typeof(inst.value.name) + actual_rettyp = self.gentype.yield_type + + # cast the local val to the type yielded + yret = self.context.cast(self.builder, val, typ, actual_rettyp) + + # get the return repr of yielded value + retval = self.context.get_return_value( + self.builder, actual_rettyp, yret, + ) + + # return + self.call_conv.return_value(self.builder, retval) + + # Resumption point + y.lower_yield_resume() + # None is returned by the yield expression + return self.context.get_constant_generic(self.builder, retty, None) + + def lower_binop(self, resty, expr, op): + # if op in utils.OPERATORS_TO_BUILTINS: + # map operator.the_op => the corresponding types.Function() + # TODO: is this looks dodgy ... + op = self.context.typing_context.resolve_value_type(op) + + lhs = expr.lhs + rhs = expr.rhs + static_lhs = expr.static_lhs + static_rhs = expr.static_rhs + lty = self.typeof(lhs.name) + rty = self.typeof(rhs.name) + lhs = self.loadvar(lhs.name) + rhs = self.loadvar(rhs.name) + + # Convert argument to match + signature = self.fndesc.calltypes[expr] + lhs = self.context.cast(self.builder, lhs, lty, signature.args[0]) + rhs = self.context.cast(self.builder, rhs, rty, signature.args[1]) + + def cast_result(res): + return self.context.cast(self.builder, res, + signature.return_type, resty) + + # First try with static operands, if known + def try_static_impl(tys, args): + if any(a is ir.UNDEFINED for a in args): + return None + try: + if isinstance(op, types.Function): + static_sig = op.get_call_type(self.context.typing_context, + tys, {}) + else: + static_sig = typing.signature(signature.return_type, *tys) + except TypingError: + return None + try: + static_impl = self.context.get_function(op, static_sig) + return static_impl(self.builder, args) + except NotImplementedError: + return None + + res = try_static_impl( + (_lit_or_omitted(static_lhs), _lit_or_omitted(static_rhs)), + (static_lhs, static_rhs), + ) + if res is not None: + return cast_result(res) + + res = try_static_impl( + (_lit_or_omitted(static_lhs), rty), + (static_lhs, rhs), + ) + if res is not None: + return cast_result(res) + + res = try_static_impl( + (lty, _lit_or_omitted(static_rhs)), + (lhs, static_rhs), + ) + if res is not None: + return cast_result(res) + + # Normal implementation for generic arguments + + sig = op.get_call_type(self.context.typing_context, signature.args, {}) + impl = self.context.get_function(op, sig) + res = impl(self.builder, (lhs, rhs)) + return cast_result(res) + + def lower_getitem(self, resty, expr, value, index, signature): + baseval = self.loadvar(value.name) + indexval = self.loadvar(index.name) + # Get implementation of getitem + op = operator.getitem + fnop = self.context.typing_context.resolve_value_type(op) + callsig = fnop.get_call_type( + self.context.typing_context, signature.args, {}, + ) + impl = self.context.get_function(fnop, callsig) + + argvals = (baseval, indexval) + argtyps = (self.typeof(value.name), + self.typeof(index.name)) + castvals = [self.context.cast(self.builder, av, at, ft) + for av, at, ft in zip(argvals, argtyps, + signature.args)] + res = impl(self.builder, castvals) + return self.context.cast(self.builder, res, + signature.return_type, + resty) + + def _cast_var(self, var, ty): + """ + Cast a Numba IR variable to the given Numba type, returning a + low-level value. + """ + if isinstance(var, _VarArgItem): + varty = self.typeof(var.vararg.name)[var.index] + val = self.builder.extract_value(self.loadvar(var.vararg.name), + var.index) + else: + varty = self.typeof(var.name) + val = self.loadvar(var.name) + return self.context.cast(self.builder, val, varty, ty) + + def fold_call_args(self, fnty, signature, pos_args, vararg, kw_args): + if vararg: + # Inject *args from function call + # The lowering will be done in _cast_var() above. + tp_vararg = self.typeof(vararg.name) + assert isinstance(tp_vararg, types.BaseTuple) + pos_args = pos_args + [_VarArgItem(vararg, i) + for i in range(len(tp_vararg))] + + # Fold keyword arguments and resolve default argument values + pysig = signature.pysig + if pysig is None: + if kw_args: + raise NotImplementedError("unsupported keyword arguments " + "when calling %s" % (fnty,)) + argvals = [self._cast_var(var, sigty) + for var, sigty in zip(pos_args, signature.args)] + else: + def normal_handler(index, param, var): + return self._cast_var(var, signature.args[index]) + + def default_handler(index, param, default): + return self.context.get_constant_generic( + self.builder, signature.args[index], default) + + def stararg_handler(index, param, vars): + stararg_ty = signature.args[index] + assert isinstance(stararg_ty, types.BaseTuple), stararg_ty + values = [self._cast_var(var, sigty) + for var, sigty in zip(vars, stararg_ty)] + return cgutils.make_anonymous_struct(self.builder, values) + + argvals = typing.fold_arguments(pysig, + pos_args, dict(kw_args), + normal_handler, + default_handler, + stararg_handler) + return argvals + + def lower_print(self, inst): + """ + Lower a ir.Print() + """ + # We handle this, as far as possible, as a normal call to built-in + # print(). This will make it easy to undo the special ir.Print + # rewrite when it becomes unnecessary (e.g. when we have native + # strings). + sig = self.fndesc.calltypes[inst] + assert sig.return_type == types.none + fnty = self.context.typing_context.resolve_value_type(print) + + # Fix the call signature to inject any constant-inferred + # string argument + pos_tys = list(sig.args) + pos_args = list(inst.args) + for i in range(len(pos_args)): + if i in inst.consts: + pyval = inst.consts[i] + if isinstance(pyval, str): + pos_tys[i] = types.literal(pyval) + + fixed_sig = typing.signature(sig.return_type, *pos_tys) + fixed_sig = fixed_sig.replace(pysig=sig.pysig) + + argvals = self.fold_call_args(fnty, sig, pos_args, inst.vararg, {}) + impl = self.context.get_function(print, fixed_sig) + impl(self.builder, argvals) + + def lower_call(self, resty, expr): + signature = self.fndesc.calltypes[expr] + self.debug_print("# lower_call: expr = {0}".format(expr)) + if isinstance(signature.return_type, types.Phantom): + return self.context.get_dummy_value() + + fnty = self.typeof(expr.func.name) + + if isinstance(fnty, types.ObjModeDispatcher): + res = self._lower_call_ObjModeDispatcher(fnty, expr, signature) + + elif isinstance(fnty, types.ExternalFunction): + res = self._lower_call_ExternalFunction(fnty, expr, signature) + + elif isinstance(fnty, types.ExternalFunctionPointer): + res = self._lower_call_ExternalFunctionPointer( + fnty, expr, signature) + + elif isinstance(fnty, types.RecursiveCall): + res = self._lower_call_RecursiveCall(fnty, expr, signature) + + elif isinstance(fnty, types.FunctionType): + res = self._lower_call_FunctionType(fnty, expr, signature) + + else: + res = self._lower_call_normal(fnty, expr, signature) + + # If lowering the call returned None, interpret that as returning dummy + # value if the return type of the function is void, otherwise there is + # a problem + if res is None: + if signature.return_type == types.void: + res = self.context.get_dummy_value() + else: + raise LoweringError( + msg="non-void function returns None from implementation", + loc=self.loc + ) + + return self.context.cast(self.builder, res, signature.return_type, + resty) + + def _lower_call_ObjModeDispatcher(self, fnty, expr, signature): + from numba.core.pythonapi import ObjModeUtils + + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + # Fix types + argnames = [a.name for a in expr.args] + argtypes = [self.typeof(a) for a in argnames] + argvalues = [self.loadvar(a) for a in argnames] + for v, ty in zip(argvalues, argtypes): + # Because .from_native_value steal the reference + self.incref(ty, v) + + argobjs = [self.pyapi.from_native_value(atyp, aval, + self.env_manager) + for atyp, aval in zip(argtypes, argvalues)] + + # Load objmode dispatcher + callee = ObjModeUtils(self.pyapi).load_dispatcher(fnty, argtypes) + # Make Call + ret_obj = self.pyapi.call_function_objargs(callee, argobjs) + has_exception = cgutils.is_null(self.builder, ret_obj) + with self. builder.if_else(has_exception) as (then, orelse): + # Handles exception + # This branch must exit the function + with then: + # Clean arg + for obj in argobjs: + self.pyapi.decref(obj) + + # Release the GIL + self.pyapi.gil_release(gil_state) + + # Return and signal exception + self.call_conv.return_exc(self.builder) + + # Handles normal return + with orelse: + # Fix output value + native = self.pyapi.to_native_value( + fnty.dispatcher.output_types, + ret_obj, + ) + output = native.value + + # Release objs + self.pyapi.decref(ret_obj) + for obj in argobjs: + self.pyapi.decref(obj) + + # cleanup output + if callable(native.cleanup): + native.cleanup() + + # Release the GIL + self.pyapi.gil_release(gil_state) + + # Error during unboxing + with self.builder.if_then(native.is_error): + self.call_conv.return_exc(self.builder) + + return output + + def _lower_call_ExternalFunction(self, fnty, expr, signature): + # Handle a named external function + self.debug_print("# external function") + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + fndesc = funcdesc.ExternalFunctionDescriptor( + fnty.symbol, fnty.sig.return_type, fnty.sig.args) + func = self.context.declare_external_function( + self.builder.module, fndesc) + return self.context.call_external_function( + self.builder, func, fndesc.argtypes, argvals, + ) + + def _lower_call_ExternalFunctionPointer(self, fnty, expr, signature): + # Handle a C function pointer + self.debug_print("# calling external function pointer") + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + pointer = self.loadvar(expr.func.name) + # If the external function pointer uses libpython + if fnty.requires_gil: + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + # Make PyObjects + newargvals = [] + pyvals = [] + for exptyp, gottyp, aval in zip(fnty.sig.args, signature.args, + argvals): + # Adjust argument values to pyobjects + if exptyp == types.ffi_forced_object: + self.incref(gottyp, aval) + obj = self.pyapi.from_native_value( + gottyp, aval, self.env_manager, + ) + newargvals.append(obj) + pyvals.append(obj) + else: + newargvals.append(aval) + + # Call external function + res = self.context.call_function_pointer( + self.builder, pointer, newargvals, fnty.cconv, + ) + # Release PyObjects + for obj in pyvals: + self.pyapi.decref(obj) + + # Release the GIL + self.pyapi.gil_release(gil_state) + # If the external function pointer does NOT use libpython + else: + res = self.context.call_function_pointer( + self.builder, pointer, argvals, fnty.cconv, + ) + return res + + def _lower_call_RecursiveCall(self, fnty, expr, signature): + # Recursive call + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + rec_ov = fnty.get_overloads(signature.args) + mangler = self.context.mangler or default_mangler + abi_tags = self.fndesc.abi_tags + mangled_name = mangler(rec_ov.qualname, signature.args, + abi_tags=abi_tags, uid=rec_ov.uid) + # special case self recursion + if self.builder.function.name.startswith(mangled_name): + res = self.context.call_internal( + self.builder, self.fndesc, signature, argvals, + ) + else: + res = self.context.call_unresolved( + self.builder, mangled_name, signature, argvals, + ) + return res + + def _lower_call_FunctionType(self, fnty, expr, signature): + self.debug_print("# calling first-class function type") + sig = types.unliteral(signature) + if not fnty.check_signature(signature): + # value dependent polymorphism? + raise UnsupportedError( + f'mismatch of function types:' + f' expected {fnty} but got {types.FunctionType(sig)}') + argvals = self.fold_call_args( + fnty, sig, expr.args, expr.vararg, expr.kws, + ) + return self.__call_first_class_function_pointer( + fnty.ftype, expr.func.name, sig, argvals, + ) + + def __call_first_class_function_pointer(self, ftype, fname, sig, argvals): + """ + Calls a first-class function pointer. + + This function is responsible for calling a first-class function pointer, + which can either be a JIT-compiled function or a Python function. It + determines if a JIT address is available, and if so, calls the function + using the JIT address. Otherwise, it calls the function using a function + pointer obtained from the `__get_first_class_function_pointer` method. + + Args: + ftype: The type of the function. + fname: The name of the function. + sig: The signature of the function. + argvals: The argument values to pass to the function. + + Returns: + The result of calling the function. + """ + context = self.context + builder = self.builder + # Determine if jit address is available + fstruct = self.loadvar(fname) + struct = cgutils.create_struct_proxy(self.typeof(fname))( + context, builder, value=fstruct + ) + jit_addr = struct.jit_addr + jit_addr.name = f'jit_addr_of_{fname}' + + ctx = context + res_slot = cgutils.alloca_once(builder, + ctx.get_value_type(sig.return_type)) + + if_jit_addr_is_null = builder.if_else( + cgutils.is_null(builder, jit_addr), + likely=False + ) + with if_jit_addr_is_null as (then, orelse): + with then: + func_ptr = self.__get_first_class_function_pointer( + ftype, fname, sig) + res = builder.call(func_ptr, argvals) + builder.store(res, res_slot) + + with orelse: + llty = ctx.call_conv.get_function_type( + sig.return_type, + sig.args + ).as_pointer() + func_ptr = builder.bitcast(jit_addr, llty) + # call + status, res = ctx.call_conv.call_function( + builder, func_ptr, sig.return_type, sig.args, argvals + ) + with cgutils.if_unlikely(builder, status.is_error): + context.call_conv.return_status_propagate(builder, status) + builder.store(res, res_slot) + return builder.load(res_slot) + + def __get_first_class_function_pointer(self, ftype, fname, sig): + from numba.experimental.function_type import lower_get_wrapper_address + + llty = self.context.get_value_type(ftype) + fstruct = self.loadvar(fname) + addr = self.builder.extract_value(fstruct, 0, + name='addr_of_%s' % (fname)) + + fptr = cgutils.alloca_once(self.builder, llty, + name="fptr_of_%s" % (fname)) + with self.builder.if_else( + cgutils.is_null(self.builder, addr), + likely=False) as (then, orelse): + with then: + self.init_pyapi() + # Acquire the GIL + gil_state = self.pyapi.gil_ensure() + pyaddr = self.builder.extract_value( + fstruct, 1, + name='pyaddr_of_%s' % (fname)) + # try to recover the function address, see + # test_zero_address BadToGood example in + # test_function_type.py + addr1 = lower_get_wrapper_address( + self.context, self.builder, pyaddr, sig, + failure_mode='ignore') + with self.builder.if_then( + cgutils.is_null(self.builder, addr1), likely=False): + self.return_exception( + RuntimeError, + exc_args=(f"{ftype} function address is null",), + loc=self.loc) + addr2 = self.pyapi.long_as_voidptr(addr1) + self.builder.store(self.builder.bitcast(addr2, llty), fptr) + self.pyapi.decref(addr1) + self.pyapi.gil_release(gil_state) + with orelse: + self.builder.store(self.builder.bitcast(addr, llty), fptr) + return self.builder.load(fptr) + + def _lower_call_normal(self, fnty, expr, signature): + # Normal function resolution + self.debug_print("# calling normal function: {0}".format(fnty)) + self.debug_print("# signature: {0}".format(signature)) + if isinstance(fnty, types.ObjModeDispatcher): + argvals = expr.func.args + else: + argvals = self.fold_call_args( + fnty, signature, expr.args, expr.vararg, expr.kws, + ) + tname = expr.target + if tname is not None: + from numba.core.target_extension import resolve_dispatcher_from_str + disp = resolve_dispatcher_from_str(tname) + hw_ctx = disp.targetdescr.target_context + impl = hw_ctx.get_function(fnty, signature) + else: + impl = self.context.get_function(fnty, signature) + if signature.recvr: + # The "self" object is passed as the function object + # for bounded function + the_self = self.loadvar(expr.func.name) + # Prepend the self reference + argvals = [the_self] + list(argvals) + + res = impl(self.builder, argvals, self.loc) + return res + + def lower_expr(self, resty, expr): + if expr.op == 'binop': + return self.lower_binop(resty, expr, expr.fn) + elif expr.op == 'inplace_binop': + lty = self.typeof(expr.lhs.name) + if lty.mutable: + return self.lower_binop(resty, expr, expr.fn) + else: + # inplace operators on non-mutable types reuse the same + # definition as the corresponding copying operators.) + return self.lower_binop(resty, expr, expr.immutable_fn) + elif expr.op == 'unary': + val = self.loadvar(expr.value.name) + typ = self.typeof(expr.value.name) + func_ty = self.context.typing_context.resolve_value_type(expr.fn) + # Get function + signature = self.fndesc.calltypes[expr] + impl = self.context.get_function(func_ty, signature) + # Convert argument to match + val = self.context.cast(self.builder, val, typ, signature.args[0]) + res = impl(self.builder, [val]) + res = self.context.cast(self.builder, res, + signature.return_type, resty) + return res + + elif expr.op == 'call': + res = self.lower_call(resty, expr) + return res + + elif expr.op == 'pair_first': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + res = self.context.pair_first(self.builder, val, ty) + self.incref(resty, res) + return res + + elif expr.op == 'pair_second': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + res = self.context.pair_second(self.builder, val, ty) + self.incref(resty, res) + return res + + elif expr.op in ('getiter', 'iternext'): + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + signature = self.fndesc.calltypes[expr] + impl = self.context.get_function(expr.op, signature) + [fty] = signature.args + castval = self.context.cast(self.builder, val, ty, fty) + res = impl(self.builder, (castval,)) + res = self.context.cast(self.builder, res, signature.return_type, + resty) + return res + + elif expr.op == 'exhaust_iter': + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + # Unpack optional + if isinstance(ty, types.Optional): + val = self.context.cast(self.builder, val, ty, ty.type) + ty = ty.type + + # If we have a tuple, we needn't do anything + # (and we can't iterate over the heterogeneous ones). + if isinstance(ty, types.BaseTuple): + assert ty == resty + self.incref(ty, val) + return val + + itemty = ty.iterator_type.yield_type + tup = self.context.get_constant_undef(resty) + pairty = types.Pair(itemty, types.boolean) + getiter_sig = typing.signature(ty.iterator_type, ty) + getiter_impl = self.context.get_function('getiter', + getiter_sig) + iternext_sig = typing.signature(pairty, ty.iterator_type) + iternext_impl = self.context.get_function('iternext', + iternext_sig) + iterobj = getiter_impl(self.builder, (val,)) + # We call iternext() as many times as desired (`expr.count`). + for i in range(expr.count): + pair = iternext_impl(self.builder, (iterobj,)) + is_valid = self.context.pair_second(self.builder, + pair, pairty) + with cgutils.if_unlikely(self.builder, + self.builder.not_(is_valid)): + self.return_exception(ValueError, loc=self.loc) + item = self.context.pair_first(self.builder, + pair, pairty) + tup = self.builder.insert_value(tup, item, i) + + # Call iternext() once more to check that the iterator + # is exhausted. + pair = iternext_impl(self.builder, (iterobj,)) + is_valid = self.context.pair_second(self.builder, + pair, pairty) + with cgutils.if_unlikely(self.builder, is_valid): + self.return_exception(ValueError, loc=self.loc) + + self.decref(ty.iterator_type, iterobj) + return tup + + elif expr.op == "getattr": + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + + if isinstance(resty, types.BoundFunction): + # if we are getting out a method, assume we have typed this + # properly and just build a bound function object + casted = self.context.cast(self.builder, val, ty, resty.this) + res = self.context.get_bound_function(self.builder, casted, + resty.this) + self.incref(resty, res) + return res + else: + impl = self.context.get_getattr(ty, expr.attr) + attrty = self.context.typing_context.resolve_getattr(ty, + expr.attr) + + if impl is None: + # ignore the attribute + return self.context.get_dummy_value() + else: + res = impl(self.context, self.builder, ty, val, expr.attr) + + # Cast the attribute type to the expected output type + res = self.context.cast(self.builder, res, attrty, resty) + return res + + elif expr.op == "static_getitem": + signature = typing.signature( + resty, + self.typeof(expr.value.name), + _lit_or_omitted(expr.index), + ) + try: + # Both get_function() and the returned implementation can + # raise NotImplementedError if the types aren't supported + impl = self.context.get_function("static_getitem", signature) + return impl(self.builder, + (self.loadvar(expr.value.name), expr.index)) + except NotImplementedError: + if expr.index_var is None: + raise + # Fall back on the generic getitem() implementation + # for this type. + signature = self.fndesc.calltypes[expr] + return self.lower_getitem(resty, expr, expr.value, + expr.index_var, signature) + elif expr.op == "typed_getitem": + signature = typing.signature( + resty, + self.typeof(expr.value.name), + self.typeof(expr.index.name), + ) + impl = self.context.get_function("typed_getitem", signature) + return impl(self.builder, (self.loadvar(expr.value.name), + self.loadvar(expr.index.name))) + elif expr.op == "getitem": + signature = self.fndesc.calltypes[expr] + return self.lower_getitem(resty, expr, expr.value, expr.index, + signature) + + elif expr.op == "build_tuple": + itemvals = [self.loadvar(i.name) for i in expr.items] + itemtys = [self.typeof(i.name) for i in expr.items] + castvals = [self.context.cast(self.builder, val, fromty, toty) + for val, toty, fromty in zip(itemvals, resty, itemtys)] + tup = self.context.make_tuple(self.builder, resty, castvals) + self.incref(resty, tup) + return tup + + elif expr.op == "build_list": + itemvals = [self.loadvar(i.name) for i in expr.items] + itemtys = [self.typeof(i.name) for i in expr.items] + if isinstance(resty, types.LiteralList): + castvals = [self.context.cast(self.builder, val, fromty, toty) + for val, toty, fromty in zip(itemvals, resty.types, + itemtys)] + tup = self.context.make_tuple(self.builder, + types.Tuple(resty.types), + castvals) + self.incref(resty, tup) + return tup + else: + castvals = [self.context.cast(self.builder, val, fromty, + resty.dtype) + for val, fromty in zip(itemvals, itemtys)] + return self.context.build_list(self.builder, resty, castvals) + + elif expr.op == "build_set": + # Insert in reverse order, as Python does + items = expr.items[::-1] + itemvals = [self.loadvar(i.name) for i in items] + itemtys = [self.typeof(i.name) for i in items] + castvals = [self.context.cast(self.builder, val, fromty, + resty.dtype) + for val, fromty in zip(itemvals, itemtys)] + return self.context.build_set(self.builder, resty, castvals) + + elif expr.op == "build_map": + items = expr.items + keys, values = [], [] + key_types, value_types = [], [] + for k, v in items: + key = self.loadvar(k.name) + keytype = self.typeof(k.name) + val = self.loadvar(v.name) + valtype = self.typeof(v.name) + keys.append(key) + values.append(val) + key_types.append(keytype) + value_types.append(valtype) + return self.context.build_map(self.builder, resty, + list(zip(key_types, value_types)), + list(zip(keys, values))) + + elif expr.op == "cast": + val = self.loadvar(expr.value.name) + ty = self.typeof(expr.value.name) + castval = self.context.cast(self.builder, val, ty, resty) + self.incref(resty, castval) + return castval + + elif expr.op == "phi": + raise LoweringError("PHI not stripped") + + elif expr.op == 'null': + return self.context.get_constant_null(resty) + + elif expr.op == 'undef': + # Numba does not raise an UnboundLocalError for undefined variables. + # The variable is set to zero. + return self.context.get_constant_null(resty) + + elif expr.op in self.context.special_ops: + res = self.context.special_ops[expr.op](self, expr) + return res + + raise NotImplementedError(expr) + + def _alloca_var(self, name, fetype): + """ + Ensure the given variable has an allocated stack slot (if needed). + """ + if name in self.varmap: + # quit early + return + + # If the name is used in multiple blocks or lowering with debuginfo... + if ((name not in self._singly_assigned_vars) or + self._disable_sroa_like_opt): + # If not already defined, allocate it + ptr = self.alloca(name, fetype) + # Remember the pointer + self.varmap[name] = ptr + + def getvar(self, name): + """ + Get a pointer to the given variable's slot. + """ + if not self._disable_sroa_like_opt: + assert name not in self._blk_local_varmap + assert name not in self._singly_assigned_vars + if name not in self.varmap: + # Allocate undefined variable as needed. + # NOTE: Py3.12 use of LOAD_FAST_AND_CLEAR will allow variable be + # referenced before it is defined. + self._alloca_var(name, self.typeof(name)) + return self.varmap[name] + + def loadvar(self, name): + """ + Load the given variable's value. + """ + if name in self._blk_local_varmap and not self._disable_sroa_like_opt: + return self._blk_local_varmap[name] + ptr = self.getvar(name) + + # Don't associate debuginfo with the load for a function arg else it + # creates instructions ahead of the first source line of the + # function which then causes problems with breaking on the function + # symbol (it hits the symbol, not the first line). + if name in self.func_ir.arg_names: + with debuginfo.suspend_emission(self.builder): + return self.builder.load(ptr) + else: + return self.builder.load(ptr) + + def storevar(self, value, name, argidx=None): + """ + Store the value into the given variable. + """ + fetype = self.typeof(name) + # Define if not already + self._alloca_var(name, fetype) + + # Store variable + if (name in self._singly_assigned_vars and + not self._disable_sroa_like_opt): + self._blk_local_varmap[name] = value + else: + if argidx is None: + # Clean up existing value stored in the variable, not needed + # if it's an arg + old = self.loadvar(name) + self.decref(fetype, old) + + # stack stored variable + ptr = self.getvar(name) + if value.type != ptr.type.pointee: + msg = ("Storing {value.type} to ptr of {ptr.type.pointee} " + "('{name}'). FE type {fetype}").format(value=value, + ptr=ptr, + fetype=fetype, + name=name) + raise AssertionError(msg) + + # If this store is associated with an argument to the function (i.e. + # store following reassemble from CC splatting structs as many args + # to the function) then mark this variable as such. + if argidx is not None: + with debuginfo.suspend_emission(self.builder): + self.builder.store(value, ptr) + loc = self.defn_loc # the line with `def ` + lltype = self.context.get_value_type(fetype) + sizeof = self.context.get_abi_sizeof(lltype) + datamodel = self.context.data_model_manager[fetype] + self.debuginfo.mark_variable(self.builder, ptr, name=name, + lltype=lltype, size=sizeof, + line=loc.line, datamodel=datamodel, + argidx=argidx) + else: + self.builder.store(value, ptr) + + def delvar(self, name): + """ + Delete the given variable. + """ + fetype = self.typeof(name) + + # Out-of-order + if (name not in self._blk_local_varmap and + not self._disable_sroa_like_opt): + if name in self._singly_assigned_vars: + self._singly_assigned_vars.discard(name) + + # Define if not already (may happen if the variable is deleted + # at the beginning of a loop, but only set later in the loop) + self._alloca_var(name, fetype) + + if name in self._blk_local_varmap and not self._disable_sroa_like_opt: + llval = self._blk_local_varmap[name] + self.decref(fetype, llval) + else: + ptr = self.getvar(name) + self.decref(fetype, self.builder.load(ptr)) + # Zero-fill variable to avoid double frees on subsequent dels + self.builder.store(Constant(ptr.type.pointee, None), ptr) + + def alloca(self, name, type): + lltype = self.context.get_value_type(type) + datamodel = self.context.data_model_manager[type] + return self.alloca_lltype(name, lltype, datamodel=datamodel) + + def alloca_lltype(self, name, lltype, datamodel=None): + # Is user variable? + is_uservar = not name.startswith('$') + # Allocate space for variable + aptr = cgutils.alloca_once(self.builder, lltype, + name=name, zfill=False) + + # Emit debug info for user variable + if is_uservar: + # Don't associate debuginfo with the alloca for a function arg, this + # is handled by the first store to the alloca so that repacking the + # splatted args from the CC is dealt with. + if name not in self.func_ir.arg_names: + sizeof = self.context.get_abi_sizeof(lltype) + self.debuginfo.mark_variable(self.builder, aptr, name=name, + lltype=lltype, size=sizeof, + line=self.loc.line, + datamodel=datamodel,) + return aptr + + def incref(self, typ, val): + if not self.context.enable_nrt: + return + + self.context.nrt.incref(self.builder, typ, val) + + def decref(self, typ, val): + if not self.context.enable_nrt: + return + + # do not associate decref with "use", it creates "jumpy" line info as + # the decrefs are usually where the ir.Del nodes are, which is at the + # end of the block. + with debuginfo.suspend_emission(self.builder): + self.context.nrt.decref(self.builder, typ, val) + + +def _lit_or_omitted(value): + """Returns a Literal instance if the type of value is supported; + otherwise, return `Omitted(value)`. + """ + try: + return types.literal(value) + except LiteralTypingError: + return types.Omitted(value) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/object_mode_passes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/object_mode_passes.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b463c14b14e018df3fafdc68e0d7a5ca92489a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/object_mode_passes.py @@ -0,0 +1,147 @@ +from numba.core import (types, typing, funcdesc, config, pylowering, transforms, + errors) +from numba.core.compiler_machinery import (FunctionPass, LoweringPass, + register_pass) +from collections import defaultdict +import warnings + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ObjectModeFrontEnd(FunctionPass): + _name = "object_mode_front_end" + + def __init__(self): + FunctionPass.__init__(self) + + def _frontend_looplift(self, state): + """ + Loop lifting analysis and transformation + """ + loop_flags = state.flags.copy() + outer_flags = state.flags.copy() + # Do not recursively loop lift + outer_flags.enable_looplift = False + loop_flags.enable_looplift = False + if not state.flags.enable_pyobject_looplift: + loop_flags.enable_pyobject = False + loop_flags.enable_ssa = False + + main, loops = transforms.loop_lifting(state.func_ir, + typingctx=state.typingctx, + targetctx=state.targetctx, + locals=state.locals, + flags=loop_flags) + if loops: + # Some loops were extracted + if config.DEBUG_FRONTEND or config.DEBUG: + for loop in loops: + print("Lifting loop", loop.get_source_location()) + from numba.core.compiler import compile_ir + cres = compile_ir(state.typingctx, state.targetctx, main, + state.args, state.return_type, + outer_flags, state.locals, + lifted=tuple(loops), lifted_from=None, + is_lifted_loop=True) + return cres + + def run_pass(self, state): + from numba.core.compiler import _EarlyPipelineCompletion + # NOTE: That so much stuff, including going back into the compiler, is + # captured in a single pass is not ideal. + if state.flags.enable_looplift: + assert not state.lifted + cres = self._frontend_looplift(state) + if cres is not None: + raise _EarlyPipelineCompletion(cres) + + # Fallback typing: everything is a python object + state.typemap = defaultdict(lambda: types.pyobject) + state.calltypes = defaultdict(lambda: types.pyobject) + state.return_type = types.pyobject + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ObjectModeBackEnd(LoweringPass): + + _name = "object_mode_back_end" + + def __init__(self): + LoweringPass.__init__(self) + + def _py_lowering_stage(self, targetctx, library, interp, flags): + fndesc = funcdesc.PythonFunctionDescriptor.from_object_mode_function( + interp + ) + with targetctx.push_code_library(library): + lower = pylowering.PyLower(targetctx, library, fndesc, interp) + lower.lower() + if not flags.no_cpython_wrapper: + lower.create_cpython_wrapper() + env = lower.env + call_helper = lower.call_helper + del lower + from numba.core.compiler import _LowerResult # TODO: move this + if flags.no_compile: + return _LowerResult(fndesc, call_helper, cfunc=None, env=env) + else: + # Prepare for execution + cfunc = targetctx.get_executable(library, fndesc, env) + return _LowerResult(fndesc, call_helper, cfunc=cfunc, env=env) + + def run_pass(self, state): + """ + Lowering for object mode + """ + + if state.library is None: + codegen = state.targetctx.codegen() + state.library = codegen.create_library(state.func_id.func_qualname) + # Enable object caching upfront, so that the library can + # be later serialized. + state.library.enable_object_caching() + + def backend_object_mode(): + """ + Object mode compilation + """ + if len(state.args) != state.nargs: + # append missing + # BUG?: What's going on with nargs here? + # check state.nargs vs self.nargs on original code + state.args = (tuple(state.args) + (types.pyobject,) * + (state.nargs - len(state.args))) + + return self._py_lowering_stage(state.targetctx, + state.library, + state.func_ir, + state.flags) + + lowered = backend_object_mode() + signature = typing.signature(state.return_type, *state.args) + from numba.core.compiler import compile_result + state.cr = compile_result( + typing_context=state.typingctx, + target_context=state.targetctx, + entry_point=lowered.cfunc, + typing_error=state.status.fail_reason, + type_annotation=state.type_annotation, + library=state.library, + call_helper=lowered.call_helper, + signature=signature, + objectmode=True, + lifted=state.lifted, + fndesc=lowered.fndesc, + environment=lowered.env, + metadata=state.metadata, + reload_init=state.reload_init, + ) + + if state.flags.release_gil: + warn_msg = ("Code running in object mode won't allow parallel" + " execution despite nogil=True.") + warnings.warn_explicit(warn_msg, errors.NumbaWarning, + state.func_id.filename, + state.func_id.firstlineno) + + return True diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/optional.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/optional.py new file mode 100644 index 0000000000000000000000000000000000000000..16dcb52360ad2190c9b6af44023a362bbc33bf37 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/optional.py @@ -0,0 +1,121 @@ +import operator + +from numba.core import types, typing, cgutils + +from numba.core.imputils import (lower_cast, lower_builtin, + lower_getattr_generic, impl_ret_untracked, + lower_setattr_generic) + + +def always_return_true_impl(context, builder, sig, args): + return cgutils.true_bit + + +def always_return_false_impl(context, builder, sig, args): + return cgutils.false_bit + + +def optional_is_none(context, builder, sig, args): + """ + Check if an Optional value is invalid + """ + [lty, rty] = sig.args + [lval, rval] = args + + # Make sure None is on the right + if lty == types.none: + lty, rty = rty, lty + lval, rval = rval, lval + + opt_type = lty + opt_val = lval + + opt = context.make_helper(builder, opt_type, opt_val) + res = builder.not_(cgutils.as_bool_bit(builder, opt.valid)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# None is/not None +lower_builtin(operator.is_, types.none, types.none)(always_return_true_impl) + +# Optional is None +lower_builtin(operator.is_, types.Optional, types.none)(optional_is_none) +lower_builtin(operator.is_, types.none, types.Optional)(optional_is_none) + + +@lower_getattr_generic(types.Optional) +def optional_getattr(context, builder, typ, value, attr): + """ + Optional.__getattr__ => redirect to the wrapped type. + """ + inner_type = typ.type + val = context.cast(builder, value, typ, inner_type) + imp = context.get_getattr(inner_type, attr) + return imp(context, builder, inner_type, val, attr) + + +@lower_setattr_generic(types.Optional) +def optional_setattr(context, builder, sig, args, attr): + """ + Optional.__setattr__ => redirect to the wrapped type. + """ + basety, valty = sig.args + target, val = args + target_type = basety.type + target = context.cast(builder, target, basety, target_type) + + newsig = typing.signature(sig.return_type, target_type, valty) + imp = context.get_setattr(attr, newsig) + return imp(builder, (target, val)) + + +@lower_cast(types.Optional, types.Optional) +def optional_to_optional(context, builder, fromty, toty, val): + """ + The handling of optional->optional cast must be special cased for + correct propagation of None value. Given type T and U. casting of + T? to U? (? denotes optional) should always succeed. If the from-value + is None, the None value the casted value (U?) should be None; otherwise, + the from-value is casted to U. This is different from casting T? to U, + which requires the from-value must not be None. + """ + optval = context.make_helper(builder, fromty, value=val) + validbit = cgutils.as_bool_bit(builder, optval.valid) + # Create uninitialized optional value + outoptval = context.make_helper(builder, toty) + + with builder.if_else(validbit) as (is_valid, is_not_valid): + with is_valid: + # Cast internal value + outoptval.valid = cgutils.true_bit + outoptval.data = context.cast(builder, optval.data, + fromty.type, toty.type) + + with is_not_valid: + # Store None to result + outoptval.valid = cgutils.false_bit + outoptval.data = cgutils.get_null_value( + outoptval.data.type) + + return outoptval._getvalue() + + +@lower_cast(types.Any, types.Optional) +def any_to_optional(context, builder, fromty, toty, val): + if fromty == types.none: + return context.make_optional_none(builder, toty.type) + else: + val = context.cast(builder, val, fromty, toty.type) + return context.make_optional_value(builder, toty.type, val) + + +@lower_cast(types.Optional, types.Any) +@lower_cast(types.Optional, types.Boolean) +def optional_to_any(context, builder, fromty, toty, val): + optval = context.make_helper(builder, fromty, value=val) + validbit = cgutils.as_bool_bit(builder, optval.valid) + with builder.if_then(builder.not_(validbit), likely=False): + msg = "expected %s, got None" % (fromty.type,) + context.call_conv.return_user_exc(builder, TypeError, (msg,)) + + return context.cast(builder, optval.data, fromty.type, toty) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/options.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/options.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e99c8daad1e9cdbec479aba13bcd069e5148f9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/options.py @@ -0,0 +1,108 @@ +""" +Target Options +""" +import operator + +from numba.core import config, utils +from numba.core.targetconfig import TargetConfig, Option + + +class TargetOptions: + """Target options maps user options from decorators to the + ``numba.core.compiler.Flags`` used by lowering and target context. + """ + class Mapping: + def __init__(self, flag_name, apply=lambda x: x): + self.flag_name = flag_name + self.apply = apply + + def finalize(self, flags, options): + """Subclasses can override this method to make target specific + customizations of default flags. + + Parameters + ---------- + flags : Flags + options : dict + """ + pass + + @classmethod + def parse_as_flags(cls, flags, options): + """Parse target options defined in ``options`` and set ``flags`` + accordingly. + + Parameters + ---------- + flags : Flags + options : dict + """ + opt = cls() + opt._apply(flags, options) + opt.finalize(flags, options) + return flags + + def _apply(self, flags, options): + # Find all Mapping instances in the class + mappings = {} + cls = type(self) + for k in dir(cls): + v = getattr(cls, k) + if isinstance(v, cls.Mapping): + mappings[k] = v + + used = set() + for k, mapping in mappings.items(): + if k in options: + v = mapping.apply(options[k]) + setattr(flags, mapping.flag_name, v) + used.add(k) + + unused = set(options) - used + if unused: + # Unread options? + m = (f"Unrecognized options: {unused}. " + f"Known options are {mappings.keys()}") + raise KeyError(m) + + +_mapping = TargetOptions.Mapping + + +class DefaultOptions: + """Defines how user-level target options are mapped to the target flags. + """ + nopython = _mapping("enable_pyobject", operator.not_) + forceobj = _mapping("force_pyobject") + looplift = _mapping("enable_looplift") + _nrt = _mapping("nrt") + debug = _mapping("debuginfo") + boundscheck = _mapping("boundscheck") + nogil = _mapping("release_gil") + writable_args = _mapping("writable_args") + + no_rewrites = _mapping("no_rewrites") + no_cpython_wrapper = _mapping("no_cpython_wrapper") + no_cfunc_wrapper = _mapping("no_cfunc_wrapper") + + parallel = _mapping("auto_parallel") + fastmath = _mapping("fastmath") + error_model = _mapping("error_model") + inline = _mapping("inline") + forceinline = _mapping("forceinline") + + _dbg_extend_lifetimes = _mapping("dbg_extend_lifetimes") + _dbg_optnone = _mapping("dbg_optnone") + + +def include_default_options(*args): + """Returns a mixin class with a subset of the options + + Parameters + ---------- + *args : str + Option names to include. + """ + glbs = {k: getattr(DefaultOptions, k) for k in args} + + return type("OptionMixins", (), glbs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/postproc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/postproc.py new file mode 100644 index 0000000000000000000000000000000000000000..eab5310ca3e4ca89507e6cfb700f8855891e30e7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/postproc.py @@ -0,0 +1,239 @@ +from functools import cached_property +from numba.core import ir, analysis, transforms, ir_utils + + +class YieldPoint(object): + + def __init__(self, block, inst): + assert isinstance(block, ir.Block) + assert isinstance(inst, ir.Yield) + self.block = block + self.inst = inst + self.live_vars = None + self.weak_live_vars = None + + +class GeneratorInfo(object): + + def __init__(self): + # { index: YieldPoint } + self.yield_points = {} + # Ordered list of variable names + self.state_vars = [] + + def get_yield_points(self): + """ + Return an iterable of YieldPoint instances. + """ + return self.yield_points.values() + + +class VariableLifetime(object): + """ + For lazily building information of variable lifetime + """ + def __init__(self, blocks): + self._blocks = blocks + + @cached_property + def cfg(self): + return analysis.compute_cfg_from_blocks(self._blocks) + + @cached_property + def usedefs(self): + return analysis.compute_use_defs(self._blocks) + + @cached_property + def livemap(self): + return analysis.compute_live_map(self.cfg, self._blocks, + self.usedefs.usemap, + self.usedefs.defmap) + + @cached_property + def deadmaps(self): + return analysis.compute_dead_maps(self.cfg, self._blocks, self.livemap, + self.usedefs.defmap) + + +# other packages that define new nodes add calls for inserting dels +# format: {type:function} +ir_extension_insert_dels = {} + + +class PostProcessor(object): + """ + A post-processor for Numba IR. + """ + + def __init__(self, func_ir): + self.func_ir = func_ir + + def run(self, emit_dels: bool = False, extend_lifetimes: bool = False): + """ + Run the following passes over Numba IR: + - canonicalize the CFG + - emit explicit `del` instructions for variables + - compute lifetime of variables + - compute generator info (if function is a generator function) + """ + self.func_ir.blocks = transforms.canonicalize_cfg(self.func_ir.blocks) + vlt = VariableLifetime(self.func_ir.blocks) + self.func_ir.variable_lifetime = vlt + + bev = analysis.compute_live_variables(vlt.cfg, self.func_ir.blocks, + vlt.usedefs.defmap, + vlt.deadmaps.combined) + for offset, ir_block in self.func_ir.blocks.items(): + self.func_ir.block_entry_vars[ir_block] = bev[offset] + + if self.func_ir.is_generator: + self.func_ir.generator_info = GeneratorInfo() + self._compute_generator_info() + else: + self.func_ir.generator_info = None + + # Emit del nodes, do this last as the generator info parsing generates + # and then strips dels as part of its analysis. + if emit_dels: + self._insert_var_dels(extend_lifetimes=extend_lifetimes) + + def _populate_generator_info(self): + """ + Fill `index` for the Yield instruction and create YieldPoints. + """ + dct = self.func_ir.generator_info.yield_points + assert not dct, 'rerunning _populate_generator_info' + for block in self.func_ir.blocks.values(): + for inst in block.body: + if isinstance(inst, ir.Assign): + yieldinst = inst.value + if isinstance(yieldinst, ir.Yield): + index = len(dct) + 1 + yieldinst.index = index + yp = YieldPoint(block, yieldinst) + dct[yieldinst.index] = yp + + def _compute_generator_info(self): + """ + Compute the generator's state variables as the union of live variables + at all yield points. + """ + # generate del info, it's used in analysis here, strip it out at the end + self._insert_var_dels() + self._populate_generator_info() + gi = self.func_ir.generator_info + for yp in gi.get_yield_points(): + live_vars = set(self.func_ir.get_block_entry_vars(yp.block)) + weak_live_vars = set() + stmts = iter(yp.block.body) + for stmt in stmts: + if isinstance(stmt, ir.Assign): + if stmt.value is yp.inst: + break + live_vars.add(stmt.target.name) + elif isinstance(stmt, ir.Del): + live_vars.remove(stmt.value) + else: + assert 0, "couldn't find yield point" + # Try to optimize out any live vars that are deleted immediately + # after the yield point. + for stmt in stmts: + if isinstance(stmt, ir.Del): + name = stmt.value + if name in live_vars: + live_vars.remove(name) + weak_live_vars.add(name) + else: + break + yp.live_vars = live_vars + yp.weak_live_vars = weak_live_vars + + st = set() + for yp in gi.get_yield_points(): + st |= yp.live_vars + st |= yp.weak_live_vars + gi.state_vars = sorted(st) + self.remove_dels() + + def _insert_var_dels(self, extend_lifetimes=False): + """ + Insert del statements for each variable. + Returns a 2-tuple of (variable definition map, variable deletion map) + which indicates variables defined and deleted in each block. + + The algorithm avoids relying on explicit knowledge on loops and + distinguish between variables that are defined locally vs variables that + come from incoming blocks. + We start with simple usage (variable reference) and definition (variable + creation) maps on each block. Propagate the liveness info to predecessor + blocks until it stabilize, at which point we know which variables must + exist before entering each block. Then, we compute the end of variable + lives and insert del statements accordingly. Variables are deleted after + the last use. Variable referenced by terminators (e.g. conditional + branch and return) are deleted by the successors or the caller. + """ + vlt = self.func_ir.variable_lifetime + self._patch_var_dels(vlt.deadmaps.internal, vlt.deadmaps.escaping, + extend_lifetimes=extend_lifetimes) + + def _patch_var_dels(self, internal_dead_map, escaping_dead_map, + extend_lifetimes=False): + """ + Insert delete in each block + """ + for offset, ir_block in self.func_ir.blocks.items(): + # for each internal var, insert delete after the last use + internal_dead_set = internal_dead_map[offset].copy() + delete_pts = [] + # for each statement in reverse order + for stmt in reversed(ir_block.body[:-1]): + # internal vars that are used here + live_set = set(v.name for v in stmt.list_vars()) + dead_set = live_set & internal_dead_set + for T, def_func in ir_extension_insert_dels.items(): + if isinstance(stmt, T): + done_dels = def_func(stmt, dead_set) + dead_set -= done_dels + internal_dead_set -= done_dels + # used here but not afterwards + delete_pts.append((stmt, dead_set)) + internal_dead_set -= dead_set + + # rewrite body and insert dels + body = [] + lastloc = ir_block.loc + del_store = [] + for stmt, delete_set in reversed(delete_pts): + # If using extended lifetimes then the Dels are all put at the + # block end just ahead of the terminator, so associate their + # location with the terminator. + if extend_lifetimes: + lastloc = ir_block.body[-1].loc + else: + lastloc = stmt.loc + # Ignore dels (assuming no user inserted deletes) + if not isinstance(stmt, ir.Del): + body.append(stmt) + # note: the reverse sort is not necessary for correctness + # it is just to minimize changes to test for now + for var_name in sorted(delete_set, reverse=True): + delnode = ir.Del(var_name, loc=lastloc) + if extend_lifetimes: + del_store.append(delnode) + else: + body.append(delnode) + if extend_lifetimes: + body.extend(del_store) + body.append(ir_block.body[-1]) # terminator + ir_block.body = body + + # vars to delete at the start + escape_dead_set = escaping_dead_map[offset] + for var_name in sorted(escape_dead_set): + ir_block.prepend(ir.Del(var_name, loc=ir_block.body[0].loc)) + + def remove_dels(self): + """ + Strips the IR of Del nodes + """ + ir_utils.remove_dels(self.func_ir.blocks) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pylowering.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pylowering.py new file mode 100644 index 0000000000000000000000000000000000000000..ca09fe3701041a74e5d9d716372ccba70b2a9330 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pylowering.py @@ -0,0 +1,672 @@ +""" +Lowering implementation for object mode. +""" + + +import builtins +import operator +import inspect +from functools import cached_property + +import llvmlite.ir + +from numba.core import types, utils, ir, generators, cgutils +from numba.core.errors import (ForbiddenConstruct, LoweringError, + NumbaNotImplementedError) +from numba.core.lowering import BaseLower + + +# Issue #475: locals() is unsupported as calling it naively would give +# out wrong results. +_unsupported_builtins = set([locals]) + + +class _Undefined: + """ + A sentinel value for undefined variable created by Expr.undef. + """ + def __repr__(self): + return "" + + +_UNDEFINED = _Undefined() + + +# Map operators to methods on the PythonAPI class +PYTHON_BINOPMAP = { + operator.add: ("number_add", False), + operator.sub: ("number_subtract", False), + operator.mul: ("number_multiply", False), + operator.truediv: ("number_truedivide", False), + operator.floordiv: ("number_floordivide", False), + operator.mod: ("number_remainder", False), + operator.pow: ("number_power", False), + operator.lshift: ("number_lshift", False), + operator.rshift: ("number_rshift", False), + operator.and_: ("number_and", False), + operator.or_: ("number_or", False), + operator.xor: ("number_xor", False), + # inplace operators + operator.iadd: ("number_add", True), + operator.isub: ("number_subtract", True), + operator.imul: ("number_multiply", True), + operator.itruediv: ("number_truedivide", True), + operator.ifloordiv: ("number_floordivide", True), + operator.imod: ("number_remainder", True), + operator.ipow: ("number_power", True), + operator.ilshift: ("number_lshift", True), + operator.irshift: ("number_rshift", True), + operator.iand: ("number_and", True), + operator.ior: ("number_or", True), + operator.ixor: ("number_xor", True), +} + +PYTHON_BINOPMAP[operator.matmul] = ("number_matrix_multiply", False) +PYTHON_BINOPMAP[operator.imatmul] = ("number_matrix_multiply", True) + +PYTHON_COMPAREOPMAP = { + operator.eq: '==', + operator.ne: '!=', + operator.lt: '<', + operator.le: '<=', + operator.gt: '>', + operator.ge: '>=', + operator.is_: 'is', + operator.is_not: 'is not', + operator.contains: 'in' +} + +class PyLower(BaseLower): + + GeneratorLower = generators.PyGeneratorLower + + def init(self): + # Strings to be frozen into the Environment object + self._frozen_strings = set() + + self._live_vars = set() + + def pre_lower(self): + super(PyLower, self).pre_lower() + self.init_pyapi() + + def post_lower(self): + pass + + def pre_block(self, block): + self.init_vars(block) + + def lower_inst(self, inst): + if isinstance(inst, ir.Assign): + value = self.lower_assign(inst) + self.storevar(value, inst.target.name) + + elif isinstance(inst, ir.SetItem): + target = self.loadvar(inst.target.name) + index = self.loadvar(inst.index.name) + value = self.loadvar(inst.value.name) + ok = self.pyapi.object_setitem(target, index, value) + self.check_int_status(ok) + + elif isinstance(inst, ir.DelItem): + target = self.loadvar(inst.target.name) + index = self.loadvar(inst.index.name) + ok = self.pyapi.object_delitem(target, index) + self.check_int_status(ok) + + elif isinstance(inst, ir.SetAttr): + target = self.loadvar(inst.target.name) + value = self.loadvar(inst.value.name) + ok = self.pyapi.object_setattr(target, + self._freeze_string(inst.attr), + value) + self.check_int_status(ok) + + elif isinstance(inst, ir.DelAttr): + target = self.loadvar(inst.target.name) + ok = self.pyapi.object_delattr(target, + self._freeze_string(inst.attr)) + self.check_int_status(ok) + + elif isinstance(inst, ir.StoreMap): + dct = self.loadvar(inst.dct.name) + key = self.loadvar(inst.key.name) + value = self.loadvar(inst.value.name) + ok = self.pyapi.dict_setitem(dct, key, value) + self.check_int_status(ok) + + elif isinstance(inst, ir.Return): + retval = self.loadvar(inst.value.name) + if self.generator_info: + # StopIteration + # We own a reference to the "return value", but we + # don't return it. + self.pyapi.decref(retval) + self.genlower.return_from_generator(self) + return + # No need to incref() as the reference is already owned. + self.call_conv.return_value(self.builder, retval) + + elif isinstance(inst, ir.Branch): + cond = self.loadvar(inst.cond.name) + if cond.type == llvmlite.ir.IntType(1): + istrue = cond + else: + istrue = self.pyapi.object_istrue(cond) + zero = llvmlite.ir.Constant(istrue.type, None) + pred = self.builder.icmp_unsigned('!=', istrue, zero) + tr = self.blkmap[inst.truebr] + fl = self.blkmap[inst.falsebr] + self.builder.cbranch(pred, tr, fl) + + elif isinstance(inst, ir.Jump): + target = self.blkmap[inst.target] + self.builder.branch(target) + + elif isinstance(inst, ir.Del): + self.delvar(inst.value) + + elif isinstance(inst, ir.PopBlock): + pass # this is just a marker + + elif isinstance(inst, ir.Raise): + if inst.exception is not None: + exc = self.loadvar(inst.exception.name) + # A reference will be stolen by raise_object() and another + # by return_exception_raised(). + self.incref(exc) + else: + exc = None + self.pyapi.raise_object(exc) + self.return_exception_raised() + + else: + msg = f"{type(inst)}, {inst}" + raise NumbaNotImplementedError(msg) + + @cached_property + def _omitted_typobj(self): + """Return a `OmittedArg` type instance as a LLVM value suitable for + testing at runtime. + """ + from numba.core.dispatcher import OmittedArg + return self.pyapi.unserialize( + self.pyapi.serialize_object(OmittedArg)) + + def lower_assign(self, inst): + """ + The returned object must have a new reference + """ + value = inst.value + if isinstance(value, (ir.Const, ir.FreeVar)): + return self.lower_const(value.value) + elif isinstance(value, ir.Var): + val = self.loadvar(value.name) + self.incref(val) + return val + elif isinstance(value, ir.Expr): + return self.lower_expr(value) + elif isinstance(value, ir.Global): + return self.lower_global(value.name, value.value) + elif isinstance(value, ir.Yield): + return self.lower_yield(value) + elif isinstance(value, ir.Arg): + param = self.func_ir.func_id.pysig.parameters.get(value.name) + + obj = self.fnargs[value.index] + slot = cgutils.alloca_once_value(self.builder, obj) + # Don't check for OmittedArg unless the argument has a default + if param is not None and param.default is inspect.Parameter.empty: + self.incref(obj) + self.builder.store(obj, slot) + else: + # When an argument is omitted, the dispatcher hands it as + # _OmittedArg() + typobj = self.pyapi.get_type(obj) + is_omitted = self.builder.icmp_unsigned('==', typobj, + self._omitted_typobj) + with self.builder.if_else(is_omitted, likely=False) as (omitted, present): + with present: + self.incref(obj) + self.builder.store(obj, slot) + with omitted: + # The argument is omitted => get the default value + obj = self.pyapi.object_getattr_string(obj, 'value') + self.builder.store(obj, slot) + + return self.builder.load(slot) + else: + raise NotImplementedError(type(value), value) + + def lower_yield(self, inst): + yp = self.generator_info.yield_points[inst.index] + assert yp.inst is inst + self.genlower.init_generator_state(self) + + # Save live vars in state + # We also need to save live vars that are del'ed afterwards. + y = generators.LowerYield(self, yp, yp.live_vars | yp.weak_live_vars) + y.lower_yield_suspend() + # Yield to caller + val = self.loadvar(inst.value.name) + # Let caller own the reference + self.pyapi.incref(val) + self.call_conv.return_value(self.builder, val) + + # Resumption point + y.lower_yield_resume() + # None is returned by the yield expression + return self.pyapi.make_none() + + def lower_binop(self, expr, op, inplace=False): + lhs = self.loadvar(expr.lhs.name) + rhs = self.loadvar(expr.rhs.name) + assert not isinstance(op, str) + if op in PYTHON_BINOPMAP: + fname, inplace = PYTHON_BINOPMAP[op] + fn = getattr(self.pyapi, fname) + res = fn(lhs, rhs, inplace=inplace) + else: + # Assumed to be rich comparison + fn = PYTHON_COMPAREOPMAP.get(expr.fn, expr.fn) + if fn == 'in': # 'in' and operator.contains have args reversed + lhs, rhs = rhs, lhs + res = self.pyapi.object_richcompare(lhs, rhs, fn) + self.check_error(res) + return res + + def lower_expr(self, expr): + if expr.op == 'binop': + return self.lower_binop(expr, expr.fn, inplace=False) + elif expr.op == 'inplace_binop': + return self.lower_binop(expr, expr.fn, inplace=True) + elif expr.op == 'unary': + value = self.loadvar(expr.value.name) + if expr.fn == operator.neg: + res = self.pyapi.number_negative(value) + elif expr.fn == operator.pos: + res = self.pyapi.number_positive(value) + elif expr.fn == operator.not_: + res = self.pyapi.object_not(value) + self.check_int_status(res) + res = self.pyapi.bool_from_bool(res) + elif expr.fn == operator.invert: + res = self.pyapi.number_invert(value) + else: + raise NotImplementedError(expr) + self.check_error(res) + return res + elif expr.op == 'call': + argvals = [self.loadvar(a.name) for a in expr.args] + fn = self.loadvar(expr.func.name) + args = self.pyapi.tuple_pack(argvals) + if expr.vararg: + # Expand *args + varargs = self.pyapi.sequence_tuple( + self.loadvar(expr.vararg.name)) + new_args = self.pyapi.sequence_concat(args, varargs) + self.decref(varargs) + self.decref(args) + args = new_args + if not expr.kws: + # No named arguments + ret = self.pyapi.call(fn, args, None) + else: + # Named arguments + keyvalues = [(k, self.loadvar(v.name)) for k, v in expr.kws] + kws = self.pyapi.dict_pack(keyvalues) + ret = self.pyapi.call(fn, args, kws) + self.decref(kws) + self.decref(args) + self.check_error(ret) + return ret + elif expr.op == 'getattr': + obj = self.loadvar(expr.value.name) + res = self.pyapi.object_getattr(obj, self._freeze_string(expr.attr)) + self.check_error(res) + return res + elif expr.op == 'build_tuple': + items = [self.loadvar(it.name) for it in expr.items] + res = self.pyapi.tuple_pack(items) + self.check_error(res) + return res + elif expr.op == 'build_list': + items = [self.loadvar(it.name) for it in expr.items] + res = self.pyapi.list_pack(items) + self.check_error(res) + return res + elif expr.op == 'build_map': + res = self.pyapi.dict_new(expr.size) + self.check_error(res) + for k, v in expr.items: + key = self.loadvar(k.name) + value = self.loadvar(v.name) + ok = self.pyapi.dict_setitem(res, key, value) + self.check_int_status(ok) + return res + elif expr.op == 'build_set': + items = [self.loadvar(it.name) for it in expr.items] + res = self.pyapi.set_new() + self.check_error(res) + for it in items: + ok = self.pyapi.set_add(res, it) + self.check_int_status(ok) + return res + elif expr.op == 'getiter': + obj = self.loadvar(expr.value.name) + res = self.pyapi.object_getiter(obj) + self.check_error(res) + return res + elif expr.op == 'iternext': + iterobj = self.loadvar(expr.value.name) + item = self.pyapi.iter_next(iterobj) + is_valid = cgutils.is_not_null(self.builder, item) + pair = self.pyapi.tuple_new(2) + with self.builder.if_else(is_valid) as (then, otherwise): + with then: + self.pyapi.tuple_setitem(pair, 0, item) + with otherwise: + self.check_occurred() + # Make the tuple valid by inserting None as dummy + # iteration "result" (it will be ignored). + self.pyapi.tuple_setitem(pair, 0, self.pyapi.make_none()) + self.pyapi.tuple_setitem(pair, 1, self.pyapi.bool_from_bool(is_valid)) + return pair + elif expr.op == 'pair_first': + pair = self.loadvar(expr.value.name) + first = self.pyapi.tuple_getitem(pair, 0) + self.incref(first) + return first + elif expr.op == 'pair_second': + pair = self.loadvar(expr.value.name) + second = self.pyapi.tuple_getitem(pair, 1) + self.incref(second) + return second + elif expr.op == 'exhaust_iter': + iterobj = self.loadvar(expr.value.name) + tup = self.pyapi.sequence_tuple(iterobj) + self.check_error(tup) + # Check tuple size is as expected + tup_size = self.pyapi.tuple_size(tup) + expected_size = self.context.get_constant(types.intp, expr.count) + has_wrong_size = self.builder.icmp_unsigned('!=', + tup_size, expected_size) + with cgutils.if_unlikely(self.builder, has_wrong_size): + self.return_exception(ValueError) + return tup + elif expr.op == 'getitem': + value = self.loadvar(expr.value.name) + index = self.loadvar(expr.index.name) + res = self.pyapi.object_getitem(value, index) + self.check_error(res) + return res + elif expr.op == 'static_getitem': + value = self.loadvar(expr.value.name) + index = self.context.get_constant(types.intp, expr.index) + indexobj = self.pyapi.long_from_ssize_t(index) + self.check_error(indexobj) + res = self.pyapi.object_getitem(value, indexobj) + self.decref(indexobj) + self.check_error(res) + return res + elif expr.op == 'getslice': + target = self.loadvar(expr.target.name) + start = self.loadvar(expr.start.name) + stop = self.loadvar(expr.stop.name) + + slicefn = self.get_builtin_obj("slice") + sliceobj = self.pyapi.call_function_objargs(slicefn, (start, stop)) + self.decref(slicefn) + self.check_error(sliceobj) + + res = self.pyapi.object_getitem(target, sliceobj) + self.check_error(res) + + return res + + elif expr.op == 'cast': + val = self.loadvar(expr.value.name) + self.incref(val) + return val + elif expr.op == 'phi': + raise LoweringError("PHI not stripped") + + elif expr.op == 'null': + # Make null value + return cgutils.get_null_value(self.pyapi.pyobj) + + elif expr.op == 'undef': + # Use a sentinel value for undefined variable + return self.lower_const(_UNDEFINED) + + else: + raise NotImplementedError(expr) + + def lower_const(self, const): + # All constants are frozen inside the environment + index = self.env_manager.add_const(const) + ret = self.env_manager.read_const(index) + self.check_error(ret) + self.incref(ret) + return ret + + def lower_global(self, name, value): + """ + 1) Check global scope dictionary. + 2) Check __builtins__. + 2a) is it a dictionary (for non __main__ module) + 2b) is it a module (for __main__ module) + """ + moddict = self.get_module_dict() + obj = self.pyapi.dict_getitem(moddict, self._freeze_string(name)) + self.incref(obj) # obj is borrowed + + try: + if value in _unsupported_builtins: + raise ForbiddenConstruct("builtins %s() is not supported" + % name, loc=self.loc) + except TypeError: + # `value` is unhashable, ignore + pass + + if hasattr(builtins, name): + obj_is_null = self.is_null(obj) + bbelse = self.builder.basic_block + + with self.builder.if_then(obj_is_null): + mod = self.pyapi.dict_getitem(moddict, + self._freeze_string("__builtins__")) + builtin = self.builtin_lookup(mod, name) + bbif = self.builder.basic_block + + retval = self.builder.phi(self.pyapi.pyobj) + retval.add_incoming(obj, bbelse) + retval.add_incoming(builtin, bbif) + + else: + retval = obj + with cgutils.if_unlikely(self.builder, self.is_null(retval)): + self.pyapi.raise_missing_global_error(name) + self.return_exception_raised() + + return retval + + # ------------------------------------------------------------------------- + + def get_module_dict(self): + return self.env_body.globals + + def get_builtin_obj(self, name): + # XXX The builtins dict could be bound into the environment + moddict = self.get_module_dict() + mod = self.pyapi.dict_getitem(moddict, + self._freeze_string("__builtins__")) + return self.builtin_lookup(mod, name) + + def builtin_lookup(self, mod, name): + """ + Args + ---- + mod: + The __builtins__ dictionary or module, as looked up in + a module's globals. + name: str + The object to lookup + """ + fromdict = self.pyapi.dict_getitem(mod, self._freeze_string(name)) + self.incref(fromdict) # fromdict is borrowed + bbifdict = self.builder.basic_block + + with cgutils.if_unlikely(self.builder, self.is_null(fromdict)): + # This happen if we are using the __main__ module + frommod = self.pyapi.object_getattr(mod, self._freeze_string(name)) + + with cgutils.if_unlikely(self.builder, self.is_null(frommod)): + self.pyapi.raise_missing_global_error(name) + self.return_exception_raised() + + bbifmod = self.builder.basic_block + + builtin = self.builder.phi(self.pyapi.pyobj) + builtin.add_incoming(fromdict, bbifdict) + builtin.add_incoming(frommod, bbifmod) + + return builtin + + def check_occurred(self): + """ + Return if an exception occurred. + """ + err_occurred = cgutils.is_not_null(self.builder, + self.pyapi.err_occurred()) + + with cgutils.if_unlikely(self.builder, err_occurred): + self.return_exception_raised() + + def check_error(self, obj): + """ + Return if *obj* is NULL. + """ + with cgutils.if_unlikely(self.builder, self.is_null(obj)): + self.return_exception_raised() + + return obj + + def check_int_status(self, num, ok_value=0): + """ + Raise an exception if *num* is smaller than *ok_value*. + """ + ok = llvmlite.ir.Constant(num.type, ok_value) + pred = self.builder.icmp_signed('<', num, ok) + with cgutils.if_unlikely(self.builder, pred): + self.return_exception_raised() + + def is_null(self, obj): + return cgutils.is_null(self.builder, obj) + + def return_exception_raised(self): + """ + Return with the currently raised exception. + """ + self.cleanup_vars() + self.call_conv.return_exc(self.builder) + + def init_vars(self, block): + """ + Initialize live variables for *block*. + """ + self._live_vars = set(self.func_ir.get_block_entry_vars(block)) + + def _getvar(self, name, ltype=None): + if name not in self.varmap: + self.varmap[name] = self.alloca(name, ltype=ltype) + return self.varmap[name] + + def loadvar(self, name): + """ + Load the llvm value of the variable named *name*. + """ + # If this raises then the live variables analysis is wrong + assert name in self._live_vars, name + ptr = self.varmap[name] + val = self.builder.load(ptr) + with cgutils.if_unlikely(self.builder, self.is_null(val)): + self.pyapi.raise_missing_name_error(name) + self.return_exception_raised() + return val + + def delvar(self, name): + """ + Delete the variable slot with the given name. This will decref + the corresponding Python object. + """ + # If this raises then the live variables analysis is wrong + self._live_vars.remove(name) + ptr = self._getvar(name) # initializes `name` if not already + self.decref(self.builder.load(ptr)) + # This is a safety guard against double decref's, but really + # the IR should be correct and have only one Del per variable + # and code path. + self.builder.store(cgutils.get_null_value(ptr.type.pointee), ptr) + + def storevar(self, value, name, clobber=False): + """ + Stores a llvm value and allocate stack slot if necessary. + The llvm value can be of arbitrary type. + """ + is_redefine = name in self._live_vars and not clobber + ptr = self._getvar(name, ltype=value.type) + if is_redefine: + old = self.builder.load(ptr) + else: + self._live_vars.add(name) + assert value.type == ptr.type.pointee, (str(value.type), + str(ptr.type.pointee)) + self.builder.store(value, ptr) + # Safe to call decref even on non python object + if is_redefine: + self.decref(old) + + def cleanup_vars(self): + """ + Cleanup live variables. + """ + for name in self._live_vars: + ptr = self._getvar(name) + self.decref(self.builder.load(ptr)) + + def alloca(self, name, ltype=None): + """ + Allocate a stack slot and initialize it to NULL. + The default is to allocate a pyobject pointer. + Use ``ltype`` to override. + """ + if ltype is None: + ltype = self.context.get_value_type(types.pyobject) + with self.builder.goto_block(self.entry_block): + ptr = self.builder.alloca(ltype, name=name) + self.builder.store(cgutils.get_null_value(ltype), ptr) + return ptr + + def _alloca_var(self, name, fetype): + # This is here for API compatibility with lowering.py::Lower. + # NOTE: fetype is unused + return self.alloca(name) + + def incref(self, value): + self.pyapi.incref(value) + + def decref(self, value): + """ + This is allow to be called on non pyobject pointer, in which case + no code is inserted. + """ + lpyobj = self.context.get_value_type(types.pyobject) + if value.type == lpyobj: + self.pyapi.decref(value) + + def _freeze_string(self, string): + """ + Freeze a Python string object into the code. + """ + return self.lower_const(string) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pythonapi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pythonapi.py new file mode 100644 index 0000000000000000000000000000000000000000..660b113e01464db8399a2bc6c5cafa308a8436e4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/pythonapi.py @@ -0,0 +1,1724 @@ +from collections import namedtuple +import contextlib +import pickle +import hashlib +import sys + +from llvmlite import ir +from llvmlite.ir import Constant + +import ctypes +from numba import _helperlib +from numba.core import ( + types, utils, config, lowering, cgutils, imputils, serialize, +) +from numba.core.utils import PYVERSION + +PY_UNICODE_1BYTE_KIND = _helperlib.py_unicode_1byte_kind +PY_UNICODE_2BYTE_KIND = _helperlib.py_unicode_2byte_kind +PY_UNICODE_4BYTE_KIND = _helperlib.py_unicode_4byte_kind +if PYVERSION in ((3, 10), (3, 11)): + PY_UNICODE_WCHAR_KIND = _helperlib.py_unicode_wchar_kind + + +class _Registry(object): + + def __init__(self): + self.functions = {} + + def register(self, typeclass): + assert issubclass(typeclass, types.Type) + def decorator(func): + if typeclass in self.functions: + raise KeyError("duplicate registration for %s" % (typeclass,)) + self.functions[typeclass] = func + return func + return decorator + + def lookup(self, typeclass, default=None): + assert issubclass(typeclass, types.Type) + for cls in typeclass.__mro__: + func = self.functions.get(cls) + if func is not None: + return func + return default + +# Registries of boxing / unboxing implementations +_boxers = _Registry() +_unboxers = _Registry() +_reflectors = _Registry() + +box = _boxers.register +unbox = _unboxers.register +reflect = _reflectors.register + +class _BoxContext(namedtuple("_BoxContext", + ("context", "builder", "pyapi", "env_manager"))): + """ + The facilities required by boxing implementations. + """ + __slots__ = () + + def box(self, typ, val): + return self.pyapi.from_native_value(typ, val, self.env_manager) + + +class _UnboxContext(namedtuple("_UnboxContext", + ("context", "builder", "pyapi"))): + """ + The facilities required by unboxing implementations. + """ + __slots__ = () + + def unbox(self, typ, obj): + return self.pyapi.to_native_value(typ, obj) + + +class _ReflectContext(namedtuple("_ReflectContext", + ("context", "builder", "pyapi", "env_manager", + "is_error"))): + """ + The facilities required by reflection implementations. + """ + __slots__ = () + + # XXX the error bit is currently unused by consumers (e.g. PyCallWrapper) + def set_error(self): + self.builder.store(self.is_error, cgutils.true_bit) + + def box(self, typ, val): + return self.pyapi.from_native_value(typ, val, self.env_manager) + + def reflect(self, typ, val): + return self.pyapi.reflect_native_value(typ, val, self.env_manager) + + +class NativeValue(object): + """ + Encapsulate the result of converting a Python object to a native value, + recording whether the conversion was successful and how to cleanup. + """ + + def __init__(self, value, is_error=None, cleanup=None): + self.value = value + self.is_error = is_error if is_error is not None else cgutils.false_bit + self.cleanup = cleanup + + +class EnvironmentManager(object): + + def __init__(self, pyapi, env, env_body, env_ptr): + assert isinstance(env, lowering.Environment) + self.pyapi = pyapi + self.env = env + self.env_body = env_body + self.env_ptr = env_ptr + + def add_const(self, const): + """ + Add a constant to the environment, return its index. + """ + # All constants are frozen inside the environment + if isinstance(const, str): + const = sys.intern(const) + for index, val in enumerate(self.env.consts): + if val is const: + break + else: + index = len(self.env.consts) + self.env.consts.append(const) + return index + + def read_const(self, index): + """ + Look up constant number *index* inside the environment body. + A borrowed reference is returned. + + The returned LLVM value may have NULL value at runtime which indicates + an error at runtime. + """ + assert index < len(self.env.consts) + + builder = self.pyapi.builder + consts = self.env_body.consts + ret = cgutils.alloca_once(builder, self.pyapi.pyobj, zfill=True) + with builder.if_else(cgutils.is_not_null(builder, consts)) as \ + (br_not_null, br_null): + with br_not_null: + getitem = self.pyapi.list_getitem(consts, index) + builder.store(getitem, ret) + with br_null: + # This can happen when the Environment is accidentally released + # and has subsequently been garbage collected. + self.pyapi.err_set_string( + "PyExc_RuntimeError", + "`env.consts` is NULL in `read_const`", + ) + return builder.load(ret) + + +_IteratorLoop = namedtuple('_IteratorLoop', ('value', 'do_break')) + + +class PythonAPI(object): + """ + Code generation facilities to call into the CPython C API (and related + helpers). + """ + + def __init__(self, context, builder): + """ + Note: Maybe called multiple times when lowering a function + """ + self.context = context + self.builder = builder + + self.module = builder.basic_block.function.module + # A unique mapping of serialized objects in this module + try: + self.module.__serialized + except AttributeError: + self.module.__serialized = {} + + # Initialize types + self.pyobj = self.context.get_argument_type(types.pyobject) + self.pyobjptr = self.pyobj.as_pointer() + self.voidptr = ir.PointerType(ir.IntType(8)) + self.long = ir.IntType(ctypes.sizeof(ctypes.c_long) * 8) + self.ulong = self.long + self.longlong = ir.IntType(ctypes.sizeof(ctypes.c_ulonglong) * 8) + self.ulonglong = self.longlong + self.double = ir.DoubleType() + self.py_ssize_t = self.context.get_value_type(types.intp) + self.cstring = ir.PointerType(ir.IntType(8)) + self.gil_state = ir.IntType(_helperlib.py_gil_state_size * 8) + self.py_buffer_t = ir.ArrayType(ir.IntType(8), _helperlib.py_buffer_size) + self.py_hash_t = self.py_ssize_t + self.py_unicode_1byte_kind = _helperlib.py_unicode_1byte_kind + self.py_unicode_2byte_kind = _helperlib.py_unicode_2byte_kind + self.py_unicode_4byte_kind = _helperlib.py_unicode_4byte_kind + + def get_env_manager(self, env, env_body, env_ptr): + return EnvironmentManager(self, env, env_body, env_ptr) + + def emit_environment_sentry(self, envptr, return_pyobject=False, + debug_msg=''): + """Emits LLVM code to ensure the `envptr` is not NULL + """ + is_null = cgutils.is_null(self.builder, envptr) + with cgutils.if_unlikely(self.builder, is_null): + if return_pyobject: + fnty = self.builder.function.type.pointee + assert fnty.return_type == self.pyobj + self.err_set_string( + "PyExc_RuntimeError", f"missing Environment: {debug_msg}", + ) + self.builder.ret(self.get_null_object()) + else: + self.context.call_conv.return_user_exc( + self.builder, RuntimeError, + (f"missing Environment: {debug_msg}",), + ) + + # ------ Python API ----- + + # + # Basic object API + # + + def incref(self, obj): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="Py_IncRef") + self.builder.call(fn, [obj]) + + def decref(self, obj): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="Py_DecRef") + self.builder.call(fn, [obj]) + + def get_type(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="numba_py_type") + return self.builder.call(fn, [obj]) + + # + # Argument unpacking + # + + def parse_tuple_and_keywords(self, args, kws, fmt, keywords, *objs): + charptr = ir.PointerType(ir.IntType(8)) + charptrary = ir.PointerType(charptr) + argtypes = [self.pyobj, self.pyobj, charptr, charptrary] + fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True) + fn = self._get_function(fnty, name="PyArg_ParseTupleAndKeywords") + return self.builder.call(fn, [args, kws, fmt, keywords] + list(objs)) + + def parse_tuple(self, args, fmt, *objs): + charptr = ir.PointerType(ir.IntType(8)) + argtypes = [self.pyobj, charptr] + fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True) + fn = self._get_function(fnty, name="PyArg_ParseTuple") + return self.builder.call(fn, [args, fmt] + list(objs)) + + def unpack_tuple(self, args, name, n_min, n_max, *objs): + charptr = ir.PointerType(ir.IntType(8)) + argtypes = [self.pyobj, charptr, self.py_ssize_t, self.py_ssize_t] + fnty = ir.FunctionType(ir.IntType(32), argtypes, var_arg=True) + fn = self._get_function(fnty, name="PyArg_UnpackTuple") + n_min = Constant(self.py_ssize_t, int(n_min)) + n_max = Constant(self.py_ssize_t, int(n_max)) + if isinstance(name, str): + name = self.context.insert_const_string(self.builder.module, name) + return self.builder.call(fn, [args, name, n_min, n_max] + list(objs)) + + # + # Exception and errors + # + + def err_occurred(self): + fnty = ir.FunctionType(self.pyobj, ()) + fn = self._get_function(fnty, name="PyErr_Occurred") + return self.builder.call(fn, ()) + + def err_clear(self): + fnty = ir.FunctionType(ir.VoidType(), ()) + fn = self._get_function(fnty, name="PyErr_Clear") + return self.builder.call(fn, ()) + + def err_set_string(self, exctype, msg): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.cstring]) + fn = self._get_function(fnty, name="PyErr_SetString") + if isinstance(exctype, str): + exctype = self.get_c_object(exctype) + if isinstance(msg, str): + msg = self.context.insert_const_string(self.module, msg) + return self.builder.call(fn, (exctype, msg)) + + def err_format(self, exctype, msg, *format_args): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.cstring], var_arg=True) + fn = self._get_function(fnty, name="PyErr_Format") + if isinstance(exctype, str): + exctype = self.get_c_object(exctype) + if isinstance(msg, str): + msg = self.context.insert_const_string(self.module, msg) + return self.builder.call(fn, (exctype, msg) + tuple(format_args)) + + def raise_object(self, exc=None): + """ + Raise an arbitrary exception (type or value or (type, args) + or None - if reraising). A reference to the argument is consumed. + """ + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="numba_do_raise") + if exc is None: + exc = self.make_none() + return self.builder.call(fn, (exc,)) + + def err_set_object(self, exctype, excval): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyErr_SetObject") + if isinstance(exctype, str): + exctype = self.get_c_object(exctype) + return self.builder.call(fn, (exctype, excval)) + + def err_set_none(self, exctype): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="PyErr_SetNone") + if isinstance(exctype, str): + exctype = self.get_c_object(exctype) + return self.builder.call(fn, (exctype,)) + + def err_write_unraisable(self, obj): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="PyErr_WriteUnraisable") + return self.builder.call(fn, (obj,)) + + def err_fetch(self, pty, pval, ptb): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobjptr] * 3) + fn = self._get_function(fnty, name="PyErr_Fetch") + return self.builder.call(fn, (pty, pval, ptb)) + + def err_restore(self, ty, val, tb): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj] * 3) + fn = self._get_function(fnty, name="PyErr_Restore") + return self.builder.call(fn, (ty, val, tb)) + + @contextlib.contextmanager + def err_push(self, keep_new=False): + """ + Temporarily push the current error indicator while the code + block is executed. If *keep_new* is True and the code block + raises a new error, the new error is kept, otherwise the old + error indicator is restored at the end of the block. + """ + pty, pval, ptb = [cgutils.alloca_once(self.builder, self.pyobj) + for i in range(3)] + self.err_fetch(pty, pval, ptb) + yield + ty = self.builder.load(pty) + val = self.builder.load(pval) + tb = self.builder.load(ptb) + if keep_new: + new_error = cgutils.is_not_null(self.builder, self.err_occurred()) + with self.builder.if_else(new_error, likely=False) as (if_error, if_ok): + with if_error: + # Code block raised an error, keep it + self.decref(ty) + self.decref(val) + self.decref(tb) + with if_ok: + # Restore previous error + self.err_restore(ty, val, tb) + else: + self.err_restore(ty, val, tb) + + def get_c_object(self, name): + """ + Get a Python object through its C-accessible *name* + (e.g. "PyExc_ValueError"). The underlying variable must be + a `PyObject *`, and the value of that pointer is returned. + """ + # A LLVM global variable is implicitly a pointer to the declared + # type, so fix up by using pyobj.pointee. + return self.context.get_c_value(self.builder, self.pyobj.pointee, name, + dllimport=True) + + def raise_missing_global_error(self, name): + msg = "global name '%s' is not defined" % name + cstr = self.context.insert_const_string(self.module, msg) + self.err_set_string("PyExc_NameError", cstr) + + def raise_missing_name_error(self, name): + msg = "name '%s' is not defined" % name + cstr = self.context.insert_const_string(self.module, msg) + self.err_set_string("PyExc_NameError", cstr) + + def fatal_error(self, msg): + fnty = ir.FunctionType(ir.VoidType(), [self.cstring]) + fn = self._get_function(fnty, name="Py_FatalError") + fn.attributes.add("noreturn") + cstr = self.context.insert_const_string(self.module, msg) + self.builder.call(fn, (cstr,)) + + # + # Concrete dict API + # + + def dict_getitem_string(self, dic, name): + """Lookup name inside dict + + Returns a borrowed reference + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.cstring]) + fn = self._get_function(fnty, name="PyDict_GetItemString") + cstr = self.context.insert_const_string(self.module, name) + return self.builder.call(fn, [dic, cstr]) + + def dict_getitem(self, dic, name): + """Lookup name inside dict + + Returns a borrowed reference + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyDict_GetItem") + return self.builder.call(fn, [dic, name]) + + def dict_new(self, presize=0): + if presize == 0: + fnty = ir.FunctionType(self.pyobj, ()) + fn = self._get_function(fnty, name="PyDict_New") + return self.builder.call(fn, ()) + else: + fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t]) + fn = self._get_function(fnty, name="_PyDict_NewPresized") + return self.builder.call(fn, + [Constant(self.py_ssize_t, int(presize))]) + + def dict_setitem(self, dictobj, nameobj, valobj): + fnty = ir.FunctionType(ir.IntType(32), (self.pyobj, self.pyobj, + self.pyobj)) + fn = self._get_function(fnty, name="PyDict_SetItem") + return self.builder.call(fn, (dictobj, nameobj, valobj)) + + def dict_setitem_string(self, dictobj, name, valobj): + fnty = ir.FunctionType(ir.IntType(32), (self.pyobj, self.cstring, + self.pyobj)) + fn = self._get_function(fnty, name="PyDict_SetItemString") + cstr = self.context.insert_const_string(self.module, name) + return self.builder.call(fn, (dictobj, cstr, valobj)) + + def dict_pack(self, keyvalues): + """ + Args + ----- + keyvalues: iterable of (str, llvm.Value of PyObject*) + """ + dictobj = self.dict_new() + with self.if_object_ok(dictobj): + for k, v in keyvalues: + self.dict_setitem_string(dictobj, k, v) + return dictobj + + # + # Concrete number APIs + # + + def float_from_double(self, fval): + fnty = ir.FunctionType(self.pyobj, [self.double]) + fn = self._get_function(fnty, name="PyFloat_FromDouble") + return self.builder.call(fn, [fval]) + + def number_as_ssize_t(self, numobj): + fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_AsSsize_t") + # We don't want any clipping, so pass OverflowError as the 2nd arg + exc_class = self.get_c_object("PyExc_OverflowError") + return self.builder.call(fn, [numobj, exc_class]) + + def number_long(self, numobj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_Long") + return self.builder.call(fn, [numobj]) + + def long_as_ulonglong(self, numobj): + fnty = ir.FunctionType(self.ulonglong, [self.pyobj]) + fn = self._get_function(fnty, name="PyLong_AsUnsignedLongLong") + return self.builder.call(fn, [numobj]) + + def long_as_longlong(self, numobj): + fnty = ir.FunctionType(self.ulonglong, [self.pyobj]) + fn = self._get_function(fnty, name="PyLong_AsLongLong") + return self.builder.call(fn, [numobj]) + + def long_as_voidptr(self, numobj): + """ + Convert the given Python integer to a void*. This is recommended + over number_as_ssize_t as it isn't affected by signedness. + """ + fnty = ir.FunctionType(self.voidptr, [self.pyobj]) + fn = self._get_function(fnty, name="PyLong_AsVoidPtr") + return self.builder.call(fn, [numobj]) + + def _long_from_native_int(self, ival, func_name, native_int_type, + signed): + fnty = ir.FunctionType(self.pyobj, [native_int_type]) + fn = self._get_function(fnty, name=func_name) + resptr = cgutils.alloca_once(self.builder, self.pyobj) + fn = self._get_function(fnty, name=func_name) + self.builder.store(self.builder.call(fn, [ival]), resptr) + + return self.builder.load(resptr) + + def long_from_long(self, ival): + func_name = "PyLong_FromLong" + fnty = ir.FunctionType(self.pyobj, [self.long]) + fn = self._get_function(fnty, name=func_name) + return self.builder.call(fn, [ival]) + + def long_from_ulong(self, ival): + return self._long_from_native_int(ival, "PyLong_FromUnsignedLong", + self.long, signed=False) + + def long_from_ssize_t(self, ival): + return self._long_from_native_int(ival, "PyLong_FromSsize_t", + self.py_ssize_t, signed=True) + + def long_from_longlong(self, ival): + return self._long_from_native_int(ival, "PyLong_FromLongLong", + self.longlong, signed=True) + + def long_from_ulonglong(self, ival): + return self._long_from_native_int(ival, "PyLong_FromUnsignedLongLong", + self.ulonglong, signed=False) + + def long_from_signed_int(self, ival): + """ + Return a Python integer from any native integer value. + """ + bits = ival.type.width + if bits <= self.long.width: + return self.long_from_long(self.builder.sext(ival, self.long)) + elif bits <= self.longlong.width: + return self.long_from_longlong(self.builder.sext(ival, self.longlong)) + else: + raise OverflowError("integer too big (%d bits)" % (bits)) + + def long_from_unsigned_int(self, ival): + """ + Same as long_from_signed_int, but for unsigned values. + """ + bits = ival.type.width + if bits <= self.ulong.width: + return self.long_from_ulong(self.builder.zext(ival, self.ulong)) + elif bits <= self.ulonglong.width: + return self.long_from_ulonglong(self.builder.zext(ival, self.ulonglong)) + else: + raise OverflowError("integer too big (%d bits)" % (bits)) + + def _get_number_operator(self, name): + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_%s" % name) + return fn + + def _call_number_operator(self, name, lhs, rhs, inplace=False): + if inplace: + name = "InPlace" + name + fn = self._get_number_operator(name) + return self.builder.call(fn, [lhs, rhs]) + + def number_add(self, lhs, rhs, inplace=False): + return self._call_number_operator("Add", lhs, rhs, inplace=inplace) + + def number_subtract(self, lhs, rhs, inplace=False): + return self._call_number_operator("Subtract", lhs, rhs, inplace=inplace) + + def number_multiply(self, lhs, rhs, inplace=False): + return self._call_number_operator("Multiply", lhs, rhs, inplace=inplace) + + def number_truedivide(self, lhs, rhs, inplace=False): + return self._call_number_operator("TrueDivide", lhs, rhs, inplace=inplace) + + def number_floordivide(self, lhs, rhs, inplace=False): + return self._call_number_operator("FloorDivide", lhs, rhs, inplace=inplace) + + def number_remainder(self, lhs, rhs, inplace=False): + return self._call_number_operator("Remainder", lhs, rhs, inplace=inplace) + + def number_matrix_multiply(self, lhs, rhs, inplace=False): + return self._call_number_operator("MatrixMultiply", lhs, rhs, inplace=inplace) + + def number_lshift(self, lhs, rhs, inplace=False): + return self._call_number_operator("Lshift", lhs, rhs, inplace=inplace) + + def number_rshift(self, lhs, rhs, inplace=False): + return self._call_number_operator("Rshift", lhs, rhs, inplace=inplace) + + def number_and(self, lhs, rhs, inplace=False): + return self._call_number_operator("And", lhs, rhs, inplace=inplace) + + def number_or(self, lhs, rhs, inplace=False): + return self._call_number_operator("Or", lhs, rhs, inplace=inplace) + + def number_xor(self, lhs, rhs, inplace=False): + return self._call_number_operator("Xor", lhs, rhs, inplace=inplace) + + def number_power(self, lhs, rhs, inplace=False): + fnty = ir.FunctionType(self.pyobj, [self.pyobj] * 3) + fname = "PyNumber_InPlacePower" if inplace else "PyNumber_Power" + fn = self._get_function(fnty, fname) + return self.builder.call(fn, [lhs, rhs, self.borrow_none()]) + + def number_negative(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_Negative") + return self.builder.call(fn, (obj,)) + + def number_positive(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_Positive") + return self.builder.call(fn, (obj,)) + + def number_float(self, val): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_Float") + return self.builder.call(fn, [val]) + + def number_invert(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyNumber_Invert") + return self.builder.call(fn, (obj,)) + + def float_as_double(self, fobj): + fnty = ir.FunctionType(self.double, [self.pyobj]) + fn = self._get_function(fnty, name="PyFloat_AsDouble") + return self.builder.call(fn, [fobj]) + + def bool_from_bool(self, bval): + """ + Get a Python bool from a LLVM boolean. + """ + longval = self.builder.zext(bval, self.long) + return self.bool_from_long(longval) + + def bool_from_long(self, ival): + fnty = ir.FunctionType(self.pyobj, [self.long]) + fn = self._get_function(fnty, name="PyBool_FromLong") + return self.builder.call(fn, [ival]) + + def complex_from_doubles(self, realval, imagval): + fnty = ir.FunctionType(self.pyobj, [ir.DoubleType(), ir.DoubleType()]) + fn = self._get_function(fnty, name="PyComplex_FromDoubles") + return self.builder.call(fn, [realval, imagval]) + + def complex_real_as_double(self, cobj): + fnty = ir.FunctionType(ir.DoubleType(), [self.pyobj]) + fn = self._get_function(fnty, name="PyComplex_RealAsDouble") + return self.builder.call(fn, [cobj]) + + def complex_imag_as_double(self, cobj): + fnty = ir.FunctionType(ir.DoubleType(), [self.pyobj]) + fn = self._get_function(fnty, name="PyComplex_ImagAsDouble") + return self.builder.call(fn, [cobj]) + + # + # Concrete slice API + # + def slice_as_ints(self, obj): + """ + Read the members of a slice of integers. + + Returns a (ok, start, stop, step) tuple where ok is a boolean and + the following members are pointer-sized ints. + """ + pstart = cgutils.alloca_once(self.builder, self.py_ssize_t) + pstop = cgutils.alloca_once(self.builder, self.py_ssize_t) + pstep = cgutils.alloca_once(self.builder, self.py_ssize_t) + fnty = ir.FunctionType(ir.IntType(32), + [self.pyobj] + [self.py_ssize_t.as_pointer()] * 3) + fn = self._get_function(fnty, name="numba_unpack_slice") + res = self.builder.call(fn, (obj, pstart, pstop, pstep)) + start = self.builder.load(pstart) + stop = self.builder.load(pstop) + step = self.builder.load(pstep) + return cgutils.is_null(self.builder, res), start, stop, step + + # + # List and sequence APIs + # + + def sequence_getslice(self, obj, start, stop): + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.py_ssize_t, + self.py_ssize_t]) + fn = self._get_function(fnty, name="PySequence_GetSlice") + return self.builder.call(fn, (obj, start, stop)) + + def sequence_tuple(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PySequence_Tuple") + return self.builder.call(fn, [obj]) + + def sequence_concat(self, obj1, obj2): + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PySequence_Concat") + return self.builder.call(fn, [obj1, obj2]) + + def list_new(self, szval): + fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t]) + fn = self._get_function(fnty, name="PyList_New") + return self.builder.call(fn, [szval]) + + def list_size(self, lst): + fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj]) + fn = self._get_function(fnty, name="PyList_Size") + return self.builder.call(fn, [lst]) + + def list_append(self, lst, val): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyList_Append") + return self.builder.call(fn, [lst, val]) + + def list_setitem(self, lst, idx, val): + """ + Warning: Steals reference to ``val`` + """ + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.py_ssize_t, + self.pyobj]) + fn = self._get_function(fnty, name="PyList_SetItem") + return self.builder.call(fn, [lst, idx, val]) + + def list_getitem(self, lst, idx): + """ + Returns a borrowed reference. + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.py_ssize_t]) + fn = self._get_function(fnty, name="PyList_GetItem") + if isinstance(idx, int): + idx = self.context.get_constant(types.intp, idx) + return self.builder.call(fn, [lst, idx]) + + def list_setslice(self, lst, start, stop, obj): + if obj is None: + obj = self.get_null_object() + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.py_ssize_t, + self.py_ssize_t, self.pyobj]) + fn = self._get_function(fnty, name="PyList_SetSlice") + return self.builder.call(fn, (lst, start, stop, obj)) + + + # + # Concrete tuple API + # + + def tuple_getitem(self, tup, idx): + """ + Borrow reference + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.py_ssize_t]) + fn = self._get_function(fnty, name="PyTuple_GetItem") + idx = self.context.get_constant(types.intp, idx) + return self.builder.call(fn, [tup, idx]) + + def tuple_pack(self, items): + fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t], var_arg=True) + fn = self._get_function(fnty, name="PyTuple_Pack") + n = self.context.get_constant(types.intp, len(items)) + args = [n] + args.extend(items) + return self.builder.call(fn, args) + + def tuple_size(self, tup): + fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj]) + fn = self._get_function(fnty, name="PyTuple_Size") + return self.builder.call(fn, [tup]) + + def tuple_new(self, count): + fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t]) + fn = self._get_function(fnty, name='PyTuple_New') + return self.builder.call(fn, [self.py_ssize_t(count)]) + + def tuple_setitem(self, tuple_val, index, item): + """ + Steals a reference to `item`. + """ + fnty = ir.FunctionType(ir.IntType(32), + [self.pyobj, self.py_ssize_t, self.pyobj]) + setitem_fn = self._get_function(fnty, name='PyTuple_SetItem') + index = self.py_ssize_t(index) + self.builder.call(setitem_fn, [tuple_val, index, item]) + + # + # Concrete set API + # + + def set_new(self, iterable=None): + if iterable is None: + iterable = self.get_null_object() + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PySet_New") + return self.builder.call(fn, [iterable]) + + def set_add(self, set, value): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PySet_Add") + return self.builder.call(fn, [set, value]) + + def set_clear(self, set): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj]) + fn = self._get_function(fnty, name="PySet_Clear") + return self.builder.call(fn, [set]) + + def set_size(self, set): + fnty = ir.FunctionType(self.py_ssize_t, [self.pyobj]) + fn = self._get_function(fnty, name="PySet_Size") + return self.builder.call(fn, [set]) + + def set_update(self, set, iterable): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="_PySet_Update") + return self.builder.call(fn, [set, iterable]) + + def set_next_entry(self, set, posptr, keyptr, hashptr): + fnty = ir.FunctionType(ir.IntType(32), + [self.pyobj, self.py_ssize_t.as_pointer(), + self.pyobj.as_pointer(), self.py_hash_t.as_pointer()]) + fn = self._get_function(fnty, name="_PySet_NextEntry") + return self.builder.call(fn, (set, posptr, keyptr, hashptr)) + + @contextlib.contextmanager + def set_iterate(self, set): + builder = self.builder + + hashptr = cgutils.alloca_once(builder, self.py_hash_t, name="hashptr") + keyptr = cgutils.alloca_once(builder, self.pyobj, name="keyptr") + posptr = cgutils.alloca_once_value(builder, + Constant(self.py_ssize_t, 0), + name="posptr") + + bb_body = builder.append_basic_block("bb_body") + bb_end = builder.append_basic_block("bb_end") + + builder.branch(bb_body) + def do_break(): + builder.branch(bb_end) + + with builder.goto_block(bb_body): + r = self.set_next_entry(set, posptr, keyptr, hashptr) + finished = cgutils.is_null(builder, r) + with builder.if_then(finished, likely=False): + builder.branch(bb_end) + yield _IteratorLoop(builder.load(keyptr), do_break) + builder.branch(bb_body) + + builder.position_at_end(bb_end) + + # + # GIL APIs + # + + def gil_ensure(self): + """ + Ensure the GIL is acquired. + The returned value must be consumed by gil_release(). + """ + gilptrty = ir.PointerType(self.gil_state) + fnty = ir.FunctionType(ir.VoidType(), [gilptrty]) + fn = self._get_function(fnty, "numba_gil_ensure") + gilptr = cgutils.alloca_once(self.builder, self.gil_state) + self.builder.call(fn, [gilptr]) + return gilptr + + def gil_release(self, gil): + """ + Release the acquired GIL by gil_ensure(). + Must be paired with a gil_ensure(). + """ + gilptrty = ir.PointerType(self.gil_state) + fnty = ir.FunctionType(ir.VoidType(), [gilptrty]) + fn = self._get_function(fnty, "numba_gil_release") + return self.builder.call(fn, [gil]) + + def save_thread(self): + """ + Release the GIL and return the former thread state + (an opaque non-NULL pointer). + """ + fnty = ir.FunctionType(self.voidptr, []) + fn = self._get_function(fnty, name="PyEval_SaveThread") + return self.builder.call(fn, []) + + def restore_thread(self, thread_state): + """ + Restore the given thread state by reacquiring the GIL. + """ + fnty = ir.FunctionType(ir.VoidType(), [self.voidptr]) + fn = self._get_function(fnty, name="PyEval_RestoreThread") + self.builder.call(fn, [thread_state]) + + # + # Generic object private data (a way of associating an arbitrary void * + # pointer to an arbitrary Python object). + # + + def object_get_private_data(self, obj): + fnty = ir.FunctionType(self.voidptr, [self.pyobj]) + fn = self._get_function(fnty, name="numba_get_pyobject_private_data") + return self.builder.call(fn, (obj,)) + + def object_set_private_data(self, obj, ptr): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj, self.voidptr]) + fn = self._get_function(fnty, name="numba_set_pyobject_private_data") + return self.builder.call(fn, (obj, ptr)) + + def object_reset_private_data(self, obj): + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="numba_reset_pyobject_private_data") + return self.builder.call(fn, (obj,)) + + + # + # Other APIs (organize them better!) + # + + def import_module(self, modname): + fnty = ir.FunctionType(self.pyobj, [self.cstring]) + fn = self._get_function(fnty, name="PyImport_ImportModule") + return self.builder.call(fn, [modname]) + + def call_function_objargs(self, callee, objargs): + fnty = ir.FunctionType(self.pyobj, [self.pyobj], var_arg=True) + fn = self._get_function(fnty, name="PyObject_CallFunctionObjArgs") + args = [callee] + list(objargs) + args.append(self.context.get_constant_null(types.pyobject)) + return self.builder.call(fn, args) + + def call_method(self, callee, method, objargs=()): + cname = self.context.insert_const_string(self.module, method) + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.cstring, self.cstring], + var_arg=True) + fn = self._get_function(fnty, name="PyObject_CallMethod") + fmt = 'O' * len(objargs) + cfmt = self.context.insert_const_string(self.module, fmt) + args = [callee, cname, cfmt] + if objargs: + args.extend(objargs) + args.append(self.context.get_constant_null(types.pyobject)) + return self.builder.call(fn, args) + + def call(self, callee, args=None, kws=None): + if args_was_none := args is None: + args = self.tuple_new(0) + if kws is None: + kws = self.get_null_object() + fnty = ir.FunctionType(self.pyobj, [self.pyobj] * 3) + fn = self._get_function(fnty, name="PyObject_Call") + result = self.builder.call(fn, (callee, args, kws)) + if args_was_none: + self.decref(args) + return result + + def object_type(self, obj): + """Emit a call to ``PyObject_Type(obj)`` to get the type of ``obj``. + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyObject_Type") + return self.builder.call(fn, (obj,)) + + def object_istrue(self, obj): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj]) + fn = self._get_function(fnty, name="PyObject_IsTrue") + return self.builder.call(fn, [obj]) + + def object_not(self, obj): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj]) + fn = self._get_function(fnty, name="PyObject_Not") + return self.builder.call(fn, [obj]) + + def object_richcompare(self, lhs, rhs, opstr): + """ + Refer to Python source Include/object.h for macros definition + of the opid. + """ + ops = ['<', '<=', '==', '!=', '>', '>='] + if opstr in ops: + opid = ops.index(opstr) + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj, ir.IntType(32)]) + fn = self._get_function(fnty, name="PyObject_RichCompare") + lopid = self.context.get_constant(types.int32, opid) + return self.builder.call(fn, (lhs, rhs, lopid)) + elif opstr == 'is': + bitflag = self.builder.icmp_unsigned('==', lhs, rhs) + return self.bool_from_bool(bitflag) + elif opstr == 'is not': + bitflag = self.builder.icmp_unsigned('!=', lhs, rhs) + return self.bool_from_bool(bitflag) + elif opstr in ('in', 'not in'): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PySequence_Contains") + status = self.builder.call(fn, (rhs, lhs)) + negone = self.context.get_constant(types.int32, -1) + is_good = self.builder.icmp_unsigned('!=', status, negone) + # Stack allocate output and initialize to Null + outptr = cgutils.alloca_once_value(self.builder, + Constant(self.pyobj, None)) + # If PySequence_Contains returns non-error value + with cgutils.if_likely(self.builder, is_good): + if opstr == 'not in': + status = self.builder.not_(status) + # Store the status as a boolean object + truncated = self.builder.trunc(status, ir.IntType(1)) + self.builder.store(self.bool_from_bool(truncated), + outptr) + + return self.builder.load(outptr) + else: + raise NotImplementedError("Unknown operator {op!r}".format( + op=opstr)) + + def iter_next(self, iterobj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyIter_Next") + return self.builder.call(fn, [iterobj]) + + def object_getiter(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyObject_GetIter") + return self.builder.call(fn, [obj]) + + def object_getattr_string(self, obj, attr): + cstr = self.context.insert_const_string(self.module, attr) + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.cstring]) + fn = self._get_function(fnty, name="PyObject_GetAttrString") + return self.builder.call(fn, [obj, cstr]) + + def object_getattr(self, obj, attr): + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_GetAttr") + return self.builder.call(fn, [obj, attr]) + + def object_setattr_string(self, obj, attr, val): + cstr = self.context.insert_const_string(self.module, attr) + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.cstring, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_SetAttrString") + return self.builder.call(fn, [obj, cstr, val]) + + def object_setattr(self, obj, attr, val): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_SetAttr") + return self.builder.call(fn, [obj, attr, val]) + + def object_delattr_string(self, obj, attr): + # PyObject_DelAttrString() is actually a C macro calling + # PyObject_SetAttrString() with value == NULL. + return self.object_setattr_string(obj, attr, self.get_null_object()) + + def object_delattr(self, obj, attr): + # PyObject_DelAttr() is actually a C macro calling + # PyObject_SetAttr() with value == NULL. + return self.object_setattr(obj, attr, self.get_null_object()) + + def object_getitem(self, obj, key): + """ + Return obj[key] + """ + fnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_GetItem") + return self.builder.call(fn, (obj, key)) + + def object_setitem(self, obj, key, val): + """ + obj[key] = val + """ + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_SetItem") + return self.builder.call(fn, (obj, key, val)) + + def object_delitem(self, obj, key): + """ + del obj[key] + """ + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.pyobj]) + fn = self._get_function(fnty, name="PyObject_DelItem") + return self.builder.call(fn, (obj, key)) + + def string_as_string(self, strobj): + fnty = ir.FunctionType(self.cstring, [self.pyobj]) + fname = "PyUnicode_AsUTF8" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [strobj]) + + def string_as_string_and_size(self, strobj): + """ + Returns a tuple of ``(ok, buffer, length)``. + The ``ok`` is i1 value that is set if ok. + The ``buffer`` is a i8* of the output buffer. + The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer. + """ + + p_length = cgutils.alloca_once(self.builder, self.py_ssize_t) + fnty = ir.FunctionType(self.cstring, [self.pyobj, + self.py_ssize_t.as_pointer()]) + fname = "PyUnicode_AsUTF8AndSize" + fn = self._get_function(fnty, name=fname) + + buffer = self.builder.call(fn, [strobj, p_length]) + ok = self.builder.icmp_unsigned('!=', + Constant(buffer.type, None), + buffer) + return (ok, buffer, self.builder.load(p_length)) + + def string_as_string_size_and_kind(self, strobj): + """ + Returns a tuple of ``(ok, buffer, length, kind)``. + The ``ok`` is i1 value that is set if ok. + The ``buffer`` is a i8* of the output buffer. + The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer. + The ``kind`` is a i32 (int32) of the Unicode kind constant + The ``hash`` is a long/uint64_t (py_hash_t) of the Unicode constant hash + """ + p_length = cgutils.alloca_once(self.builder, self.py_ssize_t) + p_kind = cgutils.alloca_once(self.builder, ir.IntType(32)) + p_ascii = cgutils.alloca_once(self.builder, ir.IntType(32)) + p_hash = cgutils.alloca_once(self.builder, self.py_hash_t) + fnty = ir.FunctionType(self.cstring, [self.pyobj, + self.py_ssize_t.as_pointer(), + ir.IntType(32).as_pointer(), + ir.IntType(32).as_pointer(), + self.py_hash_t.as_pointer()]) + fname = "numba_extract_unicode" + fn = self._get_function(fnty, name=fname) + + buffer = self.builder.call( + fn, [strobj, p_length, p_kind, p_ascii, p_hash]) + ok = self.builder.icmp_unsigned('!=', + Constant(buffer.type, None), + buffer) + return (ok, buffer, self.builder.load(p_length), + self.builder.load(p_kind), self.builder.load(p_ascii), + self.builder.load(p_hash)) + + def string_from_string_and_size(self, string, size): + fnty = ir.FunctionType(self.pyobj, [self.cstring, self.py_ssize_t]) + fname = "PyString_FromStringAndSize" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [string, size]) + + def string_from_string(self, string): + fnty = ir.FunctionType(self.pyobj, [self.cstring]) + fname = "PyUnicode_FromString" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [string]) + + def string_from_kind_and_data(self, kind, string, size): + fnty = ir.FunctionType(self.pyobj, [ir.IntType(32), self.cstring, self.py_ssize_t]) + fname = "PyUnicode_FromKindAndData" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [kind, string, size]) + + def bytes_as_string(self, obj): + fnty = ir.FunctionType(self.cstring, [self.pyobj]) + fname = "PyBytes_AsString" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [obj]) + + def bytes_as_string_and_size(self, obj, p_buffer, p_length): + fnty = ir.FunctionType( + ir.IntType(32), + [self.pyobj, self.cstring.as_pointer(), self.py_ssize_t.as_pointer()], + ) + fname = "PyBytes_AsStringAndSize" + fn = self._get_function(fnty, name=fname) + result = self.builder.call(fn, [obj, p_buffer, p_length]) + ok = self.builder.icmp_signed("!=", Constant(result.type, -1), result) + return ok + + def bytes_from_string_and_size(self, string, size): + fnty = ir.FunctionType(self.pyobj, [self.cstring, self.py_ssize_t]) + fname = "PyBytes_FromStringAndSize" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [string, size]) + + def object_hash(self, obj): + fnty = ir.FunctionType(self.py_hash_t, [self.pyobj, ]) + fname = "PyObject_Hash" + fn = self._get_function(fnty, name=fname) + return self.builder.call(fn, [obj,]) + + def object_str(self, obj): + fnty = ir.FunctionType(self.pyobj, [self.pyobj]) + fn = self._get_function(fnty, name="PyObject_Str") + return self.builder.call(fn, [obj]) + + def make_none(self): + obj = self.borrow_none() + self.incref(obj) + return obj + + def borrow_none(self): + return self.get_c_object("_Py_NoneStruct") + + def sys_write_stdout(self, fmt, *args): + fnty = ir.FunctionType(ir.VoidType(), [self.cstring], var_arg=True) + fn = self._get_function(fnty, name="PySys_FormatStdout") + return self.builder.call(fn, (fmt,) + args) + + def object_dump(self, obj): + """ + Dump a Python object on C stderr. For debugging purposes. + """ + fnty = ir.FunctionType(ir.VoidType(), [self.pyobj]) + fn = self._get_function(fnty, name="_PyObject_Dump") + return self.builder.call(fn, (obj,)) + + # + # NRT (Numba runtime) APIs + # + + def nrt_adapt_ndarray_to_python(self, aryty, ary, dtypeptr): + assert self.context.enable_nrt, "NRT required" + + intty = ir.IntType(32) + # Embed the Python type of the array (maybe subclass) in the LLVM IR. + serial_aryty_pytype = self.unserialize(self.serialize_object(aryty.box_type)) + + fnty = ir.FunctionType(self.pyobj, + [self.voidptr, self.pyobj, intty, intty, self.pyobj]) + fn = self._get_function(fnty, name="NRT_adapt_ndarray_to_python_acqref") + fn.args[0].add_attribute('nocapture') + + ndim = self.context.get_constant(types.int32, aryty.ndim) + writable = self.context.get_constant(types.int32, int(aryty.mutable)) + + aryptr = cgutils.alloca_once_value(self.builder, ary) + return self.builder.call(fn, [self.builder.bitcast(aryptr, + self.voidptr), + serial_aryty_pytype, + ndim, writable, dtypeptr]) + + def nrt_meminfo_new_from_pyobject(self, data, pyobj): + """ + Allocate a new MemInfo with data payload borrowed from a python + object. + """ + mod = self.builder.module + fnty = ir.FunctionType( + cgutils.voidptr_t, + [cgutils.voidptr_t, cgutils.voidptr_t], + ) + fn = cgutils.get_or_insert_function( + mod, + fnty, + "NRT_meminfo_new_from_pyobject", + ) + fn.args[0].add_attribute('nocapture') + fn.args[1].add_attribute('nocapture') + fn.return_value.add_attribute("noalias") + return self.builder.call(fn, [data, pyobj]) + + def nrt_meminfo_as_pyobject(self, miptr): + mod = self.builder.module + fnty = ir.FunctionType( + self.pyobj, + [cgutils.voidptr_t] + ) + fn = cgutils.get_or_insert_function( + mod, + fnty, + 'NRT_meminfo_as_pyobject', + ) + fn.return_value.add_attribute("noalias") + return self.builder.call(fn, [miptr]) + + def nrt_meminfo_from_pyobject(self, miobj): + mod = self.builder.module + fnty = ir.FunctionType( + cgutils.voidptr_t, + [self.pyobj] + ) + fn = cgutils.get_or_insert_function( + mod, + fnty, + 'NRT_meminfo_from_pyobject', + ) + fn.return_value.add_attribute("noalias") + return self.builder.call(fn, [miobj]) + + def nrt_adapt_ndarray_from_python(self, ary, ptr): + assert self.context.enable_nrt + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.voidptr]) + fn = self._get_function(fnty, name="NRT_adapt_ndarray_from_python") + fn.args[0].add_attribute('nocapture') + fn.args[1].add_attribute('nocapture') + return self.builder.call(fn, (ary, ptr)) + + def nrt_adapt_buffer_from_python(self, buf, ptr): + assert self.context.enable_nrt + fnty = ir.FunctionType(ir.VoidType(), [ir.PointerType(self.py_buffer_t), + self.voidptr]) + fn = self._get_function(fnty, name="NRT_adapt_buffer_from_python") + fn.args[0].add_attribute('nocapture') + fn.args[1].add_attribute('nocapture') + return self.builder.call(fn, (buf, ptr)) + + # ------ utils ----- + + def _get_function(self, fnty, name): + fn = cgutils.get_or_insert_function(self.module, fnty, name) + self.context.apply_target_attributes(fn) + return fn + + def alloca_obj(self): + return self.builder.alloca(self.pyobj) + + def alloca_buffer(self): + """ + Return a pointer to a stack-allocated, zero-initialized Py_buffer. + """ + # Treat the buffer as an opaque array of bytes + ptr = cgutils.alloca_once_value(self.builder, + Constant(self.py_buffer_t, None)) + return ptr + + @contextlib.contextmanager + def if_object_ok(self, obj): + with cgutils.if_likely(self.builder, + cgutils.is_not_null(self.builder, obj)): + yield + + def print_object(self, obj): + strobj = self.object_str(obj) + cstr = self.string_as_string(strobj) + fmt = self.context.insert_const_string(self.module, "%s") + self.sys_write_stdout(fmt, cstr) + self.decref(strobj) + + def print_string(self, text): + fmt = self.context.insert_const_string(self.module, text) + self.sys_write_stdout(fmt) + + def get_null_object(self): + return Constant(self.pyobj, None) + + def return_none(self): + none = self.make_none() + self.builder.ret(none) + + def list_pack(self, items): + n = len(items) + seq = self.list_new(self.context.get_constant(types.intp, n)) + with self.if_object_ok(seq): + for i in range(n): + idx = self.context.get_constant(types.intp, i) + self.incref(items[i]) + self.list_setitem(seq, idx, items[i]) + return seq + + def unserialize(self, structptr): + """ + Unserialize some data. *structptr* should be a pointer to + a {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag} + structure. + """ + fnty = ir.FunctionType(self.pyobj, + (self.voidptr, ir.IntType(32), self.voidptr)) + fn = self._get_function(fnty, name="numba_unpickle") + ptr = self.builder.extract_value(self.builder.load(structptr), 0) + n = self.builder.extract_value(self.builder.load(structptr), 1) + hashed = self.builder.extract_value(self.builder.load(structptr), 2) + return self.builder.call(fn, (ptr, n, hashed)) + + def build_dynamic_excinfo_struct(self, struct_gv, exc_args): + """ + Serialize some data at runtime. Returns a pointer to a python tuple + (bytes_data, hash) where the first element is the serialized data as + bytes and the second its hash. + """ + fnty = ir.FunctionType(self.pyobj, (self.pyobj, self.pyobj)) + fn = self._get_function(fnty, name="numba_runtime_build_excinfo_struct") + return self.builder.call(fn, (struct_gv, exc_args)) + + def serialize_uncached(self, obj): + """ + Same as serialize_object(), but don't create a global variable, + simply return a literal for structure: + {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag} + """ + # First make the array constant + data = serialize.dumps(obj) + assert len(data) < 2**31 + name = ".const.pickledata.%s" % (id(obj) if config.DIFF_IR == 0 else "DIFF_IR") + bdata = cgutils.make_bytearray(data) + # Make SHA1 hash on the pickled content + # NOTE: update buffer size in numba_unpickle() when changing the + # hash algorithm. + hashed = cgutils.make_bytearray(hashlib.sha1(data).digest()) + arr = self.context.insert_unique_const(self.module, name, bdata) + hasharr = self.context.insert_unique_const( + self.module, f"{name}.sha1", hashed, + ) + # Then populate the structure constant + struct = Constant.literal_struct([ + arr.bitcast(self.voidptr), + Constant(ir.IntType(32), arr.type.pointee.count), + hasharr.bitcast(self.voidptr), + cgutils.get_null_value(self.voidptr), + Constant(ir.IntType(32), 0), + ]) + return struct + + def serialize_object(self, obj): + """ + Serialize the given object in the bitcode, and return it + as a pointer to a + {i8* data, i32 length, i8* hashbuf, i8* fn_ptr, i32 alloc_flag}, + structure constant (suitable for passing to unserialize()). + """ + try: + gv = self.module.__serialized[obj] + except KeyError: + struct = self.serialize_uncached(obj) + name = ".const.picklebuf.%s" % (id(obj) if config.DIFF_IR == 0 else "DIFF_IR") + gv = self.context.insert_unique_const(self.module, name, struct) + # Make the id() (and hence the name) unique while populating the module. + self.module.__serialized[obj] = gv + return gv + + def c_api_error(self): + return cgutils.is_not_null(self.builder, self.err_occurred()) + + def to_native_value(self, typ, obj): + """ + Unbox the Python object as the given Numba type. + A NativeValue instance is returned. + """ + from numba.core.boxing import unbox_unsupported + + impl = _unboxers.lookup(typ.__class__, unbox_unsupported) + c = _UnboxContext(self.context, self.builder, self) + return impl(typ, obj, c) + + def from_native_return(self, typ, val, env_manager): + assert not isinstance(typ, types.Optional), "callconv should have " \ + "prevented the return of " \ + "optional value" + out = self.from_native_value(typ, val, env_manager) + return out + + def from_native_value(self, typ, val, env_manager=None): + """ + Box the native value of the given Numba type. A Python object + pointer is returned (NULL if an error occurred). + This method steals any native (NRT) reference embedded in *val*. + """ + from numba.core.boxing import box_unsupported + + impl = _boxers.lookup(typ.__class__, box_unsupported) + + c = _BoxContext(self.context, self.builder, self, env_manager) + return impl(typ, val, c) + + def reflect_native_value(self, typ, val, env_manager=None): + """ + Reflect the native value onto its Python original, if any. + An error bit (as an LLVM value) is returned. + """ + impl = _reflectors.lookup(typ.__class__) + if impl is None: + # Reflection isn't needed for most types + return cgutils.false_bit + + is_error = cgutils.alloca_once_value(self.builder, cgutils.false_bit) + c = _ReflectContext(self.context, self.builder, self, env_manager, + is_error) + impl(typ, val, c) + return self.builder.load(c.is_error) + + def to_native_generator(self, obj, typ): + """ + Extract the generator structure pointer from a generator *obj* + (a _dynfunc.Generator instance). + """ + gen_ptr_ty = ir.PointerType(self.context.get_data_type(typ)) + value = self.context.get_generator_state(self.builder, obj, gen_ptr_ty) + return NativeValue(value) + + def from_native_generator(self, val, typ, env=None): + """ + Make a Numba generator (a _dynfunc.Generator instance) from a + generator structure pointer *val*. + *env* is an optional _dynfunc.Environment instance to be wrapped + in the generator. + """ + llty = self.context.get_data_type(typ) + assert not llty.is_pointer + gen_struct_size = self.context.get_abi_sizeof(llty) + + gendesc = self.context.get_generator_desc(typ) + + # This is the PyCFunctionWithKeywords generated by PyCallWrapper + genfnty = ir.FunctionType(self.pyobj, [self.pyobj, self.pyobj, self.pyobj]) + genfn = self._get_function(genfnty, name=gendesc.llvm_cpython_wrapper_name) + + # This is the raw finalizer generated by _lower_generator_finalize_func() + finalizerty = ir.FunctionType(ir.VoidType(), [self.voidptr]) + if typ.has_finalizer: + finalizer = self._get_function(finalizerty, name=gendesc.llvm_finalizer_name) + else: + finalizer = Constant(ir.PointerType(finalizerty), None) + + # PyObject *numba_make_generator(state_size, initial_state, nextfunc, finalizer, env) + fnty = ir.FunctionType(self.pyobj, [self.py_ssize_t, + self.voidptr, + ir.PointerType(genfnty), + ir.PointerType(finalizerty), + self.voidptr]) + fn = self._get_function(fnty, name="numba_make_generator") + + state_size = Constant(self.py_ssize_t, gen_struct_size) + initial_state = self.builder.bitcast(val, self.voidptr) + if env is None: + env = self.get_null_object() + env = self.builder.bitcast(env, self.voidptr) + + return self.builder.call(fn, + (state_size, initial_state, genfn, finalizer, env)) + + def numba_array_adaptor(self, ary, ptr): + assert not self.context.enable_nrt + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, self.voidptr]) + fn = self._get_function(fnty, name="numba_adapt_ndarray") + fn.args[0].add_attribute('nocapture') + fn.args[1].add_attribute('nocapture') + return self.builder.call(fn, (ary, ptr)) + + def numba_buffer_adaptor(self, buf, ptr): + fnty = ir.FunctionType(ir.VoidType(), + [ir.PointerType(self.py_buffer_t), self.voidptr]) + fn = self._get_function(fnty, name="numba_adapt_buffer") + fn.args[0].add_attribute('nocapture') + fn.args[1].add_attribute('nocapture') + return self.builder.call(fn, (buf, ptr)) + + def complex_adaptor(self, cobj, cmplx): + fnty = ir.FunctionType(ir.IntType(32), [self.pyobj, cmplx.type]) + fn = self._get_function(fnty, name="numba_complex_adaptor") + return self.builder.call(fn, [cobj, cmplx]) + + def extract_record_data(self, obj, pbuf): + fnty = ir.FunctionType(self.voidptr, + [self.pyobj, ir.PointerType(self.py_buffer_t)]) + fn = self._get_function(fnty, name="numba_extract_record_data") + return self.builder.call(fn, [obj, pbuf]) + + def get_buffer(self, obj, pbuf): + fnty = ir.FunctionType(ir.IntType(32), + [self.pyobj, ir.PointerType(self.py_buffer_t)]) + fn = self._get_function(fnty, name="numba_get_buffer") + return self.builder.call(fn, [obj, pbuf]) + + def release_buffer(self, pbuf): + fnty = ir.FunctionType(ir.VoidType(), [ir.PointerType(self.py_buffer_t)]) + fn = self._get_function(fnty, name="numba_release_buffer") + return self.builder.call(fn, [pbuf]) + + def extract_np_datetime(self, obj): + fnty = ir.FunctionType(ir.IntType(64), [self.pyobj]) + fn = self._get_function(fnty, name="numba_extract_np_datetime") + return self.builder.call(fn, [obj]) + + def extract_np_timedelta(self, obj): + fnty = ir.FunctionType(ir.IntType(64), [self.pyobj]) + fn = self._get_function(fnty, name="numba_extract_np_timedelta") + return self.builder.call(fn, [obj]) + + def create_np_datetime(self, val, unit_code): + unit_code = Constant(ir.IntType(32), int(unit_code)) + fnty = ir.FunctionType(self.pyobj, [ir.IntType(64), ir.IntType(32)]) + fn = self._get_function(fnty, name="numba_create_np_datetime") + return self.builder.call(fn, [val, unit_code]) + + def create_np_timedelta(self, val, unit_code): + unit_code = Constant(ir.IntType(32), int(unit_code)) + fnty = ir.FunctionType(self.pyobj, [ir.IntType(64), ir.IntType(32)]) + fn = self._get_function(fnty, name="numba_create_np_timedelta") + return self.builder.call(fn, [val, unit_code]) + + def recreate_record(self, pdata, size, dtype, env_manager): + fnty = ir.FunctionType(self.pyobj, [ir.PointerType(ir.IntType(8)), + ir.IntType(32), self.pyobj]) + fn = self._get_function(fnty, name="numba_recreate_record") + dtypeaddr = env_manager.read_const(env_manager.add_const(dtype)) + return self.builder.call(fn, [pdata, size, dtypeaddr]) + + def string_from_constant_string(self, string): + cstr = self.context.insert_const_string(self.module, string) + sz = self.context.get_constant(types.intp, len(string)) + return self.string_from_string_and_size(cstr, sz) + + def call_jit_code(self, func, sig, args): + """Calls into Numba jitted code and propagate error using the Python + calling convention. + + Parameters + ---------- + func : function + The Python function to be compiled. This function is compiled + in nopython-mode. + sig : numba.typing.Signature + The function signature for *func*. + args : Sequence[llvmlite.binding.Value] + LLVM values to use as arguments. + + Returns + ------- + (is_error, res) : 2-tuple of llvmlite.binding.Value. + is_error : true iff *func* raised an exception. + res : Returned value from *func* iff *is_error* is false. + + If *is_error* is true, this method will adapt the nopython exception + into a Python exception. Caller should return NULL to Python to + indicate an error. + """ + # Compile *func* + builder = self.builder + cres = self.context.compile_subroutine(builder, func, sig) + got_retty = cres.signature.return_type + retty = sig.return_type + if got_retty != retty: + # This error indicates an error in *func* or the caller of this + # method. + raise errors.LoweringError( + f'mismatching signature {got_retty} != {retty}.\n' + ) + # Call into *func* + status, res = self.context.call_internal_no_propagate( + builder, cres.fndesc, sig, args, + ) + # Post-call handling for *func* + is_error_ptr = cgutils.alloca_once(builder, cgutils.bool_t, zfill=True) + res_type = self.context.get_value_type(sig.return_type) + res_ptr = cgutils.alloca_once(builder, res_type, zfill=True) + + # Handle error and adapt the nopython exception into cpython exception + with builder.if_else(status.is_error) as (has_err, no_err): + with has_err: + builder.store(status.is_error, is_error_ptr) + # Set error state in the Python interpreter + self.context.call_conv.raise_error(builder, self, status) + with no_err: + # Handle returned value + res = imputils.fix_returning_optional( + self.context, builder, sig, status, res, + ) + builder.store(res, res_ptr) + + is_error = builder.load(is_error_ptr) + res = builder.load(res_ptr) + return is_error, res + + +class ObjModeUtils: + """Internal utils for calling objmode dispatcher from within NPM code. + """ + def __init__(self, pyapi): + self.pyapi = pyapi + + def load_dispatcher(self, fnty, argtypes): + builder = self.pyapi.builder + tyctx = self.pyapi.context + m = builder.module + + # Add a global variable to cache the objmode dispatcher + gv = ir.GlobalVariable( + m, self.pyapi.pyobj, + name=m.get_unique_name("cached_objmode_dispatcher"), + ) + gv.initializer = gv.type.pointee(None) + gv.linkage = 'internal' + + # Make a basic-block to common exit + bb_end = builder.append_basic_block("bb_end") + + if serialize.is_serialiable(fnty.dispatcher): + serialized_dispatcher = self.pyapi.serialize_object( + (fnty.dispatcher, tuple(argtypes)), + ) + compile_args = self.pyapi.unserialize(serialized_dispatcher) + # unserialize (unpickling) can fail + failed_unser = cgutils.is_null(builder, compile_args) + with builder.if_then(failed_unser): + # early exit. `gv` is still null. + builder.branch(bb_end) + + cached = builder.load(gv) + with builder.if_then(cgutils.is_null(builder, cached)): + if serialize.is_serialiable(fnty.dispatcher): + cls = type(self) + compiler = self.pyapi.unserialize( + self.pyapi.serialize_object(cls._call_objmode_dispatcher) + ) + callee = self.pyapi.call_function_objargs( + compiler, [compile_args], + ) + # Clean up + self.pyapi.decref(compiler) + self.pyapi.decref(compile_args) + else: + entry_pt = fnty.dispatcher.compile(tuple(argtypes)) + callee = tyctx.add_dynamic_addr( + builder, id(entry_pt), info="with_objectmode", + ) + # Incref the dispatcher and cache it + self.pyapi.incref(callee) + builder.store(callee, gv) + # Jump to the exit block + builder.branch(bb_end) + # Define the exit block + builder.position_at_end(bb_end) + callee = builder.load(gv) + return callee + + @staticmethod + def _call_objmode_dispatcher(compile_args): + dispatcher, argtypes = compile_args + entrypt = dispatcher.compile(argtypes) + return entrypt diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/registry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..14f23aae7072b9709d9f0b2b99252f1711bf8ed9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/registry.py @@ -0,0 +1,84 @@ +import contextlib +#from functools import cached_property +from numba.core.utils import threadsafe_cached_property as cached_property + +from numba.core.descriptors import TargetDescriptor +from numba.core import utils, typing, dispatcher, cpu + +# ----------------------------------------------------------------------------- +# Default CPU target descriptors + + +class CPUTarget(TargetDescriptor): + options = cpu.CPUTargetOptions + + @cached_property + def _toplevel_target_context(self): + # Lazily-initialized top-level target context, for all threads + return cpu.CPUContext(self.typing_context, self._target_name) + + @cached_property + def _toplevel_typing_context(self): + # Lazily-initialized top-level typing context, for all threads + return typing.Context() + + @property + def target_context(self): + """ + The target context for CPU targets. + """ + return self._toplevel_target_context + + @property + def typing_context(self): + """ + The typing context for CPU targets. + """ + return self._toplevel_typing_context + + +# The global CPU target +cpu_target = CPUTarget('cpu') + + +class CPUDispatcher(dispatcher.Dispatcher): + targetdescr = cpu_target + + +class DelayedRegistry(utils.UniqueDict): + """ + A unique dictionary but with deferred initialisation of the values. + + Attributes + ---------- + ondemand: + + A dictionary of key -> value, where value is executed + the first time it is is used. It is used for part of a deferred + initialization strategy. + """ + def __init__(self, *args, **kws): + self.ondemand = utils.UniqueDict() + self.key_type = kws.pop('key_type', None) + self.value_type = kws.pop('value_type', None) + self._type_check = self.key_type or self.value_type + super(DelayedRegistry, self).__init__(*args, **kws) + + def __getitem__(self, item): + if item in self.ondemand: + self[item] = self.ondemand[item]() + del self.ondemand[item] + return super(DelayedRegistry, self).__getitem__(item) + + def __setitem__(self, key, value): + if self._type_check: + def check(x, ty_x): + if isinstance(ty_x, type): + assert ty_x in x.__mro__, (x, ty_x) + else: + assert isinstance(x, ty_x), (x, ty_x) + if self.key_type is not None: + check(key, self.key_type) + if self.value_type is not None: + check(value, self.value_type) + return super(DelayedRegistry, self).__setitem__(key, value) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/removerefctpass.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/removerefctpass.py new file mode 100644 index 0000000000000000000000000000000000000000..98c04869a0bc5988dc936b920340a43ea06b438c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/removerefctpass.py @@ -0,0 +1,120 @@ +""" +Implement a rewrite pass on a LLVM module to remove unnecessary +refcount operations. +""" + +from llvmlite.ir.transforms import CallVisitor + +from numba.core import types + + +class _MarkNrtCallVisitor(CallVisitor): + """ + A pass to mark all NRT_incref and NRT_decref. + """ + def __init__(self): + self.marked = set() + + def visit_Call(self, instr): + if getattr(instr.callee, 'name', '') in _accepted_nrtfns: + self.marked.add(instr) + + +def _rewrite_function(function): + # Mark NRT usage + markpass = _MarkNrtCallVisitor() + markpass.visit_Function(function) + # Remove NRT usage + for bb in function.basic_blocks: + for inst in list(bb.instructions): + if inst in markpass.marked: + bb.instructions.remove(inst) + + +_accepted_nrtfns = 'NRT_incref', 'NRT_decref' + + +def _legalize(module, dmm, fndesc): + """ + Legalize the code in the module. + Returns True if the module is legal for the rewrite pass that removes + unnecessary refcounts. + """ + + def valid_output(ty): + """ + Valid output are any type that does not need refcount + """ + model = dmm[ty] + return not model.contains_nrt_meminfo() + + def valid_input(ty): + """ + Valid input are any type that does not need refcount except Array. + """ + return valid_output(ty) or isinstance(ty, types.Array) + + + # Ensure no reference to function marked as + # "numba_args_may_always_need_nrt" + try: + nmd = module.get_named_metadata("numba_args_may_always_need_nrt") + except KeyError: + # Nothing marked + pass + else: + # Has functions marked as "numba_args_may_always_need_nrt" + if len(nmd.operands) > 0: + # The pass is illegal for this compilation unit. + return False + + # More legalization base on function type + argtypes = fndesc.argtypes + restype = fndesc.restype + calltypes = fndesc.calltypes + + # Legalize function arguments + for argty in argtypes: + if not valid_input(argty): + return False + + # Legalize function return + if not valid_output(restype): + return False + + # Legalize all called functions + for callty in calltypes.values(): + if callty is not None and not valid_output(callty.return_type): + return False + + # Ensure no allocation + for fn in module.functions: + if fn.name.startswith("NRT_"): + if fn.name not in _accepted_nrtfns: + return False + + return True + + +def remove_unnecessary_nrt_usage(function, context, fndesc): + """ + Remove unnecessary NRT incref/decref in the given LLVM function. + It uses highlevel type info to determine if the function does not need NRT. + Such a function does not: + + - return array object(s); + - take arguments that need refcounting except array; + - call function(s) that return refcounted object. + + In effect, the function will not capture or create references that extend + the lifetime of any refcounted objects beyond the lifetime of the function. + + The rewrite is performed in place. + If rewrite has happened, this function returns True, otherwise, it returns False. + """ + dmm = context.data_model_manager + if _legalize(function.module, dmm, fndesc): + _rewrite_function(function) + return True + else: + return False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/serialize.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..3103c58f9aaecb1b57788b007fa805053daca88d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/serialize.py @@ -0,0 +1,260 @@ +""" +Serialization support for compiled functions. +""" +import sys +import abc +import io +import copyreg + + +import pickle +from numba import cloudpickle +from llvmlite import ir + + +# +# Pickle support +# + +def _rebuild_reduction(cls, *args): + """ + Global hook to rebuild a given class from its __reduce__ arguments. + """ + return cls._rebuild(*args) + + +# Keep unpickled object via `numba_unpickle` alive. +_unpickled_memo = {} + + +def _numba_unpickle(address, bytedata, hashed): + """Used by `numba_unpickle` from _helperlib.c + + Parameters + ---------- + address : int + bytedata : bytes + hashed : bytes + + Returns + ------- + obj : object + unpickled object + """ + key = (address, hashed) + try: + obj = _unpickled_memo[key] + except KeyError: + _unpickled_memo[key] = obj = cloudpickle.loads(bytedata) + return obj + + +def dumps(obj): + """Similar to `pickle.dumps()`. Returns the serialized object in bytes. + """ + pickler = NumbaPickler + with io.BytesIO() as buf: + p = pickler(buf, protocol=4) + p.dump(obj) + pickled = buf.getvalue() + + return pickled + + +def runtime_build_excinfo_struct(static_exc, exc_args): + exc, static_args, locinfo = cloudpickle.loads(static_exc) + real_args = [] + exc_args_iter = iter(exc_args) + for arg in static_args: + if isinstance(arg, ir.Value): + real_args.append(next(exc_args_iter)) + else: + real_args.append(arg) + return (exc, tuple(real_args), locinfo) + + +# Alias to pickle.loads to allow `serialize.loads()` +loads = cloudpickle.loads + + +class _CustomPickled: + """A wrapper for objects that must be pickled with `NumbaPickler`. + + Standard `pickle` will pick up the implementation registered via `copyreg`. + This will spawn a `NumbaPickler` instance to serialize the data. + + `NumbaPickler` overrides the handling of this type so as not to spawn a + new pickler for the object when it is already being pickled by a + `NumbaPickler`. + """ + + __slots__ = 'ctor', 'states' + + def __init__(self, ctor, states): + self.ctor = ctor + self.states = states + + def _reduce(self): + return _CustomPickled._rebuild, (self.ctor, self.states) + + @classmethod + def _rebuild(cls, ctor, states): + return cls(ctor, states) + + +def _unpickle__CustomPickled(serialized): + """standard unpickling for `_CustomPickled`. + + Uses `NumbaPickler` to load. + """ + ctor, states = loads(serialized) + return _CustomPickled(ctor, states) + + +def _pickle__CustomPickled(cp): + """standard pickling for `_CustomPickled`. + + Uses `NumbaPickler` to dump. + """ + serialized = dumps((cp.ctor, cp.states)) + return _unpickle__CustomPickled, (serialized,) + + +# Register custom pickling for the standard pickler. +copyreg.pickle(_CustomPickled, _pickle__CustomPickled) + + +def custom_reduce(cls, states): + """For customizing object serialization in `__reduce__`. + + Object states provided here are used as keyword arguments to the + `._rebuild()` class method. + + Parameters + ---------- + states : dict + Dictionary of object states to be serialized. + + Returns + ------- + result : tuple + This tuple conforms to the return type requirement for `__reduce__`. + """ + return custom_rebuild, (_CustomPickled(cls, states),) + + +def custom_rebuild(custom_pickled): + """Customized object deserialization. + + This function is referenced internally by `custom_reduce()`. + """ + cls, states = custom_pickled.ctor, custom_pickled.states + return cls._rebuild(**states) + + +def is_serialiable(obj): + """Check if *obj* can be serialized. + + Parameters + ---------- + obj : object + + Returns + -------- + can_serialize : bool + """ + with io.BytesIO() as fout: + pickler = NumbaPickler(fout) + try: + pickler.dump(obj) + except pickle.PicklingError: + return False + else: + return True + + +def _no_pickle(obj): + raise pickle.PicklingError(f"Pickling of {type(obj)} is unsupported") + + +def disable_pickling(typ): + """This is called on a type to disable pickling + """ + NumbaPickler.disabled_types.add(typ) + # Return `typ` to allow use as a decorator + return typ + + +class NumbaPickler(cloudpickle.CloudPickler): + disabled_types = set() + """A set of types that pickling cannot is disabled. + """ + + def reducer_override(self, obj): + # Overridden to disable pickling of certain types + if type(obj) in self.disabled_types: + _no_pickle(obj) # noreturn + return super().reducer_override(obj) + + +def _custom_reduce__custompickled(cp): + return cp._reduce() + + +NumbaPickler.dispatch_table[_CustomPickled] = _custom_reduce__custompickled + + +class ReduceMixin(abc.ABC): + """A mixin class for objects that should be reduced by the NumbaPickler + instead of the standard pickler. + """ + # Subclass MUST override the below methods + + @abc.abstractmethod + def _reduce_states(self): + raise NotImplementedError + + @classmethod + @abc.abstractmethod + def _rebuild(cls, **kwargs): + raise NotImplementedError + + # Subclass can override the below methods + + def _reduce_class(self): + return self.__class__ + + # Private methods + + def __reduce__(self): + return custom_reduce(self._reduce_class(), self._reduce_states()) + + +class PickleCallableByPath: + """Wrap a callable object to be pickled by path to workaround limitation + in pickling due to non-pickleable objects in function non-locals. + + Note: + - Do not use this as a decorator. + - Wrapped object must be a global that exist in its parent module and it + can be imported by `from the_module import the_object`. + + Usage: + + >>> def my_fn(x): + >>> ... + >>> wrapped_fn = PickleCallableByPath(my_fn) + >>> # refer to `wrapped_fn` instead of `my_fn` + """ + def __init__(self, fn): + self._fn = fn + + def __call__(self, *args, **kwargs): + return self._fn(*args, **kwargs) + + def __reduce__(self): + return type(self)._rebuild, (self._fn.__module__, self._fn.__name__,) + + @classmethod + def _rebuild(cls, modname, fn_path): + return cls(getattr(sys.modules[modname], fn_path)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/sigutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/sigutils.py new file mode 100644 index 0000000000000000000000000000000000000000..aecdb8f6525e8d276a77591f0c2cc54af968051d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/sigutils.py @@ -0,0 +1,53 @@ +from numba.core import types, typing + + +def is_signature(sig): + """ + Return whether *sig* is a potentially valid signature + specification (for user-facing APIs). + """ + return isinstance(sig, (str, tuple, typing.Signature)) + + +def _parse_signature_string(signature_str): + """ + Parameters + ---------- + signature_str : str + """ + # Just eval signature_str using the types submodules as globals + return eval(signature_str, {}, types.__dict__) + + +def normalize_signature(sig): + """ + From *sig* (a signature specification), return a ``(args, return_type)`` + tuple, where ``args`` itself is a tuple of types, and ``return_type`` + can be None if not specified. + """ + if isinstance(sig, str): + parsed = _parse_signature_string(sig) + else: + parsed = sig + if isinstance(parsed, tuple): + args, return_type = parsed, None + elif isinstance(parsed, typing.Signature): + args, return_type = parsed.args, parsed.return_type + else: + raise TypeError("invalid signature: %r (type: %r) evaluates to %r " + "instead of tuple or Signature" % ( + sig, sig.__class__.__name__, + parsed.__class__.__name__ + )) + + def check_type(ty): + if not isinstance(ty, types.Type): + raise TypeError("invalid type in signature: expected a type " + "instance, got %r" % (ty,)) + + if return_type is not None: + check_type(return_type) + for ty in args: + check_type(ty) + + return args, return_type diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ssa.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ssa.py new file mode 100644 index 0000000000000000000000000000000000000000..7a44d3eb3016f90c07dfe55888a7787b1748e95e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/ssa.py @@ -0,0 +1,489 @@ +""" +Implement Dominance-Fronter-based SSA by Choi et al described in Inria SSA book + +References: + +- Static Single Assignment Book by Inria + http://ssabook.gforge.inria.fr/latest/book.pdf +- Choi et al. Incremental computation of static single assignment form. +""" +import logging +import operator +import warnings +from functools import reduce +from copy import copy +from collections import defaultdict + +from numba import config +from numba.core import ir, ir_utils, errors +from numba.core.utils import OrderedSet, _lazy_pformat +from numba.core.analysis import compute_cfg_from_blocks + + +_logger = logging.getLogger(__name__) + + +def reconstruct_ssa(func_ir): + """Apply SSA reconstruction algorithm on the given IR. + + Produces minimal SSA using Choi et al algorithm. + """ + func_ir.blocks = _run_ssa(func_ir.blocks) + + return func_ir + + +class _CacheListVars: + def __init__(self): + self._saved = {} + + def get(self, inst): + got = self._saved.get(inst) + if got is None: + self._saved[inst] = got = inst.list_vars() + return got + + +def _run_ssa(blocks): + """Run SSA reconstruction on IR blocks of a function. + """ + if not blocks: + # Empty blocks? + return {} + # Run CFG on the blocks + cfg = compute_cfg_from_blocks(blocks) + df_plus = _iterated_domfronts(cfg) + # Find SSA violators + violators = _find_defs_violators(blocks, cfg) + # Make cache for .list_vars() + cache_list_vars = _CacheListVars() + + # Process one SSA-violating variable at a time + for varname in violators: + _logger.debug( + "Fix SSA violator on var %s", varname, + ) + # Fix up the LHS + # Put fresh variables for all assignments to the variable + blocks, defmap = _fresh_vars(blocks, varname) + _logger.debug("Replaced assignments: %s", _lazy_pformat(defmap)) + # Fix up the RHS + # Re-associate the variable uses with the reaching definition + blocks = _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus, + cache_list_vars) + + # Post-condition checks. + # CFG invariant + cfg_post = compute_cfg_from_blocks(blocks) + if cfg_post != cfg: + raise errors.CompilerError("CFG mutated in SSA pass") + return blocks + + +def _fix_ssa_vars(blocks, varname, defmap, cfg, df_plus, cache_list_vars): + """Rewrite all uses to ``varname`` given the definition map + """ + states = _make_states(blocks) + states['varname'] = varname + states['defmap'] = defmap + states['phimap'] = phimap = defaultdict(list) + states['cfg'] = cfg + states['phi_locations'] = _compute_phi_locations(df_plus, defmap) + newblocks = _run_block_rewrite(blocks, states, _FixSSAVars(cache_list_vars)) + # insert phi nodes + for label, philist in phimap.items(): + curblk = newblocks[label] + # Prepend PHI nodes to the block + curblk.body = philist + curblk.body + return newblocks + + +def _iterated_domfronts(cfg): + """Compute the iterated dominance frontiers (DF+ in literatures). + + Returns a dictionary which maps block label to the set of labels of its + iterated dominance frontiers. + """ + domfronts = {k: set(vs) for k, vs in cfg.dominance_frontier().items()} + keep_going = True + while keep_going: + keep_going = False + for k, vs in domfronts.items(): + inner = reduce(operator.or_, [domfronts[v] for v in vs], set()) + if inner.difference(vs): + vs |= inner + keep_going = True + return domfronts + + +def _compute_phi_locations(iterated_df, defmap): + # See basic algorithm in Ch 4.1 in Inria SSA Book + # Compute DF+(defs) + # DF of all DFs is the union of all DFs + phi_locations = set() + for deflabel, defstmts in defmap.items(): + if defstmts: + phi_locations |= iterated_df[deflabel] + return phi_locations + + +def _fresh_vars(blocks, varname): + """Rewrite to put fresh variable names + """ + states = _make_states(blocks) + states['varname'] = varname + states['defmap'] = defmap = defaultdict(list) + newblocks = _run_block_rewrite(blocks, states, _FreshVarHandler()) + return newblocks, defmap + + +def _get_scope(blocks): + first, *_ = blocks.values() + return first.scope + + +def _find_defs_violators(blocks, cfg): + """ + Returns + ------- + res : Set[str] + The SSA violators in a dictionary of variable names. + """ + defs = defaultdict(list) + uses = defaultdict(set) + states = dict(defs=defs, uses=uses) + _run_block_analysis(blocks, states, _GatherDefsHandler()) + _logger.debug("defs %s", _lazy_pformat(defs)) + # Gather violators by number of definitions. + # The violators are added by the order that they are seen and the algorithm + # scan from the first to the last basic-block as they occur in bytecode. + violators = OrderedSet([k for k, vs in defs.items() if len(vs) > 1]) + # Gather violators by uses not dominated by the one def + doms = cfg.dominators() + for k, use_blocks in uses.items(): + if k not in violators: + for label in use_blocks: + dom = doms[label] + def_labels = {label for _assign, label in defs[k] } + if not def_labels.intersection(dom): + violators.add(k) + break + _logger.debug("SSA violators %s", _lazy_pformat(violators)) + return violators + + +def _run_block_analysis(blocks, states, handler): + for label, blk in blocks.items(): + _logger.debug("==== SSA block analysis pass on %s", label) + states['label'] = label + for _ in _run_ssa_block_pass(states, blk, handler): + pass + + +def _run_block_rewrite(blocks, states, handler): + newblocks = {} + for label, blk in blocks.items(): + _logger.debug("==== SSA block rewrite pass on %s", label) + newblk = ir.Block(scope=blk.scope, loc=blk.loc) + + newbody = [] + states['label'] = label + states['block'] = blk + for stmt in _run_ssa_block_pass(states, blk, handler): + assert stmt is not None + newbody.append(stmt) + newblk.body = newbody + newblocks[label] = newblk + return newblocks + + +def _make_states(blocks): + return dict( + scope=_get_scope(blocks), + ) + + +def _run_ssa_block_pass(states, blk, handler): + _logger.debug("Running %s", handler) + for stmt in blk.body: + _logger.debug("on stmt: %s", stmt) + if isinstance(stmt, ir.Assign): + ret = handler.on_assign(states, stmt) + else: + ret = handler.on_other(states, stmt) + if ret is not stmt and ret is not None: + _logger.debug("replaced with: %s", ret) + yield ret + + +class _BaseHandler: + """A base handler for all the passes used here for the SSA algorithm. + """ + def on_assign(self, states, assign): + """ + Called when the pass sees an ``ir.Assign``. + + Subclasses should override this for custom behavior + + Parameters + ----------- + states : dict + assign : numba.ir.Assign + + Returns + ------- + stmt : numba.ir.Assign or None + For rewrite passes, the return value is used as the replacement + for the given statement. + """ + + def on_other(self, states, stmt): + """ + Called when the pass sees an ``ir.Stmt`` that's not an assignment. + + Subclasses should override this for custom behavior + + Parameters + ----------- + states : dict + assign : numba.ir.Stmt + + Returns + ------- + stmt : numba.ir.Stmt or None + For rewrite passes, the return value is used as the replacement + for the given statement. + """ + + +class _GatherDefsHandler(_BaseHandler): + """Find all defs and uses of variable in each block + + ``states["label"]`` is a int; label of the current block + ``states["defs"]`` is a Mapping[str, List[Tuple[ir.Assign, int]]]: + - a mapping of the name of the assignee variable to the assignment + IR node and the block label. + ``states["uses"]`` is a Mapping[Set[int]] + """ + def on_assign(self, states, assign): + # keep track of assignment and the block + states["defs"][assign.target.name].append((assign, states["label"])) + # keep track of uses + for var in assign.list_vars(): + k = var.name + if k != assign.target.name: + states["uses"][k].add(states["label"]) + + def on_other(self, states, stmt): + # keep track of uses + for var in stmt.list_vars(): + k = var.name + states["uses"][k].add(states["label"]) + + +class UndefinedVariable: + def __init__(self): + raise NotImplementedError("Not intended for instantiation") + + target = ir.UNDEFINED + + +class _FreshVarHandler(_BaseHandler): + """Replaces assignment target with new fresh variables. + """ + def on_assign(self, states, assign): + if assign.target.name == states['varname']: + scope = states['scope'] + defmap = states['defmap'] + # Allow first assignment to retain the name + if len(defmap) == 0: + newtarget = assign.target + _logger.debug("first assign: %s", newtarget) + if newtarget.name not in scope.localvars: + wmsg = f"variable {newtarget.name!r} is not in scope." + warnings.warn(errors.NumbaIRAssumptionWarning(wmsg, + loc=assign.loc)) + else: + newtarget = scope.redefine(assign.target.name, loc=assign.loc) + assign = ir.Assign( + target=newtarget, + value=assign.value, + loc=assign.loc + ) + defmap[states['label']].append(assign) + return assign + + def on_other(self, states, stmt): + return stmt + + +class _FixSSAVars(_BaseHandler): + """Replace variable uses in IR nodes to the correct reaching variable + and introduce Phi nodes if necessary. This class contains the core of + the SSA reconstruction algorithm. + + See Ch 5 of the Inria SSA book for reference. The method names used here + are similar to the names used in the pseudocode in the book. + """ + + def __init__(self, cache_list_vars): + self._cache_list_vars = cache_list_vars + + def on_assign(self, states, assign): + rhs = assign.value + if isinstance(rhs, ir.Inst): + newdef = self._fix_var( + states, assign, self._cache_list_vars.get(assign.value), + ) + # Has a replacement that is not the current variable + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + replmap = {states['varname']: newdef.target} + rhs = copy(rhs) + + ir_utils.replace_vars_inner(rhs, replmap) + return ir.Assign( + target=assign.target, + value=rhs, + loc=assign.loc, + ) + elif isinstance(rhs, ir.Var): + newdef = self._fix_var(states, assign, [rhs]) + # Has a replacement that is not the current variable + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + return ir.Assign( + target=assign.target, + value=newdef.target, + loc=assign.loc, + ) + + return assign + + def on_other(self, states, stmt): + newdef = self._fix_var( + states, stmt, self._cache_list_vars.get(stmt), + ) + if newdef is not None and newdef.target is not ir.UNDEFINED: + if states['varname'] != newdef.target.name: + replmap = {states['varname']: newdef.target} + stmt = copy(stmt) + ir_utils.replace_vars_stmt(stmt, replmap) + return stmt + + def _fix_var(self, states, stmt, used_vars): + """Fix all variable uses in ``used_vars``. + """ + varnames = [k.name for k in used_vars] + phivar = states['varname'] + if phivar in varnames: + return self._find_def(states, stmt) + + def _find_def(self, states, stmt): + """Find definition of ``stmt`` for the statement ``stmt`` + """ + _logger.debug("find_def var=%r stmt=%s", states['varname'], stmt) + selected_def = None + label = states['label'] + local_defs = states['defmap'][label] + local_phis = states['phimap'][label] + block = states['block'] + + cur_pos = self._stmt_index(stmt, block) + for defstmt in reversed(local_defs): + # Phi nodes have no index + def_pos = self._stmt_index(defstmt, block, stop=cur_pos) + if def_pos < cur_pos: + selected_def = defstmt + break + # Maybe it's a PHI + elif defstmt in local_phis: + selected_def = local_phis[-1] + break + + if selected_def is None: + selected_def = self._find_def_from_top( + states, label, loc=stmt.loc, + ) + return selected_def + + def _find_def_from_top(self, states, label, loc): + """Find definition reaching block of ``label``. + + This method would look at all dominance frontiers. + Insert phi node if necessary. + """ + _logger.debug("find_def_from_top label %r", label) + cfg = states['cfg'] + defmap = states['defmap'] + phimap = states['phimap'] + phi_locations = states['phi_locations'] + + if label in phi_locations: + scope = states['scope'] + loc = states['block'].loc + # fresh variable + freshvar = scope.redefine(states['varname'], loc=loc) + # insert phi + phinode = ir.Assign( + target=freshvar, + value=ir.Expr.phi(loc=loc), + loc=loc, + ) + _logger.debug("insert phi node %s at %s", phinode, label) + defmap[label].insert(0, phinode) + phimap[label].append(phinode) + # Find incoming values for the Phi node + for pred, _ in cfg.predecessors(label): + incoming_def = self._find_def_from_bottom( + states, pred, loc=loc, + ) + _logger.debug("incoming_def %s", incoming_def) + phinode.value.incoming_values.append(incoming_def.target) + phinode.value.incoming_blocks.append(pred) + return phinode + else: + idom = cfg.immediate_dominators()[label] + if idom == label: + # We have searched to the top of the idom tree. + # Since we still cannot find a definition, + # we will warn. + _warn_about_uninitialized_variable(states['varname'], loc) + return UndefinedVariable + _logger.debug("idom %s from label %s", idom, label) + return self._find_def_from_bottom(states, idom, loc=loc) + + def _find_def_from_bottom(self, states, label, loc): + """Find definition from within the block at ``label``. + """ + _logger.debug("find_def_from_bottom label %r", label) + defmap = states['defmap'] + defs = defmap[label] + if defs: + lastdef = defs[-1] + return lastdef + else: + return self._find_def_from_top(states, label, loc=loc) + + def _stmt_index(self, defstmt, block, stop=-1): + """Find the positional index of the statement at ``block``. + + Assumptions: + - no two statements can point to the same object. + """ + # Compare using id() as IR node equality is for semantic equivalence + # opposed to direct equality (the location and scope are not considered + # as part of the equality measure, this is important here). + for i in range(len(block.body))[:stop]: + if block.body[i] is defstmt: + return i + return len(block.body) + + +def _warn_about_uninitialized_variable(varname, loc): + if config.ALWAYS_WARN_UNINIT_VAR: + warnings.warn( + errors.NumbaWarning( + f"Detected uninitialized variable {varname}", + loc=loc), + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/target_extension.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/target_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..91e5df09985b75f4971466efb07aa9c965decc1b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/target_extension.py @@ -0,0 +1,169 @@ +from abc import ABC, abstractmethod +from numba.core.registry import DelayedRegistry, CPUDispatcher +from numba.core.decorators import jit +from numba.core.errors import (InternalTargetMismatchError, + NonexistentTargetError) +from threading import local as tls + + +_active_context = tls() +_active_context_default = 'cpu' + + +class _TargetRegistry(DelayedRegistry): + + def __getitem__(self, item): + try: + return super().__getitem__(item) + except KeyError: + msg = "No target is registered against '{}', known targets:\n{}" + known = '\n'.join([f"{k: <{10}} -> {v}" + for k, v in target_registry.items()]) + raise NonexistentTargetError(msg.format(item, known)) from None + + +# Registry mapping target name strings to Target classes +target_registry = _TargetRegistry() + +# Registry mapping Target classes the @jit decorator for that target +jit_registry = DelayedRegistry() + + +class target_override(object): + """Context manager to temporarily override the current target with that + prescribed.""" + def __init__(self, name): + self._orig_target = getattr(_active_context, 'target', + _active_context_default) + self.target = name + + def __enter__(self): + _active_context.target = self.target + + def __exit__(self, ty, val, tb): + _active_context.target = self._orig_target + + +def current_target(): + """Returns the current target + """ + return getattr(_active_context, 'target', _active_context_default) + + +def get_local_target(context): + """ + Gets the local target from the call stack if available and the TLS + override if not. + """ + # TODO: Should this logic be reversed to prefer TLS override? + if len(context.callstack._stack) > 0: + target = context.callstack[0].target + else: + target = target_registry.get(current_target(), None) + if target is None: + msg = ("The target found is not registered." + "Given target was {}.") + raise ValueError(msg.format(target)) + else: + return target + + +def resolve_target_str(target_str): + """Resolves a target specified as a string to its Target class.""" + return target_registry[target_str] + + +def resolve_dispatcher_from_str(target_str): + """Returns the dispatcher associated with a target string""" + target_hw = resolve_target_str(target_str) + return dispatcher_registry[target_hw] + + +def _get_local_target_checked(tyctx, hwstr, reason): + """Returns the local target if it is compatible with the given target + name during a type resolution; otherwise, raises an exception. + + Parameters + ---------- + tyctx: typing context + hwstr: str + target name to check against + reason: str + Reason for the resolution. Expects a noun. + Returns + ------- + target_hw : Target + + Raises + ------ + InternalTargetMismatchError + """ + # Get the class for the target declared by the function + hw_clazz = resolve_target_str(hwstr) + # get the local target + target_hw = get_local_target(tyctx) + # make sure the target_hw is in the MRO for hw_clazz else bail + if not target_hw.inherits_from(hw_clazz): + raise InternalTargetMismatchError(reason, target_hw, hw_clazz) + return target_hw + + +class JitDecorator(ABC): + + @abstractmethod + def __call__(self): + return NotImplemented + + +class Target(ABC): + """ Implements a target """ + + @classmethod + def inherits_from(cls, other): + """Returns True if this target inherits from 'other' False otherwise""" + return issubclass(cls, other) + + +class Generic(Target): + """Mark the target as generic, i.e. suitable for compilation on + any target. All must inherit from this. + """ + + +class CPU(Generic): + """Mark the target as CPU. + """ + + +class GPU(Generic): + """Mark the target as GPU, i.e. suitable for compilation on a GPU + target. + """ + + +class CUDA(GPU): + """Mark the target as CUDA. + """ + + +class NPyUfunc(Target): + """Mark the target as a ufunc + """ + + +target_registry['generic'] = Generic +target_registry['CPU'] = CPU +target_registry['cpu'] = CPU +target_registry['GPU'] = GPU +target_registry['gpu'] = GPU +target_registry['CUDA'] = CUDA +target_registry['cuda'] = CUDA +target_registry['npyufunc'] = NPyUfunc + +dispatcher_registry = DelayedRegistry(key_type=Target) + + +# Register the cpu target token with its dispatcher and jit +cpu_target = target_registry['cpu'] +dispatcher_registry[cpu_target] = CPUDispatcher +jit_registry[cpu_target] = jit diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/targetconfig.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/targetconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe47f9864f8d5acdd34a98711baf01275c44c32 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/targetconfig.py @@ -0,0 +1,322 @@ +""" +This module contains utils for manipulating target configurations such as +compiler flags. +""" +import re +import zlib +import base64 + +from types import MappingProxyType +from numba.core import utils + + +class Option: + """An option to be used in ``TargetConfig``. + """ + __slots__ = "_type", "_default", "_doc" + + def __init__(self, type, *, default, doc): + """ + Parameters + ---------- + type : + Type of the option value. It can be a callable. + The setter always calls ``self._type(value)``. + default : + The default value for the option. + doc : str + Docstring for the option. + """ + self._type = type + self._default = default + self._doc = doc + + @property + def type(self): + return self._type + + @property + def default(self): + return self._default + + @property + def doc(self): + return self._doc + + +class _FlagsStack(utils.ThreadLocalStack, stack_name="flags"): + pass + + +class ConfigStack: + """A stack for tracking target configurations in the compiler. + + It stores the stack in a thread-local class attribute. All instances in the + same thread will see the same stack. + """ + @classmethod + def top_or_none(cls): + """Get the TOS or return None if no config is set. + """ + self = cls() + if self: + flags = self.top() + else: + # Note: should this be the default flag for the target instead? + flags = None + return flags + + def __init__(self): + self._stk = _FlagsStack() + + def top(self): + return self._stk.top() + + def __len__(self): + return len(self._stk) + + def enter(self, flags): + """Returns a contextmanager that performs ``push(flags)`` on enter and + ``pop()`` on exit. + """ + return self._stk.enter(flags) + + +class _MetaTargetConfig(type): + """Metaclass for ``TargetConfig``. + + When a subclass of ``TargetConfig`` is created, all ``Option`` defined + as class members will be parsed and corresponding getters, setters, and + delters will be inserted. + """ + def __init__(cls, name, bases, dct): + """Invoked when subclass is created. + + Insert properties for each ``Option`` that are class members. + All the options will be grouped inside the ``.options`` class + attribute. + """ + # Gather options from base classes and class dict + opts = {} + # Reversed scan into the base classes to follow MRO ordering such that + # the closest base class is overriding + for base_cls in reversed(bases): + opts.update(base_cls.options) + opts.update(cls.find_options(dct)) + # Store the options into class attribute as a ready-only mapping. + cls.options = MappingProxyType(opts) + + # Make properties for each of the options + def make_prop(name, option): + def getter(self): + return self._values.get(name, option.default) + + def setter(self, val): + self._values[name] = option.type(val) + + def delter(self): + del self._values[name] + + return property(getter, setter, delter, option.doc) + + for name, option in cls.options.items(): + setattr(cls, name, make_prop(name, option)) + + def find_options(cls, dct): + """Returns a new dict with all the items that are a mapping to an + ``Option``. + """ + return {k: v for k, v in dct.items() if isinstance(v, Option)} + + +class _NotSetType: + def __repr__(self): + return "" + + +_NotSet = _NotSetType() + + +class TargetConfig(metaclass=_MetaTargetConfig): + """Base class for ``TargetConfig``. + + Subclass should fill class members with ``Option``. For example: + + >>> class MyTargetConfig(TargetConfig): + >>> a_bool_option = Option(type=bool, default=False, doc="a bool") + >>> an_int_option = Option(type=int, default=0, doc="an int") + + The metaclass will insert properties for each ``Option``. For example: + + >>> tc = MyTargetConfig() + >>> tc.a_bool_option = True # invokes the setter + >>> print(tc.an_int_option) # print the default + """ + __slots__ = ["_values"] + + # Used for compression in mangling. + # Set to -15 to disable the header and checksum for smallest output. + _ZLIB_CONFIG = {"wbits": -15} + + def __init__(self, copy_from=None): + """ + Parameters + ---------- + copy_from : TargetConfig or None + if None, creates an empty ``TargetConfig``. + Otherwise, creates a copy. + """ + self._values = {} + if copy_from is not None: + assert isinstance(copy_from, TargetConfig) + self._values.update(copy_from._values) + + def __repr__(self): + # NOTE: default options will be placed at the end and grouped inside + # a square bracket; i.e. [optname=optval, ...] + args = [] + defs = [] + for k in self.options: + msg = f"{k}={getattr(self, k)}" + if not self.is_set(k): + defs.append(msg) + else: + args.append(msg) + clsname = self.__class__.__name__ + return f"{clsname}({', '.join(args)}, [{', '.join(defs)}])" + + def __hash__(self): + return hash(tuple(sorted(self.values()))) + + def __eq__(self, other): + if isinstance(other, TargetConfig): + return self.values() == other.values() + else: + return NotImplemented + + def values(self): + """Returns a dict of all the values + """ + return {k: getattr(self, k) for k in self.options} + + def is_set(self, name): + """Is the option set? + """ + self._guard_option(name) + return name in self._values + + def discard(self, name): + """Remove the option by name if it is defined. + + After this, the value for the option will be set to its default value. + """ + self._guard_option(name) + self._values.pop(name, None) + + def inherit_if_not_set(self, name, default=_NotSet): + """Inherit flag from ``ConfigStack``. + + Parameters + ---------- + name : str + Option name. + default : optional + When given, it overrides the default value. + It is only used when the flag is not defined locally and there is + no entry in the ``ConfigStack``. + """ + self._guard_option(name) + if not self.is_set(name): + cstk = ConfigStack() + if cstk: + # inherit + top = cstk.top() + setattr(self, name, getattr(top, name)) + elif default is not _NotSet: + setattr(self, name, default) + + def copy(self): + """Clone this instance. + """ + return type(self)(self) + + def summary(self) -> str: + """Returns a ``str`` that summarizes this instance. + + In contrast to ``__repr__``, only options that are explicitly set will + be shown. + """ + args = [f"{k}={v}" for k, v in self._summary_args()] + clsname = self.__class__.__name__ + return f"{clsname}({', '.join(args)})" + + def _guard_option(self, name): + if name not in self.options: + msg = f"{name!r} is not a valid option for {type(self)}" + raise ValueError(msg) + + def _summary_args(self): + """returns a sorted sequence of 2-tuple containing the + ``(flag_name, flag_value)`` for flag that are set with a non-default + value. + """ + args = [] + for k in sorted(self.options): + opt = self.options[k] + if self.is_set(k): + flagval = getattr(self, k) + if opt.default != flagval: + v = (k, flagval) + args.append(v) + return args + + @classmethod + def _make_compression_dictionary(cls) -> bytes: + """Returns a ``bytes`` object suitable for use as a dictionary for + compression. + """ + buf = [] + # include package name + buf.append("numba") + # include class name + buf.append(cls.__class__.__name__) + # include common values + buf.extend(["True", "False"]) + # include all options name and their default value + for k, opt in cls.options.items(): + buf.append(k) + buf.append(str(opt.default)) + return ''.join(buf).encode() + + def get_mangle_string(self) -> str: + """Return a string suitable for symbol mangling. + """ + zdict = self._make_compression_dictionary() + + comp = zlib.compressobj(zdict=zdict, level=zlib.Z_BEST_COMPRESSION, + **self._ZLIB_CONFIG) + # The mangled string is a compressed and base64 encoded version of the + # summary + buf = [comp.compress(self.summary().encode())] + buf.append(comp.flush()) + return base64.b64encode(b''.join(buf)).decode() + + @classmethod + def demangle(cls, mangled: str) -> str: + """Returns the demangled result from ``.get_mangle_string()`` + """ + # unescape _XX sequence + def repl(x): + return chr(int('0x' + x.group(0)[1:], 16)) + unescaped = re.sub(r"_[a-zA-Z0-9][a-zA-Z0-9]", repl, mangled) + # decode base64 + raw = base64.b64decode(unescaped) + # decompress + zdict = cls._make_compression_dictionary() + dc = zlib.decompressobj(zdict=zdict, **cls._ZLIB_CONFIG) + buf = [] + while raw: + buf.append(dc.decompress(raw)) + raw = dc.unconsumed_tail + buf.append(dc.flush()) + return b''.join(buf).decode() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/tracing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..a35b61b1ff851c3bf8438d92a415cb3bdc811077 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/tracing.py @@ -0,0 +1,228 @@ +import inspect +import logging +import sys +import threading +from functools import wraps +from itertools import chain + +from numba.core import config + + +class TLS(threading.local): + """Use a subclass to properly initialize the TLS variables in all threads.""" # noqa: E501 + + def __init__(self): + self.tracing = False + self.indent = 0 + + +tls = TLS() + + +def find_function_info(func, spec, args): + """Return function meta-data in a tuple. + + (name, type)""" + + module = getattr(func, "__module__", None) + name = getattr(func, "__name__", None) + self = getattr(func, "__self__", None) + cname = None + if self: + cname = self.__name__ + # cname = self.__class__.__name__ + # Try to deduce the class' name even for unbound methods from their + # first argument, which we assume to be a class instance if named 'self'... + elif len(spec.args) and spec.args[0] == "self": + cname = args[0].__class__.__name__ + # ...or a class object if named 'cls' + elif len(spec.args) and spec.args[0] == "cls": + cname = args[0].__name__ + if name: + qname = [] + if module and module != "__main__": + qname.append(module) + qname.append(".") + if cname: + qname.append(cname) + qname.append(".") + qname.append(name) + name = "".join(qname) + return name, None + + +def chop(value): + MAX_SIZE = 320 + s = repr(value) + if len(s) > MAX_SIZE: + return s[:MAX_SIZE] + "..." + s[-1] + else: + return s + + +def create_events(fname, spec, args, kwds): + values = dict() + if spec.defaults: + values = dict(zip(spec.args[-len(spec.defaults) :], spec.defaults)) + values.update(kwds) + values.update(list(zip(spec.args[: len(args)], args))) + positional = ["%s=%r" % (a, values.pop(a)) for a in spec.args] + anonymous = [str(a) for a in args[len(positional) :]] + keywords = ["%s=%r" % (k, values[k]) for k in sorted(values.keys())] + params = ", ".join([f for f in chain(positional, anonymous, keywords) if f]) + + enter = [">> ", tls.indent * " ", fname, "(", params, ")"] + leave = ["<< ", tls.indent * " ", fname] + return enter, leave + + +def dotrace(*args, **kwds): + """Function decorator to trace a function's entry and exit. + + *args: categories in which to trace this function. Example usage: + + @trace + def function(...):... + + @trace('mycategory') + def function(...):... + + + """ + + recursive = kwds.get("recursive", False) + + def decorator(func): + spec = None + logger = logging.getLogger("trace") + + def wrapper(*args, **kwds): + if not logger.isEnabledFor(logging.INFO) or tls.tracing: + return func(*args, **kwds) + + fname, ftype = find_function_info(func, spec, args) + + try: + tls.tracing = True + enter, leave = create_events(fname, spec, args, kwds) + + try: + logger.info("".join(enter)) + tls.indent += 1 + try: + try: + tls.tracing = False + result = func(*args, **kwds) + finally: + tls.tracing = True + except: # noqa: E722 + type, value, traceback = sys.exc_info() + leave.append(" => exception thrown\n\traise ") + mname = type.__module__ + if mname != "__main__": + leave.append(mname) + leave.append(".") + leave.append(type.__name__) + if value.args: + leave.append("(") + leave.append(", ".join(chop(v) for v in value.args)) + leave.append(")") + else: + leave.append("()") + raise + else: + if result is not None: + leave.append(" -> ") + leave.append(chop(result)) + finally: + tls.indent -= 1 + logger.info("".join(leave)) + finally: + tls.tracing = False + return result + + # wrapper end + + rewrap = lambda x: x + # Unwrap already wrapped functions + # (to be rewrapped again later) + if isinstance(func, classmethod): + rewrap = type(func) + # Note: 'func.__func__' only works in Python 3 + func = func.__get__(True).__func__ + elif isinstance(func, staticmethod): + rewrap = type(func) + # Note: 'func.__func__' only works in Python 3 + func = func.__get__(True) + elif isinstance(func, property): + raise NotImplementedError + + spec = inspect.getfullargspec(func) + return rewrap(wraps(func)(wrapper)) + + arg0 = len(args) and args[0] or None + # not supported yet... + if recursive: + raise NotImplementedError + if inspect.ismodule(arg0): + for n, f in inspect.getmembers(arg0, inspect.isfunction): + setattr(arg0, n, decorator(f)) + for n, c in inspect.getmembers(arg0, inspect.isclass): + dotrace(c, *args, recursive=recursive) + elif inspect.isclass(arg0): + for n, f in inspect.getmembers( + arg0, lambda x: (inspect.isfunction(x) or inspect.ismethod(x)) + ): + setattr(arg0, n, decorator(f)) + + if callable(arg0) or type(arg0) in (classmethod, staticmethod): + return decorator(arg0) + elif isinstance(arg0, property): + # properties combine up to three functions: 'get', 'set', 'del', + # so let's wrap them all. + pget, pset, pdel = None, None, None + if arg0.fget: + pget = decorator(arg0.fget) + if arg0.fset: + pset = decorator(arg0.fset) + if arg0.fdel: + pdel = decorator(arg0.fdel) + return property(pget, pset, pdel) + + else: + return decorator + + +def notrace(*args, **kwds): + """Just a no-op in case tracing is disabled.""" + + def decorator(func): + return func + + arg0 = len(args) and args[0] or None + + if callable(arg0) or type(arg0) in (classmethod, staticmethod): + return decorator(arg0) + else: + return decorator + + +def doevent(msg): + msg = ["== ", tls.indent * " ", msg] + logger = logging.getLogger("trace") + logger.info("".join(msg)) + + +def noevent(msg): + pass + + +if config.TRACE: + logger = logging.getLogger("trace") + logger.setLevel(logging.INFO) + logger.handlers = [logging.StreamHandler()] + trace = dotrace + event = doevent +else: + trace = notrace + event = noevent diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/transforms.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..7d25f8481af657f920d23c731894c2689d2f1c54 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/transforms.py @@ -0,0 +1,914 @@ +""" +Implement transformation on Numba IR +""" + + +from collections import namedtuple, defaultdict +import logging +import operator + +from numba.core.analysis import compute_cfg_from_blocks, find_top_level_loops +from numba.core import errors, ir, ir_utils +from numba.core.analysis import compute_use_defs, compute_cfg_from_blocks +from numba.core.utils import PYVERSION, _lazy_pformat + + +_logger = logging.getLogger(__name__) + + +def _extract_loop_lifting_candidates(cfg, blocks): + """ + Returns a list of loops that are candidate for loop lifting + """ + # check well-formed-ness of the loop + def same_exit_point(loop): + "all exits must point to the same location" + outedges = set() + for k in loop.exits: + succs = set(x for x, _ in cfg.successors(k)) + if not succs: + # If the exit point has no successor, it contains an return + # statement, which is not handled by the looplifting code. + # Thus, this loop is not a candidate. + _logger.debug("return-statement in loop.") + return False + outedges |= succs + ok = len(outedges) == 1 + _logger.debug("same_exit_point=%s (%s)", ok, outedges) + return ok + + def one_entry(loop): + "there is one entry" + ok = len(loop.entries) == 1 + _logger.debug("one_entry=%s", ok) + return ok + + def cannot_yield(loop): + "cannot have yield inside the loop" + insiders = set(loop.body) | set(loop.entries) | set(loop.exits) + for blk in map(blocks.__getitem__, insiders): + for inst in blk.body: + if isinstance(inst, ir.Assign): + if isinstance(inst.value, ir.Yield): + _logger.debug("has yield") + return False + _logger.debug("no yield") + return True + + _logger.info('finding looplift candidates') + # the check for cfg.entry_point in the loop.entries is to prevent a bad + # rewrite where a prelude for a lifted loop would get written into block -1 + # if a loop entry were in block 0 + candidates = [] + for loop in find_top_level_loops(cfg): + _logger.debug("top-level loop: %s", loop) + if (same_exit_point(loop) and one_entry(loop) and cannot_yield(loop) and + cfg.entry_point() not in loop.entries): + candidates.append(loop) + _logger.debug("add candidate: %s", loop) + return candidates + + +def find_region_inout_vars(blocks, livemap, callfrom, returnto, body_block_ids): + """Find input and output variables to a block region. + """ + inputs = livemap[callfrom] + outputs = livemap[returnto] + + # ensure live variables are actually used in the blocks, else remove, + # saves having to create something valid to run through postproc + # to achieve similar + loopblocks = {} + for k in body_block_ids: + loopblocks[k] = blocks[k] + + used_vars = set() + def_vars = set() + defs = compute_use_defs(loopblocks) + for vs in defs.usemap.values(): + used_vars |= vs + for vs in defs.defmap.values(): + def_vars |= vs + used_or_defined = used_vars | def_vars + + # note: sorted for stable ordering + inputs = sorted(set(inputs) & used_or_defined) + outputs = sorted(set(outputs) & used_or_defined & def_vars) + return inputs, outputs + + +_loop_lift_info = namedtuple('loop_lift_info', + 'loop,inputs,outputs,callfrom,returnto') + + +def _loop_lift_get_candidate_infos(cfg, blocks, livemap): + """ + Returns information on looplifting candidates. + """ + loops = _extract_loop_lifting_candidates(cfg, blocks) + loopinfos = [] + for loop in loops: + + [callfrom] = loop.entries # requirement checked earlier + an_exit = next(iter(loop.exits)) # anyone of the exit block + if len(loop.exits) > 1: + # has multiple exits + [(returnto, _)] = cfg.successors(an_exit) # requirement checked earlier + else: + # does not have multiple exits + returnto = an_exit + + local_block_ids = set(loop.body) | set(loop.entries) | set(loop.exits) + inputs, outputs = find_region_inout_vars( + blocks=blocks, + livemap=livemap, + callfrom=callfrom, + returnto=returnto, + body_block_ids=local_block_ids, + ) + + lli = _loop_lift_info(loop=loop, inputs=inputs, outputs=outputs, + callfrom=callfrom, returnto=returnto) + loopinfos.append(lli) + + return loopinfos + + +def _loop_lift_modify_call_block(liftedloop, block, inputs, outputs, returnto): + """ + Transform calling block from top-level function to call the lifted loop. + """ + scope = block.scope + loc = block.loc + blk = ir.Block(scope=scope, loc=loc) + + ir_utils.fill_block_with_call( + newblock=blk, + callee=liftedloop, + label_next=returnto, + inputs=inputs, + outputs=outputs, + ) + return blk + + +def _loop_lift_prepare_loop_func(loopinfo, blocks): + """ + Inplace transform loop blocks for use as lifted loop. + """ + entry_block = blocks[loopinfo.callfrom] + scope = entry_block.scope + loc = entry_block.loc + + # Lowering assumes the first block to be the one with the smallest offset + firstblk = min(blocks) - 1 + blocks[firstblk] = ir_utils.fill_callee_prologue( + block=ir.Block(scope=scope, loc=loc), + inputs=loopinfo.inputs, + label_next=loopinfo.callfrom, + ) + blocks[loopinfo.returnto] = ir_utils.fill_callee_epilogue( + block=ir.Block(scope=scope, loc=loc), + outputs=loopinfo.outputs, + ) + + +def _loop_lift_modify_blocks(func_ir, loopinfo, blocks, + typingctx, targetctx, flags, locals): + """ + Modify the block inplace to call to the lifted-loop. + Returns a dictionary of blocks of the lifted-loop. + """ + from numba.core.dispatcher import LiftedLoop + + # Copy loop blocks + loop = loopinfo.loop + + loopblockkeys = set(loop.body) | set(loop.entries) + if len(loop.exits) > 1: + # has multiple exits + loopblockkeys |= loop.exits + loopblocks = dict((k, blocks[k].copy()) for k in loopblockkeys) + # Modify the loop blocks + _loop_lift_prepare_loop_func(loopinfo, loopblocks) + # Since Python 3.13, [END_FOR, POP_TOP] sequence becomes the start of the + # block causing the block to have line number of the start of previous loop. + # Fix this using the loc of the first getiter. + getiter_exprs = [] + for blk in loopblocks.values(): + getiter_exprs.extend(blk.find_exprs(op="getiter")) + first_getiter = min(getiter_exprs, key=lambda x: x.loc.line) + loop_loc = first_getiter.loc + # Create a new IR for the lifted loop + lifted_ir = func_ir.derive(blocks=loopblocks, + arg_names=tuple(loopinfo.inputs), + arg_count=len(loopinfo.inputs), + force_non_generator=True, + loc=loop_loc) + liftedloop = LiftedLoop(lifted_ir, + typingctx, targetctx, flags, locals) + + # modify for calling into liftedloop + callblock = _loop_lift_modify_call_block(liftedloop, blocks[loopinfo.callfrom], + loopinfo.inputs, loopinfo.outputs, + loopinfo.returnto) + # remove blocks + for k in loopblockkeys: + del blocks[k] + # update main interpreter callsite into the liftedloop + blocks[loopinfo.callfrom] = callblock + return liftedloop + + +def _has_multiple_loop_exits(cfg, lpinfo): + """Returns True if there is more than one exit in the loop. + + NOTE: "common exits" refers to the situation where a loop exit has another + loop exit as its successor. In that case, we do not need to alter it. + """ + if len(lpinfo.exits) <= 1: + return False + exits = set(lpinfo.exits) + pdom = cfg.post_dominators() + + # Eliminate blocks that have other blocks as post-dominators. + processed = set() + remain = set(exits) # create a copy to work on + while remain: + node = remain.pop() + processed.add(node) + exits -= pdom[node] - {node} + remain = exits - processed + + return len(exits) > 1 + + +def _pre_looplift_transform(func_ir): + """Canonicalize loops for looplifting. + """ + from numba.core.postproc import PostProcessor + + cfg = compute_cfg_from_blocks(func_ir.blocks) + # For every loop that has multiple exits, combine the exits into one. + for loop_info in cfg.loops().values(): + if _has_multiple_loop_exits(cfg, loop_info): + func_ir, _common_key = _fix_multi_exit_blocks( + func_ir, loop_info.exits + ) + # Reset and reprocess the func_ir + func_ir._reset_analysis_variables() + PostProcessor(func_ir).run() + return func_ir + + +def loop_lifting(func_ir, typingctx, targetctx, flags, locals): + """ + Loop lifting transformation. + + Given a interpreter `func_ir` returns a 2 tuple of + `(toplevel_interp, [loop0_interp, loop1_interp, ....])` + """ + func_ir = _pre_looplift_transform(func_ir) + blocks = func_ir.blocks.copy() + cfg = compute_cfg_from_blocks(blocks) + loopinfos = _loop_lift_get_candidate_infos(cfg, blocks, + func_ir.variable_lifetime.livemap) + loops = [] + if loopinfos: + _logger.debug('loop lifting this IR with %d candidates:\n%s', + len(loopinfos), + _lazy_pformat(func_ir, lazy_func=lambda x: x.dump_to_string())) + for loopinfo in loopinfos: + lifted = _loop_lift_modify_blocks(func_ir, loopinfo, blocks, + typingctx, targetctx, flags, locals) + loops.append(lifted) + + # Make main IR + main = func_ir.derive(blocks=blocks) + + return main, loops + + +def canonicalize_cfg_single_backedge(blocks): + """ + Rewrite loops that have multiple backedges. + """ + cfg = compute_cfg_from_blocks(blocks) + newblocks = blocks.copy() + + def new_block_id(): + return max(newblocks.keys()) + 1 + + def has_multiple_backedges(loop): + count = 0 + for k in loop.body: + blk = blocks[k] + edges = blk.terminator.get_targets() + # is a backedge? + if loop.header in edges: + count += 1 + if count > 1: + # early exit + return True + return False + + def yield_loops_with_multiple_backedges(): + for lp in cfg.loops().values(): + if has_multiple_backedges(lp): + yield lp + + def replace_target(term, src, dst): + def replace(target): + return (dst if target == src else target) + + if isinstance(term, ir.Branch): + return ir.Branch(cond=term.cond, + truebr=replace(term.truebr), + falsebr=replace(term.falsebr), + loc=term.loc) + elif isinstance(term, ir.Jump): + return ir.Jump(target=replace(term.target), loc=term.loc) + else: + assert not term.get_targets() + return term + + def rewrite_single_backedge(loop): + """ + Add new tail block that gathers all the backedges + """ + header = loop.header + tailkey = new_block_id() + for blkkey in loop.body: + blk = newblocks[blkkey] + if header in blk.terminator.get_targets(): + newblk = blk.copy() + # rewrite backedge into jumps to new tail block + newblk.body[-1] = replace_target(blk.terminator, header, + tailkey) + newblocks[blkkey] = newblk + # create new tail block + entryblk = newblocks[header] + tailblk = ir.Block(scope=entryblk.scope, loc=entryblk.loc) + # add backedge + tailblk.append(ir.Jump(target=header, loc=tailblk.loc)) + newblocks[tailkey] = tailblk + + for loop in yield_loops_with_multiple_backedges(): + rewrite_single_backedge(loop) + + return newblocks + + +def canonicalize_cfg(blocks): + """ + Rewrite the given blocks to canonicalize the CFG. + Returns a new dictionary of blocks. + """ + return canonicalize_cfg_single_backedge(blocks) + + +def with_lifting(func_ir, typingctx, targetctx, flags, locals): + """With-lifting transformation + + Rewrite the IR to extract all withs. + Only the top-level withs are extracted. + Returns the (the_new_ir, the_lifted_with_ir) + """ + from numba.core import postproc + + def dispatcher_factory(func_ir, objectmode=False, **kwargs): + from numba.core.dispatcher import LiftedWith, ObjModeLiftedWith + + myflags = flags.copy() + if objectmode: + # Lifted with-block cannot looplift + myflags.enable_looplift = False + # Lifted with-block uses object mode + myflags.enable_pyobject = True + myflags.force_pyobject = True + myflags.no_cpython_wrapper = False + cls = ObjModeLiftedWith + else: + cls = LiftedWith + return cls(func_ir, typingctx, targetctx, myflags, locals, **kwargs) + + # find where with-contexts regions are + withs, func_ir = find_setupwiths(func_ir) + + if not withs: + return func_ir, [] + + postproc.PostProcessor(func_ir).run() # ensure we have variable lifetime + assert func_ir.variable_lifetime + vlt = func_ir.variable_lifetime + blocks = func_ir.blocks.copy() + cfg = vlt.cfg + # For each with-regions, mutate them according to + # the kind of contextmanager + sub_irs = [] + for (blk_start, blk_end) in withs: + body_blocks = [] + for node in _cfg_nodes_in_region(cfg, blk_start, blk_end): + body_blocks.append(node) + _legalize_with_head(blocks[blk_start]) + # Find the contextmanager + cmkind, extra = _get_with_contextmanager(func_ir, blocks, blk_start) + # Mutate the body and get new IR + sub = cmkind.mutate_with_body(func_ir, blocks, blk_start, blk_end, + body_blocks, dispatcher_factory, + extra) + sub_irs.append(sub) + if not sub_irs: + # Unchanged + new_ir = func_ir + else: + new_ir = func_ir.derive(blocks) + return new_ir, sub_irs + + +def _get_with_contextmanager(func_ir, blocks, blk_start): + """Get the global object used for the context manager + """ + _illegal_cm_msg = "Illegal use of context-manager." + + def get_var_dfn(var): + """Get the definition given a variable""" + return func_ir.get_definition(var) + + def get_ctxmgr_obj(var_ref): + """Return the context-manager object and extra info. + + The extra contains the arguments if the context-manager is used + as a call. + """ + # If the contextmanager used as a Call + dfn = func_ir.get_definition(var_ref) + if isinstance(dfn, ir.Expr) and dfn.op == 'call': + args = [get_var_dfn(x) for x in dfn.args] + kws = {k: get_var_dfn(v) for k, v in dfn.kws} + extra = {'args': args, 'kwargs': kws} + var_ref = dfn.func + else: + extra = None + + ctxobj = ir_utils.guard(ir_utils.find_outer_value, func_ir, var_ref) + + # check the contextmanager object + if ctxobj is ir.UNDEFINED: + raise errors.CompilerError( + "Undefined variable used as context manager", + loc=blocks[blk_start].loc, + ) + + if ctxobj is None: + raise errors.CompilerError(_illegal_cm_msg, loc=dfn.loc) + + return ctxobj, extra + + # Scan the start of the with-region for the contextmanager + for stmt in blocks[blk_start].body: + if isinstance(stmt, ir.EnterWith): + var_ref = stmt.contextmanager + ctxobj, extra = get_ctxmgr_obj(var_ref) + if not hasattr(ctxobj, 'mutate_with_body'): + raise errors.CompilerError( + "Unsupported context manager in use", + loc=blocks[blk_start].loc, + ) + return ctxobj, extra + # No contextmanager found? + raise errors.CompilerError( + "malformed with-context usage", + loc=blocks[blk_start].loc, + ) + + +def _legalize_with_head(blk): + """Given *blk*, the head block of the with-context, check that it doesn't + do anything else. + """ + counters = defaultdict(int) + for stmt in blk.body: + counters[type(stmt)] += 1 + if counters.pop(ir.EnterWith) != 1: + raise errors.CompilerError( + "with's head-block must have exactly 1 ENTER_WITH", + loc=blk.loc, + ) + if counters.pop(ir.Jump, 0) != 1: + raise errors.CompilerError( + "with's head-block must have exactly 1 JUMP", + loc=blk.loc, + ) + # Can have any number of del + counters.pop(ir.Del, None) + # There MUST NOT be any other statements + if counters: + raise errors.CompilerError( + "illegal statements in with's head-block", + loc=blk.loc, + ) + + +def _cfg_nodes_in_region(cfg, region_begin, region_end): + """Find the set of CFG nodes that are in the given region + """ + region_nodes = set() + stack = [region_begin] + while stack: + tos = stack.pop() + succlist = list(cfg.successors(tos)) + # a single block function will have a empty successor list + if succlist: + succs, _ = zip(*succlist) + nodes = set([node for node in succs + if node not in region_nodes and + node != region_end]) + stack.extend(nodes) + region_nodes |= nodes + + return region_nodes + + +def find_setupwiths(func_ir): + """Find all top-level with. + + Returns a list of ranges for the with-regions. + """ + def find_ranges(blocks): + + cfg = compute_cfg_from_blocks(blocks) + sus_setups, sus_pops = set(), set() + # traverse the cfg and collect all suspected SETUP_WITH and POP_BLOCK + # statements so that we can iterate over them + for label, block in blocks.items(): + for stmt in block.body: + if ir_utils.is_setup_with(stmt): + sus_setups.add(label) + if ir_utils.is_pop_block(stmt): + sus_pops.add(label) + + # now that we do have the statements, iterate through them in reverse + # topo order and from each start looking for pop_blocks + setup_with_to_pop_blocks_map = defaultdict(set) + for setup_block in cfg.topo_sort(sus_setups, reverse=True): + # begin pop_block, search + to_visit, seen = [], [] + to_visit.append(setup_block) + while to_visit: + # get whatever is next and record that we have seen it + block = to_visit.pop() + seen.append(block) + # go through the body of the block, looking for statements + for stmt in blocks[block].body: + # raise detected before pop_block + if ir_utils.is_raise(stmt): + raise errors.CompilerError( + 'unsupported control flow due to raise ' + 'statements inside with block' + ) + # if a pop_block, process it + if ir_utils.is_pop_block(stmt) and block in sus_pops: + # record the jump target of this block belonging to this setup + setup_with_to_pop_blocks_map[setup_block].add(block) + # remove the block from blocks to be matched + sus_pops.remove(block) + # stop looking, we have reached the frontier + break + # if we are still here, by the block terminator, + # add all its targets to the to_visit stack, unless we + # have seen them already + if ir_utils.is_terminator(stmt): + for t in stmt.get_targets(): + if t not in seen: + to_visit.append(t) + + return setup_with_to_pop_blocks_map + + blocks = func_ir.blocks + # initial find, will return a dictionary, mapping indices of blocks + # containing SETUP_WITH statements to a set of indices of blocks containing + # POP_BLOCK statements + with_ranges_dict = find_ranges(blocks) + # rewrite the CFG in case there are multiple POP_BLOCK statements for one + # with + func_ir = consolidate_multi_exit_withs(with_ranges_dict, blocks, func_ir) + # here we need to turn the withs back into a list of tuples so that the + # rest of the code can cope + with_ranges_tuple = [(s, list(p)[0]) + for (s, p) in with_ranges_dict.items()] + + # check for POP_BLOCKS with multiple outgoing edges and reject + for (_, p) in with_ranges_tuple: + targets = blocks[p].terminator.get_targets() + if len(targets) != 1: + raise errors.CompilerError( + "unsupported control flow: with-context contains branches " + "(i.e. break/return/raise) that can leave the block " + ) + # now we check for returns inside with and reject them + for (_, p) in with_ranges_tuple: + target_block = blocks[p] + if ir_utils.is_return(func_ir.blocks[ + target_block.terminator.get_targets()[0]].terminator): + _rewrite_return(func_ir, p) + + # now we need to rewrite the tuple such that we have SETUP_WITH matching the + # successor of the block that contains the POP_BLOCK. + with_ranges_tuple = [(s, func_ir.blocks[p].terminator.get_targets()[0]) + for (s, p) in with_ranges_tuple] + + # finally we check for nested with statements and reject them + with_ranges_tuple = _eliminate_nested_withs(with_ranges_tuple) + + return with_ranges_tuple, func_ir + + +def _rewrite_return(func_ir, target_block_label): + """Rewrite a return block inside a with statement. + + Arguments + --------- + + func_ir: Function IR + the CFG to transform + target_block_label: int + the block index/label of the block containing the POP_BLOCK statement + + + This implements a CFG transformation to insert a block between two other + blocks. + + The input situation is: + + ┌───────────────┐ + │ top │ + │ POP_BLOCK │ + │ bottom │ + └───────┬───────┘ + │ + ┌───────▌───────┐ + │ │ + │ RETURN │ + │ │ + └───────────────┘ + + If such a pattern is detected in IR, it means there is a `return` statement + within a `with` context. The basic idea is to rewrite the CFG as follows: + + ┌───────────────┐ + │ top │ + │ POP_BLOCK │ + │ │ + └───────┬───────┘ + │ + ┌───────▌───────┐ + │ │ + │ bottom │ + │ │ + └───────┬───────┘ + │ + ┌───────▌───────┐ + │ │ + │ RETURN │ + │ │ + └───────────────┘ + + We split the block that contains the `POP_BLOCK` statement into two blocks. + Everything from the beginning of the block up to and including the + `POP_BLOCK` statement is considered the 'top' and everything below is + considered 'bottom'. Finally the jump statements are re-wired to make sure + the CFG remains valid. + + """ + # the block itself from the index + target_block = func_ir.blocks[target_block_label] + # get the index of the block containing the return + target_block_successor_label = target_block.terminator.get_targets()[0] + # the return block + target_block_successor = func_ir.blocks[target_block_successor_label] + + # create the new return block with an appropriate label + max_label = ir_utils.find_max_label(func_ir.blocks) + new_label = max_label + 1 + # create the new return block + new_block_loc = target_block_successor.loc + new_block_scope = ir.Scope(None, loc=new_block_loc) + new_block = ir.Block(new_block_scope, loc=new_block_loc) + + # Split the block containing the POP_BLOCK into top and bottom + # Block must be of the form: + # ----------------- + # + # POP_BLOCK + # + # JUMP + # ----------------- + top_body, bottom_body = [], [] + pop_blocks = [*target_block.find_insts(ir.PopBlock)] + assert len(pop_blocks) == 1 + assert len([*target_block.find_insts(ir.Jump)]) == 1 + assert isinstance(target_block.body[-1], ir.Jump) + pb_marker = pop_blocks[0] + pb_is = target_block.body.index(pb_marker) + top_body.extend(target_block.body[:pb_is]) + top_body.append(ir.Jump(target_block_successor_label, target_block.loc)) + bottom_body.extend(target_block.body[pb_is:-1]) + bottom_body.append(ir.Jump(new_label, target_block.loc)) + + # get the contents of the return block + return_body = func_ir.blocks[target_block_successor_label].body + # finally, re-assign all blocks + new_block.body.extend(return_body) + target_block_successor.body.clear() + target_block_successor.body.extend(bottom_body) + target_block.body.clear() + target_block.body.extend(top_body) + + # finally, append the new return block and rebuild the IR properties + func_ir.blocks[new_label] = new_block + func_ir._definitions = ir_utils.build_definitions(func_ir.blocks) + return func_ir + + +def _eliminate_nested_withs(with_ranges): + known_ranges = [] + def within_known_range(start, end, known_ranges): + for a, b in known_ranges: + # FIXME: this should be a comparison in topological order, right + # now we are comparing the integers of the blocks, stuff probably + # works by accident. + if start > a and end < b: + return True + return False + + for s, e in sorted(with_ranges): + if not within_known_range(s, e, known_ranges): + known_ranges.append((s, e)) + + return known_ranges + +def consolidate_multi_exit_withs(withs: dict, blocks, func_ir): + """Modify the FunctionIR to merge the exit blocks of with constructs. + """ + for k in withs: + vs : set = withs[k] + if len(vs) > 1: + func_ir, common = _fix_multi_exit_blocks( + func_ir, vs, split_condition=ir_utils.is_pop_block, + ) + withs[k] = {common} + return func_ir + + +def _fix_multi_exit_blocks(func_ir, exit_nodes, *, split_condition=None): + """Modify the FunctionIR to create a single common exit node given the + original exit nodes. + + Parameters + ---------- + func_ir : + The FunctionIR. Mutated inplace. + exit_nodes : + The original exit nodes. A sequence of block keys. + split_condition : callable or None + If not None, it is a callable with the signature + `split_condition(statement)` that determines if the `statement` is the + splitting point (e.g. `POP_BLOCK`) in an exit node. + If it's None, the exit node is not split. + """ + + # Convert the following: + # + # | | + # +-------+ +-------+ + # | exit0 | | exit1 | + # +-------+ +-------+ + # | | + # +-------+ +-------+ + # | after0| | after1| + # +-------+ +-------+ + # | | + # + # To roughly: + # + # | | + # +-------+ +-------+ + # | exit0 | | exit1 | + # +-------+ +-------+ + # | | + # +-----+-----+ + # | + # +---------+ + # | common | + # +---------+ + # | + # +-------+ + # | post | + # +-------+ + # | + # +-----+-----+ + # | | + # +-------+ +-------+ + # | after0| | after1| + # +-------+ +-------+ + + blocks = func_ir.blocks + # Getting the scope + any_blk = min(func_ir.blocks.values()) + scope = any_blk.scope + # Getting the maximum block label + max_label = max(func_ir.blocks) + 1 + # Define the new common block for the new exit. + common_block = ir.Block(any_blk.scope, loc=ir.unknown_loc) + common_label = max_label + max_label += 1 + blocks[common_label] = common_block + # Define the new block after the exit. + post_block = ir.Block(any_blk.scope, loc=ir.unknown_loc) + post_label = max_label + max_label += 1 + blocks[post_label] = post_block + + # Adjust each exit node + remainings = [] + for i, k in enumerate(exit_nodes): + blk = blocks[k] + + # split the block if needed + if split_condition is not None: + for pt, stmt in enumerate(blk.body): + if split_condition(stmt): + break + else: + # no splitting + pt = -1 + + before = blk.body[:pt] + after = blk.body[pt:] + remainings.append(after) + + # Add control-point variable to mark which exit block this is. + blk.body = before + loc = blk.loc + blk.body.append( + ir.Assign(value=ir.Const(i, loc=loc), + target=scope.get_or_define("$cp", loc=loc), + loc=loc) + ) + # Replace terminator with a jump to the common block + assert not blk.is_terminated + blk.body.append(ir.Jump(common_label, loc=ir.unknown_loc)) + + if split_condition is not None: + # Move the splitting statement to the common block + common_block.body.append(remainings[0][0]) + assert not common_block.is_terminated + # Append jump from common block to post block + common_block.body.append(ir.Jump(post_label, loc=loc)) + + # Make if-else tree to jump to target + remain_blocks = [] + for remain in remainings: + remain_blocks.append(max_label) + max_label += 1 + + switch_block = post_block + loc = ir.unknown_loc + for i, remain in enumerate(remainings): + match_expr = scope.redefine("$cp_check", loc=loc) + match_rhs = scope.redefine("$cp_rhs", loc=loc) + + # Do comparison to match control-point variable to the exit block + switch_block.body.append( + ir.Assign( + value=ir.Const(i, loc=loc), + target=match_rhs, + loc=loc + ), + ) + + # Add assignment for the comparison + switch_block.body.append( + ir.Assign( + value=ir.Expr.binop( + fn=operator.eq, lhs=scope.get("$cp"), rhs=match_rhs, + loc=loc, + ), + target=match_expr, + loc=loc + ), + ) + + # Insert jump to the next case + [jump_target] = remain[-1].get_targets() + switch_block.body.append( + ir.Branch(match_expr, jump_target, remain_blocks[i], loc=loc), + ) + switch_block = ir.Block(scope=scope, loc=loc) + blocks[remain_blocks[i]] = switch_block + + # Add the final jump + switch_block.body.append(ir.Jump(jump_target, loc=loc)) + + return func_ir, common_label diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typed_passes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typed_passes.py new file mode 100644 index 0000000000000000000000000000000000000000..340f89d1ece7667df80affe96b12adcdacf38f35 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typed_passes.py @@ -0,0 +1,1044 @@ +import abc +from contextlib import contextmanager +from collections import defaultdict, namedtuple +from functools import partial +from copy import copy +import warnings + +from numba.core import (errors, types, typing, ir, funcdesc, rewrites, + typeinfer, config, lowering) + +from numba.parfors.parfor import PreParforPass as _parfor_PreParforPass +from numba.parfors.parfor import ParforPass as _parfor_ParforPass +from numba.parfors.parfor import ParforFusionPass as _parfor_ParforFusionPass +from numba.parfors.parfor import ParforPreLoweringPass as \ + _parfor_ParforPreLoweringPass +from numba.parfors.parfor import Parfor +from numba.parfors.parfor_lowering import ParforLower + +from numba.core.compiler_machinery import (FunctionPass, LoweringPass, + AnalysisPass, register_pass) +from numba.core.annotations import type_annotations +from numba.core.ir_utils import (raise_on_unsupported_feature, warn_deprecated, + check_and_legalize_ir, guard, + dead_code_elimination, simplify_CFG, + get_definition, + build_definitions, compute_cfg_from_blocks, + is_operator_or_getitem, + replace_vars) +from numba.core import postproc +from llvmlite import binding as llvm + + +# Outputs of type inference pass +_TypingResults = namedtuple("_TypingResults", [ + "typemap", + "return_type", + "calltypes", + "typing_errors", +]) + + +@contextmanager +def fallback_context(state, msg): + """ + Wraps code that would signal a fallback to object mode + """ + try: + yield + except Exception as e: + if not state.status.can_fallback: + raise + else: + # Clear all references attached to the traceback + e = e.with_traceback(None) + # this emits a warning containing the error message body in the + # case of fallback from npm to objmode + loop_lift = '' if state.flags.enable_looplift else 'OUT' + msg_rewrite = ("\nCompilation is falling back to object mode " + "WITH%s looplifting enabled because %s" + % (loop_lift, msg)) + warnings.warn_explicit('%s due to: %s' % (msg_rewrite, e), + errors.NumbaWarning, + state.func_id.filename, + state.func_id.firstlineno) + raise + + +def type_inference_stage(typingctx, targetctx, interp, args, return_type, + locals=None, raise_errors=True): + if locals is None: + locals = {} + if len(args) != interp.arg_count: + raise TypeError("Mismatch number of argument types") + warnings = errors.WarningsFixer(errors.NumbaWarning) + + infer = typeinfer.TypeInferer(typingctx, interp, warnings) + callstack_ctx = typingctx.callstack.register(targetctx.target, infer, + interp.func_id, args) + # Setup two contexts: 1) callstack setup/teardown 2) flush warnings + with callstack_ctx, warnings: + # Seed argument types + for index, (name, ty) in enumerate(zip(interp.arg_names, args)): + infer.seed_argument(name, index, ty) + + # Seed return type + if return_type is not None: + infer.seed_return(return_type) + + # Seed local types + for k, v in locals.items(): + infer.seed_type(k, v) + + infer.build_constraint() + # return errors in case of partial typing + errs = infer.propagate(raise_errors=raise_errors) + typemap, restype, calltypes = infer.unify(raise_errors=raise_errors) + + return _TypingResults(typemap, restype, calltypes, errs) + + +class BaseTypeInference(FunctionPass): + _raise_errors = True + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Type inference and legalization + """ + with fallback_context(state, 'Function "%s" failed type inference' + % (state.func_id.func_name,)): + # Type inference + typemap, return_type, calltypes, errs = type_inference_stage( + state.typingctx, + state.targetctx, + state.func_ir, + state.args, + state.return_type, + state.locals, + raise_errors=self._raise_errors) + state.typemap = typemap + # save errors in case of partial typing + state.typing_errors = errs + if self._raise_errors: + state.return_type = return_type + state.calltypes = calltypes + + def legalize_return_type(return_type, interp, targetctx): + """ + Only accept array return type iff it is passed into the function. + Reject function object return types if in nopython mode. + """ + if (not targetctx.enable_nrt and + isinstance(return_type, types.Array)): + # Walk IR to discover all arguments and all return statements + retstmts = [] + caststmts = {} + argvars = set() + for bid, blk in interp.blocks.items(): + for inst in blk.body: + if isinstance(inst, ir.Return): + retstmts.append(inst.value.name) + elif isinstance(inst, ir.Assign): + if (isinstance(inst.value, ir.Expr) + and inst.value.op == 'cast'): + caststmts[inst.target.name] = inst.value + elif isinstance(inst.value, ir.Arg): + argvars.add(inst.target.name) + + assert retstmts, "No return statements?" + + for var in retstmts: + cast = caststmts.get(var) + if cast is None or cast.value.name not in argvars: + if self._raise_errors: + msg = ("Only accept returning of array passed into " + "the function as argument") + raise errors.NumbaTypeError(msg) + + elif (isinstance(return_type, types.Function) or + isinstance(return_type, types.Phantom)): + if self._raise_errors: + msg = "Can't return function object ({}) in nopython mode" + raise errors.NumbaTypeError(msg.format(return_type)) + + with fallback_context(state, 'Function "%s" has invalid return type' + % (state.func_id.func_name,)): + legalize_return_type(state.return_type, state.func_ir, + state.targetctx) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class NopythonTypeInference(BaseTypeInference): + _name = "nopython_type_inference" + + +@register_pass(mutates_CFG=True, analysis_only=False) +class PartialTypeInference(BaseTypeInference): + _name = "partial_type_inference" + _raise_errors = False + + +@register_pass(mutates_CFG=False, analysis_only=False) +class AnnotateTypes(AnalysisPass): + _name = "annotate_types" + + def __init__(self): + AnalysisPass.__init__(self) + + def get_analysis_usage(self, AU): + AU.add_required(IRLegalization) + + def run_pass(self, state): + """ + Create type annotation after type inference + """ + func_ir = state.func_ir.copy() + state.type_annotation = type_annotations.TypeAnnotation( + func_ir=func_ir, + typemap=state.typemap, + calltypes=state.calltypes, + lifted=state.lifted, + lifted_from=state.lifted_from, + args=state.args, + return_type=state.return_type, + html_output=config.HTML) + + if config.ANNOTATE: + print("ANNOTATION".center(80, '-')) + print(state.type_annotation) + print('=' * 80) + if config.HTML: + with open(config.HTML, 'w') as fout: + state.type_annotation.html_annotate(fout) + + return False + + +@register_pass(mutates_CFG=True, analysis_only=False) +class NopythonRewrites(FunctionPass): + _name = "nopython_rewrites" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Perform any intermediate representation rewrites after type + inference. + """ + # a bunch of these passes are either making assumptions or rely on some + # very picky and slightly bizarre state particularly in relation to + # ir.Del presence. To accommodate, ir.Dels are added ahead of running + # this pass and stripped at the end. + + # Ensure we have an IR and type information. + assert state.func_ir + assert isinstance(getattr(state, 'typemap', None), dict) + assert isinstance(getattr(state, 'calltypes', None), dict) + msg = ('Internal error in post-inference rewriting ' + 'pass encountered during compilation of ' + 'function "%s"' % (state.func_id.func_name,)) + + pp = postproc.PostProcessor(state.func_ir) + pp.run(True) + with fallback_context(state, msg): + rewrites.rewrite_registry.apply('after-inference', state) + pp.remove_dels() + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class PreParforPass(FunctionPass): + + _name = "pre_parfor_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Preprocessing for data-parallel computations. + """ + # Ensure we have an IR and type information. + assert state.func_ir + preparfor_pass = _parfor_PreParforPass( + state.func_ir, + state.typemap, + state.calltypes, + state.typingctx, + state.targetctx, + state.flags.auto_parallel, + state.parfor_diagnostics.replaced_fns + ) + + preparfor_pass.run() + return True + + +# this is here so it pickles and for no other reason +def _reload_parfors(): + """Reloader for cached parfors + """ + # Re-initialize the parallel backend when load from cache. + from numba.np.ufunc.parallel import _launch_threads + _launch_threads() + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ParforPass(FunctionPass): + + _name = "parfor_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Convert data-parallel computations into Parfor nodes + """ + # Ensure we have an IR and type information. + assert state.func_ir + parfor_pass = _parfor_ParforPass(state.func_ir, + state.typemap, + state.calltypes, + state.return_type, + state.typingctx, + state.targetctx, + state.flags.auto_parallel, + state.flags, + state.metadata, + state.parfor_diagnostics) + parfor_pass.run() + + # check the parfor pass worked and warn if it didn't + has_parfor = False + for blk in state.func_ir.blocks.values(): + for stmnt in blk.body: + if isinstance(stmnt, Parfor): + has_parfor = True + break + else: + continue + break + + if not has_parfor: + # parfor calls the compiler chain again with a string + if not (config.DISABLE_PERFORMANCE_WARNINGS or + state.func_ir.loc.filename == ''): + url = ("https://numba.readthedocs.io/en/stable/user/" + "parallel.html#diagnostics") + msg = ("\nThe keyword argument 'parallel=True' was specified " + "but no transformation for parallel execution was " + "possible.\n\nTo find out why, try turning on parallel " + "diagnostics, see %s for help." % url) + warnings.warn(errors.NumbaPerformanceWarning(msg, + state.func_ir.loc)) + + # Add reload function to initialize the parallel backend. + state.reload_init.append(_reload_parfors) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ParforFusionPass(FunctionPass): + + _name = "parfor_fusion_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Do fusion of parfor nodes. + """ + # Ensure we have an IR and type information. + assert state.func_ir + parfor_pass = _parfor_ParforFusionPass(state.func_ir, + state.typemap, + state.calltypes, + state.return_type, + state.typingctx, + state.targetctx, + state.flags.auto_parallel, + state.flags, + state.metadata, + state.parfor_diagnostics) + parfor_pass.run() + + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ParforPreLoweringPass(FunctionPass): + + _name = "parfor_prelowering_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Prepare parfors for lowering. + """ + # Ensure we have an IR and type information. + assert state.func_ir + parfor_pass = _parfor_ParforPreLoweringPass(state.func_ir, + state.typemap, + state.calltypes, + state.return_type, + state.typingctx, + state.targetctx, + state.flags.auto_parallel, + state.flags, + state.metadata, + state.parfor_diagnostics) + parfor_pass.run() + + return True + + +@register_pass(mutates_CFG=False, analysis_only=True) +class DumpParforDiagnostics(AnalysisPass): + + _name = "dump_parfor_diagnostics" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + if state.flags.auto_parallel.enabled: + if config.PARALLEL_DIAGNOSTICS: + if state.parfor_diagnostics is not None: + state.parfor_diagnostics.dump(config.PARALLEL_DIAGNOSTICS) + else: + raise RuntimeError("Diagnostics failed.") + return True + + +class BaseNativeLowering(abc.ABC, LoweringPass): + """The base class for a lowering pass. The lowering functionality must be + specified in inheriting classes by providing an appropriate lowering class + implementation in the overridden `lowering_class` property.""" + + _name = None + + def __init__(self): + LoweringPass.__init__(self) + + @property + @abc.abstractmethod + def lowering_class(self): + """Returns the class that performs the lowering of the IR describing the + function that is the target of the current compilation.""" + pass + + def run_pass(self, state): + if state.library is None: + codegen = state.targetctx.codegen() + state.library = codegen.create_library(state.func_id.func_qualname) + # Enable object caching upfront, so that the library can + # be later serialized. + state.library.enable_object_caching() + + library = state.library + targetctx = state.targetctx + interp = state.func_ir # why is it called this?! + typemap = state.typemap + restype = state.return_type + calltypes = state.calltypes + flags = state.flags + metadata = state.metadata + pre_stats = llvm.newpassmanagers.dump_refprune_stats() + # Add reload functions to library + library._reload_init.update(state.reload_init) + + msg = ("Function %s failed at nopython " + "mode lowering" % (state.func_id.func_name,)) + with fallback_context(state, msg): + # Lowering + fndesc = \ + funcdesc.PythonFunctionDescriptor.from_specialized_function( + interp, typemap, restype, calltypes, + mangler=targetctx.mangler, inline=flags.forceinline, + noalias=flags.noalias, abi_tags=[flags.get_mangle_string()]) + + with targetctx.push_code_library(library): + lower = self.lowering_class(targetctx, library, fndesc, interp, + metadata=metadata) + lower.lower() + if not flags.no_cpython_wrapper: + lower.create_cpython_wrapper(flags.release_gil) + + if not flags.no_cfunc_wrapper: + # skip cfunc wrapper generation if unsupported + # argument or return types are used + for t in state.args: + if isinstance(t, (types.Omitted, types.Generator)): + break + else: + if isinstance(restype, + (types.Optional, types.Generator)): + pass + else: + lower.create_cfunc_wrapper() + + env = lower.env + call_helper = lower.call_helper + del lower + + from numba.core.compiler import _LowerResult # TODO: move this + if flags.no_compile: + state['cr'] = _LowerResult(fndesc, call_helper, + cfunc=None, env=env) + else: + # Prepare for execution + # Insert native function for use by other jitted-functions. + # We also register its library to allow for inlining. + cfunc = targetctx.get_executable(library, fndesc, env) + targetctx.insert_user_function(cfunc, fndesc, [library]) + state.reload_init.extend(library._reload_init) + state['cr'] = _LowerResult(fndesc, call_helper, + cfunc=cfunc, env=env) + + # capture pruning stats + post_stats = llvm.newpassmanagers.dump_refprune_stats() + metadata['prune_stats'] = post_stats - pre_stats + + # Save the LLVM pass timings + metadata['llvm_pass_timings'] = library.recorded_timings + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class NativeLowering(BaseNativeLowering): + """Lowering pass for a native function IR described solely in terms of + Numba's standard `numba.core.ir` nodes.""" + _name = "native_lowering" + + @property + def lowering_class(self): + return lowering.Lower + + +@register_pass(mutates_CFG=True, analysis_only=False) +class NativeParforLowering(BaseNativeLowering): + """Lowering pass for a native function IR described using Numba's standard + `numba.core.ir` nodes and also parfor.Parfor nodes.""" + _name = "native_parfor_lowering" + + @property + def lowering_class(self): + return ParforLower + + +@register_pass(mutates_CFG=False, analysis_only=True) +class NoPythonSupportedFeatureValidation(AnalysisPass): + """NoPython Mode check: Validates the IR to ensure that features in use are + in a form that is supported""" + + _name = "nopython_supported_feature_validation" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + raise_on_unsupported_feature(state.func_ir, state.typemap) + warn_deprecated(state.func_ir, state.typemap) + return False + + +@register_pass(mutates_CFG=False, analysis_only=True) +class IRLegalization(AnalysisPass): + + _name = "ir_legalization" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + # NOTE: this function call must go last, it checks and fixes invalid IR! + check_and_legalize_ir(state.func_ir, flags=state.flags) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class NoPythonBackend(LoweringPass): + + _name = "nopython_backend" + + def __init__(self): + LoweringPass.__init__(self) + + def run_pass(self, state): + """ + Back-end: Generate LLVM IR from Numba IR, compile to machine code + """ + lowered = state['cr'] + signature = typing.signature(state.return_type, *state.args) + + from numba.core.compiler import compile_result + state.cr = compile_result( + typing_context=state.typingctx, + target_context=state.targetctx, + entry_point=lowered.cfunc, + typing_error=state.status.fail_reason, + type_annotation=state.type_annotation, + library=state.library, + call_helper=lowered.call_helper, + signature=signature, + objectmode=False, + lifted=state.lifted, + fndesc=lowered.fndesc, + environment=lowered.env, + metadata=state.metadata, + reload_init=state.reload_init, + ) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class InlineOverloads(FunctionPass): + """ + This pass will inline a function wrapped by the numba.extending.overload + decorator directly into the site of its call depending on the value set in + the 'inline' kwarg to the decorator. + + This is a typed pass. CFG simplification and DCE are performed on + completion. + """ + + _name = "inline_overloads" + + def __init__(self): + FunctionPass.__init__(self) + + _DEBUG = False + + def run_pass(self, state): + """Run inlining of overloads + """ + if self._DEBUG: + print('before overload inline'.center(80, '-')) + print(state.func_id.unique_name) + print(state.func_ir.dump()) + print(''.center(80, '-')) + from numba.core.inline_closurecall import (InlineWorker, + callee_ir_validator) + inline_worker = InlineWorker(state.typingctx, + state.targetctx, + state.locals, + state.pipeline, + state.flags, + callee_ir_validator, + state.typemap, + state.calltypes, + ) + modified = False + work_list = list(state.func_ir.blocks.items()) + # use a work list, look for call sites via `ir.Expr.op == call` and + # then pass these to `self._do_work` to make decisions about inlining. + while work_list: + label, block = work_list.pop() + for i, instr in enumerate(block.body): + # TO-DO: other statements (setitem) + if isinstance(instr, ir.Assign): + expr = instr.value + if isinstance(expr, ir.Expr): + workfn = self._do_work_expr + + if guard(workfn, state, work_list, block, i, expr, + inline_worker): + modified = True + break # because block structure changed + + if self._DEBUG: + print('after overload inline'.center(80, '-')) + print(state.func_id.unique_name) + print(state.func_ir.dump()) + print(''.center(80, '-')) + + if modified: + # Remove dead blocks, this is safe as it relies on the CFG only. + cfg = compute_cfg_from_blocks(state.func_ir.blocks) + for dead in cfg.dead_nodes(): + del state.func_ir.blocks[dead] + # clean up blocks + dead_code_elimination(state.func_ir, + typemap=state.typemap) + # clean up unconditional branches that appear due to inlined + # functions introducing blocks + state.func_ir.blocks = simplify_CFG(state.func_ir.blocks) + + if self._DEBUG: + print('after overload inline DCE'.center(80, '-')) + print(state.func_id.unique_name) + print(state.func_ir.dump()) + print(''.center(80, '-')) + return True + + def _get_attr_info(self, state, expr): + recv_type = state.typemap[expr.value.name] + recv_type = types.unliteral(recv_type) + matched = state.typingctx.find_matching_getattr_template( + recv_type, expr.attr, + ) + if not matched: + return None + + template = matched['template'] + if getattr(template, 'is_method', False): + # The attribute template is representing a method. + # Don't inline the getattr. + return None + + templates = [template] + sig = typing.signature(matched['return_type'], recv_type) + arg_typs = sig.args + is_method = False + + return templates, sig, arg_typs, is_method + + def _get_callable_info(self, state, expr): + + def get_func_type(state, expr): + func_ty = None + if expr.op == 'call': + # check this is a known and typed function + try: + func_ty = state.typemap[expr.func.name] + except KeyError: + # e.g. Calls to CUDA Intrinsic have no mapped type + # so KeyError + return None + if not hasattr(func_ty, 'get_call_type'): + return None + + elif is_operator_or_getitem(expr): + func_ty = state.typingctx.resolve_value_type(expr.fn) + else: + return None + + return func_ty + + if expr.op == 'call': + # try and get a definition for the call, this isn't always + # possible as it might be a eval(str)/part generated + # awaiting update etc. (parfors) + to_inline = None + try: + to_inline = state.func_ir.get_definition(expr.func) + except Exception: + return None + + # do not handle closure inlining here, another pass deals with that + if getattr(to_inline, 'op', False) == 'make_function': + return None + + func_ty = get_func_type(state, expr) + if func_ty is None: + return None + + sig = state.calltypes[expr] + if not sig: + return None + + templates, arg_typs, is_method = None, None, False + if getattr(func_ty, 'template', None) is not None: + # @overload_method + is_method = True + templates = [func_ty.template] + arg_typs = (func_ty.template.this,) + sig.args + else: + # @overload case + templates = getattr(func_ty, 'templates', None) + arg_typs = sig.args + + return templates, sig, arg_typs, is_method + + def _do_work_expr(self, state, work_list, block, i, expr, inline_worker): + + def select_template(templates, args): + if templates is None: + return None + + impl = None + for template in templates: + inline_type = getattr(template, '_inline', None) + if inline_type is None: + # inline not defined + continue + if args not in template._inline_overloads: + # skip overloads not matching signature + continue + if not inline_type.is_never_inline: + try: + impl = template._overload_func(*args) + if impl is None: + raise Exception # abort for this template + break + except Exception: + continue + else: + return None + + return template, inline_type, impl + + inlinee_info = None + if expr.op == 'getattr': + inlinee_info = self._get_attr_info(state, expr) + else: + inlinee_info = self._get_callable_info(state, expr) + + if not inlinee_info: + return False + + templates, sig, arg_typs, is_method = inlinee_info + inlinee = select_template(templates, arg_typs) + if inlinee is None: + return False + template, inlinee_type, impl = inlinee + + return self._run_inliner( + state, inlinee_type, sig, template, arg_typs, expr, i, impl, block, + work_list, is_method, inline_worker, + ) + + def _run_inliner( + self, state, inline_type, sig, template, arg_typs, expr, i, impl, block, + work_list, is_method, inline_worker, + ): + + do_inline = True + if not inline_type.is_always_inline: + from numba.core.typing.templates import _inline_info + caller_inline_info = _inline_info(state.func_ir, + state.typemap, + state.calltypes, + sig) + + # must be a cost-model function, run the function + iinfo = template._inline_overloads[arg_typs]['iinfo'] + if inline_type.has_cost_model: + do_inline = inline_type.value(expr, caller_inline_info, iinfo) + else: + assert 'unreachable' + + if do_inline: + if is_method: + if not self._add_method_self_arg(state, expr): + return False + arg_typs = template._inline_overloads[arg_typs]['folded_args'] + iinfo = template._inline_overloads[arg_typs]['iinfo'] + freevars = iinfo.func_ir.func_id.func.__code__.co_freevars + _, _, _, new_blocks = inline_worker.inline_ir(state.func_ir, + block, + i, + iinfo.func_ir, + freevars, + arg_typs=arg_typs) + if work_list is not None: + for blk in new_blocks: + work_list.append(blk) + return True + else: + return False + + def _add_method_self_arg(self, state, expr): + func_def = guard(get_definition, state.func_ir, expr.func) + if func_def is None: + return False + expr.args.insert(0, func_def.value) + return True + + +@register_pass(mutates_CFG=False, analysis_only=False) +class DeadCodeElimination(FunctionPass): + """ + Does dead code elimination + """ + + _name = "dead_code_elimination" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + dead_code_elimination(state.func_ir, state.typemap) + return True + + +@register_pass(mutates_CFG=False, analysis_only=False) +class PreLowerStripPhis(FunctionPass): + """Remove phi nodes (ir.Expr.phi) introduced by SSA. + + This is needed before Lowering because the phi nodes in Numba IR do not + match the semantics of phi nodes in LLVM IR. In Numba IR, phi nodes may + expand into multiple LLVM instructions. + """ + + _name = "strip_phis" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + state.func_ir = self._strip_phi_nodes(state.func_ir) + state.func_ir._definitions = build_definitions(state.func_ir.blocks) + if "flags" in state and state.flags.auto_parallel.enabled: + self._simplify_conditionally_defined_variable(state.func_ir) + state.func_ir._definitions = build_definitions(state.func_ir.blocks) + + # Rerun postprocessor to update metadata + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run(emit_dels=False) + + # Ensure we are not in objectmode generator + if (state.func_ir.generator_info is not None + and state.typemap is not None): + # Rebuild generator type + # TODO: move this into PostProcessor + gentype = state.return_type + state_vars = state.func_ir.generator_info.state_vars + state_types = [state.typemap[k] for k in state_vars] + state.return_type = types.Generator( + gen_func=gentype.gen_func, + yield_type=gentype.yield_type, + arg_types=gentype.arg_types, + state_types=state_types, + has_finalizer=gentype.has_finalizer, + ) + return True + + def _strip_phi_nodes(self, func_ir): + """Strip Phi nodes from ``func_ir`` + + For each phi node, put incoming value to their respective incoming + basic-block at possibly the latest position (i.e. after the latest + assignment to the corresponding variable). + """ + exporters = defaultdict(list) + phis = set() + # Find all variables that needs to be exported + for label, block in func_ir.blocks.items(): + for assign in block.find_insts(ir.Assign): + if isinstance(assign.value, ir.Expr): + if assign.value.op == 'phi': + phis.add(assign) + phi = assign.value + for ib, iv in zip(phi.incoming_blocks, + phi.incoming_values): + exporters[ib].append((assign.target, iv)) + + # Rewrite the blocks with the new exporting assignments + newblocks = {} + for label, block in func_ir.blocks.items(): + newblk = copy(block) + newblocks[label] = newblk + + # strip phis + newblk.body = [stmt for stmt in block.body if stmt not in phis] + + # insert exporters + for target, rhs in exporters[label]: + # If RHS is undefined + if rhs is ir.UNDEFINED: + # Put in a NULL initializer, set the location to be in what + # will eventually materialize as the prologue. + rhs = ir.Expr.null(loc=func_ir.loc) + + assign = ir.Assign( + target=target, + value=rhs, + loc=rhs.loc + ) + # Insert at the earliest possible location; i.e. after the + # last assignment to rhs + assignments = [stmt for stmt in newblk.find_insts(ir.Assign) + if stmt.target == rhs] + if assignments: + last_assignment = assignments[-1] + newblk.insert_after(assign, last_assignment) + else: + newblk.prepend(assign) + + func_ir.blocks = newblocks + return func_ir + + def _simplify_conditionally_defined_variable(self, func_ir): + """ + Rewrite assignments like: + + ver1 = null() + ... + ver1 = ver + ... + uses(ver1) + + into: + # delete all assignments to ver1 + uses(ver) + + This is only needed for parfors because the SSA pass will create extra + variable assignments that the parfor code does not expect. + This pass helps avoid problems by reverting the effect of SSA. + """ + any_block = next(iter(func_ir.blocks.values())) + scope = any_block.scope + defs = func_ir._definitions + + def unver_or_undef(unver, defn): + # Is the definition undefined or pointing to the unversioned name? + if isinstance(defn, ir.Var): + if defn.unversioned_name == unver: + return True + elif isinstance(defn, ir.Expr): + if defn.op == "null": + return True + return False + + def legalize_all_versioned_names(var): + # Are all versioned names undefined or defined to the same + # variable chain? + if not var.versioned_names: + return False + for versioned in var.versioned_names: + vs = defs.get(versioned, ()) + if not all(map(partial(unver_or_undef, k), vs)): + return False + return True + + # Find unversioned variables that met the conditions + suspects = set() + for k in defs: + try: + # This may fail? + var = scope.get_exact(k) + except errors.NotDefinedError: + continue + # is the var name unversioned? + if var.unversioned_name == k: + if legalize_all_versioned_names(var): + suspects.add(var) + + delete_set = set() + replace_map = {} + for var in suspects: + # rewrite Var uses to the unversioned name + for versioned in var.versioned_names: + ver_var = scope.get_exact(versioned) + # delete assignment to the versioned name + delete_set.add(ver_var) + # replace references to versioned name with the unversioned + replace_map[versioned] = var + + # remove assignments to the versioned names + for _label, blk in func_ir.blocks.items(): + for assign in blk.find_insts(ir.Assign): + if assign.target in delete_set: + blk.remove(assign) + # do variable replacement + replace_vars(func_ir.blocks, replace_map) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typeinfer.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typeinfer.py new file mode 100644 index 0000000000000000000000000000000000000000..60c1460ea84266c9eee6957b1e3c1b905ad7028f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/typeinfer.py @@ -0,0 +1,1797 @@ +""" +Type inference base on CPA. +The algorithm guarantees monotonic growth of type-sets for each variable. + +Steps: + 1. seed initial types + 2. build constraints + 3. propagate constraints + 4. unify types + +Constraint propagation is precise and does not regret (no backtracing). +Constraints push types forward following the dataflow. +""" + + +import logging +import operator +import contextlib +import itertools +from pprint import pprint +from collections import OrderedDict, defaultdict +from functools import reduce + +from numba.core import types, utils, typing, ir, config +from numba.core.typing.templates import Signature +from numba.core.errors import (TypingError, UntypedAttributeError, + new_error_context, termcolor, UnsupportedError, + ForceLiteralArg, CompilerError, NumbaValueError) +from numba.core.funcdesc import qualifying_prefix +from numba.core.typeconv import Conversion + +_logger = logging.getLogger(__name__) + + +class NOTSET: + pass + + +# terminal color markup +_termcolor = termcolor() + + +class TypeVar(object): + def __init__(self, context, var): + self.context = context + self.var = var + self.type = None + self.locked = False + # Stores source location of first definition + self.define_loc = None + # Qualifiers + self.literal_value = NOTSET + + def add_type(self, tp, loc): + assert isinstance(tp, types.Type), type(tp) + # Special case for _undef_var. + # If the typevar is the _undef_var, use the incoming type directly. + if self.type is types._undef_var: + self.type = tp + return self.type + + if self.locked: + if tp != self.type: + if self.context.can_convert(tp, self.type) is None: + msg = ("No conversion from %s to %s for '%s', " + "defined at %s") + raise TypingError(msg % (tp, self.type, self.var, + self.define_loc), + loc=loc) + else: + if self.type is not None: + unified = self.context.unify_pairs(self.type, tp) + if unified is None: + msg = "Cannot unify %s and %s for '%s', defined at %s" + raise TypingError(msg % (self.type, tp, self.var, + self.define_loc), + loc=self.define_loc) + else: + # First time definition + unified = tp + self.define_loc = loc + + self.type = unified + + return self.type + + def lock(self, tp, loc, literal_value=NOTSET): + assert isinstance(tp, types.Type), type(tp) + + if self.locked: + msg = ("Invalid reassignment of a type-variable detected, type " + "variables are locked according to the user provided " + "function signature or from an ir.Const node. This is a " + "bug! Type={}. {}").format(tp, self.type) + raise CompilerError(msg, loc) + + # If there is already a type, ensure we can convert it to the + # locked type. + if (self.type is not None and + self.context.can_convert(self.type, tp) is None): + raise TypingError("No conversion from %s to %s for " + "'%s'" % (tp, self.type, self.var), loc=loc) + + self.type = tp + self.locked = True + if self.define_loc is None: + self.define_loc = loc + self.literal_value = literal_value + + def union(self, other, loc): + if other.type is not None: + self.add_type(other.type, loc=loc) + + return self.type + + def __repr__(self): + return '%s := %s' % (self.var, self.type or "") + + @property + def defined(self): + return self.type is not None + + def get(self): + return (self.type,) if self.type is not None else () + + def getone(self): + if self.type is None: + raise TypingError("Undecided type {}".format(self)) + return self.type + + def __len__(self): + return 1 if self.type is not None else 0 + + +class ConstraintNetwork(object): + """ + TODO: It is possible to optimize constraint propagation to consider only + dirty type variables. + """ + + def __init__(self): + self.constraints = [] + + def append(self, constraint): + self.constraints.append(constraint) + + def propagate(self, typeinfer): + """ + Execute all constraints. Errors are caught and returned as a list. + This allows progressing even though some constraints may fail + due to lack of information + (e.g. imprecise types such as List(undefined)). + """ + errors = [] + for constraint in self.constraints: + loc = constraint.loc + with typeinfer.warnings.catch_warnings(filename=loc.filename, + lineno=loc.line): + try: + constraint(typeinfer) + except ForceLiteralArg as e: + errors.append(e) + except TypingError as e: + _logger.debug("captured error", exc_info=e) + new_exc = TypingError( + str(e), loc=constraint.loc, + highlighting=False, + ) + errors.append(utils.chain_exception(new_exc, e)) + + return errors + + +class Propagate(object): + """ + A simple constraint for direct propagation of types for assignments. + """ + + def __init__(self, dst, src, loc): + self.dst = dst + self.src = src + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of assignment at {loc}", + loc=self.loc): + typeinfer.copy_type(self.src, self.dst, loc=self.loc) + # If `dst` is refined, notify us + typeinfer.refine_map[self.dst] = self + + def refine(self, typeinfer, target_type): + # Do not back-propagate to locked variables (e.g. constants) + assert target_type.is_precise() + typeinfer.add_type(self.src, target_type, unless_locked=True, + loc=self.loc) + + +class ArgConstraint(object): + + def __init__(self, dst, src, loc): + self.dst = dst + self.src = src + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of argument at {loc}", loc=self.loc): + typevars = typeinfer.typevars + src = typevars[self.src] + if not src.defined: + return + ty = src.getone() + if isinstance(ty, types.Omitted): + ty = typeinfer.context.resolve_value_type_prefer_literal( + ty.value, + ) + if not ty.is_precise(): + raise TypingError('non-precise type {}'.format(ty)) + typeinfer.add_type(self.dst, ty, loc=self.loc) + + +class BuildTupleConstraint(object): + def __init__(self, target, items, loc): + self.target = target + self.items = items + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of tuple at {loc}", loc=self.loc): + typevars = typeinfer.typevars + tsets = [typevars[i.name].get() for i in self.items] + for vals in itertools.product(*tsets): + if vals and all(vals[0] == v for v in vals): + tup = types.UniTuple(dtype=vals[0], count=len(vals)) + else: + # empty tuples fall here as well + tup = types.Tuple(vals) + assert tup.is_precise() + typeinfer.add_type(self.target, tup, loc=self.loc) + + +class _BuildContainerConstraint(object): + + def __init__(self, target, items, loc): + self.target = target + self.items = items + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of {container_type} at {loc}", + container_type=self.container_type, + loc=self.loc): + typevars = typeinfer.typevars + tsets = [typevars[i.name].get() for i in self.items] + if not tsets: + typeinfer.add_type(self.target, + self.container_type(types.undefined), + loc=self.loc) + else: + for typs in itertools.product(*tsets): + unified = typeinfer.context.unify_types(*typs) + if unified is not None: + typeinfer.add_type(self.target, + self.container_type(unified), + loc=self.loc) + + +class BuildListConstraint(_BuildContainerConstraint): + + def __init__(self, target, items, loc): + self.target = target + self.items = items + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of {container_type} at {loc}", + container_type=types.List, loc=self.loc): + typevars = typeinfer.typevars + tsets = [typevars[i.name].get() for i in self.items] + if not tsets: + typeinfer.add_type(self.target, + types.List(types.undefined), + loc=self.loc) + else: + for typs in itertools.product(*tsets): + unified = typeinfer.context.unify_types(*typs) + if unified is not None: + # pull out literals if available + islit = [isinstance(x, types.Literal) for x in typs] + iv = None + if all(islit): + iv = [x.literal_value for x in typs] + typeinfer.add_type(self.target, + types.List(unified, + initial_value=iv), + loc=self.loc) + else: + typeinfer.add_type(self.target, + types.LiteralList(typs), + loc=self.loc) + + +class BuildSetConstraint(_BuildContainerConstraint): + container_type = types.Set + + +class BuildMapConstraint(object): + + def __init__(self, target, items, special_value, value_indexes, loc): + self.target = target + self.items = items + self.special_value = special_value + self.value_indexes = value_indexes + self.loc = loc + + def __call__(self, typeinfer): + + with new_error_context("typing of dict at {loc}", loc=self.loc): + typevars = typeinfer.typevars + + # figure out what sort of dict is being dealt with + tsets = [(typevars[k.name].getone(), typevars[v.name].getone()) + for k, v in self.items] + + if not tsets: + typeinfer.add_type(self.target, + types.DictType(types.undefined, + types.undefined, + self.special_value), + loc=self.loc) + else: + # all the info is known about the dict, if its + # str keys -> random heterogeneous values treat as literalstrkey + ktys = [x[0] for x in tsets] + vtys = [x[1] for x in tsets] + strkey = all([isinstance(x, types.StringLiteral) for x in ktys]) + literalvty = all([isinstance(x, types.Literal) for x in vtys]) + vt0 = types.unliteral(vtys[0]) + + # homogeneous values comes in the form of being able to cast + # all the other values in the ctor to the type of the first. + # The order is important as `typed.Dict` takes it's type from + # the first element. + def check(other): + conv = typeinfer.context.can_convert(other, vt0) + return conv is not None and conv < Conversion.unsafe + homogeneous = all([check(types.unliteral(x)) for x in vtys]) + + # Special cases: + # Single key:value in ctor, key is str, value is an otherwise + # illegal container type, e.g. LiteralStrKeyDict or + # List, there's no way to put this into a typed.Dict, so make it + # a LiteralStrKeyDict, same goes for LiteralList. + if len(vtys) == 1: + valty = vtys[0] + if isinstance(valty, (types.LiteralStrKeyDict, + types.List, + types.LiteralList)): + homogeneous = False + + if strkey and not homogeneous: + resolved_dict = {x: y for x, y in zip(ktys, vtys)} + ty = types.LiteralStrKeyDict(resolved_dict, + self.value_indexes) + typeinfer.add_type(self.target, ty, loc=self.loc) + else: + init_value = self.special_value if literalvty else None + key_type, value_type = tsets[0] + typeinfer.add_type(self.target, + types.DictType(key_type, + value_type, + init_value), + loc=self.loc) + + +class ExhaustIterConstraint(object): + def __init__(self, target, count, iterator, loc): + self.target = target + self.count = count + self.iterator = iterator + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of exhaust iter at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + for tp in typevars[self.iterator.name].get(): + # unpack optional + tp = tp.type if isinstance(tp, types.Optional) else tp + if isinstance(tp, types.BaseTuple): + if len(tp) == self.count: + assert tp.is_precise() + typeinfer.add_type(self.target, tp, loc=self.loc) + break + else: + msg = (f"wrong tuple length for {self.iterator.name}: ", + f"expected {self.count}, got {len(tp)}") + raise NumbaValueError(msg) + elif isinstance(tp, types.IterableType): + tup = types.UniTuple(dtype=tp.iterator_type.yield_type, + count=self.count) + assert tup.is_precise() + typeinfer.add_type(self.target, tup, loc=self.loc) + break + else: + raise TypingError("failed to unpack {}".format(tp), + loc=self.loc) + + +class PairFirstConstraint(object): + def __init__(self, target, pair, loc): + self.target = target + self.pair = pair + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of pair-first at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + for tp in typevars[self.pair.name].get(): + if not isinstance(tp, types.Pair): + # XXX is this an error? + continue + assert (isinstance(tp.first_type, types.UndefinedFunctionType) + or tp.first_type.is_precise()) + typeinfer.add_type(self.target, tp.first_type, loc=self.loc) + + +class PairSecondConstraint(object): + def __init__(self, target, pair, loc): + self.target = target + self.pair = pair + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of pair-second at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + for tp in typevars[self.pair.name].get(): + if not isinstance(tp, types.Pair): + # XXX is this an error? + continue + assert tp.second_type.is_precise() + typeinfer.add_type(self.target, tp.second_type, loc=self.loc) + + +class StaticGetItemConstraint(object): + def __init__(self, target, value, index, index_var, loc): + self.target = target + self.value = value + self.index = index + if index_var is not None: + self.fallback = IntrinsicCallConstraint(target, operator.getitem, + (value, index_var), {}, + None, loc) + else: + self.fallback = None + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of static-get-item at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + for ty in typevars[self.value.name].get(): + sig = typeinfer.context.resolve_static_getitem( + value=ty, index=self.index, + ) + + if sig is not None: + itemty = sig.return_type + # if the itemty is not precise, let it through, unification + # will catch it and produce a better error message + typeinfer.add_type(self.target, itemty, loc=self.loc) + elif self.fallback is not None: + self.fallback(typeinfer) + + def get_call_signature(self): + # The signature is only needed for the fallback case in lowering + return self.fallback and self.fallback.get_call_signature() + + +class TypedGetItemConstraint(object): + def __init__(self, target, value, dtype, index, loc): + self.target = target + self.value = value + self.dtype = dtype + self.index = index + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of typed-get-item at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + idx_ty = typevars[self.index.name].get() + ty = typevars[self.value.name].get() + self.signature = Signature(self.dtype, ty + idx_ty, None) + typeinfer.add_type(self.target, self.dtype, loc=self.loc) + + def get_call_signature(self): + return self.signature + + +def fold_arg_vars(typevars, args, vararg, kws): + """ + Fold and resolve the argument variables of a function call. + """ + # Fetch all argument types, bail if any is unknown + n_pos_args = len(args) + kwds = [kw for (kw, var) in kws] + argtypes = [typevars[a.name] for a in args] + argtypes += [typevars[var.name] for (kw, var) in kws] + if vararg is not None: + argtypes.append(typevars[vararg.name]) + + if not all(a.defined for a in argtypes): + return + + args = tuple(a.getone() for a in argtypes) + + pos_args = args[:n_pos_args] + if vararg is not None: + errmsg = "*args in function call should be a tuple, got %s" + # Handle constant literal used for `*args` + if isinstance(args[-1], types.Literal): + const_val = args[-1].literal_value + # Is the constant value a tuple? + if not isinstance(const_val, tuple): + raise TypingError(errmsg % (args[-1],)) + # Append the elements in the const tuple to the positional args + pos_args += const_val + # Handle non-constant + elif not isinstance(args[-1], types.BaseTuple): + # Unsuitable for *args + # (Python is more lenient and accepts all iterables) + raise TypingError(errmsg % (args[-1],)) + else: + # Append the elements in the tuple to the positional args + pos_args += args[-1].types + # Drop the last arg + args = args[:-1] + kw_args = dict(zip(kwds, args[n_pos_args:])) + return pos_args, kw_args + + +def _is_array_not_precise(arrty): + """Check type is array and it is not precise + """ + return isinstance(arrty, types.Array) and not arrty.is_precise() + + +class CallConstraint(object): + """Constraint for calling functions. + Perform case analysis foreach combinations of argument types. + """ + signature = None + + def __init__(self, target, func, args, kws, vararg, loc): + self.target = target + self.func = func + self.args = args + self.kws = kws or {} + self.vararg = vararg + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of call at {loc}", loc=self.loc): + typevars = typeinfer.typevars + with new_error_context( + "resolving caller type: {func}", func=self.func): + fnty = typevars[self.func].getone() + with new_error_context("resolving callee type: {fnty}", + fnty=fnty): + self.resolve(typeinfer, typevars, fnty) + + def resolve(self, typeinfer, typevars, fnty): + assert fnty + context = typeinfer.context + + r = fold_arg_vars(typevars, self.args, self.vararg, self.kws) + if r is None: + # Cannot resolve call type until all argument types are known + return + pos_args, kw_args = r + + # Check argument to be precise + for a in itertools.chain(pos_args, kw_args.values()): + # Forbids imprecise type except array of undefined dtype + if not a.is_precise() and not isinstance(a, types.Array): + return + + # Resolve call type + if isinstance(fnty, types.TypeRef): + # Unwrap TypeRef + fnty = fnty.instance_type + try: + sig = typeinfer.resolve_call(fnty, pos_args, kw_args) + except ForceLiteralArg as e: + # Adjust for bound methods + folding_args = ((fnty.this,) + tuple(self.args) + if isinstance(fnty, types.BoundFunction) + else self.args) + folded = e.fold_arguments(folding_args, self.kws) + requested = set() + unsatisfied = set() + for idx in e.requested_args: + maybe_arg = typeinfer.func_ir.get_definition(folded[idx]) + if isinstance(maybe_arg, ir.Arg): + requested.add(maybe_arg.index) + else: + unsatisfied.add(idx) + if unsatisfied: + raise TypingError("Cannot request literal type.", loc=self.loc) + elif requested: + raise ForceLiteralArg(requested, loc=self.loc) + if sig is None: + # Note: duplicated error checking. + # See types.BaseFunction.get_call_type + # Arguments are invalid => explain why + headtemp = "Invalid use of {0} with parameters ({1})" + args = [str(a) for a in pos_args] + args += ["%s=%s" % (k, v) for k, v in sorted(kw_args.items())] + head = headtemp.format(fnty, ', '.join(map(str, args))) + desc = context.explain_function_type(fnty) + msg = '\n'.join([head, desc]) + raise TypingError(msg) + + typeinfer.add_type(self.target, sig.return_type, loc=self.loc) + + # If the function is a bound function and its receiver type + # was refined, propagate it. + if (isinstance(fnty, types.BoundFunction) + and sig.recvr is not None + and sig.recvr != fnty.this): + refined_this = context.unify_pairs(sig.recvr, fnty.this) + if (refined_this is None and + fnty.this.is_precise() and + sig.recvr.is_precise()): + msg = "Cannot refine type {} to {}".format( + sig.recvr, fnty.this, + ) + raise TypingError(msg, loc=self.loc) + if refined_this is not None and refined_this.is_precise(): + refined_fnty = fnty.copy(this=refined_this) + typeinfer.propagate_refined_type(self.func, refined_fnty) + + # If the return type is imprecise but can be unified with the + # target variable's inferred type, use the latter. + # Useful for code such as:: + # s = set() + # s.add(1) + # (the set() call must be typed as int64(), not undefined()) + if not sig.return_type.is_precise(): + target = typevars[self.target] + if target.defined: + targetty = target.getone() + if context.unify_pairs(targetty, sig.return_type) == targetty: + sig = sig.replace(return_type=targetty) + + self.signature = sig + self._add_refine_map(typeinfer, typevars, sig) + + def _add_refine_map(self, typeinfer, typevars, sig): + """Add this expression to the refine_map base on the type of target_type + """ + target_type = typevars[self.target].getone() + # Array + if (isinstance(target_type, types.Array) + and isinstance(sig.return_type.dtype, types.Undefined)): + typeinfer.refine_map[self.target] = self + # DictType + if (isinstance(target_type, types.DictType) and + not target_type.is_precise()): + typeinfer.refine_map[self.target] = self + + def refine(self, typeinfer, updated_type): + # Is getitem? + if self.func == operator.getitem: + aryty = typeinfer.typevars[self.args[0].name].getone() + # is array not precise? + if _is_array_not_precise(aryty): + # allow refinement of dtype + assert updated_type.is_precise() + newtype = aryty.copy(dtype=updated_type.dtype) + typeinfer.add_type(self.args[0].name, newtype, loc=self.loc) + else: + m = 'no type refinement implemented for function {} updating to {}' + raise TypingError(m.format(self.func, updated_type)) + + def get_call_signature(self): + return self.signature + + +class IntrinsicCallConstraint(CallConstraint): + def __call__(self, typeinfer): + with new_error_context("typing of intrinsic-call at {loc}", + loc=self.loc): + fnty = self.func + if fnty in utils.OPERATORS_TO_BUILTINS: + fnty = typeinfer.resolve_value_type(None, fnty) + self.resolve(typeinfer, typeinfer.typevars, fnty=fnty) + + +class GetAttrConstraint(object): + def __init__(self, target, attr, value, loc, inst): + self.target = target + self.attr = attr + self.value = value + self.loc = loc + self.inst = inst + + def __call__(self, typeinfer): + with new_error_context("typing of get attribute at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + valtys = typevars[self.value.name].get() + for ty in valtys: + attrty = typeinfer.context.resolve_getattr(ty, self.attr) + if attrty is None: + raise UntypedAttributeError(ty, self.attr, + loc=self.inst.loc) + else: + assert attrty.is_precise() + typeinfer.add_type(self.target, attrty, loc=self.loc) + typeinfer.refine_map[self.target] = self + + def refine(self, typeinfer, target_type): + if isinstance(target_type, types.BoundFunction): + recvr = target_type.this + assert recvr.is_precise() + typeinfer.add_type(self.value.name, recvr, loc=self.loc) + source_constraint = typeinfer.refine_map.get(self.value.name) + if source_constraint is not None: + source_constraint.refine(typeinfer, recvr) + + def __repr__(self): + return 'resolving type of attribute "{attr}" of "{value}"'.format( + value=self.value, attr=self.attr) + + +class SetItemRefinement(object): + """A mixin class to provide the common refinement logic in setitem + and static setitem. + """ + + def _refine_target_type(self, typeinfer, targetty, idxty, valty, sig): + """Refine the target-type given the known index type and value type. + """ + # For array setitem, refine imprecise array dtype + if _is_array_not_precise(targetty): + typeinfer.add_type(self.target.name, sig.args[0], loc=self.loc) + # For Dict setitem + if isinstance(targetty, types.DictType): + if not targetty.is_precise(): + refined = targetty.refine(idxty, valty) + typeinfer.add_type( + self.target.name, refined, + loc=self.loc, + ) + elif isinstance(targetty, types.LiteralStrKeyDict): + typeinfer.add_type( + self.target.name, types.DictType(idxty, valty), + loc=self.loc, + ) + + +class SetItemConstraint(SetItemRefinement): + def __init__(self, target, index, value, loc): + self.target = target + self.index = index + self.value = value + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of setitem at {loc}", loc=self.loc): + typevars = typeinfer.typevars + if not all(typevars[var.name].defined + for var in (self.target, self.index, self.value)): + return + targetty = typevars[self.target.name].getone() + idxty = typevars[self.index.name].getone() + valty = typevars[self.value.name].getone() + + sig = typeinfer.context.resolve_setitem(targetty, idxty, valty) + if sig is None: + raise TypingError("Cannot resolve setitem: %s[%s] = %s" % + (targetty, idxty, valty), loc=self.loc) + + self.signature = sig + self._refine_target_type(typeinfer, targetty, idxty, valty, sig) + + def get_call_signature(self): + return self.signature + + +class StaticSetItemConstraint(SetItemRefinement): + def __init__(self, target, index, index_var, value, loc): + self.target = target + self.index = index + self.index_var = index_var + self.value = value + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of staticsetitem at {loc}", + loc=self.loc): + typevars = typeinfer.typevars + if not all(typevars[var.name].defined + for var in (self.target, self.index_var, self.value)): + return + targetty = typevars[self.target.name].getone() + idxty = typevars[self.index_var.name].getone() + valty = typevars[self.value.name].getone() + + sig = typeinfer.context.resolve_static_setitem(targetty, + self.index, valty) + if sig is None: + sig = typeinfer.context.resolve_setitem(targetty, idxty, valty) + if sig is None: + raise TypingError("Cannot resolve setitem: %s[%r] = %s" % + (targetty, self.index, valty), loc=self.loc) + self.signature = sig + self._refine_target_type(typeinfer, targetty, idxty, valty, sig) + + def get_call_signature(self): + return self.signature + + +class DelItemConstraint(object): + def __init__(self, target, index, loc): + self.target = target + self.index = index + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of delitem at {loc}", loc=self.loc): + typevars = typeinfer.typevars + if not all(typevars[var.name].defined + for var in (self.target, self.index)): + return + targetty = typevars[self.target.name].getone() + idxty = typevars[self.index.name].getone() + + sig = typeinfer.context.resolve_delitem(targetty, idxty) + if sig is None: + raise TypingError("Cannot resolve delitem: %s[%s]" % + (targetty, idxty), loc=self.loc) + self.signature = sig + + def get_call_signature(self): + return self.signature + + +class SetAttrConstraint(object): + def __init__(self, target, attr, value, loc): + self.target = target + self.attr = attr + self.value = value + self.loc = loc + + def __call__(self, typeinfer): + with new_error_context("typing of set attribute {attr!r} at {loc}", + attr=self.attr, loc=self.loc): + typevars = typeinfer.typevars + if not all(typevars[var.name].defined + for var in (self.target, self.value)): + return + targetty = typevars[self.target.name].getone() + valty = typevars[self.value.name].getone() + sig = typeinfer.context.resolve_setattr(targetty, self.attr, + valty) + if sig is None: + raise TypingError("Cannot resolve setattr: (%s).%s = %s" % + (targetty, self.attr, valty), + loc=self.loc) + self.signature = sig + + def get_call_signature(self): + return self.signature + + +class PrintConstraint(object): + def __init__(self, args, vararg, loc): + self.args = args + self.vararg = vararg + self.loc = loc + + def __call__(self, typeinfer): + typevars = typeinfer.typevars + + r = fold_arg_vars(typevars, self.args, self.vararg, {}) + if r is None: + # Cannot resolve call type until all argument types are known + return + pos_args, kw_args = r + + fnty = typeinfer.context.resolve_value_type(print) + assert fnty is not None + sig = typeinfer.resolve_call(fnty, pos_args, kw_args) + self.signature = sig + + def get_call_signature(self): + return self.signature + + +class TypeVarMap(dict): + def set_context(self, context): + self.context = context + + def __getitem__(self, name): + if name not in self: + self[name] = TypeVar(self.context, name) + return super(TypeVarMap, self).__getitem__(name) + + def __setitem__(self, name, value): + assert isinstance(name, str) + if name in self: + raise KeyError("Cannot redefine typevar %s" % name) + else: + super(TypeVarMap, self).__setitem__(name, value) + + +# A temporary mapping of {function name: dispatcher object} +_temporary_dispatcher_map = {} +# A temporary mapping of {function name: dispatcher object reference count} +# Reference: https://github.com/numba/numba/issues/3658 +_temporary_dispatcher_map_ref_count = defaultdict(int) + + +@contextlib.contextmanager +def register_dispatcher(disp): + """ + Register a Dispatcher for inference while it is not yet stored + as global or closure variable (e.g. during execution of the @jit() + call). This allows resolution of recursive calls with eager + compilation. + """ + assert callable(disp) + assert callable(disp.py_func) + name = disp.py_func.__name__ + _temporary_dispatcher_map[name] = disp + _temporary_dispatcher_map_ref_count[name] += 1 + try: + yield + finally: + _temporary_dispatcher_map_ref_count[name] -= 1 + if not _temporary_dispatcher_map_ref_count[name]: + del _temporary_dispatcher_map[name] + + +typeinfer_extensions = {} + + +class TypeInferer(object): + """ + Operates on block that shares the same ir.Scope. + """ + + def __init__(self, context, func_ir, warnings): + self.context = context + # sort based on label, ensure iteration order! + self.blocks = OrderedDict() + for k in sorted(func_ir.blocks.keys()): + self.blocks[k] = func_ir.blocks[k] + self.generator_info = func_ir.generator_info + self.func_id = func_ir.func_id + self.func_ir = func_ir + + self.typevars = TypeVarMap() + self.typevars.set_context(context) + self.constraints = ConstraintNetwork() + self.warnings = warnings + + # { index: mangled name } + self.arg_names = {} + # self.return_type = None + # Set of assumed immutable globals + self.assumed_immutables = set() + # Track all calls and associated constraints + self.calls = [] + # The inference result of the above calls + self.calltypes = utils.UniqueDict() + # Target var -> constraint with refine hook + self.refine_map = {} + + if config.DEBUG or config.DEBUG_TYPEINFER: + self.debug = TypeInferDebug(self) + else: + self.debug = NullDebug() + + self._skip_recursion = False + + def copy(self, skip_recursion=False): + clone = TypeInferer(self.context, self.func_ir, self.warnings) + clone.arg_names = self.arg_names.copy() + clone._skip_recursion = skip_recursion + + for k, v in self.typevars.items(): + if not v.locked and v.defined: + clone.typevars[k].add_type(v.getone(), loc=v.define_loc) + + return clone + + def _mangle_arg_name(self, name): + # Disambiguise argument name + return "arg.%s" % (name,) + + def _get_return_vars(self): + rets = [] + for blk in self.blocks.values(): + inst = blk.terminator + if isinstance(inst, ir.Return): + rets.append(inst.value) + return rets + + def get_argument_types(self): + return [self.typevars[k].getone() for k in self.arg_names.values()] + + def seed_argument(self, name, index, typ): + name = self._mangle_arg_name(name) + self.seed_type(name, typ) + self.arg_names[index] = name + + def seed_type(self, name, typ): + """All arguments should be seeded. + """ + self.lock_type(name, typ, loc=None) + + def seed_return(self, typ): + """Seeding of return value is optional. + """ + for var in self._get_return_vars(): + self.lock_type(var.name, typ, loc=None) + + def build_constraint(self): + for blk in self.blocks.values(): + for inst in blk.body: + self.constrain_statement(inst) + + def return_types_from_partial(self): + """ + Resume type inference partially to deduce the return type. + Note: No side-effect to `self`. + + Returns the inferred return type or None if it cannot deduce the return + type. + """ + # Clone the typeinferer and disable typing recursive calls + cloned = self.copy(skip_recursion=True) + # rebuild constraint network + cloned.build_constraint() + # propagate without raising + cloned.propagate(raise_errors=False) + # get return types + rettypes = set() + for retvar in cloned._get_return_vars(): + if retvar.name in cloned.typevars: + typevar = cloned.typevars[retvar.name] + if typevar and typevar.defined: + rettypes.add(types.unliteral(typevar.getone())) + if not rettypes: + return + # unify return types + return cloned._unify_return_types(rettypes) + + def propagate(self, raise_errors=True): + newtoken = self.get_state_token() + oldtoken = None + # Since the number of types are finite, the typesets will eventually + # stop growing. + + while newtoken != oldtoken: + self.debug.propagate_started() + oldtoken = newtoken + # Errors can appear when the type set is incomplete; only + # raise them when there is no progress anymore. + errors = self.constraints.propagate(self) + newtoken = self.get_state_token() + self.debug.propagate_finished() + if errors: + if raise_errors: + force_lit_args = [e for e in errors + if isinstance(e, ForceLiteralArg)] + if not force_lit_args: + raise errors[0] + else: + raise reduce(operator.or_, force_lit_args) + else: + return errors + + def add_type(self, var, tp, loc, unless_locked=False): + assert isinstance(var, str), type(var) + tv = self.typevars[var] + if unless_locked and tv.locked: + return + oldty = tv.type + unified = tv.add_type(tp, loc=loc) + if unified != oldty: + self.propagate_refined_type(var, unified) + + def add_calltype(self, inst, signature): + assert signature is not None + self.calltypes[inst] = signature + + def copy_type(self, src_var, dest_var, loc): + self.typevars[dest_var].union(self.typevars[src_var], loc=loc) + + def lock_type(self, var, tp, loc, literal_value=NOTSET): + tv = self.typevars[var] + tv.lock(tp, loc=loc, literal_value=literal_value) + + def propagate_refined_type(self, updated_var, updated_type): + source_constraint = self.refine_map.get(updated_var) + if source_constraint is not None: + source_constraint.refine(self, updated_type) + + def unify(self, raise_errors=True): + """ + Run the final unification pass over all inferred types, and + catch imprecise types. + """ + typdict = utils.UniqueDict() + + def find_offender(name, exhaustive=False): + # finds the offending variable definition by name + # if exhaustive is set it will try and trace through temporary + # variables to find a concrete offending definition. + offender = None + for block in self.func_ir.blocks.values(): + offender = block.find_variable_assignment(name) + if offender is not None: + if not exhaustive: + break + try: # simple assignment + hasattr(offender.value, 'name') + offender_value = offender.value.name + except (AttributeError, KeyError): + break + orig_offender = offender + if offender_value.startswith('$'): + offender = find_offender(offender_value, + exhaustive=exhaustive) + if offender is None: + offender = orig_offender + break + return offender + + def diagnose_imprecision(offender): + # helper for diagnosing imprecise types + + list_msg = """\n +For Numba to be able to compile a list, the list must have a known and +precise type that can be inferred from the other variables. Whilst sometimes +the type of empty lists can be inferred, this is not always the case, see this +documentation for help: + +https://numba.readthedocs.io/en/stable/user/troubleshoot.html#my-code-has-an-untyped-list-problem +""" + if offender is not None: + # This block deals with imprecise lists + if hasattr(offender, 'value'): + if hasattr(offender.value, 'op'): + # might be `foo = []` + if offender.value.op == 'build_list': + return list_msg + # or might be `foo = list()` + elif offender.value.op == 'call': + try: # assignment involving a call + call_name = offender.value.func.name + # find the offender based on the call name + offender = find_offender(call_name) + if isinstance(offender.value, ir.Global): + if offender.value.name == 'list': + return list_msg + except (AttributeError, KeyError): + pass + return "" # no help possible + + def check_var(name): + tv = self.typevars[name] + if not tv.defined: + if raise_errors: + offender = find_offender(name) + val = getattr(offender, 'value', 'unknown operation') + loc = getattr(offender, 'loc', ir.unknown_loc) + msg = ("Type of variable '%s' cannot be determined, " + "operation: %s, location: %s") + raise TypingError(msg % (var, val, loc), loc) + else: + typdict[var] = types.unknown + return + tp = tv.getone() + + if isinstance(tp, types.UndefinedFunctionType): + tp = tp.get_precise() + + if not tp.is_precise(): + offender = find_offender(name, exhaustive=True) + msg = ("Cannot infer the type of variable '%s'%s, " + "have imprecise type: %s. %s") + istmp = " (temporary variable)" if var.startswith('$') else "" + loc = getattr(offender, 'loc', ir.unknown_loc) + # is this an untyped list? try and provide help + extra_msg = diagnose_imprecision(offender) + if raise_errors: + raise TypingError(msg % (var, istmp, tp, extra_msg), loc) + else: + typdict[var] = types.unknown + return + else: # type is precise, hold it + typdict[var] = tp + + # For better error display, check first user-visible vars, then + # temporaries + temps = set(k for k in self.typevars if not k[0].isalpha()) + others = set(self.typevars) - temps + for var in sorted(others): + check_var(var) + for var in sorted(temps): + check_var(var) + + try: + retty = self.get_return_type(typdict) + except Exception as e: + # partial type inference may raise e.g. attribute error if a + # constraint has no computable signature, ignore this as needed + if raise_errors: + raise e + else: + retty = None + else: + typdict = utils.UniqueDict( + typdict, **{v.name: retty for v in self._get_return_vars()}) + + try: + fntys = self.get_function_types(typdict) + except Exception as e: + # partial type inference may raise e.g. attribute error if a + # constraint has no computable signature, ignore this as needed + if raise_errors: + raise e + else: + fntys = None + + if self.generator_info: + retty = self.get_generator_type(typdict, retty, + raise_errors=raise_errors) + + def check_undef_var_in_calls(): + # Check for undefined variables in the call arguments. + for callnode, calltype in self.calltypes.items(): + if calltype is not None: + for i, v in enumerate(calltype.args, start=1): + if v is types._undef_var: + m = f"undefined variable used in call argument #{i}" + raise TypingError(m, loc=callnode.loc) + + check_undef_var_in_calls() + + self.debug.unify_finished(typdict, retty, fntys) + + return typdict, retty, fntys + + def get_generator_type(self, typdict, retty, raise_errors=True): + gi = self.generator_info + arg_types = [None] * len(self.arg_names) + for index, name in self.arg_names.items(): + arg_types[index] = typdict[name] + + state_types = None + try: + state_types = [typdict[var_name] for var_name in gi.state_vars] + except KeyError: + msg = "Cannot type generator: state variable types cannot be found" + if raise_errors: + raise TypingError(msg) + state_types = [types.unknown for _ in gi.state_vars] + + yield_types = None + try: + yield_types = [typdict[y.inst.value.name] + for y in gi.get_yield_points()] + except KeyError: + msg = "Cannot type generator: yield type cannot be found" + if raise_errors: + raise TypingError(msg) + if not yield_types: + msg = "Cannot type generator: it does not yield any value" + if raise_errors: + raise TypingError(msg) + yield_types = [types.unknown for _ in gi.get_yield_points()] + + if not yield_types or all(yield_types) == types.unknown: + # unknown yield, probably partial type inference, escape + return types.Generator(self.func_id.func, types.unknown, arg_types, + state_types, has_finalizer=True) + + yield_type = self.context.unify_types(*yield_types) + if yield_type is None or isinstance(yield_type, types.Optional): + msg = "Cannot type generator: cannot unify yielded types %s" + yp_highlights = [] + for y in gi.get_yield_points(): + msg = (_termcolor.errmsg("Yield of: IR '%s', type '%s', " + "location: %s")) + yp_highlights.append(msg % (str(y.inst), + typdict[y.inst.value.name], + y.inst.loc.strformat())) + + explain_ty = set() + for ty in yield_types: + if isinstance(ty, types.Optional): + explain_ty.add(ty.type) + explain_ty.add(types.NoneType('none')) + else: + explain_ty.add(ty) + if raise_errors: + raise TypingError("Can't unify yield type from the " + "following types: %s" + % ", ".join(sorted(map(str, explain_ty))) + + "\n\n" + "\n".join(yp_highlights)) + + return types.Generator(self.func_id.func, yield_type, arg_types, + state_types, has_finalizer=True) + + def get_function_types(self, typemap): + """ + Fill and return the calltypes map. + """ + # XXX why can't this be done on the fly? + calltypes = self.calltypes + for call, constraint in self.calls: + calltypes[call] = constraint.get_call_signature() + return calltypes + + def _unify_return_types(self, rettypes): + if rettypes: + unified = self.context.unify_types(*rettypes) + if isinstance(unified, types.FunctionType): + # unified is allowed to be UndefinedFunctionType + # instance (that is imprecise). + return unified + if unified is None or not unified.is_precise(): + def check_type(atype): + lst = [] + for k, v in self.typevars.items(): + if atype == v.type: + lst.append(k) + returns = {} + for x in reversed(lst): + for block in self.func_ir.blocks.values(): + for instr in block.find_insts(ir.Return): + value = instr.value + if isinstance(value, ir.Var): + name = value.name + else: + pass + if x == name: + returns[x] = instr + break + + interped = "" + for name, offender in returns.items(): + loc = getattr(offender, 'loc', ir.unknown_loc) + msg = ("Return of: IR name '%s', type '%s', " + "location: %s") + interped = msg % (name, atype, loc.strformat()) + return interped + + problem_str = [] + for xtype in rettypes: + problem_str.append(_termcolor.errmsg(check_type(xtype))) + + raise TypingError("Can't unify return type from the " + "following types: %s" + % ", ".join(sorted(map(str, rettypes))) + + "\n" + "\n".join(problem_str)) + return unified + else: + # Function without a successful return path + return types.none + + def get_return_type(self, typemap): + rettypes = set() + for var in self._get_return_vars(): + rettypes.add(typemap[var.name]) + retty = self._unify_return_types(rettypes) + # Check return value is not undefined + if retty is types._undef_var: + raise TypingError("return value is undefined") + return retty + + def get_state_token(self): + """The algorithm is monotonic. It can only grow or "refine" the + typevar map. + """ + return [tv.type for name, tv in sorted(self.typevars.items())] + + def constrain_statement(self, inst): + if isinstance(inst, ir.Assign): + self.typeof_assign(inst) + elif isinstance(inst, ir.SetItem): + self.typeof_setitem(inst) + elif isinstance(inst, ir.StaticSetItem): + self.typeof_static_setitem(inst) + elif isinstance(inst, ir.DelItem): + self.typeof_delitem(inst) + elif isinstance(inst, ir.SetAttr): + self.typeof_setattr(inst) + elif isinstance(inst, ir.Print): + self.typeof_print(inst) + elif isinstance(inst, ir.StoreMap): + self.typeof_storemap(inst) + elif isinstance(inst, (ir.Jump, ir.Branch, ir.Return, ir.Del)): + pass + elif isinstance(inst, (ir.DynamicRaise, ir.DynamicTryRaise)): + pass + elif isinstance(inst, (ir.StaticRaise, ir.StaticTryRaise)): + pass + elif isinstance(inst, ir.PopBlock): + pass # It's a marker statement + elif type(inst) in typeinfer_extensions: + # let external calls handle stmt if type matches + f = typeinfer_extensions[type(inst)] + f(inst, self) + else: + msg = "Unsupported constraint encountered: %s" % inst + raise UnsupportedError(msg, loc=inst.loc) + + def typeof_setitem(self, inst): + constraint = SetItemConstraint(target=inst.target, index=inst.index, + value=inst.value, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_storemap(self, inst): + constraint = SetItemConstraint(target=inst.dct, index=inst.key, + value=inst.value, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_static_setitem(self, inst): + constraint = StaticSetItemConstraint(target=inst.target, + index=inst.index, + index_var=inst.index_var, + value=inst.value, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_delitem(self, inst): + constraint = DelItemConstraint(target=inst.target, index=inst.index, + loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_setattr(self, inst): + constraint = SetAttrConstraint(target=inst.target, attr=inst.attr, + value=inst.value, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_print(self, inst): + constraint = PrintConstraint(args=inst.args, vararg=inst.vararg, + loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst, constraint)) + + def typeof_assign(self, inst): + value = inst.value + if isinstance(value, ir.Const): + self.typeof_const(inst, inst.target, value.value) + elif isinstance(value, ir.Var): + self.constraints.append(Propagate(dst=inst.target.name, + src=value.name, loc=inst.loc)) + elif isinstance(value, (ir.Global, ir.FreeVar)): + self.typeof_global(inst, inst.target, value) + elif isinstance(value, ir.Arg): + self.typeof_arg(inst, inst.target, value) + elif isinstance(value, ir.Expr): + self.typeof_expr(inst, inst.target, value) + elif isinstance(value, ir.Yield): + self.typeof_yield(inst, inst.target, value) + else: + msg = ("Unsupported assignment encountered: %s %s" % + (type(value), str(value))) + raise UnsupportedError(msg, loc=inst.loc) + + def resolve_value_type(self, inst, val): + """ + Resolve the type of a simple Python value, such as can be + represented by literals. + """ + try: + return self.context.resolve_value_type(val) + except ValueError as e: + msg = str(e) + raise TypingError(msg, loc=inst.loc) + + def typeof_arg(self, inst, target, arg): + src_name = self._mangle_arg_name(arg.name) + self.constraints.append(ArgConstraint(dst=target.name, + src=src_name, + loc=inst.loc)) + + def typeof_const(self, inst, target, const): + ty = self.resolve_value_type(inst, const) + if inst.value.use_literal_type: + lit = types.maybe_literal(value=const) + else: + lit = None + self.add_type(target.name, lit or ty, loc=inst.loc) + + def typeof_yield(self, inst, target, yield_): + # Sending values into generators isn't supported. + self.add_type(target.name, types.none, loc=inst.loc) + + def sentry_modified_builtin(self, inst, gvar): + """ + Ensure that builtins are not modified. + """ + if gvar.name == 'range' and gvar.value is not range: + bad = True + elif gvar.name == 'slice' and gvar.value is not slice: + bad = True + elif gvar.name == 'len' and gvar.value is not len: + bad = True + else: + bad = False + + if bad: + raise TypingError("Modified builtin '%s'" % gvar.name, + loc=inst.loc) + + def resolve_call(self, fnty, pos_args, kw_args): + """ + Resolve a call to a given function type. A signature is returned. + """ + if isinstance(fnty, types.FunctionType): + return fnty.get_call_type(self, pos_args, kw_args) + if isinstance(fnty, types.RecursiveCall) and not self._skip_recursion: + # Recursive call + disp = fnty.dispatcher_type.dispatcher + pysig, args = disp.fold_argument_types(pos_args, kw_args) + + frame = self.context.callstack.match(disp.py_func, args) + + # If the signature is not being compiled + if frame is None: + sig = self.context.resolve_function_type(fnty.dispatcher_type, + pos_args, kw_args) + fndesc = disp.overloads[args].fndesc + qual = qualifying_prefix(fndesc.modname, fndesc.qualname) + fnty.add_overloads(args, qual, fndesc.uid) + return sig + + fnid = frame.func_id + qual = qualifying_prefix(fnid.modname, fnid.func_qualname) + fnty.add_overloads(args, qual, fnid.unique_id) + # Resume propagation in parent frame + return_type = frame.typeinfer.return_types_from_partial() + # No known return type + if return_type is None: + raise TypingError("cannot type infer runaway recursion") + + sig = typing.signature(return_type, *args) + sig = sig.replace(pysig=pysig) + # Keep track of unique return_type + frame.add_return_type(return_type) + return sig + else: + # Normal non-recursive call + return self.context.resolve_function_type(fnty, pos_args, kw_args) + + def typeof_global(self, inst, target, gvar): + try: + typ = self.resolve_value_type(inst, gvar.value) + except TypingError as e: + if (gvar.name == self.func_id.func_name + and gvar.name in _temporary_dispatcher_map): + # Self-recursion case where the dispatcher is not (yet?) known + # as a global variable + typ = types.Dispatcher(_temporary_dispatcher_map[gvar.name]) + else: + from numba.misc import special + + nm = gvar.name + # check if the problem is actually a name error + func_glbls = self.func_id.func.__globals__ + if (nm not in func_glbls.keys() and + nm not in special.__all__ and + nm not in __builtins__.keys() and + nm not in self.func_id.code.co_freevars): + errstr = "NameError: name '%s' is not defined" + msg = _termcolor.errmsg(errstr % nm) + e.patch_message(msg) + raise + else: + msg = _termcolor.errmsg("Untyped global name '%s':" % nm) + msg += " %s" # interps the actual error + + # if the untyped global is a numba internal function then add + # to the error message asking if it's been imported. + + if nm in special.__all__: + tmp = ("\n'%s' looks like a Numba internal function, has " + "it been imported (i.e. 'from numba import %s')?\n" % + (nm, nm)) + msg += _termcolor.errmsg(tmp) + e.patch_message(msg % e) + raise + + if isinstance(typ, types.Dispatcher) and typ.dispatcher.is_compiling: + # Recursive call + callstack = self.context.callstack + callframe = callstack.findfirst(typ.dispatcher.py_func) + if callframe is not None: + typ = types.RecursiveCall(typ) + else: + raise NotImplementedError( + "call to %s: unsupported recursion" + % typ.dispatcher) + + if isinstance(typ, types.Array): + # Global array in nopython mode is constant + typ = typ.copy(readonly=True) + + if isinstance(typ, types.BaseAnonymousTuple): + # if it's a tuple of literal types, swap the type for the more + # specific literal version + literaled = [types.maybe_literal(x) for x in gvar.value] + if all(literaled): + typ = types.Tuple(literaled) + + # if any of the items in the tuple are arrays, they need to be + # typed as readonly, mutating an array in a global container + # is not supported (should be compile time constant etc). + def mark_array_ro(tup): + newtup = [] + for item in tup.types: + if isinstance(item, types.Array): + item = item.copy(readonly=True) + elif isinstance(item, types.BaseAnonymousTuple): + item = mark_array_ro(item) + newtup.append(item) + return types.BaseTuple.from_types(newtup) + typ = mark_array_ro(typ) + + self.sentry_modified_builtin(inst, gvar) + # Setting literal_value for globals because they are handled + # like const value in numba + lit = types.maybe_literal(gvar.value) + # The user may have provided the type for this variable already. + # In this case, call add_type() to make sure the value type is + # consistent. See numba.tests.test_array_reductions + # TestArrayReductions.test_array_cumsum for examples. + # Variable type locked by using the locals dict. + tv = self.typevars[target.name] + if tv.locked: + tv.add_type(lit or typ, loc=inst.loc) + else: + self.lock_type(target.name, lit or typ, loc=inst.loc) + self.assumed_immutables.add(inst) + + def typeof_expr(self, inst, target, expr): + if expr.op == 'call': + self.typeof_call(inst, target, expr) + elif expr.op in ('getiter', 'iternext'): + self.typeof_intrinsic_call(inst, target, expr.op, expr.value) + elif expr.op == 'exhaust_iter': + constraint = ExhaustIterConstraint(target.name, count=expr.count, + iterator=expr.value, + loc=expr.loc) + self.constraints.append(constraint) + elif expr.op == 'pair_first': + constraint = PairFirstConstraint(target.name, pair=expr.value, + loc=expr.loc) + self.constraints.append(constraint) + elif expr.op == 'pair_second': + constraint = PairSecondConstraint(target.name, pair=expr.value, + loc=expr.loc) + self.constraints.append(constraint) + elif expr.op == 'binop': + self.typeof_intrinsic_call(inst, target, expr.fn, expr.lhs, + expr.rhs) + elif expr.op == 'inplace_binop': + self.typeof_intrinsic_call(inst, target, expr.fn, + expr.lhs, expr.rhs) + elif expr.op == 'unary': + self.typeof_intrinsic_call(inst, target, expr.fn, expr.value) + elif expr.op == 'static_getitem': + constraint = StaticGetItemConstraint(target.name, value=expr.value, + index=expr.index, + index_var=expr.index_var, + loc=expr.loc) + self.constraints.append(constraint) + self.calls.append((inst.value, constraint)) + elif expr.op == 'getitem': + self.typeof_intrinsic_call(inst, target, operator.getitem, + expr.value, expr.index,) + elif expr.op == 'typed_getitem': + constraint = TypedGetItemConstraint(target.name, value=expr.value, + dtype=expr.dtype, + index=expr.index, + loc=expr.loc) + self.constraints.append(constraint) + self.calls.append((inst.value, constraint)) + + elif expr.op == 'getattr': + constraint = GetAttrConstraint(target.name, attr=expr.attr, + value=expr.value, loc=inst.loc, + inst=inst) + self.constraints.append(constraint) + elif expr.op == 'build_tuple': + constraint = BuildTupleConstraint(target.name, items=expr.items, + loc=inst.loc) + self.constraints.append(constraint) + elif expr.op == 'build_list': + constraint = BuildListConstraint(target.name, items=expr.items, + loc=inst.loc) + self.constraints.append(constraint) + elif expr.op == 'build_set': + constraint = BuildSetConstraint(target.name, items=expr.items, + loc=inst.loc) + self.constraints.append(constraint) + elif expr.op == 'build_map': + constraint = BuildMapConstraint( + target.name, + items=expr.items, + special_value=expr.literal_value, + value_indexes=expr.value_indexes, + loc=inst.loc) + self.constraints.append(constraint) + elif expr.op == 'cast': + self.constraints.append(Propagate(dst=target.name, + src=expr.value.name, + loc=inst.loc)) + elif expr.op == 'phi': + for iv in expr.incoming_values: + if iv is not ir.UNDEFINED: + self.constraints.append(Propagate(dst=target.name, + src=iv.name, + loc=inst.loc)) + elif expr.op == 'make_function': + self.lock_type(target.name, types.MakeFunctionLiteral(expr), + loc=inst.loc, literal_value=expr) + + elif expr.op == 'undef': + self.add_type(target.name, types._undef_var, loc=inst.loc) + + else: + msg = "Unsupported op-code encountered: %s" % expr + raise UnsupportedError(msg, loc=inst.loc) + + def typeof_call(self, inst, target, call): + constraint = CallConstraint(target.name, call.func.name, call.args, + call.kws, call.vararg, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst.value, constraint)) + + def typeof_intrinsic_call(self, inst, target, func, *args): + constraint = IntrinsicCallConstraint(target.name, func, args, + kws=(), vararg=None, loc=inst.loc) + self.constraints.append(constraint) + self.calls.append((inst.value, constraint)) + + +class NullDebug(object): + + def propagate_started(self): + pass + + def propagate_finished(self): + pass + + def unify_finished(self, typdict, retty, fntys): + pass + + +class TypeInferDebug(object): + + def __init__(self, typeinfer): + self.typeinfer = typeinfer + + def _dump_state(self): + print('---- type variables ----') + pprint([v for k, v in sorted(self.typeinfer.typevars.items())]) + + def propagate_started(self): + print("propagate".center(80, '-')) + + def propagate_finished(self): + self._dump_state() + + def unify_finished(self, typdict, retty, fntys): + print("Variable types".center(80, "-")) + pprint(typdict) + print("Return type".center(80, "-")) + pprint(retty) + print("Call types".center(80, "-")) + pprint(fntys) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/untyped_passes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/untyped_passes.py new file mode 100644 index 0000000000000000000000000000000000000000..96a1de9ee13a6b7e66d6ebc04b4469b9f5c913e8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/untyped_passes.py @@ -0,0 +1,1815 @@ +from collections import defaultdict, namedtuple +from contextlib import contextmanager +from copy import deepcopy, copy +import warnings + +from numba.core.compiler_machinery import (FunctionPass, AnalysisPass, + SSACompliantMixin, register_pass) +from numba.core import (errors, types, ir, bytecode, postproc, rewrites, config, + transforms, consts) +from numba.misc.special import literal_unroll +from numba.core.analysis import (dead_branch_prune, rewrite_semantic_constants, + find_literally_calls, compute_cfg_from_blocks, + compute_use_defs) +from numba.core.ir_utils import (guard, resolve_func_from_module, simplify_CFG, + GuardException, convert_code_obj_to_function, + build_definitions, + replace_var_names, get_name_var_table, + compile_to_numba_ir, get_definition, + find_max_label, rename_labels, + transfer_scope, fixup_var_define_in_scope, + ) +from numba.core.ssa import reconstruct_ssa +from numba.core import interpreter + + +@contextmanager +def fallback_context(state, msg): + """ + Wraps code that would signal a fallback to object mode + """ + try: + yield + except Exception as e: + if not state.status.can_fallback: + raise + else: + # Clear all references attached to the traceback + e = e.with_traceback(None) + # this emits a warning containing the error message body in the + # case of fallback from npm to objmode + loop_lift = '' if state.flags.enable_looplift else 'OUT' + msg_rewrite = ("\nCompilation is falling back to object mode " + "WITH%s looplifting enabled because %s" + % (loop_lift, msg)) + warnings.warn_explicit('%s due to: %s' % (msg_rewrite, e), + errors.NumbaWarning, + state.func_id.filename, + state.func_id.firstlineno) + raise + + +@register_pass(mutates_CFG=True, analysis_only=False) +class ExtractByteCode(FunctionPass): + _name = "extract_bytecode" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Extract bytecode from function + """ + func_id = state['func_id'] + bc = bytecode.ByteCode(func_id) + if config.DUMP_BYTECODE: + print(bc.dump()) + + state['bc'] = bc + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class TranslateByteCode(FunctionPass): + _name = "translate_bytecode" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Analyze bytecode and translating to Numba IR + """ + func_id = state['func_id'] + bc = state['bc'] + interp = interpreter.Interpreter(func_id) + func_ir = interp.interpret(bc) + state["func_ir"] = func_ir + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class FixupArgs(FunctionPass): + _name = "fixup_args" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + state['nargs'] = state['func_ir'].arg_count + if not state['args'] and state['flags'].force_pyobject: + # Allow an empty argument types specification when object mode + # is explicitly requested. + state['args'] = (types.pyobject,) * state['nargs'] + elif len(state['args']) != state['nargs']: + raise TypeError("Signature mismatch: %d argument types given, " + "but function takes %d arguments" + % (len(state['args']), state['nargs'])) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class IRProcessing(FunctionPass): + _name = "ir_processing" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + func_ir = state['func_ir'] + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + if config.DEBUG or config.DUMP_IR: + name = func_ir.func_id.func_qualname + print(("IR DUMP: %s" % name).center(80, "-")) + func_ir.dump() + if func_ir.is_generator: + print(("GENERATOR INFO: %s" % name).center(80, "-")) + func_ir.dump_generator_info() + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class RewriteSemanticConstants(FunctionPass): + _name = "rewrite_semantic_constants" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + This prunes dead branches, a dead branch is one which is derivable as + not taken at compile time purely based on const/literal evaluation. + """ + assert state.func_ir + msg = ('Internal error in pre-inference dead branch pruning ' + 'pass encountered during compilation of ' + 'function "%s"' % (state.func_id.func_name,)) + with fallback_context(state, msg): + rewrite_semantic_constants(state.func_ir, state.args) + + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class DeadBranchPrune(SSACompliantMixin, FunctionPass): + _name = "dead_branch_prune" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + This prunes dead branches, a dead branch is one which is derivable as + not taken at compile time purely based on const/literal evaluation. + """ + + # purely for demonstration purposes, obtain the analysis from a pass + # declare as a required dependent + semantic_const_analysis = self.get_analysis(type(self)) # noqa + + assert state.func_ir + msg = ('Internal error in pre-inference dead branch pruning ' + 'pass encountered during compilation of ' + 'function "%s"' % (state.func_id.func_name,)) + with fallback_context(state, msg): + dead_branch_prune(state.func_ir, state.args) + + return True + + def get_analysis_usage(self, AU): + AU.add_required(RewriteSemanticConstants) + + +@register_pass(mutates_CFG=True, analysis_only=False) +class InlineClosureLikes(FunctionPass): + _name = "inline_closure_likes" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # Ensure we have an IR and type information. + assert state.func_ir + + # if the return type is a pyobject, there's no type info available and + # no ability to resolve certain typed function calls in the array + # inlining code, use this variable to indicate + typed_pass = not isinstance(state.return_type, types.misc.PyObject) + from numba.core.inline_closurecall import InlineClosureCallPass + inline_pass = InlineClosureCallPass( + state.func_ir, + state.flags.auto_parallel, + state.parfor_diagnostics.replaced_fns, + typed_pass) + inline_pass.run() + + # Remove all Dels, and re-run postproc + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run() + + fixup_var_define_in_scope(state.func_ir.blocks) + + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class GenericRewrites(FunctionPass): + _name = "generic_rewrites" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Perform any intermediate representation rewrites before type + inference. + """ + assert state.func_ir + msg = ('Internal error in pre-inference rewriting ' + 'pass encountered during compilation of ' + 'function "%s"' % (state.func_id.func_name,)) + with fallback_context(state, msg): + rewrites.rewrite_registry.apply('before-inference', state) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class WithLifting(FunctionPass): + _name = "with_lifting" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """ + Extract with-contexts + """ + main, withs = transforms.with_lifting( + func_ir=state.func_ir, + typingctx=state.typingctx, + targetctx=state.targetctx, + flags=state.flags, + locals=state.locals, + ) + if withs: + from numba.core.compiler import compile_ir, _EarlyPipelineCompletion + cres = compile_ir(state.typingctx, state.targetctx, main, + state.args, state.return_type, + state.flags, state.locals, + lifted=tuple(withs), lifted_from=None, + pipeline_class=type(state.pipeline)) + raise _EarlyPipelineCompletion(cres) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class InlineInlinables(FunctionPass): + """ + This pass will inline a function wrapped by the numba.jit decorator directly + into the site of its call depending on the value set in the 'inline' kwarg + to the decorator. + + This is an untyped pass. CFG simplification is performed at the end of the + pass but no block level clean up is performed on the mutated IR (typing + information is not available to do so). + """ + _name = "inline_inlinables" + _DEBUG = False + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + """Run inlining of inlinables + """ + if self._DEBUG: + print('before inline'.center(80, '-')) + print(state.func_ir.dump()) + print(''.center(80, '-')) + + from numba.core.inline_closurecall import (InlineWorker, + callee_ir_validator) + inline_worker = InlineWorker(state.typingctx, + state.targetctx, + state.locals, + state.pipeline, + state.flags, + validator=callee_ir_validator) + + modified = False + # use a work list, look for call sites via `ir.Expr.op == call` and + # then pass these to `self._do_work` to make decisions about inlining. + work_list = list(state.func_ir.blocks.items()) + while work_list: + label, block = work_list.pop() + for i, instr in enumerate(block.body): + if isinstance(instr, ir.Assign): + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + if guard(self._do_work, state, work_list, block, i, + expr, inline_worker): + modified = True + break # because block structure changed + + if modified: + # clean up unconditional branches that appear due to inlined + # functions introducing blocks + cfg = compute_cfg_from_blocks(state.func_ir.blocks) + for dead in cfg.dead_nodes(): + del state.func_ir.blocks[dead] + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run() + state.func_ir.blocks = simplify_CFG(state.func_ir.blocks) + + if self._DEBUG: + print('after inline'.center(80, '-')) + print(state.func_ir.dump()) + print(''.center(80, '-')) + return True + + def _do_work(self, state, work_list, block, i, expr, inline_worker): + from numba.core.compiler import run_frontend + from numba.core.cpu import InlineOptions + + # try and get a definition for the call, this isn't always possible as + # it might be a eval(str)/part generated awaiting update etc. (parfors) + to_inline = None + try: + to_inline = state.func_ir.get_definition(expr.func) + except Exception: + if self._DEBUG: + print("Cannot find definition for %s" % expr.func) + return False + # do not handle closure inlining here, another pass deals with that. + if getattr(to_inline, 'op', False) == 'make_function': + return False + + # see if the definition is a "getattr", in which case walk the IR to + # try and find the python function via the module from which it's + # imported, this should all be encoded in the IR. + if getattr(to_inline, 'op', False) == 'getattr': + val = resolve_func_from_module(state.func_ir, to_inline) + else: + # This is likely a freevar or global + # + # NOTE: getattr 'value' on a call may fail if it's an ir.Expr as + # getattr is overloaded to look in _kws. + try: + val = getattr(to_inline, 'value', False) + except Exception: + raise GuardException + + # if something was found... + if val: + # check it's dispatcher-like, the targetoptions attr holds the + # kwargs supplied in the jit decorator and is where 'inline' will + # be if it is present. + topt = getattr(val, 'targetoptions', False) + if topt: + inline_type = topt.get('inline', None) + # has 'inline' been specified? + if inline_type is not None: + inline_opt = InlineOptions(inline_type) + # Could this be inlinable? + if not inline_opt.is_never_inline: + # yes, it could be inlinable + do_inline = True + pyfunc = val.py_func + # Has it got an associated cost model? + if inline_opt.has_cost_model: + # yes, it has a cost model, use it to determine + # whether to do the inline + py_func_ir = run_frontend(pyfunc) + do_inline = inline_type(expr, state.func_ir, + py_func_ir) + # if do_inline is True then inline! + if do_inline: + _, _, _, new_blocks = \ + inline_worker.inline_function(state.func_ir, + block, i, pyfunc,) + if work_list is not None: + for blk in new_blocks: + work_list.append(blk) + return True + return False + + +@register_pass(mutates_CFG=False, analysis_only=False) +class PreserveIR(AnalysisPass): + """ + Preserves the IR in the metadata + """ + + _name = "preserve_ir" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + state.metadata['preserved_ir'] = state.func_ir.copy() + return False + + +@register_pass(mutates_CFG=False, analysis_only=True) +class FindLiterallyCalls(FunctionPass): + """Find calls to `numba.literally()` and signal if its requirement is not + satisfied. + """ + _name = "find_literally" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + find_literally_calls(state.func_ir, state.args) + return False + + +@register_pass(mutates_CFG=True, analysis_only=False) +class CanonicalizeLoopExit(FunctionPass): + """A pass to canonicalize loop exit by splitting it from function exit. + """ + _name = "canonicalize_loop_exit" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + fir = state.func_ir + cfg = compute_cfg_from_blocks(fir.blocks) + status = False + for loop in cfg.loops().values(): + for exit_label in loop.exits: + if exit_label in cfg.exit_points(): + self._split_exit_block(fir, cfg, exit_label) + status = True + + fir._reset_analysis_variables() + + vlt = postproc.VariableLifetime(fir.blocks) + fir.variable_lifetime = vlt + return status + + def _split_exit_block(self, fir, cfg, exit_label): + curblock = fir.blocks[exit_label] + newlabel = exit_label + 1 + newlabel = find_max_label(fir.blocks) + 1 + fir.blocks[newlabel] = curblock + newblock = ir.Block(scope=curblock.scope, loc=curblock.loc) + newblock.append(ir.Jump(newlabel, loc=curblock.loc)) + fir.blocks[exit_label] = newblock + # Rename all labels + fir.blocks = rename_labels(fir.blocks) + + +@register_pass(mutates_CFG=True, analysis_only=False) +class CanonicalizeLoopEntry(FunctionPass): + """A pass to canonicalize loop header by splitting it from function entry. + + This is needed for loop-lifting; esp in py3.8 + """ + _name = "canonicalize_loop_entry" + _supported_globals = {range, enumerate, zip} + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + fir = state.func_ir + cfg = compute_cfg_from_blocks(fir.blocks) + status = False + for loop in cfg.loops().values(): + if len(loop.entries) == 1: + [entry_label] = loop.entries + if entry_label == cfg.entry_point(): + self._split_entry_block(fir, cfg, loop, entry_label) + status = True + fir._reset_analysis_variables() + + vlt = postproc.VariableLifetime(fir.blocks) + fir.variable_lifetime = vlt + return status + + def _split_entry_block(self, fir, cfg, loop, entry_label): + # Find iterator inputs into the for-loop header + header_block = fir.blocks[loop.header] + deps = set() + for expr in header_block.find_exprs(op="iternext"): + deps.add(expr.value) + # Find the getiter for each iterator + entry_block = fir.blocks[entry_label] + + # Find the start of loop entry statement that needs to be included. + startpt = None + list_of_insts = list(entry_block.find_insts(ir.Assign)) + for assign in reversed(list_of_insts): + if assign.target in deps: + rhs = assign.value + if isinstance(rhs, ir.Var): + if rhs.is_temp: + deps.add(rhs) + elif isinstance(rhs, ir.Expr): + expr = rhs + if expr.op == 'getiter': + startpt = assign + if expr.value.is_temp: + deps.add(expr.value) + elif expr.op == 'call': + defn = guard(get_definition, fir, expr.func) + if isinstance(defn, ir.Global): + if expr.func.is_temp: + deps.add(expr.func) + elif (isinstance(rhs, ir.Global) + and rhs.value in self._supported_globals): + startpt = assign + + if startpt is None: + return + + splitpt = entry_block.body.index(startpt) + new_block = entry_block.copy() + new_block.body = new_block.body[splitpt:] + new_block.loc = new_block.body[0].loc + new_label = find_max_label(fir.blocks) + 1 + entry_block.body = entry_block.body[:splitpt] + entry_block.append(ir.Jump(new_label, loc=new_block.loc)) + + fir.blocks[new_label] = new_block + # Rename all labels + fir.blocks = rename_labels(fir.blocks) + + +@register_pass(mutates_CFG=False, analysis_only=True) +class PrintIRCFG(FunctionPass): + _name = "print_ir_cfg" + + def __init__(self): + FunctionPass.__init__(self) + self._ver = 0 + + def run_pass(self, state): + fir = state.func_ir + self._ver += 1 + fir.render_dot(filename_prefix='v{}'.format(self._ver)).render() + return False + + +@register_pass(mutates_CFG=True, analysis_only=False) +class MakeFunctionToJitFunction(FunctionPass): + """ + This swaps an ir.Expr.op == "make_function" i.e. a closure, for a compiled + function containing the closure body and puts it in ir.Global. It's a 1:1 + statement value swap. `make_function` is already untyped + """ + _name = "make_function_op_code_to_jit_function" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + from numba import njit + func_ir = state.func_ir + mutated = False + for idx, blk in func_ir.blocks.items(): + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, ir.Expr): + if stmt.value.op == "make_function": + node = stmt.value + getdef = func_ir.get_definition + kw_default = getdef(node.defaults) + ok = False + if (kw_default is None or + isinstance(kw_default, ir.Const)): + ok = True + elif isinstance(kw_default, tuple): + ok = all([isinstance(getdef(x), ir.Const) + for x in kw_default]) + elif isinstance(kw_default, ir.Expr): + if kw_default.op != "build_tuple": + continue + ok = all([isinstance(getdef(x), ir.Const) + for x in kw_default.items]) + if not ok: + continue + + pyfunc = convert_code_obj_to_function(node, func_ir) + func = njit()(pyfunc) + new_node = ir.Global(node.code.co_name, func, + stmt.loc) + stmt.value = new_node + mutated |= True + + # if a change was made the del ordering is probably wrong, patch up + if mutated: + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + return mutated + + +@register_pass(mutates_CFG=True, analysis_only=False) +class TransformLiteralUnrollConstListToTuple(FunctionPass): + """ This pass spots a `literal_unroll([])` and rewrites it + as a `literal_unroll(tuple())`. + """ + _name = "transform_literal_unroll_const_list_to_tuple" + + _accepted_types = (types.BaseTuple, types.LiteralList) + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + mutated = False + func_ir = state.func_ir + for label, blk in func_ir.blocks.items(): + calls = [_ for _ in blk.find_exprs('call')] + for call in calls: + glbl = guard(get_definition, func_ir, call.func) + if glbl and isinstance(glbl, (ir.Global, ir.FreeVar)): + # find a literal_unroll + if glbl.value is literal_unroll: + if len(call.args) > 1: + msg = "literal_unroll takes one argument, found %s" + raise errors.UnsupportedError(msg % len(call.args), + call.loc) + # get the arg, make sure its a build_list + unroll_var = call.args[0] + to_unroll = guard(get_definition, func_ir, unroll_var) + if (isinstance(to_unroll, ir.Expr) and + to_unroll.op == "build_list"): + # make sure they are all const items in the list + for i, item in enumerate(to_unroll.items): + val = guard(get_definition, func_ir, item) + if not val: + msg = ("multiple definitions for variable " + "%s, cannot resolve constant") + raise errors.UnsupportedError(msg % item, + to_unroll.loc) + if not isinstance(val, ir.Const): + msg = ("Found non-constant value at " + "position %s in a list argument to " + "literal_unroll" % i) + raise errors.UnsupportedError(msg, + to_unroll.loc) + # The above appears ok, now swap the build_list for + # a built tuple. + + # find the assignment for the unroll target + to_unroll_lhs = guard(get_definition, func_ir, + unroll_var, lhs_only=True) + + if to_unroll_lhs is None: + msg = ("multiple definitions for variable " + "%s, cannot resolve constant") + raise errors.UnsupportedError(msg % unroll_var, + to_unroll.loc) + # scan all blocks looking for the LHS + for b in func_ir.blocks.values(): + asgn = b.find_variable_assignment( + to_unroll_lhs.name) + if asgn is not None: + break + else: + msg = ("Cannot find assignment for known " + "variable %s") % to_unroll_lhs.name + raise errors.CompilerError(msg, to_unroll.loc) + + # Create a tuple with the list items as contents + tup = ir.Expr.build_tuple(to_unroll.items, + to_unroll.loc) + + # swap the list for the tuple + asgn.value = tup + mutated = True + elif (isinstance(to_unroll, ir.Expr) and + to_unroll.op == "build_tuple"): + # this is fine, do nothing + pass + elif (isinstance(to_unroll, (ir.Global, ir.FreeVar)) and + isinstance(to_unroll.value, tuple)): + # this is fine, do nothing + pass + elif isinstance(to_unroll, ir.Arg): + # this is only fine if the arg is a tuple + ty = state.typemap[to_unroll.name] + if not isinstance(ty, self._accepted_types): + msg = ("Invalid use of literal_unroll with a " + "function argument, only tuples are " + "supported as function arguments, found " + "%s") % ty + raise errors.UnsupportedError(msg, + to_unroll.loc) + else: + extra = None + if isinstance(to_unroll, ir.Expr): + # probably a slice + if to_unroll.op == "getitem": + ty = state.typemap[to_unroll.value.name] + # check if this is a tuple slice + if not isinstance(ty, self._accepted_types): + extra = "operation %s" % to_unroll.op + loc = to_unroll.loc + elif isinstance(to_unroll, ir.Arg): + extra = "non-const argument %s" % to_unroll.name + loc = to_unroll.loc + else: + if to_unroll is None: + extra = ('multiple definitions of ' + 'variable "%s".' % unroll_var.name) + loc = unroll_var.loc + else: + loc = to_unroll.loc + extra = "unknown problem" + + if extra: + msg = ("Invalid use of literal_unroll, " + "argument should be a tuple or a list " + "of constant values. Failure reason: " + "found %s" % extra) + raise errors.UnsupportedError(msg, loc) + return mutated + + +@register_pass(mutates_CFG=True, analysis_only=False) +class MixedContainerUnroller(FunctionPass): + _name = "mixed_container_unroller" + + _DEBUG = False + + _accepted_types = (types.BaseTuple, types.LiteralList) + + def __init__(self): + FunctionPass.__init__(self) + + def analyse_tuple(self, tup): + """ + Returns a map of type->list(indexes) for a typed tuple + """ + d = defaultdict(list) + for i, ty in enumerate(tup): + d[ty].append(i) + return d + + def add_offset_to_labels_w_ignore(self, blocks, offset, ignore=None): + """add an offset to all block labels and jump/branch targets + don't add an offset to anything in the ignore list + """ + if ignore is None: + ignore = set() + + new_blocks = {} + for l, b in blocks.items(): + # some parfor last blocks might be empty + term = None + if b.body: + term = b.body[-1] + if isinstance(term, ir.Jump): + if term.target not in ignore: + b.body[-1] = ir.Jump(term.target + offset, term.loc) + if isinstance(term, ir.Branch): + if term.truebr not in ignore: + new_true = term.truebr + offset + else: + new_true = term.truebr + + if term.falsebr not in ignore: + new_false = term.falsebr + offset + else: + new_false = term.falsebr + b.body[-1] = ir.Branch(term.cond, new_true, new_false, term.loc) + new_blocks[l + offset] = b + return new_blocks + + def inject_loop_body(self, switch_ir, loop_ir, caller_max_label, + dont_replace, switch_data): + """ + Injects the "loop body" held in `loop_ir` into `switch_ir` where ever + there is a statement of the form `SENTINEL. = RHS`. It also: + * Finds and then deliberately does not relabel non-local jumps so as to + make the switch table suitable for injection into the IR from which + the loop body was derived. + * Looks for `typed_getitem` and wires them up to loop body version + specific variables or, if possible, directly writes in their constant + value at their use site. + + Args: + - switch_ir, the switch table with SENTINELS as generated by + self.gen_switch + - loop_ir, the IR of the loop blocks (derived from the original func_ir) + - caller_max_label, the maximum label in the func_ir caller + - dont_replace, variables that should not be renamed (to handle + references to variables that are incoming at the loop head/escaping at + the loop exit. + - switch_data, the switch table data used to generated the switch_ir, + can be generated by self.analyse_tuple. + + Returns: + - A type specific switch table with each case containing a versioned + loop body suitable for injection as a replacement for the loop_ir. + """ + + # Switch IR came from code gen, immediately relabel to prevent + # collisions with IR derived from the user code (caller) + switch_ir.blocks = self.add_offset_to_labels_w_ignore( + switch_ir.blocks, caller_max_label + 1) + + # Find the sentinels and validate the form + sentinel_exits = set() + sentinel_blocks = [] + for lbl, blk in switch_ir.blocks.items(): + for i, stmt in enumerate(blk.body): + if isinstance(stmt, ir.Assign): + if "SENTINEL" in stmt.target.name: + sentinel_blocks.append(lbl) + sentinel_exits.add(blk.body[-1].target) + break + + assert len(sentinel_exits) == 1 # should only be 1 exit + switch_ir.blocks.pop(sentinel_exits.pop()) # kill the exit, it's dead + + # find jumps that are non-local, we won't relabel these + ignore_set = set() + local_lbl = [x for x in loop_ir.blocks.keys()] + for lbl, blk in loop_ir.blocks.items(): + for i, stmt in enumerate(blk.body): + if isinstance(stmt, ir.Jump): + if stmt.target not in local_lbl: + ignore_set.add(stmt.target) + if isinstance(stmt, ir.Branch): + if stmt.truebr not in local_lbl: + ignore_set.add(stmt.truebr) + if stmt.falsebr not in local_lbl: + ignore_set.add(stmt.falsebr) + + # make sure the generated switch table matches the switch data + assert len(sentinel_blocks) == len(switch_data) + + # replace the sentinel_blocks with the loop body + for lbl, branch_ty in zip(sentinel_blocks, switch_data.keys()): + loop_blocks = deepcopy(loop_ir.blocks) + # relabel blocks WRT switch table, each block replacement will shift + # the maximum label + max_label = max(switch_ir.blocks.keys()) + loop_blocks = self.add_offset_to_labels_w_ignore( + loop_blocks, max_label + 1, ignore_set) + + # start label + loop_start_lbl = min(loop_blocks.keys()) + + # fix the typed_getitem locations in the loop blocks + for blk in loop_blocks.values(): + new_body = [] + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if (isinstance(stmt.value, ir.Expr) and + stmt.value.op == "typed_getitem"): + if isinstance(branch_ty, types.Literal): + scope = switch_ir.blocks[lbl].scope + new_const_name = scope.redefine( + "branch_const", stmt.loc).name + new_const_var = ir.Var( + blk.scope, new_const_name, stmt.loc) + new_const_val = ir.Const( + branch_ty.literal_value, stmt.loc) + const_assign = ir.Assign( + new_const_val, new_const_var, stmt.loc) + new_assign = ir.Assign( + new_const_var, stmt.target, stmt.loc) + new_body.append(const_assign) + new_body.append(new_assign) + dont_replace.append(new_const_name) + else: + orig = stmt.value + new_typed_getitem = ir.Expr.typed_getitem( + value=orig.value, dtype=branch_ty, + index=orig.index, loc=orig.loc) + new_assign = ir.Assign( + new_typed_getitem, stmt.target, stmt.loc) + new_body.append(new_assign) + else: + new_body.append(stmt) + else: + new_body.append(stmt) + blk.body = new_body + + # rename + var_table = get_name_var_table(loop_blocks) + drop_keys = [] + for k, v in var_table.items(): + if v.name in dont_replace: + drop_keys.append(k) + for k in drop_keys: + var_table.pop(k) + + new_var_dict = {} + for name, var in var_table.items(): + scope = switch_ir.blocks[lbl].scope + try: + scope.get_exact(name) + except errors.NotDefinedError: + # In case the scope doesn't have the variable, we need to + # define it prior creating new copies of it! This is + # because the scope of the function and the scope of the + # loop are different and the variable needs to be redefined + # within the scope of the loop. + scope.define(name, var.loc) + new_var_dict[name] = scope.redefine(name, var.loc).name + replace_var_names(loop_blocks, new_var_dict) + + # clobber the sentinel body and then stuff in the rest + switch_ir.blocks[lbl] = deepcopy(loop_blocks[loop_start_lbl]) + remaining_keys = [y for y in loop_blocks.keys()] + remaining_keys.remove(loop_start_lbl) + for k in remaining_keys: + switch_ir.blocks[k] = deepcopy(loop_blocks[k]) + + if self._DEBUG: + print("-" * 80 + "EXIT STUFFER") + switch_ir.dump() + print("-" * 80) + + return switch_ir + + def gen_switch(self, data, index): + """ + Generates a function with a switch table like + def foo(): + if PLACEHOLDER_INDEX in (): + SENTINEL = None + elif PLACEHOLDER_INDEX in (): + SENTINEL = None + ... + else: + raise RuntimeError + + The data is a map of (type : indexes) for example: + (int64, int64, float64) + might give: + {int64: [0, 1], float64: [2]} + + The index is the index variable for the driving range loop over the + mixed tuple. + """ + elif_tplt = "\n\telif PLACEHOLDER_INDEX in (%s,):\n\t\tSENTINEL = None" + + # Note regarding the insertion of the garbage/defeat variables below: + # These values have been designed and inserted to defeat a specific + # behaviour of the cpython optimizer. The optimization was introduced + # in Python 3.10. + + # The URL for the BPO is: + # https://bugs.python.org/issue44626 + # The code for the optimization can be found at: + # https://github.com/python/cpython/blob/d41abe8/Python/compile.c#L7533-L7557 + + # Essentially the CPython optimizer will inline the exit block under + # certain circumstances and thus replace the jump with a return if the + # exit block is small enough. This is an issue for unroller, as it + # looks for a jump, not a return, when it inserts the generated switch + # table. + + # Part of the condition for this optimization to be applied is that the + # exit block not exceed a certain (4 at the time of writing) number of + # bytecode instructions. We defeat the optimizer by inserting a + # sufficient number of instructions so that the exit block is big + # enough. We don't care about this garbage, because the generated exit + # block is discarded anyway when we smash the switch table into the + # original function and so all the inserted garbage is dropped again. + + # The final lines of the stacktrace w/o this will look like: + # + # File "/numba/numba/core/untyped_passes.py", line 830, \ + # in inject_loop_body + # sentinel_exits.add(blk.body[-1].target) + # AttributeError: Failed in nopython mode pipeline \ + # (step: handles literal_unroll) + # Failed in literal_unroll_subpipeline mode pipeline \ + # (step: performs mixed container unroll) + # 'Return' object has no attribute 'target' + # + # Which indicates that a Return has been found instead of a Jump + + b = ('def foo():\n\tif PLACEHOLDER_INDEX in (%s,):\n\t\t' + 'SENTINEL = None\n%s\n\telse:\n\t\t' + 'raise RuntimeError("Unreachable")\n\t' + 'py310_defeat1 = 1\n\t' + 'py310_defeat2 = 2\n\t' + 'py310_defeat3 = 3\n\t' + 'py310_defeat4 = 4\n\t' + ) + keys = [k for k in data.keys()] + + elifs = [] + for i in range(1, len(keys)): + elifs.append(elif_tplt % ','.join(map(str, data[keys[i]]))) + src = b % (','.join(map(str, data[keys[0]])), ''.join(elifs)) + wstr = src + l = {} + exec(wstr, {}, l) + bfunc = l['foo'] + branches = compile_to_numba_ir(bfunc, {}) + for lbl, blk in branches.blocks.items(): + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, ir.Global): + if stmt.value.name == "PLACEHOLDER_INDEX": + stmt.value = index + return branches + + def apply_transform(self, state): + # compute new CFG + func_ir = state.func_ir + cfg = compute_cfg_from_blocks(func_ir.blocks) + # find loops + loops = cfg.loops() + + # 0. Find the loops containing literal_unroll and store this + # information + unroll_info = namedtuple( + "unroll_info", [ + "loop", "call", "arg", "getitem"]) + + def get_call_args(init_arg, want): + # Chases the assignment of a called value back through a specific + # call to a global function "want" and returns the arguments + # supplied to that function's call + some_call = get_definition(func_ir, init_arg) + if not isinstance(some_call, ir.Expr): + raise GuardException + if not some_call.op == "call": + raise GuardException + the_global = get_definition(func_ir, some_call.func) + if not isinstance(the_global, ir.Global): + raise GuardException + if the_global.value is not want: + raise GuardException + return some_call + + def find_unroll_loops(loops): + """This finds loops which are compliant with the form: + for i in range(len(literal_unroll(>)))""" + unroll_loops = {} + for header_lbl, loop in loops.items(): + # TODO: check the loop head has literal_unroll, if it does but + # does not conform to the following then raise + + # scan loop header + iternexts = [_ for _ in + func_ir.blocks[loop.header].find_exprs('iternext')] + # needs to be an single iternext driven loop + if len(iternexts) != 1: + continue + for iternext in iternexts: + # Walk the canonicalised loop structure and check it + # Check loop form range(literal_unroll(container))) + phi = guard(get_definition, func_ir, iternext.value) + if phi is None: + continue + + # check call global "range" + range_call = guard(get_call_args, phi.value, range) + if range_call is None: + continue + range_arg = range_call.args[0] + + # check call global "len" + len_call = guard(get_call_args, range_arg, len) + if len_call is None: + continue + len_arg = len_call.args[0] + + # check literal_unroll + literal_unroll_call = guard(get_definition, func_ir, + len_arg) + if literal_unroll_call is None: + continue + if not isinstance(literal_unroll_call, ir.Expr): + continue + if literal_unroll_call.op != "call": + continue + literal_func = getattr(literal_unroll_call, 'func', None) + if not literal_func: + continue + call_func = guard(get_definition, func_ir, + literal_unroll_call.func) + if call_func is None: + continue + call_func_value = call_func.value + + if call_func_value is literal_unroll: + assert len(literal_unroll_call.args) == 1 + unroll_loops[loop] = literal_unroll_call + return unroll_loops + + def ensure_no_nested_unroll(unroll_loops): + # Validate loop nests, nested literal_unroll loops are unsupported. + # This doesn't check that there's a getitem or anything else + # required for the transform to work, simply just that there's no + # nesting. + for test_loop in unroll_loops: + for ref_loop in unroll_loops: + if test_loop == ref_loop: # comparing to self! skip + continue + if test_loop.header in ref_loop.body: + msg = ("Nesting of literal_unroll is unsupported") + loc = func_ir.blocks[test_loop.header].loc + raise errors.UnsupportedError(msg, loc) + + def collect_literal_unroll_info(literal_unroll_loops): + """Finds the loops induced by `literal_unroll`, returns a list of + unroll_info namedtuples for use in the transform pass. + """ + + literal_unroll_info = [] + for loop, literal_unroll_call in literal_unroll_loops.items(): + arg = literal_unroll_call.args[0] + typemap = state.typemap + resolved_arg = guard(get_definition, func_ir, arg, + lhs_only=True) + ty = typemap[resolved_arg.name] + assert isinstance(ty, self._accepted_types) + # loop header is spelled ok, now make sure the body + # actually contains a getitem + + # find a "getitem"... only looks in the blocks that belong + # _solely_ to this literal_unroll (there should not be nested + # literal_unroll loops, this is unsupported). + tuple_getitem = None + for lbli in loop.body: + blk = func_ir.blocks[lbli] + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if (isinstance(stmt.value, ir.Expr) and + stmt.value.op == "getitem"): + # check for something like a[i] + if stmt.value.value != arg: + # that failed, so check for the + # definition + dfn = guard(get_definition, func_ir, + stmt.value.value) + if dfn is None: + continue + try: + args = getattr(dfn, 'args', False) + except KeyError: + continue + if not args: + continue + if not args[0] == arg: + continue + target_ty = state.typemap[arg.name] + if not isinstance(target_ty, + self._accepted_types): + continue + tuple_getitem = stmt + break + if tuple_getitem: + break + else: + continue # no getitem in this loop + + ui = unroll_info(loop, literal_unroll_call, arg, + tuple_getitem) + literal_unroll_info.append(ui) + return literal_unroll_info + + # 1. Collect info about the literal_unroll loops, ensure they are legal + literal_unroll_loops = find_unroll_loops(loops) + # validate + ensure_no_nested_unroll(literal_unroll_loops) + # assemble info + literal_unroll_info = collect_literal_unroll_info(literal_unroll_loops) + if not literal_unroll_info: + return False + + # 2. Do the unroll, get a loop and process it! + info = literal_unroll_info[0] + self.unroll_loop(state, info) + + # 3. Rebuild the state, the IR has taken a hammering + func_ir.blocks = simplify_CFG(func_ir.blocks) + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + if self._DEBUG: + print('-' * 80 + "END OF PASS, SIMPLIFY DONE") + func_ir.dump() + func_ir._definitions = build_definitions(func_ir.blocks) + return True + + def unroll_loop(self, state, loop_info): + # The general idea here is to: + # 1. Find *a* getitem that conforms to the literal_unroll semantic, + # i.e. one that is targeting a tuple with a loop induced index + # 2. Compute a structure from the tuple that describes which + # iterations of a loop will have which type + # 3. Generate a switch table in IR form for the structure in 2 + # 4. Switch out getitems for the tuple for a `typed_getitem` + # 5. Inject switch table as replacement loop body + # 6. Patch up + func_ir = state.func_ir + getitem_target = loop_info.arg + target_ty = state.typemap[getitem_target.name] + assert isinstance(target_ty, self._accepted_types) + + # 1. find a "getitem" that conforms + tuple_getitem = [] + for lbl in loop_info.loop.body: + blk = func_ir.blocks[lbl] + for stmt in blk.body: + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, + ir.Expr) and stmt.value.op == "getitem": + # try a couple of spellings... a[i] and ref(a)[i] + if stmt.value.value != getitem_target: + dfn = func_ir.get_definition(stmt.value.value) + try: + args = getattr(dfn, 'args', False) + except KeyError: + continue + if not args: + continue + if not args[0] == getitem_target: + continue + target_ty = state.typemap[getitem_target.name] + if not isinstance(target_ty, self._accepted_types): + continue + tuple_getitem.append(stmt) + + if not tuple_getitem: + msg = ("Loop unrolling analysis has failed, there's no getitem " + "in loop body that conforms to literal_unroll " + "requirements.") + LOC = func_ir.blocks[loop_info.loop.header].loc + raise errors.CompilerError(msg, LOC) + + # 2. get switch data + switch_data = self.analyse_tuple(target_ty) + + # 3. generate switch IR + index = func_ir._definitions[tuple_getitem[0].value.index.name][0] + branches = self.gen_switch(switch_data, index) + + # 4. swap getitems for a typed_getitem, these are actually just + # placeholders at this point. When the loop is duplicated they can + # be swapped for a typed_getitem of the correct type or if the item + # is literal it can be shoved straight into the duplicated loop body + for item in tuple_getitem: + old = item.value + new = ir.Expr.typed_getitem( + old.value, types.void, old.index, old.loc) + item.value = new + + # 5. Inject switch table + + # Find the actual loop without the header (that won't get replaced) + # and derive some new IR for this set of blocks + this_loop = loop_info.loop + this_loop_body = this_loop.body - \ + set([this_loop.header]) + loop_blocks = { + x: func_ir.blocks[x] for x in this_loop_body} + new_ir = func_ir.derive(loop_blocks) + + # Work out what is live on entry and exit so as to prevent + # replacement (defined vars can escape, used vars live at the header + # need to remain as-is so their references are correct, they can + # also escape). + + usedefs = compute_use_defs(func_ir.blocks) + idx = this_loop.header + keep = set() + keep |= usedefs.usemap[idx] | usedefs.defmap[idx] + keep |= func_ir.variable_lifetime.livemap[idx] + dont_replace = [x for x in (keep)] + + # compute the unrolled body + unrolled_body = self.inject_loop_body( + branches, new_ir, max(func_ir.blocks.keys()) + 1, + dont_replace, switch_data) + + # 6. Patch in the unrolled body and fix up + blks = state.func_ir.blocks + the_scope = next(iter(blks.values())).scope + orig_lbl = tuple(this_loop_body) + + replace, *delete = orig_lbl + unroll, header_block = unrolled_body, this_loop.header + unroll_lbl = [x for x in sorted(unroll.blocks.keys())] + blks[replace] = transfer_scope(unroll.blocks[unroll_lbl[0]], the_scope) + [blks.pop(d) for d in delete] + for k in unroll_lbl[1:]: + blks[k] = transfer_scope(unroll.blocks[k], the_scope) + # stitch up the loop predicate true -> new loop body jump + blks[header_block].body[-1].truebr = replace + + def run_pass(self, state): + mutated = False + func_ir = state.func_ir + # first limit the work by squashing the CFG if possible + func_ir.blocks = simplify_CFG(func_ir.blocks) + + if self._DEBUG: + print("-" * 80 + "PASS ENTRY") + func_ir.dump() + print("-" * 80) + + # limitations: + # 1. No nested unrolls + # 2. Opt in via `numba.literal_unroll` + # 3. No multiple mix-tuple use + + # keep running the transform loop until it reports no more changes + while (True): + stat = self.apply_transform(state) + mutated |= stat + if not stat: + break + + # reset type inference now we are done with the partial results + state.typemap = {} + state.calltypes = None + + return mutated + + +@register_pass(mutates_CFG=True, analysis_only=False) +class IterLoopCanonicalization(FunctionPass): + """ Transforms loops that are induced by `getiter` into range() driven loops + If the typemap is available this will only impact Tuple and UniTuple, if it + is not available it will impact all matching loops. + """ + _name = "iter_loop_canonicalisation" + + _DEBUG = False + + # if partial typing info is available it will only look at these types + _accepted_types = (types.BaseTuple, types.LiteralList) + _accepted_calls = (literal_unroll,) + + def __init__(self): + FunctionPass.__init__(self) + + def assess_loop(self, loop, func_ir, partial_typemap=None): + # it's a iter loop if: + # - loop header is driven by an iternext + # - the iternext value is a phi derived from getiter() + + # check header + iternexts = [_ for _ in + func_ir.blocks[loop.header].find_exprs('iternext')] + if len(iternexts) != 1: + return False + for iternext in iternexts: + phi = guard(get_definition, func_ir, iternext.value) + if phi is None: + return False + if getattr(phi, 'op', False) == 'getiter': + if partial_typemap: + # check that the call site is accepted, until we're + # confident that tuple unrolling is behaving require opt-in + # guard of `literal_unroll`, remove this later! + phi_val_defn = guard(get_definition, func_ir, phi.value) + if not isinstance(phi_val_defn, ir.Expr): + return False + if not phi_val_defn.op == "call": + return False + call = guard(get_definition, func_ir, phi_val_defn) + if call is None or len(call.args) != 1: + return False + func_var = guard(get_definition, func_ir, call.func) + func = guard(get_definition, func_ir, func_var) + if func is None or not isinstance(func, + (ir.Global, ir.FreeVar)): + return False + if (func.value is None or + func.value not in self._accepted_calls): + return False + + # now check the type is supported + ty = partial_typemap.get(call.args[0].name, None) + if ty and isinstance(ty, self._accepted_types): + return len(loop.entries) == 1 + else: + return len(loop.entries) == 1 + + def transform(self, loop, func_ir, cfg): + def get_range(a): + return range(len(a)) + + iternext = [_ for _ in + func_ir.blocks[loop.header].find_exprs('iternext')][0] + LOC = func_ir.blocks[loop.header].loc + scope = func_ir.blocks[loop.header].scope + get_range_var = scope.redefine("CANONICALISER_get_range_gbl", LOC) + get_range_global = ir.Global('get_range', get_range, LOC) + assgn = ir.Assign(get_range_global, get_range_var, LOC) + + loop_entry = tuple(loop.entries)[0] + entry_block = func_ir.blocks[loop_entry] + entry_block.body.insert(0, assgn) + + iterarg = guard(get_definition, func_ir, iternext.value) + if iterarg is not None: + iterarg = iterarg.value + + # look for iternext + idx = 0 + for stmt in entry_block.body: + if isinstance(stmt, ir.Assign): + if isinstance(stmt.value, + ir.Expr) and stmt.value.op == 'getiter': + break + idx += 1 + else: + raise ValueError("problem") + + # create a range(len(tup)) and inject it + call_get_range_var = scope.redefine('CANONICALISER_call_get_range', LOC) + make_call = ir.Expr.call(get_range_var, (stmt.value.value,), (), LOC) + assgn_call = ir.Assign(make_call, call_get_range_var, LOC) + entry_block.body.insert(idx, assgn_call) + entry_block.body[idx + 1].value.value = call_get_range_var + + glbls = copy(func_ir.func_id.func.__globals__) + from numba.core.inline_closurecall import inline_closure_call + inline_closure_call(func_ir, glbls, entry_block, idx, get_range,) + kill = entry_block.body.index(assgn) + entry_block.body.pop(kill) + + # find the induction variable + references in the loop header + # fixed point iter to do this, it's a bit clunky + induction_vars = set() + header_block = func_ir.blocks[loop.header] + + # find induction var + ind = [x for x in header_block.find_exprs('pair_first')] + for x in ind: + induction_vars.add(func_ir.get_assignee(x, loop.header)) + # find aliases of the induction var + tmp = set() + for x in induction_vars: + try: # there's not always an alias, e.g. loop from inlined closure + tmp.add(func_ir.get_assignee(x, loop.header)) + except ValueError: + pass + induction_vars |= tmp + induction_var_names = set([x.name for x in induction_vars]) + + # Find the downstream blocks that might reference the induction var + succ = set() + for lbl in loop.exits: + succ |= set([x[0] for x in cfg.successors(lbl)]) + check_blocks = (loop.body | loop.exits | succ) ^ {loop.header} + + # replace RHS use of induction var with getitem + for lbl in check_blocks: + for stmt in func_ir.blocks[lbl].body: + if isinstance(stmt, ir.Assign): + # check for aliases + try: + lookup = getattr(stmt.value, 'name', None) + except KeyError: + continue + if lookup and lookup in induction_var_names: + stmt.value = ir.Expr.getitem( + iterarg, stmt.value, stmt.loc) + + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + def run_pass(self, state): + func_ir = state.func_ir + cfg = compute_cfg_from_blocks(func_ir.blocks) + loops = cfg.loops() + + mutated = False + for header, loop in loops.items(): + stat = self.assess_loop(loop, func_ir, state.typemap) + if stat: + if self._DEBUG: + print("Canonicalising loop", loop) + self.transform(loop, func_ir, cfg) + mutated = True + else: + if self._DEBUG: + print("NOT Canonicalising loop", loop) + + func_ir.blocks = simplify_CFG(func_ir.blocks) + return mutated + + +@register_pass(mutates_CFG=False, analysis_only=False) +class PropagateLiterals(FunctionPass): + """Implement literal propagation based on partial type inference""" + _name = "PropagateLiterals" + + def __init__(self): + FunctionPass.__init__(self) + + def get_analysis_usage(self, AU): + AU.add_required(ReconstructSSA) + + def run_pass(self, state): + func_ir = state.func_ir + typemap = state.typemap + flags = state.flags + + accepted_functions = ('isinstance', 'hasattr') + + if not hasattr(func_ir, '_definitions') \ + and not flags.enable_ssa: + func_ir._definitions = build_definitions(func_ir.blocks) + + changed = False + + for block in func_ir.blocks.values(): + for assign in block.find_insts(ir.Assign): + value = assign.value + if isinstance(value, (ir.Arg, ir.Const, ir.FreeVar, ir.Global)): + continue + + # 1) Don't change return stmt in the form + # $return_xyz = cast(value=ABC) + # 2) Don't propagate literal values that are not primitives + if isinstance(value, ir.Expr) and \ + value.op in ('cast', 'build_map', 'build_list', + 'build_tuple', 'build_set'): + continue + + target = assign.target + if not flags.enable_ssa: + # SSA is disabled when doing inlining + if guard(get_definition, func_ir, target.name) is None: # noqa: E501 + continue + + # Numba cannot safely determine if an isinstance call + # with a PHI node is True/False. For instance, in + # the case below, the partial type inference step can coerce + # '$z' to float, so any call to 'isinstance(z, int)' would fail. + # + # def fn(x): + # if x > 4: + # z = 1 + # else: + # z = 3.14 + # if isinstance(z, int): + # print('int') + # else: + # print('float') + # + # At the moment, one avoid propagating the literal + # value if the argument is a PHI node + + if isinstance(value, ir.Expr) and value.op == 'call': + + fn = guard(get_definition, func_ir, value.func.name) + if fn is None: + continue + + if not (isinstance(fn, ir.Global) and fn.name in + accepted_functions): + continue + + for arg in value.args: + # check if any of the args to isinstance is a PHI node + iv = func_ir._definitions[arg.name] + assert len(iv) == 1 # SSA! + if isinstance(iv[0], ir.Expr) and iv[0].op == 'phi': + msg = (f'{fn.name}() cannot determine the ' + f'type of variable "{arg.unversioned_name}" ' + 'due to a branch.') + raise errors.NumbaTypeError(msg, loc=assign.loc) + + # Only propagate a PHI node if all arguments are the same + # constant + if isinstance(value, ir.Expr) and value.op == 'phi': + # typemap will return None in case `inc.name` not in typemap + v = [typemap.get(inc.name) for inc in value.incoming_values] + # stop if the elements in `v` do not hold the same value + if v[0] is not None and any([v[0] != vi for vi in v]): + continue + + lit = typemap.get(target.name, None) + if lit and isinstance(lit, types.Literal): + # replace assign instruction by ir.Const(lit) iff + # lit is a literal value + rhs = ir.Const(lit.literal_value, assign.loc) + new_assign = ir.Assign(rhs, target, assign.loc) + + # replace instruction + block.insert_after(new_assign, assign) + block.remove(assign) + + changed = True + + # reset type inference now we are done with the partial results + state.typemap = None + state.calltypes = None + + if changed: + # Rebuild definitions + func_ir._definitions = build_definitions(func_ir.blocks) + + return changed + + +@register_pass(mutates_CFG=True, analysis_only=False) +class LiteralPropagationSubPipelinePass(FunctionPass): + """Implement literal propagation based on partial type inference""" + _name = "LiteralPropagation" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # Determine whether to even attempt this pass... if there's no + # `isinstance` as a global or as a freevar then just skip. + + found = False + func_ir = state.func_ir + for blk in func_ir.blocks.values(): + for asgn in blk.find_insts(ir.Assign): + if isinstance(asgn.value, (ir.Global, ir.FreeVar)): + value = asgn.value.value + if value is isinstance or value is hasattr: + found = True + break + if found: + break + if not found: + return False + + # run as subpipeline + from numba.core.compiler_machinery import PassManager + from numba.core.typed_passes import PartialTypeInference + pm = PassManager("literal_propagation_subpipeline") + + pm.add_pass(PartialTypeInference, "performs partial type inference") + pm.add_pass(PropagateLiterals, "performs propagation of literal values") + + # rewrite consts / dead branch pruning + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + + pm.finalize() + pm.run(state) + return True + + def get_analysis_usage(self, AU): + AU.add_required(ReconstructSSA) + + +@register_pass(mutates_CFG=True, analysis_only=False) +class LiteralUnroll(FunctionPass): + """Implement the literal_unroll semantics""" + _name = "literal_unroll" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # Determine whether to even attempt this pass... if there's no + # `literal_unroll` as a global or as a freevar then just skip. + found = False + func_ir = state.func_ir + for blk in func_ir.blocks.values(): + for asgn in blk.find_insts(ir.Assign): + if isinstance(asgn.value, (ir.Global, ir.FreeVar)): + if asgn.value.value is literal_unroll: + found = True + break + if found: + break + if not found: + return False + + # run as subpipeline + from numba.core.compiler_machinery import PassManager + from numba.core.typed_passes import PartialTypeInference + pm = PassManager("literal_unroll_subpipeline") + # get types where possible to help with list->tuple change + pm.add_pass(PartialTypeInference, "performs partial type inference") + # make const lists tuples + pm.add_pass(TransformLiteralUnrollConstListToTuple, + "switch const list for tuples") + # recompute partial typemap following IR change + pm.add_pass(PartialTypeInference, "performs partial type inference") + # canonicalise loops + pm.add_pass(IterLoopCanonicalization, + "switch iter loops for range driven loops") + # rewrite consts + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + # do the unroll + pm.add_pass(MixedContainerUnroller, "performs mixed container unroll") + # rewrite dynamic getitem to static getitem as it's possible some more + # getitems will now be statically resolvable + pm.add_pass(GenericRewrites, "Generic Rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.finalize() + pm.run(state) + return True + + +@register_pass(mutates_CFG=True, analysis_only=False) +class SimplifyCFG(FunctionPass): + """Perform CFG simplification""" + _name = "simplify_cfg" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + blks = state.func_ir.blocks + new_blks = simplify_CFG(blks) + state.func_ir.blocks = new_blks + mutated = blks != new_blks + return mutated + + +@register_pass(mutates_CFG=False, analysis_only=False) +class ReconstructSSA(FunctionPass): + """Perform SSA-reconstruction + + Produces minimal SSA. + """ + _name = "reconstruct_ssa" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + state.func_ir = reconstruct_ssa(state.func_ir) + self._patch_locals(state) + + # Rebuild definitions + state.func_ir._definitions = build_definitions(state.func_ir.blocks) + + # Rerun postprocessor to update metadata + # example generator_info + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run(emit_dels=False) + + if config.DEBUG or config.DUMP_SSA: + name = state.func_ir.func_id.func_qualname + print(f"SSA IR DUMP: {name}".center(80, "-")) + state.func_ir.dump() + + return True # XXX detect if it actually got changed + + def _patch_locals(self, state): + # Fix dispatcher locals dictionary type annotation + locals_dict = state.get('locals') + if locals_dict is None: + return + + first_blk, *_ = state.func_ir.blocks.values() + scope = first_blk.scope + for parent, redefs in scope.var_redefinitions.items(): + if parent in locals_dict: + typ = locals_dict[parent] + for derived in redefs: + locals_dict[derived] = typ + + +@register_pass(mutates_CFG=False, analysis_only=False) +class RewriteDynamicRaises(FunctionPass): + """Replace existing raise statements by dynamic raises in Numba IR. + """ + _name = "Rewrite dynamic raises" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + func_ir = state.func_ir + changed = False + + for block in func_ir.blocks.values(): + for raise_ in block.find_insts((ir.Raise, ir.TryRaise)): + call_inst = guard(get_definition, func_ir, raise_.exception) + if call_inst is None: + continue + exc_type = func_ir.infer_constant(call_inst.func.name) + exc_args = [] + for exc_arg in call_inst.args: + try: + const = func_ir.infer_constant(exc_arg) + exc_args.append(const) + except consts.ConstantInferenceError: + exc_args.append(exc_arg) + loc = raise_.loc + + cls = { + ir.TryRaise: ir.DynamicTryRaise, + ir.Raise: ir.DynamicRaise, + }[type(raise_)] + + dyn_raise = cls(exc_type, tuple(exc_args), loc) + block.insert_after(dyn_raise, raise_) + block.remove(raise_) + changed = True + return changed diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1f4189d465764ae39677799fd898fe23bc1c40 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/utils.py @@ -0,0 +1,783 @@ +import atexit +import builtins +import functools +import inspect +import os +import operator +import timeit +import math +import sys +import traceback +import weakref +import warnings +import threading +import contextlib +import json +import typing as _tp +from pprint import pformat + +from types import ModuleType +from importlib import import_module +import numpy as np + +from inspect import signature as pysignature # noqa: F401 +from inspect import Signature as pySignature # noqa: F401 +from inspect import Parameter as pyParameter # noqa: F401 + +from numba.core.config import (PYVERSION, MACHINE_BITS, # noqa: F401 + DEVELOPER_MODE) # noqa: F401 +from numba.core import config +from numba.core import types + +from collections.abc import Mapping, Sequence, MutableSet, MutableMapping + + +def erase_traceback(exc_value): + """ + Erase the traceback and hanging locals from the given exception instance. + """ + if exc_value.__traceback__ is not None: + traceback.clear_frames(exc_value.__traceback__) + return exc_value.with_traceback(None) + + +def safe_relpath(path, start=os.curdir): + """ + Produces a "safe" relative path, on windows relpath doesn't work across + drives as technically they don't share the same root. + See: https://bugs.python.org/issue7195 for details. + """ + # find the drive letters for path and start and if they are not the same + # then don't use relpath! + drive_letter = lambda x: os.path.splitdrive(os.path.abspath(x))[0] + drive_path = drive_letter(path) + drive_start = drive_letter(start) + if drive_path != drive_start: + return os.path.abspath(path) + else: + return os.path.relpath(path, start=start) + + +# Mapping between operator module functions and the corresponding built-in +# operators. + +BINOPS_TO_OPERATORS = { + '+': operator.add, + '-': operator.sub, + '*': operator.mul, + '//': operator.floordiv, + '/': operator.truediv, + '%': operator.mod, + '**': operator.pow, + '&': operator.and_, + '|': operator.or_, + '^': operator.xor, + '<<': operator.lshift, + '>>': operator.rshift, + '==': operator.eq, + '!=': operator.ne, + '<': operator.lt, + '<=': operator.le, + '>': operator.gt, + '>=': operator.ge, + 'is': operator.is_, + 'is not': operator.is_not, + # This one has its args reversed! + 'in': operator.contains, + '@': operator.matmul, +} + +INPLACE_BINOPS_TO_OPERATORS = { + '+=': operator.iadd, + '-=': operator.isub, + '*=': operator.imul, + '//=': operator.ifloordiv, + '/=': operator.itruediv, + '%=': operator.imod, + '**=': operator.ipow, + '&=': operator.iand, + '|=': operator.ior, + '^=': operator.ixor, + '<<=': operator.ilshift, + '>>=': operator.irshift, + '@=': operator.imatmul, +} + + +ALL_BINOPS_TO_OPERATORS = {**BINOPS_TO_OPERATORS, + **INPLACE_BINOPS_TO_OPERATORS} + + +UNARY_BUITINS_TO_OPERATORS = { + '+': operator.pos, + '-': operator.neg, + '~': operator.invert, + 'not': operator.not_, + 'is_true': operator.truth +} + +OPERATORS_TO_BUILTINS = { + operator.add: '+', + operator.iadd: '+=', + operator.sub: '-', + operator.isub: '-=', + operator.mul: '*', + operator.imul: '*=', + operator.floordiv: '//', + operator.ifloordiv: '//=', + operator.truediv: '/', + operator.itruediv: '/=', + operator.mod: '%', + operator.imod: '%=', + operator.pow: '**', + operator.ipow: '**=', + operator.and_: '&', + operator.iand: '&=', + operator.or_: '|', + operator.ior: '|=', + operator.xor: '^', + operator.ixor: '^=', + operator.lshift: '<<', + operator.ilshift: '<<=', + operator.rshift: '>>', + operator.irshift: '>>=', + operator.eq: '==', + operator.ne: '!=', + operator.lt: '<', + operator.le: '<=', + operator.gt: '>', + operator.ge: '>=', + operator.is_: 'is', + operator.is_not: 'is not', + # This one has its args reversed! + operator.contains: 'in', + # Unary + operator.pos: '+', + operator.neg: '-', + operator.invert: '~', + operator.not_: 'not', + operator.truth: 'is_true', +} + + +_shutting_down = False + + +def _at_shutdown(): + global _shutting_down + _shutting_down = True + + +def shutting_down(globals=globals): + """ + Whether the interpreter is currently shutting down. + For use in finalizers, __del__ methods, and similar; it is advised + to early bind this function rather than look it up when calling it, + since at shutdown module globals may be cleared. + """ + # At shutdown, the attribute may have been cleared or set to None. + v = globals().get('_shutting_down') + return v is True or v is None + + +# weakref.finalize registers an exit function that runs all finalizers for +# which atexit is True. Some of these finalizers may call shutting_down() to +# check whether the interpreter is shutting down. For this to behave correctly, +# we need to make sure that _at_shutdown is called before the finalizer exit +# function. Since atexit operates as a LIFO stack, we first construct a dummy +# finalizer then register atexit to ensure this ordering. +weakref.finalize(lambda: None, lambda: None) +atexit.register(_at_shutdown) + + +class ThreadLocalStack: + """A TLS stack container. + + Uses the BORG pattern and stores states in threadlocal storage. + """ + _tls = threading.local() + stack_name: str + _registered = {} + + def __init_subclass__(cls, *, stack_name, **kwargs): + super().__init_subclass__(**kwargs) + # Register stack_name mapping to the new subclass + assert stack_name not in cls._registered, \ + f"stack_name: '{stack_name}' already in use" + cls.stack_name = stack_name + cls._registered[stack_name] = cls + + def __init__(self): + # This class must not be used directly. + assert type(self) is not ThreadLocalStack + tls = self._tls + attr = f"stack_{self.stack_name}" + try: + tls_stack = getattr(tls, attr) + except AttributeError: + tls_stack = list() + setattr(tls, attr, tls_stack) + + self._stack = tls_stack + + def push(self, state): + """Push to the stack + """ + self._stack.append(state) + + def pop(self): + """Pop from the stack + """ + return self._stack.pop() + + def top(self): + """Get the top item on the stack. + + Raises IndexError if the stack is empty. Users should check the size + of the stack beforehand. + """ + return self._stack[-1] + + def __len__(self): + return len(self._stack) + + @contextlib.contextmanager + def enter(self, state): + """A contextmanager that pushes ``state`` for the duration of the + context. + """ + self.push(state) + try: + yield + finally: + self.pop() + + +class ConfigOptions(object): + OPTIONS = {} + + def __init__(self): + self._values = self.OPTIONS.copy() + + def set(self, name, value=True): + if name not in self.OPTIONS: + raise NameError("Invalid flag: %s" % name) + self._values[name] = value + + def unset(self, name): + self.set(name, False) + + def _check_attr(self, name): + if name not in self.OPTIONS: + raise AttributeError("Invalid flag: %s" % name) + + def __getattr__(self, name): + self._check_attr(name) + return self._values[name] + + def __setattr__(self, name, value): + if name.startswith('_'): + super(ConfigOptions, self).__setattr__(name, value) + else: + self._check_attr(name) + self._values[name] = value + + def __repr__(self): + return "Flags(%s)" % ', '.join('%s=%s' % (k, v) + for k, v in self._values.items() + if v is not False) + + def copy(self): + copy = type(self)() + copy._values = self._values.copy() + return copy + + def __eq__(self, other): + return (isinstance(other, ConfigOptions) and + other._values == self._values) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(tuple(sorted(self._values.items()))) + + +def order_by_target_specificity(target, templates, fnkey=''): + """This orders the given templates from most to least specific against the + current "target". "fnkey" is an indicative typing key for use in the + exception message in the case that there's no usable templates for the + current "target". + """ + # No templates... return early! + if templates == []: + return [] + + from numba.core.target_extension import target_registry + + # fish out templates that are specific to the target if a target is + # specified + DEFAULT_TARGET = 'generic' + usable = [] + for ix, temp_cls in enumerate(templates): + # ? Need to do something about this next line + md = getattr(temp_cls, "metadata", {}) + hw = md.get('target', DEFAULT_TARGET) + if hw is not None: + hw_clazz = target_registry[hw] + if target.inherits_from(hw_clazz): + usable.append((temp_cls, hw_clazz, ix)) + + # sort templates based on target specificity + def key(x): + return target.__mro__.index(x[1]) + order = [x[0] for x in sorted(usable, key=key)] + + if not order: + msg = (f"Function resolution cannot find any matches for function " + f"'{fnkey}' for the current target: '{target}'.") + from numba.core.errors import UnsupportedError + raise UnsupportedError(msg) + + return order + + +T = _tp.TypeVar('T') + + +class OrderedSet(MutableSet[T]): + + def __init__(self, iterable: _tp.Iterable[T] = ()): + # Just uses a dictionary under-the-hood to maintain insertion order. + self._data = dict.fromkeys(iterable, None) + + def __contains__(self, key): + return key in self._data + + def __iter__(self): + return iter(self._data) + + def __len__(self): + return len(self._data) + + def add(self, item): + self._data[item] = None + + def discard(self, item): + self._data.pop(item, None) + + +class MutableSortedSet(MutableSet[T], _tp.Generic[T]): + """Mutable Sorted Set + """ + + def __init__(self, values: _tp.Iterable[T] = ()): + self._values = set(values) + + def __len__(self): + return len(self._values) + + def __iter__(self): + return iter(k for k in sorted(self._values)) + + def __contains__(self, x: T) -> bool: + return self._values.__contains__(x) + + def add(self, x: T): + return self._values.add(x) + + def discard(self, value: T): + self._values.discard(value) + + def update(self, values): + self._values.update(values) + + +Tk = _tp.TypeVar('Tk') +Tv = _tp.TypeVar('Tv') + + +class SortedMap(Mapping[Tk, Tv], _tp.Generic[Tk, Tv]): + """Immutable + """ + + def __init__(self, seq): + self._values = [] + self._index = {} + for i, (k, v) in enumerate(sorted(seq)): + self._index[k] = i + self._values.append((k, v)) + + def __getitem__(self, k): + i = self._index[k] + return self._values[i][1] + + def __len__(self): + return len(self._values) + + def __iter__(self): + return iter(k for k, v in self._values) + + +class MutableSortedMap(MutableMapping[Tk, Tv], _tp.Generic[Tk, Tv]): + def __init__(self, dct=None): + if dct is None: + dct = {} + self._dct: dict[Tk, Tv] = dct + + def __getitem__(self, k: Tk) -> Tv: + return self._dct[k] + + def __setitem__(self, k: Tk, v: Tv): + self._dct[k] = v + + def __delitem__(self, k: Tk): + del self._dct[k] + + def __len__(self) -> int: + return len(self._dct) + + def __iter__(self) -> int: + return iter(k for k in sorted(self._dct)) + + +class UniqueDict(dict): + def __setitem__(self, key, value): + if key in self: + raise AssertionError("key already in dictionary: %r" % (key,)) + super(UniqueDict, self).__setitem__(key, value) + + +def runonce(fn): + @functools.wraps(fn) + def inner(): + if not inner._ran: + res = fn() + inner._result = res + inner._ran = True + return inner._result + + inner._ran = False + return inner + + +def bit_length(intval): + """ + Return the number of bits necessary to represent integer `intval`. + """ + assert isinstance(intval, int) + if intval >= 0: + return len(bin(intval)) - 2 + else: + return len(bin(-intval - 1)) - 2 + + +def stream_list(lst): + """ + Given a list, return an infinite iterator of iterators. + Each iterator iterates over the list from the last seen point up to + the current end-of-list. + + In effect, each iterator will give the newly appended elements from the + previous iterator instantiation time. + """ + def sublist_iterator(start, stop): + return iter(lst[start:stop]) + + start = 0 + while True: + stop = len(lst) + yield sublist_iterator(start, stop) + start = stop + + +class BenchmarkResult(object): + def __init__(self, func, records, loop): + self.func = func + self.loop = loop + self.records = np.array(records) / loop + self.best = np.min(self.records) + + def __repr__(self): + name = getattr(self.func, "__name__", self.func) + args = (name, self.loop, self.records.size, format_time(self.best)) + return "%20s: %10d loops, best of %d: %s per loop" % args + + +def format_time(tm): + units = "s ms us ns ps".split() + base = 1 + for unit in units[:-1]: + if tm >= base: + break + base /= 1000 + else: + unit = units[-1] + return "%.1f%s" % (tm / base, unit) + + +def benchmark(func, maxsec=1): + timer = timeit.Timer(func) + number = 1 + result = timer.repeat(1, number) + # Too fast to be measured + while min(result) / number == 0: + number *= 10 + result = timer.repeat(3, number) + best = min(result) / number + if best >= maxsec: + return BenchmarkResult(func, result, number) + # Scale it up to make it close the maximum time + max_per_run_time = maxsec / 3 / number + number = max(max_per_run_time / best / 3, 1) + # Round to the next power of 10 + number = int(10 ** math.ceil(math.log10(number))) + records = timer.repeat(3, number) + return BenchmarkResult(func, records, number) + + +# A dummy module for dynamically-generated functions +_dynamic_modname = '' +_dynamic_module = ModuleType(_dynamic_modname) +_dynamic_module.__builtins__ = builtins + + +def chain_exception(new_exc, old_exc): + """Set the __cause__ attribute on *new_exc* for explicit exception + chaining. Returns the inplace modified *new_exc*. + """ + if DEVELOPER_MODE: + new_exc.__cause__ = old_exc + return new_exc + + +def get_nargs_range(pyfunc): + """Return the minimal and maximal number of Python function + positional arguments. + """ + sig = pysignature(pyfunc) + min_nargs = 0 + max_nargs = 0 + for p in sig.parameters.values(): + max_nargs += 1 + if p.default == inspect._empty: + min_nargs += 1 + return min_nargs, max_nargs + + +def unify_function_types(numba_types): + """Return a normalized tuple of Numba function types so that + + Tuple(numba_types) + + becomes + + UniTuple(dtype=, count=len(numba_types)) + + If the above transformation would be incorrect, return the + original input as given. For instance, if the input tuple contains + types that are not function or dispatcher type, the transformation + is considered incorrect. + """ + dtype = unified_function_type(numba_types) + if dtype is None: + return numba_types + return (dtype,) * len(numba_types) + + +def unified_function_type(numba_types, require_precise=True): + """Returns a unified Numba function type if possible. + + Parameters + ---------- + numba_types : Sequence of numba Type instances. + require_precise : bool + If True, the returned Numba function type must be precise. + + Returns + ------- + typ : {numba.core.types.Type, None} + A unified Numba function type. Or ``None`` when the Numba types + cannot be unified, e.g. when the ``numba_types`` contains at + least two different Numba function type instances. + + If ``numba_types`` contains a Numba dispatcher type, the unified + Numba function type will be an imprecise ``UndefinedFunctionType`` + instance, or None when ``require_precise=True`` is specified. + + Specifying ``require_precise=False`` enables unifying imprecise + Numba dispatcher instances when used in tuples or if-then branches + when the precise Numba function cannot be determined on the first + occurrence that is not a call expression. + """ + from numba.core.errors import NumbaExperimentalFeatureWarning + + if not (isinstance(numba_types, Sequence) and + len(numba_types) > 0 and + isinstance(numba_types[0], + (types.Dispatcher, types.FunctionType))): + return + + warnings.warn("First-class function type feature is experimental", + category=NumbaExperimentalFeatureWarning) + + mnargs, mxargs = None, None + dispatchers = set() + function = None + undefined_function = None + + for t in numba_types: + if isinstance(t, types.Dispatcher): + mnargs1, mxargs1 = get_nargs_range(t.dispatcher.py_func) + if mnargs is None: + mnargs, mxargs = mnargs1, mxargs1 + elif not (mnargs, mxargs) == (mnargs1, mxargs1): + return + dispatchers.add(t.dispatcher) + t = t.dispatcher.get_function_type() + if t is None: + continue + if isinstance(t, types.FunctionType): + if mnargs is None: + mnargs = mxargs = t.nargs + elif not (mnargs == mxargs == t.nargs): + return + if isinstance(t, types.UndefinedFunctionType): + if undefined_function is None: + undefined_function = t + else: + # Refuse to unify using function type + return + dispatchers.update(t.dispatchers) + else: + if function is None: + function = t + else: + assert function == t + else: + return + if require_precise and (function is None or undefined_function is not None): + return + if function is not None: + if undefined_function is not None: + assert function.nargs == undefined_function.nargs + function = undefined_function + elif undefined_function is not None: + undefined_function.dispatchers.update(dispatchers) + function = undefined_function + else: + function = types.UndefinedFunctionType(mnargs, dispatchers) + + return function + + +class _RedirectSubpackage(ModuleType): + """Redirect a subpackage to a subpackage. + + This allows all references like: + + >>> from numba.old_subpackage import module + >>> module.item + + >>> import numba.old_subpackage.module + >>> numba.old_subpackage.module.item + + >>> from numba.old_subpackage.module import item + """ + def __init__(self, old_module_locals, new_module): + old_module = old_module_locals['__name__'] + super().__init__(old_module) + + self.__old_module_states = {} + self.__new_module = new_module + + new_mod_obj = import_module(new_module) + + # Map all sub-modules over + for k, v in new_mod_obj.__dict__.items(): + # Get attributes so that `subpackage.xyz` and + # `from subpackage import xyz` work + setattr(self, k, v) + if isinstance(v, ModuleType): + # Map modules into the interpreter so that + # `import subpackage.xyz` works + sys.modules[f"{old_module}.{k}"] = sys.modules[v.__name__] + + # copy across dunders so that package imports work too + for attr, value in old_module_locals.items(): + if attr.startswith('__') and attr.endswith('__'): + if attr != "__builtins__": + setattr(self, attr, value) + self.__old_module_states[attr] = value + + def __reduce__(self): + args = (self.__old_module_states, self.__new_module) + return _RedirectSubpackage, args + + +def get_hashable_key(value): + """ + Given a value, returns a key that can be used + as a hash. If the value is hashable, we return + the value, otherwise we return id(value). + + See discussion in gh #6957 + """ + try: + hash(value) + except TypeError: + return id(value) + else: + return value + + +class threadsafe_cached_property(functools.cached_property): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._lock = threading.RLock() + + def __get__(self, *args, **kwargs): + with self._lock: + return super().__get__(*args, **kwargs) + + +def dump_llvm(fndesc, module): + print(("LLVM DUMP %s" % fndesc).center(80, '-')) + if config.HIGHLIGHT_DUMPS: + try: + from pygments import highlight + from pygments.lexers import LlvmLexer as lexer + from pygments.formatters import Terminal256Formatter + from numba.misc.dump_style import by_colorscheme + print(highlight(module.__repr__(), lexer(), + Terminal256Formatter( style=by_colorscheme()))) + except ImportError: + msg = "Please install pygments to see highlighted dumps" + raise ValueError(msg) + else: + print(module) + print('=' * 80) + + +class _lazy_pformat(object): + """ Lazily generate strings that may be useful only for debugging. + pformat is the default formatter but you can pass lazy_func kwarg + to use a different formatter. + """ + def __init__(self, *args, **kwargs): + self.func = pformat + self.args = args + self.kwargs = kwargs + if "lazy_func" in kwargs: + self.func = kwargs["lazy_func"] + del kwargs["lazy_func"] + + def __str__(self): + return self.func(*self.args, **self.kwargs) + + +class _LazyJSONEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, _lazy_pformat): + return str(obj) + return super().default(obj) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/withcontexts.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/withcontexts.py new file mode 100644 index 0000000000000000000000000000000000000000..19a2e1334b89d7bea40b116885a03527e8c6c884 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/core/withcontexts.py @@ -0,0 +1,605 @@ +import numba +from numba.core import errors, ir, ir_utils, sigutils, types +from numba.core.ir_utils import build_definitions +from numba.core.transforms import find_region_inout_vars +from numba.core.typing.typeof import typeof_impl + + +class WithContext(object): + """A dummy object for use as contextmanager. + This can be used as a contextmanager. + """ + + is_callable = False + + def __enter__(self): + pass + + def __exit__(self, typ, val, tb): + pass + + def mutate_with_body( + self, + func_ir, + blocks, + blk_start, + blk_end, + body_blocks, + dispatcher_factory, + extra, + ): + """Mutate the *blocks* to implement this contextmanager. + + Parameters + ---------- + func_ir : FunctionIR + blocks : dict[ir.Block] + blk_start, blk_end : int + labels of the starting and ending block of the context-manager. + body_block: sequence[int] + A sequence of int's representing labels of the with-body + dispatcher_factory : callable + A callable that takes a `FunctionIR` and returns a `Dispatcher`. + """ + raise NotImplementedError + + +@typeof_impl.register(WithContext) +def typeof_contextmanager(val, c): + return types.ContextManager(val) + + +def _get_var_parent(name): + """Get parent of the variable given its name""" + # If not a temporary variable + if not name.startswith("$"): + # Return the base component of the name + return name.split( + ".", + )[0] + + +def _clear_blocks(blocks, to_clear): + """Remove keys in *to_clear* from *blocks*.""" + for b in to_clear: + del blocks[b] + + +class _ByPassContextType(WithContext): + """A simple context-manager that tells the compiler to bypass the body + of the with-block. + """ + + def mutate_with_body( + self, + func_ir, + blocks, + blk_start, + blk_end, + body_blocks, + dispatcher_factory, + extra, + ): + assert extra is None + # Determine variables that need forwarding + vlt = func_ir.variable_lifetime + inmap = {_get_var_parent(k): k for k in vlt.livemap[blk_start]} + outmap = {_get_var_parent(k): k for k in vlt.livemap[blk_end]} + forwardvars = {inmap[k]: outmap[k] for k in filter(bool, outmap)} + # Transform the block + _bypass_with_context(blocks, blk_start, blk_end, forwardvars) + _clear_blocks(blocks, body_blocks) + + +bypass_context = _ByPassContextType() + + +class _CallContextType(WithContext): + """A simple context-manager that tells the compiler to lift the body of the + with-block as another function. + """ + + def mutate_with_body( + self, + func_ir, + blocks, + blk_start, + blk_end, + body_blocks, + dispatcher_factory, + extra, + ): + assert extra is None + vlt = func_ir.variable_lifetime + + inputs, outputs = find_region_inout_vars( + blocks=blocks, + livemap=vlt.livemap, + callfrom=blk_start, + returnto=blk_end, + body_block_ids=set(body_blocks), + ) + + lifted_blks = {k: blocks[k] for k in body_blocks} + _mutate_with_block_callee( + lifted_blks, blk_start, blk_end, inputs, outputs + ) + + # XXX: transform body-blocks to return the output variables + lifted_ir = func_ir.derive( + blocks=lifted_blks, + arg_names=tuple(inputs), + arg_count=len(inputs), + force_non_generator=True, + ) + + dispatcher = dispatcher_factory(lifted_ir) + + newblk = _mutate_with_block_caller( + dispatcher, + blocks, + blk_start, + blk_end, + inputs, + outputs, + ) + + blocks[blk_start] = newblk + _clear_blocks(blocks, body_blocks) + return dispatcher + + +call_context = _CallContextType() + + +class _ObjModeContextType(WithContext): + """Creates a contextmanager to be used inside jitted functions to enter + *object-mode* for using interpreter features. The body of the with-context + is lifted into a function that is compiled in *object-mode*. This + transformation process is limited and cannot process all possible + Python code. However, users can wrap complicated logic in another + Python function, which will then be executed by the interpreter. + + Use this as a function that takes keyword arguments only. + The argument names must correspond to the output variables from the + with-block. Their respective values can be: + + 1. strings representing the expected types; i.e. ``"float32"``. + 2. compile-time bound global or nonlocal variables referring to the + expected type. The variables are read at compile time. + + When exiting the with-context, the output variables are converted + to the expected nopython types according to the annotation. This process + is the same as passing Python objects into arguments of a nopython + function. + + Example:: + + import numpy as np + from numba import njit, objmode, types + + def bar(x): + # This code is executed by the interpreter. + return np.asarray(list(reversed(x.tolist()))) + + # Output type as global variable + out_ty = types.intp[:] + + @njit + def foo(): + x = np.arange(5) + y = np.zeros_like(x) + with objmode(y='intp[:]', z=out_ty): # annotate return type + # this region is executed by object-mode. + y += bar(x) + z = y + return y, z + + .. note:: Known limitations: + + - with-block cannot use incoming list objects. + - with-block cannot use incoming function objects. + - with-block cannot ``yield``, ``break``, ``return`` or ``raise`` \ + such that the execution will leave the with-block immediately. + - with-block cannot contain `with` statements. + - random number generator states do not synchronize; i.e. \ + nopython-mode and object-mode uses different RNG states. + + .. note:: When used outside of no-python mode, the context-manager has no + effect. + + .. warning:: This feature is experimental. The supported features may + change with or without notice. + + """ + + is_callable = True + + def _legalize_args( + self, func_ir, args, kwargs, loc, func_globals, func_closures + ): + """ + Legalize arguments to the context-manager + + Parameters + ---------- + func_ir: FunctionIR + args: tuple + Positional arguments to the with-context call as IR nodes. + kwargs: dict + Keyword arguments to the with-context call as IR nodes. + loc: numba.core.ir.Loc + Source location of the with-context call. + func_globals: dict + The globals dictionary of the calling function. + func_closures: dict + The resolved closure variables of the calling function. + """ + if args: + raise errors.CompilerError( + "objectmode context doesn't take any positional arguments", + ) + typeanns = {} + + def report_error(varname, msg, loc): + raise errors.CompilerError( + f"Error handling objmode argument {varname!r}. {msg}", + loc=loc, + ) + + for k, v in kwargs.items(): + if isinstance(v, ir.Const) and isinstance(v.value, str): + typeanns[k] = sigutils._parse_signature_string(v.value) + elif isinstance(v, ir.FreeVar): + try: + v = func_closures[v.name] + except KeyError: + report_error( + varname=k, + msg=f"Freevar {v.name!r} is not defined.", + loc=loc, + ) + typeanns[k] = v + elif isinstance(v, ir.Global): + try: + v = func_globals[v.name] + except KeyError: + report_error( + varname=k, + msg=f"Global {v.name!r} is not defined.", + loc=loc, + ) + typeanns[k] = v + elif isinstance(v, ir.Expr) and v.op == "getattr": + try: + base_obj = func_ir.infer_constant(v.value) + typ = getattr(base_obj, v.attr) + except (errors.ConstantInferenceError, AttributeError): + report_error( + varname=k, + msg="Getattr cannot be resolved at compile-time.", + loc=loc, + ) + else: + typeanns[k] = typ + else: + report_error( + varname=k, + msg=( + "The value must be a compile-time constant either as " + "a non-local variable or a getattr expression that " + "refers to a Numba type." + ), + loc=loc, + ) + + # Legalize the types for objmode + for name, typ in typeanns.items(): + self._legalize_arg_type(name, typ, loc) + + return typeanns + + def _legalize_arg_type(self, name, typ, loc): + """Legalize the argument type + + Parameters + ---------- + name: str + argument name. + typ: numba.core.types.Type + argument type. + loc: numba.core.ir.Loc + source location for error reporting. + """ + if getattr(typ, "reflected", False): + msgbuf = [ + "Objmode context failed.", + f"Argument {name!r} is declared as " + f"an unsupported type: {typ}.", + "Reflected types are not supported.", + ] + raise errors.CompilerError(" ".join(msgbuf), loc=loc) + + def mutate_with_body( + self, + func_ir, + blocks, + blk_start, + blk_end, + body_blocks, + dispatcher_factory, + extra, + ): + cellnames = func_ir.func_id.func.__code__.co_freevars + closures = func_ir.func_id.func.__closure__ + func_globals = func_ir.func_id.func.__globals__ + if closures is not None: + # Resolve free variables + func_closures = {} + for cellname, closure in zip(cellnames, closures): + try: + cellval = closure.cell_contents + except ValueError as e: + # empty cell will raise + if str(e) != "Cell is empty": + raise + else: + func_closures[cellname] = cellval + else: + # Missing closure object + func_closures = {} + args = extra["args"] if extra else () + kwargs = extra["kwargs"] if extra else {} + + typeanns = self._legalize_args( + func_ir=func_ir, + args=args, + kwargs=kwargs, + loc=blocks[blk_start].loc, + func_globals=func_globals, + func_closures=func_closures, + ) + vlt = func_ir.variable_lifetime + + inputs, outputs = find_region_inout_vars( + blocks=blocks, + livemap=vlt.livemap, + callfrom=blk_start, + returnto=blk_end, + body_block_ids=set(body_blocks), + ) + + # Determine types in the output tuple + def strip_var_ver(x): + return x.split(".", 1)[0] + + stripped_outs = list(map(strip_var_ver, outputs)) + + # Verify that only outputs are annotated + extra_annotated = set(typeanns) - set(stripped_outs) + if extra_annotated: + msg = ( + "Invalid type annotation on non-outgoing variables: {}." + "Suggestion: remove annotation of the listed variables" + ) + raise errors.TypingError(msg.format(extra_annotated)) + + # Verify that all outputs are annotated + + # Note on "$cp" variable: + # ``transforms.consolidate_multi_exit_withs()`` introduces the variable + # for the control-point to determine the correct exit block. This + # variable crosses the with-region boundary. Thus, it will be consider + # an output variable leaving the lifted with-region. + typeanns["$cp"] = types.int32 + not_annotated = set(stripped_outs) - set(typeanns) + if not_annotated: + msg = ( + "Missing type annotation on outgoing variable(s): {0}\n\n" + "Example code: with objmode({1}='<" + "add_type_as_string_here>')\n" + ) + stable_ann = sorted(not_annotated) + raise errors.TypingError(msg.format(stable_ann, stable_ann[0])) + + # Get output types + outtup = types.Tuple([typeanns[v] for v in stripped_outs]) + + lifted_blks = {k: blocks[k] for k in body_blocks} + _mutate_with_block_callee( + lifted_blks, blk_start, blk_end, inputs, outputs + ) + + lifted_ir = func_ir.derive( + blocks=lifted_blks, + arg_names=tuple(inputs), + arg_count=len(inputs), + force_non_generator=True, + ) + + dispatcher = dispatcher_factory( + lifted_ir, objectmode=True, output_types=outtup + ) + + newblk = _mutate_with_block_caller( + dispatcher, + blocks, + blk_start, + blk_end, + inputs, + outputs, + ) + + blocks[blk_start] = newblk + _clear_blocks(blocks, body_blocks) + return dispatcher + + def __call__(self, *args, **kwargs): + # No effect when used in pure-python + return self + + +objmode_context = _ObjModeContextType() + + +def _bypass_with_context(blocks, blk_start, blk_end, forwardvars): + """Given the starting and ending block of the with-context, + replaces the head block with a new block that jumps to the end. + + *blocks* is modified inplace. + """ + sblk = blocks[blk_start] + scope = sblk.scope + loc = sblk.loc + newblk = ir.Block(scope=scope, loc=loc) + for k, v in forwardvars.items(): + newblk.append( + ir.Assign( + value=scope.get_exact(k), target=scope.get_exact(v), loc=loc + ) + ) + newblk.append(ir.Jump(target=blk_end, loc=loc)) + blocks[blk_start] = newblk + + +def _mutate_with_block_caller( + dispatcher, blocks, blk_start, blk_end, inputs, outputs +): + """Make a new block that calls into the lifeted with-context. + + Parameters + ---------- + dispatcher : Dispatcher + blocks : dict[ir.Block] + blk_start, blk_end : int + labels of the starting and ending block of the context-manager. + inputs: sequence[str] + Input variable names + outputs: sequence[str] + Output variable names + """ + sblk = blocks[blk_start] + scope = sblk.scope + loc = sblk.loc + newblock = ir.Block(scope=scope, loc=loc) + + ir_utils.fill_block_with_call( + newblock=newblock, + callee=dispatcher, + label_next=blk_end, + inputs=inputs, + outputs=outputs, + ) + return newblock + + +def _mutate_with_block_callee(blocks, blk_start, blk_end, inputs, outputs): + """Mutate *blocks* for the callee of a with-context. + + Parameters + ---------- + blocks : dict[ir.Block] + blk_start, blk_end : int + labels of the starting and ending block of the context-manager. + inputs: sequence[str] + Input variable names + outputs: sequence[str] + Output variable names + """ + if not blocks: + raise errors.NumbaValueError("No blocks in with-context block") + head_blk = min(blocks) + temp_blk = blocks[head_blk] + scope = temp_blk.scope + loc = temp_blk.loc + + blocks[blk_start] = ir_utils.fill_callee_prologue( + block=ir.Block(scope=scope, loc=loc), + inputs=inputs, + label_next=head_blk, + ) + blocks[blk_end] = ir_utils.fill_callee_epilogue( + block=ir.Block(scope=scope, loc=loc), + outputs=outputs, + ) + + +class _ParallelChunksize(WithContext): + is_callable = True + + """A context-manager that on entry stores the current chunksize + for the executing parfors and then changes the current chunksize + to the programmer specified value. On exit the original + chunksize is restored. + """ + + def mutate_with_body( + self, + func_ir, + blocks, + blk_start, + blk_end, + body_blocks, + dispatcher_factory, + extra, + ): + ir_utils.dprint_func_ir(func_ir, "Before with changes", blocks=blocks) + assert extra is not None + args = extra["args"] + assert len(args) == 1 + arg = args[0] + scope = blocks[blk_start].scope + loc = blocks[blk_start].loc + if isinstance(arg, ir.Arg): + arg = ir.Var(scope, arg.name, loc) + + set_state = [] + restore_state = [] + + # global for Numba itself + gvar = scope.redefine("$ngvar", loc) + set_state.append(ir.Assign(ir.Global("numba", numba, loc), gvar, loc)) + # getattr for set chunksize function in Numba + spcattr = ir.Expr.getattr(gvar, "set_parallel_chunksize", loc) + spcvar = scope.redefine("$spc", loc) + set_state.append(ir.Assign(spcattr, spcvar, loc)) + # call set_parallel_chunksize + orig_pc_var = scope.redefine("$save_pc", loc) + cs_var = scope.redefine("$cs_var", loc) + set_state.append(ir.Assign(arg, cs_var, loc)) + spc_call = ir.Expr.call(spcvar, [cs_var], (), loc) + set_state.append(ir.Assign(spc_call, orig_pc_var, loc)) + + restore_spc_call = ir.Expr.call(spcvar, [orig_pc_var], (), loc) + restore_state.append(ir.Assign(restore_spc_call, orig_pc_var, loc)) + + blocks[blk_start].body = ( + blocks[blk_start].body[1:-1] + + set_state + + [blocks[blk_start].body[-1]] + ) + blocks[blk_end].body = restore_state + blocks[blk_end].body + func_ir._definitions = build_definitions(blocks) + ir_utils.dprint_func_ir(func_ir, "After with changes", blocks=blocks) + + def __call__(self, *args, **kwargs): + """Act like a function and enforce the contract that + setting the chunksize takes only one integer input. + """ + if len(args) != 1 or kwargs or not isinstance(args[0], int): + raise ValueError( + "parallel_chunksize takes only a " "single integer argument." + ) + + self.chunksize = args[0] + return self + + def __enter__(self): + self.orig_chunksize = numba.get_parallel_chunksize() + numba.set_parallel_chunksize(self.chunksize) + + def __exit__(self, typ, val, tb): + numba.set_parallel_chunksize(self.orig_chunksize) + + +parallel_chunksize = _ParallelChunksize() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/builtins.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..1ebb2d7786abf8dd435324d57a20367f75190124 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/builtins.py @@ -0,0 +1,1025 @@ +from collections import namedtuple +import math +from functools import reduce + +import numpy as np +import operator +import warnings + +from llvmlite import ir + +from numba.core.imputils import (lower_builtin, lower_getattr, + lower_getattr_generic, lower_cast, + lower_constant, iternext_impl, + call_getiter, call_iternext, impl_ret_borrowed, + impl_ret_untracked, numba_typeref_ctor) +from numba.core import typing, types, utils, cgutils +from numba.core.extending import overload, intrinsic +from numba.core.typeconv import Conversion +from numba.core.errors import (TypingError, LoweringError, + NumbaExperimentalFeatureWarning, + NumbaTypeError, RequireLiteralValue, + NumbaPerformanceWarning) +from numba.core.typing.templates import (AbstractTemplate, infer_global, + signature) +from numba.misc.special import literal_unroll +from numba.core.typing.asnumbatype import as_numba_type + + +@overload(operator.truth) +def ol_truth(val): + if isinstance(val, types.Boolean): + def impl(val): + return val + return impl + + +@lower_builtin(operator.is_not, types.Any, types.Any) +def generic_is_not(context, builder, sig, args): + """ + Implement `x is not y` as `not (x is y)`. + """ + is_impl = context.get_function(operator.is_, sig) + return builder.not_(is_impl(builder, args)) + + +@lower_builtin(operator.is_, types.Any, types.Any) +def generic_is(context, builder, sig, args): + """ + Default implementation for `x is y` + """ + lhs_type, rhs_type = sig.args + # the lhs and rhs have the same type + if lhs_type == rhs_type: + # mutable types + if lhs_type.mutable: + msg = 'no default `is` implementation' + raise LoweringError(msg) + # immutable types + else: + # fallbacks to `==` + try: + eq_impl = context.get_function(operator.eq, sig) + except NotImplementedError: + # no `==` implemented for this type + return cgutils.false_bit + else: + return eq_impl(builder, args) + else: + return cgutils.false_bit + + +@lower_builtin(operator.is_, types.Opaque, types.Opaque) +def opaque_is(context, builder, sig, args): + """ + Implementation for `x is y` for Opaque types. + """ + lhs_type, rhs_type = sig.args + # the lhs and rhs have the same type + if lhs_type == rhs_type: + lhs_ptr = builder.ptrtoint(args[0], cgutils.intp_t) + rhs_ptr = builder.ptrtoint(args[1], cgutils.intp_t) + + return builder.icmp_unsigned('==', lhs_ptr, rhs_ptr) + else: + return cgutils.false_bit + + +@lower_builtin(operator.is_, types.Boolean, types.Boolean) +def bool_is_impl(context, builder, sig, args): + """ + Implementation for `x is y` for types derived from types.Boolean + (e.g. BooleanLiteral), and cross-checks between literal and non-literal + booleans, to satisfy Python's behavior preserving identity for bools. + """ + arg1, arg2 = args + arg1_type, arg2_type = sig.args + _arg1 = context.cast(builder, arg1, arg1_type, types.boolean) + _arg2 = context.cast(builder, arg2, arg2_type, types.boolean) + eq_impl = context.get_function( + operator.eq, + typing.signature(types.boolean, types.boolean, types.boolean) + ) + return eq_impl(builder, (_arg1, _arg2)) + + +# keep types.IntegerLiteral, as otherwise there's ambiguity between this and int_eq_impl +@lower_builtin(operator.eq, types.Literal, types.Literal) +@lower_builtin(operator.eq, types.IntegerLiteral, types.IntegerLiteral) +def const_eq_impl(context, builder, sig, args): + arg1, arg2 = sig.args + val = 0 + if arg1.literal_value == arg2.literal_value: + val = 1 + res = ir.Constant(ir.IntType(1), val) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# keep types.IntegerLiteral, as otherwise there's ambiguity between this and int_ne_impl +@lower_builtin(operator.ne, types.Literal, types.Literal) +@lower_builtin(operator.ne, types.IntegerLiteral, types.IntegerLiteral) +def const_ne_impl(context, builder, sig, args): + arg1, arg2 = sig.args + val = 0 + if arg1.literal_value != arg2.literal_value: + val = 1 + res = ir.Constant(ir.IntType(1), val) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def gen_non_eq(val): + def none_equality(a, b): + a_none = isinstance(a, types.NoneType) + b_none = isinstance(b, types.NoneType) + if a_none and b_none: + def impl(a, b): + return val + return impl + elif a_none ^ b_none: + def impl(a, b): + return not val + return impl + return none_equality + +overload(operator.eq)(gen_non_eq(True)) +overload(operator.ne)(gen_non_eq(False)) + +#------------------------------------------------------------------------------- + +@lower_getattr_generic(types.DeferredType) +def deferred_getattr(context, builder, typ, value, attr): + """ + Deferred.__getattr__ => redirect to the actual type. + """ + inner_type = typ.get() + val = context.cast(builder, value, typ, inner_type) + imp = context.get_getattr(inner_type, attr) + return imp(context, builder, inner_type, val, attr) + +@lower_cast(types.Any, types.DeferredType) +@lower_cast(types.Optional, types.DeferredType) +@lower_cast(types.Boolean, types.DeferredType) +def any_to_deferred(context, builder, fromty, toty, val): + actual = context.cast(builder, val, fromty, toty.get()) + model = context.data_model_manager[toty] + return model.set(builder, model.make_uninitialized(), actual) + +@lower_cast(types.DeferredType, types.Any) +@lower_cast(types.DeferredType, types.Boolean) +@lower_cast(types.DeferredType, types.Optional) +def deferred_to_any(context, builder, fromty, toty, val): + model = context.data_model_manager[fromty] + val = model.get(builder, val) + return context.cast(builder, val, fromty.get(), toty) + + +#------------------------------------------------------------------------------ + +@lower_builtin(operator.getitem, types.CPointer, types.Integer) +def getitem_cpointer(context, builder, sig, args): + base_ptr, idx = args + elem_ptr = builder.gep(base_ptr, [idx]) + res = builder.load(elem_ptr) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(operator.setitem, types.CPointer, types.Integer, types.Any) +def setitem_cpointer(context, builder, sig, args): + base_ptr, idx, val = args + elem_ptr = builder.gep(base_ptr, [idx]) + builder.store(val, elem_ptr) + + +#------------------------------------------------------------------------------- + +def do_minmax(context, builder, argtys, args, cmpop): + assert len(argtys) == len(args), (argtys, args) + assert len(args) > 0 + + def binary_minmax(accumulator, value): + # This is careful to reproduce Python's algorithm, e.g. + # max(1.5, nan, 2.5) should return 2.5 (not nan or 1.5) + accty, acc = accumulator + vty, v = value + ty = context.typing_context.unify_types(accty, vty) + assert ty is not None + acc = context.cast(builder, acc, accty, ty) + v = context.cast(builder, v, vty, ty) + cmpsig = typing.signature(types.boolean, ty, ty) + ge = context.get_function(cmpop, cmpsig) + pred = ge(builder, (v, acc)) + res = builder.select(pred, v, acc) + return ty, res + + typvals = zip(argtys, args) + resty, resval = reduce(binary_minmax, typvals) + return resval + + +@lower_builtin(max, types.BaseTuple) +def max_iterable(context, builder, sig, args): + argtys = list(sig.args[0]) + args = cgutils.unpack_tuple(builder, args[0]) + return do_minmax(context, builder, argtys, args, operator.gt) + +@lower_builtin(max, types.VarArg(types.Any)) +def max_vararg(context, builder, sig, args): + return do_minmax(context, builder, sig.args, args, operator.gt) + +@lower_builtin(min, types.BaseTuple) +def min_iterable(context, builder, sig, args): + argtys = list(sig.args[0]) + args = cgutils.unpack_tuple(builder, args[0]) + return do_minmax(context, builder, argtys, args, operator.lt) + +@lower_builtin(min, types.VarArg(types.Any)) +def min_vararg(context, builder, sig, args): + return do_minmax(context, builder, sig.args, args, operator.lt) + + +def _round_intrinsic(tp): + # round() rounds half to even + return "llvm.rint.f%d" % (tp.bitwidth,) + +@lower_builtin(round, types.Float) +def round_impl_unary(context, builder, sig, args): + fltty = sig.args[0] + llty = context.get_value_type(fltty) + module = builder.module + fnty = ir.FunctionType(llty, [llty]) + fn = cgutils.get_or_insert_function(module, fnty, _round_intrinsic(fltty)) + res = builder.call(fn, args) + # unary round() returns an int + res = builder.fptosi(res, context.get_value_type(sig.return_type)) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(round, types.Float, types.Integer) +def round_impl_binary(context, builder, sig, args): + fltty = sig.args[0] + # Allow calling the intrinsic from the Python implementation below. + # This avoids the conversion to an int in Python 3's unary round(). + _round = types.ExternalFunction( + _round_intrinsic(fltty), typing.signature(fltty, fltty)) + + def round_ndigits(x, ndigits): + if math.isinf(x) or math.isnan(x): + return x + + if ndigits >= 0: + if ndigits > 22: + # pow1 and pow2 are each safe from overflow, but + # pow1*pow2 ~= pow(10.0, ndigits) might overflow. + pow1 = 10.0 ** (ndigits - 22) + pow2 = 1e22 + else: + pow1 = 10.0 ** ndigits + pow2 = 1.0 + y = (x * pow1) * pow2 + if math.isinf(y): + return x + return (_round(y) / pow2) / pow1 + + else: + pow1 = 10.0 ** (-ndigits) + y = x / pow1 + return _round(y) * pow1 + + res = context.compile_internal(builder, round_ndigits, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +#------------------------------------------------------------------------------- +# Numeric constructors + +@lower_builtin(int, types.Any) +@lower_builtin(float, types.Any) +def int_impl(context, builder, sig, args): + [ty] = sig.args + [val] = args + res = context.cast(builder, val, ty, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(float, types.StringLiteral) +def float_literal_impl(context, builder, sig, args): + [ty] = sig.args + res = context.get_constant(sig.return_type, float(ty.literal_value)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(complex, types.VarArg(types.Any)) +def complex_impl(context, builder, sig, args): + complex_type = sig.return_type + float_type = complex_type.underlying_float + if len(sig.args) == 1: + [argty] = sig.args + [arg] = args + if isinstance(argty, types.Complex): + # Cast Complex* to Complex* + res = context.cast(builder, arg, argty, complex_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + else: + real = context.cast(builder, arg, argty, float_type) + imag = context.get_constant(float_type, 0) + + elif len(sig.args) == 2: + [realty, imagty] = sig.args + [real, imag] = args + real = context.cast(builder, real, realty, float_type) + imag = context.cast(builder, imag, imagty, float_type) + + cmplx = context.make_complex(builder, complex_type) + cmplx.real = real + cmplx.imag = imag + res = cmplx._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(types.NumberClass, types.Any) +def number_constructor(context, builder, sig, args): + """ + Call a number class, e.g. np.int32(...) + """ + if isinstance(sig.return_type, types.Array): + # Array constructor + dt = sig.return_type.dtype + def foo(*arg_hack): + return np.array(arg_hack, dtype=dt) + res = context.compile_internal(builder, foo, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + else: + # Scalar constructor + [val] = args + [valty] = sig.args + return context.cast(builder, val, valty, sig.return_type) + + +#------------------------------------------------------------------------------- +# Constants + +@lower_constant(types.Dummy) +def constant_dummy(context, builder, ty, pyval): + # This handles None, etc. + return context.get_dummy_value() + +@lower_constant(types.ExternalFunctionPointer) +def constant_function_pointer(context, builder, ty, pyval): + ptrty = context.get_function_pointer_type(ty) + ptrval = context.add_dynamic_addr(builder, ty.get_pointer(pyval), + info=str(pyval)) + return builder.bitcast(ptrval, ptrty) + + +@lower_constant(types.Optional) +def constant_optional(context, builder, ty, pyval): + if pyval is None: + return context.make_optional_none(builder, ty.type) + else: + return context.make_optional_value(builder, ty.type, pyval) + + +# ----------------------------------------------------------------------------- + +@lower_builtin(type, types.Any) +def type_impl(context, builder, sig, args): + """ + One-argument type() builtin. + """ + return context.get_dummy_value() + + +@lower_builtin(iter, types.IterableType) +def iter_impl(context, builder, sig, args): + ty, = sig.args + val, = args + iterval = call_getiter(context, builder, ty, val) + return iterval + + +@lower_builtin(next, types.IteratorType) +def next_impl(context, builder, sig, args): + iterty, = sig.args + iterval, = args + + res = call_iternext(context, builder, iterty, iterval) + + with builder.if_then(builder.not_(res.is_valid()), likely=False): + context.call_conv.return_user_exc(builder, StopIteration, ()) + + return res.yielded_value() + + +# ----------------------------------------------------------------------------- + +@lower_builtin("not in", types.Any, types.Any) +def not_in(context, builder, sig, args): + def in_impl(a, b): + return operator.contains(b, a) + + res = context.compile_internal(builder, in_impl, sig, args) + return builder.not_(res) + + +# ----------------------------------------------------------------------------- + +@lower_builtin(len, types.ConstSized) +def constsized_len(context, builder, sig, args): + [ty] = sig.args + retty = sig.return_type + res = context.get_constant(retty, len(ty.types)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(bool, types.Sized) +def sized_bool(context, builder, sig, args): + [ty] = sig.args + if len(ty): + return cgutils.true_bit + else: + return cgutils.false_bit + +@lower_builtin(tuple) +def lower_empty_tuple(context, builder, sig, args): + retty = sig.return_type + res = context.get_constant_undef(retty) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(tuple, types.BaseTuple) +def lower_tuple(context, builder, sig, args): + val, = args + return impl_ret_borrowed(context, builder, sig.return_type, val) + +@overload(bool) +def bool_sequence(x): + valid_types = ( + types.CharSeq, + types.UnicodeCharSeq, + types.DictType, + types.ListType, + types.UnicodeType, + types.Set, + ) + + if isinstance(x, valid_types): + def bool_impl(x): + return len(x) > 0 + return bool_impl + +@overload(bool, inline='always') +def bool_none(x): + if isinstance(x, types.NoneType) or x is None: + return lambda x: False + +# ----------------------------------------------------------------------------- + +def get_type_max_value(typ): + if isinstance(typ, types.Float): + return np.inf + if isinstance(typ, types.Integer): + return typ.maxval + raise NotImplementedError("Unsupported type") + +def get_type_min_value(typ): + if isinstance(typ, types.Float): + return -np.inf + if isinstance(typ, types.Integer): + return typ.minval + raise NotImplementedError("Unsupported type") + +@infer_global(get_type_min_value) +@infer_global(get_type_max_value) +class MinValInfer(AbstractTemplate): + def generic(self, args, kws): + assert not kws + assert len(args) == 1 + if isinstance(args[0], (types.DType, types.NumberClass)): + return signature(args[0].dtype, *args) + +@lower_builtin(get_type_min_value, types.NumberClass) +@lower_builtin(get_type_min_value, types.DType) +def lower_get_type_min_value(context, builder, sig, args): + typ = sig.args[0].dtype + + if isinstance(typ, types.Integer): + bw = typ.bitwidth + lty = ir.IntType(bw) + val = typ.minval + res = ir.Constant(lty, val) + elif isinstance(typ, types.Float): + bw = typ.bitwidth + if bw == 32: + lty = ir.FloatType() + elif bw == 64: + lty = ir.DoubleType() + else: + raise NotImplementedError("llvmlite only supports 32 and 64 bit floats") + npty = getattr(np, 'float{}'.format(bw)) + res = ir.Constant(lty, -np.inf) + elif isinstance(typ, (types.NPDatetime, types.NPTimedelta)): + bw = 64 + lty = ir.IntType(bw) + val = types.int64.minval + 1 # minval is NaT, so minval + 1 is the smallest value + res = ir.Constant(lty, val) + return impl_ret_untracked(context, builder, lty, res) + +@lower_builtin(get_type_max_value, types.NumberClass) +@lower_builtin(get_type_max_value, types.DType) +def lower_get_type_max_value(context, builder, sig, args): + typ = sig.args[0].dtype + + if isinstance(typ, types.Integer): + bw = typ.bitwidth + lty = ir.IntType(bw) + val = typ.maxval + res = ir.Constant(lty, val) + elif isinstance(typ, types.Float): + bw = typ.bitwidth + if bw == 32: + lty = ir.FloatType() + elif bw == 64: + lty = ir.DoubleType() + else: + raise NotImplementedError("llvmlite only supports 32 and 64 bit floats") + npty = getattr(np, 'float{}'.format(bw)) + res = ir.Constant(lty, np.inf) + elif isinstance(typ, (types.NPDatetime, types.NPTimedelta)): + bw = 64 + lty = ir.IntType(bw) + val = types.int64.maxval + res = ir.Constant(lty, val) + return impl_ret_untracked(context, builder, lty, res) + +# ----------------------------------------------------------------------------- + +from numba.core.typing.builtins import IndexValue, IndexValueType +from numba.extending import overload, register_jitable + +@lower_builtin(IndexValue, types.intp, types.Type) +@lower_builtin(IndexValue, types.uintp, types.Type) +def impl_index_value(context, builder, sig, args): + typ = sig.return_type + index, value = args + index_value = cgutils.create_struct_proxy(typ)(context, builder) + index_value.index = index + index_value.value = value + return index_value._getvalue() + + +@overload(min) +def indval_min(indval1, indval2): + if isinstance(indval1, IndexValueType) and \ + isinstance(indval2, IndexValueType): + def min_impl(indval1, indval2): + if np.isnan(indval1.value): + if np.isnan(indval2.value): + # both indval1 and indval2 are nans so order by index + if indval1.index < indval2.index: + return indval1 + else: + return indval2 + else: + # comparing against one nan always considered less + return indval1 + elif np.isnan(indval2.value): + # indval1 not a nan but indval2 is so consider indval2 less + return indval2 + elif indval1.value > indval2.value: + return indval2 + elif indval1.value == indval2.value: + if indval1.index < indval2.index: + return indval1 + else: + return indval2 + return indval1 + return min_impl + + +@overload(min) +def boolval_min(val1, val2): + if isinstance(val1, types.Boolean) and \ + isinstance(val2, types.Boolean): + def bool_min_impl(val1, val2): + return val1 and val2 + return bool_min_impl + + +@overload(max) +def indval_max(indval1, indval2): + if isinstance(indval1, IndexValueType) and \ + isinstance(indval2, IndexValueType): + def max_impl(indval1, indval2): + if np.isnan(indval1.value): + if np.isnan(indval2.value): + # both indval1 and indval2 are nans so order by index + if indval1.index < indval2.index: + return indval1 + else: + return indval2 + else: + # comparing against one nan always considered larger + return indval1 + elif np.isnan(indval2.value): + # indval1 not a nan but indval2 is so consider indval2 larger + return indval2 + elif indval2.value > indval1.value: + return indval2 + elif indval1.value == indval2.value: + if indval1.index < indval2.index: + return indval1 + else: + return indval2 + return indval1 + return max_impl + + +@overload(max) +def boolval_max(val1, val2): + if isinstance(val1, types.Boolean) and \ + isinstance(val2, types.Boolean): + def bool_max_impl(val1, val2): + return val1 or val2 + return bool_max_impl + + +greater_than = register_jitable(lambda a, b: a > b) +less_than = register_jitable(lambda a, b: a < b) + + +@register_jitable +def min_max_impl(iterable, op): + if isinstance(iterable, types.IterableType): + def impl(iterable): + it = iter(iterable) + return_val = next(it) + for val in it: + if op(val, return_val): + return_val = val + return return_val + return impl + + +@overload(min) +def iterable_min(iterable): + return min_max_impl(iterable, less_than) + + +@overload(max) +def iterable_max(iterable): + return min_max_impl(iterable, greater_than) + + +@lower_builtin(types.TypeRef, types.VarArg(types.Any)) +def redirect_type_ctor(context, builder, sig, args): + """Redirect constructor implementation to `numba_typeref_ctor(cls, *args)`, + which should be overloaded by the type's implementation. + + For example: + + d = Dict() + + `d` will be typed as `TypeRef[DictType]()`. Thus, it will call into this + implementation. We need to redirect the lowering to a function + named ``numba_typeref_ctor``. + """ + cls = sig.return_type + + def call_ctor(cls, *args): + return numba_typeref_ctor(cls, *args) + + # Pack arguments into a tuple for `*args` + ctor_args = types.Tuple.from_types(sig.args) + # Make signature T(TypeRef[T], *args) where T is cls + sig = typing.signature(cls, types.TypeRef(cls), ctor_args) + if len(ctor_args) > 0: + args = (context.get_dummy_value(), # Type object has no runtime repr. + context.make_tuple(builder, ctor_args, args)) + else: + args = (context.get_dummy_value(), # Type object has no runtime repr. + context.make_tuple(builder, ctor_args, ())) + + return context.compile_internal(builder, call_ctor, sig, args) + + +@overload(sum) +def ol_sum(iterable, start=0): + # Cpython explicitly rejects strings, bytes and bytearrays + # https://github.com/python/cpython/blob/3.9/Python/bltinmodule.c#L2310-L2329 # noqa: E501 + error = None + if isinstance(start, types.UnicodeType): + error = ('strings', '') + elif isinstance(start, types.Bytes): + error = ('bytes', 'b') + elif isinstance(start, types.ByteArray): + error = ('bytearray', 'b') + + if error is not None: + msg = "sum() can't sum {} [use {}''.join(seq) instead]".format(*error) + raise TypingError(msg) + + # if the container is homogeneous then it's relatively easy to handle. + if isinstance(iterable, (types.containers._HomogeneousTuple, types.List, + types.ListType, types.Array, types.RangeType)): + iterator = iter + elif isinstance(iterable, (types.containers._HeterogeneousTuple)): + # if container is heterogeneous then literal unroll and hope for the + # best. + iterator = literal_unroll + else: + return None + + def impl(iterable, start=0): + acc = start + for x in iterator(iterable): + # This most likely widens the type, this is expected Numba behaviour + acc = acc + x + return acc + return impl + + +# ------------------------------------------------------------------------------ +# map, filter, reduce + + +@overload(map) +def ol_map(func, iterable, *args): + def impl(func, iterable, *args): + for x in zip(iterable, *args): + yield func(*x) + return impl + + +@overload(filter) +def ol_filter(func, iterable): + if (func is None) or isinstance(func, types.NoneType): + def impl(func, iterable): + for x in iterable: + if x: + yield x + else: + def impl(func, iterable): + for x in iterable: + if func(x): + yield x + return impl + + +@overload(isinstance) +def ol_isinstance(var, typs): + + def true_impl(var, typs): + return True + + def false_impl(var, typs): + return False + + var_ty = as_numba_type(var) + + if isinstance(var_ty, types.Optional): + msg = f'isinstance cannot handle optional types. Found: "{var_ty}"' + raise NumbaTypeError(msg) + + # NOTE: The current implementation of `isinstance` restricts the type of the + # instance variable to types that are well known and in common use. The + # danger of unrestricted type comparison is that a "default" of `False` is + # required and this means that if there is a bug in the logic of the + # comparison tree `isinstance` returns False! It's therefore safer to just + # reject the compilation as untypable! + supported_var_ty = (types.Number, types.Bytes, types.RangeType, + types.DictType, types.LiteralStrKeyDict, types.List, + types.ListType, types.Tuple, types.UniTuple, types.Set, + types.Function, types.ClassType, types.UnicodeType, + types.ClassInstanceType, types.NoneType, types.Array, + types.Boolean, types.Float, types.UnicodeCharSeq, + types.Complex, types.NPDatetime, types.NPTimedelta,) + if not isinstance(var_ty, supported_var_ty): + msg = f'isinstance() does not support variables of type "{var_ty}".' + raise NumbaTypeError(msg) + + t_typs = typs + + # Check the types that the var can be an instance of, it'll be a scalar, + # a unituple or a tuple. + if isinstance(t_typs, types.UniTuple): + # corner case - all types in isinstance are the same + t_typs = (t_typs.key[0]) + + if not isinstance(t_typs, types.Tuple): + t_typs = (t_typs, ) + + for typ in t_typs: + + if isinstance(typ, types.Function): + key = typ.key[0] # functions like int(..), float(..), str(..) + elif isinstance(typ, types.ClassType): + key = typ # jitclasses + else: + key = typ.key + + # corner cases for bytes, range, ... + # avoid registering those types on `as_numba_type` + types_not_registered = { + bytes: types.Bytes, + range: types.RangeType, + dict: (types.DictType, types.LiteralStrKeyDict), + list: types.List, + tuple: types.BaseTuple, + set: types.Set, + } + if key in types_not_registered: + if isinstance(var_ty, types_not_registered[key]): + return true_impl + continue + + if isinstance(typ, types.TypeRef): + # Use of Numba type classes is in general not supported as they do + # not work when the jit is disabled. + if key not in (types.ListType, types.DictType): + msg = ("Numba type classes (except numba.typed.* container " + "types) are not supported.") + raise NumbaTypeError(msg) + # Case for TypeRef (i.e. isinstance(var, typed.List)) + # var_ty == ListType[int64] (instance) + # typ == types.ListType (class) + return true_impl if type(var_ty) is key else false_impl + else: + numba_typ = as_numba_type(key) + if var_ty == numba_typ: + return true_impl + elif isinstance(numba_typ, (types.NPDatetime, types.NPTimedelta)): + if isinstance(var_ty, type(numba_typ)): + return true_impl + elif isinstance(numba_typ, types.ClassType) and \ + isinstance(var_ty, types.ClassInstanceType) and \ + var_ty.key == numba_typ.instance_type.key: + # check for jitclasses + return true_impl + elif isinstance(numba_typ, types.Container) and \ + numba_typ.key[0] == types.undefined: + # check for containers (list, tuple, set, ...) + if isinstance(var_ty, numba_typ.__class__) or \ + (isinstance(var_ty, types.BaseTuple) and \ + isinstance(numba_typ, types.BaseTuple)): + return true_impl + + return false_impl + + +# -- getattr implementation + +def _getattr_raise_attr_exc(obj, name): + # Dummy function for the purpose of creating an overloadable stub from + # which to raise an AttributeError as needed + pass + + +@overload(_getattr_raise_attr_exc) +def ol__getattr_raise_attr_exc(obj, name): + if not isinstance(name, types.StringLiteral): + raise RequireLiteralValue("argument 'name' must be a literal string") + lname = name.literal_value + message = f"'{obj}' has no attribute '{lname}'" + + def impl(obj, name): + raise AttributeError(message) + return impl + + +@intrinsic +def resolve_getattr(tyctx, obj, name, default): + if not isinstance(name, types.StringLiteral): + raise RequireLiteralValue("argument 'name' must be a literal string") + lname = name.literal_value + fn = tyctx.resolve_getattr(obj, lname) + # Cannot handle things like `getattr(np, 'cos')` as the return type is + # types.Function. + if isinstance(fn, types.Function): + msg = ("Returning function objects is not implemented. " + f"getattr() was requested to return {fn} from attribute " + f"'{lname}' of {obj}.") + raise TypingError(msg) + + if fn is None: # No attribute + + # if default is not _getattr_default then return the default + if not (isinstance(default, types.NamedTuple) and + default.instance_class == _getattr_default_type): + # it's not the marker default value, so return it + sig = default(obj, name, default) + def impl(cgctx, builder, sig, llargs): + tmp = llargs[-1] + cgctx.nrt.incref(builder, default, tmp) + return tmp + else: + # else wire in raising an AttributeError + fnty = tyctx.resolve_value_type(_getattr_raise_attr_exc) + raise_sig = fnty.get_call_type(tyctx, (obj, name), {}) + sig = types.none(obj, name, default) + def impl(cgctx, builder, sig, llargs): + native_impl = cgctx.get_function(fnty, raise_sig) + return native_impl(builder, llargs[:-1]) + + else: # Attribute present, wire in handing it back to the overload(getattr) + sig = fn(obj, name, default) + if isinstance(fn, types.BoundFunction): + # It's a method on an object + def impl(cgctx, builder, sig, ll_args): + cast_type = fn.this + casted = cgctx.cast(builder, ll_args[0], obj, cast_type) + res = cgctx.get_bound_function(builder, casted, cast_type) + cgctx.nrt.incref(builder, fn, res) + return res + else: + # Else it's some other type of attribute. + # Ensure typing calls occur at typing time, not at lowering + attrty = tyctx.resolve_getattr(obj, lname) + def impl(cgctx, builder, sig, ll_args): + attr_impl = cgctx.get_getattr(obj, lname) + res = attr_impl(cgctx, builder, obj, ll_args[0], lname) + casted = cgctx.cast(builder, res, attrty, fn) + cgctx.nrt.incref(builder, fn, casted) + return casted + return sig, impl + + +# These are marker objects to indicate "no default has been provided" in a call +_getattr_default_type = namedtuple('_getattr_default_type', '') +_getattr_default = _getattr_default_type() + + +# getattr with no default arg, obj is an open type and name is forced as a +# literal string. The _getattr_default marker is used to indicate "no default +# was provided". +@overload(getattr, prefer_literal=True) +def ol_getattr_2(obj, name): + def impl(obj, name): + return resolve_getattr(obj, name, _getattr_default) + return impl + + +# getattr with default arg present, obj is an open type, name is forced as a +# literal string, the "default" is again an open type. Note that the CPython +# definition is: `getattr(object, name[, default]) -> value`, the `default` +# is not a kwarg. +@overload(getattr) +def ol_getattr_3(obj, name, default): + def impl(obj, name, default): + return resolve_getattr(obj, name, default) + return impl + + +@intrinsic +def resolve_hasattr(tyctx, obj, name): + if not isinstance(name, types.StringLiteral): + raise RequireLiteralValue("argument 'name' must be a literal string") + lname = name.literal_value + fn = tyctx.resolve_getattr(obj, lname) + # Whilst technically the return type could be a types.bool_, the literal + # value is resolvable at typing time. Propagating this literal information + # into the type system allows the compiler to prune branches based on a + # hasattr predicate. As a result the signature is based on literals. This is + # "safe" because the overload requires a literal string so each will be a + # different variant of (obj, literal(name)) -> literal(bool). + if fn is None: + retty = types.literal(False) + else: + retty = types.literal(True) + sig = retty(obj, name) + def impl(cgctx, builder, sig, ll_args): + return cgutils.false_bit if fn is None else cgutils.true_bit + return sig, impl + +# hasattr cannot be implemented as a getattr call and then catching +# AttributeError because Numba doesn't support catching anything other than +# "Exception", so lacks the specificity required. Instead this implementation +# tries to resolve the attribute via typing information and returns True/False +# based on that. +@overload(hasattr) +def ol_hasattr(obj, name): + def impl(obj, name): + return resolve_hasattr(obj, name) + return impl + + +@overload(repr) +def ol_repr_generic(obj): + missing_repr_format = f"" + def impl(obj): + attr = '__repr__' + if hasattr(obj, attr) == True: + return getattr(obj, attr)() + else: + # There's no __str__ or __repr__ defined for this object, return + # something generic + return missing_repr_format + return impl + + +@overload(str) +def ol_str_generic(object=''): + def impl(object=""): + attr = '__str__' + if hasattr(object, attr) == True: + return getattr(object, attr)() + else: + return repr(object) + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/charseq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/charseq.py new file mode 100644 index 0000000000000000000000000000000000000000..9945c4117b3bf054451fdd7fb5bab41fb50ca41d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/charseq.py @@ -0,0 +1,1020 @@ +"""Implements operations on bytes and str (unicode) array items.""" +import operator +import numpy as np +from llvmlite import ir + +from numba.core import types, cgutils +from numba.core.extending import (overload, intrinsic, overload_method, + lower_cast, register_jitable) +from numba.core.cgutils import is_nonelike +from numba.cpython import unicode + +# bytes and str arrays items are of type CharSeq and UnicodeCharSeq, +# respectively. See numpy/types/npytypes.py for CharSeq, +# UnicodeCharSeq definitions. The corresponding data models are +# defined in numpy/datamodel/models.py. Boxing/unboxing of item types +# are defined in numpy/targets/boxing.py, see box_unicodecharseq, +# unbox_unicodecharseq, box_charseq, unbox_charseq. + +s1_dtype = np.dtype('S1') +assert s1_dtype.itemsize == 1 +bytes_type = types.Bytes(types.uint8, 1, "C", readonly=True) + +# Currently, NumPy supports only UTF-32 arrays but this may change in +# future and the approach used here for supporting str arrays may need +# a revision depending on how NumPy will support UTF-8 and UTF-16 +# arrays. +u1_dtype = np.dtype('U1') +unicode_byte_width = u1_dtype.itemsize +unicode_uint = {1: np.uint8, 2: np.uint16, 4: np.uint32}[unicode_byte_width] +unicode_kind = {1: unicode.PY_UNICODE_1BYTE_KIND, + 2: unicode.PY_UNICODE_2BYTE_KIND, + 4: unicode.PY_UNICODE_4BYTE_KIND}[unicode_byte_width] + + +# this is modified version of numba.unicode.make_deref_codegen +def make_deref_codegen(bitsize): + def codegen(context, builder, signature, args): + data, idx = args + rawptr = cgutils.alloca_once_value(builder, value=data) + ptr = builder.bitcast(rawptr, ir.IntType(bitsize).as_pointer()) + ch = builder.load(builder.gep(ptr, [idx])) + return builder.zext(ch, ir.IntType(32)) + return codegen + + +@intrinsic +def deref_uint8(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(8) + + +@intrinsic +def deref_uint16(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(16) + + +@intrinsic +def deref_uint32(typingctx, data, offset): + sig = types.uint32(data, types.intp) + return sig, make_deref_codegen(32) + + +@register_jitable(_nrt=False) +def charseq_get_code(a, i): + """Access i-th item of CharSeq object via code value + """ + return deref_uint8(a, i) + + +@register_jitable +def charseq_get_value(a, i): + """Access i-th item of CharSeq object via code value. + + null code is interpreted as IndexError + """ + code = charseq_get_code(a, i) + if code == 0: + raise IndexError('index out of range') + return code + + +@register_jitable(_nrt=False) +def unicode_charseq_get_code(a, i): + """Access i-th item of UnicodeCharSeq object via code value + """ + if unicode_byte_width == 4: + return deref_uint32(a, i) + elif unicode_byte_width == 2: + return deref_uint16(a, i) + elif unicode_byte_width == 1: + return deref_uint8(a, i) + else: + raise NotImplementedError( + 'unicode_charseq_get_code: unicode_byte_width not in [1, 2, 4]') + + +@register_jitable +def unicode_get_code(a, i): + """Access i-th item of UnicodeType object. + """ + return unicode._get_code_point(a, i) + + +@register_jitable +def bytes_get_code(a, i): + """Access i-th item of Bytes object. + """ + return a[i] + + +def _get_code_impl(a): + if isinstance(a, types.CharSeq): + return charseq_get_code + elif isinstance(a, types.Bytes): + return bytes_get_code + elif isinstance(a, types.UnicodeCharSeq): + return unicode_charseq_get_code + elif isinstance(a, types.UnicodeType): + return unicode_get_code + + +def _same_kind(a, b): + for t in [(types.CharSeq, types.Bytes), + (types.UnicodeCharSeq, types.UnicodeType)]: + if isinstance(a, t) and isinstance(b, t): + return True + return False + + +def _is_bytes(a): + return isinstance(a, (types.CharSeq, types.Bytes)) + + +def is_default(x, default): + return x == default or isinstance(x, types.Omitted) + + +@register_jitable +def unicode_charseq_get_value(a, i): + """Access i-th item of UnicodeCharSeq object via unicode value + + null code is interpreted as IndexError + """ + code = unicode_charseq_get_code(a, i) + if code == 0: + raise IndexError('index out of range') + # Return numpy equivalent of `chr(code)` + return np.array(code, unicode_uint).view(u1_dtype)[()] + + +# +# CAST +# +# Currently, the following casting operations are supported: +# Bytes -> CharSeq (ex: a=np.array(b'abc'); a[()] = b'123') +# UnicodeType -> UnicodeCharSeq (ex: a=np.array('abc'); a[()] = '123') +# CharSeq -> Bytes (ex: a=np.array(b'abc'); b = bytes(a[()])) +# UnicodeType -> Bytes (ex: str('123')._to_bytes()) +# +# The following casting operations can be implemented when required: +# Bytes -> UnicodeCharSeq (ex: a=np.array('abc'); a[()] = b'123') +# UnicodeType -> CharSeq (ex: a=np.array(b'abc'); a[()] = '123') +# UnicodeType -> Bytes (ex: bytes('123', 'utf8')) +# + + +@lower_cast(types.Bytes, types.CharSeq) +def bytes_to_charseq(context, builder, fromty, toty, val): + barr = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src = builder.bitcast(barr.data, ir.IntType(8).as_pointer()) + src_length = barr.nitems + + lty = context.get_value_type(toty) + dstint_t = ir.IntType(8) + dst_ptr = cgutils.alloca_once(builder, lty) + dst = builder.bitcast(dst_ptr, dstint_t.as_pointer()) + + dst_length = ir.Constant(src_length.type, toty.count) + is_shorter_value = builder.icmp_unsigned('<', src_length, dst_length) + count = builder.select(is_shorter_value, src_length, dst_length) + with builder.if_then(is_shorter_value): + cgutils.memset(builder, + dst, + ir.Constant(src_length.type, + toty.count), 0) + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + + return builder.load(dst_ptr) + + +def _make_constant_bytes(context, builder, nbytes): + bstr_ctor = cgutils.create_struct_proxy(bytes_type) + bstr = bstr_ctor(context, builder) + + if isinstance(nbytes, int): + nbytes = ir.Constant(bstr.nitems.type, nbytes) + + bstr.meminfo = context.nrt.meminfo_alloc(builder, nbytes) + bstr.nitems = nbytes + bstr.itemsize = ir.Constant(bstr.itemsize.type, 1) + bstr.data = context.nrt.meminfo_data(builder, bstr.meminfo) + bstr.parent = cgutils.get_null_value(bstr.parent.type) + # bstr.shape and bstr.strides are not used + bstr.shape = cgutils.get_null_value(bstr.shape.type) + bstr.strides = cgutils.get_null_value(bstr.strides.type) + return bstr + + +@lower_cast(types.CharSeq, types.Bytes) +def charseq_to_bytes(context, builder, fromty, toty, val): + bstr = _make_constant_bytes(context, builder, val.type.count) + rawptr = cgutils.alloca_once_value(builder, value=val) + ptr = builder.bitcast(rawptr, bstr.data.type) + cgutils.memcpy(builder, bstr.data, ptr, bstr.nitems) + return bstr + + +@lower_cast(types.UnicodeType, types.Bytes) +def unicode_to_bytes_cast(context, builder, fromty, toty, val): + uni_str = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src1 = builder.bitcast(uni_str.data, ir.IntType(8).as_pointer()) + notkind1 = builder.icmp_unsigned('!=', uni_str.kind, + ir.Constant(uni_str.kind.type, 1)) + src_length = uni_str.length + + with builder.if_then(notkind1): + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast higher than 8-bit unicode_type to bytes",)) + + bstr = _make_constant_bytes(context, builder, src_length) + cgutils.memcpy(builder, bstr.data, src1, bstr.nitems) + return bstr + + +@intrinsic +def _unicode_to_bytes(typingctx, s): + # used in _to_bytes method + assert s == types.unicode_type + sig = bytes_type(s) + + def codegen(context, builder, signature, args): + return unicode_to_bytes_cast( + context, builder, s, bytes_type, args[0])._getvalue() + return sig, codegen + + +@lower_cast(types.UnicodeType, types.UnicodeCharSeq) +def unicode_to_unicode_charseq(context, builder, fromty, toty, val): + uni_str = cgutils.create_struct_proxy(fromty)(context, builder, value=val) + src1 = builder.bitcast(uni_str.data, ir.IntType(8).as_pointer()) + src2 = builder.bitcast(uni_str.data, ir.IntType(16).as_pointer()) + src4 = builder.bitcast(uni_str.data, ir.IntType(32).as_pointer()) + kind1 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 1)) + kind2 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 2)) + kind4 = builder.icmp_unsigned('==', uni_str.kind, + ir.Constant(uni_str.kind.type, 4)) + src_length = uni_str.length + + lty = context.get_value_type(toty) + dstint_t = ir.IntType(8 * unicode_byte_width) + dst_ptr = cgutils.alloca_once(builder, lty) + dst = builder.bitcast(dst_ptr, dstint_t.as_pointer()) + + dst_length = ir.Constant(src_length.type, toty.count) + is_shorter_value = builder.icmp_unsigned('<', src_length, dst_length) + count = builder.select(is_shorter_value, src_length, dst_length) + with builder.if_then(is_shorter_value): + cgutils.memset(builder, + dst, + ir.Constant(src_length.type, + toty.count * unicode_byte_width), 0) + + with builder.if_then(kind1): + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src1, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + + with builder.if_then(kind2): + if unicode_byte_width >= 2: + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src2, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + else: + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast 16-bit unicode_type to %s-bit %s" + % (unicode_byte_width * 8, toty))) + + with builder.if_then(kind4): + if unicode_byte_width >= 4: + with cgutils.for_range(builder, count) as loop: + in_ptr = builder.gep(src4, [loop.index]) + in_val = builder.zext(builder.load(in_ptr), dstint_t) + builder.store(in_val, builder.gep(dst, [loop.index])) + else: + context.call_conv.return_user_exc( + builder, ValueError, + ("cannot cast 32-bit unicode_type to %s-bit %s" + % (unicode_byte_width * 8, toty))) + + return builder.load(dst_ptr) + +# +# Operations on bytes/str array items +# +# Implementation note: while some operations need +# CharSeq/UnicodeCharSeq specific implementations (getitem, len, str, +# etc), many operations can be supported by casting +# CharSeq/UnicodeCharSeq objects to Bytes/UnicodeType objects and +# re-use existing operations. +# +# However, in numba more operations are implemented for UnicodeType +# than for Bytes objects, hence the support for operations with bytes +# array items will be less complete than for str arrays. Although, in +# some cases (hash, contains, etc) the UnicodeType implementations can +# be reused for Bytes objects via using `_to_str` method. +# + + +@overload(operator.getitem) +def charseq_getitem(s, i): + get_value = None + if isinstance(i, types.Integer): + if isinstance(s, types.CharSeq): + get_value = charseq_get_value + if isinstance(s, types.UnicodeCharSeq): + get_value = unicode_charseq_get_value + if get_value is not None: + max_i = s.count + msg = 'index out of range [0, %s]' % (max_i - 1) + + def getitem_impl(s, i): + if i < max_i and i >= 0: + return get_value(s, i) + raise IndexError(msg) + return getitem_impl + + +@overload(len) +def charseq_len(s): + if isinstance(s, (types.CharSeq, types.UnicodeCharSeq)): + get_code = _get_code_impl(s) + n = s.count + if n == 0: + def len_impl(s): + return 0 + return len_impl + else: + def len_impl(s): + # return the index of the last non-null value (numpy + # behavior) + i = n + code = 0 + while code == 0: + i = i - 1 + if i < 0: + break + code = get_code(s, i) + return i + 1 + return len_impl + + +@overload(operator.add) +@overload(operator.iadd) +def charseq_concat(a, b): + if not _same_kind(a, b): + return + if (isinstance(a, types.UnicodeCharSeq) and + isinstance(b, types.UnicodeType)): + def impl(a, b): + return str(a) + b + return impl + if (isinstance(b, types.UnicodeCharSeq) and + isinstance(a, types.UnicodeType)): + def impl(a, b): + return a + str(b) + return impl + if (isinstance(a, types.UnicodeCharSeq) and + isinstance(b, types.UnicodeCharSeq)): + def impl(a, b): + return str(a) + str(b) + return impl + if (isinstance(a, (types.CharSeq, types.Bytes)) and + isinstance(b, (types.CharSeq, types.Bytes))): + def impl(a, b): + return (a._to_str() + b._to_str())._to_bytes() + return impl + + +@overload(operator.mul) +def charseq_repeat(a, b): + if isinstance(a, types.UnicodeCharSeq): + def wrap(a, b): + return str(a) * b + return wrap + if isinstance(b, types.UnicodeCharSeq): + def wrap(a, b): + return a * str(b) + return wrap + if isinstance(a, (types.CharSeq, types.Bytes)): + def wrap(a, b): + return (a._to_str() * b)._to_bytes() + return wrap + if isinstance(b, (types.CharSeq, types.Bytes)): + def wrap(a, b): + return (a * b._to_str())._to_bytes() + return wrap + + +@overload(operator.not_) +def charseq_not(a): + if isinstance(a, (types.UnicodeCharSeq, types.CharSeq, types.Bytes)): + def impl(a): + return len(a) == 0 + return impl + + +@overload(operator.eq) +def charseq_eq(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def eq_impl(a, b): + n = len(a) + if n != len(b): + return False + for i in range(n): + if left_code(a, i) != right_code(b, i): + return False + return True + return eq_impl + + +@overload(operator.ne) +def charseq_ne(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def ne_impl(a, b): + return not (a == b) + return ne_impl + + +@overload(operator.lt) +def charseq_lt(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def lt_impl(a, b): + na = len(a) + nb = len(b) + n = min(na, nb) + for i in range(n): + ca, cb = left_code(a, i), right_code(b, i) + if ca != cb: + return ca < cb + return na < nb + return lt_impl + + +@overload(operator.gt) +def charseq_gt(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def gt_impl(a, b): + return b < a + return gt_impl + + +@overload(operator.le) +def charseq_le(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def le_impl(a, b): + return not (a > b) + return le_impl + + +@overload(operator.ge) +def charseq_ge(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + def ge_impl(a, b): + return not (a < b) + return ge_impl + + +@overload(operator.contains) +def charseq_contains(a, b): + if not _same_kind(a, b): + return + left_code = _get_code_impl(a) + right_code = _get_code_impl(b) + if left_code is not None and right_code is not None: + if _is_bytes(a): + def contains_impl(a, b): + # Ideally, `return bytes(b) in bytes(a)` would be used + # here, but numba Bytes does not implement + # contains. So, using `unicode_type` implementation + # here: + return b._to_str() in a._to_str() + else: + def contains_impl(a, b): + return str(b) in str(a) + return contains_impl + + +@overload_method(types.UnicodeCharSeq, 'isascii') +@overload_method(types.CharSeq, 'isascii') +@overload_method(types.Bytes, 'isascii') +def charseq_isascii(s): + get_code = _get_code_impl(s) + + def impl(s): + for i in range(len(s)): + if get_code(s, i) > 127: + return False + return True + return impl + + +@overload_method(types.UnicodeCharSeq, '_get_kind') +@overload_method(types.CharSeq, '_get_kind') +def charseq_get_kind(s): + get_code = _get_code_impl(s) + + def impl(s): + max_code = 0 + for i in range(len(s)): + code = get_code(s, i) + if code > max_code: + max_code = code + if max_code > 0xffff: + return unicode.PY_UNICODE_4BYTE_KIND + if max_code > 0xff: + return unicode.PY_UNICODE_2BYTE_KIND + return unicode.PY_UNICODE_1BYTE_KIND + return impl + + +@overload_method(types.UnicodeType, '_to_bytes') +def unicode_to_bytes_mth(s): + """Convert unicode_type object to Bytes object. + + Note: The usage of _to_bytes method can be eliminated once all + Python bytes operations are implemented for numba Bytes objects. + + """ + def impl(s): + return _unicode_to_bytes(s) + return impl + + +@overload_method(types.CharSeq, '_to_str') +@overload_method(types.Bytes, '_to_str') +def charseq_to_str_mth(s): + """Convert bytes array item or bytes instance to UTF-8 str. + + Note: The usage of _to_str method can be eliminated once all + Python bytes operations are implemented for numba Bytes objects. + """ + get_code = _get_code_impl(s) + + def tostr_impl(s): + n = len(s) + is_ascii = s.isascii() + result = unicode._empty_string( + unicode.PY_UNICODE_1BYTE_KIND, n, is_ascii) + for i in range(n): + code = get_code(s, i) + unicode._set_code_point(result, i, code) + return result + return tostr_impl + + +@overload_method(types.UnicodeCharSeq, "__str__") +def charseq_str(s): + get_code = _get_code_impl(s) + + def str_impl(s): + n = len(s) + kind = s._get_kind() + is_ascii = kind == 1 and s.isascii() + result = unicode._empty_string(kind, n, is_ascii) + for i in range(n): + code = get_code(s, i) + unicode._set_code_point(result, i, code) + return result + + return str_impl + + +@overload(bytes) +def charseq_bytes(s): + if isinstance(s, types.CharSeq): + return lambda s: s + + +@overload_method(types.UnicodeCharSeq, '__hash__') +def unicode_charseq_hash(s): + def impl(s): + return hash(str(s)) + return impl + + +@overload_method(types.CharSeq, '__hash__') +def charseq_hash(s): + def impl(s): + # Ideally, `return hash(bytes(s))` would be used here but + # numba Bytes does not implement hash (yet). However, for a + # UTF-8 string `s`, we have hash(bytes(s)) == hash(s), hence, + # we can convert CharSeq object to unicode_type and reuse its + # hash implementation: + return hash(s._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'isupper') +def unicode_charseq_isupper(s): + def impl(s): + # workaround unicode_type.isupper bug: it returns int value + return not not str(s).isupper() + return impl + + +@overload_method(types.CharSeq, 'isupper') +def charseq_isupper(s): + def impl(s): + # return bytes(s).isupper() # TODO: implement isupper for Bytes + return not not s._to_str().isupper() + return impl + + +@overload_method(types.UnicodeCharSeq, 'upper') +def unicode_charseq_upper(s): + def impl(s): + return str(s).upper() + return impl + + +@overload_method(types.CharSeq, 'upper') +def charseq_upper(s): + def impl(s): + # return bytes(s).upper() # TODO: implement upper for Bytes + return s._to_str().upper()._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'find') +@overload_method(types.CharSeq, 'find') +@overload_method(types.Bytes, 'find') +def unicode_charseq_find(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).find(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).find(b) + return impl + if isinstance(a, types.CharSeq): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().find(b._to_str()) + return impl + if isinstance(a, types.UnicodeType): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return a.find(str(b)) + return impl + if isinstance(a, types.Bytes): + if isinstance(b, types.CharSeq): + def impl(a, b): + return a._to_str().find(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'rfind') +@overload_method(types.CharSeq, 'rfind') +@overload_method(types.Bytes, 'rfind') +def unicode_charseq_rfind(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).rfind(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).rfind(b) + return impl + if isinstance(a, types.CharSeq): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().rfind(b._to_str()) + return impl + if isinstance(a, types.UnicodeType): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return a.rfind(str(b)) + return impl + if isinstance(a, types.Bytes): + if isinstance(b, types.CharSeq): + def impl(a, b): + return a._to_str().rfind(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'startswith') +@overload_method(types.CharSeq, 'startswith') +@overload_method(types.Bytes, 'startswith') +def unicode_charseq_startswith(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).startswith(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).startswith(b) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().startswith(b._to_str()) + return impl + + +@overload_method(types.UnicodeCharSeq, 'endswith') +@overload_method(types.CharSeq, 'endswith') +@overload_method(types.Bytes, 'endswith') +def unicode_charseq_endswith(a, b): + if isinstance(a, types.UnicodeCharSeq): + if isinstance(b, types.UnicodeCharSeq): + def impl(a, b): + return str(a).endswith(str(b)) + return impl + if isinstance(b, types.UnicodeType): + def impl(a, b): + return str(a).endswith(b) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(b, (types.CharSeq, types.Bytes)): + def impl(a, b): + return a._to_str().endswith(b._to_str()) + return impl + + +@register_jitable +def _map_bytes(seq): + return [s._to_bytes() for s in seq] + + +@overload_method(types.UnicodeCharSeq, 'split') +@overload_method(types.CharSeq, 'split') +@overload_method(types.Bytes, 'split') +def unicode_charseq_split(a, sep=None, maxsplit=-1): + if not (maxsplit == -1 or + isinstance(maxsplit, (types.Omitted, types.Integer, + types.IntegerLiteral))): + return None + if isinstance(a, types.UnicodeCharSeq): + if isinstance(sep, types.UnicodeCharSeq): + def impl(a, sep=None, maxsplit=-1): + return str(a).split(sep=str(sep), maxsplit=maxsplit) + return impl + if isinstance(sep, types.UnicodeType): + def impl(a, sep=None, maxsplit=-1): + return str(a).split(sep=sep, maxsplit=maxsplit) + return impl + if is_nonelike(sep): + if is_default(maxsplit, -1): + def impl(a, sep=None, maxsplit=-1): + return str(a).split() + else: + def impl(a, sep=None, maxsplit=-1): + return str(a).split(maxsplit=maxsplit) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if isinstance(sep, (types.CharSeq, types.Bytes)): + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split(sep._to_str(), + maxsplit=maxsplit)) + return impl + if is_nonelike(sep): + if is_default(maxsplit, -1): + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split()) + else: + def impl(a, sep=None, maxsplit=-1): + return _map_bytes(a._to_str().split(maxsplit=maxsplit)) + return impl + +# NOT IMPLEMENTED: rsplit + + +@overload_method(types.UnicodeCharSeq, 'ljust') +@overload_method(types.CharSeq, 'ljust') +@overload_method(types.Bytes, 'ljust') +def unicode_charseq_ljust(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).ljust(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).ljust(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).ljust(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().ljust(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().ljust(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'rjust') +@overload_method(types.CharSeq, 'rjust') +@overload_method(types.Bytes, 'rjust') +def unicode_charseq_rjust(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).rjust(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).rjust(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).rjust(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().rjust(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().rjust(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'center') +@overload_method(types.CharSeq, 'center') +@overload_method(types.Bytes, 'center') +def unicode_charseq_center(a, width, fillchar=' '): + if isinstance(a, types.UnicodeCharSeq): + if is_default(fillchar, ' '): + def impl(a, width, fillchar=' '): + return str(a).center(width) + return impl + elif isinstance(fillchar, types.UnicodeCharSeq): + def impl(a, width, fillchar=' '): + return str(a).center(width, str(fillchar)) + return impl + elif isinstance(fillchar, types.UnicodeType): + def impl(a, width, fillchar=' '): + return str(a).center(width, fillchar) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_default(fillchar, ' ') or is_default(fillchar, b' '): + def impl(a, width, fillchar=' '): + return a._to_str().center(width)._to_bytes() + return impl + elif isinstance(fillchar, (types.CharSeq, types.Bytes)): + def impl(a, width, fillchar=' '): + return a._to_str().center(width, fillchar._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'zfill') +@overload_method(types.CharSeq, 'zfill') +@overload_method(types.Bytes, 'zfill') +def unicode_charseq_zfill(a, width): + if isinstance(a, types.UnicodeCharSeq): + def impl(a, width): + return str(a).zfill(width) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + def impl(a, width): + return a._to_str().zfill(width)._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'lstrip') +@overload_method(types.CharSeq, 'lstrip') +@overload_method(types.Bytes, 'lstrip') +def unicode_charseq_lstrip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).lstrip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).lstrip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).lstrip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().lstrip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().lstrip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'rstrip') +@overload_method(types.CharSeq, 'rstrip') +@overload_method(types.Bytes, 'rstrip') +def unicode_charseq_rstrip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).rstrip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).rstrip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).rstrip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().rstrip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().rstrip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'strip') +@overload_method(types.CharSeq, 'strip') +@overload_method(types.Bytes, 'strip') +def unicode_charseq_strip(a, chars=None): + if isinstance(a, types.UnicodeCharSeq): + if is_nonelike(chars): + def impl(a, chars=None): + return str(a).strip() + return impl + elif isinstance(chars, types.UnicodeCharSeq): + def impl(a, chars=None): + return str(a).strip(str(chars)) + return impl + elif isinstance(chars, types.UnicodeType): + def impl(a, chars=None): + return str(a).strip(chars) + return impl + if isinstance(a, (types.CharSeq, types.Bytes)): + if is_nonelike(chars): + def impl(a, chars=None): + return a._to_str().strip()._to_bytes() + return impl + elif isinstance(chars, (types.CharSeq, types.Bytes)): + def impl(a, chars=None): + return a._to_str().strip(chars._to_str())._to_bytes() + return impl + + +@overload_method(types.UnicodeCharSeq, 'join') +@overload_method(types.CharSeq, 'join') +@overload_method(types.Bytes, 'join') +def unicode_charseq_join(a, parts): + + if isinstance(a, types.UnicodeCharSeq): + # assuming parts contains UnicodeCharSeq or UnicodeType objects + def impl(a, parts): + _parts = [str(p) for p in parts] + return str(a).join(_parts) + return impl + + if isinstance(a, (types.CharSeq, types.Bytes)): + # assuming parts contains CharSeq or Bytes objects + def impl(a, parts): + _parts = [p._to_str() for p in parts] + return a._to_str().join(_parts)._to_bytes() + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/cmathimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/cmathimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4305e9d45dde68b5f32b56e462bd5b064bfaed18 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/cmathimpl.py @@ -0,0 +1,542 @@ +""" +Implement the cmath module functions. +""" + + +import cmath +import math + +from numba.core.imputils import Registry, impl_ret_untracked +from numba.core import types, cgutils +from numba.core.typing import signature +from numba.cpython import builtins, mathimpl +from numba.core.extending import overload + +registry = Registry('cmathimpl') +lower = registry.lower + + +def is_nan(builder, z): + return builder.fcmp_unordered('uno', z.real, z.imag) + +def is_inf(builder, z): + return builder.or_(mathimpl.is_inf(builder, z.real), + mathimpl.is_inf(builder, z.imag)) + +def is_finite(builder, z): + return builder.and_(mathimpl.is_finite(builder, z.real), + mathimpl.is_finite(builder, z.imag)) + + +@lower(cmath.isnan, types.Complex) +def isnan_float_impl(context, builder, sig, args): + [typ] = sig.args + [value] = args + z = context.make_complex(builder, typ, value=value) + res = is_nan(builder, z) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower(cmath.isinf, types.Complex) +def isinf_float_impl(context, builder, sig, args): + [typ] = sig.args + [value] = args + z = context.make_complex(builder, typ, value=value) + res = is_inf(builder, z) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(cmath.isfinite, types.Complex) +def isfinite_float_impl(context, builder, sig, args): + [typ] = sig.args + [value] = args + z = context.make_complex(builder, typ, value=value) + res = is_finite(builder, z) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@overload(cmath.rect) +def impl_cmath_rect(r, phi): + if all([isinstance(typ, types.Float) for typ in [r, phi]]): + def impl(r, phi): + if not math.isfinite(phi): + if not r: + # cmath.rect(0, phi={inf, nan}) = 0 + return abs(r) + if math.isinf(r): + # cmath.rect(inf, phi={inf, nan}) = inf + j phi + return complex(r, phi) + real = math.cos(phi) + imag = math.sin(phi) + if real == 0. and math.isinf(r): + # 0 * inf would return NaN, we want to keep 0 but xor the sign + real /= r + else: + real *= r + if imag == 0. and math.isinf(r): + # ditto + imag /= r + else: + imag *= r + return complex(real, imag) + return impl + + +def intrinsic_complex_unary(inner_func): + def wrapper(context, builder, sig, args): + [typ] = sig.args + [value] = args + z = context.make_complex(builder, typ, value=value) + x = z.real + y = z.imag + # Same as above: math.isfinite() is unavailable on 2.x so we precompute + # its value and pass it to the pure Python implementation. + x_is_finite = mathimpl.is_finite(builder, x) + y_is_finite = mathimpl.is_finite(builder, y) + inner_sig = signature(sig.return_type, + *(typ.underlying_float,) * 2 + (types.boolean,) * 2) + res = context.compile_internal(builder, inner_func, inner_sig, + (x, y, x_is_finite, y_is_finite)) + return impl_ret_untracked(context, builder, sig, res) + return wrapper + + +NAN = float('nan') +INF = float('inf') + +@lower(cmath.exp, types.Complex) +@intrinsic_complex_unary +def exp_impl(x, y, x_is_finite, y_is_finite): + """cmath.exp(x + y j)""" + if x_is_finite: + if y_is_finite: + c = math.cos(y) + s = math.sin(y) + r = math.exp(x) + return complex(r * c, r * s) + else: + return complex(NAN, NAN) + elif math.isnan(x): + if y: + return complex(x, x) # nan + j nan + else: + return complex(x, y) # nan + 0j + elif x > 0.0: + # x == +inf + if y_is_finite: + real = math.cos(y) + imag = math.sin(y) + # Avoid NaNs if math.cos(y) or math.sin(y) == 0 + # (e.g. cmath.exp(inf + 0j) == inf + 0j) + if real != 0: + real *= x + if imag != 0: + imag *= x + return complex(real, imag) + else: + return complex(x, NAN) + else: + # x == -inf + if y_is_finite: + r = math.exp(x) + c = math.cos(y) + s = math.sin(y) + return complex(r * c, r * s) + else: + r = 0 + return complex(r, r) + +@lower(cmath.log, types.Complex) +@intrinsic_complex_unary +def log_impl(x, y, x_is_finite, y_is_finite): + """cmath.log(x + y j)""" + a = math.log(math.hypot(x, y)) + b = math.atan2(y, x) + return complex(a, b) + + +@lower(cmath.log, types.Complex, types.Complex) +def log_base_impl(context, builder, sig, args): + """cmath.log(z, base)""" + [z, base] = args + + def log_base(z, base): + return cmath.log(z) / cmath.log(base) + + res = context.compile_internal(builder, log_base, sig, args) + return impl_ret_untracked(context, builder, sig, res) + + +@overload(cmath.log10) +def impl_cmath_log10(z): + if not isinstance(z, types.Complex): + return + + LN_10 = 2.302585092994045684 + + def log10_impl(z): + """cmath.log10(z)""" + z = cmath.log(z) + # This formula gives better results on +/-inf than cmath.log(z, 10) + # See http://bugs.python.org/issue22544 + return complex(z.real / LN_10, z.imag / LN_10) + + return log10_impl + + +@overload(cmath.phase) +def phase_impl(x): + """cmath.phase(x + y j)""" + + if not isinstance(x, types.Complex): + return + + def impl(x): + return math.atan2(x.imag, x.real) + return impl + + +@overload(cmath.polar) +def polar_impl(x): + if not isinstance(x, types.Complex): + return + + def impl(x): + r, i = x.real, x.imag + return math.hypot(r, i), math.atan2(i, r) + return impl + + +@lower(cmath.sqrt, types.Complex) +def sqrt_impl(context, builder, sig, args): + # We risk spurious overflow for components >= FLT_MAX / (1 + sqrt(2)). + + SQRT2 = 1.414213562373095048801688724209698079E0 + ONE_PLUS_SQRT2 = (1. + SQRT2) + theargflt = sig.args[0].underlying_float + # Get a type specific maximum value so scaling for overflow is based on that + MAX = mathimpl.DBL_MAX if theargflt.bitwidth == 64 else mathimpl.FLT_MAX + # THRES will be double precision, should not impact typing as it's just + # used for comparison, there *may* be a few values near THRES which + # deviate from e.g. NumPy due to rounding that occurs in the computation + # of this value in the case of a 32bit argument. + THRES = MAX / ONE_PLUS_SQRT2 + + def sqrt_impl(z): + """cmath.sqrt(z)""" + # This is NumPy's algorithm, see npy_csqrt() in npy_math_complex.c.src + a = z.real + b = z.imag + if a == 0.0 and b == 0.0: + return complex(abs(b), b) + if math.isinf(b): + return complex(abs(b), b) + if math.isnan(a): + return complex(a, a) + if math.isinf(a): + if a < 0.0: + return complex(abs(b - b), math.copysign(a, b)) + else: + return complex(a, math.copysign(b - b, b)) + + # The remaining special case (b is NaN) is handled just fine by + # the normal code path below. + + # Scale to avoid overflow + if abs(a) >= THRES or abs(b) >= THRES: + a *= 0.25 + b *= 0.25 + scale = True + else: + scale = False + # Algorithm 312, CACM vol 10, Oct 1967 + if a >= 0: + t = math.sqrt((a + math.hypot(a, b)) * 0.5) + real = t + imag = b / (2 * t) + else: + t = math.sqrt((-a + math.hypot(a, b)) * 0.5) + real = abs(b) / (2 * t) + imag = math.copysign(t, b) + # Rescale + if scale: + return complex(real * 2, imag) + else: + return complex(real, imag) + + res = context.compile_internal(builder, sqrt_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + + +@lower(cmath.cos, types.Complex) +def cos_impl(context, builder, sig, args): + def cos_impl(z): + """cmath.cos(z) = cmath.cosh(z j)""" + return cmath.cosh(complex(-z.imag, z.real)) + + res = context.compile_internal(builder, cos_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@overload(cmath.cosh) +def impl_cmath_cosh(z): + if not isinstance(z, types.Complex): + return + + def cosh_impl(z): + """cmath.cosh(z)""" + x = z.real + y = z.imag + if math.isinf(x): + if math.isnan(y): + # x = +inf, y = NaN => cmath.cosh(x + y j) = inf + Nan * j + real = abs(x) + imag = y + elif y == 0.0: + # x = +inf, y = 0 => cmath.cosh(x + y j) = inf + 0j + real = abs(x) + imag = y + else: + real = math.copysign(x, math.cos(y)) + imag = math.copysign(x, math.sin(y)) + if x < 0.0: + # x = -inf => negate imaginary part of result + imag = -imag + return complex(real, imag) + return complex(math.cos(y) * math.cosh(x), + math.sin(y) * math.sinh(x)) + return cosh_impl + + +@lower(cmath.sin, types.Complex) +def sin_impl(context, builder, sig, args): + def sin_impl(z): + """cmath.sin(z) = -j * cmath.sinh(z j)""" + r = cmath.sinh(complex(-z.imag, z.real)) + return complex(r.imag, -r.real) + + res = context.compile_internal(builder, sin_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@overload(cmath.sinh) +def impl_cmath_sinh(z): + if not isinstance(z, types.Complex): + return + + def sinh_impl(z): + """cmath.sinh(z)""" + x = z.real + y = z.imag + if math.isinf(x): + if math.isnan(y): + # x = +/-inf, y = NaN => cmath.sinh(x + y j) = x + NaN * j + real = x + imag = y + else: + real = math.cos(y) + imag = math.sin(y) + if real != 0.: + real *= x + if imag != 0.: + imag *= abs(x) + return complex(real, imag) + return complex(math.cos(y) * math.sinh(x), + math.sin(y) * math.cosh(x)) + return sinh_impl + + +@lower(cmath.tan, types.Complex) +def tan_impl(context, builder, sig, args): + def tan_impl(z): + """cmath.tan(z) = -j * cmath.tanh(z j)""" + r = cmath.tanh(complex(-z.imag, z.real)) + return complex(r.imag, -r.real) + + res = context.compile_internal(builder, tan_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + + +@overload(cmath.tanh) +def impl_cmath_tanh(z): + if not isinstance(z, types.Complex): + return + + def tanh_impl(z): + """cmath.tanh(z)""" + x = z.real + y = z.imag + if math.isinf(x): + real = math.copysign(1., x) + if math.isinf(y): + imag = 0. + else: + imag = math.copysign(0., math.sin(2. * y)) + return complex(real, imag) + # This is CPython's algorithm (see c_tanh() in cmathmodule.c). + # XXX how to force float constants into single precision? + tx = math.tanh(x) + ty = math.tan(y) + cx = 1. / math.cosh(x) + txty = tx * ty + denom = 1. + txty * txty + return complex( + tx * (1. + ty * ty) / denom, + ((ty / denom) * cx) * cx) + + return tanh_impl + + +@lower(cmath.acos, types.Complex) +def acos_impl(context, builder, sig, args): + LN_4 = math.log(4) + THRES = mathimpl.FLT_MAX / 4 + + def acos_impl(z): + """cmath.acos(z)""" + # CPython's algorithm (see c_acos() in cmathmodule.c) + if abs(z.real) > THRES or abs(z.imag) > THRES: + # Avoid unnecessary overflow for large arguments + # (also handles infinities gracefully) + real = math.atan2(abs(z.imag), z.real) + imag = math.copysign( + math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4, + -z.imag) + return complex(real, imag) + else: + s1 = cmath.sqrt(complex(1. - z.real, -z.imag)) + s2 = cmath.sqrt(complex(1. + z.real, z.imag)) + real = 2. * math.atan2(s1.real, s2.real) + imag = math.asinh(s2.real * s1.imag - s2.imag * s1.real) + return complex(real, imag) + + res = context.compile_internal(builder, acos_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@overload(cmath.acosh) +def impl_cmath_acosh(z): + if not isinstance(z, types.Complex): + return + + LN_4 = math.log(4) + THRES = mathimpl.FLT_MAX / 4 + + def acosh_impl(z): + """cmath.acosh(z)""" + # CPython's algorithm (see c_acosh() in cmathmodule.c) + if abs(z.real) > THRES or abs(z.imag) > THRES: + # Avoid unnecessary overflow for large arguments + # (also handles infinities gracefully) + real = math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4 + imag = math.atan2(z.imag, z.real) + return complex(real, imag) + else: + s1 = cmath.sqrt(complex(z.real - 1., z.imag)) + s2 = cmath.sqrt(complex(z.real + 1., z.imag)) + real = math.asinh(s1.real * s2.real + s1.imag * s2.imag) + imag = 2. * math.atan2(s1.imag, s2.real) + return complex(real, imag) + # Condensed formula (NumPy) + #return cmath.log(z + cmath.sqrt(z + 1.) * cmath.sqrt(z - 1.)) + + return acosh_impl + + +@lower(cmath.asinh, types.Complex) +def asinh_impl(context, builder, sig, args): + LN_4 = math.log(4) + THRES = mathimpl.FLT_MAX / 4 + + def asinh_impl(z): + """cmath.asinh(z)""" + # CPython's algorithm (see c_asinh() in cmathmodule.c) + if abs(z.real) > THRES or abs(z.imag) > THRES: + real = math.copysign( + math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4, + z.real) + imag = math.atan2(z.imag, abs(z.real)) + return complex(real, imag) + else: + s1 = cmath.sqrt(complex(1. + z.imag, -z.real)) + s2 = cmath.sqrt(complex(1. - z.imag, z.real)) + real = math.asinh(s1.real * s2.imag - s2.real * s1.imag) + imag = math.atan2(z.imag, s1.real * s2.real - s1.imag * s2.imag) + return complex(real, imag) + + res = context.compile_internal(builder, asinh_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@lower(cmath.asin, types.Complex) +def asin_impl(context, builder, sig, args): + def asin_impl(z): + """cmath.asin(z) = -j * cmath.asinh(z j)""" + r = cmath.asinh(complex(-z.imag, z.real)) + return complex(r.imag, -r.real) + + res = context.compile_internal(builder, asin_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@lower(cmath.atan, types.Complex) +def atan_impl(context, builder, sig, args): + def atan_impl(z): + """cmath.atan(z) = -j * cmath.atanh(z j)""" + r = cmath.atanh(complex(-z.imag, z.real)) + if math.isinf(z.real) and math.isnan(z.imag): + # XXX this is odd but necessary + return complex(r.imag, r.real) + else: + return complex(r.imag, -r.real) + + res = context.compile_internal(builder, atan_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) + +@lower(cmath.atanh, types.Complex) +def atanh_impl(context, builder, sig, args): + LN_4 = math.log(4) + THRES_LARGE = math.sqrt(mathimpl.FLT_MAX / 4) + THRES_SMALL = math.sqrt(mathimpl.FLT_MIN) + PI_12 = math.pi / 2 + + def atanh_impl(z): + """cmath.atanh(z)""" + # CPython's algorithm (see c_atanh() in cmathmodule.c) + if z.real < 0.: + # Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). + negate = True + z = -z + else: + negate = False + + ay = abs(z.imag) + if math.isnan(z.real) or z.real > THRES_LARGE or ay > THRES_LARGE: + if math.isinf(z.imag): + real = math.copysign(0., z.real) + elif math.isinf(z.real): + real = 0. + else: + # may be safe from overflow, depending on hypot's implementation... + h = math.hypot(z.real * 0.5, z.imag * 0.5) + real = z.real/4./h/h + imag = -math.copysign(PI_12, -z.imag) + elif z.real == 1. and ay < THRES_SMALL: + # C99 standard says: atanh(1+/-0.) should be inf +/- 0j + if ay == 0.: + real = INF + imag = z.imag + else: + real = -math.log(math.sqrt(ay) / + math.sqrt(math.hypot(ay, 2.))) + imag = math.copysign(math.atan2(2., -ay) / 2, z.imag) + else: + sqay = ay * ay + zr1 = 1 - z.real + real = math.log1p(4. * z.real / (zr1 * zr1 + sqay)) * 0.25 + imag = -math.atan2(-2. * z.imag, + zr1 * (1 + z.real) - sqay) * 0.5 + + if math.isnan(z.imag): + imag = NAN + if negate: + return complex(-real, -imag) + else: + return complex(real, imag) + + res = context.compile_internal(builder, atanh_impl, sig, args) + return impl_ret_untracked(context, builder, sig, res) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/enumimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/enumimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4d811d22e5e9272486bd1cdf594ed573478eb751 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/enumimpl.py @@ -0,0 +1,89 @@ +""" +Implementation of enums. +""" +import operator + +from numba.core.imputils import (lower_builtin, lower_getattr, + lower_getattr_generic, lower_cast, + lower_constant, impl_ret_untracked) +from numba.core import types +from numba.core.extending import overload_method + + +@lower_builtin(operator.eq, types.EnumMember, types.EnumMember) +def enum_eq(context, builder, sig, args): + tu, tv = sig.args + u, v = args + res = context.generic_compare(builder, operator.eq, + (tu.dtype, tv.dtype), (u, v)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.is_, types.EnumMember, types.EnumMember) +def enum_is(context, builder, sig, args): + tu, tv = sig.args + u, v = args + if tu == tv: + res = context.generic_compare(builder, operator.eq, + (tu.dtype, tv.dtype), (u, v)) + else: + res = context.get_constant(sig.return_type, False) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.ne, types.EnumMember, types.EnumMember) +def enum_ne(context, builder, sig, args): + tu, tv = sig.args + u, v = args + res = context.generic_compare(builder, operator.ne, + (tu.dtype, tv.dtype), (u, v)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_getattr(types.EnumMember, 'value') +def enum_value(context, builder, ty, val): + return val + + +@lower_cast(types.IntEnumMember, types.Integer) +def int_enum_to_int(context, builder, fromty, toty, val): + """ + Convert an IntEnum member to its raw integer value. + """ + return context.cast(builder, val, fromty.dtype, toty) + + +@lower_constant(types.EnumMember) +def enum_constant(context, builder, ty, pyval): + """ + Return a LLVM constant representing enum member *pyval*. + """ + return context.get_constant_generic(builder, ty.dtype, pyval.value) + + +@lower_getattr_generic(types.EnumClass) +def enum_class_getattr(context, builder, ty, val, attr): + """ + Return an enum member by attribute name. + """ + member = getattr(ty.instance_class, attr) + return context.get_constant_generic(builder, ty.dtype, member.value) + + +@lower_builtin('static_getitem', types.EnumClass, types.StringLiteral) +def enum_class_getitem(context, builder, sig, args): + """ + Return an enum member by index name. + """ + enum_cls_typ, idx = sig.args + member = enum_cls_typ.instance_class[idx.literal_value] + return context.get_constant_generic(builder, enum_cls_typ.dtype, + member.value) + + +@overload_method(types.IntEnumMember, '__hash__') +def intenum_hash(val): + # uses the hash of the value, for IntEnums this will be int.__hash__ + def hash_impl(val): + return hash(val.value) + return hash_impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/hashing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..836d1616a2a49e291321fce0823492cc48e33273 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/hashing.py @@ -0,0 +1,743 @@ +""" +Hash implementations for Numba types +""" + +import math +import numpy as np +import sys +import ctypes +import warnings +from collections import namedtuple + +import llvmlite.binding as ll +from llvmlite import ir + +from numba import literal_unroll +from numba.core.extending import ( + overload, overload_method, intrinsic, register_jitable) +from numba.core import errors +from numba.core import types +from numba.core.unsafe.bytes import grab_byte, grab_uint64_t +from numba.cpython.randomimpl import (const_int, get_next_int, get_next_int32, + get_state_ptr) + +# This is Py_hash_t, which is a Py_ssize_t, which has sizeof(size_t): +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Include/pyport.h#L91-L96 # noqa: E501 +_hash_width = sys.hash_info.width +_Py_hash_t = getattr(types, 'int%s' % _hash_width) +_Py_uhash_t = getattr(types, 'uint%s' % _hash_width) + +# Constants from CPython source, obtained by various means: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Include/pyhash.h # noqa: E501 +_PyHASH_INF = sys.hash_info.inf +_PyHASH_NAN = sys.hash_info.nan +_PyHASH_MODULUS = _Py_uhash_t(sys.hash_info.modulus) +_PyHASH_BITS = 31 if types.intp.bitwidth == 32 else 61 # mersenne primes +_PyHASH_MULTIPLIER = 0xf4243 # 1000003UL +_PyHASH_IMAG = _PyHASH_MULTIPLIER +_PyLong_SHIFT = sys.int_info.bits_per_digit +_Py_HASH_CUTOFF = sys.hash_info.cutoff +_Py_hashfunc_name = sys.hash_info.algorithm + + +# This stub/overload pair are used to force branch pruning to remove the dead +# branch based on the potential `None` type of the hash_func which works better +# if the predicate for the prune in an ir.Arg. The obj is an arg to allow for +# a custom error message. +def _defer_hash(hash_func): + pass + + +@overload(_defer_hash) +def ol_defer_hash(obj, hash_func): + err_msg = f"unhashable type: '{obj}'" + + def impl(obj, hash_func): + if hash_func is None: + raise TypeError(err_msg) + else: + return hash_func() + return impl + + +# hash(obj) is implemented by calling obj.__hash__() +@overload(hash) +def hash_overload(obj): + attempt_generic_msg = ("No __hash__ is defined for object of type " + f"'{obj}' and a generic hash() cannot be " + "performed as there is no suitable object " + "represention in Numba compiled code!") + + def impl(obj): + if hasattr(obj, '__hash__'): + return _defer_hash(obj, getattr(obj, '__hash__')) + else: + raise TypeError(attempt_generic_msg) + return impl + + +@register_jitable +def process_return(val): + asint = _Py_hash_t(val) + if (asint == int(-1)): + asint = int(-2) + return asint + + +# This is a translation of CPython's _Py_HashDouble: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Python/pyhash.c#L34-L129 # noqa: E501 +# NOTE: In Python 3.10 hash of nan is now hash of the pointer to the PyObject +# containing said nan. Numba cannot replicate this as there is no object, so it +# elects to replicate the behaviour i.e. hash of nan is something "unique" which +# satisfies https://bugs.python.org/issue43475. + +@register_jitable(locals={'x': _Py_uhash_t, + 'y': _Py_uhash_t, + 'm': types.double, + 'e': types.intc, + 'sign': types.intc, + '_PyHASH_MODULUS': _Py_uhash_t, + '_PyHASH_BITS': types.intc}) +def _Py_HashDouble(v): + if not np.isfinite(v): + if (np.isinf(v)): + if (v > 0): + return _PyHASH_INF + else: + return -_PyHASH_INF + else: + # Python 3.10 does not use `_PyHASH_NAN`. + # https://github.com/python/cpython/blob/2c4792264f9218692a1bd87398a60591f756b171/Python/pyhash.c#L102 # noqa: E501 + # Numba returns a pseudo-random number to reflect the spirit of the + # change. + x = _prng_random_hash() + return process_return(x) + + m, e = math.frexp(v) + + sign = 1 + if (m < 0): + sign = -1 + m = -m + + # process 28 bits at a time; this should work well both for binary + # and hexadecimal floating point. + x = 0 + while (m): + x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28) + m *= 268435456.0 # /* 2**28 */ + e -= 28 + y = int(m) # /* pull out integer part */ + m -= y + x += y + if x >= _PyHASH_MODULUS: + x -= _PyHASH_MODULUS + # /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */ + if e >= 0: + e = e % _PyHASH_BITS + else: + e = _PyHASH_BITS - 1 - ((-1 - e) % _PyHASH_BITS) + + x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e) + + x = x * sign + return process_return(x) + + +@intrinsic +def _fpext(tyctx, val): + def impl(cgctx, builder, signature, args): + val = args[0] + return builder.fpext(val, ir.DoubleType()) + sig = types.float64(types.float32) + return sig, impl + + +@intrinsic +def _prng_random_hash(tyctx): + + def impl(cgctx, builder, signature, args): + state_ptr = get_state_ptr(cgctx, builder, "internal") + bits = const_int(_hash_width) + + # Why not just use get_next_int() with the correct bitwidth? + # get_next_int() always returns an i64, because the bitwidth it is + # passed may not be a compile-time constant, so it needs to allocate + # the largest unit of storage that may be required. Therefore, if the + # hash width is 32, then we need to use get_next_int32() to ensure we + # don't return a wider-than-expected hash, even if everything above + # the low 32 bits would have been zero. + if _hash_width == 32: + value = get_next_int32(cgctx, builder, state_ptr) + else: + value = get_next_int(cgctx, builder, state_ptr, bits, False) + + return value + + sig = _Py_hash_t() + return sig, impl + + +# This is a translation of CPython's long_hash, but restricted to the numerical +# domain reachable by int64/uint64 (i.e. no BigInt like support): +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Objects/longobject.c#L2934-L2989 # noqa: E501 +# obdigit is a uint32_t which is typedef'd to digit +# int32_t is typedef'd to sdigit + + +@register_jitable(locals={'x': _Py_uhash_t, + 'p1': _Py_uhash_t, + 'p2': _Py_uhash_t, + 'p3': _Py_uhash_t, + 'p4': _Py_uhash_t, + '_PyHASH_MODULUS': _Py_uhash_t, + '_PyHASH_BITS': types.int32, + '_PyLong_SHIFT': types.int32,}) +def _long_impl(val): + # This function assumes val came from a long int repr with val being a + # uint64_t this means having to split the input into PyLong_SHIFT size + # chunks in an unsigned hash wide type, max numba can handle is a 64bit int + + # mask to select low _PyLong_SHIFT bits + _tmp_shift = 32 - _PyLong_SHIFT + mask_shift = (~types.uint32(0x0)) >> _tmp_shift + + # a 64bit wide max means Numba only needs 3 x 30 bit values max, + # or 5 x 15 bit values max on 32bit platforms + i = (64 // _PyLong_SHIFT) + 1 + + # alg as per hash_long + x = 0 + p3 = (_PyHASH_BITS - _PyLong_SHIFT) + for idx in range(i - 1, -1, -1): + p1 = x << _PyLong_SHIFT + p2 = p1 & _PyHASH_MODULUS + p4 = x >> p3 + x = p2 | p4 + # the shift and mask splits out the `ob_digit` parts of a Long repr + x += types.uint32((val >> idx * _PyLong_SHIFT) & mask_shift) + if x >= _PyHASH_MODULUS: + x -= _PyHASH_MODULUS + return _Py_hash_t(x) + + +# This has no CPython equivalent, CPython uses long_hash. +@overload_method(types.Integer, '__hash__') +@overload_method(types.Boolean, '__hash__') +def int_hash(val): + + _HASH_I64_MIN = -2 if sys.maxsize <= 2 ** 32 else -4 + _SIGNED_MIN = types.int64(-0x8000000000000000) + + # Find a suitable type to hold a "big" value, i.e. iinfo(ty).min/max + # this is to ensure e.g. int32.min is handled ok as it's abs() is its value + _BIG = types.int64 if getattr(val, 'signed', False) else types.uint64 + + # this is a bit involved due to the CPython repr of ints + def impl(val): + # If the magnitude is under PyHASH_MODULUS, just return the + # value val as the hash, couple of special cases if val == val: + # 1. it's 0, in which case return 0 + # 2. it's signed int minimum value, return the value CPython computes + # but Numba cannot as there's no type wide enough to hold the shifts. + # + # If the magnitude is greater than PyHASH_MODULUS then... if the value + # is negative then negate it switch the sign on the hash once computed + # and use the standard wide unsigned hash implementation + val = _BIG(val) + mag = abs(val) + if mag < _PyHASH_MODULUS: + if val == 0: + ret = 0 + elif val == _SIGNED_MIN: # e.g. int64 min, -0x8000000000000000 + ret = _Py_hash_t(_HASH_I64_MIN) + else: + ret = _Py_hash_t(val) + else: + needs_negate = False + if val < 0: + val = -val + needs_negate = True + ret = _long_impl(val) + if needs_negate: + ret = -ret + return process_return(ret) + return impl + +# This is a translation of CPython's float_hash: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Objects/floatobject.c#L528-L532 # noqa: E501 + + +@overload_method(types.Float, '__hash__') +def float_hash(val): + if val.bitwidth == 64: + def impl(val): + hashed = _Py_HashDouble(val) + return hashed + else: + def impl(val): + # widen the 32bit float to 64bit + fpextended = np.float64(_fpext(val)) + hashed = _Py_HashDouble(fpextended) + return hashed + return impl + +# This is a translation of CPython's complex_hash: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Objects/complexobject.c#L408-L428 # noqa: E501 + + +@overload_method(types.Complex, '__hash__') +def complex_hash(val): + def impl(val): + hashreal = hash(val.real) + hashimag = hash(val.imag) + # Note: if the imaginary part is 0, hashimag is 0 now, + # so the following returns hashreal unchanged. This is + # important because numbers of different types that + # compare equal must have the same hash value, so that + # hash(x + 0*j) must equal hash(x). + combined = hashreal + _PyHASH_IMAG * hashimag + return process_return(combined) + return impl + + +# Python 3.8 strengthened its hash alg for tuples. +# This is a translation of CPython's tuplehash for Python >=3.8 +# https://github.com/python/cpython/blob/b738237d6792acba85b1f6e6c8993a812c7fd815/Objects/tupleobject.c#L338-L391 # noqa: E501 + +# These consts are needed for this alg variant, they are from: +# https://github.com/python/cpython/blob/b738237d6792acba85b1f6e6c8993a812c7fd815/Objects/tupleobject.c#L353-L363 # noqa: E501 +if _Py_uhash_t.bitwidth // 8 > 4: + _PyHASH_XXPRIME_1 = _Py_uhash_t(11400714785074694791) + _PyHASH_XXPRIME_2 = _Py_uhash_t(14029467366897019727) + _PyHASH_XXPRIME_5 = _Py_uhash_t(2870177450012600261) + + @register_jitable(locals={'x': types.uint64}) + def _PyHASH_XXROTATE(x): + # Rotate left 31 bits + return ((x << types.uint64(31)) | (x >> types.uint64(33))) +else: + _PyHASH_XXPRIME_1 = _Py_uhash_t(2654435761) + _PyHASH_XXPRIME_2 = _Py_uhash_t(2246822519) + _PyHASH_XXPRIME_5 = _Py_uhash_t(374761393) + + @register_jitable(locals={'x': types.uint64}) + def _PyHASH_XXROTATE(x): + # Rotate left 13 bits + return ((x << types.uint64(13)) | (x >> types.uint64(19))) + + +@register_jitable(locals={'acc': _Py_uhash_t, 'lane': _Py_uhash_t, + '_PyHASH_XXPRIME_5': _Py_uhash_t, + '_PyHASH_XXPRIME_1': _Py_uhash_t, + 'tl': _Py_uhash_t}) +def _tuple_hash(tup): + tl = len(tup) + acc = _PyHASH_XXPRIME_5 + for x in literal_unroll(tup): + lane = hash(x) + if lane == _Py_uhash_t(-1): + return -1 + acc += lane * _PyHASH_XXPRIME_2 + acc = _PyHASH_XXROTATE(acc) + acc *= _PyHASH_XXPRIME_1 + + acc += tl ^ (_PyHASH_XXPRIME_5 ^ _Py_uhash_t(3527539)) + + if acc == _Py_uhash_t(-1): + return process_return(1546275796) + + return process_return(acc) + + +@overload_method(types.BaseTuple, '__hash__') +def tuple_hash(val): + def impl(val): + return _tuple_hash(val) + return impl + + +# ------------------------------------------------------------------------------ +# String/bytes hashing needs hashseed info, this is from: +# https://stackoverflow.com/a/41088757 +# with thanks to Martijn Pieters +# +# Developer note: +# CPython makes use of an internal "hashsecret" which is essentially a struct +# containing some state that is set on CPython initialization and contains magic +# numbers used particularly in unicode/string hashing. This code binds to the +# Python runtime libraries in use by the current process and reads the +# "hashsecret" state so that it can be used by Numba. As this is done at runtime +# the behaviour and influence of the PYTHONHASHSEED environment variable is +# accommodated. + +from ctypes import ( # noqa + c_size_t, + c_ubyte, + c_uint64, + pythonapi, + Structure, + Union, +) # noqa + + +class FNV(Structure): + _fields_ = [ + ('prefix', c_size_t), + ('suffix', c_size_t) + ] + + +class SIPHASH(Structure): + _fields_ = [ + ('k0', c_uint64), + ('k1', c_uint64), + ] + + +class DJBX33A(Structure): + _fields_ = [ + ('padding', c_ubyte * 16), + ('suffix', c_size_t), + ] + + +class EXPAT(Structure): + _fields_ = [ + ('padding', c_ubyte * 16), + ('hashsalt', c_size_t), + ] + + +class _Py_HashSecret_t(Union): + _fields_ = [ + # ensure 24 bytes + ('uc', c_ubyte * 24), + # two Py_hash_t for FNV + ('fnv', FNV), + # two uint64 for SipHash24 + ('siphash', SIPHASH), + # a different (!) Py_hash_t for small string optimization + ('djbx33a', DJBX33A), + ('expat', EXPAT), + ] + + +_hashsecret_entry = namedtuple('_hashsecret_entry', ['symbol', 'value']) + + +# Only a few members are needed at present +def _build_hashsecret(): + """Read hash secret from the Python process + + Returns + ------- + info : dict + - keys are "djbx33a_suffix", "siphash_k0", siphash_k1". + - values are the namedtuple[symbol:str, value:int] + """ + # Read hashsecret and inject it into the LLVM symbol map under the + # prefix `_numba_hashsecret_`. + pyhashsecret = _Py_HashSecret_t.in_dll(pythonapi, '_Py_HashSecret') + info = {} + + def inject(name, val): + symbol_name = "_numba_hashsecret_{}".format(name) + val = ctypes.c_uint64(val) + addr = ctypes.addressof(val) + ll.add_symbol(symbol_name, addr) + info[name] = _hashsecret_entry(symbol=symbol_name, value=val) + + inject('djbx33a_suffix', pyhashsecret.djbx33a.suffix) + inject('siphash_k0', pyhashsecret.siphash.k0) + inject('siphash_k1', pyhashsecret.siphash.k1) + return info + + +_hashsecret = _build_hashsecret() + + +# ------------------------------------------------------------------------------ + + +if _Py_hashfunc_name in ('siphash13', 'siphash24', 'fnv'): + + # Check for use of the FNV hashing alg, warn users that it's not implemented + # and functionality relying of properties derived from hashing will be fine + # but hash values themselves are likely to be different. + if _Py_hashfunc_name == 'fnv': + msg = ("FNV hashing is not implemented in Numba. See PEP 456 " + "https://www.python.org/dev/peps/pep-0456/ " + "for rationale over not using FNV. Numba will continue to work, " + "but hashes for built in types will be computed using " + "siphash24. This will permit e.g. dictionaries to continue to " + "behave as expected, however anything relying on the value of " + "the hash opposed to hash as a derived property is likely to " + "not work as expected.") + warnings.warn(msg) + + # This is a translation of CPython's siphash24 function: + # https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Python/pyhash.c#L287-L413 # noqa: E501 + # and also, since Py 3.11, a translation of CPython's siphash13 function: + # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Python/pyhash.c#L376-L424 + # the only differences are in the use of SINGLE_ROUND in siphash13 vs. + # DOUBLE_ROUND in siphash24, and that siphash13 has an extra "ROUND" applied + # just before the final XORing of components to create the return value. + + # /* ********************************************************************* + # + # Copyright (c) 2013 Marek Majkowski + + # Permission is hereby granted, free of charge, to any person obtaining a + # copy of this software and associated documentation files (the "Software"), + # to deal in the Software without restriction, including without limitation + # the rights to use, copy, modify, merge, publish, distribute, sublicense, + # and/or sell copies of the Software, and to permit persons to whom the + # Software is furnished to do so, subject to the following conditions: + + # The above copyright notice and this permission notice shall be included in + # all copies or substantial portions of the Software. + + # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + # DEALINGS IN THE SOFTWARE. + # + + # Original location: + # https://github.com/majek/csiphash/ + + # Solution inspired by code from: + # Samuel Neves (supercop/crypto_auth/siphash24/little) + #djb (supercop/crypto_auth/siphash24/little2) + # Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c) + + # Modified for Python by Christian Heimes: + # - C89 / MSVC compatibility + # - _rotl64() on Windows + # - letoh64() fallback + # */ + + @register_jitable(locals={'x': types.uint64, + 'b': types.uint64, }) + def _ROTATE(x, b): + return types.uint64(((x) << (b)) | ((x) >> (types.uint64(64) - (b)))) + + @register_jitable(locals={'a': types.uint64, + 'b': types.uint64, + 'c': types.uint64, + 'd': types.uint64, + 's': types.uint64, + 't': types.uint64, }) + def _HALF_ROUND(a, b, c, d, s, t): + a += b + c += d + b = _ROTATE(b, s) ^ a + d = _ROTATE(d, t) ^ c + a = _ROTATE(a, 32) + return a, b, c, d + + @register_jitable(locals={'v0': types.uint64, + 'v1': types.uint64, + 'v2': types.uint64, + 'v3': types.uint64, }) + def _SINGLE_ROUND(v0, v1, v2, v3): + v0, v1, v2, v3 = _HALF_ROUND(v0, v1, v2, v3, 13, 16) + v2, v1, v0, v3 = _HALF_ROUND(v2, v1, v0, v3, 17, 21) + return v0, v1, v2, v3 + + @register_jitable(locals={'v0': types.uint64, + 'v1': types.uint64, + 'v2': types.uint64, + 'v3': types.uint64, }) + def _DOUBLE_ROUND(v0, v1, v2, v3): + v0, v1, v2, v3 = _SINGLE_ROUND(v0, v1, v2, v3) + v0, v1, v2, v3 = _SINGLE_ROUND(v0, v1, v2, v3) + return v0, v1, v2, v3 + + def _gen_siphash(alg): + if alg == 'siphash13': + _ROUNDER = _SINGLE_ROUND + _EXTRA_ROUND = True + elif alg == 'siphash24': + _ROUNDER = _DOUBLE_ROUND + _EXTRA_ROUND = False + else: + assert 0, 'unreachable' + + @register_jitable(locals={'v0': types.uint64, + 'v1': types.uint64, + 'v2': types.uint64, + 'v3': types.uint64, + 'b': types.uint64, + 'mi': types.uint64, + 't': types.uint64, + 'mask': types.uint64, + 'jmp': types.uint64, + 'ohexefef': types.uint64}) + def _siphash(k0, k1, src, src_sz): + b = types.uint64(src_sz) << 56 + v0 = k0 ^ types.uint64(0x736f6d6570736575) + v1 = k1 ^ types.uint64(0x646f72616e646f6d) + v2 = k0 ^ types.uint64(0x6c7967656e657261) + v3 = k1 ^ types.uint64(0x7465646279746573) + + idx = 0 + while (src_sz >= 8): + mi = grab_uint64_t(src, idx) + idx += 1 + src_sz -= 8 + v3 ^= mi + v0, v1, v2, v3 = _ROUNDER(v0, v1, v2, v3) + v0 ^= mi + + # this is the switch fallthrough: + # https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Python/pyhash.c#L390-L400 # noqa: E501 + t = types.uint64(0x0) + boffset = idx * 8 + ohexefef = types.uint64(0xff) + if src_sz >= 7: + jmp = (6 * 8) + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 6)) + << jmp) + if src_sz >= 6: + jmp = (5 * 8) + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 5)) + << jmp) + if src_sz >= 5: + jmp = (4 * 8) + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 4)) + << jmp) + if src_sz >= 4: + t &= types.uint64(0xffffffff00000000) + for i in range(4): + jmp = i * 8 + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + i)) + << jmp) + if src_sz >= 3: + jmp = (2 * 8) + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 2)) + << jmp) + if src_sz >= 2: + jmp = (1 * 8) + mask = ~types.uint64(ohexefef << jmp) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 1)) + << jmp) + if src_sz >= 1: + mask = ~(ohexefef) + t = (t & mask) | (types.uint64(grab_byte(src, boffset + 0))) + + b |= t + v3 ^= b + v0, v1, v2, v3 = _ROUNDER(v0, v1, v2, v3) + v0 ^= b + v2 ^= ohexefef + v0, v1, v2, v3 = _ROUNDER(v0, v1, v2, v3) + v0, v1, v2, v3 = _ROUNDER(v0, v1, v2, v3) + if _EXTRA_ROUND: + v0, v1, v2, v3 = _ROUNDER(v0, v1, v2, v3) + t = (v0 ^ v1) ^ (v2 ^ v3) + return t + + return _siphash + + _siphash13 = _gen_siphash('siphash13') + _siphash24 = _gen_siphash('siphash24') + + _siphasher = _siphash13 if _Py_hashfunc_name == 'siphash13' else _siphash24 + +else: + msg = "Unsupported hashing algorithm in use %s" % _Py_hashfunc_name + raise ValueError(msg) + + +@intrinsic +def _inject_hashsecret_read(tyctx, name): + """Emit code to load the hashsecret. + """ + if not isinstance(name, types.StringLiteral): + raise errors.TypingError("requires literal string") + + sym = _hashsecret[name.literal_value].symbol + resty = types.uint64 + sig = resty(name) + + def impl(cgctx, builder, sig, args): + mod = builder.module + try: + # Search for existing global + gv = mod.get_global(sym) + except KeyError: + # Inject the symbol if not already exist. + gv = ir.GlobalVariable(mod, ir.IntType(64), name=sym) + v = builder.load(gv) + return v + + return sig, impl + + +def _load_hashsecret(name): + return _hashsecret[name].value + + +@overload(_load_hashsecret) +def _impl_load_hashsecret(name): + def imp(name): + return _inject_hashsecret_read(name) + return imp + + +# This is a translation of CPythons's _Py_HashBytes: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Python/pyhash.c#L145-L191 # noqa: E501 + + +@register_jitable(locals={'_hash': _Py_uhash_t}) +def _Py_HashBytes(val, _len): + if (_len == 0): + return process_return(0) + + if (_len < _Py_HASH_CUTOFF): + # TODO: this branch needs testing, needs a CPython setup for it! + # /* Optimize hashing of very small strings with inline DJBX33A. */ + _hash = _Py_uhash_t(5381) # /* DJBX33A starts with 5381 */ + for idx in range(_len): + _hash = ((_hash << 5) + _hash) + np.uint8(grab_byte(val, idx)) + + _hash ^= _len + _hash ^= _load_hashsecret('djbx33a_suffix') + else: + tmp = _siphasher(types.uint64(_load_hashsecret('siphash_k0')), + types.uint64(_load_hashsecret('siphash_k1')), + val, _len) + _hash = process_return(tmp) + return process_return(_hash) + +# This is an approximate translation of CPython's unicode_hash: +# https://github.com/python/cpython/blob/d1dd6be613381b996b9071443ef081de8e5f3aff/Objects/unicodeobject.c#L11635-L11663 # noqa: E501 + + +@overload_method(types.UnicodeType, '__hash__') +def unicode_hash(val): + from numba.cpython.unicode import _kind_to_byte_width + + def impl(val): + kindwidth = _kind_to_byte_width(val._kind) + _len = len(val) + # use the cache if possible + current_hash = val._hash + if current_hash != -1: + return current_hash + else: + # cannot write hash value to cache in the unicode struct due to + # pass by value on the struct making the struct member immutable + return _Py_HashBytes(val._data, kindwidth * _len) + + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/heapq.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/heapq.py new file mode 100644 index 0000000000000000000000000000000000000000..15c8166d8f7ac133b4cb63dda332c59e3918a20c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/heapq.py @@ -0,0 +1,266 @@ +# A port of https://github.com/python/cpython/blob/e42b7051/Lib/heapq.py + + +import heapq as hq + +from numba.core import types +from numba.core.errors import TypingError +from numba.core.extending import overload, register_jitable + + +@register_jitable +def _siftdown(heap, startpos, pos): + newitem = heap[pos] + + while pos > startpos: + parentpos = (pos - 1) >> 1 + parent = heap[parentpos] + if newitem < parent: + heap[pos] = parent + pos = parentpos + continue + break + + heap[pos] = newitem + + +@register_jitable +def _siftup(heap, pos): + endpos = len(heap) + startpos = pos + newitem = heap[pos] + + childpos = 2 * pos + 1 + while childpos < endpos: + + rightpos = childpos + 1 + if rightpos < endpos and not heap[childpos] < heap[rightpos]: + childpos = rightpos + + heap[pos] = heap[childpos] + pos = childpos + childpos = 2 * pos + 1 + + heap[pos] = newitem + _siftdown(heap, startpos, pos) + + +@register_jitable +def _siftdown_max(heap, startpos, pos): + newitem = heap[pos] + + while pos > startpos: + parentpos = (pos - 1) >> 1 + parent = heap[parentpos] + if parent < newitem: + heap[pos] = parent + pos = parentpos + continue + break + heap[pos] = newitem + + +@register_jitable +def _siftup_max(heap, pos): + endpos = len(heap) + startpos = pos + newitem = heap[pos] + + childpos = 2 * pos + 1 + while childpos < endpos: + + rightpos = childpos + 1 + if rightpos < endpos and not heap[rightpos] < heap[childpos]: + childpos = rightpos + + heap[pos] = heap[childpos] + pos = childpos + childpos = 2 * pos + 1 + + heap[pos] = newitem + _siftdown_max(heap, startpos, pos) + + +@register_jitable +def reversed_range(x): + # analogous to reversed(range(x)) + return range(x - 1, -1, -1) + + +@register_jitable +def _heapify_max(x): + n = len(x) + + for i in reversed_range(n // 2): + _siftup_max(x, i) + + +@register_jitable +def _heapreplace_max(heap, item): + returnitem = heap[0] + heap[0] = item + _siftup_max(heap, 0) + return returnitem + + +def assert_heap_type(heap): + if not isinstance(heap, (types.List, types.ListType)): + raise TypingError('heap argument must be a list') + + dt = heap.dtype + if isinstance(dt, types.Complex): + msg = ("'<' not supported between instances " + "of 'complex' and 'complex'") + raise TypingError(msg) + + +def assert_item_type_consistent_with_heap_type(heap, item): + if not heap.dtype == item: + raise TypingError('heap type must be the same as item type') + + +@overload(hq.heapify) +def hq_heapify(x): + assert_heap_type(x) + + def hq_heapify_impl(x): + n = len(x) + for i in reversed_range(n // 2): + _siftup(x, i) + + return hq_heapify_impl + + +@overload(hq.heappop) +def hq_heappop(heap): + assert_heap_type(heap) + + def hq_heappop_impl(heap): + lastelt = heap.pop() + if heap: + returnitem = heap[0] + heap[0] = lastelt + _siftup(heap, 0) + return returnitem + return lastelt + + return hq_heappop_impl + + +@overload(hq.heappush) +def heappush(heap, item): + assert_heap_type(heap) + assert_item_type_consistent_with_heap_type(heap, item) + + def hq_heappush_impl(heap, item): + heap.append(item) + _siftdown(heap, 0, len(heap) - 1) + + return hq_heappush_impl + + +@overload(hq.heapreplace) +def heapreplace(heap, item): + assert_heap_type(heap) + assert_item_type_consistent_with_heap_type(heap, item) + + def hq_heapreplace(heap, item): + returnitem = heap[0] + heap[0] = item + _siftup(heap, 0) + return returnitem + + return hq_heapreplace + + +@overload(hq.heappushpop) +def heappushpop(heap, item): + assert_heap_type(heap) + assert_item_type_consistent_with_heap_type(heap, item) + + def hq_heappushpop_impl(heap, item): + if heap and heap[0] < item: + item, heap[0] = heap[0], item + _siftup(heap, 0) + return item + + return hq_heappushpop_impl + + +def check_input_types(n, iterable): + + if not isinstance(n, (types.Integer, types.Boolean)): + raise TypingError("First argument 'n' must be an integer") + # heapq also accepts 1.0 (but not 0.0, 2.0, 3.0...) but + # this isn't replicated + + if not isinstance(iterable, (types.Sequence, types.Array, types.ListType)): + raise TypingError("Second argument 'iterable' must be iterable") + + +@overload(hq.nsmallest) +def nsmallest(n, iterable): + check_input_types(n, iterable) + + def hq_nsmallest_impl(n, iterable): + + if n == 0: + return [iterable[0] for _ in range(0)] + elif n == 1: + out = min(iterable) + return [out] + + size = len(iterable) + if n >= size: + return sorted(iterable)[:n] + + it = iter(iterable) + result = [(elem, i) for i, elem in zip(range(n), it)] + + _heapify_max(result) + top = result[0][0] + order = n + + for elem in it: + if elem < top: + _heapreplace_max(result, (elem, order)) + top, _order = result[0] + order += 1 + result.sort() + return [elem for (elem, order) in result] + + return hq_nsmallest_impl + + +@overload(hq.nlargest) +def nlargest(n, iterable): + check_input_types(n, iterable) + + def hq_nlargest_impl(n, iterable): + + if n == 0: + return [iterable[0] for _ in range(0)] + elif n == 1: + out = max(iterable) + return [out] + + size = len(iterable) + if n >= size: + return sorted(iterable)[::-1][:n] + + it = iter(iterable) + result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)] + + hq.heapify(result) + top = result[0][0] + order = -n + + for elem in it: + if top < elem: + hq.heapreplace(result, (elem, order)) + top, _order = result[0] + order -= 1 + result.sort(reverse=True) + return [elem for (elem, order) in result] + + return hq_nlargest_impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/iterators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/iterators.py new file mode 100644 index 0000000000000000000000000000000000000000..fa55dd2b1342f3dd07f034987be724945e423382 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/iterators.py @@ -0,0 +1,140 @@ +""" +Implementation of various iterable and iterator types. +""" + +from numba.core import types, cgutils +from numba.core.imputils import ( + lower_builtin, iternext_impl, call_iternext, call_getiter, + impl_ret_borrowed, impl_ret_new_ref, RefType) + + + +@lower_builtin('getiter', types.IteratorType) +def iterator_getiter(context, builder, sig, args): + [it] = args + return impl_ret_borrowed(context, builder, sig.return_type, it) + +#------------------------------------------------------------------------------- +# builtin `enumerate` implementation + +@lower_builtin(enumerate, types.IterableType) +@lower_builtin(enumerate, types.IterableType, types.Integer) +def make_enumerate_object(context, builder, sig, args): + assert len(args) == 1 or len(args) == 2 # enumerate(it) or enumerate(it, start) + srcty = sig.args[0] + + if len(args) == 1: + src = args[0] + start_val = context.get_constant(types.intp, 0) + elif len(args) == 2: + src = args[0] + start_val = context.cast(builder, args[1], sig.args[1], types.intp) + + iterobj = call_getiter(context, builder, srcty, src) + + enum = context.make_helper(builder, sig.return_type) + + countptr = cgutils.alloca_once(builder, start_val.type) + builder.store(start_val, countptr) + + enum.count = countptr + enum.iter = iterobj + + res = enum._getvalue() + return impl_ret_new_ref(context, builder, sig.return_type, res) + +@lower_builtin('iternext', types.EnumerateType) +@iternext_impl(RefType.NEW) +def iternext_enumerate(context, builder, sig, args, result): + [enumty] = sig.args + [enum] = args + + enum = context.make_helper(builder, enumty, value=enum) + + count = builder.load(enum.count) + ncount = builder.add(count, context.get_constant(types.intp, 1)) + builder.store(ncount, enum.count) + + srcres = call_iternext(context, builder, enumty.source_type, enum.iter) + is_valid = srcres.is_valid() + result.set_valid(is_valid) + + with builder.if_then(is_valid): + srcval = srcres.yielded_value() + result.yield_(context.make_tuple(builder, enumty.yield_type, + [count, srcval])) + + +#------------------------------------------------------------------------------- +# builtin `zip` implementation + +@lower_builtin(zip, types.VarArg(types.Any)) +def make_zip_object(context, builder, sig, args): + zip_type = sig.return_type + + assert len(args) == len(zip_type.source_types) + + zipobj = context.make_helper(builder, zip_type) + + for i, (arg, srcty) in enumerate(zip(args, sig.args)): + zipobj[i] = call_getiter(context, builder, srcty, arg) + + res = zipobj._getvalue() + return impl_ret_new_ref(context, builder, sig.return_type, res) + +@lower_builtin('iternext', types.ZipType) +@iternext_impl(RefType.NEW) +def iternext_zip(context, builder, sig, args, result): + [zip_type] = sig.args + [zipobj] = args + + zipobj = context.make_helper(builder, zip_type, value=zipobj) + + if len(zipobj) == 0: + # zip() is an empty iterator + result.set_exhausted() + return + + p_ret_tup = cgutils.alloca_once(builder, + context.get_value_type(zip_type.yield_type)) + p_is_valid = cgutils.alloca_once_value(builder, value=cgutils.true_bit) + + for i, (iterobj, srcty) in enumerate(zip(zipobj, zip_type.source_types)): + is_valid = builder.load(p_is_valid) + # Avoid calling the remaining iternext if a iterator has been exhausted + with builder.if_then(is_valid): + srcres = call_iternext(context, builder, srcty, iterobj) + is_valid = builder.and_(is_valid, srcres.is_valid()) + builder.store(is_valid, p_is_valid) + val = srcres.yielded_value() + ptr = cgutils.gep_inbounds(builder, p_ret_tup, 0, i) + builder.store(val, ptr) + + is_valid = builder.load(p_is_valid) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + result.yield_(builder.load(p_ret_tup)) + + +#------------------------------------------------------------------------------- +# generator implementation + +@lower_builtin('iternext', types.Generator) +@iternext_impl(RefType.BORROWED) +def iternext_zip(context, builder, sig, args, result): + genty, = sig.args + gen, = args + impl = context.get_generator_impl(genty) + status, retval = impl(context, builder, sig, args) + context.add_linking_libs(getattr(impl, 'libs', ())) + + with cgutils.if_likely(builder, status.is_ok): + result.set_valid(True) + result.yield_(retval) + with cgutils.if_unlikely(builder, status.is_stop_iteration): + result.set_exhausted() + with cgutils.if_unlikely(builder, + builder.and_(status.is_error, + builder.not_(status.is_stop_iteration))): + context.call_conv.return_status_propagate(builder, status) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/listobj.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/listobj.py new file mode 100644 index 0000000000000000000000000000000000000000..7f35ab2dd5f2a64f673f8c03902ed265c6cbf725 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/listobj.py @@ -0,0 +1,1254 @@ +""" +Support for native homogeneous lists. +""" + + +import math +import operator +from functools import cached_property + +from llvmlite import ir +from numba.core import types, typing, errors, cgutils, config +from numba.core.imputils import (lower_builtin, lower_cast, + iternext_impl, impl_ret_borrowed, + impl_ret_new_ref, impl_ret_untracked, + RefType) +from numba.core.extending import overload_method, overload +from numba.misc import quicksort +from numba.cpython import slicing +from numba import literal_unroll + + +def get_list_payload(context, builder, list_type, value): + """ + Given a list value and type, get its payload structure (as a + reference, so that mutations are seen by all). + """ + payload_type = types.ListPayload(list_type) + payload = context.nrt.meminfo_data(builder, value.meminfo) + ptrty = context.get_data_type(payload_type).as_pointer() + payload = builder.bitcast(payload, ptrty) + return context.make_data_helper(builder, payload_type, ref=payload) + + +def get_itemsize(context, list_type): + """ + Return the item size for the given list type. + """ + llty = context.get_data_type(list_type.dtype) + return context.get_abi_sizeof(llty) + + +class _ListPayloadMixin(object): + + @property + def size(self): + return self._payload.size + + @size.setter + def size(self, value): + self._payload.size = value + + @property + def dirty(self): + return self._payload.dirty + + @property + def data(self): + return self._payload._get_ptr_by_name('data') + + def _gep(self, idx): + return cgutils.gep(self._builder, self.data, idx) + + def getitem(self, idx): + ptr = self._gep(idx) + data_item = self._builder.load(ptr) + return self._datamodel.from_data(self._builder, data_item) + + def fix_index(self, idx): + """ + Fix negative indices by adding the size to them. Positive + indices are left untouched. + """ + is_negative = self._builder.icmp_signed('<', idx, + ir.Constant(idx.type, 0)) + wrapped_index = self._builder.add(idx, self.size) + return self._builder.select(is_negative, wrapped_index, idx) + + def is_out_of_bounds(self, idx): + """ + Return whether the index is out of bounds. + """ + underflow = self._builder.icmp_signed('<', idx, + ir.Constant(idx.type, 0)) + overflow = self._builder.icmp_signed('>=', idx, self.size) + return self._builder.or_(underflow, overflow) + + def clamp_index(self, idx): + """ + Clamp the index in [0, size]. + """ + builder = self._builder + idxptr = cgutils.alloca_once_value(builder, idx) + + zero = ir.Constant(idx.type, 0) + size = self.size + + underflow = self._builder.icmp_signed('<', idx, zero) + with builder.if_then(underflow, likely=False): + builder.store(zero, idxptr) + overflow = self._builder.icmp_signed('>=', idx, size) + with builder.if_then(overflow, likely=False): + builder.store(size, idxptr) + + return builder.load(idxptr) + + def guard_index(self, idx, msg): + """ + Raise an error if the index is out of bounds. + """ + with self._builder.if_then(self.is_out_of_bounds(idx), likely=False): + self._context.call_conv.return_user_exc(self._builder, + IndexError, (msg,)) + + def fix_slice(self, slice): + """ + Fix slice start and stop to be valid (inclusive and exclusive, resp) + indexing bounds. + """ + return slicing.fix_slice(self._builder, slice, self.size) + + def incref_value(self, val): + "Incref an element value" + self._context.nrt.incref(self._builder, self.dtype, val) + + def decref_value(self, val): + "Decref an element value" + self._context.nrt.decref(self._builder, self.dtype, val) + + +class ListPayloadAccessor(_ListPayloadMixin): + """ + A helper object to access the list attributes given the pointer to the + payload type. + """ + def __init__(self, context, builder, list_type, payload_ptr): + self._context = context + self._builder = builder + self._ty = list_type + self._datamodel = context.data_model_manager[list_type.dtype] + payload_type = types.ListPayload(list_type) + ptrty = context.get_data_type(payload_type).as_pointer() + payload_ptr = builder.bitcast(payload_ptr, ptrty) + payload = context.make_data_helper(builder, payload_type, + ref=payload_ptr) + self._payload = payload + + +class ListInstance(_ListPayloadMixin): + + def __init__(self, context, builder, list_type, list_val): + self._context = context + self._builder = builder + self._ty = list_type + self._list = context.make_helper(builder, list_type, list_val) + self._itemsize = get_itemsize(context, list_type) + self._datamodel = context.data_model_manager[list_type.dtype] + + @property + def dtype(self): + return self._ty.dtype + + @property + def _payload(self): + # This cannot be cached as it can be reallocated + return get_list_payload(self._context, self._builder, self._ty, self._list) + + @property + def parent(self): + return self._list.parent + + @parent.setter + def parent(self, value): + self._list.parent = value + + @property + def value(self): + return self._list._getvalue() + + @property + def meminfo(self): + return self._list.meminfo + + def set_dirty(self, val): + if self._ty.reflected: + self._payload.dirty = cgutils.true_bit if val else cgutils.false_bit + + def clear_value(self, idx): + """Remove the value at the location + """ + self.decref_value(self.getitem(idx)) + # it's necessary for the dtor which just decref every slot on it. + self.zfill(idx, self._builder.add(idx, idx.type(1))) + + def setitem(self, idx, val, incref, decref_old_value=True): + # Decref old data + if decref_old_value: + self.decref_value(self.getitem(idx)) + + ptr = self._gep(idx) + data_item = self._datamodel.as_data(self._builder, val) + self._builder.store(data_item, ptr) + self.set_dirty(True) + if incref: + # Incref the underlying data + self.incref_value(val) + + def inititem(self, idx, val, incref=True): + ptr = self._gep(idx) + data_item = self._datamodel.as_data(self._builder, val) + self._builder.store(data_item, ptr) + if incref: + self.incref_value(val) + + def zfill(self, start, stop): + """Zero-fill the memory at index *start* to *stop* + + *stop* MUST not be smaller than *start*. + """ + builder = self._builder + base = self._gep(start) + end = self._gep(stop) + intaddr_t = self._context.get_value_type(types.intp) + size = builder.sub(builder.ptrtoint(end, intaddr_t), + builder.ptrtoint(base, intaddr_t)) + cgutils.memset(builder, base, size, ir.IntType(8)(0)) + + @classmethod + def allocate_ex(cls, context, builder, list_type, nitems): + """ + Allocate a ListInstance with its storage. + Return a (ok, instance) tuple where *ok* is a LLVM boolean and + *instance* is a ListInstance object (the object's contents are + only valid when *ok* is true). + """ + intp_t = context.get_value_type(types.intp) + + if isinstance(nitems, int): + nitems = ir.Constant(intp_t, nitems) + + payload_type = context.get_data_type(types.ListPayload(list_type)) + payload_size = context.get_abi_sizeof(payload_type) + + itemsize = get_itemsize(context, list_type) + # Account for the fact that the payload struct contains one entry + payload_size -= itemsize + + ok = cgutils.alloca_once_value(builder, cgutils.true_bit) + self = cls(context, builder, list_type, None) + + # Total allocation size = + nitems * itemsize + allocsize, ovf = cgutils.muladd_with_overflow(builder, nitems, + ir.Constant(intp_t, itemsize), + ir.Constant(intp_t, payload_size)) + with builder.if_then(ovf, likely=False): + builder.store(cgutils.false_bit, ok) + + with builder.if_then(builder.load(ok), likely=True): + meminfo = context.nrt.meminfo_new_varsize_dtor_unchecked( + builder, size=allocsize, dtor=self.get_dtor()) + with builder.if_else(cgutils.is_null(builder, meminfo), + likely=False) as (if_error, if_ok): + with if_error: + builder.store(cgutils.false_bit, ok) + with if_ok: + self._list.meminfo = meminfo + self._list.parent = context.get_constant_null(types.pyobject) + self._payload.allocated = nitems + self._payload.size = ir.Constant(intp_t, 0) # for safety + self._payload.dirty = cgutils.false_bit + # Zero the allocated region + self.zfill(self.size.type(0), nitems) + + return builder.load(ok), self + + def define_dtor(self): + "Define the destructor if not already defined" + context = self._context + builder = self._builder + mod = builder.module + # Declare dtor + fnty = ir.FunctionType(ir.VoidType(), [cgutils.voidptr_t]) + fn = cgutils.get_or_insert_function(mod, fnty, + '.dtor.list.{}'.format(self.dtype)) + if not fn.is_declaration: + # End early if the dtor is already defined + return fn + fn.linkage = 'linkonce_odr' + # Populate the dtor + builder = ir.IRBuilder(fn.append_basic_block()) + base_ptr = fn.args[0] # void* + + # get payload + payload = ListPayloadAccessor(context, builder, self._ty, base_ptr) + + # Loop over all data to decref + intp = payload.size.type + with cgutils.for_range_slice( + builder, start=intp(0), stop=payload.size, step=intp(1), + intp=intp) as (idx, _): + val = payload.getitem(idx) + context.nrt.decref(builder, self.dtype, val) + builder.ret_void() + return fn + + def get_dtor(self): + """"Get the element dtor function pointer as void pointer. + + It's safe to be called multiple times. + """ + # Define and set the Dtor + dtor = self.define_dtor() + dtor_fnptr = self._builder.bitcast(dtor, cgutils.voidptr_t) + return dtor_fnptr + + @classmethod + def allocate(cls, context, builder, list_type, nitems): + """ + Allocate a ListInstance with its storage. Same as allocate_ex(), + but return an initialized *instance*. If allocation failed, + control is transferred to the caller using the target's current + call convention. + """ + ok, self = cls.allocate_ex(context, builder, list_type, nitems) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot allocate list",)) + return self + + @classmethod + def from_meminfo(cls, context, builder, list_type, meminfo): + """ + Allocate a new list instance pointing to an existing payload + (a meminfo pointer). + Note the parent field has to be filled by the caller. + """ + self = cls(context, builder, list_type, None) + self._list.meminfo = meminfo + self._list.parent = context.get_constant_null(types.pyobject) + context.nrt.incref(builder, list_type, self.value) + # Payload is part of the meminfo, no need to touch it + return self + + def resize(self, new_size): + """ + Ensure the list is properly sized for the new size. + """ + def _payload_realloc(new_allocated): + payload_type = context.get_data_type(types.ListPayload(self._ty)) + payload_size = context.get_abi_sizeof(payload_type) + # Account for the fact that the payload struct contains one entry + payload_size -= itemsize + + allocsize, ovf = cgutils.muladd_with_overflow( + builder, new_allocated, + ir.Constant(intp_t, itemsize), + ir.Constant(intp_t, payload_size)) + with builder.if_then(ovf, likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot resize list",)) + + ptr = context.nrt.meminfo_varsize_realloc_unchecked(builder, + self._list.meminfo, + size=allocsize) + cgutils.guard_memory_error(context, builder, ptr, + "cannot resize list") + self._payload.allocated = new_allocated + + context = self._context + builder = self._builder + intp_t = new_size.type + + itemsize = get_itemsize(context, self._ty) + allocated = self._payload.allocated + + two = ir.Constant(intp_t, 2) + eight = ir.Constant(intp_t, 8) + + # allocated < new_size + is_too_small = builder.icmp_signed('<', allocated, new_size) + # (allocated >> 2) > new_size + is_too_large = builder.icmp_signed('>', builder.ashr(allocated, two), new_size) + + with builder.if_then(is_too_large, likely=False): + # Exact downsize to requested size + # NOTE: is_too_large must be aggressive enough to avoid repeated + # upsizes and downsizes when growing a list. + _payload_realloc(new_size) + + with builder.if_then(is_too_small, likely=False): + # Upsize with moderate over-allocation (size + size >> 2 + 8) + new_allocated = builder.add(eight, + builder.add(new_size, + builder.ashr(new_size, two))) + _payload_realloc(new_allocated) + self.zfill(self.size, new_allocated) + + self._payload.size = new_size + self.set_dirty(True) + + def move(self, dest_idx, src_idx, count): + """ + Move `count` elements from `src_idx` to `dest_idx`. + """ + dest_ptr = self._gep(dest_idx) + src_ptr = self._gep(src_idx) + cgutils.raw_memmove(self._builder, dest_ptr, src_ptr, + count, itemsize=self._itemsize) + + self.set_dirty(True) + +class ListIterInstance(_ListPayloadMixin): + + def __init__(self, context, builder, iter_type, iter_val): + self._context = context + self._builder = builder + self._ty = iter_type + self._iter = context.make_helper(builder, iter_type, iter_val) + self._datamodel = context.data_model_manager[iter_type.yield_type] + + @classmethod + def from_list(cls, context, builder, iter_type, list_val): + list_inst = ListInstance(context, builder, iter_type.container, list_val) + self = cls(context, builder, iter_type, None) + index = context.get_constant(types.intp, 0) + self._iter.index = cgutils.alloca_once_value(builder, index) + self._iter.meminfo = list_inst.meminfo + return self + + @property + def _payload(self): + # This cannot be cached as it can be reallocated + return get_list_payload(self._context, self._builder, + self._ty.container, self._iter) + + @property + def value(self): + return self._iter._getvalue() + + @property + def index(self): + return self._builder.load(self._iter.index) + + @index.setter + def index(self, value): + self._builder.store(value, self._iter.index) + + +#------------------------------------------------------------------------------- +# Constructors + +def build_list(context, builder, list_type, items): + """ + Build a list of the given type, containing the given items. + """ + nitems = len(items) + inst = ListInstance.allocate(context, builder, list_type, nitems) + # Populate list + inst.size = context.get_constant(types.intp, nitems) + for i, val in enumerate(items): + inst.setitem(context.get_constant(types.intp, i), val, incref=True) + + return impl_ret_new_ref(context, builder, list_type, inst.value) + + +@lower_builtin(list, types.IterableType) +def list_constructor(context, builder, sig, args): + + def list_impl(iterable): + res = [] + res.extend(iterable) + return res + + return context.compile_internal(builder, list_impl, sig, args) + +@lower_builtin(list) +def list_constructor(context, builder, sig, args): + list_type = sig.return_type + list_len = 0 + inst = ListInstance.allocate(context, builder, list_type, list_len) + return impl_ret_new_ref(context, builder, list_type, inst.value) + +#------------------------------------------------------------------------------- +# Various operations + +@lower_builtin(len, types.List) +def list_len(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + return inst.size + +@lower_builtin('getiter', types.List) +def getiter_list(context, builder, sig, args): + inst = ListIterInstance.from_list(context, builder, sig.return_type, args[0]) + return impl_ret_borrowed(context, builder, sig.return_type, inst.value) + +@lower_builtin('iternext', types.ListIter) +@iternext_impl(RefType.BORROWED) +def iternext_listiter(context, builder, sig, args, result): + inst = ListIterInstance(context, builder, sig.args[0], args[0]) + + index = inst.index + nitems = inst.size + is_valid = builder.icmp_signed('<', index, nitems) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + result.yield_(inst.getitem(index)) + inst.index = builder.add(index, context.get_constant(types.intp, 1)) + + +@lower_builtin(operator.getitem, types.List, types.Integer) +def getitem_list(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + index = args[1] + + index = inst.fix_index(index) + inst.guard_index(index, msg="getitem out of range") + result = inst.getitem(index) + + return impl_ret_borrowed(context, builder, sig.return_type, result) + +@lower_builtin(operator.setitem, types.List, types.Integer, types.Any) +def setitem_list(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + index = args[1] + value = args[2] + + index = inst.fix_index(index) + inst.guard_index(index, msg="setitem out of range") + inst.setitem(index, value, incref=True) + return context.get_dummy_value() + + +@lower_builtin(operator.getitem, types.List, types.SliceType) +def getslice_list(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + slice = context.make_helper(builder, sig.args[1], args[1]) + slicing.guard_invalid_slice(context, builder, sig.args[1], slice) + inst.fix_slice(slice) + + # Allocate result and populate it + result_size = slicing.get_slice_length(builder, slice) + result = ListInstance.allocate(context, builder, sig.return_type, + result_size) + result.size = result_size + with cgutils.for_range_slice_generic(builder, slice.start, slice.stop, + slice.step) as (pos_range, neg_range): + with pos_range as (idx, count): + value = inst.getitem(idx) + result.inititem(count, value, incref=True) + with neg_range as (idx, count): + value = inst.getitem(idx) + result.inititem(count, value, incref=True) + + return impl_ret_new_ref(context, builder, sig.return_type, result.value) + +@lower_builtin(operator.setitem, types.List, types.SliceType, types.Any) +def setitem_list(context, builder, sig, args): + dest = ListInstance(context, builder, sig.args[0], args[0]) + src = ListInstance(context, builder, sig.args[2], args[2]) + + slice = context.make_helper(builder, sig.args[1], args[1]) + slicing.guard_invalid_slice(context, builder, sig.args[1], slice) + dest.fix_slice(slice) + + src_size = src.size + avail_size = slicing.get_slice_length(builder, slice) + size_delta = builder.sub(src.size, avail_size) + + zero = ir.Constant(size_delta.type, 0) + one = ir.Constant(size_delta.type, 1) + + with builder.if_else(builder.icmp_signed('==', slice.step, one)) as (then, otherwise): + with then: + # Slice step == 1 => we can resize + + # Compute the real stop, e.g. for dest[2:0] = [...] + real_stop = builder.add(slice.start, avail_size) + # Size of the list tail, after the end of slice + tail_size = builder.sub(dest.size, real_stop) + + with builder.if_then(builder.icmp_signed('>', size_delta, zero)): + # Grow list then move list tail + dest.resize(builder.add(dest.size, size_delta)) + dest.move(builder.add(real_stop, size_delta), real_stop, + tail_size) + + with builder.if_then(builder.icmp_signed('<', size_delta, zero)): + # Move list tail then shrink list + dest.move(builder.add(real_stop, size_delta), real_stop, + tail_size) + dest.resize(builder.add(dest.size, size_delta)) + + dest_offset = slice.start + + with cgutils.for_range(builder, src_size) as loop: + value = src.getitem(loop.index) + dest.setitem(builder.add(loop.index, dest_offset), value, incref=True) + + with otherwise: + with builder.if_then(builder.icmp_signed('!=', size_delta, zero)): + msg = "cannot resize extended list slice with step != 1" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + with cgutils.for_range_slice_generic( + builder, slice.start, slice.stop, slice.step) as (pos_range, neg_range): + with pos_range as (index, count): + value = src.getitem(count) + dest.setitem(index, value, incref=True) + with neg_range as (index, count): + value = src.getitem(count) + dest.setitem(index, value, incref=True) + + return context.get_dummy_value() + + + +@lower_builtin(operator.delitem, types.List, types.Integer) +def delitem_list_index(context, builder, sig, args): + + def list_delitem_impl(lst, i): + lst.pop(i) + + return context.compile_internal(builder, list_delitem_impl, sig, args) + + +@lower_builtin(operator.delitem, types.List, types.SliceType) +def delitem_list(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + slice = context.make_helper(builder, sig.args[1], args[1]) + + slicing.guard_invalid_slice(context, builder, sig.args[1], slice) + inst.fix_slice(slice) + + slice_len = slicing.get_slice_length(builder, slice) + + one = ir.Constant(slice_len.type, 1) + + with builder.if_then(builder.icmp_signed('!=', slice.step, one), likely=False): + msg = "unsupported del list[start:stop:step] with step != 1" + context.call_conv.return_user_exc(builder, NotImplementedError, (msg,)) + + # Compute the real stop, e.g. for dest[2:0] + start = slice.start + real_stop = builder.add(start, slice_len) + # Decref the removed range + with cgutils.for_range_slice( + builder, start, real_stop, start.type(1) + ) as (idx, _): + inst.decref_value(inst.getitem(idx)) + + # Size of the list tail, after the end of slice + tail_size = builder.sub(inst.size, real_stop) + inst.move(start, real_stop, tail_size) + inst.resize(builder.sub(inst.size, slice_len)) + + return context.get_dummy_value() + + +# XXX should there be a specific module for Sequence or collection base classes? + +@lower_builtin(operator.contains, types.Sequence, types.Any) +def in_seq(context, builder, sig, args): + def seq_contains_impl(lst, value): + for elem in lst: + if elem == value: + return True + return False + + return context.compile_internal(builder, seq_contains_impl, sig, args) + +@lower_builtin(bool, types.Sequence) +def sequence_bool(context, builder, sig, args): + def sequence_bool_impl(seq): + return len(seq) != 0 + + return context.compile_internal(builder, sequence_bool_impl, sig, args) + + +@overload(operator.truth) +def sequence_truth(seq): + if isinstance(seq, types.Sequence): + def impl(seq): + return len(seq) != 0 + return impl + + +@lower_builtin(operator.add, types.List, types.List) +def list_add(context, builder, sig, args): + a = ListInstance(context, builder, sig.args[0], args[0]) + b = ListInstance(context, builder, sig.args[1], args[1]) + + a_size = a.size + b_size = b.size + nitems = builder.add(a_size, b_size) + dest = ListInstance.allocate(context, builder, sig.return_type, nitems) + dest.size = nitems + + with cgutils.for_range(builder, a_size) as loop: + value = a.getitem(loop.index) + value = context.cast(builder, value, a.dtype, dest.dtype) + dest.setitem(loop.index, value, incref=True) + with cgutils.for_range(builder, b_size) as loop: + value = b.getitem(loop.index) + value = context.cast(builder, value, b.dtype, dest.dtype) + dest.setitem(builder.add(loop.index, a_size), value, incref=True) + + return impl_ret_new_ref(context, builder, sig.return_type, dest.value) + +@lower_builtin(operator.iadd, types.List, types.List) +def list_add_inplace(context, builder, sig, args): + assert sig.args[0].dtype == sig.return_type.dtype + dest = _list_extend_list(context, builder, sig, args) + + return impl_ret_borrowed(context, builder, sig.return_type, dest.value) + + +@lower_builtin(operator.mul, types.List, types.Integer) +@lower_builtin(operator.mul, types.Integer, types.List) +def list_mul(context, builder, sig, args): + if isinstance(sig.args[0], types.List): + list_idx, int_idx = 0, 1 + else: + list_idx, int_idx = 1, 0 + src = ListInstance(context, builder, sig.args[list_idx], args[list_idx]) + src_size = src.size + + mult = args[int_idx] + zero = ir.Constant(mult.type, 0) + mult = builder.select(cgutils.is_neg_int(builder, mult), zero, mult) + nitems = builder.mul(mult, src_size) + + dest = ListInstance.allocate(context, builder, sig.return_type, nitems) + dest.size = nitems + + with cgutils.for_range_slice(builder, zero, nitems, src_size, inc=True) as (dest_offset, _): + with cgutils.for_range(builder, src_size) as loop: + value = src.getitem(loop.index) + dest.setitem(builder.add(loop.index, dest_offset), value, incref=True) + + return impl_ret_new_ref(context, builder, sig.return_type, dest.value) + +@lower_builtin(operator.imul, types.List, types.Integer) +def list_mul_inplace(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + src_size = inst.size + + mult = args[1] + zero = ir.Constant(mult.type, 0) + mult = builder.select(cgutils.is_neg_int(builder, mult), zero, mult) + nitems = builder.mul(mult, src_size) + + inst.resize(nitems) + + with cgutils.for_range_slice(builder, src_size, nitems, src_size, inc=True) as (dest_offset, _): + with cgutils.for_range(builder, src_size) as loop: + value = inst.getitem(loop.index) + inst.setitem(builder.add(loop.index, dest_offset), value, incref=True) + + return impl_ret_borrowed(context, builder, sig.return_type, inst.value) + + +#------------------------------------------------------------------------------- +# Comparisons + +@lower_builtin(operator.is_, types.List, types.List) +def list_is(context, builder, sig, args): + a = ListInstance(context, builder, sig.args[0], args[0]) + b = ListInstance(context, builder, sig.args[1], args[1]) + ma = builder.ptrtoint(a.meminfo, cgutils.intp_t) + mb = builder.ptrtoint(b.meminfo, cgutils.intp_t) + return builder.icmp_signed('==', ma, mb) + +@lower_builtin(operator.eq, types.List, types.List) +def list_eq(context, builder, sig, args): + aty, bty = sig.args + a = ListInstance(context, builder, aty, args[0]) + b = ListInstance(context, builder, bty, args[1]) + + a_size = a.size + same_size = builder.icmp_signed('==', a_size, b.size) + + res = cgutils.alloca_once_value(builder, same_size) + + with builder.if_then(same_size): + with cgutils.for_range(builder, a_size) as loop: + v = a.getitem(loop.index) + w = b.getitem(loop.index) + itemres = context.generic_compare(builder, operator.eq, + (aty.dtype, bty.dtype), (v, w)) + with builder.if_then(builder.not_(itemres)): + # Exit early + builder.store(cgutils.false_bit, res) + loop.do_break() + + return builder.load(res) + + +def all_list(*args): + return all([isinstance(typ, types.List) for typ in args]) + +@overload(operator.ne) +def impl_list_ne(a, b): + if not all_list(a, b): + return + + def list_ne_impl(a, b): + return not (a == b) + + return list_ne_impl + +@overload(operator.le) +def impl_list_le(a, b): + if not all_list(a, b): + return + + def list_le_impl(a, b): + m = len(a) + n = len(b) + for i in range(min(m, n)): + if a[i] < b[i]: + return True + elif a[i] > b[i]: + return False + return m <= n + + return list_le_impl + +@overload(operator.lt) +def impl_list_lt(a, b): + if not all_list(a, b): + return + + def list_lt_impl(a, b): + m = len(a) + n = len(b) + for i in range(min(m, n)): + if a[i] < b[i]: + return True + elif a[i] > b[i]: + return False + return m < n + + return list_lt_impl + +@overload(operator.ge) +def impl_list_ge(a, b): + if not all_list(a, b): + return + + def list_ge_impl(a, b): + return b <= a + + return list_ge_impl + +@overload(operator.gt) +def impl_list_gt(a, b): + if not all_list(a, b): + return + + def list_gt_impl(a, b): + return b < a + + return list_gt_impl + +#------------------------------------------------------------------------------- +# Methods + +@lower_builtin("list.append", types.List, types.Any) +def list_append(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + item = args[1] + + n = inst.size + new_size = builder.add(n, ir.Constant(n.type, 1)) + inst.resize(new_size) + inst.setitem(n, item, incref=True) + + return context.get_dummy_value() + +@lower_builtin("list.clear", types.List) +def list_clear(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + inst.resize(context.get_constant(types.intp, 0)) + + return context.get_dummy_value() + + +@overload_method(types.List, "copy") +def list_copy(lst): + def list_copy_impl(lst): + return list(lst) + + return list_copy_impl + + +@overload_method(types.List, "count") +def list_count(lst, value): + + def list_count_impl(lst, value): + res = 0 + for elem in lst: + if elem == value: + res += 1 + return res + + return list_count_impl + + +def _list_extend_list(context, builder, sig, args): + src = ListInstance(context, builder, sig.args[1], args[1]) + dest = ListInstance(context, builder, sig.args[0], args[0]) + + src_size = src.size + dest_size = dest.size + nitems = builder.add(src_size, dest_size) + dest.resize(nitems) + dest.size = nitems + + with cgutils.for_range(builder, src_size) as loop: + value = src.getitem(loop.index) + value = context.cast(builder, value, src.dtype, dest.dtype) + dest.setitem(builder.add(loop.index, dest_size), value, incref=True) + + return dest + +@lower_builtin("list.extend", types.List, types.IterableType) +def list_extend(context, builder, sig, args): + if isinstance(sig.args[1], types.List): + # Specialize for list operands, for speed. + _list_extend_list(context, builder, sig, args) + return context.get_dummy_value() + + def list_extend(lst, iterable): + # Speed hack to avoid NRT refcount operations inside the loop + meth = lst.append + for v in iterable: + meth(v) + + return context.compile_internal(builder, list_extend, sig, args) + + +intp_max = types.intp.maxval + + +@overload_method(types.List, "index") +def list_index(lst, value, start=0, stop=intp_max): + + if not isinstance(start, (int, types.Integer, types.Omitted)): + raise errors.TypingError(f'arg "start" must be an Integer. Got {start}') + if not isinstance(stop, (int, types.Integer, types.Omitted)): + raise errors.TypingError(f'arg "stop" must be an Integer. Got {stop}') + + def list_index_impl(lst, value, start=0, stop=intp_max): + n = len(lst) + if start < 0: + start += n + if start < 0: + start = 0 + if stop < 0: + stop += n + if stop > n: + stop = n + for i in range(start, stop): + if lst[i] == value: + return i + # XXX references are leaked when raising + raise ValueError("value not in list") + return list_index_impl + + +@lower_builtin("list.insert", types.List, types.Integer, + types.Any) +def list_insert(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + index = inst.fix_index(args[1]) + index = inst.clamp_index(index) + value = args[2] + + n = inst.size + one = ir.Constant(n.type, 1) + new_size = builder.add(n, one) + inst.resize(new_size) + inst.move(builder.add(index, one), index, builder.sub(n, index)) + inst.setitem(index, value, incref=True, decref_old_value=False) + + return context.get_dummy_value() + +@lower_builtin("list.pop", types.List) +def list_pop(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + + n = inst.size + cgutils.guard_zero(context, builder, n, + (IndexError, "pop from empty list")) + n = builder.sub(n, ir.Constant(n.type, 1)) + res = inst.getitem(n) + inst.incref_value(res) # incref the pop'ed element + inst.clear_value(n) # clear the storage space + inst.resize(n) + return impl_ret_new_ref(context, builder, sig.return_type, res) + +@lower_builtin("list.pop", types.List, types.Integer) +def list_pop(context, builder, sig, args): + inst = ListInstance(context, builder, sig.args[0], args[0]) + idx = inst.fix_index(args[1]) + + n = inst.size + cgutils.guard_zero(context, builder, n, + (IndexError, "pop from empty list")) + inst.guard_index(idx, "pop index out of range") + + res = inst.getitem(idx) + + one = ir.Constant(n.type, 1) + n = builder.sub(n, ir.Constant(n.type, 1)) + inst.move(idx, builder.add(idx, one), builder.sub(n, idx)) + inst.resize(n) + return impl_ret_new_ref(context, builder, sig.return_type, res) + +@overload_method(types.List, "remove") +def list_remove(lst, value): + + def list_remove_impl(lst, value): + for i in range(len(lst)): + if lst[i] == value: + lst.pop(i) + return + # XXX references are leaked when raising + raise ValueError("list.remove(x): x not in list") + + return list_remove_impl + +@overload_method(types.List, "reverse") +def list_reverse(lst): + + def list_reverse_impl(lst): + for a in range(0, len(lst) // 2): + b = -a - 1 + lst[a], lst[b] = lst[b], lst[a] + + return list_reverse_impl + +# ----------------------------------------------------------------------------- +# Sorting + +def gt(a, b): + return a > b + +sort_forwards = quicksort.make_jit_quicksort().run_quicksort +sort_backwards = quicksort.make_jit_quicksort(lt=gt).run_quicksort + +arg_sort_forwards = quicksort.make_jit_quicksort(is_argsort=True, + is_list=True).run_quicksort +arg_sort_backwards = quicksort.make_jit_quicksort(is_argsort=True, lt=gt, + is_list=True).run_quicksort + + +def _sort_check_reverse(reverse): + if isinstance(reverse, types.Omitted): + rty = reverse.value + elif isinstance(reverse, types.Optional): + rty = reverse.type + else: + rty = reverse + if not isinstance(rty, (types.Boolean, types.Integer, int, bool)): + msg = "an integer is required for 'reverse' (got type %s)" % reverse + raise errors.TypingError(msg) + return rty + + +def _sort_check_key(key): + if isinstance(key, types.Optional): + msg = ("Key must concretely be None or a Numba JIT compiled function, " + "an Optional (union of None and a value) was found") + raise errors.TypingError(msg) + if not (cgutils.is_nonelike(key) or isinstance(key, types.Dispatcher)): + msg = "Key must be None or a Numba JIT compiled function" + raise errors.TypingError(msg) + + +@overload_method(types.List, "sort") +def ol_list_sort(lst, key=None, reverse=False): + + _sort_check_key(key) + _sort_check_reverse(reverse) + + if cgutils.is_nonelike(key): + KEY = False + sort_f = sort_forwards + sort_b = sort_backwards + elif isinstance(key, types.Dispatcher): + KEY = True + sort_f = arg_sort_forwards + sort_b = arg_sort_backwards + + def impl(lst, key=None, reverse=False): + if KEY is True: + _lst = [key(x) for x in lst] + else: + _lst = lst + if reverse is False or reverse == 0: + tmp = sort_f(_lst) + else: + tmp = sort_b(_lst) + if KEY is True: + lst[:] = [lst[i] for i in tmp] + return impl + + +@overload(sorted) +def ol_sorted(iterable, key=None, reverse=False): + + if not isinstance(iterable, types.IterableType): + return False + + _sort_check_key(key) + _sort_check_reverse(reverse) + + def impl(iterable, key=None, reverse=False): + lst = list(iterable) + lst.sort(key=key, reverse=reverse) + return lst + return impl + +# ----------------------------------------------------------------------------- +# Implicit casting + +@lower_cast(types.List, types.List) +def list_to_list(context, builder, fromty, toty, val): + # Casting from non-reflected to reflected + assert fromty.dtype == toty.dtype + return val + +# ----------------------------------------------------------------------------- +# Implementations for types.LiteralList +# ----------------------------------------------------------------------------- + +_banned_error = errors.TypingError("Cannot mutate a literal list") + + +# Things that mutate literal lists are banned +@overload_method(types.LiteralList, 'append') +def literal_list_banned_append(lst, obj): + raise _banned_error + + +@overload_method(types.LiteralList, 'extend') +def literal_list_banned_extend(lst, iterable): + raise _banned_error + + +@overload_method(types.LiteralList, 'insert') +def literal_list_banned_insert(lst, index, obj): + raise _banned_error + + +@overload_method(types.LiteralList, 'remove') +def literal_list_banned_remove(lst, value): + raise _banned_error + + +@overload_method(types.LiteralList, 'pop') +def literal_list_banned_pop(lst, index=-1): + raise _banned_error + + +@overload_method(types.LiteralList, 'clear') +def literal_list_banned_clear(lst): + raise _banned_error + + +@overload_method(types.LiteralList, 'sort') +def literal_list_banned_sort(lst, key=None, reverse=False): + raise _banned_error + + +@overload_method(types.LiteralList, 'reverse') +def literal_list_banned_reverse(lst): + raise _banned_error + +_index_end = types.intp.maxval + +@overload_method(types.LiteralList, 'index') +def literal_list_index(lst, x, start=0, end=_index_end): + # TODO: To make this work, need consts as slice for start/end so as to + # be able to statically analyse the bounds, then its a just loop body + # versioning based iteration along with enumerate to find the item + if isinstance(lst, types.LiteralList): + msg = "list.index is unsupported for literal lists" + raise errors.TypingError(msg) + +@overload_method(types.LiteralList, 'count') +def literal_list_count(lst, x): + if isinstance(lst, types.LiteralList): + def impl(lst, x): + count = 0 + for val in literal_unroll(lst): + if val == x: + count += 1 + return count + return impl + +@overload_method(types.LiteralList, 'copy') +def literal_list_count(lst): + if isinstance(lst, types.LiteralList): + def impl(lst): + return lst # tuples are immutable, as is this, so just return it + return impl + +@overload(operator.delitem) +def literal_list_delitem(lst, index): + if isinstance(lst, types.LiteralList): + raise _banned_error + +@overload(operator.setitem) +def literal_list_setitem(lst, index, value): + if isinstance(lst, types.LiteralList): + raise errors.TypingError("Cannot mutate a literal list") + +@overload(operator.getitem) +def literal_list_getitem(lst, *args): + if not isinstance(lst, types.LiteralList): + return + msg = ("Cannot __getitem__ on a literal list, return type cannot be " + "statically determined.") + raise errors.TypingError(msg) + +@overload(len) +def literal_list_len(lst): + if not isinstance(lst, types.LiteralList): + return + l = lst.count + return lambda lst: l + +@overload(operator.contains) +def literal_list_contains(lst, item): + if isinstance(lst, types.LiteralList): + def impl(lst, item): + for val in literal_unroll(lst): + if val == item: + return True + return False + return impl + +@lower_cast(types.LiteralList, types.LiteralList) +def literallist_to_literallist(context, builder, fromty, toty, val): + if len(fromty) != len(toty): + # Disallowed by typing layer + raise NotImplementedError + + olditems = cgutils.unpack_tuple(builder, val, len(fromty)) + items = [context.cast(builder, v, f, t) + for v, f, t in zip(olditems, fromty, toty)] + return context.make_tuple(builder, toty, items) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/mathimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/mathimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3c6e88dbc06ea107ac6a8fb2841f291d9c46ef --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/mathimpl.py @@ -0,0 +1,471 @@ +""" +Provide math calls that uses intrinsics or libc math functions. +""" + +import math +import operator +import sys +import numpy as np + +import llvmlite.ir +from llvmlite.ir import Constant + +from numba.core.imputils import Registry, impl_ret_untracked +from numba import typeof +from numba.core import types, utils, config, cgutils +from numba.core.extending import overload +from numba.core.typing import signature +from numba.cpython.unsafe.numbers import trailing_zeros + + +registry = Registry('mathimpl') +lower = registry.lower + + +# Helpers, shared with cmathimpl. +_NP_FLT_FINFO = np.finfo(np.dtype('float32')) +FLT_MAX = _NP_FLT_FINFO.max +FLT_MIN = _NP_FLT_FINFO.tiny + +_NP_DBL_FINFO = np.finfo(np.dtype('float64')) +DBL_MAX = _NP_DBL_FINFO.max +DBL_MIN = _NP_DBL_FINFO.tiny + +FLOAT_ABS_MASK = 0x7fffffff +FLOAT_SIGN_MASK = 0x80000000 +DOUBLE_ABS_MASK = 0x7fffffffffffffff +DOUBLE_SIGN_MASK = 0x8000000000000000 + + +def is_nan(builder, val): + """ + Return a condition testing whether *val* is a NaN. + """ + return builder.fcmp_unordered('uno', val, val) + +def is_inf(builder, val): + """ + Return a condition testing whether *val* is an infinite. + """ + pos_inf = Constant(val.type, float("+inf")) + neg_inf = Constant(val.type, float("-inf")) + isposinf = builder.fcmp_ordered('==', val, pos_inf) + isneginf = builder.fcmp_ordered('==', val, neg_inf) + return builder.or_(isposinf, isneginf) + +def is_finite(builder, val): + """ + Return a condition testing whether *val* is a finite. + """ + # is_finite(x) <=> x - x != NaN + val_minus_val = builder.fsub(val, val) + return builder.fcmp_ordered('ord', val_minus_val, val_minus_val) + +def f64_as_int64(builder, val): + """ + Bitcast a double into a 64-bit integer. + """ + assert val.type == llvmlite.ir.DoubleType() + return builder.bitcast(val, llvmlite.ir.IntType(64)) + +def int64_as_f64(builder, val): + """ + Bitcast a 64-bit integer into a double. + """ + assert val.type == llvmlite.ir.IntType(64) + return builder.bitcast(val, llvmlite.ir.DoubleType()) + +def f32_as_int32(builder, val): + """ + Bitcast a float into a 32-bit integer. + """ + assert val.type == llvmlite.ir.FloatType() + return builder.bitcast(val, llvmlite.ir.IntType(32)) + +def int32_as_f32(builder, val): + """ + Bitcast a 32-bit integer into a float. + """ + assert val.type == llvmlite.ir.IntType(32) + return builder.bitcast(val, llvmlite.ir.FloatType()) + +def negate_real(builder, val): + """ + Negate real number *val*, with proper handling of zeros. + """ + # The negative zero forces LLVM to handle signed zeros properly. + return builder.fsub(Constant(val.type, -0.0), val) + +def call_fp_intrinsic(builder, name, args): + """ + Call a LLVM intrinsic floating-point operation. + """ + mod = builder.module + intr = mod.declare_intrinsic(name, [a.type for a in args]) + return builder.call(intr, args) + + +def _unary_int_input_wrapper_impl(wrapped_impl): + """ + Return an implementation factory to convert the single integral input + argument to a float64, then defer to the *wrapped_impl*. + """ + def implementer(context, builder, sig, args): + val, = args + input_type = sig.args[0] + fpval = context.cast(builder, val, input_type, types.float64) + inner_sig = signature(types.float64, types.float64) + res = wrapped_impl(context, builder, inner_sig, (fpval,)) + return context.cast(builder, res, types.float64, sig.return_type) + + return implementer + +def unary_math_int_impl(fn, float_impl): + impl = _unary_int_input_wrapper_impl(float_impl) + lower(fn, types.Integer)(impl) + +def unary_math_intr(fn, intrcode): + """ + Implement the math function *fn* using the LLVM intrinsic *intrcode*. + """ + @lower(fn, types.Float) + def float_impl(context, builder, sig, args): + res = call_fp_intrinsic(builder, intrcode, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + unary_math_int_impl(fn, float_impl) + return float_impl + +def unary_math_extern(fn, f32extern, f64extern, int_restype=False): + """ + Register implementations of Python function *fn* using the + external function named *f32extern* and *f64extern* (for float32 + and float64 inputs, respectively). + If *int_restype* is true, then the function's return value should be + integral, otherwise floating-point. + """ + f_restype = types.int64 if int_restype else None + + def float_impl(context, builder, sig, args): + """ + Implement *fn* for a types.Float input. + """ + [val] = args + mod = builder.module + input_type = sig.args[0] + lty = context.get_value_type(input_type) + func_name = { + types.float32: f32extern, + types.float64: f64extern, + }[input_type] + fnty = llvmlite.ir.FunctionType(lty, [lty]) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, (val,)) + res = context.cast(builder, res, input_type, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + lower(fn, types.Float)(float_impl) + + # Implement wrapper for integer inputs + unary_math_int_impl(fn, float_impl) + + return float_impl + + +unary_math_intr(math.fabs, 'llvm.fabs') +exp_impl = unary_math_intr(math.exp, 'llvm.exp') +if sys.version_info >= (3, 11): + exp2_impl = unary_math_intr(math.exp2, 'llvm.exp2') +log_impl = unary_math_intr(math.log, 'llvm.log') +log10_impl = unary_math_intr(math.log10, 'llvm.log10') +log2_impl = unary_math_intr(math.log2, 'llvm.log2') +sin_impl = unary_math_intr(math.sin, 'llvm.sin') +cos_impl = unary_math_intr(math.cos, 'llvm.cos') + +log1p_impl = unary_math_extern(math.log1p, "log1pf", "log1p") +expm1_impl = unary_math_extern(math.expm1, "expm1f", "expm1") +erf_impl = unary_math_extern(math.erf, "erff", "erf") +erfc_impl = unary_math_extern(math.erfc, "erfcf", "erfc") + +tan_impl = unary_math_extern(math.tan, "tanf", "tan") +asin_impl = unary_math_extern(math.asin, "asinf", "asin") +acos_impl = unary_math_extern(math.acos, "acosf", "acos") +atan_impl = unary_math_extern(math.atan, "atanf", "atan") + +asinh_impl = unary_math_extern(math.asinh, "asinhf", "asinh") +acosh_impl = unary_math_extern(math.acosh, "acoshf", "acosh") +atanh_impl = unary_math_extern(math.atanh, "atanhf", "atanh") +sinh_impl = unary_math_extern(math.sinh, "sinhf", "sinh") +cosh_impl = unary_math_extern(math.cosh, "coshf", "cosh") +tanh_impl = unary_math_extern(math.tanh, "tanhf", "tanh") + +log2_impl = unary_math_extern(math.log2, "log2f", "log2") +ceil_impl = unary_math_extern(math.ceil, "ceilf", "ceil", True) +floor_impl = unary_math_extern(math.floor, "floorf", "floor", True) + +gamma_impl = unary_math_extern(math.gamma, "numba_gammaf", "numba_gamma") # work-around +sqrt_impl = unary_math_extern(math.sqrt, "sqrtf", "sqrt") +trunc_impl = unary_math_extern(math.trunc, "truncf", "trunc", True) +lgamma_impl = unary_math_extern(math.lgamma, "lgammaf", "lgamma") + + +@lower(math.isnan, types.Float) +def isnan_float_impl(context, builder, sig, args): + [val] = args + res = is_nan(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower(math.isnan, types.Integer) +def isnan_int_impl(context, builder, sig, args): + res = cgutils.false_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isinf, types.Float) +def isinf_float_impl(context, builder, sig, args): + [val] = args + res = is_inf(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower(math.isinf, types.Integer) +def isinf_int_impl(context, builder, sig, args): + res = cgutils.false_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isfinite, types.Float) +def isfinite_float_impl(context, builder, sig, args): + [val] = args + res = is_finite(builder, val) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.isfinite, types.Integer) +def isfinite_int_impl(context, builder, sig, args): + res = cgutils.true_bit + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.copysign, types.Float, types.Float) +def copysign_float_impl(context, builder, sig, args): + lty = args[0].type + mod = builder.module + fn = cgutils.get_or_insert_function(mod, llvmlite.ir.FunctionType(lty, (lty, lty)), + 'llvm.copysign.%s' % lty.intrinsic_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.frexp, types.Float) +def frexp_impl(context, builder, sig, args): + val, = args + fltty = context.get_data_type(sig.args[0]) + intty = context.get_data_type(sig.return_type[1]) + expptr = cgutils.alloca_once(builder, intty, name='exp') + fnty = llvmlite.ir.FunctionType(fltty, (fltty, llvmlite.ir.PointerType(intty))) + fname = { + "float": "numba_frexpf", + "double": "numba_frexp", + }[str(fltty)] + fn = cgutils.get_or_insert_function(builder.module, fnty, fname) + res = builder.call(fn, (val, expptr)) + res = cgutils.make_anonymous_struct(builder, (res, builder.load(expptr))) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.ldexp, types.Float, types.intc) +def ldexp_impl(context, builder, sig, args): + val, exp = args + fltty, intty = map(context.get_data_type, sig.args) + fnty = llvmlite.ir.FunctionType(fltty, (fltty, intty)) + fname = { + "float": "numba_ldexpf", + "double": "numba_ldexp", + }[str(fltty)] + fn = cgutils.insert_pure_function(builder.module, fnty, name=fname) + res = builder.call(fn, (val, exp)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.atan2, types.int64, types.int64) +def atan2_s64_impl(context, builder, sig, args): + [y, x] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + return atan2_float_impl(context, builder, fsig, (y, x)) + +@lower(math.atan2, types.uint64, types.uint64) +def atan2_u64_impl(context, builder, sig, args): + [y, x] = args + y = builder.uitofp(y, llvmlite.ir.DoubleType()) + x = builder.uitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + return atan2_float_impl(context, builder, fsig, (y, x)) + +@lower(math.atan2, types.Float, types.Float) +def atan2_float_impl(context, builder, sig, args): + assert len(args) == 2 + mod = builder.module + ty = sig.args[0] + lty = context.get_value_type(ty) + func_name = { + types.float32: "atan2f", + types.float64: "atan2" + }[ty] + fnty = llvmlite.ir.FunctionType(lty, (lty, lty)) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + + +@lower(math.hypot, types.int64, types.int64) +def hypot_s64_impl(context, builder, sig, args): + [x, y] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + res = hypot_float_impl(context, builder, fsig, (x, y)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.hypot, types.uint64, types.uint64) +def hypot_u64_impl(context, builder, sig, args): + [x, y] = args + y = builder.sitofp(y, llvmlite.ir.DoubleType()) + x = builder.sitofp(x, llvmlite.ir.DoubleType()) + fsig = signature(types.float64, types.float64, types.float64) + res = hypot_float_impl(context, builder, fsig, (x, y)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(math.hypot, types.Float, types.Float) +def hypot_float_impl(context, builder, sig, args): + xty, yty = sig.args + assert xty == yty == sig.return_type + x, y = args + + # Windows has alternate names for hypot/hypotf, see + # https://msdn.microsoft.com/fr-fr/library/a9yb3dbt%28v=vs.80%29.aspx + fname = { + types.float32: "_hypotf" if sys.platform == 'win32' else "hypotf", + types.float64: "_hypot" if sys.platform == 'win32' else "hypot", + }[xty] + plat_hypot = types.ExternalFunction(fname, sig) + + if sys.platform == 'win32' and config.MACHINE_BITS == 32: + inf = xty(float('inf')) + + def hypot_impl(x, y): + if math.isinf(x) or math.isinf(y): + return inf + return plat_hypot(x, y) + else: + def hypot_impl(x, y): + return plat_hypot(x, y) + + res = context.compile_internal(builder, hypot_impl, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ----------------------------------------------------------------------------- + +@lower(math.radians, types.Float) +def radians_float_impl(context, builder, sig, args): + [x] = args + coef = context.get_constant(sig.return_type, math.pi / 180) + res = builder.fmul(x, coef) + return impl_ret_untracked(context, builder, sig.return_type, res) + +unary_math_int_impl(math.radians, radians_float_impl) + +# ----------------------------------------------------------------------------- + +@lower(math.degrees, types.Float) +def degrees_float_impl(context, builder, sig, args): + [x] = args + coef = context.get_constant(sig.return_type, 180 / math.pi) + res = builder.fmul(x, coef) + return impl_ret_untracked(context, builder, sig.return_type, res) + +unary_math_int_impl(math.degrees, degrees_float_impl) + +# ----------------------------------------------------------------------------- + +@lower(math.pow, types.Float, types.Float) +@lower(math.pow, types.Float, types.Integer) +def pow_impl(context, builder, sig, args): + impl = context.get_function(operator.pow, sig) + return impl(builder, args) + +# ----------------------------------------------------------------------------- + +@lower(math.nextafter, types.Float, types.Float) +def nextafter_impl(context, builder, sig, args): + assert len(args) == 2 + ty = sig.args[0] + lty = context.get_value_type(ty) + func_name = { + types.float32: "nextafterf", + types.float64: "nextafter" + }[ty] + fnty = llvmlite.ir.FunctionType(lty, (lty, lty)) + fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name) + res = builder.call(fn, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# ----------------------------------------------------------------------------- + +def _unsigned(T): + """Convert integer to unsigned integer of equivalent width.""" + pass + +@overload(_unsigned) +def _unsigned_impl(T): + if T in types.unsigned_domain: + return lambda T: T + elif T in types.signed_domain: + newT = getattr(types, 'uint{}'.format(T.bitwidth)) + return lambda T: newT(T) + + +def gcd_impl(context, builder, sig, args): + xty, yty = sig.args + assert xty == yty == sig.return_type + x, y = args + + def gcd(a, b): + """ + Stein's algorithm, heavily cribbed from Julia implementation. + """ + T = type(a) + if a == 0: return abs(b) + if b == 0: return abs(a) + za = trailing_zeros(a) + zb = trailing_zeros(b) + k = min(za, zb) + # Uses np.*_shift instead of operators due to return types + u = _unsigned(abs(np.right_shift(a, za))) + v = _unsigned(abs(np.right_shift(b, zb))) + while u != v: + if u > v: + u, v = v, u + v -= u + v = np.right_shift(v, trailing_zeros(v)) + r = np.left_shift(T(u), k) + return r + + res = context.compile_internal(builder, gcd, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +lower(math.gcd, types.Integer, types.Integer)(gcd_impl) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/numbers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..740dd8950a05d5d3685825aafdf60c88908a20a1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/numbers.py @@ -0,0 +1,1397 @@ +import math +import numbers + +import numpy as np +import operator + +from llvmlite import ir +from llvmlite.ir import Constant + +from numba.core.imputils import (lower_builtin, lower_getattr, + lower_getattr_generic, lower_cast, + lower_constant, impl_ret_borrowed, + impl_ret_untracked) +from numba.core import typing, types, utils, errors, cgutils, optional +from numba.core.extending import intrinsic, overload_method +from numba.cpython.unsafe.numbers import viewer + +def _int_arith_flags(rettype): + """ + Return the modifier flags for integer arithmetic. + """ + if rettype.signed: + # Ignore the effects of signed overflow. This is important for + # optimization of some indexing operations. For example + # array[i+1] could see `i+1` trigger a signed overflow and + # give a negative number. With Python's indexing, a negative + # index is treated differently: its resolution has a runtime cost. + # Telling LLVM to ignore signed overflows allows it to optimize + # away the check for a negative `i+1` if it knows `i` is positive. + return ['nsw'] + else: + return [] + + +def int_add_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + a = context.cast(builder, va, ta, sig.return_type) + b = context.cast(builder, vb, tb, sig.return_type) + res = builder.add(a, b, flags=_int_arith_flags(sig.return_type)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_sub_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + a = context.cast(builder, va, ta, sig.return_type) + b = context.cast(builder, vb, tb, sig.return_type) + res = builder.sub(a, b, flags=_int_arith_flags(sig.return_type)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_mul_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + a = context.cast(builder, va, ta, sig.return_type) + b = context.cast(builder, vb, tb, sig.return_type) + res = builder.mul(a, b, flags=_int_arith_flags(sig.return_type)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_divmod_signed(context, builder, ty, x, y): + """ + Reference Objects/intobject.c + xdivy = x / y; + xmody = (long)(x - (unsigned long)xdivy * y); + /* If the signs of x and y differ, and the remainder is non-0, + * C89 doesn't define whether xdivy is now the floor or the + * ceiling of the infinitely precise quotient. We want the floor, + * and we have it iff the remainder's sign matches y's. + */ + if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) { + xmody += y; + --xdivy; + assert(xmody && ((y ^ xmody) >= 0)); + } + *p_xdivy = xdivy; + *p_xmody = xmody; + """ + assert x.type == y.type + + ZERO = y.type(0) + ONE = y.type(1) + + # NOTE: On x86 at least, dividing the lowest representable integer + # (e.g. 0x80000000 for int32) by -1 causes a SIFGPE (division overflow), + # causing the process to crash. + # We return 0, 0 instead (more or less like Numpy). + + resdiv = cgutils.alloca_once_value(builder, ZERO) + resmod = cgutils.alloca_once_value(builder, ZERO) + + is_overflow = builder.and_( + builder.icmp_signed('==', x, x.type(ty.minval)), + builder.icmp_signed('==', y, y.type(-1))) + + with builder.if_then(builder.not_(is_overflow), likely=True): + # Note LLVM will optimize this to a single divmod instruction, + # if available on the target CPU (e.g. x86). + xdivy = builder.sdiv(x, y) + xmody = builder.srem(x, y) + + y_xor_xmody_ltz = builder.icmp_signed('<', builder.xor(y, xmody), ZERO) + xmody_istrue = builder.icmp_signed('!=', xmody, ZERO) + cond = builder.and_(xmody_istrue, y_xor_xmody_ltz) + + with builder.if_else(cond) as (if_different_signs, if_same_signs): + with if_same_signs: + builder.store(xdivy, resdiv) + builder.store(xmody, resmod) + + with if_different_signs: + builder.store(builder.sub(xdivy, ONE), resdiv) + builder.store(builder.add(xmody, y), resmod) + + return builder.load(resdiv), builder.load(resmod) + + +def int_divmod(context, builder, ty, x, y): + """ + Integer divmod(x, y). The caller must ensure that y != 0. + """ + if ty.signed: + return int_divmod_signed(context, builder, ty, x, y) + else: + return builder.udiv(x, y), builder.urem(x, y) + + +def _int_divmod_impl(context, builder, sig, args, zerodiv_message): + va, vb = args + ta, tb = sig.args + + ty = sig.return_type + if isinstance(ty, types.UniTuple): + ty = ty.dtype + a = context.cast(builder, va, ta, ty) + b = context.cast(builder, vb, tb, ty) + quot = cgutils.alloca_once(builder, a.type, name="quot") + rem = cgutils.alloca_once(builder, a.type, name="rem") + + with builder.if_else(cgutils.is_scalar_zero(builder, b), likely=False + ) as (if_zero, if_non_zero): + with if_zero: + if not context.error_model.fp_zero_division( + builder, (zerodiv_message,)): + # No exception raised => return 0 + # XXX We should also set the FPU exception status, but + # there's no easy way to do that from LLVM. + builder.store(b, quot) + builder.store(b, rem) + with if_non_zero: + q, r = int_divmod(context, builder, ty, a, b) + builder.store(q, quot) + builder.store(r, rem) + + return quot, rem + + +@lower_builtin(divmod, types.Integer, types.Integer) +def int_divmod_impl(context, builder, sig, args): + quot, rem = _int_divmod_impl(context, builder, sig, args, + "integer divmod by zero") + + return cgutils.pack_array(builder, + (builder.load(quot), builder.load(rem))) + + +@lower_builtin(operator.floordiv, types.Integer, types.Integer) +@lower_builtin(operator.ifloordiv, types.Integer, types.Integer) +def int_floordiv_impl(context, builder, sig, args): + quot, rem = _int_divmod_impl(context, builder, sig, args, + "integer division by zero") + return builder.load(quot) + + +@lower_builtin(operator.truediv, types.Integer, types.Integer) +@lower_builtin(operator.itruediv, types.Integer, types.Integer) +def int_truediv_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + a = context.cast(builder, va, ta, sig.return_type) + b = context.cast(builder, vb, tb, sig.return_type) + with cgutils.if_zero(builder, b): + context.error_model.fp_zero_division(builder, ("division by zero",)) + res = builder.fdiv(a, b) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.mod, types.Integer, types.Integer) +@lower_builtin(operator.imod, types.Integer, types.Integer) +def int_rem_impl(context, builder, sig, args): + quot, rem = _int_divmod_impl(context, builder, sig, args, + "integer modulo by zero") + return builder.load(rem) + + +def _get_power_zerodiv_return(context, return_type): + if (isinstance(return_type, types.Integer) + and not context.error_model.raise_on_fp_zero_division): + # If not raising, return 0x8000... when computing 0 ** + return -1 << (return_type.bitwidth - 1) + else: + return False + + +def int_power_impl(context, builder, sig, args): + """ + a ^ b, where a is an integer or real, and b an integer + """ + is_integer = isinstance(sig.args[0], types.Integer) + tp = sig.return_type + zerodiv_return = _get_power_zerodiv_return(context, tp) + + def int_power(a, b): + # Ensure computations are done with a large enough width + r = tp(1) + a = tp(a) + if b < 0: + invert = True + exp = -b + if exp < 0: + raise OverflowError + if is_integer: + if a == 0: + if zerodiv_return: + return zerodiv_return + else: + raise ZeroDivisionError("0 cannot be raised to a negative power") + if a != 1 and a != -1: + return 0 + else: + invert = False + exp = b + if exp > 0x10000: + # Optimization cutoff: fallback on the generic algorithm + return math.pow(a, float(b)) + while exp != 0: + if exp & 1: + r *= a + exp >>= 1 + a *= a + + if invert: + return 1.0 / r + return r + + res = context.compile_internal(builder, int_power, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.pow, types.Integer, types.IntegerLiteral) +@lower_builtin(operator.ipow, types.Integer, types.IntegerLiteral) +@lower_builtin(operator.pow, types.Float, types.IntegerLiteral) +@lower_builtin(operator.ipow, types.Float, types.IntegerLiteral) +def static_power_impl(context, builder, sig, args): + """ + a ^ b, where a is an integer or real, and b a constant integer + """ + exp = sig.args[1].value + if not isinstance(exp, numbers.Integral): + raise NotImplementedError + if abs(exp) > 0x10000: + # Optimization cutoff: fallback on the generic algorithm above + raise NotImplementedError + invert = exp < 0 + exp = abs(exp) + + tp = sig.return_type + is_integer = isinstance(tp, types.Integer) + zerodiv_return = _get_power_zerodiv_return(context, tp) + + val = context.cast(builder, args[0], sig.args[0], tp) + lty = val.type + + def mul(a, b): + if is_integer: + return builder.mul(a, b) + else: + return builder.fmul(a, b) + + # Unroll the exponentiation loop + res = lty(1) + a = val + while exp != 0: + if exp & 1: + res = mul(res, val) + exp >>= 1 + val = mul(val, val) + + if invert: + # If the exponent was negative, fix the result by inverting it + if is_integer: + # Integer inversion + def invert_impl(a): + if a == 0: + if zerodiv_return: + return zerodiv_return + else: + raise ZeroDivisionError("0 cannot be raised to a negative power") + if a != 1 and a != -1: + return 0 + else: + return a + + else: + # Real inversion + def invert_impl(a): + return 1.0 / a + + res = context.compile_internal(builder, invert_impl, + typing.signature(tp, tp), (res,)) + + return res + + +def int_slt_impl(context, builder, sig, args): + res = builder.icmp_signed('<', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_sle_impl(context, builder, sig, args): + res = builder.icmp_signed('<=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_sgt_impl(context, builder, sig, args): + res = builder.icmp_signed('>', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_sge_impl(context, builder, sig, args): + res = builder.icmp_signed('>=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_ult_impl(context, builder, sig, args): + res = builder.icmp_unsigned('<', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_ule_impl(context, builder, sig, args): + res = builder.icmp_unsigned('<=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_ugt_impl(context, builder, sig, args): + res = builder.icmp_unsigned('>', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_uge_impl(context, builder, sig, args): + res = builder.icmp_unsigned('>=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_eq_impl(context, builder, sig, args): + res = builder.icmp_unsigned('==', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_ne_impl(context, builder, sig, args): + res = builder.icmp_unsigned('!=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_signed_unsigned_cmp(op): + def impl(context, builder, sig, args): + (left, right) = args + # This code is translated from the NumPy source. + # What we're going to do is divide the range of a signed value at zero. + # If the signed value is less than zero, then we can treat zero as the + # unsigned value since the unsigned value is necessarily zero or larger + # and any signed comparison between a negative value and zero/infinity + # will yield the same result. If the signed value is greater than or + # equal to zero, then we can safely cast it to an unsigned value and do + # the expected unsigned-unsigned comparison operation. + # Original: https://github.com/numpy/numpy/pull/23713 + cmp_zero = builder.icmp_signed('<', left, Constant(left.type, 0)) + lt_zero = builder.icmp_signed(op, left, Constant(left.type, 0)) + ge_zero = builder.icmp_unsigned(op, left, right) + res = builder.select(cmp_zero, lt_zero, ge_zero) + return impl_ret_untracked(context, builder, sig.return_type, res) + return impl + + +def int_unsigned_signed_cmp(op): + def impl(context, builder, sig, args): + (left, right) = args + # See the function `int_signed_unsigned_cmp` for implementation notes. + cmp_zero = builder.icmp_signed('<', right, Constant(right.type, 0)) + lt_zero = builder.icmp_signed(op, Constant(right.type, 0), right) + ge_zero = builder.icmp_unsigned(op, left, right) + res = builder.select(cmp_zero, lt_zero, ge_zero) + return impl_ret_untracked(context, builder, sig.return_type, res) + return impl + + +def int_abs_impl(context, builder, sig, args): + [x] = args + ZERO = Constant(x.type, None) + ltz = builder.icmp_signed('<', x, ZERO) + negated = builder.neg(x) + res = builder.select(ltz, negated, x) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def uint_abs_impl(context, builder, sig, args): + [x] = args + return impl_ret_untracked(context, builder, sig.return_type, x) + + +def int_shl_impl(context, builder, sig, args): + [valty, amtty] = sig.args + [val, amt] = args + val = context.cast(builder, val, valty, sig.return_type) + amt = context.cast(builder, amt, amtty, sig.return_type) + res = builder.shl(val, amt) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_shr_impl(context, builder, sig, args): + [valty, amtty] = sig.args + [val, amt] = args + val = context.cast(builder, val, valty, sig.return_type) + amt = context.cast(builder, amt, amtty, sig.return_type) + if sig.return_type.signed: + res = builder.ashr(val, amt) + else: + res = builder.lshr(val, amt) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_and_impl(context, builder, sig, args): + [at, bt] = sig.args + [av, bv] = args + cav = context.cast(builder, av, at, sig.return_type) + cbc = context.cast(builder, bv, bt, sig.return_type) + res = builder.and_(cav, cbc) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_or_impl(context, builder, sig, args): + [at, bt] = sig.args + [av, bv] = args + cav = context.cast(builder, av, at, sig.return_type) + cbc = context.cast(builder, bv, bt, sig.return_type) + res = builder.or_(cav, cbc) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_xor_impl(context, builder, sig, args): + [at, bt] = sig.args + [av, bv] = args + cav = context.cast(builder, av, at, sig.return_type) + cbc = context.cast(builder, bv, bt, sig.return_type) + res = builder.xor(cav, cbc) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_negate_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + # Negate before upcasting, for unsigned numbers + res = builder.neg(val) + res = context.cast(builder, res, typ, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_positive_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + res = context.cast(builder, val, typ, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_invert_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + # Invert before upcasting, for unsigned numbers + res = builder.xor(val, Constant(val.type, int('1' * val.type.width, 2))) + res = context.cast(builder, res, typ, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def int_sign_impl(context, builder, sig, args): + """ + np.sign(int) + """ + [x] = args + POS = Constant(x.type, 1) + NEG = Constant(x.type, -1) + ZERO = Constant(x.type, 0) + + cmp_zero = builder.icmp_unsigned('==', x, ZERO) + cmp_pos = builder.icmp_signed('>', x, ZERO) + + presult = cgutils.alloca_once(builder, x.type) + + bb_zero = builder.append_basic_block(".zero") + bb_postest = builder.append_basic_block(".postest") + bb_pos = builder.append_basic_block(".pos") + bb_neg = builder.append_basic_block(".neg") + bb_exit = builder.append_basic_block(".exit") + + builder.cbranch(cmp_zero, bb_zero, bb_postest) + + with builder.goto_block(bb_zero): + builder.store(ZERO, presult) + builder.branch(bb_exit) + + with builder.goto_block(bb_postest): + builder.cbranch(cmp_pos, bb_pos, bb_neg) + + with builder.goto_block(bb_pos): + builder.store(POS, presult) + builder.branch(bb_exit) + + with builder.goto_block(bb_neg): + builder.store(NEG, presult) + builder.branch(bb_exit) + + builder.position_at_end(bb_exit) + res = builder.load(presult) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def bool_negate_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + res = context.cast(builder, val, typ, sig.return_type) + res = builder.neg(res) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def bool_unary_positive_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + res = context.cast(builder, val, typ, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +lower_builtin(operator.eq, types.boolean, types.boolean)(int_eq_impl) +lower_builtin(operator.ne, types.boolean, types.boolean)(int_ne_impl) +lower_builtin(operator.lt, types.boolean, types.boolean)(int_ult_impl) +lower_builtin(operator.le, types.boolean, types.boolean)(int_ule_impl) +lower_builtin(operator.gt, types.boolean, types.boolean)(int_ugt_impl) +lower_builtin(operator.ge, types.boolean, types.boolean)(int_uge_impl) +lower_builtin(operator.neg, types.boolean)(bool_negate_impl) +lower_builtin(operator.pos, types.boolean)(bool_unary_positive_impl) + + +def _implement_integer_operators(): + ty = types.Integer + + lower_builtin(operator.add, ty, ty)(int_add_impl) + lower_builtin(operator.iadd, ty, ty)(int_add_impl) + lower_builtin(operator.sub, ty, ty)(int_sub_impl) + lower_builtin(operator.isub, ty, ty)(int_sub_impl) + lower_builtin(operator.mul, ty, ty)(int_mul_impl) + lower_builtin(operator.imul, ty, ty)(int_mul_impl) + lower_builtin(operator.eq, ty, ty)(int_eq_impl) + lower_builtin(operator.ne, ty, ty)(int_ne_impl) + + lower_builtin(operator.lshift, ty, ty)(int_shl_impl) + lower_builtin(operator.ilshift, ty, ty)(int_shl_impl) + lower_builtin(operator.rshift, ty, ty)(int_shr_impl) + lower_builtin(operator.irshift, ty, ty)(int_shr_impl) + + lower_builtin(operator.neg, ty)(int_negate_impl) + lower_builtin(operator.pos, ty)(int_positive_impl) + + lower_builtin(operator.pow, ty, ty)(int_power_impl) + lower_builtin(operator.ipow, ty, ty)(int_power_impl) + lower_builtin(pow, ty, ty)(int_power_impl) + + for ty in types.unsigned_domain: + lower_builtin(operator.lt, ty, ty)(int_ult_impl) + lower_builtin(operator.le, ty, ty)(int_ule_impl) + lower_builtin(operator.gt, ty, ty)(int_ugt_impl) + lower_builtin(operator.ge, ty, ty)(int_uge_impl) + lower_builtin(operator.pow, types.Float, ty)(int_power_impl) + lower_builtin(operator.ipow, types.Float, ty)(int_power_impl) + lower_builtin(pow, types.Float, ty)(int_power_impl) + lower_builtin(abs, ty)(uint_abs_impl) + + lower_builtin(operator.lt, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl) + lower_builtin(operator.gt, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl) + lower_builtin(operator.le, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl) + lower_builtin(operator.ge, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl) + for ty in types.signed_domain: + lower_builtin(operator.lt, ty, ty)(int_slt_impl) + lower_builtin(operator.le, ty, ty)(int_sle_impl) + lower_builtin(operator.gt, ty, ty)(int_sgt_impl) + lower_builtin(operator.ge, ty, ty)(int_sge_impl) + lower_builtin(operator.pow, types.Float, ty)(int_power_impl) + lower_builtin(operator.ipow, types.Float, ty)(int_power_impl) + lower_builtin(pow, types.Float, ty)(int_power_impl) + lower_builtin(abs, ty)(int_abs_impl) + +def _implement_bitwise_operators(): + for ty in (types.Boolean, types.Integer): + lower_builtin(operator.and_, ty, ty)(int_and_impl) + lower_builtin(operator.iand, ty, ty)(int_and_impl) + lower_builtin(operator.or_, ty, ty)(int_or_impl) + lower_builtin(operator.ior, ty, ty)(int_or_impl) + lower_builtin(operator.xor, ty, ty)(int_xor_impl) + lower_builtin(operator.ixor, ty, ty)(int_xor_impl) + + lower_builtin(operator.invert, ty)(int_invert_impl) + +_implement_integer_operators() + +_implement_bitwise_operators() + + +def real_add_impl(context, builder, sig, args): + res = builder.fadd(*args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_sub_impl(context, builder, sig, args): + res = builder.fsub(*args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_mul_impl(context, builder, sig, args): + res = builder.fmul(*args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_div_impl(context, builder, sig, args): + with cgutils.if_zero(builder, args[1]): + context.error_model.fp_zero_division(builder, ("division by zero",)) + res = builder.fdiv(*args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_divmod(context, builder, x, y): + assert x.type == y.type + floatty = x.type + + module = builder.module + fname = context.mangler(".numba.python.rem", [x.type]) + fnty = ir.FunctionType(floatty, (floatty, floatty, ir.PointerType(floatty))) + fn = cgutils.get_or_insert_function(module, fnty, fname) + + if fn.is_declaration: + fn.linkage = 'linkonce_odr' + fnbuilder = ir.IRBuilder(fn.append_basic_block('entry')) + fx, fy, pmod = fn.args + div, mod = real_divmod_func_body(context, fnbuilder, fx, fy) + fnbuilder.store(mod, pmod) + fnbuilder.ret(div) + + pmod = cgutils.alloca_once(builder, floatty) + quotient = builder.call(fn, (x, y, pmod)) + return quotient, builder.load(pmod) + + +def real_divmod_func_body(context, builder, vx, wx): + # Reference Objects/floatobject.c + # + # float_divmod(PyObject *v, PyObject *w) + # { + # double vx, wx; + # double div, mod, floordiv; + # CONVERT_TO_DOUBLE(v, vx); + # CONVERT_TO_DOUBLE(w, wx); + # mod = fmod(vx, wx); + # /* fmod is typically exact, so vx-mod is *mathematically* an + # exact multiple of wx. But this is fp arithmetic, and fp + # vx - mod is an approximation; the result is that div may + # not be an exact integral value after the division, although + # it will always be very close to one. + # */ + # div = (vx - mod) / wx; + # if (mod) { + # /* ensure the remainder has the same sign as the denominator */ + # if ((wx < 0) != (mod < 0)) { + # mod += wx; + # div -= 1.0; + # } + # } + # else { + # /* the remainder is zero, and in the presence of signed zeroes + # fmod returns different results across platforms; ensure + # it has the same sign as the denominator; we'd like to do + # "mod = wx * 0.0", but that may get optimized away */ + # mod *= mod; /* hide "mod = +0" from optimizer */ + # if (wx < 0.0) + # mod = -mod; + # } + # /* snap quotient to nearest integral value */ + # if (div) { + # floordiv = floor(div); + # if (div - floordiv > 0.5) + # floordiv += 1.0; + # } + # else { + # /* div is zero - get the same sign as the true quotient */ + # div *= div; /* hide "div = +0" from optimizers */ + # floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ + # } + # return Py_BuildValue("(dd)", floordiv, mod); + # } + pmod = cgutils.alloca_once(builder, vx.type) + pdiv = cgutils.alloca_once(builder, vx.type) + pfloordiv = cgutils.alloca_once(builder, vx.type) + + mod = builder.frem(vx, wx) + div = builder.fdiv(builder.fsub(vx, mod), wx) + + builder.store(mod, pmod) + builder.store(div, pdiv) + + # Note the use of negative zero for proper negating with `ZERO - x` + ZERO = vx.type(0.0) + NZERO = vx.type(-0.0) + ONE = vx.type(1.0) + mod_istrue = builder.fcmp_unordered('!=', mod, ZERO) + wx_ltz = builder.fcmp_ordered('<', wx, ZERO) + mod_ltz = builder.fcmp_ordered('<', mod, ZERO) + + with builder.if_else(mod_istrue, likely=True) as (if_nonzero_mod, if_zero_mod): + with if_nonzero_mod: + # `mod` is non-zero or NaN + # Ensure the remainder has the same sign as the denominator + wx_ltz_ne_mod_ltz = builder.icmp_unsigned('!=', wx_ltz, mod_ltz) + + with builder.if_then(wx_ltz_ne_mod_ltz): + builder.store(builder.fsub(div, ONE), pdiv) + builder.store(builder.fadd(mod, wx), pmod) + + with if_zero_mod: + # `mod` is zero, select the proper sign depending on + # the denominator's sign + mod = builder.select(wx_ltz, NZERO, ZERO) + builder.store(mod, pmod) + + del mod, div + + div = builder.load(pdiv) + div_istrue = builder.fcmp_ordered('!=', div, ZERO) + + with builder.if_then(div_istrue): + realtypemap = {'float': types.float32, + 'double': types.float64} + realtype = realtypemap[str(wx.type)] + floorfn = context.get_function(math.floor, + typing.signature(realtype, realtype)) + floordiv = floorfn(builder, [div]) + floordivdiff = builder.fsub(div, floordiv) + floordivincr = builder.fadd(floordiv, ONE) + HALF = Constant(wx.type, 0.5) + pred = builder.fcmp_ordered('>', floordivdiff, HALF) + floordiv = builder.select(pred, floordivincr, floordiv) + builder.store(floordiv, pfloordiv) + + with cgutils.ifnot(builder, div_istrue): + div = builder.fmul(div, div) + builder.store(div, pdiv) + floordiv = builder.fdiv(builder.fmul(div, vx), wx) + builder.store(floordiv, pfloordiv) + + return builder.load(pfloordiv), builder.load(pmod) + + +@lower_builtin(divmod, types.Float, types.Float) +def real_divmod_impl(context, builder, sig, args, loc=None): + x, y = args + quot = cgutils.alloca_once(builder, x.type, name="quot") + rem = cgutils.alloca_once(builder, x.type, name="rem") + + with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False + ) as (if_zero, if_non_zero): + with if_zero: + if not context.error_model.fp_zero_division( + builder, ("modulo by zero",), loc): + # No exception raised => compute the nan result, + # and set the FP exception word for Numpy warnings. + q = builder.fdiv(x, y) + r = builder.frem(x, y) + builder.store(q, quot) + builder.store(r, rem) + with if_non_zero: + q, r = real_divmod(context, builder, x, y) + builder.store(q, quot) + builder.store(r, rem) + + return cgutils.pack_array(builder, + (builder.load(quot), builder.load(rem))) + + +def real_mod_impl(context, builder, sig, args, loc=None): + x, y = args + res = cgutils.alloca_once(builder, x.type) + with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False + ) as (if_zero, if_non_zero): + with if_zero: + if not context.error_model.fp_zero_division( + builder, ("modulo by zero",), loc): + # No exception raised => compute the nan result, + # and set the FP exception word for Numpy warnings. + rem = builder.frem(x, y) + builder.store(rem, res) + with if_non_zero: + _, rem = real_divmod(context, builder, x, y) + builder.store(rem, res) + return impl_ret_untracked(context, builder, sig.return_type, + builder.load(res)) + + +def real_floordiv_impl(context, builder, sig, args, loc=None): + x, y = args + res = cgutils.alloca_once(builder, x.type) + with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False + ) as (if_zero, if_non_zero): + with if_zero: + if not context.error_model.fp_zero_division( + builder, ("division by zero",), loc): + # No exception raised => compute the +/-inf or nan result, + # and set the FP exception word for Numpy warnings. + quot = builder.fdiv(x, y) + builder.store(quot, res) + with if_non_zero: + quot, _ = real_divmod(context, builder, x, y) + builder.store(quot, res) + return impl_ret_untracked(context, builder, sig.return_type, + builder.load(res)) + + +def real_power_impl(context, builder, sig, args): + x, y = args + module = builder.module + if context.implement_powi_as_math_call: + imp = context.get_function(math.pow, sig) + res = imp(builder, args) + else: + fn = module.declare_intrinsic('llvm.pow', [y.type]) + res = builder.call(fn, (x, y)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_lt_impl(context, builder, sig, args): + res = builder.fcmp_ordered('<', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_le_impl(context, builder, sig, args): + res = builder.fcmp_ordered('<=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_gt_impl(context, builder, sig, args): + res = builder.fcmp_ordered('>', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_ge_impl(context, builder, sig, args): + res = builder.fcmp_ordered('>=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_eq_impl(context, builder, sig, args): + res = builder.fcmp_ordered('==', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_ne_impl(context, builder, sig, args): + res = builder.fcmp_unordered('!=', *args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_abs_impl(context, builder, sig, args): + [ty] = sig.args + sig = typing.signature(ty, ty) + impl = context.get_function(math.fabs, sig) + return impl(builder, args) + + +def real_negate_impl(context, builder, sig, args): + from numba.cpython import mathimpl + res = mathimpl.negate_real(builder, args[0]) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_positive_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + res = context.cast(builder, val, typ, sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def real_sign_impl(context, builder, sig, args): + """ + np.sign(float) + """ + [x] = args + POS = Constant(x.type, 1) + NEG = Constant(x.type, -1) + ZERO = Constant(x.type, 0) + + presult = cgutils.alloca_once(builder, x.type) + + is_pos = builder.fcmp_ordered('>', x, ZERO) + is_neg = builder.fcmp_ordered('<', x, ZERO) + + with builder.if_else(is_pos) as (gt_zero, not_gt_zero): + with gt_zero: + builder.store(POS, presult) + with not_gt_zero: + with builder.if_else(is_neg) as (lt_zero, not_lt_zero): + with lt_zero: + builder.store(NEG, presult) + with not_lt_zero: + # For both NaN and 0, the result of sign() is simply + # the input value. + builder.store(x, presult) + + res = builder.load(presult) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +ty = types.Float + +lower_builtin(operator.add, ty, ty)(real_add_impl) +lower_builtin(operator.iadd, ty, ty)(real_add_impl) +lower_builtin(operator.sub, ty, ty)(real_sub_impl) +lower_builtin(operator.isub, ty, ty)(real_sub_impl) +lower_builtin(operator.mul, ty, ty)(real_mul_impl) +lower_builtin(operator.imul, ty, ty)(real_mul_impl) +lower_builtin(operator.floordiv, ty, ty)(real_floordiv_impl) +lower_builtin(operator.ifloordiv, ty, ty)(real_floordiv_impl) +lower_builtin(operator.truediv, ty, ty)(real_div_impl) +lower_builtin(operator.itruediv, ty, ty)(real_div_impl) +lower_builtin(operator.mod, ty, ty)(real_mod_impl) +lower_builtin(operator.imod, ty, ty)(real_mod_impl) +lower_builtin(operator.pow, ty, ty)(real_power_impl) +lower_builtin(operator.ipow, ty, ty)(real_power_impl) +lower_builtin(pow, ty, ty)(real_power_impl) + +lower_builtin(operator.eq, ty, ty)(real_eq_impl) +lower_builtin(operator.ne, ty, ty)(real_ne_impl) +lower_builtin(operator.lt, ty, ty)(real_lt_impl) +lower_builtin(operator.le, ty, ty)(real_le_impl) +lower_builtin(operator.gt, ty, ty)(real_gt_impl) +lower_builtin(operator.ge, ty, ty)(real_ge_impl) + +lower_builtin(abs, ty)(real_abs_impl) + +lower_builtin(operator.neg, ty)(real_negate_impl) +lower_builtin(operator.pos, ty)(real_positive_impl) + +del ty + + +@lower_getattr(types.Complex, "real") +def complex_real_impl(context, builder, typ, value): + cplx = context.make_complex(builder, typ, value=value) + res = cplx.real + return impl_ret_untracked(context, builder, typ, res) + +@lower_getattr(types.Complex, "imag") +def complex_imag_impl(context, builder, typ, value): + cplx = context.make_complex(builder, typ, value=value) + res = cplx.imag + return impl_ret_untracked(context, builder, typ, res) + +@lower_builtin("complex.conjugate", types.Complex) +def complex_conjugate_impl(context, builder, sig, args): + from numba.cpython import mathimpl + z = context.make_complex(builder, sig.args[0], args[0]) + z.imag = mathimpl.negate_real(builder, z.imag) + res = z._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + +def real_real_impl(context, builder, typ, value): + return impl_ret_untracked(context, builder, typ, value) + +def real_imag_impl(context, builder, typ, value): + res = cgutils.get_null_value(value.type) + return impl_ret_untracked(context, builder, typ, res) + +def real_conjugate_impl(context, builder, sig, args): + return impl_ret_untracked(context, builder, sig.return_type, args[0]) + +for cls in (types.Float, types.Integer): + lower_getattr(cls, "real")(real_real_impl) + lower_getattr(cls, "imag")(real_imag_impl) + lower_builtin("complex.conjugate", cls)(real_conjugate_impl) + + +@lower_builtin(operator.pow, types.Complex, types.Complex) +@lower_builtin(operator.ipow, types.Complex, types.Complex) +@lower_builtin(pow, types.Complex, types.Complex) +def complex_power_impl(context, builder, sig, args): + [ca, cb] = args + ty = sig.args[0] + fty = ty.underlying_float + a = context.make_helper(builder, ty, value=ca) + b = context.make_helper(builder, ty, value=cb) + c = context.make_helper(builder, ty) + module = builder.module + pa = a._getpointer() + pb = b._getpointer() + pc = c._getpointer() + + # Optimize for square because cpow loses a lot of precision + TWO = context.get_constant(fty, 2) + ZERO = context.get_constant(fty, 0) + + b_real_is_two = builder.fcmp_ordered('==', b.real, TWO) + b_imag_is_zero = builder.fcmp_ordered('==', b.imag, ZERO) + b_is_two = builder.and_(b_real_is_two, b_imag_is_zero) + + with builder.if_else(b_is_two) as (then, otherwise): + with then: + # Lower as multiplication + res = complex_mul_impl(context, builder, sig, (ca, ca)) + cres = context.make_helper(builder, ty, value=res) + c.real = cres.real + c.imag = cres.imag + + with otherwise: + # Lower with call to external function + func_name = { + types.complex64: "numba_cpowf", + types.complex128: "numba_cpow", + }[ty] + fnty = ir.FunctionType(ir.VoidType(), [pa.type] * 3) + cpow = cgutils.get_or_insert_function(module, fnty, func_name) + builder.call(cpow, (pa, pb, pc)) + + res = builder.load(pc) + return impl_ret_untracked(context, builder, sig.return_type, res) + +def complex_add_impl(context, builder, sig, args): + [cx, cy] = args + ty = sig.args[0] + x = context.make_complex(builder, ty, value=cx) + y = context.make_complex(builder, ty, value=cy) + z = context.make_complex(builder, ty) + a = x.real + b = x.imag + c = y.real + d = y.imag + z.real = builder.fadd(a, c) + z.imag = builder.fadd(b, d) + res = z._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_sub_impl(context, builder, sig, args): + [cx, cy] = args + ty = sig.args[0] + x = context.make_complex(builder, ty, value=cx) + y = context.make_complex(builder, ty, value=cy) + z = context.make_complex(builder, ty) + a = x.real + b = x.imag + c = y.real + d = y.imag + z.real = builder.fsub(a, c) + z.imag = builder.fsub(b, d) + res = z._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_mul_impl(context, builder, sig, args): + """ + (a+bi)(c+di)=(ac-bd)+i(ad+bc) + """ + [cx, cy] = args + ty = sig.args[0] + x = context.make_complex(builder, ty, value=cx) + y = context.make_complex(builder, ty, value=cy) + z = context.make_complex(builder, ty) + a = x.real + b = x.imag + c = y.real + d = y.imag + ac = builder.fmul(a, c) + bd = builder.fmul(b, d) + ad = builder.fmul(a, d) + bc = builder.fmul(b, c) + z.real = builder.fsub(ac, bd) + z.imag = builder.fadd(ad, bc) + res = z._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +NAN = float('nan') + +def complex_div_impl(context, builder, sig, args): + def complex_div(a, b): + # This is CPython's algorithm (in _Py_c_quot()). + areal = a.real + aimag = a.imag + breal = b.real + bimag = b.imag + if not breal and not bimag: + raise ZeroDivisionError("complex division by zero") + if abs(breal) >= abs(bimag): + # Divide tops and bottom by b.real + if not breal: + return complex(NAN, NAN) + ratio = bimag / breal + denom = breal + bimag * ratio + return complex( + (areal + aimag * ratio) / denom, + (aimag - areal * ratio) / denom) + else: + # Divide tops and bottom by b.imag + if not bimag: + return complex(NAN, NAN) + ratio = breal / bimag + denom = breal * ratio + bimag + return complex( + (a.real * ratio + a.imag) / denom, + (a.imag * ratio - a.real) / denom) + + res = context.compile_internal(builder, complex_div, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_negate_impl(context, builder, sig, args): + from numba.cpython import mathimpl + [typ] = sig.args + [val] = args + cmplx = context.make_complex(builder, typ, value=val) + res = context.make_complex(builder, typ) + res.real = mathimpl.negate_real(builder, cmplx.real) + res.imag = mathimpl.negate_real(builder, cmplx.imag) + res = res._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_positive_impl(context, builder, sig, args): + [val] = args + return impl_ret_untracked(context, builder, sig.return_type, val) + + +def complex_eq_impl(context, builder, sig, args): + [cx, cy] = args + typ = sig.args[0] + x = context.make_complex(builder, typ, value=cx) + y = context.make_complex(builder, typ, value=cy) + + reals_are_eq = builder.fcmp_ordered('==', x.real, y.real) + imags_are_eq = builder.fcmp_ordered('==', x.imag, y.imag) + res = builder.and_(reals_are_eq, imags_are_eq) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_ne_impl(context, builder, sig, args): + [cx, cy] = args + typ = sig.args[0] + x = context.make_complex(builder, typ, value=cx) + y = context.make_complex(builder, typ, value=cy) + + reals_are_ne = builder.fcmp_unordered('!=', x.real, y.real) + imags_are_ne = builder.fcmp_unordered('!=', x.imag, y.imag) + res = builder.or_(reals_are_ne, imags_are_ne) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def complex_abs_impl(context, builder, sig, args): + """ + abs(z) := hypot(z.real, z.imag) + """ + def complex_abs(z): + return math.hypot(z.real, z.imag) + + res = context.compile_internal(builder, complex_abs, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +ty = types.Complex + +lower_builtin(operator.add, ty, ty)(complex_add_impl) +lower_builtin(operator.iadd, ty, ty)(complex_add_impl) +lower_builtin(operator.sub, ty, ty)(complex_sub_impl) +lower_builtin(operator.isub, ty, ty)(complex_sub_impl) +lower_builtin(operator.mul, ty, ty)(complex_mul_impl) +lower_builtin(operator.imul, ty, ty)(complex_mul_impl) +lower_builtin(operator.truediv, ty, ty)(complex_div_impl) +lower_builtin(operator.itruediv, ty, ty)(complex_div_impl) +lower_builtin(operator.neg, ty)(complex_negate_impl) +lower_builtin(operator.pos, ty)(complex_positive_impl) +# Complex modulo is deprecated in python3 + +lower_builtin(operator.eq, ty, ty)(complex_eq_impl) +lower_builtin(operator.ne, ty, ty)(complex_ne_impl) + +lower_builtin(abs, ty)(complex_abs_impl) + +del ty + + +@lower_builtin("number.item", types.Boolean) +@lower_builtin("number.item", types.Number) +def number_item_impl(context, builder, sig, args): + """ + The no-op .item() method on booleans and numbers. + """ + return args[0] + + +#------------------------------------------------------------------------------ + + +def number_not_impl(context, builder, sig, args): + [typ] = sig.args + [val] = args + istrue = context.cast(builder, val, typ, sig.return_type) + res = builder.not_(istrue) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(bool, types.Boolean) +def bool_as_bool(context, builder, sig, args): + [val] = args + return val + +@lower_builtin(bool, types.Integer) +def int_as_bool(context, builder, sig, args): + [val] = args + return builder.icmp_unsigned('!=', val, Constant(val.type, 0)) + +@lower_builtin(bool, types.Float) +def float_as_bool(context, builder, sig, args): + [val] = args + return builder.fcmp_unordered('!=', val, Constant(val.type, 0.0)) + +@lower_builtin(bool, types.Complex) +def complex_as_bool(context, builder, sig, args): + [typ] = sig.args + [val] = args + cmplx = context.make_complex(builder, typ, val) + real, imag = cmplx.real, cmplx.imag + zero = Constant(real.type, 0.0) + real_istrue = builder.fcmp_unordered('!=', real, zero) + imag_istrue = builder.fcmp_unordered('!=', imag, zero) + return builder.or_(real_istrue, imag_istrue) + + +for ty in (types.Integer, types.Float, types.Complex): + lower_builtin(operator.not_, ty)(number_not_impl) + +lower_builtin(operator.not_, types.boolean)(number_not_impl) + + +#------------------------------------------------------------------------------ +# Hashing numbers, see hashing.py + +#------------------------------------------------------------------------------- +# Implicit casts between numerics + +@lower_cast(types.IntegerLiteral, types.Integer) +@lower_cast(types.IntegerLiteral, types.Float) +@lower_cast(types.IntegerLiteral, types.Complex) +def literal_int_to_number(context, builder, fromty, toty, val): + lit = context.get_constant_generic( + builder, + fromty.literal_type, + fromty.literal_value, + ) + return context.cast(builder, lit, fromty.literal_type, toty) + + +@lower_cast(types.Integer, types.Integer) +def integer_to_integer(context, builder, fromty, toty, val): + if toty.bitwidth == fromty.bitwidth: + # Just a change of signedness + return val + elif toty.bitwidth < fromty.bitwidth: + # Downcast + return builder.trunc(val, context.get_value_type(toty)) + elif fromty.signed: + # Signed upcast + return builder.sext(val, context.get_value_type(toty)) + else: + # Unsigned upcast + return builder.zext(val, context.get_value_type(toty)) + +@lower_cast(types.Integer, types.voidptr) +def integer_to_voidptr(context, builder, fromty, toty, val): + return builder.inttoptr(val, context.get_value_type(toty)) + +@lower_cast(types.Float, types.Float) +def float_to_float(context, builder, fromty, toty, val): + lty = context.get_value_type(toty) + if fromty.bitwidth < toty.bitwidth: + return builder.fpext(val, lty) + else: + return builder.fptrunc(val, lty) + +@lower_cast(types.Integer, types.Float) +def integer_to_float(context, builder, fromty, toty, val): + lty = context.get_value_type(toty) + if fromty.signed: + return builder.sitofp(val, lty) + else: + return builder.uitofp(val, lty) + +@lower_cast(types.Float, types.Integer) +def float_to_integer(context, builder, fromty, toty, val): + lty = context.get_value_type(toty) + if toty.signed: + return builder.fptosi(val, lty) + else: + return builder.fptoui(val, lty) + +@lower_cast(types.Float, types.Complex) +@lower_cast(types.Integer, types.Complex) +def non_complex_to_complex(context, builder, fromty, toty, val): + real = context.cast(builder, val, fromty, toty.underlying_float) + imag = context.get_constant(toty.underlying_float, 0) + + cmplx = context.make_complex(builder, toty) + cmplx.real = real + cmplx.imag = imag + return cmplx._getvalue() + +@lower_cast(types.Complex, types.Complex) +def complex_to_complex(context, builder, fromty, toty, val): + srcty = fromty.underlying_float + dstty = toty.underlying_float + + src = context.make_complex(builder, fromty, value=val) + dst = context.make_complex(builder, toty) + dst.real = context.cast(builder, src.real, srcty, dstty) + dst.imag = context.cast(builder, src.imag, srcty, dstty) + return dst._getvalue() + +@lower_cast(types.Any, types.Boolean) +def any_to_boolean(context, builder, fromty, toty, val): + return context.is_true(builder, fromty, val) + +@lower_cast(types.Boolean, types.Number) +def boolean_to_any(context, builder, fromty, toty, val): + # Casting from boolean to anything first casts to int32 + asint = builder.zext(val, ir.IntType(32)) + return context.cast(builder, asint, types.int32, toty) + +@lower_cast(types.IntegerLiteral, types.Boolean) +@lower_cast(types.BooleanLiteral, types.Boolean) +def literal_int_to_boolean(context, builder, fromty, toty, val): + lit = context.get_constant_generic( + builder, + fromty.literal_type, + fromty.literal_value, + ) + return context.is_true(builder, fromty.literal_type, lit) + +#------------------------------------------------------------------------------- +# Constants + +@lower_constant(types.Complex) +def constant_complex(context, builder, ty, pyval): + fty = ty.underlying_float + real = context.get_constant_generic(builder, fty, pyval.real) + imag = context.get_constant_generic(builder, fty, pyval.imag) + return Constant.literal_struct((real, imag)) + +@lower_constant(types.Integer) +@lower_constant(types.Float) +@lower_constant(types.Boolean) +def constant_integer(context, builder, ty, pyval): + # See https://github.com/numba/numba/issues/6979 + # llvmlite ir.IntType specialises the formatting of the constant for a + # cpython bool. A NumPy np.bool_ is not a cpython bool so force it to be one + # so that the constant renders correctly! + if isinstance(pyval, np.bool_): + pyval = bool(pyval) + lty = context.get_value_type(ty) + return lty(pyval) + + +#------------------------------------------------------------------------------- +# View + +def scalar_view(scalar, viewty): + """ Typing for the np scalar 'view' method. """ + if (isinstance(scalar, (types.Float, types.Integer)) + and isinstance(viewty, types.abstract.DTypeSpec)): + if scalar.bitwidth != viewty.dtype.bitwidth: + raise errors.TypingError( + "Changing the dtype of a 0d array is only supported if the " + "itemsize is unchanged") + + def impl(scalar, viewty): + return viewer(scalar, viewty) + return impl + + +overload_method(types.Float, 'view')(scalar_view) +overload_method(types.Integer, 'view')(scalar_view) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/printimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/printimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce54004cf1ae3d62f2342c1c6d460c234e45274 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/printimpl.py @@ -0,0 +1,82 @@ +""" +This file implements print functionality for the CPU. +""" +from numba.core import types, typing, cgutils +from numba.core.imputils import Registry, impl_ret_untracked + +registry = Registry('printimpl') +lower = registry.lower + + +# NOTE: the current implementation relies on CPython API even in +# nopython mode. + + +@lower("print_item", types.Literal) +def print_item_impl(context, builder, sig, args): + """ + Print a single constant value. + """ + ty, = sig.args + val = ty.literal_value + + pyapi = context.get_python_api(builder) + + strobj = pyapi.unserialize(pyapi.serialize_object(val)) + pyapi.print_object(strobj) + pyapi.decref(strobj) + + res = context.get_dummy_value() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower("print_item", types.Any) +def print_item_impl(context, builder, sig, args): + """ + Print a single native value by boxing it in a Python object and + invoking the Python interpreter's print routine. + """ + ty, = sig.args + val, = args + + pyapi = context.get_python_api(builder) + env_manager = context.get_env_manager(builder) + + if context.enable_nrt: + context.nrt.incref(builder, ty, val) + + obj = pyapi.from_native_value(ty, val, env_manager) + with builder.if_else(cgutils.is_not_null(builder, obj), likely=True) as (if_ok, if_error): + with if_ok: + pyapi.print_object(obj) + pyapi.decref(obj) + with if_error: + cstr = context.insert_const_string(builder.module, + "the print() function") + strobj = pyapi.string_from_string(cstr) + pyapi.err_write_unraisable(strobj) + pyapi.decref(strobj) + + res = context.get_dummy_value() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower(print, types.VarArg(types.Any)) +def print_varargs_impl(context, builder, sig, args): + """ + A entire print() call. + """ + pyapi = context.get_python_api(builder) + gil = pyapi.gil_ensure() + + for i, (argtype, argval) in enumerate(zip(sig.args, args)): + signature = typing.signature(types.none, argtype) + imp = context.get_function("print_item", signature) + imp(builder, [argval]) + if i < len(args) - 1: + pyapi.print_string(' ') + pyapi.print_string('\n') + + pyapi.gil_release(gil) + res = context.get_dummy_value() + return impl_ret_untracked(context, builder, sig.return_type, res) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/randomimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/randomimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..e55e14682fcb3192fcc822c4d25c182f295d4ee2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/randomimpl.py @@ -0,0 +1,2335 @@ +""" +Implement the random and np.random module functions. +""" + + +import math +import random + +import numpy as np + +from llvmlite import ir + +from numba.core.cgutils import is_nonelike, is_empty_tuple +from numba.core.extending import intrinsic, overload, register_jitable +from numba.core.imputils import Registry +from numba.core.typing import signature +from numba.core import types, cgutils +from numba.core.errors import NumbaTypeError +from numba.np.random._constants import LONG_MAX + +registry = Registry('randomimpl') +lower = registry.lower + +int32_t = ir.IntType(32) +int64_t = ir.IntType(64) +def const_int(x): + return ir.Constant(int32_t, x) +double = ir.DoubleType() + +N = 624 +N_const = ir.Constant(int32_t, N) + + +# This is the same struct as rnd_state_t in _random.c. +rnd_state_t = ir.LiteralStructType([ + # index + int32_t, + # mt[N] + ir.ArrayType(int32_t, N), + # has_gauss + int32_t, + # gauss + double, + # is_initialized + int32_t, + ]) +rnd_state_ptr_t = ir.PointerType(rnd_state_t) + + +def get_state_ptr(context, builder, name): + """ + Get a pointer to the given thread-local random state + (depending on *name*: "py" or "np"). + If the state isn't initialized, it is lazily initialized with + system entropy. + """ + assert name in ('py', 'np', 'internal') + func_name = "numba_get_%s_random_state" % name + fnty = ir.FunctionType(rnd_state_ptr_t, ()) + fn = cgutils.get_or_insert_function(builder.module, fnty, func_name) + # These two attributes allow LLVM to hoist the function call + # outside of loops. + fn.attributes.add('readnone') + fn.attributes.add('nounwind') + return builder.call(fn, ()) + +def get_py_state_ptr(context, builder): + """ + Get a pointer to the thread-local Python random state. + """ + return get_state_ptr(context, builder, 'py') + +def get_np_state_ptr(context, builder): + """ + Get a pointer to the thread-local Numpy random state. + """ + return get_state_ptr(context, builder, 'np') + +def get_internal_state_ptr(context, builder): + """ + Get a pointer to the thread-local internal random state. + """ + return get_state_ptr(context, builder, 'internal') + +# Accessors +def get_index_ptr(builder, state_ptr): + return cgutils.gep_inbounds(builder, state_ptr, 0, 0) + +def get_array_ptr(builder, state_ptr): + return cgutils.gep_inbounds(builder, state_ptr, 0, 1) + +def get_has_gauss_ptr(builder, state_ptr): + return cgutils.gep_inbounds(builder, state_ptr, 0, 2) + +def get_gauss_ptr(builder, state_ptr): + return cgutils.gep_inbounds(builder, state_ptr, 0, 3) + +def get_rnd_shuffle(builder): + """ + Get the internal function to shuffle the MT taste. + """ + fnty = ir.FunctionType(ir.VoidType(), (rnd_state_ptr_t,)) + fn = cgutils.get_or_insert_function(builder.function.module, fnty, + "numba_rnd_shuffle") + fn.args[0].add_attribute("nocapture") + return fn + + +def get_next_int32(context, builder, state_ptr): + """ + Get the next int32 generated by the PRNG at *state_ptr*. + """ + idxptr = get_index_ptr(builder, state_ptr) + idx = builder.load(idxptr) + need_reshuffle = builder.icmp_unsigned('>=', idx, N_const) + with cgutils.if_unlikely(builder, need_reshuffle): + fn = get_rnd_shuffle(builder) + builder.call(fn, (state_ptr,)) + builder.store(const_int(0), idxptr) + idx = builder.load(idxptr) + array_ptr = get_array_ptr(builder, state_ptr) + y = builder.load(cgutils.gep_inbounds(builder, array_ptr, 0, idx)) + idx = builder.add(idx, const_int(1)) + builder.store(idx, idxptr) + # Tempering + y = builder.xor(y, builder.lshr(y, const_int(11))) + y = builder.xor(y, builder.and_(builder.shl(y, const_int(7)), + const_int(0x9d2c5680))) + y = builder.xor(y, builder.and_(builder.shl(y, const_int(15)), + const_int(0xefc60000))) + y = builder.xor(y, builder.lshr(y, const_int(18))) + return y + +def get_next_double(context, builder, state_ptr): + """ + Get the next double generated by the PRNG at *state_ptr*. + """ + # a = rk_random(state) >> 5, b = rk_random(state) >> 6; + a = builder.lshr(get_next_int32(context, builder, state_ptr), const_int(5)) + b = builder.lshr(get_next_int32(context, builder, state_ptr), const_int(6)) + + # return (a * 67108864.0 + b) / 9007199254740992.0; + a = builder.uitofp(a, double) + b = builder.uitofp(b, double) + return builder.fdiv( + builder.fadd(b, builder.fmul(a, ir.Constant(double, 67108864.0))), + ir.Constant(double, 9007199254740992.0)) + +def get_next_int(context, builder, state_ptr, nbits, is_numpy): + """ + Get the next integer with width *nbits*. + """ + c32 = ir.Constant(nbits.type, 32) + def get_shifted_int(nbits): + shift = builder.sub(c32, nbits) + y = get_next_int32(context, builder, state_ptr) + + # This truncation/extension is safe because 0 < nbits <= 64 + if nbits.type.width < y.type.width: + shift = builder.zext(shift, y.type) + elif nbits.type.width > y.type.width: + shift = builder.trunc(shift, y.type) + + if is_numpy: + # Use the last N bits, to match np.random + mask = builder.not_(ir.Constant(y.type, 0)) + mask = builder.lshr(mask, shift) + return builder.and_(y, mask) + else: + # Use the first N bits, to match CPython random + return builder.lshr(y, shift) + + ret = cgutils.alloca_once_value(builder, ir.Constant(int64_t, 0)) + + is_32b = builder.icmp_unsigned('<=', nbits, c32) + with builder.if_else(is_32b) as (ifsmall, iflarge): + with ifsmall: + low = get_shifted_int(nbits) + builder.store(builder.zext(low, int64_t), ret) + with iflarge: + # XXX This assumes nbits <= 64 + if is_numpy: + # Get the high bits first to match np.random + high = get_shifted_int(builder.sub(nbits, c32)) + low = get_next_int32(context, builder, state_ptr) + if not is_numpy: + # Get the high bits second to match CPython random + high = get_shifted_int(builder.sub(nbits, c32)) + total = builder.add( + builder.zext(low, int64_t), + builder.shl(builder.zext(high, int64_t), + ir.Constant(int64_t, 32))) + builder.store(total, ret) + + return builder.load(ret) + + +@overload(random.seed) +def seed_impl(a): + if isinstance(a, types.Integer): + fn = register_jitable(_seed_impl('py')) + def impl(a): + return fn(a) + return impl + + +@overload(np.random.seed) +def seed_impl(seed): + if isinstance(seed, types.Integer): + return _seed_impl('np') + + +def _seed_impl(state_type): + @intrinsic + def _impl(typingcontext, seed): + def codegen(context, builder, sig, args): + seed_value, = args + fnty = ir.FunctionType(ir.VoidType(), (rnd_state_ptr_t, int32_t)) + fn = cgutils.get_or_insert_function(builder.function.module, fnty, + 'numba_rnd_init') + builder.call(fn, (get_state_ptr(context, builder, state_type), + seed_value)) + return context.get_constant(types.none, None) + return signature(types.void, types.uint32), codegen + return lambda seed: _impl(seed) + + +@overload(random.random) +def random_impl(): + @intrinsic + def _impl(typingcontext): + def codegen(context, builder, sig, args): + state_ptr = get_state_ptr(context, builder, "py") + return get_next_double(context, builder, state_ptr) + return signature(types.double), codegen + return lambda: _impl() + + +@overload(np.random.random) +@overload(np.random.random_sample) +@overload(np.random.sample) +@overload(np.random.ranf) +def random_impl0(): + @intrinsic + def _impl(typingcontext): + def codegen(context, builder, sig, args): + state_ptr = get_state_ptr(context, builder, "np") + return get_next_double(context, builder, state_ptr) + return signature(types.float64), codegen + return lambda: _impl() + + +@overload(np.random.random) +@overload(np.random.random_sample) +@overload(np.random.sample) +@overload(np.random.ranf) +def random_impl1(size=None): + if is_nonelike(size): + return lambda size=None: np.random.random() + if is_empty_tuple(size): + # Handle size = () + return lambda size=None: np.array(np.random.random()) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)): + def _impl(size=None): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.random() + return out + return _impl + + +@overload(random.gauss) +@overload(random.normalvariate) +def gauss_impl(mu, sigma): + if isinstance(mu, (types.Float, types.Integer)) and isinstance( + sigma, (types.Float, types.Integer)): + @intrinsic + def _impl(typingcontext, mu, sigma): + loc_preprocessor = _double_preprocessor(mu) + scale_preprocessor = _double_preprocessor(sigma) + return signature(types.float64, mu, sigma),\ + _gauss_impl("py", loc_preprocessor, scale_preprocessor) + return lambda mu, sigma: _impl(mu, sigma) + + +@overload(np.random.standard_normal) +@overload(np.random.normal) +def np_gauss_impl0(): + return lambda: np.random.normal(0.0, 1.0) + + +@overload(np.random.normal) +def np_gauss_impl1(loc): + if isinstance(loc, (types.Float, types.Integer)): + return lambda loc: np.random.normal(loc, 1.0) + + +@overload(np.random.normal) +def np_gauss_impl2(loc, scale): + if isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)): + @intrinsic + def _impl(typingcontext, loc, scale): + loc_preprocessor = _double_preprocessor(loc) + scale_preprocessor = _double_preprocessor(scale) + return signature(types.float64, loc, scale),\ + _gauss_impl("np", loc_preprocessor, scale_preprocessor) + return lambda loc, scale: _impl(loc, scale) + + +@overload(np.random.standard_normal) +def standard_normal_impl1(size): + if is_nonelike(size): + return lambda size: np.random.standard_normal() + if is_empty_tuple(size): + # Handle size = () + return lambda size: np.array(np.random.standard_normal()) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.standard_normal() + return out + return _impl + + +@overload(np.random.normal) +def np_gauss_impl3(loc, scale, size): + if (isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)) and + is_nonelike(size)): + return lambda loc, scale, size: np.random.normal(loc, scale) + if (isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)) and + is_empty_tuple(size)): + # Handle size = () + return lambda loc, scale, size: np.array(np.random.normal(loc, scale)) + if (isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)) and + (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)))): + def _impl(loc, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.normal(loc, scale) + return out + return _impl + + +def _gauss_pair_impl(_random): + def compute_gauss_pair(): + """ + Compute a pair of numbers on the normal distribution. + """ + while True: + x1 = 2.0 * _random() - 1.0 + x2 = 2.0 * _random() - 1.0 + r2 = x1*x1 + x2*x2 + if r2 < 1.0 and r2 != 0.0: + break + + # Box-Muller transform + f = math.sqrt(-2.0 * math.log(r2) / r2) + return f * x1, f * x2 + return compute_gauss_pair + + +def _gauss_impl(state, loc_preprocessor, scale_preprocessor): + def _impl(context, builder, sig, args): + # The type for all computations (either float or double) + ty = sig.return_type + llty = context.get_data_type(ty) + _random = {"py": random.random, + "np": np.random.random}[state] + + state_ptr = get_state_ptr(context, builder, state) + + ret = cgutils.alloca_once(builder, llty, name="result") + + gauss_ptr = get_gauss_ptr(builder, state_ptr) + has_gauss_ptr = get_has_gauss_ptr(builder, state_ptr) + has_gauss = cgutils.is_true(builder, builder.load(has_gauss_ptr)) + with builder.if_else(has_gauss) as (then, otherwise): + with then: + # if has_gauss: return it + builder.store(builder.load(gauss_ptr), ret) + builder.store(const_int(0), has_gauss_ptr) + with otherwise: + # if not has_gauss: compute a pair of numbers using the Box-Muller + # transform; keep one and return the other + pair = context.compile_internal(builder, + _gauss_pair_impl(_random), + signature(types.UniTuple(ty, 2)), + ()) + + first, second = cgutils.unpack_tuple(builder, pair, 2) + builder.store(first, gauss_ptr) + builder.store(second, ret) + builder.store(const_int(1), has_gauss_ptr) + + mu, sigma = args + return builder.fadd(loc_preprocessor(builder, mu), + builder.fmul(scale_preprocessor(builder, sigma), + builder.load(ret))) + return _impl + + +def _double_preprocessor(value): + ty = ir.types.DoubleType() + + if isinstance(value, types.Integer): + if value.signed: + return lambda builder, v: builder.sitofp(v, ty) + else: + return lambda builder, v: builder.uitofp(v, ty) + elif isinstance(value, types.Float): + if value.bitwidth != 64: + return lambda builder, v: builder.fpext(v, ty) + else: + return lambda _builder, v: v + else: + raise NumbaTypeError("Cannot convert {} to floating point type" % value) + + +@overload(random.getrandbits) +def getrandbits_impl(k): + if isinstance(k, types.Integer): + @intrinsic + def _impl(typingcontext, k): + def codegen(context, builder, sig, args): + nbits, = args + + too_large = builder.icmp_unsigned(">=", nbits, const_int(65)) + too_small = builder.icmp_unsigned("==", nbits, const_int(0)) + with cgutils.if_unlikely(builder, builder.or_(too_large, + too_small)): + msg = "getrandbits() limited to 64 bits" + context.call_conv.return_user_exc(builder, OverflowError, + (msg,)) + state_ptr = get_state_ptr(context, builder, "py") + return get_next_int(context, builder, state_ptr, nbits, False) + return signature(types.uint64, k), codegen + return lambda k: _impl(k) + + +def _randrange_impl(context, builder, start, stop, step, ty, signed, state): + state_ptr = get_state_ptr(context, builder, state) + zero = ir.Constant(ty, 0) + one = ir.Constant(ty, 1) + nptr = cgutils.alloca_once(builder, ty, name="n") + + # n = stop - start + builder.store(builder.sub(stop, start), nptr) + + with builder.if_then(builder.icmp_signed('<', step, zero)): + # n = (n + step + 1) // step + w = builder.add(builder.add(builder.load(nptr), step), one) + n = builder.sdiv(w, step) + builder.store(n, nptr) + with builder.if_then(builder.icmp_signed('>', step, one)): + # n = (n + step - 1) // step + w = builder.sub(builder.add(builder.load(nptr), step), one) + n = builder.sdiv(w, step) + builder.store(n, nptr) + + n = builder.load(nptr) + with cgutils.if_unlikely(builder, builder.icmp_signed('<=', n, zero)): + # n <= 0 + msg = "empty range for randrange()" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + fnty = ir.FunctionType(ty, [ty, cgutils.true_bit.type]) + fn = cgutils.get_or_insert_function(builder.function.module, fnty, + "llvm.ctlz.%s" % ty) + # Since the upper bound is exclusive, we need to subtract one before + # calculating the number of bits. This leads to a special case when + # n == 1; there's only one possible result, so we don't need bits from + # the PRNG. This case is handled separately towards the end of this + # function. CPython's implementation is simpler and just runs another + # iteration of the while loop when the resulting number is too large + # instead of subtracting one, to avoid needing to handle a special + # case. Thus, we only perform this subtraction for the NumPy case. + nm1 = builder.sub(n, one) if state == "np" else n + nbits = builder.trunc(builder.call(fn, [nm1, cgutils.true_bit]), int32_t) + nbits = builder.sub(ir.Constant(int32_t, ty.width), nbits) + + rptr = cgutils.alloca_once(builder, ty, name="r") + + def get_num(): + bbwhile = builder.append_basic_block("while") + bbend = builder.append_basic_block("while.end") + builder.branch(bbwhile) + + builder.position_at_end(bbwhile) + r = get_next_int(context, builder, state_ptr, nbits, state == "np") + r = builder.trunc(r, ty) + too_large = builder.icmp_signed('>=', r, n) + builder.cbranch(too_large, bbwhile, bbend) + + builder.position_at_end(bbend) + builder.store(r, rptr) + + if state == "np": + # Handle n == 1 case, per previous comment. + with builder.if_else(builder.icmp_signed('==', n, one)) as (is_one, is_not_one): + with is_one: + builder.store(zero, rptr) + with is_not_one: + get_num() + else: + get_num() + + return builder.add(start, builder.mul(builder.load(rptr), step)) + + +@overload(random.randrange) +def randrange_impl_1(start): + if isinstance(start, types.Integer): + return lambda start: random.randrange(0, start, 1) + + +@overload(random.randrange) +def randrange_impl_2(start, stop): + if isinstance(start, types.Integer) and isinstance(stop, types.Integer): + return lambda start, stop: random.randrange(start, stop, 1) + + +def _randrange_preprocessor(bitwidth, ty): + if ty.bitwidth != bitwidth: + return (ir.IRBuilder.sext if ty.signed + else ir.IRBuilder.zext) + else: + return lambda _builder, v, _ty: v + + +@overload(random.randrange) +def randrange_impl_3(start, stop, step): + if (isinstance(start, types.Integer) and isinstance(stop, types.Integer) and + isinstance(step, types.Integer)): + signed = max(start.signed, stop.signed, step.signed) + bitwidth = max(start.bitwidth, stop.bitwidth, step.bitwidth) + int_ty = types.Integer.from_bitwidth(bitwidth, signed) + llvm_type = ir.IntType(bitwidth) + + start_preprocessor = _randrange_preprocessor(bitwidth, start) + stop_preprocessor = _randrange_preprocessor(bitwidth, stop) + step_preprocessor = _randrange_preprocessor(bitwidth, step) + + @intrinsic + def _impl(typingcontext, start, stop, step): + def codegen(context, builder, sig, args): + start, stop, step = args + + start = start_preprocessor(builder, start, llvm_type) + stop = stop_preprocessor(builder, stop, llvm_type) + step = step_preprocessor(builder, step, llvm_type) + return _randrange_impl(context, builder, start, stop, step, + llvm_type, signed, 'py') + return signature(int_ty, start, stop, step), codegen + return lambda start, stop, step: _impl(start, stop, step) + + +@overload(random.randint) +def randint_impl_1(a, b): + if isinstance(a, types.Integer) and isinstance(b, types.Integer): + return lambda a, b: random.randrange(a, b + 1, 1) + + +@overload(np.random.randint) +def np_randint_impl_1(low): + if isinstance(low, types.Integer): + return lambda low: np.random.randint(0, low) + + +@overload(np.random.randint) +def np_randint_impl_2(low, high): + if isinstance(low, types.Integer) and isinstance(high, types.Integer): + signed = max(low.signed, high.signed) + bitwidth = max(low.bitwidth, high.bitwidth) + int_ty = types.Integer.from_bitwidth(bitwidth, signed) + llvm_type = ir.IntType(bitwidth) + + start_preprocessor = _randrange_preprocessor(bitwidth, low) + stop_preprocessor = _randrange_preprocessor(bitwidth, high) + + @intrinsic + def _impl(typingcontext, low, high): + def codegen(context, builder, sig, args): + start, stop = args + + start = start_preprocessor(builder, start, llvm_type) + stop = stop_preprocessor(builder, stop, llvm_type) + step = ir.Constant(llvm_type, 1) + return _randrange_impl(context, builder, start, stop, step, + llvm_type, signed, 'np') + return signature(int_ty, low, high), codegen + return lambda low, high: _impl(low, high) + + +@overload(np.random.randint) +def np_randint_impl_3(low, high, size): + if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and + is_nonelike(size)): + return lambda low, high, size: np.random.randint(low, high) + if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and + is_empty_tuple(size)): + # Handle size = () + return lambda low, high, size: np.array(np.random.randint(low, high)) + if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and + (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)))): + bitwidth = max(low.bitwidth, high.bitwidth) + result_type = getattr(np, f'int{bitwidth}') + + def _impl(low, high, size): + out = np.empty(size, dtype=result_type) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.randint(low, high) + return out + return _impl + + +@overload(np.random.uniform) +def np_uniform_impl0(): + return lambda: np.random.uniform(0.0, 1.0) + + +@overload(random.uniform) +def uniform_impl2(a, b): + if isinstance(a, (types.Float, types.Integer)) and isinstance( + b, (types.Float, types.Integer)): + @intrinsic + def _impl(typingcontext, a, b): + low_preprocessor = _double_preprocessor(a) + high_preprocessor = _double_preprocessor(b) + return signature(types.float64, a, b), uniform_impl( + 'py', low_preprocessor, high_preprocessor) + return lambda a, b: _impl(a, b) + + +@overload(np.random.uniform) +def np_uniform_impl2(low, high): + if isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)): + @intrinsic + def _impl(typingcontext, low, high): + low_preprocessor = _double_preprocessor(low) + high_preprocessor = _double_preprocessor(high) + return signature(types.float64, low, high), uniform_impl( + 'np', low_preprocessor, high_preprocessor) + return lambda low, high: _impl(low, high) + + +def uniform_impl(state, a_preprocessor, b_preprocessor): + def impl(context, builder, sig, args): + state_ptr = get_state_ptr(context, builder, state) + a, b = args + a = a_preprocessor(builder, a) + b = b_preprocessor(builder, b) + width = builder.fsub(b, a) + r = get_next_double(context, builder, state_ptr) + return builder.fadd(a, builder.fmul(width, r)) + return impl + + +@overload(np.random.uniform) +def np_uniform_impl3(low, high, size): + if (isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)) and + is_nonelike(size)): + return lambda low, high, size: np.random.uniform(low, high) + if (isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)) and + is_empty_tuple(size)): + # When calling np.random.uniform with size = (), the returned value isn't a + # float like when size = None. Instead, it's an array of shape () + return lambda low, high, size: np.array(np.random.uniform(low, high)) + if (isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)) and + (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)))): + def _impl(low, high, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.uniform(low, high) + return out + return _impl + + +@overload(random.triangular) +def triangular_impl_2(low, high): + def _impl(low, high): + u = random.random() + c = 0.5 + if u > c: + u = 1.0 - u + low, high = high, low + return low + (high - low) * math.sqrt(u * c) + + if isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)): + return _impl + + +@overload(random.triangular) +def triangular_impl_3(low, high, mode): + if (isinstance(low, (types.Float, types.Integer)) and isinstance( + high, (types.Float, types.Integer)) and + isinstance(mode, (types.Float, types.Integer))): + def _impl(low, high, mode): + if high == low: + return low + u = random.random() + c = (mode - low) / (high - low) + if u > c: + u = 1.0 - u + c = 1.0 - c + low, high = high, low + return low + (high - low) * math.sqrt(u * c) + + return _impl + + +@overload(np.random.triangular) +def triangular_impl_3(left, mode, right): + if (isinstance(left, (types.Float, types.Integer)) and isinstance( + mode, (types.Float, types.Integer)) and + isinstance(right, (types.Float, types.Integer))): + def _impl(left, mode, right): + if right == left: + return left + u = np.random.random() + c = (mode - left) / (right - left) + if u > c: + u = 1.0 - u + c = 1.0 - c + left, right = right, left + return left + (right - left) * math.sqrt(u * c) + + return _impl + + +@overload(np.random.triangular) +def triangular_impl(left, mode, right, size=None): + if is_nonelike(size): + return lambda left, mode, right, size=None: np.random.triangular(left, + mode, + right) + if is_empty_tuple(size): + # Handle size = () + return lambda left, mode, right, size=None: np.array( + np.random.triangular(left, mode, right) + ) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(left, mode, right, size=None): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.triangular(left, mode, right) + return out + return _impl + + +@overload(random.gammavariate) +def gammavariate_impl(alpha, beta): + if isinstance(alpha, (types.Float, types.Integer)) and isinstance( + beta, (types.Float, types.Integer)): + return _gammavariate_impl(random.random) + + +@overload(np.random.standard_gamma) +@overload(np.random.gamma) +def ol_np_random_gamma1(shape): + if isinstance(shape, (types.Float, types.Integer)): + return lambda shape: np.random.gamma(shape, 1.0) + + +@overload(np.random.gamma) +def ol_np_random_gamma2(shape, scale): + if isinstance(shape, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)): + fn = register_jitable(_gammavariate_impl(np.random.random)) + def impl(shape, scale): + return fn(shape, scale) + return impl + + +def _gammavariate_impl(_random): + def _impl(alpha, beta): + """Gamma distribution. Taken from CPython. + """ + SG_MAGICCONST = 1.0 + math.log(4.5) + # alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2 + + # Warning: a few older sources define the gamma distribution in terms + # of alpha > -1.0 + if alpha <= 0.0 or beta <= 0.0: + raise ValueError('gammavariate: alpha and beta must be > 0.0') + + if alpha > 1.0: + # Uses R.C.H. Cheng, "The generation of Gamma + # variables with non-integral shape parameters", + # Applied Statistics, (1977), 26, No. 1, p71-74 + ainv = math.sqrt(2.0 * alpha - 1.0) + bbb = alpha - math.log(4.0) + ccc = alpha + ainv + + while 1: + u1 = _random() + if not 1e-7 < u1 < .9999999: + continue + u2 = 1.0 - _random() + v = math.log(u1/(1.0-u1))/ainv + x = alpha*math.exp(v) + z = u1*u1*u2 + r = bbb+ccc*v-x + if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= math.log(z): + return x * beta + + elif alpha == 1.0: + # expovariate(1) + + # Adjust due to cpython + # commit 63d152232e1742660f481c04a811f824b91f6790 + return -math.log(1.0 - _random()) * beta + + else: # alpha is between 0 and 1 (exclusive) + # Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle + while 1: + u = _random() + b = (math.e + alpha)/math.e + p = b*u + if p <= 1.0: + x = p ** (1.0/alpha) + else: + x = -math.log((b-p)/alpha) + u1 = _random() + if p > 1.0: + if u1 <= x ** (alpha - 1.0): + break + elif u1 <= math.exp(-x): + break + return x * beta + return _impl + + +@overload(np.random.gamma) +def gamma_impl(shape, scale, size): + if is_nonelike(size): + return lambda shape, scale, size: np.random.gamma(shape, scale) + if is_empty_tuple(size): + # Handle size = () + return lambda shape, scale, size: np.array(np.random.gamma(shape, scale)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(shape, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.gamma(shape, scale) + return out + return _impl + + +@overload(np.random.standard_gamma) +def standard_gamma_impl(shape, size): + if is_nonelike(size): + return lambda shape, size: np.random.standard_gamma(shape) + if is_empty_tuple(size): + # Handle size = () + return lambda shape, size: np.array(np.random.standard_gamma(shape)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(shape, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.standard_gamma(shape) + return out + return _impl + + +@overload(random.betavariate) +def betavariate_impl(alpha, beta): + if isinstance(alpha, (types.Float, types.Integer)) and isinstance( + beta, (types.Float, types.Integer)): + return _betavariate_impl(random.gammavariate) + + +@overload(np.random.beta) +def ol_np_random_beta(a, b): + if isinstance(a, (types.Float, types.Integer)) and isinstance( + b, (types.Float, types.Integer)): + fn = register_jitable(_betavariate_impl(np.random.gamma)) + def impl(a, b): + return fn(a, b) + return impl + + +def _betavariate_impl(gamma): + def _impl(alpha, beta): + """Beta distribution. Taken from CPython. + """ + # This version due to Janne Sinkkonen, and matches all the std + # texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution"). + y = gamma(alpha, 1.) + if y == 0.0: + return 0.0 + else: + return y / (y + gamma(beta, 1.)) + return _impl + + +@overload(np.random.beta) +def beta_impl(a, b, size): + if is_nonelike(size): + return lambda a, b, size: np.random.beta(a, b) + if is_empty_tuple(size): + # When calling np.random.beta with size = (), the returned value isn't a + # float like when size = None. Instead, it's an array of shape () + return lambda a, b, size: np.array(np.random.beta(a, b)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(a, b, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.beta(a, b) + return out + return _impl + + +@overload(random.expovariate) +def expovariate_impl(lambd): + if isinstance(lambd, types.Float): + def _impl(lambd): + """Exponential distribution. Taken from CPython. + """ + # lambd: rate lambd = 1/mean + # ('lambda' is a Python reserved word) + + # we use 1-random() instead of random() to preclude the + # possibility of taking the log of zero. + return -math.log(1.0 - random.random()) / lambd + + return _impl + + +@overload(np.random.exponential) +def exponential_impl(scale): + if isinstance(scale, (types.Float, types.Integer)): + def _impl(scale): + return -math.log(1.0 - np.random.random()) * scale + return _impl + + +@overload(np.random.exponential) +def exponential_impl(scale, size): + if is_nonelike(size): + return lambda scale, size: np.random.exponential(scale) + if is_empty_tuple(size): + # Handle size = () + return lambda scale, size: np.array(np.random.exponential(scale)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.exponential(scale) + return out + return _impl + + +@overload(np.random.standard_exponential) +@overload(np.random.exponential) +def exponential_impl(): + def _impl(): + return -math.log(1.0 - np.random.random()) + return _impl + + +@overload(np.random.standard_exponential) +def standard_exponential_impl(size): + if is_nonelike(size): + return lambda size: np.random.standard_exponential() + if is_empty_tuple(size): + # Handle size = () + return lambda size: np.array(np.random.standard_exponential()) + if (isinstance(size, types.Integer) or + (isinstance(size, types.UniTuple) and isinstance(size.dtype, + types.Integer)) + ): + def _impl(size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.standard_exponential() + return out + return _impl + + +@overload(np.random.lognormal) +def np_lognormal_impl0(): + return lambda: np.random.lognormal(0.0, 1.0) + + +@overload(np.random.lognormal) +def np_log_normal_impl1(mean): + if isinstance(mean, (types.Float, types.Integer)): + return lambda mean: np.random.lognormal(mean, 1.0) + + +@overload(np.random.lognormal) +def np_log_normal_impl2(mean, sigma): + if isinstance(mean, (types.Float, types.Integer)) and isinstance( + sigma, (types.Float, types.Integer)): + fn = register_jitable(_lognormvariate_impl(np.random.normal)) + return lambda mean, sigma: fn(mean, sigma) + + +@overload(np.random.lognormal) +def lognormal_impl(mean, sigma, size): + if is_nonelike(size): + return lambda mean, sigma, size: np.random.lognormal(mean, sigma) + if is_empty_tuple(size): + # Handle size = () + return lambda mean, sigma, size: np.array(np.random.lognormal(mean, sigma)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(mean, sigma, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.lognormal(mean, sigma) + return out + return _impl + + +@overload(random.lognormvariate) +def lognormvariate_impl(mu, sigma): + if isinstance(mu, types.Float) and isinstance(sigma, types.Float): + fn = register_jitable(_lognormvariate_impl(random.gauss)) + return lambda mu, sigma: fn(mu, sigma) + + +def _lognormvariate_impl(_gauss): + return lambda mu, sigma: math.exp(_gauss(mu, sigma)) + + +@overload(random.paretovariate) +def paretovariate_impl(alpha): + if isinstance(alpha, types.Float): + def _impl(alpha): + """Pareto distribution. Taken from CPython.""" + # Jain, pg. 495 + u = 1.0 - random.random() + return 1.0 / u ** (1.0/alpha) + + return _impl + + +@overload(np.random.pareto) +def pareto_impl(a): + if isinstance(a, types.Float): + def _impl(a): + # Same as paretovariate() - 1. + u = 1.0 - np.random.random() + return 1.0 / u ** (1.0/a) - 1 + + return _impl + + +@overload(np.random.pareto) +def pareto_impl(a, size): + if is_nonelike(size): + return lambda a, size: np.random.pareto(a) + if is_empty_tuple(size): + # Handle size = () + return lambda a, size: np.array(np.random.pareto(a)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(a, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.pareto(a) + return out + return _impl + + +@overload(random.weibullvariate) +def weibullvariate_impl(alpha, beta): + if isinstance(alpha, (types.Float, types.Integer)) and isinstance( + beta, (types.Float, types.Integer)): + def _impl(alpha, beta): + """Weibull distribution. Taken from CPython.""" + # Jain, pg. 499; bug fix courtesy Bill Arms + u = 1.0 - random.random() + return alpha * (-math.log(u)) ** (1.0/beta) + + return _impl + + +@overload(np.random.weibull) +def weibull_impl(a): + if isinstance(a, (types.Float, types.Integer)): + def _impl(a): + # Same as weibullvariate(1.0, a) + u = 1.0 - np.random.random() + return (-math.log(u)) ** (1.0/a) + + return _impl + + +@overload(np.random.weibull) +def weibull_impl2(a, size): + if is_nonelike(size): + return lambda a, size: np.random.weibull(a) + if is_empty_tuple(size): + # Handle size = () + return lambda a, size: np.array(np.random.weibull(a)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(a, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.weibull(a) + return out + return _impl + + +@overload(random.vonmisesvariate) +def vonmisesvariate_impl(mu, kappa): + if isinstance(mu, types.Float) and isinstance(kappa, types.Float): + return _vonmisesvariate_impl(random.random) + + +@overload(np.random.vonmises) +def vonmisesvariate_impl(mu, kappa): + if isinstance(mu, types.Float) and isinstance(kappa, types.Float): + return _vonmisesvariate_impl(np.random.random) + + +def _vonmisesvariate_impl(_random): + def _impl(mu, kappa): + """Circular data distribution. Taken from CPython. + Note the algorithm in Python 2.6 and Numpy is different: + http://bugs.python.org/issue17141 + """ + # mu: mean angle (in radians between 0 and 2*pi) + # kappa: concentration parameter kappa (>= 0) + # if kappa = 0 generate uniform random angle + + # Based upon an algorithm published in: Fisher, N.I., + # "Statistical Analysis of Circular Data", Cambridge + # University Press, 1993. + + # Thanks to Magnus Kessler for a correction to the + # implementation of step 4. + if kappa <= 1e-6: + return 2.0 * math.pi * _random() + + s = 0.5 / kappa + r = s + math.sqrt(1.0 + s * s) + + while 1: + u1 = _random() + z = math.cos(math.pi * u1) + + d = z / (r + z) + u2 = _random() + if u2 < 1.0 - d * d or u2 <= (1.0 - d) * math.exp(d): + break + + q = 1.0 / r + f = (q + z) / (1.0 + q * z) + u3 = _random() + if u3 > 0.5: + theta = (mu + math.acos(f)) % (2.0 * math.pi) + else: + theta = (mu - math.acos(f)) % (2.0 * math.pi) + + return theta + + return _impl + + +@overload(np.random.vonmises) +def vonmises_impl(mu, kappa, size): + if is_nonelike(size): + return lambda mu, kappa, size: np.random.vonmises(mu, kappa) + if is_empty_tuple(size): + # Handle size = () + return lambda mu, kappa, size: np.array(np.random.vonmises(mu, kappa)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(mu, kappa, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.vonmises(mu, kappa) + return out + return _impl + + +@overload(np.random.binomial) +def binomial_impl(n, p): + if isinstance(n, types.Integer) and isinstance( + p, (types.Float, types.Integer)): + def _impl(n, p): + """ + Binomial distribution. Numpy's variant of the BINV algorithm + is used. + (Numpy uses BTPE for n*p >= 30, though) + """ + if n < 0: + raise ValueError("binomial(): n <= 0") + if not (0.0 <= p <= 1.0): + raise ValueError("binomial(): p outside of [0, 1]") + if p == 0.0: + return 0 + if p == 1.0: + return n + + flipped = p > 0.5 + if flipped: + p = 1.0 - p + q = 1.0 - p + + niters = 1 + qn = q ** n + while qn <= 1e-308: + # Underflow => split into several iterations + # Note this is much slower than Numpy's BTPE + niters <<= 2 + n >>= 2 + qn = q ** n + assert n > 0 + + np_prod = n * p + bound = min(n, np_prod + 10.0 * math.sqrt(np_prod * q + 1)) + + total = 0 + while niters > 0: + X = 0 + U = np.random.random() + px = qn + while X <= bound: + if U <= px: + total += n - X if flipped else X + niters -= 1 + break + U -= px + X += 1 + px = ((n - X + 1) * p * px) / (X * q) + + return total + + return _impl + + +@overload(np.random.binomial) +def binomial_impl(n, p, size): + if is_nonelike(size): + return lambda n, p, size: np.random.binomial(n, p) + if is_empty_tuple(size): + # When calling np.random.binomial with size = (), the returned value isn't a + # float like when size = None. Instead, it's an array of shape () + return lambda n, p, size: np.array(np.random.binomial(n, p)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(n, p, size): + out = np.empty(size, dtype=np.intp) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.binomial(n, p) + return out + return _impl + + +@overload(np.random.chisquare) +def chisquare_impl(df): + if isinstance(df, (types.Float, types.Integer)): + def _impl(df): + return 2.0 * np.random.standard_gamma(df / 2.0) + + return _impl + + +@overload(np.random.chisquare) +def chisquare_impl2(df, size): + if is_nonelike(size): + return lambda df, size: np.random.chisquare(df) + if is_empty_tuple(size): + return lambda df, size: np.array(np.random.chisquare(df)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(df, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.chisquare(df) + return out + return _impl + + +@overload(np.random.f) +def f_impl(dfnum, dfden): + if isinstance(dfnum, (types.Float, types.Integer)) and isinstance( + dfden, (types.Float, types.Integer)): + def _impl(dfnum, dfden): + return ((np.random.chisquare(dfnum) * dfden) / + (np.random.chisquare(dfden) * dfnum)) + + return _impl + + +@overload(np.random.f) +def f_impl(dfnum, dfden, size): + if (isinstance(dfnum, (types.Float, types.Integer)) and isinstance( + dfden, (types.Float, types.Integer)) and + is_nonelike(size)): + return lambda dfnum, dfden, size: np.random.f(dfnum, dfden) + if (isinstance(dfnum, (types.Float, types.Integer)) and isinstance( + dfden, (types.Float, types.Integer)) and + is_empty_tuple(size)): + # Handle size = () + return lambda dfnum, dfden, size: np.array(np.random.f(dfnum, dfden)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(dfnum, dfden, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.f(dfnum, dfden) + return out + return _impl + + +@overload(np.random.geometric) +def geometric_impl(p): + if isinstance(p, (types.Float, types.Integer)): + def _impl(p): + # Numpy's algorithm. + if p <= 0.0 or p > 1.0: + raise ValueError("geometric(): p outside of (0, 1]") + q = 1.0 - p + if p >= 0.333333333333333333333333: + X = int(1) + sum = prod = p + U = np.random.random() + while U > sum: + prod *= q + sum += prod + X += 1 + return X + else: + return math.ceil(math.log(1.0 - np.random.random()) / + math.log(q)) + + return _impl + + +@overload(np.random.geometric) +def geometric_impl(p, size): + if is_nonelike(size): + return lambda p, size: np.random.geometric(p) + if is_empty_tuple(size): + # Handle size = () + return lambda p, size: np.array(np.random.geometric(p)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer))): + def _impl(p, size): + out = np.empty(size, dtype=np.int64) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.geometric(p) + return out + return _impl + + +@overload(np.random.gumbel) +def gumbel_impl(loc, scale): + if isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)): + def _impl(loc, scale): + U = 1.0 - np.random.random() + return loc - scale * math.log(-math.log(U)) + + return _impl + + +@overload(np.random.gumbel) +def gumbel_impl3(loc, scale, size): + if is_nonelike(size): + return lambda loc, scale, size: np.random.gumbel(loc, scale) + if is_empty_tuple(size): + # Handle size = () + return lambda loc, scale, size: np.array(np.random.gumbel(loc, scale)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(loc, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.gumbel(loc, scale) + return out + return _impl + + +@overload(np.random.hypergeometric) +def hypergeometric_impl(ngood, nbad, nsample): + if (isinstance(ngood, (types.Float, types.Integer)) and isinstance( + nbad, (types.Float, types.Integer)) + and isinstance(nsample, (types.Float, types.Integer))): + def _impl(ngood, nbad, nsample): + """Numpy's algorithm for hypergeometric().""" + d1 = int(nbad) + int(ngood) - int(nsample) + d2 = float(min(nbad, ngood)) + + Y = d2 + K = int(nsample) + while Y > 0.0 and K > 0: + Y -= math.floor(np.random.random() + Y / (d1 + K)) + K -= 1 + Z = int(d2 - Y) + if ngood > nbad: + return int(nsample) - Z + else: + return Z + + return _impl + + +@overload(np.random.hypergeometric) +def hypergeometric_impl(ngood, nbad, nsample, size): + if is_nonelike(size): + return lambda ngood, nbad, nsample, size:\ + np.random.hypergeometric(ngood, nbad, nsample) + if is_empty_tuple(size): + # Handle size = () + return lambda ngood, nbad, nsample, size:\ + np.array(np.random.hypergeometric(ngood, nbad, nsample)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(ngood, nbad, nsample, size): + out = np.empty(size, dtype=np.intp) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.hypergeometric(ngood, nbad, nsample) + return out + return _impl + + +@overload(np.random.laplace) +def laplace_impl0(): + return lambda: np.random.laplace(0.0, 1.0) + + +@overload(np.random.laplace) +def laplace_impl1(loc): + if isinstance(loc, (types.Float, types.Integer)): + return lambda loc: np.random.laplace(loc, 1.0) + + +@overload(np.random.laplace) +def laplace_impl2(loc, scale): + if isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)): + return laplace_impl + + +@overload(np.random.laplace) +def laplace_impl3(loc, scale, size): + if is_nonelike(size): + return lambda loc, scale, size: np.random.laplace(loc, scale) + if is_empty_tuple(size): + # Handle size = () + return lambda loc, scale, size: np.array(np.random.laplace(loc, scale)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(loc, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.laplace(loc, scale) + return out + return _impl + + +def laplace_impl(loc, scale): + U = np.random.random() + if U < 0.5: + return loc + scale * math.log(U + U) + else: + return loc - scale * math.log(2.0 - U - U) + + +@overload(np.random.logistic) +def logistic_impl0(): + return lambda: np.random.logistic(0.0, 1.0) + + +@overload(np.random.logistic) +def logistic_impl1(loc): + if isinstance(loc, (types.Float, types.Integer)): + return lambda loc: np.random.logistic(loc, 1.0) + + +@overload(np.random.logistic) +def logistic_impl2(loc, scale): + if isinstance(loc, (types.Float, types.Integer)) and isinstance( + scale, (types.Float, types.Integer)): + return logistic_impl + + +@overload(np.random.logistic) +def logistic_impl3(loc, scale, size): + if is_nonelike(size): + return lambda loc, scale, size: np.random.logistic(loc, scale) + if is_empty_tuple(size): + # Handle size = () + return lambda loc, scale, size: np.array(np.random.logistic(loc, scale)) + if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer))): + def _impl(loc, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.logistic(loc, scale) + return out + return _impl + + +def logistic_impl(loc, scale): + U = np.random.random() + return loc + scale * math.log(U / (1.0 - U)) + + +def _logseries_impl(p): + """Numpy's algorithm for logseries().""" + if p <= 0.0 or p > 1.0: + raise ValueError("logseries(): p outside of (0, 1]") + r = math.log(1.0 - p) + + while 1: + V = np.random.random() + if V >= p: + return 1 + U = np.random.random() + q = 1.0 - math.exp(r * U) + if V <= q * q: + # XXX what if V == 0.0 ? + return np.int64(1.0 + math.log(V) / math.log(q)) + elif V >= q: + return 1 + else: + return 2 + + +@overload(np.random.logseries) +def logseries_impl(p): + if isinstance(p, (types.Float, types.Integer)): + return _logseries_impl + + +@overload(np.random.logseries) +def logseries_impl(p, size): + if is_nonelike(size): + return lambda p, size: np.random.logseries(p) + if is_empty_tuple(size): + return lambda p, size: np.array(np.random.logseries(p)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(p, size): + out = np.empty(size, dtype=np.int64) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.logseries(p) + return out + return _impl + + +@overload(np.random.negative_binomial) +def negative_binomial_impl(n, p): + if isinstance(n, (types.Float, types.Integer)) and isinstance( + p,(types.Float, types.Integer)): + def _impl(n, p): + if n <= 0: + raise ValueError("negative_binomial(): n <= 0") + if p < 0.0 or p > 1.0: + raise ValueError("negative_binomial(): p outside of [0, 1]") + Y = np.random.gamma(n, (1.0 - p) / p) + return np.random.poisson(Y) + + return _impl + + +@overload(np.random.poisson) +def poisson_impl0(): + return lambda: np.random.poisson(1.0) + + +@overload(np.random.poisson) +def poisson_impl1(lam): + if isinstance(lam, (types.Float, types.Integer)): + @intrinsic + def _impl(typingcontext, lam): + lam_preprocessor = _double_preprocessor(lam) + + def codegen(context, builder, sig, args): + state_ptr = get_np_state_ptr(context, builder) + + retptr = cgutils.alloca_once(builder, int64_t, name="ret") + bbcont = builder.append_basic_block("bbcont") + bbend = builder.append_basic_block("bbend") + + lam, = args + lam = lam_preprocessor(builder, lam) + big_lam = builder.fcmp_ordered('>=', lam, + ir.Constant(double, 10.0)) + with builder.if_then(big_lam): + # For lambda >= 10.0, we switch to a more accurate + # algorithm (see _random.c). + fnty = ir.FunctionType(int64_t, (rnd_state_ptr_t, double)) + fn = cgutils.get_or_insert_function(builder.function.module, + fnty, + "numba_poisson_ptrs") + ret = builder.call(fn, (state_ptr, lam)) + builder.store(ret, retptr) + builder.branch(bbend) + + builder.branch(bbcont) + builder.position_at_end(bbcont) + + _random = np.random.random + _exp = math.exp + + def poisson_impl(lam): + """Numpy's algorithm for poisson() on small *lam*. + + This method is invoked only if the parameter lambda of the + distribution is small ( < 10 ). The algorithm used is + described in "Knuth, D. 1969. 'Seminumerical Algorithms. + The Art of Computer Programming' vol 2. + """ + if lam < 0.0: + raise ValueError("poisson(): lambda < 0") + if lam == 0.0: + return 0 + enlam = _exp(-lam) + X = 0 + prod = 1.0 + while 1: + U = _random() + prod *= U + if prod <= enlam: + return X + X += 1 + + ret = context.compile_internal(builder, poisson_impl, sig, args) + builder.store(ret, retptr) + builder.branch(bbend) + builder.position_at_end(bbend) + return builder.load(retptr) + return signature(types.int64, lam), codegen + return lambda lam: _impl(lam) + + +@overload(np.random.poisson) +def poisson_impl2(lam, size): + if isinstance(lam, (types.Float, types.Integer)) and is_nonelike(size): + return lambda lam, size: np.random.poisson(lam) + if isinstance(lam, (types.Float, types.Integer)) and is_empty_tuple(size): + # Handle size = () + return lambda lam, size: np.array(np.random.poisson(lam)) + if isinstance(lam, (types.Float, types.Integer)) and ( + isinstance(size, types.Integer) or + (isinstance(size, types.UniTuple) and isinstance(size.dtype, + types.Integer)) + ): + def _impl(lam, size): + out = np.empty(size, dtype=np.intp) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.poisson(lam) + return out + return _impl + + +@overload(np.random.power) +def power_impl(a): + if isinstance(a, (types.Float, types.Integer)): + def _impl(a): + if a <= 0.0: + raise ValueError("power(): a <= 0") + return math.pow(1 - math.exp(-np.random.standard_exponential()), + 1./a) + + return _impl + + +@overload(np.random.power) +def power_impl(a, size): + if is_nonelike(size): + return lambda a, size: np.random.power(a) + if is_empty_tuple(size): + # Handle size = () + return lambda a, size: np.array(np.random.power(a)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(a, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.power(a) + return out + return _impl + + +@overload(np.random.rayleigh) +def rayleigh_impl0(): + return lambda: np.random.rayleigh(1.0) + + +@overload(np.random.rayleigh) +def rayleigh_impl1(scale): + if isinstance(scale, (types.Float, types.Integer)): + def impl(scale): + if scale <= 0.0: + raise ValueError("rayleigh(): scale <= 0") + return scale * math.sqrt(-2.0 * math.log(1.0 - np.random.random())) + return impl + + + + +@overload(np.random.rayleigh) +def rayleigh_impl2(scale, size): + if is_nonelike(size): + return lambda scale, size: np.random.rayleigh(scale) + if is_empty_tuple(size): + # Handle size = () + return lambda scale, size: np.array(np.random.rayleigh(scale)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.rayleigh(scale) + return out + return _impl + + +@overload(np.random.standard_cauchy) +def cauchy_impl(): + def _impl(): + return np.random.standard_normal() / np.random.standard_normal() + + return _impl + + +@overload(np.random.standard_cauchy) +def standard_cauchy_impl(size): + if is_nonelike(size): + return lambda size: np.random.standard_cauchy() + if is_empty_tuple(size): + # Handle size = () + return lambda size: np.array(np.random.standard_cauchy()) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)): + def _impl(size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.standard_cauchy() + return out + return _impl + + +@overload(np.random.standard_t) +def standard_t_impl(df): + if isinstance(df, (types.Float, types.Integer)): + def _impl(df): + N = np.random.standard_normal() + G = np.random.standard_gamma(df / 2.0) + X = math.sqrt(df / 2.0) * N / math.sqrt(G) + return X + + return _impl + + +@overload(np.random.standard_t) +def standard_t_impl2(df, size): + if is_nonelike(size): + return lambda df, size: np.random.standard_t(df) + if is_empty_tuple(size): + return lambda df, size: np.array(np.random.standard_t(df)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(df, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.standard_t(df) + return out + return _impl + + +@overload(np.random.wald) +def wald_impl(mean, scale): + if isinstance(mean, types.Float) and isinstance(scale, types.Float): + def _impl(mean, scale): + if mean <= 0.0: + raise ValueError("wald(): mean <= 0") + if scale <= 0.0: + raise ValueError("wald(): scale <= 0") + mu_2l = mean / (2.0 * scale) + Y = np.random.standard_normal() + Y = mean * Y * Y + X = mean + mu_2l * (Y - math.sqrt(4 * scale * Y + Y * Y)) + U = np.random.random() + if U <= mean / (mean + X): + return X + else: + return mean * mean / X + + return _impl + + +@overload(np.random.wald) +def wald_impl2(mean, scale, size): + if is_nonelike(size): + return lambda mean, scale, size: np.random.wald(mean, scale) + if is_empty_tuple(size): + # Handle size = () + return lambda mean, scale, size: np.array(np.random.wald(mean, scale)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(mean, scale, size): + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.wald(mean, scale) + return out + return _impl + + +@overload(np.random.zipf) +def zipf_impl(a): + if isinstance(a, types.Float): + def _impl(a): + if a <= 1.0: + raise ValueError("zipf(): a <= 1") + am1 = a - 1.0 + b = 2.0 ** am1 + while 1: + U = 1.0 - np.random.random() + V = np.random.random() + X = int(math.floor(U ** (-1.0 / am1))) + + if (X > LONG_MAX or X < 1.0): + continue + + T = (1.0 + 1.0 / X) ** am1 + if X >= 1 and V * X * (T - 1.0) / (b - 1.0) <= (T / b): + return X + + return _impl + + +@overload(np.random.zipf) +def zipf_impl(a, size): + if is_nonelike(size): + return lambda a, size: np.random.zipf(a) + if is_empty_tuple(size): + # Handle size = () + return lambda a, size: np.array(np.random.zipf(a)) + if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and + isinstance(size.dtype, + types.Integer)): + def _impl(a, size): + out = np.empty(size, dtype=np.intp) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = np.random.zipf(a) + return out + return _impl + +def do_shuffle_impl(x, rng): + + if not isinstance(x, types.Buffer): + msg = "The argument to shuffle() should be a buffer type" + raise NumbaTypeError(msg) + + if rng == "np": + rand = np.random.randint + elif rng == "py": + rand = random.randrange + + if x.ndim == 1: + def impl(x): + i = x.shape[0] - 1 + while i > 0: + j = rand(i + 1) + x[i], x[j] = x[j], x[i] + i -= 1 + else: + def impl(x): + i = x.shape[0] - 1 + while i > 0: + j = rand(i + 1) + x[i], x[j] = np.copy(x[j]), np.copy(x[i]) + i -= 1 + + return impl + + +@overload(random.shuffle) +def shuffle_impl(x): + return do_shuffle_impl(x, "py") + + +@overload(np.random.shuffle) +def shuffle_impl(x): + return do_shuffle_impl(x, "np") + + +@overload(np.random.permutation) +def permutation_impl(x): + if isinstance(x, types.Integer): + def permutation_impl(x): + y = np.arange(x) + np.random.shuffle(y) + return y + elif isinstance(x, types.Array): + def permutation_impl(x): + arr_copy = x.copy() + np.random.shuffle(arr_copy) + return arr_copy + else: + permutation_impl = None + return permutation_impl + + +# ------------------------------------------------------------------------ +# Irregular aliases: np.random.rand, np.random.randn + +@overload(np.random.rand) +def rand(*size): + if len(size) == 0: + # Scalar output + def rand_impl(*size): + return np.random.random() + + else: + # Array output + def rand_impl(*size): + return np.random.random(size) + + return rand_impl + + +@overload(np.random.randn) +def randn(*size): + if len(size) == 0: + # Scalar output + def randn_impl(*size): + return np.random.standard_normal() + + else: + # Array output + def randn_impl(*size): + return np.random.standard_normal(size) + + return randn_impl + + +# ------------------------------------------------------------------------ +# np.random.choice + +@overload(np.random.choice) +def choice(a, size=None, replace=True): + + if isinstance(a, types.Array): + # choice() over an array population + assert a.ndim == 1 + dtype = a.dtype + + @register_jitable + def get_source_size(a): + return len(a) + + @register_jitable + def copy_source(a): + return a.copy() + + @register_jitable + def getitem(a, a_i): + return a[a_i] + + elif isinstance(a, types.Integer): + # choice() over an implied arange() population + dtype = np.intp + + @register_jitable + def get_source_size(a): + return a + + @register_jitable + def copy_source(a): + return np.arange(a) + + @register_jitable + def getitem(a, a_i): + return a_i + + else: + raise NumbaTypeError("np.random.choice() first argument should be " + "int or array, got %s" % (a,)) + + if size in (None, types.none): + def choice_impl(a, size=None, replace=True): + """ + choice() implementation returning a single sample + (note *replace* is ignored) + """ + n = get_source_size(a) + i = np.random.randint(0, n) + return getitem(a, i) + + else: + def choice_impl(a, size=None, replace=True): + """ + choice() implementation returning an array of samples + """ + n = get_source_size(a) + if replace: + out = np.empty(size, dtype) + fl = out.flat + for i in range(len(fl)): + j = np.random.randint(0, n) + fl[i] = getitem(a, j) + return out + else: + # Note we have to construct the array to compute out.size + # (`size` can be an arbitrary int or tuple of ints) + out = np.empty(size, dtype) + if out.size > n: + raise ValueError("Cannot take a larger sample than " + "population when 'replace=False'") + # Get a permuted copy of the source array + # we need this implementation in order to get the + # np.random.choice inside numba to match the output + # of np.random.choice outside numba when np.random.seed + # is set to the same value + permuted_a = np.random.permutation(a) + fl = out.flat + for i in range(len(fl)): + fl[i] = permuted_a[i] + return out + + return choice_impl + + +# ------------------------------------------------------------------------ +# np.random.multinomial + +@overload(np.random.multinomial) +def multinomial(n, pvals, size=None): + + dtype = np.intp + + @register_jitable + def multinomial_inner(n, pvals, out): + # Numpy's algorithm for multinomial() + fl = out.flat + sz = out.size + plen = len(pvals) + + for i in range(0, sz, plen): + # Loop body: take a set of n experiments and fill up + # fl[i:i + plen] with the distribution of results. + + # Current sum of outcome probabilities + p_sum = 1.0 + # Current remaining number of experiments + n_experiments = n + # For each possible outcome `j`, compute the number of results + # with this outcome. This is done by considering the + # conditional probability P(X=j | X>=j) and running a binomial + # distribution over the remaining number of experiments. + for j in range(0, plen - 1): + p_j = pvals[j] + n_j = fl[i + j] = np.random.binomial(n_experiments, p_j / p_sum) + n_experiments -= n_j + if n_experiments <= 0: + # Note the output was initialized to zero + break + p_sum -= p_j + if n_experiments > 0: + # The remaining experiments end up in the last bucket + fl[i + plen - 1] = n_experiments + + if not isinstance(n, types.Integer): + raise NumbaTypeError("np.random.multinomial(): n should be an " + "integer, got %s" % (n,)) + + if not isinstance(pvals, (types.Sequence, types.Array)): + raise NumbaTypeError("np.random.multinomial(): pvals should be an " + "array or sequence, got %s" % (pvals,)) + + if size in (None, types.none): + def multinomial_impl(n, pvals, size=None): + """ + multinomial(..., size=None) + """ + out = np.zeros(len(pvals), dtype) + multinomial_inner(n, pvals, out) + return out + + elif isinstance(size, types.Integer): + def multinomial_impl(n, pvals, size=None): + """ + multinomial(..., size=int) + """ + out = np.zeros((size, len(pvals)), dtype) + multinomial_inner(n, pvals, out) + return out + + elif isinstance(size, types.BaseTuple): + def multinomial_impl(n, pvals, size=None): + """ + multinomial(..., size=tuple) + """ + out = np.zeros(size + (len(pvals),), dtype) + multinomial_inner(n, pvals, out) + return out + + else: + raise NumbaTypeError("np.random.multinomial(): size should be int or " + "tuple or None, got %s" % (size,)) + + return multinomial_impl + +# ------------------------------------------------------------------------ +# np.random.dirichlet + + +@overload(np.random.dirichlet) +def dirichlet(alpha): + if isinstance(alpha, (types.Sequence, types.Array)): + def dirichlet_impl(alpha): + out = np.empty(len(alpha)) + dirichlet_arr(alpha, out) + return out + return dirichlet_impl + + +@overload(np.random.dirichlet) +def dirichlet(alpha, size=None): + if not isinstance(alpha, (types.Sequence, types.Array)): + raise NumbaTypeError( + "np.random.dirichlet(): alpha should be an " + "array or sequence, got %s" % (alpha,) + ) + + if size in (None, types.none) or is_empty_tuple(size): + + def dirichlet_impl(alpha, size=None): + out = np.empty(len(alpha)) + dirichlet_arr(alpha, out) + return out + + elif isinstance(size, types.Integer): + + def dirichlet_impl(alpha, size=None): + """ + dirichlet(..., size=int) + """ + out = np.empty((size, len(alpha))) + dirichlet_arr(alpha, out) + return out + + elif isinstance(size, types.UniTuple) and isinstance(size.dtype, + types.Integer): + def dirichlet_impl(alpha, size=None): + """ + dirichlet(..., size=tuple) + """ + out = np.empty(size + (len(alpha),)) + dirichlet_arr(alpha, out) + return out + + else: + raise NumbaTypeError( + "np.random.dirichlet(): size should be int or " + "tuple of ints or None, got %s" % size + ) + + return dirichlet_impl + + +@register_jitable +def dirichlet_arr(alpha, out): + + # Gamma distribution method to generate a Dirichlet distribution + + for a_val in iter(alpha): + if a_val <= 0: + raise ValueError("dirichlet: alpha must be > 0.0") + + a_len = len(alpha) + size = out.size + flat = out.flat + for i in range(0, size, a_len): + # calculate gamma random numbers per alpha specifications + norm = 0 # use this to normalize every the group total to 1 + for k, w in enumerate(alpha): + flat[i + k] = np.random.gamma(w, 1) + norm += flat[i + k].item() + for k, w in enumerate(alpha): + flat[i + k] /= norm + + +# ------------------------------------------------------------------------ +# np.random.noncentral_chisquare + + +@overload(np.random.noncentral_chisquare) +def noncentral_chisquare(df, nonc): + if isinstance(df, (types.Float, types.Integer)) and isinstance( + nonc, (types.Float, types.Integer)): + def noncentral_chisquare_impl(df, nonc): + validate_noncentral_chisquare_input(df, nonc) + return noncentral_chisquare_single(df, nonc) + + return noncentral_chisquare_impl + + +@overload(np.random.noncentral_chisquare) +def noncentral_chisquare(df, nonc, size=None): + if size in (None, types.none): + def noncentral_chisquare_impl(df, nonc, size=None): + validate_noncentral_chisquare_input(df, nonc) + return noncentral_chisquare_single(df, nonc) + return noncentral_chisquare_impl + if is_empty_tuple(size): + # Handle size = () + def noncentral_chisquare_impl(df, nonc, size=None): + validate_noncentral_chisquare_input(df, nonc) + return np.array(noncentral_chisquare_single(df, nonc)) + return noncentral_chisquare_impl + elif isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) + and isinstance(size.dtype, + types.Integer)): + + def noncentral_chisquare_impl(df, nonc, size=None): + validate_noncentral_chisquare_input(df, nonc) + out = np.empty(size) + out_flat = out.flat + for idx in range(out.size): + out_flat[idx] = noncentral_chisquare_single(df, nonc) + return out + return noncentral_chisquare_impl + else: + raise NumbaTypeError( + "np.random.noncentral_chisquare(): size should be int or " + "tuple of ints or None, got %s" % size + ) + + +@register_jitable +def noncentral_chisquare_single(df, nonc): + # identical to numpy implementation from distributions.c + # https://github.com/numpy/numpy/blob/c65bc212ec1987caefba0ea7efe6a55803318de9/numpy/random/src/distributions/distributions.c#L797 + + if np.isnan(nonc): + return np.nan + + if 1 < df: + chi2 = np.random.chisquare(df-1) + n = np.random.standard_normal() + np.sqrt(nonc) + return chi2 + n * n + + else: + i = np.random.poisson(nonc/2.0) + return np.random.chisquare(df + 2 * i) + + +@register_jitable +def validate_noncentral_chisquare_input(df, nonc): + if df <= 0: + raise ValueError("df <= 0") + if nonc < 0: + raise ValueError("nonc < 0") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/rangeobj.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/rangeobj.py new file mode 100644 index 0000000000000000000000000000000000000000..5e385abf284379ceb001ec4538496b71fee34f57 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/rangeobj.py @@ -0,0 +1,241 @@ +""" +Implementation of the range object for fixed-size integers. +""" + +import operator + +from numba import prange +from numba.core import types, cgutils, errors, config +from numba.core.imputils import (lower_builtin, lower_cast, + iterator_impl, impl_ret_untracked) +from numba.core.typing import signature +from numba.core.extending import intrinsic, overload, overload_attribute, register_jitable +from numba.parfors.parfor import internal_prange + +def make_range_iterator(typ): + """ + Return the Structure representation of the given *typ* (an + instance of types.RangeIteratorType). + """ + return cgutils.create_struct_proxy(typ) + + +def make_range_impl(int_type, range_state_type, range_iter_type): + RangeState = cgutils.create_struct_proxy(range_state_type) + + @lower_builtin(range, int_type) + @lower_builtin(prange, int_type) + @lower_builtin(internal_prange, int_type) + def range1_impl(context, builder, sig, args): + """ + range(stop: int) -> range object + """ + [stop] = args + state = RangeState(context, builder) + state.start = context.get_constant(int_type, 0) + state.stop = stop + state.step = context.get_constant(int_type, 1) + return impl_ret_untracked(context, + builder, + range_state_type, + state._getvalue()) + + @lower_builtin(range, int_type, int_type) + @lower_builtin(prange, int_type, int_type) + @lower_builtin(internal_prange, int_type, int_type) + def range2_impl(context, builder, sig, args): + """ + range(start: int, stop: int) -> range object + """ + start, stop = args + state = RangeState(context, builder) + state.start = start + state.stop = stop + state.step = context.get_constant(int_type, 1) + return impl_ret_untracked(context, + builder, + range_state_type, + state._getvalue()) + + @lower_builtin(range, int_type, int_type, int_type) + @lower_builtin(prange, int_type, int_type, int_type) + @lower_builtin(internal_prange, int_type, int_type, int_type) + def range3_impl(context, builder, sig, args): + """ + range(start: int, stop: int, step: int) -> range object + """ + [start, stop, step] = args + state = RangeState(context, builder) + state.start = start + state.stop = stop + state.step = step + return impl_ret_untracked(context, + builder, + range_state_type, + state._getvalue()) + + @lower_builtin(len, range_state_type) + def range_len(context, builder, sig, args): + """ + len(range) + """ + (value,) = args + state = RangeState(context, builder, value) + res = RangeIter.from_range_state(context, builder, state) + return impl_ret_untracked(context, builder, int_type, builder.load(res.count)) + + @lower_builtin('getiter', range_state_type) + def getiter_range32_impl(context, builder, sig, args): + """ + range.__iter__ + """ + (value,) = args + state = RangeState(context, builder, value) + res = RangeIter.from_range_state(context, builder, state)._getvalue() + return impl_ret_untracked(context, builder, range_iter_type, res) + + @iterator_impl(range_state_type, range_iter_type) + class RangeIter(make_range_iterator(range_iter_type)): + + @classmethod + def from_range_state(cls, context, builder, state): + """ + Create a RangeIter initialized from the given RangeState *state*. + """ + self = cls(context, builder) + start = state.start + stop = state.stop + step = state.step + + startptr = cgutils.alloca_once(builder, start.type) + builder.store(start, startptr) + + countptr = cgutils.alloca_once(builder, start.type) + + self.iter = startptr + self.stop = stop + self.step = step + self.count = countptr + + diff = builder.sub(stop, start) + zero = context.get_constant(int_type, 0) + one = context.get_constant(int_type, 1) + pos_diff = builder.icmp_signed('>', diff, zero) + pos_step = builder.icmp_signed('>', step, zero) + sign_differs = builder.xor(pos_diff, pos_step) + zero_step = builder.icmp_unsigned('==', step, zero) + + with cgutils.if_unlikely(builder, zero_step): + # step shouldn't be zero + context.call_conv.return_user_exc(builder, ValueError, + ("range() arg 3 must not be zero",)) + + with builder.if_else(sign_differs) as (then, orelse): + with then: + builder.store(zero, self.count) + + with orelse: + rem = builder.srem(diff, step) + rem = builder.select(pos_diff, rem, builder.neg(rem)) + uneven = builder.icmp_signed('>', rem, zero) + newcount = builder.add(builder.sdiv(diff, step), + builder.select(uneven, one, zero)) + builder.store(newcount, self.count) + + return self + + def iternext(self, context, builder, result): + zero = context.get_constant(int_type, 0) + countptr = self.count + count = builder.load(countptr) + is_valid = builder.icmp_signed('>', count, zero) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + value = builder.load(self.iter) + result.yield_(value) + one = context.get_constant(int_type, 1) + + builder.store(builder.sub(count, one, flags=["nsw"]), countptr) + builder.store(builder.add(value, self.step), self.iter) + +range_impl_map = { + types.int32 : (types.range_state32_type, types.range_iter32_type), + types.int64 : (types.range_state64_type, types.range_iter64_type), + types.uint64 : (types.unsigned_range_state64_type, types.unsigned_range_iter64_type) +} + +for int_type, state_types in range_impl_map.items(): + make_range_impl(int_type, *state_types) + +@lower_cast(types.RangeType, types.RangeType) +def range_to_range(context, builder, fromty, toty, val): + olditems = cgutils.unpack_tuple(builder, val, 3) + items = [context.cast(builder, v, fromty.dtype, toty.dtype) + for v in olditems] + return cgutils.make_anonymous_struct(builder, items) + + +def make_range_attr(index, attribute): + @intrinsic + def rangetype_attr_getter(typingctx, a): + if isinstance(a, types.RangeType): + def codegen(context, builder, sig, args): + (val,) = args + items = cgutils.unpack_tuple(builder, val, 3) + return impl_ret_untracked(context, builder, sig.return_type, + items[index]) + return signature(a.dtype, a), codegen + + @overload_attribute(types.RangeType, attribute) + def range_attr(rnge): + def get(rnge): + return rangetype_attr_getter(rnge) + return get + + +@register_jitable +def impl_contains_helper(robj, val): + if robj.step > 0 and (val < robj.start or val >= robj.stop): + return False + elif robj.step < 0 and (val <= robj.stop or val > robj.start): + return False + + return ((val - robj.start) % robj.step) == 0 + + +@overload(operator.contains) +def impl_contains(robj, val): + def impl_false(robj, val): + return False + + if not isinstance(robj, types.RangeType): + return + + elif isinstance(val, (types.Integer, types.Boolean)): + return impl_contains_helper + + elif isinstance(val, types.Float): + def impl(robj, val): + if val % 1 != 0: + return False + else: + return impl_contains_helper(robj, int(val)) + return impl + + elif isinstance(val, types.Complex): + def impl(robj, val): + if val.imag != 0: + return False + elif val.real % 1 != 0: + return False + else: + return impl_contains_helper(robj, int(val.real)) + return impl + + elif not isinstance(val, types.Number): + return impl_false + + +for ix, attr in enumerate(('start', 'stop', 'step')): + make_range_attr(index=ix, attribute=attr) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/setobj.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/setobj.py new file mode 100644 index 0000000000000000000000000000000000000000..441067ef365c12e71e4414de2eff05a10421f078 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/setobj.py @@ -0,0 +1,1711 @@ +""" +Support for native homogeneous sets. +""" + + +import collections +import contextlib +import math +import operator +from functools import cached_property + +from llvmlite import ir +from numba.core import types, typing, cgutils +from numba.core.imputils import (lower_builtin, lower_cast, + iternext_impl, impl_ret_borrowed, + impl_ret_new_ref, impl_ret_untracked, + for_iter, call_len, RefType) +from numba.misc import quicksort +from numba.cpython import slicing +from numba.core.errors import NumbaValueError, TypingError +from numba.core.extending import overload, overload_method, intrinsic + + +def get_payload_struct(context, builder, set_type, ptr): + """ + Given a set value and type, get its payload structure (as a + reference, so that mutations are seen by all). + """ + payload_type = types.SetPayload(set_type) + ptrty = context.get_data_type(payload_type).as_pointer() + payload = builder.bitcast(ptr, ptrty) + return context.make_data_helper(builder, payload_type, ref=payload) + + +def get_entry_size(context, set_type): + """ + Return the entry size for the given set type. + """ + llty = context.get_data_type(types.SetEntry(set_type)) + return context.get_abi_sizeof(llty) + + +# Note these values are special: +# - EMPTY is obtained by issuing memset(..., 0xFF) +# - (unsigned) EMPTY > (unsigned) DELETED > any other hash value +EMPTY = -1 +DELETED = -2 +FALLBACK = -43 + +# Minimal size of entries table. Must be a power of 2! +MINSIZE = 16 + +# Number of cache-friendly linear probes before switching to non-linear probing +LINEAR_PROBES = 3 + +DEBUG_ALLOCS = False + + +def get_hash_value(context, builder, typ, value): + """ + Compute the hash of the given value. + """ + typingctx = context.typing_context + fnty = typingctx.resolve_value_type(hash) + sig = fnty.get_call_type(typingctx, (typ,), {}) + fn = context.get_function(fnty, sig) + h = fn(builder, (value,)) + # Fixup reserved values + is_ok = is_hash_used(context, builder, h) + fallback = ir.Constant(h.type, FALLBACK) + return builder.select(is_ok, h, fallback) + + +@intrinsic +def _get_hash_value_intrinsic(typingctx, value): + def impl(context, builder, typ, args): + return get_hash_value(context, builder, value, args[0]) + fnty = typingctx.resolve_value_type(hash) + sig = fnty.get_call_type(typingctx, (value,), {}) + return sig, impl + + +def is_hash_empty(context, builder, h): + """ + Whether the hash value denotes an empty entry. + """ + empty = ir.Constant(h.type, EMPTY) + return builder.icmp_unsigned('==', h, empty) + +def is_hash_deleted(context, builder, h): + """ + Whether the hash value denotes a deleted entry. + """ + deleted = ir.Constant(h.type, DELETED) + return builder.icmp_unsigned('==', h, deleted) + +def is_hash_used(context, builder, h): + """ + Whether the hash value denotes an active entry. + """ + # Everything below DELETED is an used entry + deleted = ir.Constant(h.type, DELETED) + return builder.icmp_unsigned('<', h, deleted) + + +def check_all_set(*args): + if not all([isinstance(typ, types.Set) for typ in args]): + raise TypingError(f"All arguments must be Sets, got {args}") + + if not all([args[0].dtype == s.dtype for s in args]): + raise TypingError(f"All Sets must be of the same type, got {args}") + + +SetLoop = collections.namedtuple('SetLoop', ('index', 'entry', 'do_break')) + + +class _SetPayload(object): + + def __init__(self, context, builder, set_type, ptr): + payload = get_payload_struct(context, builder, set_type, ptr) + self._context = context + self._builder = builder + self._ty = set_type + self._payload = payload + self._entries = payload._get_ptr_by_name('entries') + self._ptr = ptr + + @property + def mask(self): + return self._payload.mask + + @mask.setter + def mask(self, value): + # CAUTION: mask must be a power of 2 minus 1 + self._payload.mask = value + + @property + def used(self): + return self._payload.used + + @used.setter + def used(self, value): + self._payload.used = value + + @property + def fill(self): + return self._payload.fill + + @fill.setter + def fill(self, value): + self._payload.fill = value + + @property + def finger(self): + return self._payload.finger + + @finger.setter + def finger(self, value): + self._payload.finger = value + + @property + def dirty(self): + return self._payload.dirty + + @dirty.setter + def dirty(self, value): + self._payload.dirty = value + + @property + def entries(self): + """ + A pointer to the start of the entries array. + """ + return self._entries + + @property + def ptr(self): + """ + A pointer to the start of the NRT-allocated area. + """ + return self._ptr + + def get_entry(self, idx): + """ + Get entry number *idx*. + """ + entry_ptr = cgutils.gep(self._builder, self._entries, idx) + entry = self._context.make_data_helper(self._builder, + types.SetEntry(self._ty), + ref=entry_ptr) + return entry + + def _lookup(self, item, h, for_insert=False): + """ + Lookup the *item* with the given hash values in the entries. + + Return a (found, entry index) tuple: + - If found is true, points to the entry containing + the item. + - If found is false, points to the empty entry that + the item can be written to (only if *for_insert* is true) + """ + context = self._context + builder = self._builder + + intp_t = h.type + + mask = self.mask + dtype = self._ty.dtype + tyctx = context.typing_context + fnty = tyctx.resolve_value_type(operator.eq) + sig = fnty.get_call_type(tyctx, (dtype, dtype), {}) + eqfn = context.get_function(fnty, sig) + + one = ir.Constant(intp_t, 1) + five = ir.Constant(intp_t, 5) + + # The perturbation value for probing + perturb = cgutils.alloca_once_value(builder, h) + # The index of the entry being considered: start with (hash & mask) + index = cgutils.alloca_once_value(builder, + builder.and_(h, mask)) + if for_insert: + # The index of the first deleted entry in the lookup chain + free_index_sentinel = mask.type(-1) # highest unsigned index + free_index = cgutils.alloca_once_value(builder, free_index_sentinel) + + bb_body = builder.append_basic_block("lookup.body") + bb_found = builder.append_basic_block("lookup.found") + bb_not_found = builder.append_basic_block("lookup.not_found") + bb_end = builder.append_basic_block("lookup.end") + + def check_entry(i): + """ + Check entry *i* against the value being searched for. + """ + entry = self.get_entry(i) + entry_hash = entry.hash + + with builder.if_then(builder.icmp_unsigned('==', h, entry_hash)): + # Hashes are equal, compare values + # (note this also ensures the entry is used) + eq = eqfn(builder, (item, entry.key)) + with builder.if_then(eq): + builder.branch(bb_found) + + with builder.if_then(is_hash_empty(context, builder, entry_hash)): + builder.branch(bb_not_found) + + if for_insert: + # Memorize the index of the first deleted entry + with builder.if_then(is_hash_deleted(context, builder, entry_hash)): + j = builder.load(free_index) + j = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel), + i, j) + builder.store(j, free_index) + + # First linear probing. When the number of collisions is small, + # the lineary probing loop achieves better cache locality and + # is also slightly cheaper computationally. + with cgutils.for_range(builder, ir.Constant(intp_t, LINEAR_PROBES)): + i = builder.load(index) + check_entry(i) + i = builder.add(i, one) + i = builder.and_(i, mask) + builder.store(i, index) + + # If not found after linear probing, switch to a non-linear + # perturbation keyed on the unmasked hash value. + # XXX how to tell LLVM this branch is unlikely? + builder.branch(bb_body) + with builder.goto_block(bb_body): + i = builder.load(index) + check_entry(i) + + # Perturb to go to next entry: + # perturb >>= 5 + # i = (i * 5 + 1 + perturb) & mask + p = builder.load(perturb) + p = builder.lshr(p, five) + i = builder.add(one, builder.mul(i, five)) + i = builder.and_(mask, builder.add(i, p)) + builder.store(i, index) + builder.store(p, perturb) + # Loop + builder.branch(bb_body) + + with builder.goto_block(bb_not_found): + if for_insert: + # Not found => for insertion, return the index of the first + # deleted entry (if any), to avoid creating an infinite + # lookup chain (issue #1913). + i = builder.load(index) + j = builder.load(free_index) + i = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel), + i, j) + builder.store(i, index) + builder.branch(bb_end) + + with builder.goto_block(bb_found): + builder.branch(bb_end) + + builder.position_at_end(bb_end) + + found = builder.phi(ir.IntType(1), 'found') + found.add_incoming(cgutils.true_bit, bb_found) + found.add_incoming(cgutils.false_bit, bb_not_found) + + return found, builder.load(index) + + @contextlib.contextmanager + def _iterate(self, start=None): + """ + Iterate over the payload's entries. Yield a SetLoop. + """ + context = self._context + builder = self._builder + + intp_t = context.get_value_type(types.intp) + one = ir.Constant(intp_t, 1) + size = builder.add(self.mask, one) + + with cgutils.for_range(builder, size, start=start) as range_loop: + entry = self.get_entry(range_loop.index) + is_used = is_hash_used(context, builder, entry.hash) + with builder.if_then(is_used): + loop = SetLoop(index=range_loop.index, entry=entry, + do_break=range_loop.do_break) + yield loop + + @contextlib.contextmanager + def _next_entry(self): + """ + Yield a random entry from the payload. Caller must ensure the + set isn't empty, otherwise the function won't end. + """ + context = self._context + builder = self._builder + + intp_t = context.get_value_type(types.intp) + zero = ir.Constant(intp_t, 0) + one = ir.Constant(intp_t, 1) + mask = self.mask + + # Start walking the entries from the stored "search finger" and + # break as soon as we find a used entry. + + bb_body = builder.append_basic_block('next_entry_body') + bb_end = builder.append_basic_block('next_entry_end') + + index = cgutils.alloca_once_value(builder, self.finger) + builder.branch(bb_body) + + with builder.goto_block(bb_body): + i = builder.load(index) + # ANDing with mask ensures we stay inside the table boundaries + i = builder.and_(mask, builder.add(i, one)) + builder.store(i, index) + entry = self.get_entry(i) + is_used = is_hash_used(context, builder, entry.hash) + builder.cbranch(is_used, bb_end, bb_body) + + builder.position_at_end(bb_end) + + # Update the search finger with the next position. This avoids + # O(n**2) behaviour when pop() is called in a loop. + i = builder.load(index) + self.finger = i + yield self.get_entry(i) + + +class SetInstance(object): + + def __init__(self, context, builder, set_type, set_val): + self._context = context + self._builder = builder + self._ty = set_type + self._entrysize = get_entry_size(context, set_type) + self._set = context.make_helper(builder, set_type, set_val) + + @property + def dtype(self): + return self._ty.dtype + + @property + def payload(self): + """ + The _SetPayload for this set. + """ + # This cannot be cached as the pointer can move around! + context = self._context + builder = self._builder + + ptr = self._context.nrt.meminfo_data(builder, self.meminfo) + return _SetPayload(context, builder, self._ty, ptr) + + @property + def value(self): + return self._set._getvalue() + + @property + def meminfo(self): + return self._set.meminfo + + @property + def parent(self): + return self._set.parent + + @parent.setter + def parent(self, value): + self._set.parent = value + + def get_size(self): + """ + Return the number of elements in the size. + """ + return self.payload.used + + def set_dirty(self, val): + if self._ty.reflected: + self.payload.dirty = cgutils.true_bit if val else cgutils.false_bit + + def _add_entry(self, payload, entry, item, h, do_resize=True): + context = self._context + builder = self._builder + + old_hash = entry.hash + entry.hash = h + self.incref_value(item) + entry.key = item + # used++ + used = payload.used + one = ir.Constant(used.type, 1) + used = payload.used = builder.add(used, one) + # fill++ if entry wasn't a deleted one + with builder.if_then(is_hash_empty(context, builder, old_hash), + likely=True): + payload.fill = builder.add(payload.fill, one) + # Grow table if necessary + if do_resize: + self.upsize(used) + self.set_dirty(True) + + def _add_key(self, payload, item, h, do_resize=True, do_incref=True): + context = self._context + builder = self._builder + + found, i = payload._lookup(item, h, for_insert=True) + not_found = builder.not_(found) + + with builder.if_then(not_found): + # Not found => add it + entry = payload.get_entry(i) + old_hash = entry.hash + entry.hash = h + if do_incref: + self.incref_value(item) + entry.key = item + # used++ + used = payload.used + one = ir.Constant(used.type, 1) + used = payload.used = builder.add(used, one) + # fill++ if entry wasn't a deleted one + with builder.if_then(is_hash_empty(context, builder, old_hash), + likely=True): + payload.fill = builder.add(payload.fill, one) + # Grow table if necessary + if do_resize: + self.upsize(used) + self.set_dirty(True) + + def _remove_entry(self, payload, entry, do_resize=True, do_decref=True): + # Mark entry deleted + entry.hash = ir.Constant(entry.hash.type, DELETED) + if do_decref: + self.decref_value(entry.key) + # used-- + used = payload.used + one = ir.Constant(used.type, 1) + used = payload.used = self._builder.sub(used, one) + # Shrink table if necessary + if do_resize: + self.downsize(used) + self.set_dirty(True) + + def _remove_key(self, payload, item, h, do_resize=True): + context = self._context + builder = self._builder + + found, i = payload._lookup(item, h) + + with builder.if_then(found): + entry = payload.get_entry(i) + self._remove_entry(payload, entry, do_resize) + + return found + + def add(self, item, do_resize=True): + context = self._context + builder = self._builder + + payload = self.payload + h = get_hash_value(context, builder, self._ty.dtype, item) + self._add_key(payload, item, h, do_resize) + + def add_pyapi(self, pyapi, item, do_resize=True): + """A version of .add for use inside functions following Python calling + convention. + """ + context = self._context + builder = self._builder + + payload = self.payload + h = self._pyapi_get_hash_value(pyapi, context, builder, item) + self._add_key(payload, item, h, do_resize) + + def _pyapi_get_hash_value(self, pyapi, context, builder, item): + """Python API compatible version of `get_hash_value()`. + """ + argtypes = [self._ty.dtype] + resty = types.intp + + def wrapper(val): + return _get_hash_value_intrinsic(val) + + args = [item] + sig = typing.signature(resty, *argtypes) + is_error, retval = pyapi.call_jit_code(wrapper, sig, args) + # Handle return status + with builder.if_then(is_error, likely=False): + # Raise nopython exception as a Python exception + builder.ret(pyapi.get_null_object()) + return retval + + def contains(self, item): + context = self._context + builder = self._builder + + payload = self.payload + h = get_hash_value(context, builder, self._ty.dtype, item) + found, i = payload._lookup(item, h) + return found + + def discard(self, item): + context = self._context + builder = self._builder + + payload = self.payload + h = get_hash_value(context, builder, self._ty.dtype, item) + found = self._remove_key(payload, item, h) + return found + + def pop(self): + context = self._context + builder = self._builder + + lty = context.get_value_type(self._ty.dtype) + key = cgutils.alloca_once(builder, lty) + + payload = self.payload + with payload._next_entry() as entry: + builder.store(entry.key, key) + # since the value is returned don't decref in _remove_entry() + self._remove_entry(payload, entry, do_decref=False) + + return builder.load(key) + + def clear(self): + context = self._context + builder = self._builder + + intp_t = context.get_value_type(types.intp) + minsize = ir.Constant(intp_t, MINSIZE) + self._replace_payload(minsize) + self.set_dirty(True) + + def copy(self): + """ + Return a copy of this set. + """ + context = self._context + builder = self._builder + + payload = self.payload + used = payload.used + fill = payload.fill + + other = type(self)(context, builder, self._ty, None) + + no_deleted_entries = builder.icmp_unsigned('==', used, fill) + with builder.if_else(no_deleted_entries, likely=True) \ + as (if_no_deleted, if_deleted): + with if_no_deleted: + # No deleted entries => raw copy the payload + ok = other._copy_payload(payload) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot copy set",)) + + with if_deleted: + # Deleted entries => re-insert entries one by one + nentries = self.choose_alloc_size(context, builder, used) + ok = other._allocate_payload(nentries) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot copy set",)) + + other_payload = other.payload + with payload._iterate() as loop: + entry = loop.entry + other._add_key(other_payload, entry.key, entry.hash, + do_resize=False) + + return other + + def intersect(self, other): + """ + In-place intersection with *other* set. + """ + context = self._context + builder = self._builder + payload = self.payload + other_payload = other.payload + + with payload._iterate() as loop: + entry = loop.entry + found, _ = other_payload._lookup(entry.key, entry.hash) + with builder.if_then(builder.not_(found)): + self._remove_entry(payload, entry, do_resize=False) + + # Final downsize + self.downsize(payload.used) + + def difference(self, other): + """ + In-place difference with *other* set. + """ + context = self._context + builder = self._builder + payload = self.payload + other_payload = other.payload + + with other_payload._iterate() as loop: + entry = loop.entry + self._remove_key(payload, entry.key, entry.hash, do_resize=False) + + # Final downsize + self.downsize(payload.used) + + def symmetric_difference(self, other): + """ + In-place symmetric difference with *other* set. + """ + context = self._context + builder = self._builder + other_payload = other.payload + + with other_payload._iterate() as loop: + key = loop.entry.key + h = loop.entry.hash + # We must reload our payload as it may be resized during the loop + payload = self.payload + found, i = payload._lookup(key, h, for_insert=True) + entry = payload.get_entry(i) + with builder.if_else(found) as (if_common, if_not_common): + with if_common: + self._remove_entry(payload, entry, do_resize=False) + with if_not_common: + self._add_entry(payload, entry, key, h) + + # Final downsize + self.downsize(self.payload.used) + + def issubset(self, other, strict=False): + context = self._context + builder = self._builder + payload = self.payload + other_payload = other.payload + + cmp_op = '<' if strict else '<=' + + res = cgutils.alloca_once_value(builder, cgutils.true_bit) + with builder.if_else( + builder.icmp_unsigned(cmp_op, payload.used, other_payload.used) + ) as (if_smaller, if_larger): + with if_larger: + # self larger than other => self cannot possibly a subset + builder.store(cgutils.false_bit, res) + with if_smaller: + # check whether each key of self is in other + with payload._iterate() as loop: + entry = loop.entry + found, _ = other_payload._lookup(entry.key, entry.hash) + with builder.if_then(builder.not_(found)): + builder.store(cgutils.false_bit, res) + loop.do_break() + + return builder.load(res) + + def isdisjoint(self, other): + context = self._context + builder = self._builder + payload = self.payload + other_payload = other.payload + + res = cgutils.alloca_once_value(builder, cgutils.true_bit) + + def check(smaller, larger): + # Loop over the smaller of the two, and search in the larger + with smaller._iterate() as loop: + entry = loop.entry + found, _ = larger._lookup(entry.key, entry.hash) + with builder.if_then(found): + builder.store(cgutils.false_bit, res) + loop.do_break() + + with builder.if_else( + builder.icmp_unsigned('>', payload.used, other_payload.used) + ) as (if_larger, otherwise): + + with if_larger: + # len(self) > len(other) + check(other_payload, payload) + + with otherwise: + # len(self) <= len(other) + check(payload, other_payload) + + return builder.load(res) + + def equals(self, other): + context = self._context + builder = self._builder + payload = self.payload + other_payload = other.payload + + res = cgutils.alloca_once_value(builder, cgutils.true_bit) + with builder.if_else( + builder.icmp_unsigned('==', payload.used, other_payload.used) + ) as (if_same_size, otherwise): + with if_same_size: + # same sizes => check whether each key of self is in other + with payload._iterate() as loop: + entry = loop.entry + found, _ = other_payload._lookup(entry.key, entry.hash) + with builder.if_then(builder.not_(found)): + builder.store(cgutils.false_bit, res) + loop.do_break() + with otherwise: + # different sizes => cannot possibly be equal + builder.store(cgutils.false_bit, res) + + return builder.load(res) + + @classmethod + def allocate_ex(cls, context, builder, set_type, nitems=None): + """ + Allocate a SetInstance with its storage. + Return a (ok, instance) tuple where *ok* is a LLVM boolean and + *instance* is a SetInstance object (the object's contents are + only valid when *ok* is true). + """ + intp_t = context.get_value_type(types.intp) + + if nitems is None: + nentries = ir.Constant(intp_t, MINSIZE) + else: + if isinstance(nitems, int): + nitems = ir.Constant(intp_t, nitems) + nentries = cls.choose_alloc_size(context, builder, nitems) + + self = cls(context, builder, set_type, None) + ok = self._allocate_payload(nentries) + return ok, self + + @classmethod + def allocate(cls, context, builder, set_type, nitems=None): + """ + Allocate a SetInstance with its storage. Same as allocate_ex(), + but return an initialized *instance*. If allocation failed, + control is transferred to the caller using the target's current + call convention. + """ + ok, self = cls.allocate_ex(context, builder, set_type, nitems) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot allocate set",)) + return self + + @classmethod + def from_meminfo(cls, context, builder, set_type, meminfo): + """ + Allocate a new set instance pointing to an existing payload + (a meminfo pointer). + Note the parent field has to be filled by the caller. + """ + self = cls(context, builder, set_type, None) + self._set.meminfo = meminfo + self._set.parent = context.get_constant_null(types.pyobject) + context.nrt.incref(builder, set_type, self.value) + # Payload is part of the meminfo, no need to touch it + return self + + @classmethod + def choose_alloc_size(cls, context, builder, nitems): + """ + Choose a suitable number of entries for the given number of items. + """ + intp_t = nitems.type + one = ir.Constant(intp_t, 1) + minsize = ir.Constant(intp_t, MINSIZE) + + # Ensure number of entries >= 2 * used + min_entries = builder.shl(nitems, one) + # Find out first suitable power of 2, starting from MINSIZE + size_p = cgutils.alloca_once_value(builder, minsize) + + bb_body = builder.append_basic_block("calcsize.body") + bb_end = builder.append_basic_block("calcsize.end") + + builder.branch(bb_body) + + with builder.goto_block(bb_body): + size = builder.load(size_p) + is_large_enough = builder.icmp_unsigned('>=', size, min_entries) + with builder.if_then(is_large_enough, likely=False): + builder.branch(bb_end) + next_size = builder.shl(size, one) + builder.store(next_size, size_p) + builder.branch(bb_body) + + builder.position_at_end(bb_end) + return builder.load(size_p) + + def upsize(self, nitems): + """ + When adding to the set, ensure it is properly sized for the given + number of used entries. + """ + context = self._context + builder = self._builder + intp_t = nitems.type + + one = ir.Constant(intp_t, 1) + two = ir.Constant(intp_t, 2) + + payload = self.payload + + # Ensure number of entries >= 2 * used + min_entries = builder.shl(nitems, one) + size = builder.add(payload.mask, one) + need_resize = builder.icmp_unsigned('>=', min_entries, size) + + with builder.if_then(need_resize, likely=False): + # Find out next suitable size + new_size_p = cgutils.alloca_once_value(builder, size) + + bb_body = builder.append_basic_block("calcsize.body") + bb_end = builder.append_basic_block("calcsize.end") + + builder.branch(bb_body) + + with builder.goto_block(bb_body): + # Multiply by 4 (ensuring size remains a power of two) + new_size = builder.load(new_size_p) + new_size = builder.shl(new_size, two) + builder.store(new_size, new_size_p) + is_too_small = builder.icmp_unsigned('>=', min_entries, new_size) + builder.cbranch(is_too_small, bb_body, bb_end) + + builder.position_at_end(bb_end) + + new_size = builder.load(new_size_p) + if DEBUG_ALLOCS: + context.printf(builder, + "upsize to %zd items: current size = %zd, " + "min entries = %zd, new size = %zd\n", + nitems, size, min_entries, new_size) + self._resize(payload, new_size, "cannot grow set") + + def downsize(self, nitems): + """ + When removing from the set, ensure it is properly sized for the given + number of used entries. + """ + context = self._context + builder = self._builder + intp_t = nitems.type + + one = ir.Constant(intp_t, 1) + two = ir.Constant(intp_t, 2) + minsize = ir.Constant(intp_t, MINSIZE) + + payload = self.payload + + # Ensure entries >= max(2 * used, MINSIZE) + min_entries = builder.shl(nitems, one) + min_entries = builder.select(builder.icmp_unsigned('>=', min_entries, minsize), + min_entries, minsize) + # Shrink only if size >= 4 * min_entries && size > MINSIZE + max_size = builder.shl(min_entries, two) + size = builder.add(payload.mask, one) + need_resize = builder.and_( + builder.icmp_unsigned('<=', max_size, size), + builder.icmp_unsigned('<', minsize, size)) + + with builder.if_then(need_resize, likely=False): + # Find out next suitable size + new_size_p = cgutils.alloca_once_value(builder, size) + + bb_body = builder.append_basic_block("calcsize.body") + bb_end = builder.append_basic_block("calcsize.end") + + builder.branch(bb_body) + + with builder.goto_block(bb_body): + # Divide by 2 (ensuring size remains a power of two) + new_size = builder.load(new_size_p) + new_size = builder.lshr(new_size, one) + # Keep current size if new size would be < min_entries + is_too_small = builder.icmp_unsigned('>', min_entries, new_size) + with builder.if_then(is_too_small): + builder.branch(bb_end) + builder.store(new_size, new_size_p) + builder.branch(bb_body) + + builder.position_at_end(bb_end) + + # Ensure new_size >= MINSIZE + new_size = builder.load(new_size_p) + # At this point, new_size should be < size if the factors + # above were chosen carefully! + + if DEBUG_ALLOCS: + context.printf(builder, + "downsize to %zd items: current size = %zd, " + "min entries = %zd, new size = %zd\n", + nitems, size, min_entries, new_size) + self._resize(payload, new_size, "cannot shrink set") + + def _resize(self, payload, nentries, errmsg): + """ + Resize the payload to the given number of entries. + + CAUTION: *nentries* must be a power of 2! + """ + context = self._context + builder = self._builder + + # Allocate new entries + old_payload = payload + + ok = self._allocate_payload(nentries, realloc=True) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + (errmsg,)) + + # Re-insert old entries + # No incref since they already were the first time they were inserted + payload = self.payload + with old_payload._iterate() as loop: + entry = loop.entry + self._add_key(payload, entry.key, entry.hash, + do_resize=False, do_incref=False) + + self._free_payload(old_payload.ptr) + + def _replace_payload(self, nentries): + """ + Replace the payload with a new empty payload with the given number + of entries. + + CAUTION: *nentries* must be a power of 2! + """ + context = self._context + builder = self._builder + + # decref all of the previous entries + with self.payload._iterate() as loop: + entry = loop.entry + self.decref_value(entry.key) + + # Free old payload + self._free_payload(self.payload.ptr) + + ok = self._allocate_payload(nentries, realloc=True) + with builder.if_then(builder.not_(ok), likely=False): + context.call_conv.return_user_exc(builder, MemoryError, + ("cannot reallocate set",)) + + def _allocate_payload(self, nentries, realloc=False): + """ + Allocate and initialize payload for the given number of entries. + If *realloc* is True, the existing meminfo is reused. + + CAUTION: *nentries* must be a power of 2! + """ + context = self._context + builder = self._builder + + ok = cgutils.alloca_once_value(builder, cgutils.true_bit) + + intp_t = context.get_value_type(types.intp) + zero = ir.Constant(intp_t, 0) + one = ir.Constant(intp_t, 1) + + payload_type = context.get_data_type(types.SetPayload(self._ty)) + payload_size = context.get_abi_sizeof(payload_type) + entry_size = self._entrysize + # Account for the fact that the payload struct already contains an entry + payload_size -= entry_size + + # Total allocation size = + nentries * entry_size + allocsize, ovf = cgutils.muladd_with_overflow(builder, nentries, + ir.Constant(intp_t, entry_size), + ir.Constant(intp_t, payload_size)) + with builder.if_then(ovf, likely=False): + builder.store(cgutils.false_bit, ok) + + with builder.if_then(builder.load(ok), likely=True): + if realloc: + meminfo = self._set.meminfo + ptr = context.nrt.meminfo_varsize_alloc_unchecked(builder, + meminfo, + size=allocsize) + alloc_ok = cgutils.is_null(builder, ptr) + else: + # create destructor to be called upon set destruction + dtor = self._imp_dtor(context, builder.module) + meminfo = context.nrt.meminfo_new_varsize_dtor_unchecked( + builder, allocsize, builder.bitcast(dtor, cgutils.voidptr_t)) + alloc_ok = cgutils.is_null(builder, meminfo) + + with builder.if_else(alloc_ok, + likely=False) as (if_error, if_ok): + with if_error: + builder.store(cgutils.false_bit, ok) + with if_ok: + if not realloc: + self._set.meminfo = meminfo + self._set.parent = context.get_constant_null(types.pyobject) + payload = self.payload + # Initialize entries to 0xff (EMPTY) + cgutils.memset(builder, payload.ptr, allocsize, 0xFF) + payload.used = zero + payload.fill = zero + payload.finger = zero + new_mask = builder.sub(nentries, one) + payload.mask = new_mask + + if DEBUG_ALLOCS: + context.printf(builder, + "allocated %zd bytes for set at %p: mask = %zd\n", + allocsize, payload.ptr, new_mask) + + return builder.load(ok) + + def _free_payload(self, ptr): + """ + Free an allocated old payload at *ptr*. + """ + self._context.nrt.meminfo_varsize_free(self._builder, self.meminfo, ptr) + + def _copy_payload(self, src_payload): + """ + Raw-copy the given payload into self. + """ + context = self._context + builder = self._builder + + ok = cgutils.alloca_once_value(builder, cgutils.true_bit) + + intp_t = context.get_value_type(types.intp) + zero = ir.Constant(intp_t, 0) + one = ir.Constant(intp_t, 1) + + payload_type = context.get_data_type(types.SetPayload(self._ty)) + payload_size = context.get_abi_sizeof(payload_type) + entry_size = self._entrysize + # Account for the fact that the payload struct already contains an entry + payload_size -= entry_size + + mask = src_payload.mask + nentries = builder.add(one, mask) + + # Total allocation size = + nentries * entry_size + # (note there can't be any overflow since we're reusing an existing + # payload's parameters) + allocsize = builder.add(ir.Constant(intp_t, payload_size), + builder.mul(ir.Constant(intp_t, entry_size), + nentries)) + + with builder.if_then(builder.load(ok), likely=True): + # create destructor for new meminfo + dtor = self._imp_dtor(context, builder.module) + meminfo = context.nrt.meminfo_new_varsize_dtor_unchecked( + builder, allocsize, builder.bitcast(dtor, cgutils.voidptr_t)) + alloc_ok = cgutils.is_null(builder, meminfo) + + with builder.if_else(alloc_ok, likely=False) as (if_error, if_ok): + with if_error: + builder.store(cgutils.false_bit, ok) + with if_ok: + self._set.meminfo = meminfo + payload = self.payload + payload.used = src_payload.used + payload.fill = src_payload.fill + payload.finger = zero + payload.mask = mask + + # instead of using `_add_key` for every entry, since the + # size of the new set is the same, we can just copy the + # data directly without having to re-compute the hash + cgutils.raw_memcpy(builder, payload.entries, + src_payload.entries, nentries, + entry_size) + # increment the refcounts to simulate `_add_key` for each + # element + with src_payload._iterate() as loop: + self.incref_value(loop.entry.key) + + if DEBUG_ALLOCS: + context.printf(builder, + "allocated %zd bytes for set at %p: mask = %zd\n", + allocsize, payload.ptr, mask) + + return builder.load(ok) + + def _imp_dtor(self, context, module): + """Define the dtor for set + """ + llvoidptr = cgutils.voidptr_t + llsize_t= context.get_value_type(types.size_t) + # create a dtor function that takes (void* set, size_t size, void* dtor_info) + fnty = ir.FunctionType( + ir.VoidType(), + [llvoidptr, llsize_t, llvoidptr], + ) + # create type-specific name + fname = f".dtor.set.{self._ty.dtype}" + + fn = cgutils.get_or_insert_function(module, fnty, name=fname) + + if fn.is_declaration: + # Set linkage + fn.linkage = 'linkonce_odr' + # Define + builder = ir.IRBuilder(fn.append_basic_block()) + payload = _SetPayload(context, builder, self._ty, fn.args[0]) + with payload._iterate() as loop: + entry = loop.entry + context.nrt.decref(builder, self._ty.dtype, entry.key) + builder.ret_void() + + return fn + + def incref_value(self, val): + """Incref an element value + """ + self._context.nrt.incref(self._builder, self._ty.dtype, val) + + def decref_value(self, val): + """Decref an element value + """ + self._context.nrt.decref(self._builder, self._ty.dtype, val) + + +class SetIterInstance(object): + + def __init__(self, context, builder, iter_type, iter_val): + self._context = context + self._builder = builder + self._ty = iter_type + self._iter = context.make_helper(builder, iter_type, iter_val) + ptr = self._context.nrt.meminfo_data(builder, self.meminfo) + self._payload = _SetPayload(context, builder, self._ty.container, ptr) + + @classmethod + def from_set(cls, context, builder, iter_type, set_val): + set_inst = SetInstance(context, builder, iter_type.container, set_val) + self = cls(context, builder, iter_type, None) + index = context.get_constant(types.intp, 0) + self._iter.index = cgutils.alloca_once_value(builder, index) + self._iter.meminfo = set_inst.meminfo + return self + + @property + def value(self): + return self._iter._getvalue() + + @property + def meminfo(self): + return self._iter.meminfo + + @property + def index(self): + return self._builder.load(self._iter.index) + + @index.setter + def index(self, value): + self._builder.store(value, self._iter.index) + + def iternext(self, result): + index = self.index + payload = self._payload + one = ir.Constant(index.type, 1) + + result.set_exhausted() + + with payload._iterate(start=index) as loop: + # An entry was found + entry = loop.entry + result.set_valid() + result.yield_(entry.key) + self.index = self._builder.add(loop.index, one) + loop.do_break() + + +#------------------------------------------------------------------------------- +# Constructors + +def build_set(context, builder, set_type, items): + """ + Build a set of the given type, containing the given items. + """ + nitems = len(items) + inst = SetInstance.allocate(context, builder, set_type, nitems) + + if nitems > 0: + + # Populate set. Inlining the insertion code for each item would be very + # costly, instead we create a LLVM array and iterate over it. + array = cgutils.pack_array(builder, items) + array_ptr = cgutils.alloca_once_value(builder, array) + + count = context.get_constant(types.intp, nitems) + with cgutils.for_range(builder, count) as loop: + item = builder.load(cgutils.gep(builder, array_ptr, 0, loop.index)) + inst.add(item) + + return impl_ret_new_ref(context, builder, set_type, inst.value) + + +@lower_builtin(set) +def set_empty_constructor(context, builder, sig, args): + set_type = sig.return_type + inst = SetInstance.allocate(context, builder, set_type) + return impl_ret_new_ref(context, builder, set_type, inst.value) + +@lower_builtin(set, types.IterableType) +def set_constructor(context, builder, sig, args): + set_type = sig.return_type + items_type, = sig.args + items, = args + + # If the argument has a len(), preallocate the set so as to + # avoid resizes. + # `for_iter` increfs each item in the set, so a `decref` is required each + # iteration to balance. Because the `incref` from `.add` is dependent on + # the item not already existing in the set, just removing its incref is not + # enough to guarantee all memory is freed + n = call_len(context, builder, items_type, items) + inst = SetInstance.allocate(context, builder, set_type, n) + with for_iter(context, builder, items_type, items) as loop: + inst.add(loop.value) + context.nrt.decref(builder, set_type.dtype, loop.value) + + return impl_ret_new_ref(context, builder, set_type, inst.value) + + +#------------------------------------------------------------------------------- +# Various operations + +@lower_builtin(len, types.Set) +def set_len(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + return inst.get_size() + +@lower_builtin(operator.contains, types.Set, types.Any) +def in_set(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + return inst.contains(args[1]) + +@lower_builtin('getiter', types.Set) +def getiter_set(context, builder, sig, args): + inst = SetIterInstance.from_set(context, builder, sig.return_type, args[0]) + return impl_ret_borrowed(context, builder, sig.return_type, inst.value) + +@lower_builtin('iternext', types.SetIter) +@iternext_impl(RefType.BORROWED) +def iternext_listiter(context, builder, sig, args, result): + inst = SetIterInstance(context, builder, sig.args[0], args[0]) + inst.iternext(result) + + +#------------------------------------------------------------------------------- +# Methods + +# One-item-at-a-time operations + +@lower_builtin("set.add", types.Set, types.Any) +def set_add(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + item = args[1] + inst.add(item) + + return context.get_dummy_value() + + +@intrinsic +def _set_discard(typingctx, s, item): + sig = types.none(s, item) + + def set_discard(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + item = args[1] + inst.discard(item) + + return context.get_dummy_value() + + return sig, set_discard + + +@overload_method(types.Set, "discard") +def ol_set_discard(s, item): + return lambda s, item: _set_discard(s, item) + + +@intrinsic +def _set_pop(typingctx, s): + sig = s.dtype(s) + + def set_pop(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + used = inst.payload.used + with builder.if_then(cgutils.is_null(builder, used), likely=False): + context.call_conv.return_user_exc(builder, KeyError, + ("set.pop(): empty set",)) + + return inst.pop() + + return sig, set_pop + + +@overload_method(types.Set, "pop") +def ol_set_pop(s): + return lambda s: _set_pop(s) + + +@intrinsic +def _set_remove(typingctx, s, item): + sig = types.none(s, item) + + def set_remove(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + item = args[1] + found = inst.discard(item) + with builder.if_then(builder.not_(found), likely=False): + context.call_conv.return_user_exc(builder, KeyError, + ("set.remove(): key not in set",)) + + return context.get_dummy_value() + + return sig, set_remove + + +@overload_method(types.Set, "remove") +def ol_set_remove(s, item): + if s.dtype == item: + return lambda s, item: _set_remove(s, item) + + +# Mutating set operations + +@intrinsic +def _set_clear(typingctx, s): + sig = types.none(s) + + def set_clear(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + inst.clear() + return context.get_dummy_value() + + return sig, set_clear + + +@overload_method(types.Set, "clear") +def ol_set_clear(s): + return lambda s: _set_clear(s) + + +@intrinsic +def _set_copy(typingctx, s): + sig = s(s) + + def set_copy(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = inst.copy() + return impl_ret_new_ref(context, builder, sig.return_type, other.value) + + return sig, set_copy + + +@overload_method(types.Set, "copy") +def ol_set_copy(s): + return lambda s: _set_copy(s) + + +def set_difference_update(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + + inst.difference(other) + + return context.get_dummy_value() + + +@intrinsic +def _set_difference_update(typingctx, a, b): + sig = types.none(a, b) + return sig, set_difference_update + + +@overload_method(types.Set, "difference_update") +def set_difference_update_impl(a, b): + check_all_set(a, b) + return lambda a, b: _set_difference_update(a, b) + + +def set_intersection_update(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + inst.intersect(other) + return context.get_dummy_value() + + +@intrinsic +def _set_intersection_update(typingctx, a, b): + sig = types.none(a, b) + return sig, set_intersection_update + + +@overload_method(types.Set, "intersection_update") +def set_intersection_update_impl(a, b): + check_all_set(a, b) + return lambda a, b: _set_intersection_update(a, b) + + +def set_symmetric_difference_update(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + inst.symmetric_difference(other) + return context.get_dummy_value() + + +@intrinsic +def _set_symmetric_difference_update(typingctx, a, b): + sig = types.none(a, b) + return sig, set_symmetric_difference_update + + +@overload_method(types.Set, "symmetric_difference_update") +def set_symmetric_difference_update_impl(a, b): + check_all_set(a, b) + return lambda a, b: _set_symmetric_difference_update(a, b) + + +@lower_builtin("set.update", types.Set, types.IterableType) +def set_update(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + items_type = sig.args[1] + items = args[1] + + # If the argument has a len(), assume there are few collisions and + # presize to len(set) + len(items) + n = call_len(context, builder, items_type, items) + if n is not None: + new_size = builder.add(inst.payload.used, n) + inst.upsize(new_size) + + with for_iter(context, builder, items_type, items) as loop: + # make sure that the items being added are of the same dtype as the + # set instance + casted = context.cast(builder, loop.value, items_type.dtype, inst.dtype) + inst.add(casted) + # decref each item to counter balance the incref from `for_iter` + # `.add` will conditionally incref when the item does not already exist + # in the set, therefore removing its incref is not enough to guarantee + # all memory is freed + context.nrt.decref(builder, items_type.dtype, loop.value) + + if n is not None: + # If we pre-grew the set, downsize in case there were many collisions + inst.downsize(inst.payload.used) + + return context.get_dummy_value() + +def gen_operator_impl(op, impl): + @intrinsic + def _set_operator_intr(typingctx, a, b): + sig = a(a, b) + def codegen(context, builder, sig, args): + assert sig.return_type == sig.args[0] + impl(context, builder, sig, args) + return impl_ret_borrowed(context, builder, sig.args[0], args[0]) + return sig, codegen + + @overload(op) + def _ol_set_operator(a, b): + check_all_set(a, b) + return lambda a, b: _set_operator_intr(a, b) + + +for op_, op_impl in [ + (operator.iand, set_intersection_update), + (operator.ior, set_update), + (operator.isub, set_difference_update), + (operator.ixor, set_symmetric_difference_update), + ]: + gen_operator_impl(op_, op_impl) + + +# Set operations creating a new set + +@overload(operator.sub) +@overload_method(types.Set, "difference") +def impl_set_difference(a, b): + check_all_set(a, b) + + def difference_impl(a, b): + s = a.copy() + s.difference_update(b) + return s + + return difference_impl + +@overload(operator.and_) +@overload_method(types.Set, "intersection") +def set_intersection(a, b): + check_all_set(a, b) + + def intersection_impl(a, b): + if len(a) < len(b): + s = a.copy() + s.intersection_update(b) + return s + else: + s = b.copy() + s.intersection_update(a) + return s + + return intersection_impl + +@overload(operator.xor) +@overload_method(types.Set, "symmetric_difference") +def set_symmetric_difference(a, b): + check_all_set(a, b) + + def symmetric_difference_impl(a, b): + if len(a) > len(b): + s = a.copy() + s.symmetric_difference_update(b) + return s + else: + s = b.copy() + s.symmetric_difference_update(a) + return s + + return symmetric_difference_impl + +@overload(operator.or_) +@overload_method(types.Set, "union") +def set_union(a, b): + check_all_set(a, b) + + def union_impl(a, b): + if len(a) > len(b): + s = a.copy() + s.update(b) + return s + else: + s = b.copy() + s.update(a) + return s + + return union_impl + + +# Predicates + +@intrinsic +def _set_isdisjoint(typingctx, a, b): + sig = types.boolean(a, b) + + def codegen(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + + return inst.isdisjoint(other) + + return sig, codegen + + +@overload_method(types.Set, "isdisjoint") +def set_isdisjoint(a, b): + check_all_set(a, b) + + return lambda a, b: _set_isdisjoint(a, b) + + +@intrinsic +def _set_issubset(typingctx, a, b): + sig = types.boolean(a, b) + + def codegen(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + + return inst.issubset(other) + + return sig, codegen + +@overload(operator.le) +@overload_method(types.Set, "issubset") +def set_issubset(a, b): + check_all_set(a, b) + + return lambda a, b: _set_issubset(a, b) + + +@overload(operator.ge) +@overload_method(types.Set, "issuperset") +def set_issuperset(a, b): + check_all_set(a, b) + + def superset_impl(a, b): + return b.issubset(a) + + return superset_impl + +@intrinsic +def _set_eq(typingctx, a, b): + sig = types.boolean(a, b) + + def codegen(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + + return inst.equals(other) + + return sig, codegen + +@overload(operator.eq) +def set_eq(a, b): + check_all_set(a, b) + + return lambda a, b: _set_eq(a, b) + +@overload(operator.ne) +def set_ne(a, b): + check_all_set(a, b) + + def ne_impl(a, b): + return not a == b + + return ne_impl + +@intrinsic +def _set_lt(typingctx, a, b): + sig = types.boolean(a, b) + + def codegen(context, builder, sig, args): + inst = SetInstance(context, builder, sig.args[0], args[0]) + other = SetInstance(context, builder, sig.args[1], args[1]) + + return inst.issubset(other, strict=True) + + return sig, codegen + +@overload(operator.lt) +def set_lt(a, b): + check_all_set(a, b) + + return lambda a, b: _set_lt(a, b) + +@overload(operator.gt) +def set_gt(a, b): + check_all_set(a, b) + + def gt_impl(a, b): + return b < a + + return gt_impl + +@lower_builtin(operator.is_, types.Set, types.Set) +def set_is(context, builder, sig, args): + a = SetInstance(context, builder, sig.args[0], args[0]) + b = SetInstance(context, builder, sig.args[1], args[1]) + ma = builder.ptrtoint(a.meminfo, cgutils.intp_t) + mb = builder.ptrtoint(b.meminfo, cgutils.intp_t) + return builder.icmp_signed('==', ma, mb) + + +# ----------------------------------------------------------------------------- +# Implicit casting + +@lower_cast(types.Set, types.Set) +def set_to_set(context, builder, fromty, toty, val): + # Casting from non-reflected to reflected + assert fromty.dtype == toty.dtype + return val diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/slicing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c38e2d97992d1dc5565f8c7e61c3b866c3ac75 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/slicing.py @@ -0,0 +1,302 @@ +""" +Implement slices and various slice computations. +""" + +from itertools import zip_longest + +from llvmlite import ir +from numba.core import cgutils, types, typing, utils +from numba.core.imputils import (impl_ret_borrowed, impl_ret_new_ref, + impl_ret_untracked, iternext_impl, + lower_builtin, lower_cast, lower_constant, + lower_getattr) + + +def fix_index(builder, idx, size): + """ + Fix negative index by adding *size* to it. Positive + indices are left untouched. + """ + is_negative = builder.icmp_signed('<', idx, ir.Constant(size.type, 0)) + wrapped_index = builder.add(idx, size) + return builder.select(is_negative, wrapped_index, idx) + + +def fix_slice(builder, slice, size): + """ + Fix *slice* start and stop to be valid (inclusive and exclusive, resp) + indexing bounds for a sequence of the given *size*. + """ + # See PySlice_GetIndicesEx() + zero = ir.Constant(size.type, 0) + minus_one = ir.Constant(size.type, -1) + + def fix_bound(bound_name, lower_repl, upper_repl): + bound = getattr(slice, bound_name) + bound = fix_index(builder, bound, size) + # Store value + setattr(slice, bound_name, bound) + # Still negative? => clamp to lower_repl + underflow = builder.icmp_signed('<', bound, zero) + with builder.if_then(underflow, likely=False): + setattr(slice, bound_name, lower_repl) + # Greater than size? => clamp to upper_repl + overflow = builder.icmp_signed('>=', bound, size) + with builder.if_then(overflow, likely=False): + setattr(slice, bound_name, upper_repl) + + with builder.if_else(cgutils.is_neg_int(builder, slice.step)) as (if_neg_step, if_pos_step): + with if_pos_step: + # < 0 => 0; >= size => size + fix_bound('start', zero, size) + fix_bound('stop', zero, size) + with if_neg_step: + # < 0 => -1; >= size => size - 1 + lower = minus_one + upper = builder.add(size, minus_one) + fix_bound('start', lower, upper) + fix_bound('stop', lower, upper) + + +def get_slice_length(builder, slicestruct): + """ + Given a slice, compute the number of indices it spans, i.e. the + number of iterations that for_range_slice() will execute. + + Pseudo-code: + assert step != 0 + if step > 0: + if stop <= start: + return 0 + else: + return (stop - start - 1) // step + 1 + else: + if stop >= start: + return 0 + else: + return (stop - start + 1) // step + 1 + + (see PySlice_GetIndicesEx() in CPython) + """ + start = slicestruct.start + stop = slicestruct.stop + step = slicestruct.step + one = ir.Constant(start.type, 1) + zero = ir.Constant(start.type, 0) + + is_step_negative = cgutils.is_neg_int(builder, step) + delta = builder.sub(stop, start) + + # Nominal case + pos_dividend = builder.sub(delta, one) + neg_dividend = builder.add(delta, one) + dividend = builder.select(is_step_negative, neg_dividend, pos_dividend) + nominal_length = builder.add(one, builder.sdiv(dividend, step)) + + # Catch zero length + is_zero_length = builder.select(is_step_negative, + builder.icmp_signed('>=', delta, zero), + builder.icmp_signed('<=', delta, zero)) + + # Clamp to 0 if is_zero_length + return builder.select(is_zero_length, zero, nominal_length) + + +def get_slice_bounds(builder, slicestruct): + """ + Return the [lower, upper) indexing bounds of a slice. + """ + start = slicestruct.start + stop = slicestruct.stop + zero = start.type(0) + one = start.type(1) + # This is a bit pessimal, e.g. it will return [1, 5) instead + # of [1, 4) for `1:5:2` + is_step_negative = builder.icmp_signed('<', slicestruct.step, zero) + lower = builder.select(is_step_negative, + builder.add(stop, one), start) + upper = builder.select(is_step_negative, + builder.add(start, one), stop) + return lower, upper + + +def fix_stride(builder, slice, stride): + """ + Fix the given stride for the slice's step. + """ + return builder.mul(slice.step, stride) + +def guard_invalid_slice(context, builder, typ, slicestruct): + """ + Guard against *slicestruct* having a zero step (and raise ValueError). + """ + if typ.has_step: + cgutils.guard_null(context, builder, slicestruct.step, + (ValueError, "slice step cannot be zero")) + + +def get_defaults(context): + """ + Get the default values for a slice's members: + (start for positive step, start for negative step, + stop for positive step, stop for negative step, step) + """ + maxint = (1 << (context.address_size - 1)) - 1 + return (0, maxint, maxint, - maxint - 1, 1) + + +#--------------------------------------------------------------------------- +# The slice structure + +@lower_builtin(slice, types.VarArg(types.Any)) +def slice_constructor_impl(context, builder, sig, args): + ( + default_start_pos, + default_start_neg, + default_stop_pos, + default_stop_neg, + default_step, + ) = [context.get_constant(types.intp, x) for x in get_defaults(context)] + + slice_args = [None] * 3 + + # Fetch non-None arguments + if len(args) == 1 and sig.args[0] is not types.none: + slice_args[1] = args[0] + else: + for i, (ty, val) in enumerate(zip(sig.args, args)): + if ty is not types.none: + slice_args[i] = val + + # Fill omitted arguments + def get_arg_value(i, default): + val = slice_args[i] + if val is None: + return default + else: + return val + + step = get_arg_value(2, default_step) + is_step_negative = builder.icmp_signed('<', step, + context.get_constant(types.intp, 0)) + default_stop = builder.select(is_step_negative, + default_stop_neg, default_stop_pos) + default_start = builder.select(is_step_negative, + default_start_neg, default_start_pos) + stop = get_arg_value(1, default_stop) + start = get_arg_value(0, default_start) + + ty = sig.return_type + sli = context.make_helper(builder, sig.return_type) + sli.start = start + sli.stop = stop + sli.step = step + + res = sli._getvalue() + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_getattr(types.SliceType, "start") +def slice_start_impl(context, builder, typ, value): + sli = context.make_helper(builder, typ, value) + return sli.start + +@lower_getattr(types.SliceType, "stop") +def slice_stop_impl(context, builder, typ, value): + sli = context.make_helper(builder, typ, value) + return sli.stop + +@lower_getattr(types.SliceType, "step") +def slice_step_impl(context, builder, typ, value): + if typ.has_step: + sli = context.make_helper(builder, typ, value) + return sli.step + else: + return context.get_constant(types.intp, 1) + + +@lower_builtin("slice.indices", types.SliceType, types.Integer) +def slice_indices(context, builder, sig, args): + length = args[1] + sli = context.make_helper(builder, sig.args[0], args[0]) + + with builder.if_then(cgutils.is_neg_int(builder, length), likely=False): + context.call_conv.return_user_exc( + builder, ValueError, + ("length should not be negative",) + ) + with builder.if_then(cgutils.is_scalar_zero(builder, sli.step), likely=False): + context.call_conv.return_user_exc( + builder, ValueError, + ("slice step cannot be zero",) + ) + + fix_slice(builder, sli, length) + + return context.make_tuple( + builder, + sig.return_type, + (sli.start, sli.stop, sli.step) + ) + + +def make_slice_from_constant(context, builder, ty, pyval): + sli = context.make_helper(builder, ty) + lty = context.get_value_type(types.intp) + + ( + default_start_pos, + default_start_neg, + default_stop_pos, + default_stop_neg, + default_step, + ) = [context.get_constant(types.intp, x) for x in get_defaults(context)] + + step = pyval.step + if step is None: + step_is_neg = False + step = default_step + else: + step_is_neg = step < 0 + step = lty(step) + + start = pyval.start + if start is None: + if step_is_neg: + start = default_start_neg + else: + start = default_start_pos + else: + start = lty(start) + + stop = pyval.stop + if stop is None: + if step_is_neg: + stop = default_stop_neg + else: + stop = default_stop_pos + else: + stop = lty(stop) + + sli.start = start + sli.stop = stop + sli.step = step + + return sli._getvalue() + + +@lower_constant(types.SliceType) +def constant_slice(context, builder, ty, pyval): + if isinstance(ty, types.Literal): + typ = ty.literal_type + else: + typ = ty + + return make_slice_from_constant(context, builder, typ, pyval) + + +@lower_cast(types.misc.SliceLiteral, types.SliceType) +def cast_from_literal(context, builder, fromty, toty, val): + return make_slice_from_constant( + context, builder, toty, fromty.literal_value, + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/tupleobj.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/tupleobj.py new file mode 100644 index 0000000000000000000000000000000000000000..7a76fea0e2ef9d4002be876f927aae454550e97e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/tupleobj.py @@ -0,0 +1,412 @@ +""" +Implementation of tuple objects +""" + +import operator + +from numba.core.imputils import (lower_builtin, lower_getattr_generic, + lower_cast, lower_constant, iternext_impl, + impl_ret_borrowed, impl_ret_untracked, + RefType) +from numba.core import typing, types, cgutils +from numba.core.extending import overload_method, overload, intrinsic + + +@lower_builtin(types.NamedTupleClass, types.VarArg(types.Any)) +def namedtuple_constructor(context, builder, sig, args): + # A namedtuple has the same representation as a regular tuple + # the arguments need casting (lower_cast) from the types in the ctor args + # to those in the ctor return type, this is to handle cases such as a + # literal present in the args, but a type present in the return type. + newargs = [] + for i, arg in enumerate(args): + casted = context.cast(builder, arg, sig.args[i], sig.return_type[i]) + newargs.append(casted) + res = context.make_tuple(builder, sig.return_type, tuple(newargs)) + # The tuple's contents are borrowed + return impl_ret_borrowed(context, builder, sig.return_type, res) + +@lower_builtin(operator.add, types.BaseTuple, types.BaseTuple) +def tuple_add(context, builder, sig, args): + left, right = [cgutils.unpack_tuple(builder, x) for x in args] + res = context.make_tuple(builder, sig.return_type, left + right) + # The tuple's contents are borrowed + return impl_ret_borrowed(context, builder, sig.return_type, res) + +def tuple_cmp_ordered(context, builder, op, sig, args): + tu, tv = sig.args + u, v = args + res = cgutils.alloca_once_value(builder, cgutils.true_bit) + bbend = builder.append_basic_block("cmp_end") + for i, (ta, tb) in enumerate(zip(tu.types, tv.types)): + a = builder.extract_value(u, i) + b = builder.extract_value(v, i) + not_equal = context.generic_compare(builder, operator.ne, (ta, tb), (a, b)) + with builder.if_then(not_equal): + pred = context.generic_compare(builder, op, (ta, tb), (a, b)) + builder.store(pred, res) + builder.branch(bbend) + # Everything matched equal => compare lengths + len_compare = op(len(tu.types), len(tv.types)) + pred = context.get_constant(types.boolean, len_compare) + builder.store(pred, res) + builder.branch(bbend) + builder.position_at_end(bbend) + return builder.load(res) + + +@lower_builtin(operator.eq, types.BaseTuple, types.BaseTuple) +def tuple_eq(context, builder, sig, args): + tu, tv = sig.args + u, v = args + if len(tu.types) != len(tv.types): + res = context.get_constant(types.boolean, False) + return impl_ret_untracked(context, builder, sig.return_type, res) + res = context.get_constant(types.boolean, True) + for i, (ta, tb) in enumerate(zip(tu.types, tv.types)): + a = builder.extract_value(u, i) + b = builder.extract_value(v, i) + pred = context.generic_compare(builder, operator.eq, (ta, tb), (a, b)) + res = builder.and_(res, pred) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(operator.ne, types.BaseTuple, types.BaseTuple) +def tuple_ne(context, builder, sig, args): + res = builder.not_(tuple_eq(context, builder, sig, args)) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(operator.lt, types.BaseTuple, types.BaseTuple) +def tuple_lt(context, builder, sig, args): + res = tuple_cmp_ordered(context, builder, operator.lt, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(operator.le, types.BaseTuple, types.BaseTuple) +def tuple_le(context, builder, sig, args): + res = tuple_cmp_ordered(context, builder, operator.le, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(operator.gt, types.BaseTuple, types.BaseTuple) +def tuple_gt(context, builder, sig, args): + res = tuple_cmp_ordered(context, builder, operator.gt, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +@lower_builtin(operator.ge, types.BaseTuple, types.BaseTuple) +def tuple_ge(context, builder, sig, args): + res = tuple_cmp_ordered(context, builder, operator.ge, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# for hashing see hashing.py + +@lower_getattr_generic(types.BaseNamedTuple) +def namedtuple_getattr(context, builder, typ, value, attr): + """ + Fetch a namedtuple's field. + """ + index = typ.fields.index(attr) + res = builder.extract_value(value, index) + return impl_ret_borrowed(context, builder, typ[index], res) + + +@lower_constant(types.UniTuple) +@lower_constant(types.NamedUniTuple) +def unituple_constant(context, builder, ty, pyval): + """ + Create a homogeneous tuple constant. + """ + consts = [context.get_constant_generic(builder, ty.dtype, v) + for v in pyval] + return impl_ret_borrowed( + context, builder, ty, cgutils.pack_array(builder, consts), + ) + +@lower_constant(types.Tuple) +@lower_constant(types.NamedTuple) +def unituple_constant(context, builder, ty, pyval): + """ + Create a heterogeneous tuple constant. + """ + consts = [context.get_constant_generic(builder, ty.types[i], v) + for i, v in enumerate(pyval)] + return impl_ret_borrowed( + context, builder, ty, cgutils.pack_struct(builder, consts), + ) + + +#------------------------------------------------------------------------------ +# Tuple iterators + +@lower_builtin('getiter', types.UniTuple) +@lower_builtin('getiter', types.NamedUniTuple) +def getiter_unituple(context, builder, sig, args): + [tupty] = sig.args + [tup] = args + + iterval = context.make_helper(builder, types.UniTupleIter(tupty)) + + index0 = context.get_constant(types.intp, 0) + indexptr = cgutils.alloca_once(builder, index0.type) + builder.store(index0, indexptr) + + iterval.index = indexptr + iterval.tuple = tup + + res = iterval._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('iternext', types.UniTupleIter) +@iternext_impl(RefType.BORROWED) +def iternext_unituple(context, builder, sig, args, result): + [tupiterty] = sig.args + [tupiter] = args + + iterval = context.make_helper(builder, tupiterty, value=tupiter) + + tup = iterval.tuple + idxptr = iterval.index + idx = builder.load(idxptr) + count = context.get_constant(types.intp, tupiterty.container.count) + + is_valid = builder.icmp_signed('<', idx, count) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + getitem_sig = typing.signature(tupiterty.container.dtype, + tupiterty.container, + types.intp) + getitem_out = getitem_unituple(context, builder, getitem_sig, + [tup, idx]) + # As a iternext_impl function, this will incref the yieled value. + # We need to release the new reference from getitem_unituple. + if context.enable_nrt: + context.nrt.decref(builder, tupiterty.container.dtype, getitem_out) + result.yield_(getitem_out) + nidx = builder.add(idx, context.get_constant(types.intp, 1)) + builder.store(nidx, iterval.index) + + +@overload(operator.getitem) +def getitem_literal_idx(tup, idx): + """ + Overloads BaseTuple getitem to cover cases where constant + inference and RewriteConstGetitems cannot replace it + with a static_getitem. + """ + if not (isinstance(tup, types.BaseTuple) + and isinstance(idx, types.IntegerLiteral)): + return None + + idx_val = idx.literal_value + def getitem_literal_idx_impl(tup, idx): + return tup[idx_val] + + return getitem_literal_idx_impl + + +@lower_builtin('typed_getitem', types.BaseTuple, types.Any) +def getitem_typed(context, builder, sig, args): + tupty, _ = sig.args + tup, idx = args + errmsg_oob = ("tuple index out of range",) + + if len(tupty) == 0: + # Empty tuple. + + # Always branch and raise IndexError + with builder.if_then(cgutils.true_bit): + context.call_conv.return_user_exc(builder, IndexError, + errmsg_oob) + # This is unreachable in runtime, + # but it exists to not terminate the current basicblock. + res = context.get_constant_null(sig.return_type) + return impl_ret_untracked(context, builder, + sig.return_type, res) + else: + # The tuple is not empty + + bbelse = builder.append_basic_block("typed_switch.else") + bbend = builder.append_basic_block("typed_switch.end") + switch = builder.switch(idx, bbelse) + + with builder.goto_block(bbelse): + context.call_conv.return_user_exc(builder, IndexError, + errmsg_oob) + + lrtty = context.get_value_type(sig.return_type) + voidptrty = context.get_value_type(types.voidptr) + with builder.goto_block(bbend): + phinode = builder.phi(voidptrty) + + for i in range(tupty.count): + ki = context.get_constant(types.intp, i) + bbi = builder.append_basic_block("typed_switch.%d" % i) + switch.add_case(ki, bbi) + # handle negative indexing, create case (-tuple.count + i) to + # reference same block as i + kin = context.get_constant(types.intp, -tupty.count + i) + switch.add_case(kin, bbi) + with builder.goto_block(bbi): + value = builder.extract_value(tup, i) + # Dragon warning... + # The fact the code has made it this far suggests that type + # inference decided whatever was being done with the item pulled + # from the tuple was legitimate, it is not the job of lowering + # to argue about that. However, here lies a problem, the tuple + # lowering is implemented as a switch table with each case + # writing to a phi node slot that is returned. The type of this + # phi node slot needs to be "correct" for the current type but + # it also needs to survive stores being made to it from the + # other cases that will in effect never run. To do this a stack + # slot is made for each case for the specific type and then cast + # to a void pointer type, this is then added as an incoming on + # the phi node, at the end of the switch the phi node is then + # cast back to the required return type for this typed_getitem. + # The only further complication is that if the value is not a + # pointer then the void* juggle won't work so a cast is made + # prior to store, again, that type inference has permitted it + # suggests this is safe. + # End Dragon warning... + DOCAST = context.typing_context.unify_types(sig.args[0][i], + sig.return_type) == sig.return_type + if DOCAST: + value_slot = builder.alloca(lrtty, + name="TYPED_VALUE_SLOT%s" % i) + casted = context.cast(builder, value, sig.args[0][i], + sig.return_type) + builder.store(casted, value_slot) + else: + value_slot = builder.alloca(value.type, + name="TYPED_VALUE_SLOT%s" % i) + builder.store(value, value_slot) + phinode.add_incoming(builder.bitcast(value_slot, voidptrty), + bbi) + builder.branch(bbend) + + builder.position_at_end(bbend) + res = builder.bitcast(phinode, lrtty.as_pointer()) + res = builder.load(res) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(operator.getitem, types.UniTuple, types.intp) +@lower_builtin(operator.getitem, types.UniTuple, types.uintp) +@lower_builtin(operator.getitem, types.NamedUniTuple, types.intp) +@lower_builtin(operator.getitem, types.NamedUniTuple, types.uintp) +def getitem_unituple(context, builder, sig, args): + tupty, _ = sig.args + tup, idx = args + + errmsg_oob = ("tuple index out of range",) + + if len(tupty) == 0: + # Empty tuple. + + # Always branch and raise IndexError + with builder.if_then(cgutils.true_bit): + context.call_conv.return_user_exc(builder, IndexError, + errmsg_oob) + # This is unreachable in runtime, + # but it exists to not terminate the current basicblock. + res = context.get_constant_null(sig.return_type) + return impl_ret_untracked(context, builder, + sig.return_type, res) + else: + # The tuple is not empty + bbelse = builder.append_basic_block("switch.else") + bbend = builder.append_basic_block("switch.end") + switch = builder.switch(idx, bbelse) + + with builder.goto_block(bbelse): + context.call_conv.return_user_exc(builder, IndexError, + errmsg_oob) + + lrtty = context.get_value_type(tupty.dtype) + with builder.goto_block(bbend): + phinode = builder.phi(lrtty) + + for i in range(tupty.count): + ki = context.get_constant(types.intp, i) + bbi = builder.append_basic_block("switch.%d" % i) + switch.add_case(ki, bbi) + # handle negative indexing, create case (-tuple.count + i) to + # reference same block as i + kin = context.get_constant(types.intp, -tupty.count + i) + switch.add_case(kin, bbi) + with builder.goto_block(bbi): + value = builder.extract_value(tup, i) + builder.branch(bbend) + phinode.add_incoming(value, bbi) + + builder.position_at_end(bbend) + res = phinode + assert sig.return_type == tupty.dtype + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('static_getitem', types.LiteralStrKeyDict, types.StringLiteral) +@lower_builtin('static_getitem', types.LiteralList, types.IntegerLiteral) +@lower_builtin('static_getitem', types.LiteralList, types.SliceLiteral) +@lower_builtin('static_getitem', types.BaseTuple, types.IntegerLiteral) +@lower_builtin('static_getitem', types.BaseTuple, types.SliceLiteral) +def static_getitem_tuple(context, builder, sig, args): + tupty, idxty = sig.args + tup, idx = args + if isinstance(idx, int): + if idx < 0: + idx += len(tupty) + if not 0 <= idx < len(tupty): + raise IndexError("cannot index at %d in %s" % (idx, tupty)) + res = builder.extract_value(tup, idx) + elif isinstance(idx, slice): + items = cgutils.unpack_tuple(builder, tup)[idx] + res = context.make_tuple(builder, sig.return_type, items) + elif isinstance(tupty, types.LiteralStrKeyDict): + # pretend to be a dictionary + idx_val = idxty.literal_value + idx_offset = tupty.fields.index(idx_val) + res = builder.extract_value(tup, idx_offset) + else: + raise NotImplementedError("unexpected index %r for %s" + % (idx, sig.args[0])) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +#------------------------------------------------------------------------------ +# Implicit conversion + +@lower_cast(types.BaseTuple, types.BaseTuple) +def tuple_to_tuple(context, builder, fromty, toty, val): + if (isinstance(fromty, types.BaseNamedTuple) + or isinstance(toty, types.BaseNamedTuple)): + # Disallowed by typing layer + raise NotImplementedError + + if len(fromty) != len(toty): + # Disallowed by typing layer + raise NotImplementedError + + olditems = cgutils.unpack_tuple(builder, val, len(fromty)) + items = [context.cast(builder, v, f, t) + for v, f, t in zip(olditems, fromty, toty)] + return context.make_tuple(builder, toty, items) + + +#------------------------------------------------------------------------------ +# Methods + +@overload_method(types.BaseTuple, 'index') +def tuple_index(tup, value): + + def tuple_index_impl(tup, value): + for i in range(len(tup)): + if tup[i] == value: + return i + raise ValueError("tuple.index(x): x not in tuple") + + return tuple_index_impl + + +@overload(operator.contains) +def in_seq_empty_tuple(x, y): + if isinstance(x, types.Tuple) and not x.types: + return lambda x, y: False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5725bba9394190b98bb76606379077c594ad5c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode.py @@ -0,0 +1,2672 @@ +import sys +import operator + +import numpy as np +from llvmlite.ir import IntType, Constant + +from numba.core.cgutils import is_nonelike +from numba.core.extending import ( + models, + register_model, + make_attribute_wrapper, + unbox, + box, + NativeValue, + overload, + overload_method, + intrinsic, + register_jitable, +) +from numba.core.imputils import (lower_constant, lower_cast, lower_builtin, + iternext_impl, impl_ret_new_ref, RefType) +from numba.core.datamodel import register_default, StructModel +from numba.core import types, cgutils +from numba.core.utils import PYVERSION +from numba.core.pythonapi import ( + PY_UNICODE_1BYTE_KIND, + PY_UNICODE_2BYTE_KIND, + PY_UNICODE_4BYTE_KIND, +) +from numba._helperlib import c_helpers +from numba.cpython.hashing import _Py_hash_t +from numba.core.unsafe.bytes import memcpy_region +from numba.core.errors import TypingError +from numba.cpython.unicode_support import (_Py_TOUPPER, _Py_TOLOWER, _Py_UCS4, + _Py_ISALNUM, + _PyUnicode_ToUpperFull, + _PyUnicode_ToLowerFull, + _PyUnicode_ToFoldedFull, + _PyUnicode_ToTitleFull, + _PyUnicode_IsPrintable, + _PyUnicode_IsSpace, + _Py_ISSPACE, + _PyUnicode_IsXidStart, + _PyUnicode_IsXidContinue, + _PyUnicode_IsCased, + _PyUnicode_IsCaseIgnorable, + _PyUnicode_IsUppercase, + _PyUnicode_IsLowercase, + _PyUnicode_IsLineBreak, + _Py_ISLINEBREAK, + _Py_ISLINEFEED, + _Py_ISCARRIAGERETURN, + _PyUnicode_IsTitlecase, + _Py_ISLOWER, + _Py_ISUPPER, + _Py_TAB, + _Py_LINEFEED, + _Py_CARRIAGE_RETURN, + _Py_SPACE, + _PyUnicode_IsAlpha, + _PyUnicode_IsNumeric, + _Py_ISALPHA, + _PyUnicode_IsDigit, + _PyUnicode_IsDecimalDigit) +from numba.cpython import slicing + +if PYVERSION in ((3, 10), (3, 11)): + from numba.core.pythonapi import PY_UNICODE_WCHAR_KIND + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L84-L85 # noqa: E501 +_MAX_UNICODE = 0x10ffff + +# https://github.com/python/cpython/blob/1960eb005e04b7ad8a91018088cfdb0646bc1ca0/Objects/stringlib/fastsearch.h#L31 # noqa: E501 +_BLOOM_WIDTH = types.intp.bitwidth + +# DATA MODEL + + +@register_model(types.UnicodeType) +class UnicodeModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('data', types.voidptr), + ('length', types.intp), + ('kind', types.int32), + ('is_ascii', types.uint32), + ('hash', _Py_hash_t), + ('meminfo', types.MemInfoPointer(types.voidptr)), + # A pointer to the owner python str/unicode object + ('parent', types.pyobject), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + + +make_attribute_wrapper(types.UnicodeType, 'data', '_data') +make_attribute_wrapper(types.UnicodeType, 'length', '_length') +make_attribute_wrapper(types.UnicodeType, 'kind', '_kind') +make_attribute_wrapper(types.UnicodeType, 'is_ascii', '_is_ascii') +make_attribute_wrapper(types.UnicodeType, 'hash', '_hash') + + +@register_default(types.UnicodeIteratorType) +class UnicodeIteratorModel(StructModel): + def __init__(self, dmm, fe_type): + members = [('index', types.EphemeralPointer(types.uintp)), + ('data', fe_type.data)] + super(UnicodeIteratorModel, self).__init__(dmm, fe_type, members) + +# CAST + + +def compile_time_get_string_data(obj): + """Get string data from a python string for use at compile-time to embed + the string data into the LLVM module. + """ + from ctypes import ( + CFUNCTYPE, c_void_p, c_int, c_uint, c_ssize_t, c_ubyte, py_object, + POINTER, byref, + ) + + extract_unicode_fn = c_helpers['extract_unicode'] + proto = CFUNCTYPE(c_void_p, py_object, POINTER(c_ssize_t), POINTER(c_int), + POINTER(c_uint), POINTER(c_ssize_t)) + fn = proto(extract_unicode_fn) + length = c_ssize_t() + kind = c_int() + is_ascii = c_uint() + hashv = c_ssize_t() + data = fn(obj, byref(length), byref(kind), byref(is_ascii), byref(hashv)) + if data is None: + raise ValueError("cannot extract unicode data from the given string") + length = length.value + kind = kind.value + is_ascii = is_ascii.value + nbytes = (length + 1) * _kind_to_byte_width(kind) + out = (c_ubyte * nbytes).from_address(data) + return bytes(out), length, kind, is_ascii, hashv.value + + +def make_string_from_constant(context, builder, typ, literal_string): + """ + Get string data by `compile_time_get_string_data()` and return a + unicode_type LLVM value + """ + databytes, length, kind, is_ascii, hashv = \ + compile_time_get_string_data(literal_string) + mod = builder.module + gv = context.insert_const_bytes(mod, databytes) + uni_str = cgutils.create_struct_proxy(typ)(context, builder) + uni_str.data = gv + uni_str.length = uni_str.length.type(length) + uni_str.kind = uni_str.kind.type(kind) + uni_str.is_ascii = uni_str.is_ascii.type(is_ascii) + # Set hash to -1 to indicate that it should be computed. + # We cannot bake in the hash value because of hashseed randomization. + uni_str.hash = uni_str.hash.type(-1) + return uni_str._getvalue() + + +@lower_cast(types.StringLiteral, types.unicode_type) +def cast_from_literal(context, builder, fromty, toty, val): + return make_string_from_constant( + context, builder, toty, fromty.literal_value, + ) + + +# CONSTANT + +@lower_constant(types.unicode_type) +def constant_unicode(context, builder, typ, pyval): + return make_string_from_constant(context, builder, typ, pyval) + + +# BOXING + + +@unbox(types.UnicodeType) +def unbox_unicode_str(typ, obj, c): + """ + Convert a unicode str object to a native unicode structure. + """ + ok, data, length, kind, is_ascii, hashv = \ + c.pyapi.string_as_string_size_and_kind(obj) + uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder) + uni_str.data = data + uni_str.length = length + uni_str.kind = kind + uni_str.is_ascii = is_ascii + uni_str.hash = hashv + uni_str.meminfo = c.pyapi.nrt_meminfo_new_from_pyobject( + data, # the borrowed data pointer + obj, # the owner pyobject; the call will incref it. + ) + uni_str.parent = obj + + is_error = cgutils.is_not_null(c.builder, c.pyapi.err_occurred()) + return NativeValue(uni_str._getvalue(), is_error=is_error) + + +@box(types.UnicodeType) +def box_unicode_str(typ, val, c): + """ + Convert a native unicode structure to a unicode string + """ + uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val) + res = c.pyapi.string_from_kind_and_data( + uni_str.kind, uni_str.data, uni_str.length) + # hash isn't needed now, just compute it so it ends up in the unicodeobject + # hash cache, cpython doesn't always do this, depends how a string was + # created it's safe, just burns the cycles required to hash on @box + c.pyapi.object_hash(res) + c.context.nrt.decref(c.builder, typ, val) + return res + + +# HELPER FUNCTIONS + + +def make_deref_codegen(bitsize): + def codegen(context, builder, signature, args): + data, idx = args + ptr = builder.bitcast(data, IntType(bitsize).as_pointer()) + ch = builder.load(builder.gep(ptr, [idx])) + return builder.zext(ch, IntType(32)) + + return codegen + + +@intrinsic +def deref_uint8(typingctx, data, offset): + sig = types.uint32(types.voidptr, types.intp) + return sig, make_deref_codegen(8) + + +@intrinsic +def deref_uint16(typingctx, data, offset): + sig = types.uint32(types.voidptr, types.intp) + return sig, make_deref_codegen(16) + + +@intrinsic +def deref_uint32(typingctx, data, offset): + sig = types.uint32(types.voidptr, types.intp) + return sig, make_deref_codegen(32) + + +@intrinsic +def _malloc_string(typingctx, kind, char_bytes, length, is_ascii): + """make empty string with data buffer of size alloc_bytes. + + Must set length and kind values for string after it is returned + """ + def details(context, builder, signature, args): + [kind_val, char_bytes_val, length_val, is_ascii_val] = args + + # fill the struct + uni_str_ctor = cgutils.create_struct_proxy(types.unicode_type) + uni_str = uni_str_ctor(context, builder) + # add null padding character + nbytes_val = builder.mul(char_bytes_val, + builder.add(length_val, + Constant(length_val.type, 1))) + uni_str.meminfo = context.nrt.meminfo_alloc(builder, nbytes_val) + uni_str.kind = kind_val + uni_str.is_ascii = is_ascii_val + uni_str.length = length_val + # empty string has hash value -1 to indicate "need to compute hash" + uni_str.hash = context.get_constant(_Py_hash_t, -1) + uni_str.data = context.nrt.meminfo_data(builder, uni_str.meminfo) + # Set parent to NULL + uni_str.parent = cgutils.get_null_value(uni_str.parent.type) + return uni_str._getvalue() + + sig = types.unicode_type(types.int32, types.intp, types.intp, types.uint32) + return sig, details + + +@register_jitable +def _empty_string(kind, length, is_ascii=0): + char_width = _kind_to_byte_width(kind) + s = _malloc_string(kind, char_width, length, is_ascii) + _set_code_point(s, length, np.uint32(0)) # Write NULL character + return s + + +# Disable RefCt for performance. +@register_jitable(_nrt=False) +def _get_code_point(a, i): + if a._kind == PY_UNICODE_1BYTE_KIND: + return deref_uint8(a._data, i) + elif a._kind == PY_UNICODE_2BYTE_KIND: + return deref_uint16(a._data, i) + elif a._kind == PY_UNICODE_4BYTE_KIND: + return deref_uint32(a._data, i) + else: + # there's also a wchar kind, but that's one of the above, + # so skipping for this example + return 0 + +#### + + +def make_set_codegen(bitsize): + def codegen(context, builder, signature, args): + data, idx, ch = args + if bitsize < 32: + ch = builder.trunc(ch, IntType(bitsize)) + ptr = builder.bitcast(data, IntType(bitsize).as_pointer()) + builder.store(ch, builder.gep(ptr, [idx])) + return context.get_dummy_value() + + return codegen + + +@intrinsic +def set_uint8(typingctx, data, idx, ch): + sig = types.void(types.voidptr, types.int64, types.uint32) + return sig, make_set_codegen(8) + + +@intrinsic +def set_uint16(typingctx, data, idx, ch): + sig = types.void(types.voidptr, types.int64, types.uint32) + return sig, make_set_codegen(16) + + +@intrinsic +def set_uint32(typingctx, data, idx, ch): + sig = types.void(types.voidptr, types.int64, types.uint32) + return sig, make_set_codegen(32) + + +@register_jitable(_nrt=False) +def _set_code_point(a, i, ch): + # WARNING: This method is very dangerous: + # * Assumes that data contents can be changed (only allowed for new + # strings) + # * Assumes that the kind of unicode string is sufficiently wide to + # accept ch. Will truncate ch to make it fit. + # * Assumes that i is within the valid boundaries of the function + if a._kind == PY_UNICODE_1BYTE_KIND: + set_uint8(a._data, i, ch) + elif a._kind == PY_UNICODE_2BYTE_KIND: + set_uint16(a._data, i, ch) + elif a._kind == PY_UNICODE_4BYTE_KIND: + set_uint32(a._data, i, ch) + else: + raise AssertionError( + "Unexpected unicode representation in _set_code_point") + + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + @register_jitable + def _pick_kind(kind1, kind2): + if kind1 == PY_UNICODE_1BYTE_KIND: + return kind2 + elif kind1 == PY_UNICODE_2BYTE_KIND: + if kind2 == PY_UNICODE_4BYTE_KIND: + return kind2 + else: + return kind1 + elif kind1 == PY_UNICODE_4BYTE_KIND: + return kind1 + else: + raise AssertionError( + "Unexpected unicode representation in _pick_kind") +elif PYVERSION in ((3, 10), (3, 11)): + @register_jitable + def _pick_kind(kind1, kind2): + if (kind1 == PY_UNICODE_WCHAR_KIND or kind2 == PY_UNICODE_WCHAR_KIND): + raise AssertionError("PY_UNICODE_WCHAR_KIND unsupported") + + if kind1 == PY_UNICODE_1BYTE_KIND: + return kind2 + elif kind1 == PY_UNICODE_2BYTE_KIND: + if kind2 == PY_UNICODE_4BYTE_KIND: + return kind2 + else: + return kind1 + elif kind1 == PY_UNICODE_4BYTE_KIND: + return kind1 + else: + raise AssertionError( + "Unexpected unicode representation in _pick_kind") +else: + raise NotImplementedError(PYVERSION) + + +@register_jitable +def _pick_ascii(is_ascii1, is_ascii2): + if is_ascii1 == 1 and is_ascii2 == 1: + return types.uint32(1) + return types.uint32(0) + + +if PYVERSION in ((3, 12), (3, 13), (3, 14)): + @register_jitable + def _kind_to_byte_width(kind): + if kind == PY_UNICODE_1BYTE_KIND: + return 1 + elif kind == PY_UNICODE_2BYTE_KIND: + return 2 + elif kind == PY_UNICODE_4BYTE_KIND: + return 4 + else: + raise AssertionError("Unexpected unicode encoding encountered") +elif PYVERSION in ((3, 10), (3, 11)): + @register_jitable + def _kind_to_byte_width(kind): + if kind == PY_UNICODE_1BYTE_KIND: + return 1 + elif kind == PY_UNICODE_2BYTE_KIND: + return 2 + elif kind == PY_UNICODE_4BYTE_KIND: + return 4 + elif kind == PY_UNICODE_WCHAR_KIND: + raise AssertionError("PY_UNICODE_WCHAR_KIND unsupported") + else: + raise AssertionError("Unexpected unicode encoding encountered") +else: + raise NotImplementedError(PYVERSION) + + +@register_jitable(_nrt=False) +def _cmp_region(a, a_offset, b, b_offset, n): + if n == 0: + return 0 + elif a_offset + n > a._length: + return -1 + elif b_offset + n > b._length: + return 1 + + for i in range(n): + a_chr = _get_code_point(a, a_offset + i) + b_chr = _get_code_point(b, b_offset + i) + if a_chr < b_chr: + return -1 + elif a_chr > b_chr: + return 1 + + return 0 + + +@register_jitable +def _codepoint_to_kind(cp): + """ + Compute the minimum unicode kind needed to hold a given codepoint + """ + if cp < 256: + return PY_UNICODE_1BYTE_KIND + elif cp < 65536: + return PY_UNICODE_2BYTE_KIND + else: + # Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) + MAX_UNICODE = 0x10ffff + if cp > MAX_UNICODE: + msg = "Invalid codepoint. Found value greater than Unicode maximum" + raise ValueError(msg) + return PY_UNICODE_4BYTE_KIND + + +@register_jitable +def _codepoint_is_ascii(ch): + """ + Returns true if a codepoint is in the ASCII range + """ + return ch < 128 + + +# PUBLIC API + + +@overload(len) +def unicode_len(s): + if isinstance(s, types.UnicodeType): + def len_impl(s): + return s._length + return len_impl + + +@overload(operator.eq) +def unicode_eq(a, b): + if not (a.is_internal and b.is_internal): + return + if isinstance(a, types.Optional): + check_a = a.type + else: + check_a = a + if isinstance(b, types.Optional): + check_b = b.type + else: + check_b = b + accept = (types.UnicodeType, types.StringLiteral, types.UnicodeCharSeq) + a_unicode = isinstance(check_a, accept) + b_unicode = isinstance(check_b, accept) + if a_unicode and b_unicode: + def eq_impl(a, b): + # handle Optionals at runtime + a_none = a is None + b_none = b is None + if a_none or b_none: + if a_none and b_none: + return True + else: + return False + # the str() is for UnicodeCharSeq, it's a nop else + a = str(a) + b = str(b) + if len(a) != len(b): + return False + return _cmp_region(a, 0, b, 0, len(a)) == 0 + return eq_impl + elif a_unicode ^ b_unicode: + # one of the things is unicode, everything compares False + def eq_impl(a, b): + return False + return eq_impl + + +@overload(operator.ne) +def unicode_ne(a, b): + if not (a.is_internal and b.is_internal): + return + accept = (types.UnicodeType, types.StringLiteral, types.UnicodeCharSeq) + a_unicode = isinstance(a, accept) + b_unicode = isinstance(b, accept) + if a_unicode and b_unicode: + def ne_impl(a, b): + return not (a == b) + return ne_impl + elif a_unicode ^ b_unicode: + # one of the things is unicode, everything compares True + def eq_impl(a, b): + return True + return eq_impl + + +@overload(operator.lt) +def unicode_lt(a, b): + a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral)) + b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral)) + if a_unicode and b_unicode: + def lt_impl(a, b): + minlen = min(len(a), len(b)) + eqcode = _cmp_region(a, 0, b, 0, minlen) + if eqcode == -1: + return True + elif eqcode == 0: + return len(a) < len(b) + return False + return lt_impl + + +@overload(operator.gt) +def unicode_gt(a, b): + a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral)) + b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral)) + if a_unicode and b_unicode: + def gt_impl(a, b): + minlen = min(len(a), len(b)) + eqcode = _cmp_region(a, 0, b, 0, minlen) + if eqcode == 1: + return True + elif eqcode == 0: + return len(a) > len(b) + return False + return gt_impl + + +@overload(operator.le) +def unicode_le(a, b): + a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral)) + b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral)) + if a_unicode and b_unicode: + def le_impl(a, b): + return not (a > b) + return le_impl + + +@overload(operator.ge) +def unicode_ge(a, b): + a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral)) + b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral)) + if a_unicode and b_unicode: + def ge_impl(a, b): + return not (a < b) + return ge_impl + + +@overload(operator.contains) +def unicode_contains(a, b): + if isinstance(a, types.UnicodeType) and isinstance(b, types.UnicodeType): + def contains_impl(a, b): + # note parameter swap: contains(a, b) == b in a + return _find(a, b) > -1 + return contains_impl + + +def unicode_idx_check_type(ty, name): + """Check object belongs to one of specific types + ty: type + Type of the object + name: str + Name of the object + """ + thety = ty + # if the type is omitted, the concrete type is the value + if isinstance(ty, types.Omitted): + thety = ty.value + # if the type is optional, the concrete type is the captured type + elif isinstance(ty, types.Optional): + thety = ty.type + + accepted = (types.Integer, types.NoneType) + if thety is not None and not isinstance(thety, accepted): + raise TypingError('"{}" must be {}, not {}'.format(name, accepted, ty)) + + +def unicode_sub_check_type(ty, name): + """Check object belongs to unicode type""" + if not isinstance(ty, types.UnicodeType): + msg = '"{}" must be {}, not {}'.format(name, types.UnicodeType, ty) + raise TypingError(msg) + + +# FAST SEARCH algorithm implementation from cpython + +@register_jitable +def _bloom_add(mask, ch): + mask |= (1 << (ch & (_BLOOM_WIDTH - 1))) + return mask + + +@register_jitable +def _bloom_check(mask, ch): + return mask & (1 << (ch & (_BLOOM_WIDTH - 1))) + + +# https://github.com/python/cpython/blob/1960eb005e04b7ad8a91018088cfdb0646bc1ca0/Objects/stringlib/fastsearch.h#L550 # noqa: E501 +@register_jitable +def _default_find(data, substr, start, end): + """Left finder.""" + m = len(substr) + if m == 0: + return start + + gap = mlast = m - 1 + last = _get_code_point(substr, mlast) + + zero = types.intp(0) + mask = _bloom_add(zero, last) + for i in range(mlast): + ch = _get_code_point(substr, i) + mask = _bloom_add(mask, ch) + if ch == last: + gap = mlast - i - 1 + + i = start + while i <= end - m: + ch = _get_code_point(data, mlast + i) + if ch == last: + j = 0 + while j < mlast: + haystack_ch = _get_code_point(data, i + j) + needle_ch = _get_code_point(substr, j) + if haystack_ch != needle_ch: + break + j += 1 + if j == mlast: + # got a match + return i + + ch = _get_code_point(data, mlast + i + 1) + if _bloom_check(mask, ch) == 0: + i += m + else: + i += gap + else: + ch = _get_code_point(data, mlast + i + 1) + if _bloom_check(mask, ch) == 0: + i += m + i += 1 + + return -1 + + +@register_jitable +def _default_rfind(data, substr, start, end): + """Right finder.""" + m = len(substr) + if m == 0: + return end + + skip = mlast = m - 1 + mfirst = _get_code_point(substr, 0) + mask = _bloom_add(0, mfirst) + i = mlast + while i > 0: + ch = _get_code_point(substr, i) + mask = _bloom_add(mask, ch) + if ch == mfirst: + skip = i - 1 + i -= 1 + + i = end - m + while i >= start: + ch = _get_code_point(data, i) + if ch == mfirst: + j = mlast + while j > 0: + haystack_ch = _get_code_point(data, i + j) + needle_ch = _get_code_point(substr, j) + if haystack_ch != needle_ch: + break + j -= 1 + + if j == 0: + # got a match + return i + + ch = _get_code_point(data, i - 1) + if i > start and _bloom_check(mask, ch) == 0: + i -= m + else: + i -= skip + + else: + ch = _get_code_point(data, i - 1) + if i > start and _bloom_check(mask, ch) == 0: + i -= m + i -= 1 + + return -1 + + +def generate_finder(find_func): + """Generate finder either left or right.""" + def impl(data, substr, start=None, end=None): + length = len(data) + sub_length = len(substr) + if start is None: + start = 0 + if end is None: + end = length + + start, end = _adjust_indices(length, start, end) + if end - start < sub_length: + return -1 + + return find_func(data, substr, start, end) + + return impl + + +_find = register_jitable(generate_finder(_default_find)) +_rfind = register_jitable(generate_finder(_default_rfind)) + + +@overload_method(types.UnicodeType, 'find') +def unicode_find(data, substr, start=None, end=None): + """Implements str.find()""" + if isinstance(substr, types.UnicodeCharSeq): + def find_impl(data, substr, start=None, end=None): + return data.find(str(substr)) + return find_impl + + unicode_idx_check_type(start, 'start') + unicode_idx_check_type(end, 'end') + unicode_sub_check_type(substr, 'substr') + + return _find + + +@overload_method(types.UnicodeType, 'rfind') +def unicode_rfind(data, substr, start=None, end=None): + """Implements str.rfind()""" + if isinstance(substr, types.UnicodeCharSeq): + def rfind_impl(data, substr, start=None, end=None): + return data.rfind(str(substr)) + return rfind_impl + + unicode_idx_check_type(start, 'start') + unicode_idx_check_type(end, 'end') + unicode_sub_check_type(substr, 'substr') + + return _rfind + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12831-L12857 # noqa: E501 +@overload_method(types.UnicodeType, 'rindex') +def unicode_rindex(s, sub, start=None, end=None): + """Implements str.rindex()""" + unicode_idx_check_type(start, 'start') + unicode_idx_check_type(end, 'end') + unicode_sub_check_type(sub, 'sub') + + def rindex_impl(s, sub, start=None, end=None): + result = s.rfind(sub, start, end) + if result < 0: + raise ValueError('substring not found') + + return result + + return rindex_impl + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11692-L11718 # noqa: E501 +@overload_method(types.UnicodeType, 'index') +def unicode_index(s, sub, start=None, end=None): + """Implements str.index()""" + unicode_idx_check_type(start, 'start') + unicode_idx_check_type(end, 'end') + unicode_sub_check_type(sub, 'sub') + + def index_impl(s, sub, start=None, end=None): + result = s.find(sub, start, end) + if result < 0: + raise ValueError('substring not found') + + return result + + return index_impl + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12922-L12976 # noqa: E501 +@overload_method(types.UnicodeType, 'partition') +def unicode_partition(data, sep): + """Implements str.partition()""" + thety = sep + # if the type is omitted, the concrete type is the value + if isinstance(sep, types.Omitted): + thety = sep.value + # if the type is optional, the concrete type is the captured type + elif isinstance(sep, types.Optional): + thety = sep.type + + accepted = (types.UnicodeType, types.UnicodeCharSeq) + if thety is not None and not isinstance(thety, accepted): + msg = '"{}" must be {}, not {}'.format('sep', accepted, sep) + raise TypingError(msg) + + def impl(data, sep): + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/partition.h#L7-L60 # noqa: E501 + sep = str(sep) + empty_str = _empty_string(data._kind, 0, data._is_ascii) + sep_length = len(sep) + if data._kind < sep._kind or len(data) < sep_length: + return data, empty_str, empty_str + + if sep_length == 0: + raise ValueError('empty separator') + + pos = data.find(sep) + if pos < 0: + return data, empty_str, empty_str + + return data[0:pos], sep, data[pos + sep_length:len(data)] + + return impl + + +@overload_method(types.UnicodeType, 'count') +def unicode_count(src, sub, start=None, end=None): + + _count_args_types_check(start) + _count_args_types_check(end) + + if isinstance(sub, types.UnicodeType): + def count_impl(src, sub, start=None, end=None): + count = 0 + src_len = len(src) + sub_len = len(sub) + + start = _normalize_slice_idx_count(start, src_len, 0) + end = _normalize_slice_idx_count(end, src_len, src_len) + + if end - start < 0 or start > src_len: + return 0 + + src = src[start : end] + src_len = len(src) + start, end = 0, src_len + if sub_len == 0: + return src_len + 1 + + while (start + sub_len <= src_len): + if src[start : start + sub_len] == sub: + count += 1 + start += sub_len + else: + start += 1 + return count + return count_impl + error_msg = "The substring must be a UnicodeType, not {}" + raise TypingError(error_msg.format(type(sub))) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12979-L13033 # noqa: E501 +@overload_method(types.UnicodeType, 'rpartition') +def unicode_rpartition(data, sep): + """Implements str.rpartition()""" + thety = sep + # if the type is omitted, the concrete type is the value + if isinstance(sep, types.Omitted): + thety = sep.value + # if the type is optional, the concrete type is the captured type + elif isinstance(sep, types.Optional): + thety = sep.type + + accepted = (types.UnicodeType, types.UnicodeCharSeq) + if thety is not None and not isinstance(thety, accepted): + msg = '"{}" must be {}, not {}'.format('sep', accepted, sep) + raise TypingError(msg) + + def impl(data, sep): + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/partition.h#L62-L115 # noqa: E501 + sep = str(sep) + empty_str = _empty_string(data._kind, 0, data._is_ascii) + sep_length = len(sep) + if data._kind < sep._kind or len(data) < sep_length: + return empty_str, empty_str, data + + if sep_length == 0: + raise ValueError('empty separator') + + pos = data.rfind(sep) + if pos < 0: + return empty_str, empty_str, data + + return data[0:pos], sep, data[pos + sep_length:len(data)] + + return impl + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9342-L9354 # noqa: E501 +@register_jitable +def _adjust_indices(length, start, end): + if end > length: + end = length + if end < 0: + end += length + if end < 0: + end = 0 + if start < 0: + start += length + if start < 0: + start = 0 + + return start, end + + +@overload_method(types.UnicodeType, 'startswith') +def unicode_startswith(s, prefix, start=None, end=None): + if not is_nonelike(start) and not isinstance(start, types.Integer): + raise TypingError( + "When specified, the arg 'start' must be an Integer or None") + + if not is_nonelike(end) and not isinstance(end, types.Integer): + raise TypingError( + "When specified, the arg 'end' must be an Integer or None") + + if isinstance(prefix, types.UniTuple) and \ + isinstance(prefix.dtype, types.UnicodeType): + + def startswith_tuple_impl(s, prefix, start=None, end=None): + for item in prefix: + if s.startswith(item, start, end): + return True + return False + + return startswith_tuple_impl + + elif isinstance(prefix, types.UnicodeCharSeq): + def startswith_char_seq_impl(s, prefix, start=None, end=None): + return s.startswith(str(prefix), start, end) + + return startswith_char_seq_impl + + elif isinstance(prefix, types.UnicodeType): + def startswith_unicode_impl(s, prefix, start=None, end=None): + length, prefix_length = len(s), len(prefix) + if start is None: + start = 0 + if end is None: + end = length + + start, end = _adjust_indices(length, start, end) + if end - start < prefix_length: + return False + + if prefix_length == 0: + return True + + s_slice = s[start:end] + + return _cmp_region(s_slice, 0, prefix, 0, prefix_length) == 0 + + return startswith_unicode_impl + + else: + raise TypingError( + "The arg 'prefix' should be a string or a tuple of strings") + + +@overload_method(types.UnicodeType, 'endswith') +def unicode_endswith(s, substr, start=None, end=None): + if not (start is None or isinstance(start, (types.Omitted, + types.Integer, + types.NoneType))): + raise TypingError('The arg must be a Integer or None') + + if not (end is None or isinstance(end, (types.Omitted, + types.Integer, + types.NoneType))): + raise TypingError('The arg must be a Integer or None') + + if isinstance(substr, (types.Tuple, types.UniTuple)): + def endswith_impl(s, substr, start=None, end=None): + for item in substr: + if s.endswith(item, start, end) is True: + return True + + return False + return endswith_impl + + if isinstance(substr, types.UnicodeType): + def endswith_impl(s, substr, start=None, end=None): + length = len(s) + sub_length = len(substr) + if start is None: + start = 0 + if end is None: + end = length + + start, end = _adjust_indices(length, start, end) + if end - start < sub_length: + return False + + if sub_length == 0: + return True + + s = s[start:end] + offset = len(s) - sub_length + + return _cmp_region(s, offset, substr, 0, sub_length) == 0 + return endswith_impl + + if isinstance(substr, types.UnicodeCharSeq): + def endswith_impl(s, substr, start=None, end=None): + return s.endswith(str(substr), start, end) + return endswith_impl + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11519-L11595 # noqa: E501 +@overload_method(types.UnicodeType, 'expandtabs') +def unicode_expandtabs(data, tabsize=8): + """Implements str.expandtabs()""" + thety = tabsize + # if the type is omitted, the concrete type is the value + if isinstance(tabsize, types.Omitted): + thety = tabsize.value + # if the type is optional, the concrete type is the captured type + elif isinstance(tabsize, types.Optional): + thety = tabsize.type + + accepted = (types.Integer, int) + if thety is not None and not isinstance(thety, accepted): + raise TypingError( + '"tabsize" must be {}, not {}'.format(accepted, tabsize)) + + def expandtabs_impl(data, tabsize=8): + length = len(data) + j = line_pos = 0 + found = False + for i in range(length): + code_point = _get_code_point(data, i) + if code_point == _Py_TAB: + found = True + if tabsize > 0: + # cannot overflow + incr = tabsize - (line_pos % tabsize) + if j > sys.maxsize - incr: + raise OverflowError('new string is too long') + line_pos += incr + j += incr + else: + if j > sys.maxsize - 1: + raise OverflowError('new string is too long') + line_pos += 1 + j += 1 + if code_point in (_Py_LINEFEED, _Py_CARRIAGE_RETURN): + line_pos = 0 + + if not found: + return data + + res = _empty_string(data._kind, j, data._is_ascii) + j = line_pos = 0 + for i in range(length): + code_point = _get_code_point(data, i) + if code_point == _Py_TAB: + if tabsize > 0: + incr = tabsize - (line_pos % tabsize) + line_pos += incr + for idx in range(j, j + incr): + _set_code_point(res, idx, _Py_SPACE) + j += incr + else: + line_pos += 1 + _set_code_point(res, j, code_point) + j += 1 + if code_point in (_Py_LINEFEED, _Py_CARRIAGE_RETURN): + line_pos = 0 + + return res + + return expandtabs_impl + + +@overload_method(types.UnicodeType, 'split') +def unicode_split(a, sep=None, maxsplit=-1): + if not (maxsplit == -1 or + isinstance(maxsplit, (types.Omitted, types.Integer, + types.IntegerLiteral))): + return None # fail typing if maxsplit is not an integer + + if isinstance(sep, types.UnicodeCharSeq): + def split_impl(a, sep=None, maxsplit=-1): + return a.split(str(sep), maxsplit=maxsplit) + return split_impl + + if isinstance(sep, types.UnicodeType): + def split_impl(a, sep=None, maxsplit=-1): + a_len = len(a) + sep_len = len(sep) + + if sep_len == 0: + raise ValueError('empty separator') + + parts = [] + last = 0 + idx = 0 + + if sep_len == 1 and maxsplit == -1: + sep_code_point = _get_code_point(sep, 0) + for idx in range(a_len): + if _get_code_point(a, idx) == sep_code_point: + parts.append(a[last:idx]) + last = idx + 1 + else: + split_count = 0 + + while idx < a_len and (maxsplit == -1 or + split_count < maxsplit): + if _cmp_region(a, idx, sep, 0, sep_len) == 0: + parts.append(a[last:idx]) + idx += sep_len + last = idx + split_count += 1 + else: + idx += 1 + + if last <= a_len: + parts.append(a[last:]) + + return parts + return split_impl + elif sep is None or isinstance(sep, types.NoneType) or \ + getattr(sep, 'value', False) is None: + def split_whitespace_impl(a, sep=None, maxsplit=-1): + a_len = len(a) + + parts = [] + last = 0 + idx = 0 + split_count = 0 + in_whitespace_block = True + + for idx in range(a_len): + code_point = _get_code_point(a, idx) + is_whitespace = _PyUnicode_IsSpace(code_point) + if in_whitespace_block: + if is_whitespace: + pass # keep consuming space + else: + last = idx # this is the start of the next string + in_whitespace_block = False + else: + if not is_whitespace: + pass # keep searching for whitespace transition + else: + parts.append(a[last:idx]) + in_whitespace_block = True + split_count += 1 + if maxsplit != -1 and split_count == maxsplit: + break + + if last <= a_len and not in_whitespace_block: + parts.append(a[last:]) + + return parts + return split_whitespace_impl + + +def generate_rsplit_whitespace_impl(isspace_func): + """Generate whitespace rsplit func based on either ascii or unicode""" + + def rsplit_whitespace_impl(data, sep=None, maxsplit=-1): + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/split.h#L192-L240 # noqa: E501 + if maxsplit < 0: + maxsplit = sys.maxsize + + result = [] + i = len(data) - 1 + while maxsplit > 0: + while i >= 0: + code_point = _get_code_point(data, i) + if not isspace_func(code_point): + break + i -= 1 + if i < 0: + break + j = i + i -= 1 + while i >= 0: + code_point = _get_code_point(data, i) + if isspace_func(code_point): + break + i -= 1 + result.append(data[i + 1:j + 1]) + maxsplit -= 1 + + if i >= 0: + # Only occurs when maxsplit was reached + # Skip any remaining whitespace and copy to beginning of string + while i >= 0: + code_point = _get_code_point(data, i) + if not isspace_func(code_point): + break + i -= 1 + if i >= 0: + result.append(data[0:i + 1]) + + return result[::-1] + + return rsplit_whitespace_impl + + +unicode_rsplit_whitespace_impl = register_jitable( + generate_rsplit_whitespace_impl(_PyUnicode_IsSpace)) +ascii_rsplit_whitespace_impl = register_jitable( + generate_rsplit_whitespace_impl(_Py_ISSPACE)) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L13095-L13108 # noqa: E501 +@overload_method(types.UnicodeType, 'rsplit') +def unicode_rsplit(data, sep=None, maxsplit=-1): + """Implements str.unicode_rsplit()""" + + def _unicode_rsplit_check_type(ty, name, accepted): + """Check object belongs to one of specified types""" + thety = ty + # if the type is omitted, the concrete type is the value + if isinstance(ty, types.Omitted): + thety = ty.value + # if the type is optional, the concrete type is the captured type + elif isinstance(ty, types.Optional): + thety = ty.type + + if thety is not None and not isinstance(thety, accepted): + raise TypingError( + '"{}" must be {}, not {}'.format(name, accepted, ty)) + + _unicode_rsplit_check_type(sep, 'sep', (types.UnicodeType, + types.UnicodeCharSeq, + types.NoneType)) + _unicode_rsplit_check_type(maxsplit, 'maxsplit', (types.Integer, int)) + + if sep is None or isinstance(sep, (types.NoneType, types.Omitted)): + + def rsplit_whitespace_impl(data, sep=None, maxsplit=-1): + if data._is_ascii: + return ascii_rsplit_whitespace_impl(data, sep, maxsplit) + return unicode_rsplit_whitespace_impl(data, sep, maxsplit) + + return rsplit_whitespace_impl + + def rsplit_impl(data, sep=None, maxsplit=-1): + sep = str(sep) + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/split.h#L286-L333 # noqa: E501 + if data._kind < sep._kind or len(data) < len(sep): + return [data] + + def _rsplit_char(data, ch, maxsplit): + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/split.h#L242-L284 # noqa: E501 + result = [] + ch_code_point = _get_code_point(ch, 0) + i = j = len(data) - 1 + while i >= 0 and maxsplit > 0: + data_code_point = _get_code_point(data, i) + if data_code_point == ch_code_point: + result.append(data[i + 1 : j + 1]) + j = i = i - 1 + maxsplit -= 1 + i -= 1 + if j >= -1: + result.append(data[0 : j + 1]) + + return result[::-1] + + if maxsplit < 0: + maxsplit = sys.maxsize + + sep_length = len(sep) + + if sep_length == 0: + raise ValueError('empty separator') + if sep_length == 1: + return _rsplit_char(data, sep, maxsplit) + + result = [] + j = len(data) + while maxsplit > 0: + pos = data.rfind(sep, start=0, end=j) + if pos < 0: + break + result.append(data[pos + sep_length:j]) + j = pos + maxsplit -= 1 + + result.append(data[0:j]) + + return result[::-1] + + return rsplit_impl + + +@overload_method(types.UnicodeType, 'center') +def unicode_center(string, width, fillchar=' '): + if not isinstance(width, types.Integer): + raise TypingError('The width must be an Integer') + + if isinstance(fillchar, types.UnicodeCharSeq): + def center_impl(string, width, fillchar=' '): + return string.center(width, str(fillchar)) + return center_impl + + if not (fillchar == ' ' or + isinstance(fillchar, (types.Omitted, types.UnicodeType))): + raise TypingError('The fillchar must be a UnicodeType') + + def center_impl(string, width, fillchar=' '): + str_len = len(string) + fillchar_len = len(fillchar) + + if fillchar_len != 1: + raise ValueError('The fill character must be exactly one ' + 'character long') + + if width <= str_len: + return string + + allmargin = width - str_len + lmargin = (allmargin // 2) + (allmargin & width & 1) + rmargin = allmargin - lmargin + + l_string = fillchar * lmargin + if lmargin == rmargin: + return l_string + string + l_string + else: + return l_string + string + (fillchar * rmargin) + + return center_impl + + +def gen_unicode_Xjust(STRING_FIRST): + def unicode_Xjust(string, width, fillchar=' '): + if not isinstance(width, types.Integer): + raise TypingError('The width must be an Integer') + + if isinstance(fillchar, types.UnicodeCharSeq): + if STRING_FIRST: + def ljust_impl(string, width, fillchar=' '): + return string.ljust(width, str(fillchar)) + return ljust_impl + else: + def rjust_impl(string, width, fillchar=' '): + return string.rjust(width, str(fillchar)) + return rjust_impl + + if not (fillchar == ' ' or + isinstance(fillchar, (types.Omitted, types.UnicodeType))): + raise TypingError('The fillchar must be a UnicodeType') + + def impl(string, width, fillchar=' '): + str_len = len(string) + fillchar_len = len(fillchar) + + if fillchar_len != 1: + raise ValueError('The fill character must be exactly one ' + 'character long') + + if width <= str_len: + return string + + newstr = (fillchar * (width - str_len)) + if STRING_FIRST: + return string + newstr + else: + return newstr + string + + return impl + + return unicode_Xjust + + +overload_method(types.UnicodeType, 'rjust')(gen_unicode_Xjust(False)) +overload_method(types.UnicodeType, 'ljust')(gen_unicode_Xjust(True)) + + +def generate_splitlines_func(is_line_break_func): + """Generate splitlines performer based on ascii or unicode line breaks.""" + def impl(data, keepends): + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/split.h#L335-L389 # noqa: E501 + length = len(data) + result = [] + i = j = 0 + while i < length: + # find a line and append it + while i < length: + code_point = _get_code_point(data, i) + if is_line_break_func(code_point): + break + i += 1 + + # skip the line break reading CRLF as one line break + eol = i + if i < length: + if i + 1 < length: + cur_cp = _get_code_point(data, i) + next_cp = _get_code_point(data, i + 1) + if _Py_ISCARRIAGERETURN(cur_cp) and _Py_ISLINEFEED(next_cp): + i += 1 + i += 1 + if keepends: + eol = i + + result.append(data[j:eol]) + j = i + + return result + + return impl + + +_ascii_splitlines = register_jitable(generate_splitlines_func(_Py_ISLINEBREAK)) +_unicode_splitlines = register_jitable(generate_splitlines_func( + _PyUnicode_IsLineBreak)) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L10196-L10229 # noqa: E501 +@overload_method(types.UnicodeType, 'splitlines') +def unicode_splitlines(data, keepends=False): + """Implements str.splitlines()""" + thety = keepends + # if the type is omitted, the concrete type is the value + if isinstance(keepends, types.Omitted): + thety = keepends.value + # if the type is optional, the concrete type is the captured type + elif isinstance(keepends, types.Optional): + thety = keepends.type + + accepted = (types.Integer, int, types.Boolean, bool) + if thety is not None and not isinstance(thety, accepted): + raise TypingError( + '"{}" must be {}, not {}'.format('keepends', accepted, keepends)) + + def splitlines_impl(data, keepends=False): + if data._is_ascii: + return _ascii_splitlines(data, keepends) + + return _unicode_splitlines(data, keepends) + + return splitlines_impl + + +@register_jitable +def join_list(sep, parts): + parts_len = len(parts) + if parts_len == 0: + return '' + + # Precompute size and char_width of result + sep_len = len(sep) + length = (parts_len - 1) * sep_len + kind = sep._kind + is_ascii = sep._is_ascii + for p in parts: + length += len(p) + kind = _pick_kind(kind, p._kind) + is_ascii = _pick_ascii(is_ascii, p._is_ascii) + + result = _empty_string(kind, length, is_ascii) + + # populate string + part = parts[0] + _strncpy(result, 0, part, 0, len(part)) + dst_offset = len(part) + for idx in range(1, parts_len): + _strncpy(result, dst_offset, sep, 0, sep_len) + dst_offset += sep_len + part = parts[idx] + _strncpy(result, dst_offset, part, 0, len(part)) + dst_offset += len(part) + + return result + + +@overload_method(types.UnicodeType, 'join') +def unicode_join(sep, parts): + + if isinstance(parts, types.List): + if isinstance(parts.dtype, types.UnicodeType): + def join_list_impl(sep, parts): + return join_list(sep, parts) + return join_list_impl + elif isinstance(parts.dtype, types.UnicodeCharSeq): + def join_list_impl(sep, parts): + _parts = [str(p) for p in parts] + return join_list(sep, _parts) + return join_list_impl + else: + pass # lists of any other type not supported + elif isinstance(parts, types.IterableType): + def join_iter_impl(sep, parts): + parts_list = [p for p in parts] + return sep.join(parts_list) + return join_iter_impl + elif isinstance(parts, types.UnicodeType): + # Temporary workaround until UnicodeType is iterable + def join_str_impl(sep, parts): + parts_list = [parts[i] for i in range(len(parts))] + return join_list(sep, parts_list) + return join_str_impl + + +@overload_method(types.UnicodeType, 'zfill') +def unicode_zfill(string, width): + if not isinstance(width, types.Integer): + raise TypingError(" must be an Integer") + + def zfill_impl(string, width): + + str_len = len(string) + + if width <= str_len: + return string + + first_char = string[0] if str_len else '' + padding = '0' * (width - str_len) + + if first_char in ['+', '-']: + newstr = first_char + padding + string[1:] + else: + newstr = padding + string + + return newstr + + return zfill_impl + + +# ------------------------------------------------------------------------------ +# Strip functions +# ------------------------------------------------------------------------------ +@register_jitable +def unicode_strip_left_bound(string, chars): + str_len = len(string) + + i = 0 + if chars is not None: + for i in range(str_len): + if string[i] not in chars: + return i + else: + for i in range(str_len): + if not _PyUnicode_IsSpace(string[i]): + return i + + return str_len + + +@register_jitable +def unicode_strip_right_bound(string, chars): + str_len = len(string) + i = 0 + if chars is not None: + for i in range(str_len - 1, -1, -1): + if string[i] not in chars: + i += 1 + break + else: + for i in range(str_len - 1, -1, -1): + if not _PyUnicode_IsSpace(string[i]): + i += 1 + break + + return i + + +def unicode_strip_types_check(chars): + if isinstance(chars, types.Optional): + chars = chars.type # catch optional type with invalid non-None type + if not (chars is None or isinstance(chars, (types.Omitted, + types.UnicodeType, + types.NoneType))): + raise TypingError('The arg must be a UnicodeType or None') + + +def _count_args_types_check(arg): + if isinstance(arg, types.Optional): + arg = arg.type + if not (arg is None or isinstance(arg, (types.Omitted, + types.Integer, + types.NoneType))): + raise TypingError("The slice indices must be an Integer or None") + + +@overload_method(types.UnicodeType, 'lstrip') +def unicode_lstrip(string, chars=None): + + if isinstance(chars, types.UnicodeCharSeq): + def lstrip_impl(string, chars=None): + return string.lstrip(str(chars)) + return lstrip_impl + + unicode_strip_types_check(chars) + + def lstrip_impl(string, chars=None): + return string[unicode_strip_left_bound(string, chars):] + return lstrip_impl + + +@overload_method(types.UnicodeType, 'rstrip') +def unicode_rstrip(string, chars=None): + + if isinstance(chars, types.UnicodeCharSeq): + def rstrip_impl(string, chars=None): + return string.rstrip(str(chars)) + return rstrip_impl + + unicode_strip_types_check(chars) + + def rstrip_impl(string, chars=None): + return string[:unicode_strip_right_bound(string, chars)] + return rstrip_impl + + +@overload_method(types.UnicodeType, 'strip') +def unicode_strip(string, chars=None): + + if isinstance(chars, types.UnicodeCharSeq): + def strip_impl(string, chars=None): + return string.strip(str(chars)) + return strip_impl + + unicode_strip_types_check(chars) + + def strip_impl(string, chars=None): + lb = unicode_strip_left_bound(string, chars) + rb = unicode_strip_right_bound(string, chars) + return string[lb:rb] + return strip_impl + + +# ------------------------------------------------------------------------------ +# Slice functions +# ------------------------------------------------------------------------------ + +@register_jitable +def normalize_str_idx(idx, length, is_start=True): + """ + Parameters + ---------- + idx : int or None + the index + length : int + the string length + is_start : bool; optional with defaults to True + Is it the *start* or the *stop* of the slice? + + Returns + ------- + norm_idx : int + normalized index + """ + if idx is None: + if is_start: + return 0 + else: + return length + elif idx < 0: + idx += length + + if idx < 0 or idx >= length: + raise IndexError("string index out of range") + + return idx + + +@register_jitable +def _normalize_slice_idx_count(arg, slice_len, default): + """ + Used for unicode_count + + If arg < -slice_len, returns 0 (prevents circle) + + If arg is within slice, e.g -slice_len <= arg < slice_len + returns its real index via arg % slice_len + + If arg > slice_len, returns arg (in this case count must + return 0 if it is start index) + """ + + if arg is None: + return default + if -slice_len <= arg < slice_len: + return arg % slice_len + return 0 if arg < 0 else arg + + +@intrinsic +def _normalize_slice(typingctx, sliceobj, length): + """Fix slice object. + """ + sig = sliceobj(sliceobj, length) + + def codegen(context, builder, sig, args): + [slicetype, lengthtype] = sig.args + [sliceobj, length] = args + slice = context.make_helper(builder, slicetype, sliceobj) + slicing.guard_invalid_slice(context, builder, slicetype, slice) + slicing.fix_slice(builder, slice, length) + return slice._getvalue() + + return sig, codegen + + +@intrinsic +def _slice_span(typingctx, sliceobj): + """Compute the span from the given slice object. + """ + sig = types.intp(sliceobj) + + def codegen(context, builder, sig, args): + [slicetype] = sig.args + [sliceobj] = args + slice = context.make_helper(builder, slicetype, sliceobj) + result_size = slicing.get_slice_length(builder, slice) + return result_size + + return sig, codegen + + +@register_jitable(_nrt=False) +def _strncpy(dst, dst_offset, src, src_offset, n): + if src._kind == dst._kind: + byte_width = _kind_to_byte_width(src._kind) + src_byte_offset = byte_width * src_offset + dst_byte_offset = byte_width * dst_offset + nbytes = n * byte_width + memcpy_region(dst._data, dst_byte_offset, src._data, + src_byte_offset, nbytes, align=1) + else: + for i in range(n): + _set_code_point(dst, dst_offset + i, + _get_code_point(src, src_offset + i)) + + +@intrinsic +def _get_str_slice_view(typingctx, src_t, start_t, length_t): + """Create a slice of a unicode string using a view of its data to avoid + extra allocation. + """ + assert src_t == types.unicode_type + + def codegen(context, builder, sig, args): + src, start, length = args + in_str = cgutils.create_struct_proxy( + types.unicode_type)(context, builder, value=src) + view_str = cgutils.create_struct_proxy( + types.unicode_type)(context, builder) + view_str.meminfo = in_str.meminfo + view_str.kind = in_str.kind + view_str.is_ascii = in_str.is_ascii + view_str.length = length + # hash value -1 to indicate "need to compute hash" + view_str.hash = context.get_constant(_Py_hash_t, -1) + # get a pointer to start of slice data + bw_typ = context.typing_context.resolve_value_type(_kind_to_byte_width) + bw_sig = bw_typ.get_call_type( + context.typing_context, (types.int32,), {}) + bw_impl = context.get_function(bw_typ, bw_sig) + byte_width = bw_impl(builder, (in_str.kind,)) + offset = builder.mul(start, byte_width) + view_str.data = builder.gep(in_str.data, [offset]) + # Set parent pyobject to NULL + view_str.parent = cgutils.get_null_value(view_str.parent.type) + # incref original string + if context.enable_nrt: + context.nrt.incref(builder, sig.args[0], src) + return view_str._getvalue() + + sig = types.unicode_type(types.unicode_type, types.intp, types.intp) + return sig, codegen + + +@overload(operator.getitem) +def unicode_getitem(s, idx): + if isinstance(s, types.UnicodeType): + if isinstance(idx, types.Integer): + def getitem_char(s, idx): + idx = normalize_str_idx(idx, len(s)) + cp = _get_code_point(s, idx) + kind = _codepoint_to_kind(cp) + if kind == s._kind: + return _get_str_slice_view(s, idx, 1) + else: + is_ascii = _codepoint_is_ascii(cp) + ret = _empty_string(kind, 1, is_ascii) + _set_code_point(ret, 0, cp) + return ret + return getitem_char + elif isinstance(idx, types.SliceType): + def getitem_slice(s, idx): + slice_idx = _normalize_slice(idx, len(s)) + span = _slice_span(slice_idx) + + cp = _get_code_point(s, slice_idx.start) + kind = _codepoint_to_kind(cp) + is_ascii = _codepoint_is_ascii(cp) + + # Check slice to see if it's homogeneous in kind + for i in range(slice_idx.start + slice_idx.step, + slice_idx.stop, slice_idx.step): + cp = _get_code_point(s, i) + is_ascii &= _codepoint_is_ascii(cp) + new_kind = _codepoint_to_kind(cp) + if kind != new_kind: + kind = _pick_kind(kind, new_kind) + # TODO: it might be possible to break here if the kind + # is PY_UNICODE_4BYTE_KIND but there are potentially + # strings coming from other internal functions that are + # this wide and also actually ASCII (i.e. kind is larger + # than actually required for storing the code point), so + # it's necessary to continue. + + if slice_idx.step == 1 and kind == s._kind: + # Can return a view, the slice has the same kind as the + # string itself and it's a stride slice 1. + return _get_str_slice_view(s, slice_idx.start, span) + else: + # It's heterogeneous in kind OR stride != 1 + ret = _empty_string(kind, span, is_ascii) + cur = slice_idx.start + for i in range(span): + _set_code_point(ret, i, _get_code_point(s, cur)) + cur += slice_idx.step + return ret + + return getitem_slice + + +# ------------------------------------------------------------------------------ +# String operations +# ------------------------------------------------------------------------------ + + +@overload(operator.add) +@overload(operator.iadd) +def unicode_concat(a, b): + if isinstance(a, types.UnicodeType) and isinstance(b, types.UnicodeType): + def concat_impl(a, b): + new_length = a._length + b._length + new_kind = _pick_kind(a._kind, b._kind) + new_ascii = _pick_ascii(a._is_ascii, b._is_ascii) + result = _empty_string(new_kind, new_length, new_ascii) + for i in range(len(a)): + _set_code_point(result, i, _get_code_point(a, i)) + for j in range(len(b)): + _set_code_point(result, len(a) + j, _get_code_point(b, j)) + return result + return concat_impl + + if isinstance(a, types.UnicodeType) and isinstance(b, types.UnicodeCharSeq): + def concat_impl(a, b): + return a + str(b) + return concat_impl + + +@register_jitable +def _repeat_impl(str_arg, mult_arg): + if str_arg == '' or mult_arg < 1: + return '' + elif mult_arg == 1: + return str_arg + else: + new_length = str_arg._length * mult_arg + new_kind = str_arg._kind + result = _empty_string(new_kind, new_length, str_arg._is_ascii) + # make initial copy into result + len_a = len(str_arg) + _strncpy(result, 0, str_arg, 0, len_a) + # loop through powers of 2 for efficient copying + copy_size = len_a + while 2 * copy_size <= new_length: + _strncpy(result, copy_size, result, 0, copy_size) + copy_size *= 2 + + if not 2 * copy_size == new_length: + # if copy_size not an exact multiple it then needs + # to complete the rest of the copies + rest = new_length - copy_size + _strncpy(result, copy_size, result, copy_size - rest, rest) + return result + + +@overload(operator.mul) +def unicode_repeat(a, b): + if isinstance(a, types.UnicodeType) and isinstance(b, types.Integer): + def wrap(a, b): + return _repeat_impl(a, b) + return wrap + elif isinstance(a, types.Integer) and isinstance(b, types.UnicodeType): + def wrap(a, b): + return _repeat_impl(b, a) + return wrap + + +@overload(operator.not_) +def unicode_not(a): + if isinstance(a, types.UnicodeType): + def impl(a): + return len(a) == 0 + return impl + + +@overload_method(types.UnicodeType, 'replace') +def unicode_replace(s, old_str, new_str, count=-1): + thety = count + if isinstance(count, types.Omitted): + thety = count.value + elif isinstance(count, types.Optional): + thety = count.type + + if not isinstance(thety, (int, types.Integer)): + raise TypingError('Unsupported parameters. The parameters ' + 'must be Integer. Given count: {}'.format(count)) + + if not isinstance(old_str, (types.UnicodeType, types.NoneType)): + raise TypingError('The object must be a UnicodeType.' + ' Given: {}'.format(old_str)) + + if not isinstance(new_str, types.UnicodeType): + raise TypingError('The object must be a UnicodeType.' + ' Given: {}'.format(new_str)) + + def impl(s, old_str, new_str, count=-1): + if count == 0: + return s + if old_str == '': + schars = list(s) + if count == -1: + return new_str + new_str.join(schars) + new_str + split_result = [new_str] + min_count = min(len(schars), count) + for i in range(min_count): + split_result.append(schars[i]) + if i + 1 != min_count: + split_result.append(new_str) + else: + split_result.append(''.join(schars[(i + 1):])) + if count > len(schars): + split_result.append(new_str) + return ''.join(split_result) + schars = s.split(old_str, count) + result = new_str.join(schars) + return result + + return impl + +# ------------------------------------------------------------------------------ +# String `is*()` methods +# ------------------------------------------------------------------------------ + + +# generates isalpha/isalnum +def gen_isAlX(ascii_func, unicode_func): + def unicode_isAlX(data): + + def impl(data): + length = len(data) + if length == 0: + return False + + if length == 1: + code_point = _get_code_point(data, 0) + if data._is_ascii: + return ascii_func(code_point) + else: + return unicode_func(code_point) + + if data._is_ascii: + for i in range(length): + code_point = _get_code_point(data, i) + if not ascii_func(code_point): + return False + + for i in range(length): + code_point = _get_code_point(data, i) + if not unicode_func(code_point): + return False + + return True + + return impl + return unicode_isAlX + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11928-L11964 # noqa: E501 +overload_method(types.UnicodeType, 'isalpha')(gen_isAlX(_Py_ISALPHA, + _PyUnicode_IsAlpha)) + +_unicode_is_alnum = register_jitable(lambda x: + (_PyUnicode_IsNumeric(x) or + _PyUnicode_IsAlpha(x))) + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11975-L12006 # noqa: E501 +overload_method(types.UnicodeType, 'isalnum')(gen_isAlX(_Py_ISALNUM, + _unicode_is_alnum)) + + +def _is_upper(is_lower, is_upper, is_title): + # impl is an approximate translation of: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11794-L11827 # noqa: E501 + # mixed with: + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/bytes_methods.c#L218-L242 # noqa: E501 + def impl(a): + l = len(a) + if l == 1: + return is_upper(_get_code_point(a, 0)) != 0 + if l == 0: + return False + cased = False + for idx in range(l): + code_point = _get_code_point(a, idx) + if is_lower(code_point) or is_title(code_point): + return False + elif (not cased and is_upper(code_point)): + cased = True + return cased + return impl + + +_always_false = register_jitable(lambda x: False) +_ascii_is_upper = register_jitable(_is_upper(_Py_ISLOWER, _Py_ISUPPER, + _always_false)) +_unicode_is_upper = register_jitable(_is_upper(_PyUnicode_IsLowercase, + _PyUnicode_IsUppercase, + _PyUnicode_IsTitlecase)) + + +@overload_method(types.UnicodeType, 'isupper') +def unicode_isupper(a): + """ + Implements .isupper() + """ + def impl(a): + if a._is_ascii: + return _ascii_is_upper(a) + else: + return _unicode_is_upper(a) + return impl + + +@overload_method(types.UnicodeType, 'isascii') +def unicode_isascii(data): + """Implements UnicodeType.isascii()""" + + def impl(data): + return data._is_ascii + return impl + + +@overload_method(types.UnicodeType, 'istitle') +def unicode_istitle(data): + """ + Implements UnicodeType.istitle() + The algorithm is an approximate translation from CPython: + https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11829-L11885 # noqa: E501 + """ + + def impl(data): + length = len(data) + if length == 1: + char = _get_code_point(data, 0) + return _PyUnicode_IsUppercase(char) or _PyUnicode_IsTitlecase(char) + + if length == 0: + return False + + cased = False + previous_is_cased = False + for idx in range(length): + char = _get_code_point(data, idx) + if _PyUnicode_IsUppercase(char) or _PyUnicode_IsTitlecase(char): + if previous_is_cased: + return False + previous_is_cased = True + cased = True + elif _PyUnicode_IsLowercase(char): + if not previous_is_cased: + return False + previous_is_cased = True + cased = True + else: + previous_is_cased = False + + return cased + return impl + + +@overload_method(types.UnicodeType, 'islower') +def unicode_islower(data): + """ + impl is an approximate translation of: + https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L11900-L11933 # noqa: E501 + mixed with: + https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/bytes_methods.c#L131-L156 # noqa: E501 + """ + + def impl(data): + length = len(data) + if length == 1: + return _PyUnicode_IsLowercase(_get_code_point(data, 0)) + if length == 0: + return False + + cased = False + for idx in range(length): + cp = _get_code_point(data, idx) + if _PyUnicode_IsUppercase(cp) or _PyUnicode_IsTitlecase(cp): + return False + elif not cased and _PyUnicode_IsLowercase(cp): + cased = True + return cased + return impl + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12126-L12161 # noqa: E501 +@overload_method(types.UnicodeType, 'isidentifier') +def unicode_isidentifier(data): + """Implements UnicodeType.isidentifier()""" + + def impl(data): + length = len(data) + if length == 0: + return False + + first_cp = _get_code_point(data, 0) + if not _PyUnicode_IsXidStart(first_cp) and first_cp != 0x5F: + return False + + for i in range(1, length): + code_point = _get_code_point(data, i) + if not _PyUnicode_IsXidContinue(code_point): + return False + + return True + + return impl + + +# generator for simple unicode "isX" methods +def gen_isX(_PyUnicode_IS_func, empty_is_false=True): + def unicode_isX(data): + def impl(data): + length = len(data) + if length == 1: + return _PyUnicode_IS_func(_get_code_point(data, 0)) + + if empty_is_false and length == 0: + return False + + for i in range(length): + code_point = _get_code_point(data, i) + if not _PyUnicode_IS_func(code_point): + return False + + return True + + return impl + return unicode_isX + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11896-L11925 # noqa: E501 +overload_method(types.UnicodeType, 'isspace')(gen_isX(_PyUnicode_IsSpace)) + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12096-L12124 # noqa: E501 +overload_method(types.UnicodeType, 'isnumeric')(gen_isX(_PyUnicode_IsNumeric)) + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12056-L12085 # noqa: E501 +overload_method(types.UnicodeType, 'isdigit')(gen_isX(_PyUnicode_IsDigit)) + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12017-L12045 # noqa: E501 +overload_method(types.UnicodeType, 'isdecimal')( + gen_isX(_PyUnicode_IsDecimalDigit)) + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12188-L12213 # noqa: E501 +overload_method(types.UnicodeType, 'isprintable')( + gen_isX(_PyUnicode_IsPrintable, False)) + +# ------------------------------------------------------------------------------ +# String methods that apply a transformation to the characters themselves +# ------------------------------------------------------------------------------ + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L9863-L9908 # noqa: E501 +def case_operation(ascii_func, unicode_func): + """Generate common case operation performer.""" + def impl(data): + length = len(data) + if length == 0: + return _empty_string(data._kind, length, data._is_ascii) + + if data._is_ascii: + res = _empty_string(data._kind, length, 1) + ascii_func(data, res) + return res + + # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L9863-L9908 # noqa: E501 + tmp = _empty_string(PY_UNICODE_4BYTE_KIND, 3 * length, data._is_ascii) + # maxchar should be inside of a list to be pass as argument by reference + maxchars = [0] + newlength = unicode_func(data, length, tmp, maxchars) + maxchar = maxchars[0] + newkind = _codepoint_to_kind(maxchar) + res = _empty_string(newkind, newlength, _codepoint_is_ascii(maxchar)) + for i in range(newlength): + _set_code_point(res, i, _get_code_point(tmp, i)) + + return res + + return impl + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9856-L9883 # noqa: E501 +@register_jitable +def _handle_capital_sigma(data, length, idx): + """This is a translation of the function that handles the capital sigma.""" + c = 0 + j = idx - 1 + while j >= 0: + c = _get_code_point(data, j) + if not _PyUnicode_IsCaseIgnorable(c): + break + j -= 1 + final_sigma = (j >= 0 and _PyUnicode_IsCased(c)) + if final_sigma: + j = idx + 1 + while j < length: + c = _get_code_point(data, j) + if not _PyUnicode_IsCaseIgnorable(c): + break + j += 1 + final_sigma = (j == length or (not _PyUnicode_IsCased(c))) + + return 0x3c2 if final_sigma else 0x3c3 + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9885-L9895 # noqa: E501 +@register_jitable +def _lower_ucs4(code_point, data, length, idx, mapped): + """This is a translation of the function that lowers a character.""" + if code_point == 0x3A3: + mapped[0] = _handle_capital_sigma(data, length, idx) + return 1 + return _PyUnicode_ToLowerFull(code_point, mapped) + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9946-L9965 # noqa: E501 +def _gen_unicode_upper_or_lower(lower): + def _do_upper_or_lower(data, length, res, maxchars): + k = 0 + for idx in range(length): + mapped = np.zeros(3, dtype=_Py_UCS4) + code_point = _get_code_point(data, idx) + if lower: + n_res = _lower_ucs4(code_point, data, length, idx, mapped) + else: + # might be needed if call _do_upper_or_lower in unicode_upper + n_res = _PyUnicode_ToUpperFull(code_point, mapped) + for m in mapped[:n_res]: + maxchars[0] = max(maxchars[0], m) + _set_code_point(res, k, m) + k += 1 + return k + return _do_upper_or_lower + + +_unicode_upper = register_jitable(_gen_unicode_upper_or_lower(False)) +_unicode_lower = register_jitable(_gen_unicode_upper_or_lower(True)) + + +def _gen_ascii_upper_or_lower(func): + def _ascii_upper_or_lower(data, res): + for idx in range(len(data)): + code_point = _get_code_point(data, idx) + _set_code_point(res, idx, func(code_point)) + return _ascii_upper_or_lower + + +_ascii_upper = register_jitable(_gen_ascii_upper_or_lower(_Py_TOUPPER)) +_ascii_lower = register_jitable(_gen_ascii_upper_or_lower(_Py_TOLOWER)) + + +@overload_method(types.UnicodeType, 'lower') +def unicode_lower(data): + """Implements .lower()""" + return case_operation(_ascii_lower, _unicode_lower) + + +@overload_method(types.UnicodeType, 'upper') +def unicode_upper(data): + """Implements .upper()""" + return case_operation(_ascii_upper, _unicode_upper) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L9819-L9834 # noqa: E501 +@register_jitable +def _unicode_casefold(data, length, res, maxchars): + k = 0 + mapped = np.zeros(3, dtype=_Py_UCS4) + for idx in range(length): + mapped.fill(0) + code_point = _get_code_point(data, idx) + n_res = _PyUnicode_ToFoldedFull(code_point, mapped) + for m in mapped[:n_res]: + maxchar = maxchars[0] + maxchars[0] = max(maxchar, m) + _set_code_point(res, k, m) + k += 1 + + return k + + +@register_jitable +def _ascii_casefold(data, res): + for idx in range(len(data)): + code_point = _get_code_point(data, idx) + _set_code_point(res, idx, _Py_TOLOWER(code_point)) + + +@overload_method(types.UnicodeType, 'casefold') +def unicode_casefold(data): + """Implements str.casefold()""" + return case_operation(_ascii_casefold, _unicode_casefold) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L9737-L9759 # noqa: E501 +@register_jitable +def _unicode_capitalize(data, length, res, maxchars): + k = 0 + maxchar = 0 + mapped = np.zeros(3, dtype=_Py_UCS4) + code_point = _get_code_point(data, 0) + + n_res = _PyUnicode_ToTitleFull(code_point, mapped) + + for m in mapped[:n_res]: + maxchar = max(maxchar, m) + _set_code_point(res, k, m) + k += 1 + for idx in range(1, length): + mapped.fill(0) + code_point = _get_code_point(data, idx) + n_res = _lower_ucs4(code_point, data, length, idx, mapped) + for m in mapped[:n_res]: + maxchar = max(maxchar, m) + _set_code_point(res, k, m) + k += 1 + maxchars[0] = maxchar + return k + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/bytes_methods.c#L361-L382 # noqa: E501 +@register_jitable +def _ascii_capitalize(data, res): + code_point = _get_code_point(data, 0) + _set_code_point(res, 0, _Py_TOUPPER(code_point)) + for idx in range(1, len(data)): + code_point = _get_code_point(data, idx) + _set_code_point(res, idx, _Py_TOLOWER(code_point)) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L10765-L10774 # noqa: E501 +@overload_method(types.UnicodeType, 'capitalize') +def unicode_capitalize(data): + return case_operation(_ascii_capitalize, _unicode_capitalize) + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9996-L10021 # noqa: E501 +@register_jitable +def _unicode_title(data, length, res, maxchars): + """This is a translation of the function that titles a unicode string.""" + k = 0 + previous_cased = False + mapped = np.empty(3, dtype=_Py_UCS4) + for idx in range(length): + mapped.fill(0) + code_point = _get_code_point(data, idx) + if previous_cased: + n_res = _lower_ucs4(code_point, data, length, idx, mapped) + else: + n_res = _PyUnicode_ToTitleFull(_Py_UCS4(code_point), mapped) + for m in mapped[:n_res]: + maxchar, = maxchars + maxchars[0] = max(maxchar, m) + _set_code_point(res, k, m) + k += 1 + previous_cased = _PyUnicode_IsCased(_Py_UCS4(code_point)) + return k + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/bytes_methods.c#L332-L352 # noqa: E501 +@register_jitable +def _ascii_title(data, res): + """ Does .title() on an ASCII string """ + previous_is_cased = False + for idx in range(len(data)): + code_point = _get_code_point(data, idx) + if _Py_ISLOWER(code_point): + if not previous_is_cased: + code_point = _Py_TOUPPER(code_point) + previous_is_cased = True + elif _Py_ISUPPER(code_point): + if previous_is_cased: + code_point = _Py_TOLOWER(code_point) + previous_is_cased = True + else: + previous_is_cased = False + _set_code_point(res, idx, code_point) + + +# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L10023-L10069 # noqa: E501 +@overload_method(types.UnicodeType, 'title') +def unicode_title(data): + """Implements str.title()""" + # https://docs.python.org/3/library/stdtypes.html#str.title + return case_operation(_ascii_title, _unicode_title) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/bytes_methods.c#L391-L408 # noqa: E501 +@register_jitable +def _ascii_swapcase(data, res): + for idx in range(len(data)): + code_point = _get_code_point(data, idx) + if _Py_ISUPPER(code_point): + code_point = _Py_TOLOWER(code_point) + elif _Py_ISLOWER(code_point): + code_point = _Py_TOUPPER(code_point) + _set_code_point(res, idx, code_point) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L9761-L9784 # noqa: E501 +@register_jitable +def _unicode_swapcase(data, length, res, maxchars): + k = 0 + maxchar = 0 + mapped = np.empty(3, dtype=_Py_UCS4) + for idx in range(length): + mapped.fill(0) + code_point = _get_code_point(data, idx) + if _PyUnicode_IsUppercase(code_point): + n_res = _lower_ucs4(code_point, data, length, idx, mapped) + elif _PyUnicode_IsLowercase(code_point): + n_res = _PyUnicode_ToUpperFull(code_point, mapped) + else: + n_res = 1 + mapped[0] = code_point + for m in mapped[:n_res]: + maxchar = max(maxchar, m) + _set_code_point(res, k, m) + k += 1 + maxchars[0] = maxchar + return k + + +@overload_method(types.UnicodeType, 'swapcase') +def unicode_swapcase(data): + return case_operation(_ascii_swapcase, _unicode_swapcase) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/bltinmodule.c#L1781-L1824 # noqa: E501 +@overload(ord) +def ol_ord(c): + if isinstance(c, types.UnicodeType): + def impl(c): + lc = len(c) + if lc != 1: + # CPython does TypeError + raise TypeError("ord() expected a character") + return _get_code_point(c, 0) + return impl + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L2005-L2028 # noqa: E501 +# This looks a bit different to the cpython implementation but, with the +# exception of a latin1 fast path is logically the same. It finds the "kind" of +# the codepoint `ch`, creates a length 1 string of that kind and then injects +# the code point into the zero position of that string. Cpython does similar but +# branches for each kind (this is encapsulated in Numba's _set_code_point). +@register_jitable +def _unicode_char(ch): + assert ch <= _MAX_UNICODE + kind = _codepoint_to_kind(ch) + ret = _empty_string(kind, 1, kind == PY_UNICODE_1BYTE_KIND) + _set_code_point(ret, 0, ch) + return ret + + +_out_of_range_msg = "chr() arg not in range(0x%hx)" % _MAX_UNICODE + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L3045-L3055 # noqa: E501 +@register_jitable +def _PyUnicode_FromOrdinal(ordinal): + if (ordinal < 0 or ordinal > _MAX_UNICODE): + raise ValueError(_out_of_range_msg) + + return _unicode_char(_Py_UCS4(ordinal)) + + +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/bltinmodule.c#L715-L720 # noqa: E501 +@overload(chr) +def ol_chr(i): + if isinstance(i, types.Integer): + def impl(i): + return _PyUnicode_FromOrdinal(i) + return impl + + +@overload_method(types.UnicodeType, "__str__") +def unicode_str(s): + return lambda s: s + + +@overload_method(types.UnicodeType, "__repr__") +def unicode_repr(s): + # Can't use f-string as the impl ends up calling str and then repr, which + # then recurses somewhere in imports. + return lambda s: "'" + s + "'" + + +@overload_method(types.Integer, "__str__") +def integer_str(n): + + ten = n(10) + + def impl(n): + flag = False + if n < 0: + n = -n + flag = True + if n == 0: + return '0' + length = flag + 1 + int(np.floor(np.log10(n))) + kind = PY_UNICODE_1BYTE_KIND + char_width = _kind_to_byte_width(kind) + s = _malloc_string(kind, char_width, length, True) + if flag: + _set_code_point(s, 0, ord('-')) + idx = length - 1 + while n > 0: + n, digit = divmod(n, ten) + c = ord('0') + digit + _set_code_point(s, idx, c) + idx -= 1 + return s + return impl + + +@overload_method(types.Integer, "__repr__") +def integer_repr(n): + return lambda n: n.__str__() + + +@overload_method(types.Boolean, "__repr__") +@overload_method(types.Boolean, "__str__") +def boolean_str(b): + return lambda b: 'True' if b else 'False' + + +# ------------------------------------------------------------------------------ +# iteration +# ------------------------------------------------------------------------------ + + +@lower_builtin('getiter', types.UnicodeType) +def getiter_unicode(context, builder, sig, args): + [ty] = sig.args + [data] = args + + iterobj = context.make_helper(builder, sig.return_type) + + # set the index to zero + zero = context.get_constant(types.uintp, 0) + indexptr = cgutils.alloca_once_value(builder, zero) + + iterobj.index = indexptr + + # wire in the unicode type data + iterobj.data = data + + # incref as needed + if context.enable_nrt: + context.nrt.incref(builder, ty, data) + + res = iterobj._getvalue() + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +@lower_builtin('iternext', types.UnicodeIteratorType) +# a new ref counted object is put into result._yield so set the new_ref to True! +@iternext_impl(RefType.NEW) +def iternext_unicode(context, builder, sig, args, result): + [iterty] = sig.args + [iter] = args + + tyctx = context.typing_context + + # get ref to unicode.__getitem__ + fnty = tyctx.resolve_value_type(operator.getitem) + getitem_sig = fnty.get_call_type(tyctx, (types.unicode_type, types.uintp), + {}) + getitem_impl = context.get_function(fnty, getitem_sig) + + # get ref to unicode.__len__ + fnty = tyctx.resolve_value_type(len) + len_sig = fnty.get_call_type(tyctx, (types.unicode_type,), {}) + len_impl = context.get_function(fnty, len_sig) + + # grab unicode iterator struct + iterobj = context.make_helper(builder, iterty, value=iter) + + # find the length of the string + strlen = len_impl(builder, (iterobj.data,)) + + # find the current index + index = builder.load(iterobj.index) + + # see if the index is in range + is_valid = builder.icmp_unsigned('<', index, strlen) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + # return value at index + gotitem = getitem_impl(builder, (iterobj.data, index,)) + result.yield_(gotitem) + + # bump index for next cycle + nindex = cgutils.increment_index(builder, index) + builder.store(nindex, iterobj.index) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode_support.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode_support.py new file mode 100644 index 0000000000000000000000000000000000000000..533ba070f9db4fb642aef222081149345a6ed6aa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cpython/unicode_support.py @@ -0,0 +1,765 @@ +""" +This module contains support functions for more advanced unicode operations. +This is not a public API and is for Numba internal use only. Most of the +functions are relatively straightforward translations of the functions with the +same name in CPython. +""" +from collections import namedtuple +from enum import IntEnum + +import llvmlite.ir +import numpy as np + +from numba.core import types, cgutils +from numba.core.imputils import (impl_ret_untracked) + +from numba.core.extending import overload, intrinsic, register_jitable +from numba.core.errors import TypingError + +# This is equivalent to the struct `_PyUnicode_TypeRecord defined in CPython's +# Objects/unicodectype.c +typerecord = namedtuple('typerecord', + 'upper lower title decimal digit flags') + +# The Py_UCS4 type from CPython: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/unicodeobject.h#L112 # noqa: E501 +_Py_UCS4 = types.uint32 + +# ------------------------------------------------------------------------------ +# Start code related to/from CPython's unicodectype impl +# +# NOTE: the original source at: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c # noqa: E501 +# contains this statement: +# +# /* +# Unicode character type helpers. +# +# Written by Marc-Andre Lemburg (mal@lemburg.com). +# Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com) +# +# Copyright (c) Corporation for National Research Initiatives. +# +# */ + + +# This enum contains the values defined in CPython's Objects/unicodectype.c that +# provide masks for use against the various members of the typerecord +# +# See: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L13-L27 # noqa: E501 +# + + +_Py_TAB = 0x9 +_Py_LINEFEED = 0xa +_Py_CARRIAGE_RETURN = 0xd +_Py_SPACE = 0x20 + + +class _PyUnicode_TyperecordMasks(IntEnum): + ALPHA_MASK = 0x01 + DECIMAL_MASK = 0x02 + DIGIT_MASK = 0x04 + LOWER_MASK = 0x08 + LINEBREAK_MASK = 0x10 + SPACE_MASK = 0x20 + TITLE_MASK = 0x40 + UPPER_MASK = 0x80 + XID_START_MASK = 0x100 + XID_CONTINUE_MASK = 0x200 + PRINTABLE_MASK = 0x400 + NUMERIC_MASK = 0x800 + CASE_IGNORABLE_MASK = 0x1000 + CASED_MASK = 0x2000 + EXTENDED_CASE_MASK = 0x4000 + + +def _PyUnicode_gettyperecord(a): + raise RuntimeError("Calling the Python definition is invalid") + + +@intrinsic +def _gettyperecord_impl(typingctx, codepoint): + """ + Provides the binding to numba_gettyperecord, returns a `typerecord` + namedtuple of properties from the codepoint. + """ + if not isinstance(codepoint, types.Integer): + raise TypingError("codepoint must be an integer") + + def details(context, builder, signature, args): + ll_void = context.get_value_type(types.void) + ll_Py_UCS4 = context.get_value_type(_Py_UCS4) + ll_intc = context.get_value_type(types.intc) + ll_intc_ptr = ll_intc.as_pointer() + ll_uchar = context.get_value_type(types.uchar) + ll_uchar_ptr = ll_uchar.as_pointer() + ll_ushort = context.get_value_type(types.ushort) + ll_ushort_ptr = ll_ushort.as_pointer() + fnty = llvmlite.ir.FunctionType(ll_void, [ + ll_Py_UCS4, # code + ll_intc_ptr, # upper + ll_intc_ptr, # lower + ll_intc_ptr, # title + ll_uchar_ptr, # decimal + ll_uchar_ptr, # digit + ll_ushort_ptr, # flags + ]) + fn = cgutils.get_or_insert_function( + builder.module, + fnty, name="numba_gettyperecord") + upper = cgutils.alloca_once(builder, ll_intc, name='upper') + lower = cgutils.alloca_once(builder, ll_intc, name='lower') + title = cgutils.alloca_once(builder, ll_intc, name='title') + decimal = cgutils.alloca_once(builder, ll_uchar, name='decimal') + digit = cgutils.alloca_once(builder, ll_uchar, name='digit') + flags = cgutils.alloca_once(builder, ll_ushort, name='flags') + + byref = [ upper, lower, title, decimal, digit, flags] + builder.call(fn, [args[0]] + byref) + buf = [] + for x in byref: + buf.append(builder.load(x)) + + res = context.make_tuple(builder, signature.return_type, tuple(buf)) + return impl_ret_untracked(context, builder, signature.return_type, res) + + tupty = types.NamedTuple([types.intc, types.intc, types.intc, types.uchar, + types.uchar, types.ushort], typerecord) + sig = tupty(_Py_UCS4) + return sig, details + + +@overload(_PyUnicode_gettyperecord) +def gettyperecord_impl(a): + """ + Provides a _PyUnicode_gettyperecord binding, for convenience it will accept + single character strings and code points. + """ + if isinstance(a, types.UnicodeType): + from numba.cpython.unicode import _get_code_point + + def impl(a): + if len(a) > 1: + msg = "gettyperecord takes a single unicode character" + raise ValueError(msg) + code_point = _get_code_point(a, 0) + data = _gettyperecord_impl(_Py_UCS4(code_point)) + return data + return impl + if isinstance(a, types.Integer): + return lambda a: _gettyperecord_impl(_Py_UCS4(a)) + + +# whilst it's possible to grab the _PyUnicode_ExtendedCase symbol as it's global +# it is safer to use a defined api: +@intrinsic +def _PyUnicode_ExtendedCase(typingctx, index): + """ + Accessor function for the _PyUnicode_ExtendedCase array, binds to + numba_get_PyUnicode_ExtendedCase which wraps the array and does the lookup + """ + if not isinstance(index, types.Integer): + raise TypingError("Expected an index") + + def details(context, builder, signature, args): + ll_Py_UCS4 = context.get_value_type(_Py_UCS4) + ll_intc = context.get_value_type(types.intc) + fnty = llvmlite.ir.FunctionType(ll_Py_UCS4, [ll_intc]) + fn = cgutils.get_or_insert_function( + builder.module, + fnty, name="numba_get_PyUnicode_ExtendedCase") + return builder.call(fn, [args[0]]) + + sig = _Py_UCS4(types.intc) + return sig, details + +# The following functions are replications of the functions with the same name +# in CPython's Objects/unicodectype.c + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L64-L71 # noqa: E501 +@register_jitable +def _PyUnicode_ToTitlecase(ch): + ctype = _PyUnicode_gettyperecord(ch) + if (ctype.flags & _PyUnicode_TyperecordMasks.EXTENDED_CASE_MASK): + return _PyUnicode_ExtendedCase(ctype.title & 0xFFFF) + return ch + ctype.title + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L76-L81 # noqa: E501 +@register_jitable +def _PyUnicode_IsTitlecase(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.TITLE_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L86-L91 # noqa: E501 +@register_jitable +def _PyUnicode_IsXidStart(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.XID_START_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L96-L101 # noqa: E501 +@register_jitable +def _PyUnicode_IsXidContinue(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.XID_CONTINUE_MASK != 0 + + +@register_jitable +def _PyUnicode_ToDecimalDigit(ch): + ctype = _PyUnicode_gettyperecord(ch) + if ctype.flags & _PyUnicode_TyperecordMasks.DECIMAL_MASK: + return ctype.decimal + return -1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L123-L1128 # noqa: E501 +@register_jitable +def _PyUnicode_ToDigit(ch): + ctype = _PyUnicode_gettyperecord(ch) + if ctype.flags & _PyUnicode_TyperecordMasks.DIGIT_MASK: + return ctype.digit + return -1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L140-L145 # noqa: E501 +@register_jitable +def _PyUnicode_IsNumeric(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.NUMERIC_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L160-L165 # noqa: E501 +@register_jitable +def _PyUnicode_IsPrintable(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.PRINTABLE_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L170-L175 # noqa: E501 +@register_jitable +def _PyUnicode_IsLowercase(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.LOWER_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L180-L185 # noqa: E501 +@register_jitable +def _PyUnicode_IsUppercase(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.UPPER_MASK != 0 + + +@register_jitable +def _PyUnicode_IsLineBreak(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.LINEBREAK_MASK != 0 + + +@register_jitable +def _PyUnicode_ToUppercase(ch): + raise NotImplementedError + + +@register_jitable +def _PyUnicode_ToLowercase(ch): + raise NotImplementedError + + +# From: https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodectype.c#L211-L225 # noqa: E501 +@register_jitable +def _PyUnicode_ToLowerFull(ch, res): + ctype = _PyUnicode_gettyperecord(ch) + if (ctype.flags & _PyUnicode_TyperecordMasks.EXTENDED_CASE_MASK): + index = ctype.lower & 0xFFFF + n = ctype.lower >> 24 + for i in range(n): + res[i] = _PyUnicode_ExtendedCase(index + i) + return n + res[0] = ch + ctype.lower + return 1 + + +# From: https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodectype.c#L227-L241 # noqa: E501 +@register_jitable +def _PyUnicode_ToTitleFull(ch, res): + ctype = _PyUnicode_gettyperecord(ch) + if (ctype.flags & _PyUnicode_TyperecordMasks.EXTENDED_CASE_MASK): + index = ctype.title & 0xFFFF + n = ctype.title >> 24 + for i in range(n): + res[i] = _PyUnicode_ExtendedCase(index + i) + return n + res[0] = ch + ctype.title + return 1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L243-L257 # noqa: E501 +@register_jitable +def _PyUnicode_ToUpperFull(ch, res): + ctype = _PyUnicode_gettyperecord(ch) + if (ctype.flags & _PyUnicode_TyperecordMasks.EXTENDED_CASE_MASK): + index = ctype.upper & 0xFFFF + n = ctype.upper >> 24 + for i in range(n): + # Perhaps needed to use unicode._set_code_point() here + res[i] = _PyUnicode_ExtendedCase(index + i) + return n + res[0] = ch + ctype.upper + return 1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L259-L272 # noqa: E501 +@register_jitable +def _PyUnicode_ToFoldedFull(ch, res): + ctype = _PyUnicode_gettyperecord(ch) + extended_case_mask = _PyUnicode_TyperecordMasks.EXTENDED_CASE_MASK + if ctype.flags & extended_case_mask and (ctype.lower >> 20) & 7: + index = (ctype.lower & 0xFFFF) + (ctype.lower >> 24) + n = (ctype.lower >> 20) & 7 + for i in range(n): + res[i] = _PyUnicode_ExtendedCase(index + i) + return n + return _PyUnicode_ToLowerFull(ch, res) + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L274-L279 # noqa: E501 +@register_jitable +def _PyUnicode_IsCased(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.CASED_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L281-L286 # noqa: E501 +@register_jitable +def _PyUnicode_IsCaseIgnorable(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.CASE_IGNORABLE_MASK != 0 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L123-L135 # noqa: E501 +@register_jitable +def _PyUnicode_IsDigit(ch): + if _PyUnicode_ToDigit(ch) < 0: + return 0 + return 1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L106-L118 # noqa: E501 +@register_jitable +def _PyUnicode_IsDecimalDigit(ch): + if _PyUnicode_ToDecimalDigit(ch) < 0: + return 0 + return 1 + + +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodectype.c#L291-L296 # noqa: E501 +@register_jitable +def _PyUnicode_IsSpace(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.SPACE_MASK != 0 + + +@register_jitable +def _PyUnicode_IsAlpha(ch): + ctype = _PyUnicode_gettyperecord(ch) + return ctype.flags & _PyUnicode_TyperecordMasks.ALPHA_MASK != 0 + + +# End code related to/from CPython's unicodectype impl +# ------------------------------------------------------------------------------ + + +# ------------------------------------------------------------------------------ +# Start code related to/from CPython's pyctype + +# From the definition in CPython's Include/pyctype.h +# From: https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L5-L11 # noqa: E501 +class _PY_CTF(IntEnum): + LOWER = 0x01 + UPPER = 0x02 + ALPHA = 0x01 | 0x02 + DIGIT = 0x04 + ALNUM = 0x01 | 0x02 | 0x04 + SPACE = 0x08 + XDIGIT = 0x10 + + +# From the definition in CPython's Python/pyctype.c +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/pyctype.c#L5 # noqa: E501 +_Py_ctype_table = np.array([ + 0, # 0x0 '\x00' + 0, # 0x1 '\x01' + 0, # 0x2 '\x02' + 0, # 0x3 '\x03' + 0, # 0x4 '\x04' + 0, # 0x5 '\x05' + 0, # 0x6 '\x06' + 0, # 0x7 '\x07' + 0, # 0x8 '\x08' + _PY_CTF.SPACE, # 0x9 '\t' + _PY_CTF.SPACE, # 0xa '\n' + _PY_CTF.SPACE, # 0xb '\v' + _PY_CTF.SPACE, # 0xc '\f' + _PY_CTF.SPACE, # 0xd '\r' + 0, # 0xe '\x0e' + 0, # 0xf '\x0f' + 0, # 0x10 '\x10' + 0, # 0x11 '\x11' + 0, # 0x12 '\x12' + 0, # 0x13 '\x13' + 0, # 0x14 '\x14' + 0, # 0x15 '\x15' + 0, # 0x16 '\x16' + 0, # 0x17 '\x17' + 0, # 0x18 '\x18' + 0, # 0x19 '\x19' + 0, # 0x1a '\x1a' + 0, # 0x1b '\x1b' + 0, # 0x1c '\x1c' + 0, # 0x1d '\x1d' + 0, # 0x1e '\x1e' + 0, # 0x1f '\x1f' + _PY_CTF.SPACE, # 0x20 ' ' + 0, # 0x21 '!' + 0, # 0x22 '"' + 0, # 0x23 '#' + 0, # 0x24 '$' + 0, # 0x25 '%' + 0, # 0x26 '&' + 0, # 0x27 "'" + 0, # 0x28 '(' + 0, # 0x29 ')' + 0, # 0x2a '*' + 0, # 0x2b '+' + 0, # 0x2c ',' + 0, # 0x2d '-' + 0, # 0x2e '.' + 0, # 0x2f '/' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x30 '0' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x31 '1' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x32 '2' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x33 '3' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x34 '4' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x35 '5' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x36 '6' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x37 '7' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x38 '8' + _PY_CTF.DIGIT | _PY_CTF.XDIGIT, # 0x39 '9' + 0, # 0x3a ':' + 0, # 0x3b ';' + 0, # 0x3c '<' + 0, # 0x3d '=' + 0, # 0x3e '>' + 0, # 0x3f '?' + 0, # 0x40 '@' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x41 'A' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x42 'B' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x43 'C' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x44 'D' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x45 'E' + _PY_CTF.UPPER | _PY_CTF.XDIGIT, # 0x46 'F' + _PY_CTF.UPPER, # 0x47 'G' + _PY_CTF.UPPER, # 0x48 'H' + _PY_CTF.UPPER, # 0x49 'I' + _PY_CTF.UPPER, # 0x4a 'J' + _PY_CTF.UPPER, # 0x4b 'K' + _PY_CTF.UPPER, # 0x4c 'L' + _PY_CTF.UPPER, # 0x4d 'M' + _PY_CTF.UPPER, # 0x4e 'N' + _PY_CTF.UPPER, # 0x4f 'O' + _PY_CTF.UPPER, # 0x50 'P' + _PY_CTF.UPPER, # 0x51 'Q' + _PY_CTF.UPPER, # 0x52 'R' + _PY_CTF.UPPER, # 0x53 'S' + _PY_CTF.UPPER, # 0x54 'T' + _PY_CTF.UPPER, # 0x55 'U' + _PY_CTF.UPPER, # 0x56 'V' + _PY_CTF.UPPER, # 0x57 'W' + _PY_CTF.UPPER, # 0x58 'X' + _PY_CTF.UPPER, # 0x59 'Y' + _PY_CTF.UPPER, # 0x5a 'Z' + 0, # 0x5b '[' + 0, # 0x5c '\\' + 0, # 0x5d ']' + 0, # 0x5e '^' + 0, # 0x5f '_' + 0, # 0x60 '`' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x61 'a' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x62 'b' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x63 'c' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x64 'd' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x65 'e' + _PY_CTF.LOWER | _PY_CTF.XDIGIT, # 0x66 'f' + _PY_CTF.LOWER, # 0x67 'g' + _PY_CTF.LOWER, # 0x68 'h' + _PY_CTF.LOWER, # 0x69 'i' + _PY_CTF.LOWER, # 0x6a 'j' + _PY_CTF.LOWER, # 0x6b 'k' + _PY_CTF.LOWER, # 0x6c 'l' + _PY_CTF.LOWER, # 0x6d 'm' + _PY_CTF.LOWER, # 0x6e 'n' + _PY_CTF.LOWER, # 0x6f 'o' + _PY_CTF.LOWER, # 0x70 'p' + _PY_CTF.LOWER, # 0x71 'q' + _PY_CTF.LOWER, # 0x72 'r' + _PY_CTF.LOWER, # 0x73 's' + _PY_CTF.LOWER, # 0x74 't' + _PY_CTF.LOWER, # 0x75 'u' + _PY_CTF.LOWER, # 0x76 'v' + _PY_CTF.LOWER, # 0x77 'w' + _PY_CTF.LOWER, # 0x78 'x' + _PY_CTF.LOWER, # 0x79 'y' + _PY_CTF.LOWER, # 0x7a 'z' + 0, # 0x7b '{' + 0, # 0x7c '|' + 0, # 0x7d '}' + 0, # 0x7e '~' + 0, # 0x7f '\x7f' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +], dtype=np.intc) + + +# From the definition in CPython's Python/pyctype.c +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/pyctype.c#L145 # noqa: E501 +_Py_ctype_tolower = np.array([ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, +], dtype=np.uint8) + + +# From the definition in CPython's Python/pyctype.c +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/pyctype.c#L180 +_Py_ctype_toupper = np.array([ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, + 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, +], dtype=np.uint8) + + +class _PY_CTF_LB(IntEnum): + LINE_BREAK = 0x01 + LINE_FEED = 0x02 + CARRIAGE_RETURN = 0x04 + + +_Py_ctype_islinebreak = np.array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + _PY_CTF_LB.LINE_BREAK | _PY_CTF_LB.LINE_FEED, # 0xa '\n' + _PY_CTF_LB.LINE_BREAK, # 0xb '\v' + _PY_CTF_LB.LINE_BREAK, # 0xc '\f' + _PY_CTF_LB.LINE_BREAK | _PY_CTF_LB.CARRIAGE_RETURN, # 0xd '\r' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + _PY_CTF_LB.LINE_BREAK, # 0x1c '\x1c' + _PY_CTF_LB.LINE_BREAK, # 0x1d '\x1d' + _PY_CTF_LB.LINE_BREAK, # 0x1e '\x1e' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + _PY_CTF_LB.LINE_BREAK, # 0x85 '\x85' + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, +], dtype=np.intc) + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pymacro.h#L25 # noqa: E501 +@register_jitable +def _Py_CHARMASK(ch): + """ + Equivalent to the CPython macro `Py_CHARMASK()`, masks off all but the + lowest 256 bits of ch. + """ + return types.uint8(ch) & types.uint8(0xff) + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L30 # noqa: E501 +@register_jitable +def _Py_TOUPPER(ch): + """ + Equivalent to the CPython macro `Py_TOUPPER()` converts an ASCII range + code point to the upper equivalent + """ + return _Py_ctype_toupper[_Py_CHARMASK(ch)] + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L29 # noqa: E501 +@register_jitable +def _Py_TOLOWER(ch): + """ + Equivalent to the CPython macro `Py_TOLOWER()` converts an ASCII range + code point to the lower equivalent + """ + return _Py_ctype_tolower[_Py_CHARMASK(ch)] + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L18 # noqa: E501 +@register_jitable +def _Py_ISLOWER(ch): + """ + Equivalent to the CPython macro `Py_ISLOWER()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.LOWER + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L19 # noqa: E501 +@register_jitable +def _Py_ISUPPER(ch): + """ + Equivalent to the CPython macro `Py_ISUPPER()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.UPPER + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L20 # noqa: E501 +@register_jitable +def _Py_ISALPHA(ch): + """ + Equivalent to the CPython macro `Py_ISALPHA()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALPHA + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L21 # noqa: E501 +@register_jitable +def _Py_ISDIGIT(ch): + """ + Equivalent to the CPython macro `Py_ISDIGIT()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.DIGIT + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L22 # noqa: E501 +@register_jitable +def _Py_ISXDIGIT(ch): + """ + Equivalent to the CPython macro `Py_ISXDIGIT()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.XDIGIT + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L23 # noqa: E501 +@register_jitable +def _Py_ISALNUM(ch): + """ + Equivalent to the CPython macro `Py_ISALNUM()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.ALNUM + + +# Translation of: +# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Include/pyctype.h#L24 # noqa: E501 +@register_jitable +def _Py_ISSPACE(ch): + """ + Equivalent to the CPython macro `Py_ISSPACE()` + """ + return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.SPACE + + +@register_jitable +def _Py_ISLINEBREAK(ch): + """Check if character is ASCII line break""" + return _Py_ctype_islinebreak[_Py_CHARMASK(ch)] & _PY_CTF_LB.LINE_BREAK + + +@register_jitable +def _Py_ISLINEFEED(ch): + """Check if character is line feed `\n`""" + return _Py_ctype_islinebreak[_Py_CHARMASK(ch)] & _PY_CTF_LB.LINE_FEED + + +@register_jitable +def _Py_ISCARRIAGERETURN(ch): + """Check if character is carriage return `\r`""" + return _Py_ctype_islinebreak[_Py_CHARMASK(ch)] & _PY_CTF_LB.CARRIAGE_RETURN + + +# End code related to/from CPython's pyctype +# ------------------------------------------------------------------------------ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a30c316c4a524b3a41a080dd7e82fe597e6f130 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/__init__.py @@ -0,0 +1,22 @@ +from numba import runtests +from numba.core import config + +if config.ENABLE_CUDASIM: + from .simulator_init import * +else: + from .device_init import * + from .device_init import _auto_device + +from numba.cuda.compiler import (compile, compile_for_current_device, + compile_ptx, compile_ptx_for_current_device) + +# Are we the numba.cuda built in to upstream Numba, or the out-of-tree +# NVIDIA-maintained target? +implementation = "Built-in" + + +def test(*args, **kwargs): + if not is_available(): + raise cuda_error() + + return runtests.main("numba.cuda.tests", *args, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api.py new file mode 100644 index 0000000000000000000000000000000000000000..43847496fa17e618fbdbf4e9478360e008f88ab5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api.py @@ -0,0 +1,525 @@ +""" +API that are reported to numba.cuda +""" + + +import contextlib +import os + +import numpy as np + +from .cudadrv import devicearray, devices, driver +from numba.core import config +from numba.cuda.api_util import prepare_shape_strides_dtype + +# NDarray device helper + +require_context = devices.require_context +current_context = devices.get_context +gpus = devices.gpus + + +@require_context +def from_cuda_array_interface(desc, owner=None, sync=True): + """Create a DeviceNDArray from a cuda-array-interface description. + The ``owner`` is the owner of the underlying memory. + The resulting DeviceNDArray will acquire a reference from it. + + If ``sync`` is ``True``, then the imported stream (if present) will be + synchronized. + """ + version = desc.get('version') + # Mask introduced in version 1 + if 1 <= version: + mask = desc.get('mask') + # Would ideally be better to detect if the mask is all valid + if mask is not None: + raise NotImplementedError('Masked arrays are not supported') + + shape = desc['shape'] + strides = desc.get('strides') + dtype = np.dtype(desc['typestr']) + + shape, strides, dtype = prepare_shape_strides_dtype( + shape, strides, dtype, order='C') + size = driver.memory_size_from_info(shape, strides, dtype.itemsize) + + devptr = driver.get_devptr_for_active_ctx(desc['data'][0]) + data = driver.MemoryPointer( + current_context(), devptr, size=size, owner=owner) + stream_ptr = desc.get('stream', None) + if stream_ptr is not None: + stream = external_stream(stream_ptr) + if sync and config.CUDA_ARRAY_INTERFACE_SYNC: + stream.synchronize() + else: + stream = 0 # No "Numba default stream", not the CUDA default stream + da = devicearray.DeviceNDArray(shape=shape, strides=strides, + dtype=dtype, gpu_data=data, + stream=stream) + return da + + +def as_cuda_array(obj, sync=True): + """Create a DeviceNDArray from any object that implements + the :ref:`cuda array interface `. + + A view of the underlying GPU buffer is created. No copying of the data + is done. The resulting DeviceNDArray will acquire a reference from `obj`. + + If ``sync`` is ``True``, then the imported stream (if present) will be + synchronized. + """ + if not is_cuda_array(obj): + raise TypeError("*obj* doesn't implement the cuda array interface.") + else: + return from_cuda_array_interface(obj.__cuda_array_interface__, + owner=obj, sync=sync) + + +def is_cuda_array(obj): + """Test if the object has defined the `__cuda_array_interface__` attribute. + + Does not verify the validity of the interface. + """ + return hasattr(obj, '__cuda_array_interface__') + + +def is_float16_supported(): + """Whether 16-bit floats are supported. + + float16 is always supported in current versions of Numba - returns True. + """ + return True + + +@require_context +def to_device(obj, stream=0, copy=True, to=None): + """to_device(obj, stream=0, copy=True, to=None) + + Allocate and transfer a numpy ndarray or structured scalar to the device. + + To copy host->device a numpy array:: + + ary = np.arange(10) + d_ary = cuda.to_device(ary) + + To enqueue the transfer to a stream:: + + stream = cuda.stream() + d_ary = cuda.to_device(ary, stream=stream) + + The resulting ``d_ary`` is a ``DeviceNDArray``. + + To copy device->host:: + + hary = d_ary.copy_to_host() + + To copy device->host to an existing array:: + + ary = np.empty(shape=d_ary.shape, dtype=d_ary.dtype) + d_ary.copy_to_host(ary) + + To enqueue the transfer to a stream:: + + hary = d_ary.copy_to_host(stream=stream) + """ + if to is None: + to, new = devicearray.auto_device(obj, stream=stream, copy=copy, + user_explicit=True) + return to + if copy: + to.copy_to_device(obj, stream=stream) + return to + + +@require_context +def device_array(shape, dtype=np.float64, strides=None, order='C', stream=0): + """device_array(shape, dtype=np.float64, strides=None, order='C', stream=0) + + Allocate an empty device ndarray. Similar to :meth:`numpy.empty`. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + return devicearray.DeviceNDArray(shape=shape, strides=strides, dtype=dtype, + stream=stream) + + +@require_context +def managed_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + attach_global=True): + """managed_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + attach_global=True) + + Allocate a np.ndarray with a buffer that is managed. + Similar to np.empty(). + + Managed memory is supported on Linux / x86 and PowerPC, and is considered + experimental on Windows and Linux / AArch64. + + :param attach_global: A flag indicating whether to attach globally. Global + attachment implies that the memory is accessible from + any stream on any device. If ``False``, attachment is + *host*, and memory is only accessible by devices + with Compute Capability 6.0 and later. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize) + buffer = current_context().memallocmanaged(bytesize, + attach_global=attach_global) + npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + managedview = np.ndarray.view(npary, type=devicearray.ManagedNDArray) + managedview.device_setup(buffer, stream=stream) + return managedview + + +@require_context +def pinned_array(shape, dtype=np.float64, strides=None, order='C'): + """pinned_array(shape, dtype=np.float64, strides=None, order='C') + + Allocate an :class:`ndarray ` with a buffer that is pinned + (pagelocked). Similar to :func:`np.empty() `. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, + dtype.itemsize) + buffer = current_context().memhostalloc(bytesize) + return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + + +@require_context +def mapped_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + portable=False, wc=False): + """mapped_array(shape, dtype=np.float64, strides=None, order='C', stream=0, + portable=False, wc=False) + + Allocate a mapped ndarray with a buffer that is pinned and mapped on + to the device. Similar to np.empty() + + :param portable: a boolean flag to allow the allocated device memory to be + usable in multiple devices. + :param wc: a boolean flag to enable writecombined allocation which is faster + to write by the host and to read by the device, but slower to + write by the host and slower to write by the device. + """ + shape, strides, dtype = prepare_shape_strides_dtype(shape, strides, dtype, + order) + bytesize = driver.memory_size_from_info(shape, strides, dtype.itemsize) + buffer = current_context().memhostalloc(bytesize, mapped=True) + npary = np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order, + buffer=buffer) + mappedview = np.ndarray.view(npary, type=devicearray.MappedNDArray) + mappedview.device_setup(buffer, stream=stream) + return mappedview + + +@contextlib.contextmanager +@require_context +def open_ipc_array(handle, shape, dtype, strides=None, offset=0): + """ + A context manager that opens a IPC *handle* (*CUipcMemHandle*) that is + represented as a sequence of bytes (e.g. *bytes*, tuple of int) + and represent it as an array of the given *shape*, *strides* and *dtype*. + The *strides* can be omitted. In that case, it is assumed to be a 1D + C contiguous array. + + Yields a device array. + + The IPC handle is closed automatically when context manager exits. + """ + dtype = np.dtype(dtype) + # compute size + size = np.prod(shape) * dtype.itemsize + # manually recreate the IPC mem handle + if driver.USE_NV_BINDING: + driver_handle = driver.binding.CUipcMemHandle() + driver_handle.reserved = handle + else: + driver_handle = driver.drvapi.cu_ipc_mem_handle(*handle) + # use *IpcHandle* to open the IPC memory + ipchandle = driver.IpcHandle(None, driver_handle, size, offset=offset) + yield ipchandle.open_array(current_context(), shape=shape, + strides=strides, dtype=dtype) + ipchandle.close() + + +def synchronize(): + "Synchronize the current context." + return current_context().synchronize() + + +def _contiguous_strides_like_array(ary): + """ + Given an array, compute strides for a new contiguous array of the same + shape. + """ + # Don't recompute strides if the default strides will be sufficient to + # create a contiguous array. + if ary.flags['C_CONTIGUOUS'] or ary.flags['F_CONTIGUOUS'] or ary.ndim <= 1: + return None + + # Otherwise, we need to compute new strides using an algorithm adapted from + # NumPy v1.17.4's PyArray_NewLikeArrayWithShape in + # core/src/multiarray/ctors.c. We permute the strides in ascending order + # then compute the stride for the dimensions with the same permutation. + + # Stride permutation. E.g. a stride array (4, -2, 12) becomes + # [(1, -2), (0, 4), (2, 12)] + strideperm = [ x for x in enumerate(ary.strides) ] + strideperm.sort(key=lambda x: x[1]) + + # Compute new strides using permutation + strides = [0] * len(ary.strides) + stride = ary.dtype.itemsize + for i_perm, _ in strideperm: + strides[i_perm] = stride + stride *= ary.shape[i_perm] + return tuple(strides) + + +def _order_like_array(ary): + if ary.flags['F_CONTIGUOUS'] and not ary.flags['C_CONTIGUOUS']: + return 'F' + else: + return 'C' + + +def device_array_like(ary, stream=0): + """ + Call :func:`device_array() ` with information from + the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return device_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order, stream=stream) + + +def mapped_array_like(ary, stream=0, portable=False, wc=False): + """ + Call :func:`mapped_array() ` with the information + from the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return mapped_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order, stream=stream, portable=portable, wc=wc) + + +def pinned_array_like(ary): + """ + Call :func:`pinned_array() ` with the information + from the array. + """ + strides = _contiguous_strides_like_array(ary) + order = _order_like_array(ary) + return pinned_array(shape=ary.shape, dtype=ary.dtype, strides=strides, + order=order) + + +# Stream helper +@require_context +def stream(): + """ + Create a CUDA stream that represents a command queue for the device. + """ + return current_context().create_stream() + + +@require_context +def default_stream(): + """ + Get the default CUDA stream. CUDA semantics in general are that the default + stream is either the legacy default stream or the per-thread default stream + depending on which CUDA APIs are in use. In Numba, the APIs for the legacy + default stream are always the ones in use, but an option to use APIs for + the per-thread default stream may be provided in future. + """ + return current_context().get_default_stream() + + +@require_context +def legacy_default_stream(): + """ + Get the legacy default CUDA stream. + """ + return current_context().get_legacy_default_stream() + + +@require_context +def per_thread_default_stream(): + """ + Get the per-thread default CUDA stream. + """ + return current_context().get_per_thread_default_stream() + + +@require_context +def external_stream(ptr): + """Create a Numba stream object for a stream allocated outside Numba. + + :param ptr: Pointer to the external stream to wrap in a Numba Stream + :type ptr: int + """ + return current_context().create_external_stream(ptr) + + +# Page lock +@require_context +@contextlib.contextmanager +def pinned(*arylist): + """A context manager for temporary pinning a sequence of host ndarrays. + """ + pmlist = [] + for ary in arylist: + pm = current_context().mempin(ary, driver.host_pointer(ary), + driver.host_memory_size(ary), + mapped=False) + pmlist.append(pm) + yield + + +@require_context +@contextlib.contextmanager +def mapped(*arylist, **kws): + """A context manager for temporarily mapping a sequence of host ndarrays. + """ + assert not kws or 'stream' in kws, "Only accept 'stream' as keyword." + stream = kws.get('stream', 0) + pmlist = [] + devarylist = [] + for ary in arylist: + pm = current_context().mempin(ary, driver.host_pointer(ary), + driver.host_memory_size(ary), + mapped=True) + pmlist.append(pm) + devary = devicearray.from_array_like(ary, gpu_data=pm, stream=stream) + devarylist.append(devary) + try: + if len(devarylist) == 1: + yield devarylist[0] + else: + yield devarylist + finally: + # When exiting from `with cuda.mapped(*arrs) as mapped_arrs:`, the name + # `mapped_arrs` stays in scope, blocking automatic unmapping based on + # reference count. We therefore invoke the finalizer manually. + for pm in pmlist: + pm.free() + + +def event(timing=True): + """ + Create a CUDA event. Timing data is only recorded by the event if it is + created with ``timing=True``. + """ + evt = current_context().create_event(timing=timing) + return evt + + +event_elapsed_time = driver.event_elapsed_time + + +# Device selection + +def select_device(device_id): + """ + Make the context associated with device *device_id* the current context. + + Returns a Device instance. + + Raises exception on error. + """ + context = devices.get_context(device_id) + return context.device + + +def get_current_device(): + "Get current device associated with the current thread" + return current_context().device + + +def list_devices(): + "Return a list of all detected devices" + return devices.gpus + + +def close(): + """ + Explicitly clears all contexts in the current thread, and destroys all + contexts if the current thread is the main thread. + """ + devices.reset() + + +def _auto_device(ary, stream=0, copy=True): + return devicearray.auto_device(ary, stream=stream, copy=copy) + + +def detect(): + """ + Detect supported CUDA hardware and print a summary of the detected hardware. + + Returns a boolean indicating whether any supported devices were detected. + """ + devlist = list_devices() + print('Found %d CUDA devices' % len(devlist)) + supported_count = 0 + for dev in devlist: + attrs = [] + cc = dev.compute_capability + kernel_timeout = dev.KERNEL_EXEC_TIMEOUT + tcc = dev.TCC_DRIVER + fp32_to_fp64_ratio = dev.SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO + attrs += [('Compute Capability', '%d.%d' % cc)] + attrs += [('PCI Device ID', dev.PCI_DEVICE_ID)] + attrs += [('PCI Bus ID', dev.PCI_BUS_ID)] + attrs += [('UUID', dev.uuid)] + attrs += [('Watchdog', 'Enabled' if kernel_timeout else 'Disabled')] + if os.name == "nt": + attrs += [('Compute Mode', 'TCC' if tcc else 'WDDM')] + attrs += [('FP32/FP64 Performance Ratio', fp32_to_fp64_ratio)] + if cc < (3, 5): + support = '[NOT SUPPORTED: CC < 3.5]' + elif cc < (5, 0): + support = '[SUPPORTED (DEPRECATED)]' + supported_count += 1 + else: + support = '[SUPPORTED]' + supported_count += 1 + + print('id %d %20s %40s' % (dev.id, dev.name, support)) + for key, val in attrs: + print('%40s: %s' % (key, val)) + + print('Summary:') + print('\t%d/%d devices are supported' % (supported_count, len(devlist))) + return supported_count > 0 + + +@contextlib.contextmanager +def defer_cleanup(): + """ + Temporarily disable memory deallocation. + Use this to prevent resource deallocation breaking asynchronous execution. + + For example:: + + with defer_cleanup(): + # all cleanup is deferred in here + do_speed_critical_code() + # cleanup can occur here + + Note: this context manager can be nested. + """ + with current_context().defer_cleanup(): + yield + + +profiling = require_context(driver.profiling) +profile_start = require_context(driver.profile_start) +profile_stop = require_context(driver.profile_stop) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api_util.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b8bffb7c108bde4335793599434bf1465360758f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/api_util.py @@ -0,0 +1,30 @@ +import numpy as np + + +def prepare_shape_strides_dtype(shape, strides, dtype, order): + dtype = np.dtype(dtype) + if isinstance(shape, int): + shape = (shape,) + if isinstance(strides, int): + strides = (strides,) + else: + strides = strides or _fill_stride_by_order(shape, dtype, order) + return shape, strides, dtype + + +def _fill_stride_by_order(shape, dtype, order): + nd = len(shape) + if nd == 0: + return () + strides = [0] * nd + if order == 'C': + strides[-1] = dtype.itemsize + for d in reversed(range(nd - 1)): + strides[d] = strides[d + 1] * shape[d + 1] + elif order == 'F': + strides[0] = dtype.itemsize + for d in range(1, nd): + strides[d] = strides[d - 1] * shape[d - 1] + else: + raise ValueError('must be either C/F order') + return tuple(strides) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/args.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/args.py new file mode 100644 index 0000000000000000000000000000000000000000..472bd0b873f46d0bbe8b091e7dc35ffa7ed6d077 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/args.py @@ -0,0 +1,77 @@ +""" +Hints to wrap Kernel arguments to indicate how to manage host-device +memory transfers before & after the kernel call. +""" +import abc + +from numba.core.typing.typeof import typeof, Purpose + + +class ArgHint(metaclass=abc.ABCMeta): + def __init__(self, value): + self.value = value + + @abc.abstractmethod + def to_device(self, retr, stream=0): + """ + :param stream: a stream to use when copying data + :param retr: + a list of clean-up work to do after the kernel's been run. + Append 0-arg lambdas to it! + :return: a value (usually an `DeviceNDArray`) to be passed to + the kernel + """ + pass + + @property + def _numba_type_(self): + return typeof(self.value, Purpose.argument) + + +class In(ArgHint): + def to_device(self, retr, stream=0): + from .cudadrv.devicearray import auto_device + devary, _ = auto_device( + self.value, + stream=stream) + # A dummy writeback functor to keep devary alive until the kernel + # is called. + retr.append(lambda: devary) + return devary + + +class Out(ArgHint): + def to_device(self, retr, stream=0): + from .cudadrv.devicearray import auto_device + devary, conv = auto_device( + self.value, + copy=False, + stream=stream) + if conv: + retr.append(lambda: devary.copy_to_host(self.value, stream=stream)) + return devary + + +class InOut(ArgHint): + def to_device(self, retr, stream=0): + from .cudadrv.devicearray import auto_device + devary, conv = auto_device( + self.value, + stream=stream) + if conv: + retr.append(lambda: devary.copy_to_host(self.value, stream=stream)) + return devary + + +def wrap_arg(value, default=InOut): + return value if isinstance(value, ArgHint) else default(value) + + +__all__ = [ + 'In', + 'Out', + 'InOut', + + 'ArgHint', + 'wrap_arg', +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cg.py new file mode 100644 index 0000000000000000000000000000000000000000..00d55704befe578fcc529586bc8696ca9261c6db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cg.py @@ -0,0 +1,62 @@ +from numba.core import types +from numba.core.extending import overload, overload_method +from numba.core.typing import signature +from numba.cuda import nvvmutils +from numba.cuda.extending import intrinsic +from numba.cuda.types import grid_group, GridGroup as GridGroupClass + + +class GridGroup: + """A cooperative group representing the entire grid""" + + def sync() -> None: + """Synchronize this grid group""" + + +def this_grid() -> GridGroup: + """Get the current grid group.""" + return GridGroup() + + +@intrinsic +def _this_grid(typingctx): + sig = signature(grid_group) + + def codegen(context, builder, sig, args): + one = context.get_constant(types.int32, 1) + mod = builder.module + return builder.call( + nvvmutils.declare_cudaCGGetIntrinsicHandle(mod), + (one,)) + + return sig, codegen + + +@overload(this_grid, target='cuda') +def _ol_this_grid(): + def impl(): + return _this_grid() + + return impl + + +@intrinsic +def _grid_group_sync(typingctx, group): + sig = signature(types.int32, group) + + def codegen(context, builder, sig, args): + flags = context.get_constant(types.int32, 0) + mod = builder.module + return builder.call( + nvvmutils.declare_cudaCGSynchronize(mod), + (*args, flags)) + + return sig, codegen + + +@overload_method(GridGroupClass, 'sync', target='cuda') +def _ol_grid_group_sync(group): + def impl(group): + return _grid_group_sync(group) + + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/codegen.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..6009dcbdcc7d3a7c5aaf51b106126fa8fbb6696b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/codegen.py @@ -0,0 +1,378 @@ +from llvmlite import ir + +from numba.core import config, serialize +from numba.core.codegen import Codegen, CodeLibrary +from .cudadrv import devices, driver, nvvm, runtime +from numba.cuda.cudadrv.libs import get_cudalib + +import os +import subprocess +import tempfile + + +CUDA_TRIPLE = 'nvptx64-nvidia-cuda' + + +def run_nvdisasm(cubin, flags): + # nvdisasm only accepts input from a file, so we need to write out to a + # temp file and clean up afterwards. + fd = None + fname = None + try: + fd, fname = tempfile.mkstemp() + with open(fname, 'wb') as f: + f.write(cubin) + + try: + cp = subprocess.run(['nvdisasm', *flags, fname], check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + except FileNotFoundError as e: + msg = ("nvdisasm has not been found. You may need " + "to install the CUDA toolkit and ensure that " + "it is available on your PATH.\n") + raise RuntimeError(msg) from e + return cp.stdout.decode('utf-8') + finally: + if fd is not None: + os.close(fd) + if fname is not None: + os.unlink(fname) + + +def disassemble_cubin(cubin): + # Request lineinfo in disassembly + flags = ['-gi'] + return run_nvdisasm(cubin, flags) + + +def disassemble_cubin_for_cfg(cubin): + # Request control flow graph in disassembly + flags = ['-cfg'] + return run_nvdisasm(cubin, flags) + + +class CUDACodeLibrary(serialize.ReduceMixin, CodeLibrary): + """ + The CUDACodeLibrary generates PTX, SASS, cubins for multiple different + compute capabilities. It also loads cubins to multiple devices (via + get_cufunc), which may be of different compute capabilities. + """ + + def __init__(self, codegen, name, entry_name=None, max_registers=None, + nvvm_options=None): + """ + codegen: + Codegen object. + name: + Name of the function in the source. + entry_name: + Name of the kernel function in the binary, if this is a global + kernel and not a device function. + max_registers: + The maximum register usage to aim for when linking. + nvvm_options: + Dict of options to pass to NVVM. + """ + super().__init__(codegen, name) + + # The llvmlite module for this library. + self._module = None + # CodeLibrary objects that will be "linked" into this library. The + # modules within them are compiled from NVVM IR to PTX along with the + # IR from this module - in that sense they are "linked" by NVVM at PTX + # generation time, rather than at link time. + self._linking_libraries = set() + # Files to link with the generated PTX. These are linked using the + # Driver API at link time. + self._linking_files = set() + # Should we link libcudadevrt? + self.needs_cudadevrt = False + + # Cache the LLVM IR string + self._llvm_strs = None + # Maps CC -> PTX string + self._ptx_cache = {} + # Maps CC -> LTO-IR + self._ltoir_cache = {} + # Maps CC -> cubin + self._cubin_cache = {} + # Maps CC -> linker info output for cubin + self._linkerinfo_cache = {} + # Maps Device numeric ID -> cufunc + self._cufunc_cache = {} + + self._max_registers = max_registers + if nvvm_options is None: + nvvm_options = {} + self._nvvm_options = nvvm_options + self._entry_name = entry_name + + @property + def llvm_strs(self): + if self._llvm_strs is None: + self._llvm_strs = [str(mod) for mod in self.modules] + return self._llvm_strs + + def get_llvm_str(self): + return "\n\n".join(self.llvm_strs) + + def _ensure_cc(self, cc): + if cc is not None: + return cc + + device = devices.get_context().device + return device.compute_capability + + def get_asm_str(self, cc=None): + cc = self._ensure_cc(cc) + + ptxes = self._ptx_cache.get(cc, None) + if ptxes: + return ptxes + + arch = nvvm.get_arch_option(*cc) + options = self._nvvm_options.copy() + options['arch'] = arch + + irs = self.llvm_strs + + ptx = nvvm.compile_ir(irs, **options) + + # Sometimes the result from NVVM contains trailing whitespace and + # nulls, which we strip so that the assembly dump looks a little + # tidier. + ptx = ptx.decode().strip('\x00').strip() + + if config.DUMP_ASSEMBLY: + print(("ASSEMBLY %s" % self._name).center(80, '-')) + print(ptx) + print('=' * 80) + + self._ptx_cache[cc] = ptx + + return ptx + + def get_ltoir(self, cc=None): + cc = self._ensure_cc(cc) + + ltoir = self._ltoir_cache.get(cc, None) + if ltoir is not None: + return ltoir + + arch = nvvm.get_arch_option(*cc) + options = self._nvvm_options.copy() + options['arch'] = arch + options['gen-lto'] = None + + irs = self.llvm_strs + ltoir = nvvm.compile_ir(irs, **options) + self._ltoir_cache[cc] = ltoir + + return ltoir + + def get_cubin(self, cc=None): + cc = self._ensure_cc(cc) + + cubin = self._cubin_cache.get(cc, None) + if cubin: + return cubin + + linker = driver.Linker.new(max_registers=self._max_registers, cc=cc) + + if linker.lto: + ltoir = self.get_ltoir(cc=cc) + linker.add_ltoir(ltoir) + else: + ptx = self.get_asm_str(cc=cc) + linker.add_ptx(ptx.encode()) + + for path in self._linking_files: + linker.add_file_guess_ext(path) + if self.needs_cudadevrt: + linker.add_file_guess_ext(get_cudalib('cudadevrt', static=True)) + + cubin = linker.complete() + self._cubin_cache[cc] = cubin + self._linkerinfo_cache[cc] = linker.info_log + + return cubin + + def get_cufunc(self): + if self._entry_name is None: + msg = "Missing entry_name - are you trying to get the cufunc " \ + "for a device function?" + raise RuntimeError(msg) + + ctx = devices.get_context() + device = ctx.device + + cufunc = self._cufunc_cache.get(device.id, None) + if cufunc: + return cufunc + + cubin = self.get_cubin(cc=device.compute_capability) + module = ctx.create_module_image(cubin) + + # Load + cufunc = module.get_function(self._entry_name) + + # Populate caches + self._cufunc_cache[device.id] = cufunc + + return cufunc + + def get_linkerinfo(self, cc): + try: + return self._linkerinfo_cache[cc] + except KeyError: + raise KeyError(f'No linkerinfo for CC {cc}') + + def get_sass(self, cc=None): + return disassemble_cubin(self.get_cubin(cc=cc)) + + def get_sass_cfg(self, cc=None): + return disassemble_cubin_for_cfg(self.get_cubin(cc=cc)) + + def add_ir_module(self, mod): + self._raise_if_finalized() + if self._module is not None: + raise RuntimeError('CUDACodeLibrary only supports one module') + self._module = mod + + def add_linking_library(self, library): + library._ensure_finalized() + + # We don't want to allow linking more libraries in after finalization + # because our linked libraries are modified by the finalization, and we + # won't be able to finalize again after adding new ones + self._raise_if_finalized() + + self._linking_libraries.add(library) + + def add_linking_file(self, filepath): + self._linking_files.add(filepath) + + def get_function(self, name): + for fn in self._module.functions: + if fn.name == name: + return fn + raise KeyError(f'Function {name} not found') + + @property + def modules(self): + return [self._module] + [mod for lib in self._linking_libraries + for mod in lib.modules] + + @property + def linking_libraries(self): + # Libraries we link to may link to other libraries, so we recursively + # traverse the linking libraries property to build up a list of all + # linked libraries. + libs = [] + for lib in self._linking_libraries: + libs.extend(lib.linking_libraries) + libs.append(lib) + return libs + + def finalize(self): + # Unlike the CPUCodeLibrary, we don't invoke the binding layer here - + # we only adjust the linkage of functions. Global kernels (with + # external linkage) have their linkage untouched. Device functions are + # set linkonce_odr to prevent them appearing in the PTX. + + self._raise_if_finalized() + + # Note in-place modification of the linkage of functions in linked + # libraries. This presently causes no issues as only device functions + # are shared across code libraries, so they would always need their + # linkage set to linkonce_odr. If in a future scenario some code + # libraries require linkonce_odr linkage of functions in linked + # modules, and another code library requires another linkage, each code + # library will need to take its own private copy of its linked modules. + # + # See also discussion on PR #890: + # https://github.com/numba/numba/pull/890 + for library in self._linking_libraries: + for mod in library.modules: + for fn in mod.functions: + if not fn.is_declaration: + fn.linkage = 'linkonce_odr' + + self._finalized = True + + def _reduce_states(self): + """ + Reduce the instance for serialization. We retain the PTX and cubins, + but loaded functions are discarded. They are recreated when needed + after deserialization. + """ + if self._linking_files: + msg = 'Cannot pickle CUDACodeLibrary with linking files' + raise RuntimeError(msg) + if not self._finalized: + raise RuntimeError('Cannot pickle unfinalized CUDACodeLibrary') + return dict( + codegen=None, + name=self.name, + entry_name=self._entry_name, + llvm_strs=self.llvm_strs, + ptx_cache=self._ptx_cache, + cubin_cache=self._cubin_cache, + linkerinfo_cache=self._linkerinfo_cache, + max_registers=self._max_registers, + nvvm_options=self._nvvm_options, + needs_cudadevrt=self.needs_cudadevrt + ) + + @classmethod + def _rebuild(cls, codegen, name, entry_name, llvm_strs, ptx_cache, + cubin_cache, linkerinfo_cache, max_registers, nvvm_options, + needs_cudadevrt): + """ + Rebuild an instance. + """ + instance = cls(codegen, name, entry_name=entry_name) + + instance._llvm_strs = llvm_strs + instance._ptx_cache = ptx_cache + instance._cubin_cache = cubin_cache + instance._linkerinfo_cache = linkerinfo_cache + + instance._max_registers = max_registers + instance._nvvm_options = nvvm_options + instance.needs_cudadevrt = needs_cudadevrt + + instance._finalized = True + + return instance + + +class JITCUDACodegen(Codegen): + """ + This codegen implementation for CUDA only generates optimized LLVM IR. + Generation of PTX code is done separately (see numba.cuda.compiler). + """ + + _library_class = CUDACodeLibrary + + def __init__(self, module_name): + pass + + def _create_empty_module(self, name): + ir_module = ir.Module(name) + ir_module.triple = CUDA_TRIPLE + ir_module.data_layout = nvvm.NVVM().data_layout + nvvm.add_ir_version(ir_module) + return ir_module + + def _add_module(self, module): + pass + + def magic_tuple(self): + """ + Return a tuple unambiguously describing the codegen behaviour. + """ + ctx = devices.get_context() + cc = ctx.device.compute_capability + return (runtime.runtime.get_version(), cc) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/compiler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e2bcb08919eddff275b89e03a19fee4b817fe0e2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/compiler.py @@ -0,0 +1,422 @@ +from llvmlite import ir +from numba.core.typing.templates import ConcreteTemplate +from numba.core import types, typing, funcdesc, config, compiler, sigutils +from numba.core.compiler import (sanitize_compile_result_entries, CompilerBase, + DefaultPassBuilder, Flags, Option, + CompileResult) +from numba.core.compiler_lock import global_compiler_lock +from numba.core.compiler_machinery import (LoweringPass, + PassManager, register_pass) +from numba.core.errors import NumbaInvalidConfigWarning +from numba.core.typed_passes import (IRLegalization, NativeLowering, + AnnotateTypes) +from warnings import warn +from numba.cuda.api import get_current_device +from numba.cuda.target import CUDACABICallConv + + +def _nvvm_options_type(x): + if x is None: + return None + + else: + assert isinstance(x, dict) + return x + + +class CUDAFlags(Flags): + nvvm_options = Option( + type=_nvvm_options_type, + default=None, + doc="NVVM options", + ) + compute_capability = Option( + type=tuple, + default=None, + doc="Compute Capability", + ) + + +# The CUDACompileResult (CCR) has a specially-defined entry point equal to its +# id. This is because the entry point is used as a key into a dict of +# overloads by the base dispatcher. The id of the CCR is the only small and +# unique property of a CompileResult in the CUDA target (cf. the CPU target, +# which uses its entry_point, which is a pointer value). +# +# This does feel a little hackish, and there are two ways in which this could +# be improved: +# +# 1. We could change the core of Numba so that each CompileResult has its own +# unique ID that can be used as a key - e.g. a count, similar to the way in +# which types have unique counts. +# 2. At some future time when kernel launch uses a compiled function, the entry +# point will no longer need to be a synthetic value, but will instead be a +# pointer to the compiled function as in the CPU target. + +class CUDACompileResult(CompileResult): + @property + def entry_point(self): + return id(self) + + +def cuda_compile_result(**entries): + entries = sanitize_compile_result_entries(entries) + return CUDACompileResult(**entries) + + +@register_pass(mutates_CFG=True, analysis_only=False) +class CUDABackend(LoweringPass): + + _name = "cuda_backend" + + def __init__(self): + LoweringPass.__init__(self) + + def run_pass(self, state): + """ + Back-end: Packages lowering output in a compile result + """ + lowered = state['cr'] + signature = typing.signature(state.return_type, *state.args) + + state.cr = cuda_compile_result( + typing_context=state.typingctx, + target_context=state.targetctx, + typing_error=state.status.fail_reason, + type_annotation=state.type_annotation, + library=state.library, + call_helper=lowered.call_helper, + signature=signature, + fndesc=lowered.fndesc, + ) + return True + + +@register_pass(mutates_CFG=False, analysis_only=False) +class CreateLibrary(LoweringPass): + """ + Create a CUDACodeLibrary for the NativeLowering pass to populate. The + NativeLowering pass will create a code library if none exists, but we need + to set it up with nvvm_options from the flags if they are present. + """ + + _name = "create_library" + + def __init__(self): + LoweringPass.__init__(self) + + def run_pass(self, state): + codegen = state.targetctx.codegen() + name = state.func_id.func_qualname + nvvm_options = state.flags.nvvm_options + state.library = codegen.create_library(name, nvvm_options=nvvm_options) + # Enable object caching upfront so that the library can be serialized. + state.library.enable_object_caching() + + return True + + +class CUDACompiler(CompilerBase): + def define_pipelines(self): + dpb = DefaultPassBuilder + pm = PassManager('cuda') + + untyped_passes = dpb.define_untyped_pipeline(self.state) + pm.passes.extend(untyped_passes.passes) + + typed_passes = dpb.define_typed_pipeline(self.state) + pm.passes.extend(typed_passes.passes) + + lowering_passes = self.define_cuda_lowering_pipeline(self.state) + pm.passes.extend(lowering_passes.passes) + + pm.finalize() + return [pm] + + def define_cuda_lowering_pipeline(self, state): + pm = PassManager('cuda_lowering') + # legalise + pm.add_pass(IRLegalization, + "ensure IR is legal prior to lowering") + pm.add_pass(AnnotateTypes, "annotate types") + + # lower + pm.add_pass(CreateLibrary, "create library") + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(CUDABackend, "cuda backend") + + pm.finalize() + return pm + + +@global_compiler_lock +def compile_cuda(pyfunc, return_type, args, debug=False, lineinfo=False, + inline=False, fastmath=False, nvvm_options=None, + cc=None): + if cc is None: + raise ValueError('Compute Capability must be supplied') + + from .descriptor import cuda_target + typingctx = cuda_target.typing_context + targetctx = cuda_target.target_context + + flags = CUDAFlags() + # Do not compile (generate native code), just lower (to LLVM) + flags.no_compile = True + flags.no_cpython_wrapper = True + flags.no_cfunc_wrapper = True + + # Both debug and lineinfo turn on debug information in the compiled code, + # but we keep them separate arguments in case we later want to overload + # some other behavior on the debug flag. In particular, -opt=3 is not + # supported with debug enabled, and enabling only lineinfo should not + # affect the error model. + if debug or lineinfo: + flags.debuginfo = True + + if lineinfo: + flags.dbg_directives_only = True + + if debug: + flags.error_model = 'python' + else: + flags.error_model = 'numpy' + + if inline: + flags.forceinline = True + if fastmath: + flags.fastmath = True + if nvvm_options: + flags.nvvm_options = nvvm_options + flags.compute_capability = cc + + # Run compilation pipeline + from numba.core.target_extension import target_override + with target_override('cuda'): + cres = compiler.compile_extra(typingctx=typingctx, + targetctx=targetctx, + func=pyfunc, + args=args, + return_type=return_type, + flags=flags, + locals={}, + pipeline_class=CUDACompiler) + + library = cres.library + library.finalize() + + return cres + + +def cabi_wrap_function(context, lib, fndesc, wrapper_function_name, + nvvm_options): + """ + Wrap a Numba ABI function in a C ABI wrapper at the NVVM IR level. + + The C ABI wrapper will have the same name as the source Python function. + """ + # The wrapper will be contained in a new library that links to the wrapped + # function's library + library = lib.codegen.create_library(f'{lib.name}_function_', + entry_name=wrapper_function_name, + nvvm_options=nvvm_options) + library.add_linking_library(lib) + + # Determine the caller (C ABI) and wrapper (Numba ABI) function types + argtypes = fndesc.argtypes + restype = fndesc.restype + c_call_conv = CUDACABICallConv(context) + wrapfnty = c_call_conv.get_function_type(restype, argtypes) + fnty = context.call_conv.get_function_type(fndesc.restype, argtypes) + + # Create a new module and declare the callee + wrapper_module = context.create_module("cuda.cabi.wrapper") + func = ir.Function(wrapper_module, fnty, fndesc.llvm_func_name) + + # Define the caller - populate it with a call to the callee and return + # its return value + + wrapfn = ir.Function(wrapper_module, wrapfnty, wrapper_function_name) + builder = ir.IRBuilder(wrapfn.append_basic_block('')) + + arginfo = context.get_arg_packer(argtypes) + callargs = arginfo.from_arguments(builder, wrapfn.args) + # We get (status, return_value), but we ignore the status since we + # can't propagate it through the C ABI anyway + _, return_value = context.call_conv.call_function( + builder, func, restype, argtypes, callargs) + builder.ret(return_value) + + library.add_ir_module(wrapper_module) + library.finalize() + return library + + +@global_compiler_lock +def compile(pyfunc, sig, debug=False, lineinfo=False, device=True, + fastmath=False, cc=None, opt=True, abi="c", abi_info=None, + output='ptx'): + """Compile a Python function to PTX or LTO-IR for a given set of argument + types. + + :param pyfunc: The Python function to compile. + :param sig: The signature representing the function's input and output + types. If this is a tuple of argument types without a return + type, the inferred return type is returned by this function. If + a signature including a return type is passed, the compiled code + will include a cast from the inferred return type to the + specified return type, and this function will return the + specified return type. + :param debug: Whether to include debug info in the compiled code. + :type debug: bool + :param lineinfo: Whether to include a line mapping from the compiled code + to the source code. Usually this is used with optimized + code (since debug mode would automatically include this), + so we want debug info in the LLVM IR but only the line + mapping in the final output. + :type lineinfo: bool + :param device: Whether to compile a device function. + :type device: bool + :param fastmath: Whether to enable fast math flags (ftz=1, prec_sqrt=0, + prec_div=, and fma=1) + :type fastmath: bool + :param cc: Compute capability to compile for, as a tuple + ``(MAJOR, MINOR)``. Defaults to ``(5, 0)``. + :type cc: tuple + :param opt: Enable optimizations. Defaults to ``True``. + :type opt: bool + :param abi: The ABI for a compiled function - either ``"numba"`` or + ``"c"``. Note that the Numba ABI is not considered stable. + The C ABI is only supported for device functions at present. + :type abi: str + :param abi_info: A dict of ABI-specific options. The ``"c"`` ABI supports + one option, ``"abi_name"``, for providing the wrapper + function's name. The ``"numba"`` ABI has no options. + :type abi_info: dict + :param output: Type of output to generate, either ``"ptx"`` or ``"ltoir"``. + :type output: str + :return: (code, resty): The compiled code and inferred return type + :rtype: tuple + """ + if abi not in ("numba", "c"): + raise NotImplementedError(f'Unsupported ABI: {abi}') + + if abi == 'c' and not device: + raise NotImplementedError('The C ABI is not supported for kernels') + + if output not in ("ptx", "ltoir"): + raise NotImplementedError(f'Unsupported output type: {output}') + + if debug and opt: + msg = ("debug=True with opt=True (the default) " + "is not supported by CUDA. This may result in a crash" + " - set debug=False or opt=False.") + warn(NumbaInvalidConfigWarning(msg)) + + lto = (output == 'ltoir') + abi_info = abi_info or dict() + + nvvm_options = { + 'fastmath': fastmath, + 'opt': 3 if opt else 0 + } + + if lto: + nvvm_options['gen-lto'] = None + + args, return_type = sigutils.normalize_signature(sig) + + cc = cc or config.CUDA_DEFAULT_PTX_CC + cres = compile_cuda(pyfunc, return_type, args, debug=debug, + lineinfo=lineinfo, fastmath=fastmath, + nvvm_options=nvvm_options, cc=cc) + resty = cres.signature.return_type + + if resty and not device and resty != types.void: + raise TypeError("CUDA kernel must have void return type.") + + tgt = cres.target_context + + if device: + lib = cres.library + if abi == "c": + wrapper_name = abi_info.get('abi_name', pyfunc.__name__) + lib = cabi_wrap_function(tgt, lib, cres.fndesc, wrapper_name, + nvvm_options) + else: + code = pyfunc.__code__ + filename = code.co_filename + linenum = code.co_firstlineno + + lib, kernel = tgt.prepare_cuda_kernel(cres.library, cres.fndesc, debug, + lineinfo, nvvm_options, filename, + linenum) + + if lto: + code = lib.get_ltoir(cc=cc) + else: + code = lib.get_asm_str(cc=cc) + return code, resty + + +def compile_for_current_device(pyfunc, sig, debug=False, lineinfo=False, + device=True, fastmath=False, opt=True, + abi="c", abi_info=None, output='ptx'): + """Compile a Python function to PTX or LTO-IR for a given signature for the + current device's compute capabilility. This calls :func:`compile` with an + appropriate ``cc`` value for the current device.""" + cc = get_current_device().compute_capability + return compile(pyfunc, sig, debug=debug, lineinfo=lineinfo, device=device, + fastmath=fastmath, cc=cc, opt=opt, abi=abi, + abi_info=abi_info, output=output) + + +def compile_ptx(pyfunc, sig, debug=False, lineinfo=False, device=False, + fastmath=False, cc=None, opt=True, abi="numba", abi_info=None): + """Compile a Python function to PTX for a given signature. See + :func:`compile`. The defaults for this function are to compile a kernel + with the Numba ABI, rather than :func:`compile`'s default of compiling a + device function with the C ABI.""" + return compile(pyfunc, sig, debug=debug, lineinfo=lineinfo, device=device, + fastmath=fastmath, cc=cc, opt=opt, abi=abi, + abi_info=abi_info, output='ptx') + + +def compile_ptx_for_current_device(pyfunc, sig, debug=False, lineinfo=False, + device=False, fastmath=False, opt=True, + abi="numba", abi_info=None): + """Compile a Python function to PTX for a given signature for the current + device's compute capabilility. See :func:`compile_ptx`.""" + cc = get_current_device().compute_capability + return compile_ptx(pyfunc, sig, debug=debug, lineinfo=lineinfo, + device=device, fastmath=fastmath, cc=cc, opt=opt, + abi=abi, abi_info=abi_info) + + +def declare_device_function(name, restype, argtypes): + return declare_device_function_template(name, restype, argtypes).key + + +def declare_device_function_template(name, restype, argtypes): + from .descriptor import cuda_target + typingctx = cuda_target.typing_context + targetctx = cuda_target.target_context + sig = typing.signature(restype, *argtypes) + extfn = ExternFunction(name, sig) + + class device_function_template(ConcreteTemplate): + key = extfn + cases = [sig] + + fndesc = funcdesc.ExternalFunctionDescriptor( + name=name, restype=restype, argtypes=argtypes) + typingctx.insert_user_function(extfn, device_function_template) + targetctx.insert_user_function(extfn, fndesc) + + return device_function_template + + +class ExternFunction(object): + def __init__(self, name, sig): + self.name = name + self.sig = sig diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cpp_function_wrappers.cu b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cpp_function_wrappers.cu new file mode 100644 index 0000000000000000000000000000000000000000..a2cd1e054c40ebce33016fff1bcd9d869be9f07c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cpp_function_wrappers.cu @@ -0,0 +1,47 @@ +#include "cuda_fp16.h" + +#define FNDEF(fname) __numba_wrapper_ ## fname + +#define UNARY_FUNCTION(fname) extern "C" __device__ int\ + FNDEF(fname)( \ + short* return_value,\ + short x\ +)\ +{\ + __half retval = fname(__short_as_half (x));\ +\ + *return_value = __half_as_short (retval);\ + /* Signal that no Python exception occurred */ \ + return 0;\ +}\ + +extern "C" __device__ int +FNDEF(hdiv)( + short* return_value, + short x, + short y +) +{ + __half retval = __hdiv(__short_as_half (x), __short_as_half (y)); + + *return_value = __half_as_short (retval); + // Signal that no Python exception occurred + return 0; +} + +UNARY_FUNCTION(hsin) +UNARY_FUNCTION(hcos) +UNARY_FUNCTION(hlog) +UNARY_FUNCTION(hlog10) +UNARY_FUNCTION(hlog2) +UNARY_FUNCTION(hexp) +UNARY_FUNCTION(hexp10) +UNARY_FUNCTION(hexp2) +UNARY_FUNCTION(hsqrt) +UNARY_FUNCTION(hrsqrt) +UNARY_FUNCTION(hfloor) +UNARY_FUNCTION(hceil) +UNARY_FUNCTION(hrcp) +UNARY_FUNCTION(hrint) +UNARY_FUNCTION(htrunc) + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..3001595e9a4cbe2d20a3c81ffe00bd981e82c9b6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.h @@ -0,0 +1,3631 @@ +/* +* Copyright 1993-2021 NVIDIA Corporation. All rights reserved. +* +* NOTICE TO LICENSEE: +* +* This source code and/or documentation ("Licensed Deliverables") are +* subject to NVIDIA intellectual property rights under U.S. and +* international Copyright laws. +* +* These Licensed Deliverables contained herein is PROPRIETARY and +* CONFIDENTIAL to NVIDIA and is being provided under the terms and +* conditions of a form of NVIDIA software license agreement by and +* between NVIDIA and Licensee ("License Agreement") or electronically +* accepted by Licensee. Notwithstanding any terms or conditions to +* the contrary in the License Agreement, reproduction or disclosure +* of the Licensed Deliverables to any third party without the express +* written consent of NVIDIA is prohibited. +* +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE +* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS +* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. +* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED +* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, +* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY +* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY +* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +* OF THESE LICENSED DELIVERABLES. +* +* U.S. Government End Users. These Licensed Deliverables are a +* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT +* 1995), consisting of "commercial computer software" and "commercial +* computer software documentation" as such terms are used in 48 +* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government +* only as a commercial end item. Consistent with 48 C.F.R.12.212 and +* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all +* U.S. Government End Users acquire the Licensed Deliverables with +* only those rights set forth herein. +* +* Any use of the Licensed Deliverables in individual and commercial +* software must include, in the user documentation and internal +* comments to the code, the above Disclaimer and U.S. Government End +* Users Notice. +*/ + +/** +* \defgroup CUDA_MATH_INTRINSIC_HALF Half Precision Intrinsics +* This section describes half precision intrinsic functions that are +* only supported in device code. +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF_ARITHMETIC Half Arithmetic Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF2_ARITHMETIC Half2 Arithmetic Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF_COMPARISON Half Comparison Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF2_COMPARISON Half2 Comparison Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF_MISC Half Precision Conversion and Data Movement +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF_FUNCTIONS Half Math Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +/** +* \defgroup CUDA_MATH__HALF2_FUNCTIONS Half2 Math Functions +* \ingroup CUDA_MATH_INTRINSIC_HALF +* To use these functions, include the header file \p cuda_fp16.h in your program. +*/ + +#ifndef __CUDA_FP16_H__ +#define __CUDA_FP16_H__ + +#if defined(__cplusplus) +#if defined(__CUDACC__) +#define __CUDA_FP16_DECL__ static __device__ __inline__ +#define __CUDA_HOSTDEVICE_FP16_DECL__ static __host__ __device__ __inline__ +#else +#define __CUDA_HOSTDEVICE_FP16_DECL__ static +#endif /* defined(__CUDACC__) */ + +#define __CUDA_FP16_TYPES_EXIST__ + +/* Forward-declaration of structures defined in "cuda_fp16.hpp" */ + +/** + * \brief half datatype + * + * \details This structure implements the datatype for storing + * half-precision floating-point numbers. The structure implements + * assignment operators and type conversions. + * 16 bits are being used in total: 1 sign bit, 5 bits for the exponent, + * and the significand is being stored in 10 bits. + * The total precision is 11 bits. There are 15361 representable + * numbers within the interval [0.0, 1.0], endpoints included. + * On average we have log10(2**11) ~ 3.311 decimal digits. + * + * \internal + * \req IEEE 754-2008 compliant implementation of half-precision + * floating-point numbers. + * \endinternal + */ +struct __half; + +/** + * \brief half2 datatype + * + * \details This structure implements the datatype for storing two + * half-precision floating-point numbers. + * The structure implements assignment operators and type conversions. + * + * \internal + * \req Vectorified version of half. + * \endinternal + */ +struct __half2; + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts double number to half precision in round-to-nearest-even mode +* and returns \p half with converted value. +* +* \details Converts double number \p a to half precision in round-to-nearest-even mode. +* \param[in] a - double. Is only being read. +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __double2half(const double a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts float number to half precision in round-to-nearest-even mode +* and returns \p half with converted value. +* +* \details Converts float number \p a to half precision in round-to-nearest-even mode. +* \param[in] a - float. Is only being read. +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts float number to half precision in round-to-nearest-even mode +* and returns \p half with converted value. +* +* \details Converts float number \p a to half precision in round-to-nearest-even mode. +* \param[in] a - float. Is only being read. +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rn(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts float number to half precision in round-towards-zero mode +* and returns \p half with converted value. +* +* \details Converts float number \p a to half precision in round-towards-zero mode. +* \param[in] a - float. Is only being read. +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rz(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts float number to half precision in round-down mode +* and returns \p half with converted value. +* +* \details Converts float number \p a to half precision in round-down mode. +* \param[in] a - float. Is only being read. +* +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rd(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts float number to half precision in round-up mode +* and returns \p half with converted value. +* +* \details Converts float number \p a to half precision in round-up mode. +* \param[in] a - float. Is only being read. +* +* \returns half +* \retval a converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_ru(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts \p half number to float. +* +* \details Converts half number \p a to float. +* \param[in] a - float. Is only being read. +* +* \returns float +* \retval a converted to float. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ float __half2float(const __half a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts input to half precision in round-to-nearest-even mode and +* populates both halves of \p half2 with converted value. +* +* \details Converts input \p a to half precision in round-to-nearest-even mode and +* populates both halves of \p half2 with converted value. +* \param[in] a - float. Is only being read. +* +* \returns half2 +* \retval The \p half2 value with both halves equal to the converted half +* precision number. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __float2half2_rn(const float a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts both input floats to half precision in round-to-nearest-even +* mode and returns \p half2 with converted values. +* +* \details Converts both input floats to half precision in round-to-nearest-even mode +* and combines the results into one \p half2 number. Low 16 bits of the return +* value correspond to the input \p a, high 16 bits correspond to the input \p +* b. +* \param[in] a - float. Is only being read. +* \param[in] b - float. Is only being read. +* +* \returns half2 +* \retval The \p half2 value with corresponding halves equal to the +* converted input floats. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __floats2half2_rn(const float a, const float b); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts low 16 bits of \p half2 to float and returns the result +* +* \details Converts low 16 bits of \p half2 input \p a to 32-bit floating-point number +* and returns the result. +* \param[in] a - half2. Is only being read. +* +* \returns float +* \retval The low 16 bits of \p a converted to float. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ float __low2float(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts high 16 bits of \p half2 to float and returns the result +* +* \details Converts high 16 bits of \p half2 input \p a to 32-bit floating-point number +* and returns the result. +* \param[in] a - half2. Is only being read. +* +* \returns float +* \retval The high 16 bits of \p a converted to float. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ float __high2float(const __half2 a); + +#if defined(__CUDACC__) +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts both components of float2 number to half precision in +* round-to-nearest-even mode and returns \p half2 with converted values. +* +* \details Converts both components of float2 to half precision in round-to-nearest +* mode and combines the results into one \p half2 number. Low 16 bits of the +* return value correspond to \p a.x and high 16 bits of the return value +* correspond to \p a.y. +* \param[in] a - float2. Is only being read. +* +* \returns half2 +* \retval The \p half2 which has corresponding halves equal to the +* converted float2 components. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __float22half2_rn(const float2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Converts both halves of \p half2 to float2 and returns the result. +* +* \details Converts both halves of \p half2 input \p a to float2 and returns the +* result. +* \param[in] a - half2. Is only being read. +* +* \returns float2 +* \retval a converted to float2. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ float2 __half22float2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed integer in round-to-nearest-even mode. +* +* \details Convert the half-precision floating-point value \p h to a signed integer in +* round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns int +* \retval h converted to a signed integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ int __half2int_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed integer in round-towards-zero mode. +* +* \details Convert the half-precision floating-point value \p h to a signed integer in +* round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns int +* \retval h converted to a signed integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ int __half2int_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to a signed integer in +* round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns int +* \retval h converted to a signed integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ int __half2int_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to a signed integer in +* round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns int +* \retval h converted to a signed integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ int __half2int_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed integer to a half in round-to-nearest-even mode. +* +* \details Convert the signed integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __int2half_rn(const int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed integer to a half in round-towards-zero mode. +* +* \details Convert the signed integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __int2half_rz(const int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed integer to a half in round-down mode. +* +* \details Convert the signed integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __int2half_rd(const int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed integer to a half in round-up mode. +* +* \details Convert the signed integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __int2half_ru(const int i); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed short integer in round-to-nearest-even +* mode. +* +* \details Convert the half-precision floating-point value \p h to a signed short +* integer in round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns short int +* \retval h converted to a signed short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ short int __half2short_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed short integer in round-towards-zero mode. +* +* \details Convert the half-precision floating-point value \p h to a signed short +* integer in round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns short int +* \retval h converted to a signed short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ short int __half2short_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed short integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to a signed short +* integer in round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns short int +* \retval h converted to a signed short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ short int __half2short_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed short integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to a signed short +* integer in round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns short int +* \retval h converted to a signed short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ short int __half2short_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed short integer to a half in round-to-nearest-even +* mode. +* +* \details Convert the signed short integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __short2half_rn(const short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed short integer to a half in round-towards-zero mode. +* +* \details Convert the signed short integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __short2half_rz(const short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed short integer to a half in round-down mode. +* +* \details Convert the signed short integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __short2half_rd(const short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed short integer to a half in round-up mode. +* +* \details Convert the signed short integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __short2half_ru(const short int i); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned integer in round-to-nearest-even mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned integer +* in round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned int +* \retval h converted to an unsigned integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned int __half2uint_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned integer in round-towards-zero mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned integer +* in round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned int +* \retval h converted to an unsigned integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned int __half2uint_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned integer +* in round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned int +* \retval h converted to an unsigned integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned int __half2uint_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned integer +* in round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned int +* \retval h converted to an unsigned integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned int __half2uint_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned integer to a half in round-to-nearest-even mode. +* +* \details Convert the unsigned integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - unsigned int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __uint2half_rn(const unsigned int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned integer to a half in round-towards-zero mode. +* +* \details Convert the unsigned integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - unsigned int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __uint2half_rz(const unsigned int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned integer to a half in round-down mode. +* +* \details Convert the unsigned integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - unsigned int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __uint2half_rd(const unsigned int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned integer to a half in round-up mode. +* +* \details Convert the unsigned integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - unsigned int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __uint2half_ru(const unsigned int i); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned short integer in round-to-nearest-even +* mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned short +* integer in round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned short int +* \retval h converted to an unsigned short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned short int __half2ushort_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned short integer in round-towards-zero +* mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned short +* integer in round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned short int +* \retval h converted to an unsigned short integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned short int __half2ushort_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned short integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned short +* integer in round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned short int +* \retval h converted to an unsigned short integer. +*/ +__CUDA_FP16_DECL__ unsigned short int __half2ushort_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned short integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned short +* integer in round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned short int +* \retval h converted to an unsigned short integer. +*/ +__CUDA_FP16_DECL__ unsigned short int __half2ushort_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned short integer to a half in round-to-nearest-even +* mode. +* +* \details Convert the unsigned short integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - unsigned short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ushort2half_rn(const unsigned short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned short integer to a half in round-towards-zero +* mode. +* +* \details Convert the unsigned short integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - unsigned short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ushort2half_rz(const unsigned short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned short integer to a half in round-down mode. +* +* \details Convert the unsigned short integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - unsigned short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ushort2half_rd(const unsigned short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned short integer to a half in round-up mode. +* +* \details Convert the unsigned short integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - unsigned short int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ushort2half_ru(const unsigned short int i); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned 64-bit integer in round-to-nearest-even +* mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned 64-bit +* integer in round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned long long int +* \retval h converted to an unsigned 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned long long int __half2ull_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned 64-bit integer in round-towards-zero +* mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned 64-bit +* integer in round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned long long int +* \retval h converted to an unsigned 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned long long int __half2ull_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned 64-bit integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned 64-bit +* integer in round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned long long int +* \retval h converted to an unsigned 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned long long int __half2ull_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to an unsigned 64-bit integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to an unsigned 64-bit +* integer in round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns unsigned long long int +* \retval h converted to an unsigned 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned long long int __half2ull_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned 64-bit integer to a half in round-to-nearest-even +* mode. +* +* \details Convert the unsigned 64-bit integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - unsigned long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ull2half_rn(const unsigned long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned 64-bit integer to a half in round-towards-zero +* mode. +* +* \details Convert the unsigned 64-bit integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - unsigned long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ull2half_rz(const unsigned long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned 64-bit integer to a half in round-down mode. +* +* \details Convert the unsigned 64-bit integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - unsigned long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ull2half_rd(const unsigned long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert an unsigned 64-bit integer to a half in round-up mode. +* +* \details Convert the unsigned 64-bit integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - unsigned long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ull2half_ru(const unsigned long long int i); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed 64-bit integer in round-to-nearest-even +* mode. +* +* \details Convert the half-precision floating-point value \p h to a signed 64-bit +* integer in round-to-nearest-even mode. +* \param[in] h - half. Is only being read. +* +* \returns long long int +* \retval h converted to a signed 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ long long int __half2ll_rn(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed 64-bit integer in round-towards-zero mode. +* +* \details Convert the half-precision floating-point value \p h to a signed 64-bit +* integer in round-towards-zero mode. +* \param[in] h - half. Is only being read. +* +* \returns long long int +* \retval h converted to a signed 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ long long int __half2ll_rz(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed 64-bit integer in round-down mode. +* +* \details Convert the half-precision floating-point value \p h to a signed 64-bit +* integer in round-down mode. +* \param[in] h - half. Is only being read. +* +* \returns long long int +* \retval h converted to a signed 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ long long int __half2ll_rd(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a half to a signed 64-bit integer in round-up mode. +* +* \details Convert the half-precision floating-point value \p h to a signed 64-bit +* integer in round-up mode. +* \param[in] h - half. Is only being read. +* +* \returns long long int +* \retval h converted to a signed 64-bit integer. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ long long int __half2ll_ru(const __half h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed 64-bit integer to a half in round-to-nearest-even +* mode. +* +* \details Convert the signed 64-bit integer value \p i to a half-precision floating-point +* value in round-to-nearest-even mode. +* \param[in] i - long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ll2half_rn(const long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed 64-bit integer to a half in round-towards-zero mode. +* +* \details Convert the signed 64-bit integer value \p i to a half-precision floating-point +* value in round-towards-zero mode. +* \param[in] i - long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +*/ +__CUDA_FP16_DECL__ __half __ll2half_rz(const long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed 64-bit integer to a half in round-down mode. +* +* \details Convert the signed 64-bit integer value \p i to a half-precision floating-point +* value in round-down mode. +* \param[in] i - long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ll2half_rd(const long long int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Convert a signed 64-bit integer to a half in round-up mode. +* +* \details Convert the signed 64-bit integer value \p i to a half-precision floating-point +* value in round-up mode. +* \param[in] i - long long int. Is only being read. +* +* \returns half +* \retval i converted to half. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ll2half_ru(const long long int i); + +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Truncate input argument to the integral part. +* +* \details Round \p h to the nearest integer value that does not exceed \p h in +* magnitude. +* \param[in] h - half. Is only being read. +* +* \returns half +* \retval The truncated integer value. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half htrunc(const __half h); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculate ceiling of the input argument. +* +* \details Compute the smallest integer value not less than \p h. +* \param[in] h - half. Is only being read. +* +* \returns half +* \retval The smallest integer value not less than \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hceil(const __half h); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculate the largest integer less than or equal to \p h. +* +* \details Calculate the largest integer value which is less than or equal to \p h. +* \param[in] h - half. Is only being read. +* +* \returns half +* \retval The largest integer value which is less than or equal to \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hfloor(const __half h); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Round input to nearest integer value in half-precision floating-point +* number. +* +* \details Round \p h to the nearest integer value in half-precision floating-point +* format, with halfway cases rounded to the nearest even integer value. +* \param[in] h - half. Is only being read. +* +* \returns half +* \retval The nearest integer to \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hrint(const __half h); + +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Truncate \p half2 vector input argument to the integral part. +* +* \details Round each component of vector \p h to the nearest integer value that does +* not exceed \p h in magnitude. +* \param[in] h - half2. Is only being read. +* +* \returns half2 +* \retval The truncated \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2trunc(const __half2 h); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculate \p half2 vector ceiling of the input argument. +* +* \details For each component of vector \p h compute the smallest integer value not less +* than \p h. +* \param[in] h - half2. Is only being read. +* +* \returns half2 +* \retval The vector of smallest integers not less than \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2ceil(const __half2 h); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculate the largest integer less than or equal to \p h. +* +* \details For each component of vector \p h calculate the largest integer value which +* is less than or equal to \p h. +* \param[in] h - half2. Is only being read. +* +* \returns half2 +* \retval The vector of largest integers which is less than or equal to \p h. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2floor(const __half2 h); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Round input to nearest integer value in half-precision floating-point +* number. +* +* \details Round each component of \p half2 vector \p h to the nearest integer value in +* half-precision floating-point format, with halfway cases rounded to the +* nearest even integer value. +* \param[in] h - half2. Is only being read. +* +* \returns half2 +* \retval The vector of rounded integer values. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2rint(const __half2 h); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Returns \p half2 with both halves equal to the input value. +* +* \details Returns \p half2 number with both halves equal to the input \p a \p half +* number. +* \param[in] a - half. Is only being read. +* +* \returns half2 +* \retval The vector which has both its halves equal to the input \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __half2half2(const __half a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Swaps both halves of the \p half2 input. +* +* \details Swaps both halves of the \p half2 input and returns a new \p half2 number +* with swapped halves. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval a with its halves being swapped. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __lowhigh2highlow(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Extracts low 16 bits from each of the two \p half2 inputs and combines +* into one \p half2 number. +* +* \details Extracts low 16 bits from each of the two \p half2 inputs and combines into +* one \p half2 number. Low 16 bits from input \p a is stored in low 16 bits of +* the return value, low 16 bits from input \p b is stored in high 16 bits of +* the return value. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The low 16 bits of \p a and of \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __lows2half2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Extracts high 16 bits from each of the two \p half2 inputs and +* combines into one \p half2 number. +* +* \details Extracts high 16 bits from each of the two \p half2 inputs and combines into +* one \p half2 number. High 16 bits from input \p a is stored in low 16 bits of +* the return value, high 16 bits from input \p b is stored in high 16 bits of +* the return value. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The high 16 bits of \p a and of \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __highs2half2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Returns high 16 bits of \p half2 input. +* +* \details Returns high 16 bits of \p half2 input \p a. +* \param[in] a - half2. Is only being read. +* +* \returns half +* \retval The high 16 bits of the input. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __high2half(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Returns low 16 bits of \p half2 input. +* +* \details Returns low 16 bits of \p half2 input \p a. +* \param[in] a - half2. Is only being read. +* +* \returns half +* \retval Returns \p half which contains low 16 bits of the input \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __low2half(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Checks if the input \p half number is infinite. +* +* \details Checks if the input \p half number \p a is infinite. +* \param[in] a - half. Is only being read. +* +* \returns int +* \retval -1 iff \p a is equal to negative infinity, +* \retval 1 iff \p a is equal to positive infinity, +* \retval 0 otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ int __hisinf(const __half a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Combines two \p half numbers into one \p half2 number. +* +* \details Combines two input \p half number \p a and \p b into one \p half2 number. +* Input \p a is stored in low 16 bits of the return value, input \p b is stored +* in high 16 bits of the return value. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half2 +* \retval The half2 with one half equal to \p a and the other to \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __halves2half2(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Extracts low 16 bits from \p half2 input. +* +* \details Extracts low 16 bits from \p half2 input \p a and returns a new \p half2 +* number which has both halves equal to the extracted bits. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The half2 with both halves equal to the low 16 bits of the input. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __low2half2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Extracts high 16 bits from \p half2 input. +* +* \details Extracts high 16 bits from \p half2 input \p a and returns a new \p half2 +* number which has both halves equal to the extracted bits. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The half2 with both halves equal to the high 16 bits of the input. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __high2half2(const __half2 a); + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Reinterprets bits in a \p half as a signed short integer. +* +* \details Reinterprets the bits in the half-precision floating-point number \p h +* as a signed short integer. +* \param[in] h - half. Is only being read. +* +* \returns short int +* \retval The reinterpreted value. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ short int __half_as_short(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Reinterprets bits in a \p half as an unsigned short integer. +* +* \details Reinterprets the bits in the half-precision floating-point \p h +* as an unsigned short number. +* \param[in] h - half. Is only being read. +* +* \returns unsigned short int +* \retval The reinterpreted value. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ unsigned short int __half_as_ushort(const __half h); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Reinterprets bits in a signed short integer as a \p half. +* +* \details Reinterprets the bits in the signed short integer \p i as a +* half-precision floating-point number. +* \param[in] i - short int. Is only being read. +* +* \returns half +* \retval The reinterpreted value. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __short_as_half(const short int i); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Reinterprets bits in an unsigned short integer as a \p half. +* +* \details Reinterprets the bits in the unsigned short integer \p i as a +* half-precision floating-point number. +* \param[in] i - unsigned short int. Is only being read. +* +* \returns half +* \retval The reinterpreted value. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __ushort_as_half(const unsigned short int i); + +#if __CUDA_ARCH__ >= 300 || !defined(__CUDA_ARCH__) +#if !defined warpSize && !defined __local_warpSize +#define warpSize 32 +#define __local_warpSize +#endif + +#if defined(_WIN32) +# define __DEPRECATED__(msg) __declspec(deprecated(msg)) +#elif (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5 && !defined(__clang__)))) +# define __DEPRECATED__(msg) __attribute__((deprecated)) +#else +# define __DEPRECATED__(msg) __attribute__((deprecated(msg))) +#endif + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 +#define __WSB_DEPRECATION_MESSAGE(x) #x"() is deprecated in favor of "#x"_sync() and may be removed in a future release (Use -Wno-deprecated-declarations to suppress this warning)." + +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl)) __half2 __shfl(const __half2 var, const int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_up)) __half2 __shfl_up(const __half2 var, const unsigned int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_down))__half2 __shfl_down(const __half2 var, const unsigned int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_xor)) __half2 __shfl_xor(const __half2 var, const int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl)) __half __shfl(const __half var, const int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_up)) __half __shfl_up(const __half var, const unsigned int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_down)) __half __shfl_down(const __half var, const unsigned int delta, const int width = warpSize); +__CUDA_FP16_DECL__ __DEPRECATED__(__WSB_DEPRECATION_MESSAGE(__shfl_xor)) __half __shfl_xor(const __half var, const int delta, const int width = warpSize); +#endif + +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Direct copy from indexed thread. +* +* \details Returns the value of var held by the thread whose ID is given by delta. +* If width is less than warpSize then each subsection of the warp behaves as a separate +* entity with a starting logical thread ID of 0. If delta is outside the range [0:width-1], +* the value returned corresponds to the value of var held by the delta modulo width (i.e. +* within the same subsection). width must have a value which is a power of 2; +* results are undefined if width is not a power of 2, or is a number greater than +* warpSize. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half2. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 4-byte word referenced by var from the source thread ID as half2. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __shfl_sync(const unsigned mask, const __half2 var, const int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread with lower ID relative to the caller. +* +* \details Calculates a source thread ID by subtracting delta from the caller's lane ID. +* The value of var held by the resulting lane ID is returned: in effect, var is shifted up +* the warp by delta threads. If width is less than warpSize then each subsection of the warp +* behaves as a separate entity with a starting logical thread ID of 0. The source thread index +* will not wrap around the value of width, so effectively the lower delta threads will be unchanged. +* width must have a value which is a power of 2; results are undefined if width is not a power of 2, +* or is a number greater than warpSize. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half2. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 4-byte word referenced by var from the source thread ID as half2. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __shfl_up_sync(const unsigned mask, const __half2 var, const unsigned int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread with higher ID relative to the caller. +* +* \details Calculates a source thread ID by adding delta to the caller's thread ID. +* The value of var held by the resulting thread ID is returned: this has the effect +* of shifting var down the warp by delta threads. If width is less than warpSize then +* each subsection of the warp behaves as a separate entity with a starting logical +* thread ID of 0. As for __shfl_up_sync(), the ID number of the source thread +* will not wrap around the value of width and so the upper delta threads +* will remain unchanged. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half2. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 4-byte word referenced by var from the source thread ID as half2. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __shfl_down_sync(const unsigned mask, const __half2 var, const unsigned int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread based on bitwise XOR of own thread ID. +* +* \details Calculates a source thread ID by performing a bitwise XOR of the caller's thread ID with mask: +* the value of var held by the resulting thread ID is returned. If width is less than warpSize then each +* group of width consecutive threads are able to access elements from earlier groups of threads, +* however if they attempt to access elements from later groups of threads their own value of var +* will be returned. This mode implements a butterfly addressing pattern such as is used in tree +* reduction and broadcast. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half2. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 4-byte word referenced by var from the source thread ID as half2. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __shfl_xor_sync(const unsigned mask, const __half2 var, const int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Direct copy from indexed thread. +* +* \details Returns the value of var held by the thread whose ID is given by delta. +* If width is less than warpSize then each subsection of the warp behaves as a separate +* entity with a starting logical thread ID of 0. If delta is outside the range [0:width-1], +* the value returned corresponds to the value of var held by the delta modulo width (i.e. +* within the same subsection). width must have a value which is a power of 2; +* results are undefined if width is not a power of 2, or is a number greater than +* warpSize. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 2-byte word referenced by var from the source thread ID as half. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __shfl_sync(const unsigned mask, const __half var, const int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread with lower ID relative to the caller. +* \details Calculates a source thread ID by subtracting delta from the caller's lane ID. +* The value of var held by the resulting lane ID is returned: in effect, var is shifted up +* the warp by delta threads. If width is less than warpSize then each subsection of the warp +* behaves as a separate entity with a starting logical thread ID of 0. The source thread index +* will not wrap around the value of width, so effectively the lower delta threads will be unchanged. +* width must have a value which is a power of 2; results are undefined if width is not a power of 2, +* or is a number greater than warpSize. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 2-byte word referenced by var from the source thread ID as half. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __shfl_up_sync(const unsigned mask, const __half var, const unsigned int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread with higher ID relative to the caller. +* +* \details Calculates a source thread ID by adding delta to the caller's thread ID. +* The value of var held by the resulting thread ID is returned: this has the effect +* of shifting var down the warp by delta threads. If width is less than warpSize then +* each subsection of the warp behaves as a separate entity with a starting logical +* thread ID of 0. As for __shfl_up_sync(), the ID number of the source thread +* will not wrap around the value of width and so the upper delta threads +* will remain unchanged. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 2-byte word referenced by var from the source thread ID as half. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __shfl_down_sync(const unsigned mask, const __half var, const unsigned int delta, const int width = warpSize); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Exchange a variable between threads within a warp. Copy from a thread based on bitwise XOR of own thread ID. +* +* \details Calculates a source thread ID by performing a bitwise XOR of the caller's thread ID with mask: +* the value of var held by the resulting thread ID is returned. If width is less than warpSize then each +* group of width consecutive threads are able to access elements from earlier groups of threads, +* however if they attempt to access elements from later groups of threads their own value of var +* will be returned. This mode implements a butterfly addressing pattern such as is used in tree +* reduction and broadcast. +* \param[in] mask - unsigned int. Is only being read. +* \param[in] var - half. Is only being read. +* \param[in] delta - int. Is only being read. +* \param[in] width - int. Is only being read. +* +* \returns Returns the 2-byte word referenced by var from the source thread ID as half. +* If the source thread ID is out of range or the source thread has exited, the calling thread's own var is returned. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior not reentrant, not thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __shfl_xor_sync(const unsigned mask, const __half var, const int delta, const int width = warpSize); + +#if defined(__local_warpSize) +#undef warpSize +#undef __local_warpSize +#endif +#endif /*__CUDA_ARCH__ >= 300 || !defined(__CUDA_ARCH__) */ + +#if defined(__cplusplus) && ( __CUDA_ARCH__ >=320 || !defined(__CUDA_ARCH__) ) +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.nc` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldg(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.nc` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldg(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cg` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldcg(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cg` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldcg(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.ca` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldca(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.ca` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldca(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cs` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldcs(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cs` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldcs(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.lu` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldlu(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.lu` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldlu(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cv` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half2 __ldcv(const __half2 *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `ld.global.cv` load instruction. +* \param[in] ptr - memory location +* \returns The value pointed by `ptr` +*/ +__CUDA_FP16_DECL__ __half __ldcv(const __half *const ptr); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.wb` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stwb(__half2 *const ptr, const __half2 value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.wb` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stwb(__half *const ptr, const __half value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.cg` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stcg(__half2 *const ptr, const __half2 value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.cg` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stcg(__half *const ptr, const __half value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.cs` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stcs(__half2 *const ptr, const __half2 value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.cs` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stcs(__half *const ptr, const __half value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.wt` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stwt(__half2 *const ptr, const __half2 value); +/** +* \ingroup CUDA_MATH__HALF_MISC +* \brief Generates a `st.global.wt` store instruction. +* \param[out] ptr - memory location +* \param[in] value - the value to be stored +*/ +__CUDA_FP16_DECL__ void __stwt(__half *const ptr, const __half value); +#endif /*defined(__cplusplus) && ( __CUDA_ARCH__ >=320 || !defined(__CUDA_ARCH__) )*/ + +#if __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__) +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs half2 vector if-equal comparison. +* +* \details Performs \p half2 vector if-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of if-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __heq2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector not-equal comparison. +* +* \details Performs \p half2 vector not-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of not-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hne2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector less-equal comparison. +* +* \details Performs \p half2 vector less-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The \p half2 result of less-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hle2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector greater-equal comparison. +* +* \details Performs \p half2 vector greater-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of greater-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hge2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector less-than comparison. +* +* \details Performs \p half2 vector less-than comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The half2 vector result of less-than comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hlt2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector greater-than comparison. +* +* \details Performs \p half2 vector greater-than comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of greater-than comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hgt2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered if-equal comparison. +* +* \details Performs \p half2 vector if-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of unordered if-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hequ2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered not-equal comparison. +* +* \details Performs \p half2 vector not-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of unordered not-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hneu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered less-equal comparison. +* +* Performs \p half2 vector less-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of unordered less-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hleu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered greater-equal comparison. +* +* \details Performs \p half2 vector greater-equal comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The \p half2 vector result of unordered greater-equal comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hgeu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered less-than comparison. +* +* \details Performs \p half2 vector less-than comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The vector result of unordered less-than comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hltu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered greater-than comparison. +* +* \details Performs \p half2 vector greater-than comparison of inputs \p a and \p b. +* The corresponding \p half results are set to 1.0 for true, or 0.0 for false. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The \p half2 vector result of unordered greater-than comparison of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hgtu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Determine whether \p half2 argument is a NaN. +* +* \details Determine whether each half of input \p half2 number \p a is a NaN. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The half2 with the corresponding \p half results set to +* 1.0 for NaN, 0.0 otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hisnan2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector addition in round-to-nearest-even mode. +* +* \details Performs \p half2 vector add of inputs \p a and \p b, in round-to-nearest +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-95 +* \endinternal +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The sum of vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hadd2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector subtraction in round-to-nearest-even mode. +* +* \details Subtracts \p half2 input vector \p b from input vector \p a in +* round-to-nearest-even mode. +* \internal +* \req DEEPLEARN-SRM_REQ-104 +* \endinternal +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The subtraction of vector \p b from \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hsub2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector multiplication in round-to-nearest-even mode. +* +* \details Performs \p half2 vector multiplication of inputs \p a and \p b, in +* round-to-nearest-even mode. +* \internal +* \req DEEPLEARN-SRM_REQ-102 +* \endinternal +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise multiplying the vectors \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmul2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector division in round-to-nearest-even mode. +* +* \details Divides \p half2 input vector \p a by input vector \p b in round-to-nearest +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-103 +* \endinternal +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise division of \p a with \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __h2div(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Calculates the absolute value of both halves of the input \p half2 number and +* returns the result. +* +* \details Calculates the absolute value of both halves of the input \p half2 number and +* returns the result. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval Returns \p a with the absolute value of both halves. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __habs2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector addition in round-to-nearest-even mode, with +* saturation to [0.0, 1.0]. +* +* \details Performs \p half2 vector add of inputs \p a and \p b, in round-to-nearest +* mode, and clamps the results to range [0.0, 1.0]. NaN results are flushed to +* +0.0. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The sum of \p a and \p b, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hadd2_sat(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector subtraction in round-to-nearest-even mode, +* with saturation to [0.0, 1.0]. +* +* \details Subtracts \p half2 input vector \p b from input vector \p a in +* round-to-nearest-even mode, and clamps the results to range [0.0, 1.0]. NaN +* results are flushed to +0.0. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The subtraction of vector \p b from \p a, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hsub2_sat(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector multiplication in round-to-nearest-even mode, +* with saturation to [0.0, 1.0]. +* +* \details Performs \p half2 vector multiplication of inputs \p a and \p b, in +* round-to-nearest-even mode, and clamps the results to range [0.0, 1.0]. NaN +* results are flushed to +0.0. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise multiplication of vectors \p a and \p b, +* with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmul2_sat(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector fused multiply-add in round-to-nearest-even +* mode. +* +* \details Performs \p half2 vector multiply on inputs \p a and \p b, +* then performs a \p half2 vector add of the result with \p c, +* rounding the result once in round-to-nearest-even mode. +* \internal +* \req DEEPLEARN-SRM_REQ-105 +* \endinternal +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* \param[in] c - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise fused multiply-add operation on vectors \p a, \p b, and \p c. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hfma2(const __half2 a, const __half2 b, const __half2 c); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector fused multiply-add in round-to-nearest-even +* mode, with saturation to [0.0, 1.0]. +* +* \details Performs \p half2 vector multiply on inputs \p a and \p b, +* then performs a \p half2 vector add of the result with \p c, +* rounding the result once in round-to-nearest-even mode, and clamps the +* results to range [0.0, 1.0]. NaN results are flushed to +0.0. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* \param[in] c - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise fused multiply-add operation on vectors \p a, \p b, and \p c, +* with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hfma2_sat(const __half2 a, const __half2 b, const __half2 c); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Negates both halves of the input \p half2 number and returns the +* result. +* +* \details Negates both halves of the input \p half2 number \p a and returns the result. +* \internal +* \req DEEPLEARN-SRM_REQ-101 +* \endinternal +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval Returns \p a with both halves negated. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hneg2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Calculates the absolute value of input \p half number and returns the result. +* +* \details Calculates the absolute value of input \p half number and returns the result. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The absolute value of a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __habs(const __half a); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half addition in round-to-nearest-even mode. +* +* \details Performs \p half addition of inputs \p a and \p b, in round-to-nearest-even +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-94 +* \endinternal +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The sum of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hadd(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half subtraction in round-to-nearest-even mode. +* +* \details Subtracts \p half input \p b from input \p a in round-to-nearest +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-97 +* \endinternal +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The result of subtracting \p b from \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hsub(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half multiplication in round-to-nearest-even mode. +* +* \details Performs \p half multiplication of inputs \p a and \p b, in round-to-nearest +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-99 +* \endinternal +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The result of multiplying \p a and \p b. +*/ +__CUDA_FP16_DECL__ __half __hmul(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half division in round-to-nearest-even mode. +* +* \details Divides \p half input \p a by input \p b in round-to-nearest +* mode. +* \internal +* \req DEEPLEARN-SRM_REQ-98 +* \endinternal +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The result of dividing \p a by \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hdiv(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half addition in round-to-nearest-even mode, with +* saturation to [0.0, 1.0]. +* +* \details Performs \p half add of inputs \p a and \p b, in round-to-nearest-even mode, +* and clamps the result to range [0.0, 1.0]. NaN results are flushed to +0.0. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The sum of \p a and \p b, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hadd_sat(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half subtraction in round-to-nearest-even mode, with +* saturation to [0.0, 1.0]. +* +* \details Subtracts \p half input \p b from input \p a in round-to-nearest +* mode, +* and clamps the result to range [0.0, 1.0]. NaN results are flushed to +0.0. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The result of subtraction of \p b from \p a, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hsub_sat(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half multiplication in round-to-nearest-even mode, with +* saturation to [0.0, 1.0]. +* +* \details Performs \p half multiplication of inputs \p a and \p b, in round-to-nearest +* mode, and clamps the result to range [0.0, 1.0]. NaN results are flushed to +* +0.0. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \retval The result of multiplying \p a and \p b, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hmul_sat(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half fused multiply-add in round-to-nearest-even mode. +* +* \details Performs \p half multiply on inputs \p a and \p b, +* then performs a \p half add of the result with \p c, +* rounding the result once in round-to-nearest-even mode. +* \internal +* \req DEEPLEARN-SRM_REQ-96 +* \endinternal +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* \param[in] c - half. Is only being read. +* +* \returns half +* \retval The result of fused multiply-add operation on \p +* a, \p b, and \p c. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hfma(const __half a, const __half b, const __half c); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half fused multiply-add in round-to-nearest-even mode, +* with saturation to [0.0, 1.0]. +* +* \details Performs \p half multiply on inputs \p a and \p b, +* then performs a \p half add of the result with \p c, +* rounding the result once in round-to-nearest-even mode, and clamps the result +* to range [0.0, 1.0]. NaN results are flushed to +0.0. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* \param[in] c - half. Is only being read. +* +* \returns half +* \retval The result of fused multiply-add operation on \p +* a, \p b, and \p c, with respect to saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hfma_sat(const __half a, const __half b, const __half c); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Negates input \p half number and returns the result. +* +* \details Negates input \p half number and returns the result. +* \internal +* \req DEEPLEARN-SRM_REQ-100 +* \endinternal +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval minus a +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hneg(const __half a); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector if-equal comparison and returns boolean true +* iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector if-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half if-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of if-equal comparison +* of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbeq2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector not-equal comparison and returns boolean +* true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector not-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half not-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of not-equal comparison +* of vectors \p a and \p b are true, +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbne2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector less-equal comparison and returns boolean +* true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector less-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half less-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of less-equal comparison +* of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hble2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector greater-equal comparison and returns boolean +* true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector greater-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half greater-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of greater-equal +* comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbge2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector less-than comparison and returns boolean +* true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector less-than comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half less-than comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of less-than comparison +* of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hblt2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector greater-than comparison and returns boolean +* true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector greater-than comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half greater-than comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate false results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of greater-than +* comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbgt2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered if-equal comparison and returns +* boolean true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector if-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half if-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered if-equal +* comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbequ2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered not-equal comparison and returns +* boolean true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector not-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half not-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered not-equal +* comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbneu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered less-equal comparison and returns +* boolean true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector less-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half less-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered less-equal +* comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbleu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered greater-equal comparison and +* returns boolean true iff both \p half results are true, boolean false +* otherwise. +* +* \details Performs \p half2 vector greater-equal comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half greater-equal comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered +* greater-equal comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbgeu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered less-than comparison and returns +* boolean true iff both \p half results are true, boolean false otherwise. +* +* \details Performs \p half2 vector less-than comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half less-than comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered less-than comparison of +* vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbltu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Performs \p half2 vector unordered greater-than comparison and +* returns boolean true iff both \p half results are true, boolean false +* otherwise. +* +* \details Performs \p half2 vector greater-than comparison of inputs \p a and \p b. +* The bool result is set to true only if both \p half greater-than comparisons +* evaluate to true, or false otherwise. +* NaN inputs generate true results. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns bool +* \retval true if both \p half results of unordered +* greater-than comparison of vectors \p a and \p b are true; +* \retval false otherwise. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hbgtu2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half if-equal comparison. +* +* \details Performs \p half if-equal comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of if-equal comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __heq(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half not-equal comparison. +* +* \details Performs \p half not-equal comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of not-equal comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hne(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half less-equal comparison. +* +* \details Performs \p half less-equal comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of less-equal comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hle(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half greater-equal comparison. +* +* \details Performs \p half greater-equal comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of greater-equal comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hge(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half less-than comparison. +* +* \details Performs \p half less-than comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of less-than comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hlt(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half greater-than comparison. +* +* \details Performs \p half greater-than comparison of inputs \p a and \p b. +* NaN inputs generate false results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of greater-than comparison of \p a and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hgt(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered if-equal comparison. +* +* \details Performs \p half if-equal comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered if-equal comparison of \p a and +* \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hequ(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered not-equal comparison. +* +* \details Performs \p half not-equal comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered not-equal comparison of \p a and +* \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hneu(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered less-equal comparison. +* +* \details Performs \p half less-equal comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered less-equal comparison of \p a and +* \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hleu(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered greater-equal comparison. +* +* \details Performs \p half greater-equal comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered greater-equal comparison of \p a +* and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hgeu(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered less-than comparison. +* +* \details Performs \p half less-than comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered less-than comparison of \p a and +* \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hltu(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Performs \p half unordered greater-than comparison. +* +* \details Performs \p half greater-than comparison of inputs \p a and \p b. +* NaN inputs generate true results. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns bool +* \retval The boolean result of unordered greater-than comparison of \p a +* and \p b. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hgtu(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Determine whether \p half argument is a NaN. +* +* \details Determine whether \p half value \p a is a NaN. +* \param[in] a - half. Is only being read. +* +* \returns bool +* \retval true iff argument is NaN. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ bool __hisnan(const __half a); +#if __CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__) +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Calculates \p half maximum of two input values. +* +* \details Calculates \p half max(\p a, \p b) +* defined as (\p a > \p b) ? \p a : \p b. +* - If either of inputs is NaN, the other input is returned. +* - If both inputs are NaNs, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hmax(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Calculates \p half minimum of two input values. +* +* \details Calculates \p half min(\p a, \p b) +* defined as (\p a < \p b) ? \p a : \p b. +* - If either of inputs is NaN, the other input is returned. +* - If both inputs are NaNs, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hmin(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Calculates \p half maximum of two input values, NaNs pass through. +* +* \details Calculates \p half max(\p a, \p b) +* defined as (\p a > \p b) ? \p a : \p b. +* - If either of inputs is NaN, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hmax_nan(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_COMPARISON +* \brief Calculates \p half minimum of two input values, NaNs pass through. +* +* \details Calculates \p half min(\p a, \p b) +* defined as (\p a < \p b) ? \p a : \p b. +* - If either of inputs is NaN, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* +* \returns half +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hmin_nan(const __half a, const __half b); +/** +* \ingroup CUDA_MATH__HALF_ARITHMETIC +* \brief Performs \p half fused multiply-add in round-to-nearest-even mode with relu saturation. +* +* \details Performs \p half multiply on inputs \p a and \p b, +* then performs a \p half add of the result with \p c, +* rounding the result once in round-to-nearest-even mode. +* Then negative result is clamped to 0. +* NaN result is converted to canonical NaN. +* \param[in] a - half. Is only being read. +* \param[in] b - half. Is only being read. +* \param[in] c - half. Is only being read. +* +* \returns half +* \retval The result of fused multiply-add operation on \p +* a, \p b, and \p c with relu saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half __hfma_relu(const __half a, const __half b, const __half c); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Calculates \p half2 vector maximum of two inputs. +* +* \details Calculates \p half2 vector max(\p a, \p b). +* Elementwise \p half operation is defined as +* (\p a > \p b) ? \p a : \p b. +* - If either of inputs is NaN, the other input is returned. +* - If both inputs are NaNs, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise maximum of vectors \p a and \p b +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmax2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Calculates \p half2 vector minimum of two inputs. +* +* \details Calculates \p half2 vector min(\p a, \p b). +* Elementwise \p half operation is defined as +* (\p a < \p b) ? \p a : \p b. +* - If either of inputs is NaN, the other input is returned. +* - If both inputs are NaNs, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise minimum of vectors \p a and \p b +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmin2(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Calculates \p half2 vector maximum of two inputs, NaNs pass through. +* +* \details Calculates \p half2 vector max(\p a, \p b). +* Elementwise \p half operation is defined as +* (\p a > \p b) ? \p a : \p b. +* - If either of inputs is NaN, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise maximum of vectors \p a and \p b, with NaNs pass through +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmax2_nan(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_COMPARISON +* \brief Calculates \p half2 vector minimum of two inputs, NaNs pass through. +* +* \details Calculates \p half2 vector min(\p a, \p b). +* Elementwise \p half operation is defined as +* (\p a < \p b) ? \p a : \p b. +* - If either of inputs is NaN, then canonical NaN is returned. +* - If values of both inputs are 0.0, then +0.0 > -0.0 +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise minimum of vectors \p a and \p b, with NaNs pass through +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hmin2_nan(const __half2 a, const __half2 b); +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs \p half2 vector fused multiply-add in round-to-nearest-even +* mode with relu saturation. +* +* \details Performs \p half2 vector multiply on inputs \p a and \p b, +* then performs a \p half2 vector add of the result with \p c, +* rounding the result once in round-to-nearest-even mode. +* Then negative result is clamped to 0. +* NaN result is converted to canonical NaN. +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* \param[in] c - half2. Is only being read. +* +* \returns half2 +* \retval The result of elementwise fused multiply-add operation on vectors \p a, \p b, and \p c with relu saturation. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hfma2_relu(const __half2 a, const __half2 b, const __half2 c); +#endif /*__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__)*/ +/** +* \ingroup CUDA_MATH__HALF2_ARITHMETIC +* \brief Performs fast complex multiply-accumulate +* +* \details Interprets vector \p half2 input pairs \p a, \p b, and \p c as +* complex numbers in \p half precision and performs +* complex multiply-accumulate operation: a*b + c +* \param[in] a - half2. Is only being read. +* \param[in] b - half2. Is only being read. +* \param[in] c - half2. Is only being read. +* +* \returns half2 +* \retval The result of complex multiply-accumulate operation on complex numbers \p a, \p b, and \p c +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 __hcmadd(const __half2 a, const __half2 b, const __half2 c); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half square root in round-to-nearest-even mode. +* +* \details Calculates \p half square root of input \p a in round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The square root of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hsqrt(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half reciprocal square root in round-to-nearest-even +* mode. +* +* \details Calculates \p half reciprocal square root of input \p a in round-to-nearest +* mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The reciprocal square root of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hrsqrt(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half reciprocal in round-to-nearest-even mode. +* +* \details Calculates \p half reciprocal of input \p a in round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The reciprocal of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hrcp(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half natural logarithm in round-to-nearest-even mode. +* +* \details Calculates \p half natural logarithm of input \p a in round-to-nearest-even +* mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The natural logarithm of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hlog(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half binary logarithm in round-to-nearest-even mode. +* +* \details Calculates \p half binary logarithm of input \p a in round-to-nearest-even +* mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The binary logarithm of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hlog2(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half decimal logarithm in round-to-nearest-even mode. +* +* \details Calculates \p half decimal logarithm of input \p a in round-to-nearest-even +* mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The decimal logarithm of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hlog10(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half natural exponential function in round-to-nearest +* mode. +* +* \details Calculates \p half natural exponential function of input \p a in +* round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The natural exponential function on \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hexp(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half binary exponential function in round-to-nearest +* mode. +* +* \details Calculates \p half binary exponential function of input \p a in +* round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The binary exponential function on \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hexp2(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half decimal exponential function in round-to-nearest +* mode. +* +* \details Calculates \p half decimal exponential function of input \p a in +* round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The decimal exponential function on \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hexp10(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half cosine in round-to-nearest-even mode. +* +* \details Calculates \p half cosine of input \p a in round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The cosine of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hcos(const __half a); +/** +* \ingroup CUDA_MATH__HALF_FUNCTIONS +* \brief Calculates \p half sine in round-to-nearest-even mode. +* +* \details Calculates \p half sine of input \p a in round-to-nearest-even mode. +* \param[in] a - half. Is only being read. +* +* \returns half +* \retval The sine of \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half hsin(const __half a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector square root in round-to-nearest-even mode. +* +* \details Calculates \p half2 square root of input vector \p a in round-to-nearest +* mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise square root on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2sqrt(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector reciprocal square root in round-to-nearest +* mode. +* +* \details Calculates \p half2 reciprocal square root of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise reciprocal square root on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2rsqrt(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector reciprocal in round-to-nearest-even mode. +* +* \details Calculates \p half2 reciprocal of input vector \p a in round-to-nearest-even +* mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise reciprocal on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2rcp(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector natural logarithm in round-to-nearest-even +* mode. +* +* \details Calculates \p half2 natural logarithm of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise natural logarithm on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2log(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector binary logarithm in round-to-nearest-even +* mode. +* +* \details Calculates \p half2 binary logarithm of input vector \p a in round-to-nearest +* mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise binary logarithm on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2log2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector decimal logarithm in round-to-nearest-even +* mode. +* +* \details Calculates \p half2 decimal logarithm of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise decimal logarithm on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2log10(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector exponential function in round-to-nearest +* mode. +* +* \details Calculates \p half2 exponential function of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise exponential function on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2exp(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector binary exponential function in +* round-to-nearest-even mode. +* +* \details Calculates \p half2 binary exponential function of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise binary exponential function on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2exp2(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector decimal exponential function in +* round-to-nearest-even mode. +* +* \details Calculates \p half2 decimal exponential function of input vector \p a in +* round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise decimal exponential function on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2exp10(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector cosine in round-to-nearest-even mode. +* +* \details Calculates \p half2 cosine of input vector \p a in round-to-nearest-even +* mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise cosine on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2cos(const __half2 a); +/** +* \ingroup CUDA_MATH__HALF2_FUNCTIONS +* \brief Calculates \p half2 vector sine in round-to-nearest-even mode. +* +* \details Calculates \p half2 sine of input vector \p a in round-to-nearest-even mode. +* \param[in] a - half2. Is only being read. +* +* \returns half2 +* \retval The elementwise sine on vector \p a. +* \internal +* \exception-guarantee no-throw guarantee +* \behavior reentrant, thread safe +* \endinternal +*/ +__CUDA_FP16_DECL__ __half2 h2sin(const __half2 a); + +#endif /*if __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__)*/ + +#if __CUDA_ARCH__ >= 600 || !defined(__CUDA_ARCH__) + +__CUDA_FP16_DECL__ __half2 atomicAdd(__half2 *const address, const __half2 val); + +#endif /*if __CUDA_ARCH__ >= 600 || !defined(__CUDA_ARCH__)*/ + +#if __CUDA_ARCH__ >= 700 || !defined(__CUDA_ARCH__) + +__CUDA_FP16_DECL__ __half atomicAdd(__half *const address, const __half val); + +#endif /*if __CUDA_ARCH__ >= 700 || !defined(__CUDA_ARCH__)*/ + +#endif /* defined(__CUDACC__) */ + +#undef __CUDA_FP16_DECL__ +#undef __CUDA_HOSTDEVICE_FP16_DECL__ + +#endif /* defined(__cplusplus) */ + +/* Note the .hpp file is included even for host-side compilation, to capture the "half" & "half2" definitions */ +#include "cuda_fp16.hpp" + +#endif /* end of include guard: __CUDA_FP16_H__ */ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.hpp b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.hpp new file mode 100644 index 0000000000000000000000000000000000000000..19bbd3412d52b6df05404313cdc7ce3699beaaf3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_fp16.hpp @@ -0,0 +1,2465 @@ +/* +* Copyright 1993-2020 NVIDIA Corporation. All rights reserved. +* +* NOTICE TO LICENSEE: +* +* This source code and/or documentation ("Licensed Deliverables") are +* subject to NVIDIA intellectual property rights under U.S. and +* international Copyright laws. +* +* These Licensed Deliverables contained herein is PROPRIETARY and +* CONFIDENTIAL to NVIDIA and is being provided under the terms and +* conditions of a form of NVIDIA software license agreement by and +* between NVIDIA and Licensee ("License Agreement") or electronically +* accepted by Licensee. Notwithstanding any terms or conditions to +* the contrary in the License Agreement, reproduction or disclosure +* of the Licensed Deliverables to any third party without the express +* written consent of NVIDIA is prohibited. +* +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE +* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS +* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. +* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED +* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, +* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. +* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE +* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY +* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY +* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +* OF THESE LICENSED DELIVERABLES. +* +* U.S. Government End Users. These Licensed Deliverables are a +* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT +* 1995), consisting of "commercial computer software" and "commercial +* computer software documentation" as such terms are used in 48 +* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government +* only as a commercial end item. Consistent with 48 C.F.R.12.212 and +* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all +* U.S. Government End Users acquire the Licensed Deliverables with +* only those rights set forth herein. +* +* Any use of the Licensed Deliverables in individual and commercial +* software must include, in the user documentation and internal +* comments to the code, the above Disclaimer and U.S. Government End +* Users Notice. +*/ + +#if !defined(__CUDA_FP16_HPP__) +#define __CUDA_FP16_HPP__ + +#if !defined(__CUDA_FP16_H__) +#error "Do not include this file directly. Instead, include cuda_fp16.h." +#endif + +#if !defined(_MSC_VER) && __cplusplus >= 201103L +# define __CPP_VERSION_AT_LEAST_11_FP16 +#elif _MSC_FULL_VER >= 190024210 && _MSVC_LANG >= 201103L +# define __CPP_VERSION_AT_LEAST_11_FP16 +#endif + +/* C++11 header for std::move. + * In RTC mode, std::move is provided implicitly; don't include the header + */ +#if defined(__CPP_VERSION_AT_LEAST_11_FP16) && !defined(__CUDACC_RTC__) +#include +#endif /* __cplusplus >= 201103L && !defined(__CUDACC_RTC__) */ + +/* C++ header for std::memcpy (used for type punning in host-side implementations). + * When compiling as a CUDA source file memcpy is provided implicitly. + * !defined(__CUDACC__) implies !defined(__CUDACC_RTC__). + */ +#if defined(__cplusplus) && !defined(__CUDACC__) +#include +#endif /* defined(__cplusplus) && !defined(__CUDACC__) */ + + +/* Set up function decorations */ +#if defined(__CUDACC__) +#define __CUDA_FP16_DECL__ static __device__ __inline__ +#define __CUDA_HOSTDEVICE_FP16_DECL__ static __host__ __device__ __inline__ +#define __VECTOR_FUNCTIONS_DECL__ static __inline__ __host__ __device__ +#define __CUDA_HOSTDEVICE__ __host__ __device__ +#else /* !defined(__CUDACC__) */ +#if defined(__GNUC__) +#define __CUDA_HOSTDEVICE_FP16_DECL__ static __attribute__ ((unused)) +#else +#define __CUDA_HOSTDEVICE_FP16_DECL__ static +#endif /* defined(__GNUC__) */ +#define __CUDA_HOSTDEVICE__ +#endif /* defined(__CUDACC_) */ + +/* Set up structure-alignment attribute */ +#if defined(__CUDACC__) +#define __CUDA_ALIGN__(align) __align__(align) +#else +/* Define alignment macro based on compiler type (cannot assume C11 "_Alignas" is available) */ +#if __cplusplus >= 201103L +#define __CUDA_ALIGN__(n) alignas(n) /* C++11 kindly gives us a keyword for this */ +#else /* !defined(__CPP_VERSION_AT_LEAST_11_FP16)*/ +#if defined(__GNUC__) +#define __CUDA_ALIGN__(n) __attribute__ ((aligned(n))) +#elif defined(_MSC_VER) +#define __CUDA_ALIGN__(n) __declspec(align(n)) +#else +#define __CUDA_ALIGN__(n) +#endif /* defined(__GNUC__) */ +#endif /* defined(__CPP_VERSION_AT_LEAST_11_FP16) */ +#endif /* defined(__CUDACC__) */ + +/* Macros to allow half & half2 to be used by inline assembly */ +#define __HALF_TO_US(var) *(reinterpret_cast(&(var))) +#define __HALF_TO_CUS(var) *(reinterpret_cast(&(var))) +#define __HALF2_TO_UI(var) *(reinterpret_cast(&(var))) +#define __HALF2_TO_CUI(var) *(reinterpret_cast(&(var))) + +/* Macros for half & half2 binary arithmetic */ +#define __BINARY_OP_HALF_MACRO(name) /* do */ {\ + __half val; \ + asm( "{"#name".f16 %0,%1,%2;\n}" \ + :"=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a)),"h"(__HALF_TO_CUS(b))); \ + return val; \ +} /* while(0) */ +#define __BINARY_OP_HALF2_MACRO(name) /* do */ {\ + __half2 val; \ + asm( "{"#name".f16x2 %0,%1,%2;\n}" \ + :"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)),"r"(__HALF2_TO_CUI(b))); \ + return val; \ +} /* while(0) */ +#define __TERNARY_OP_HALF_MACRO(name) /* do */ {\ + __half val; \ + asm( "{"#name".f16 %0,%1,%2,%3;\n}" \ + :"=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a)),"h"(__HALF_TO_CUS(b)),"h"(__HALF_TO_CUS(c))); \ + return val; \ +} /* while(0) */ +#define __TERNARY_OP_HALF2_MACRO(name) /* do */ {\ + __half2 val; \ + asm( "{"#name".f16x2 %0,%1,%2,%3;\n}" \ + :"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)),"r"(__HALF2_TO_CUI(b)),"r"(__HALF2_TO_CUI(c))); \ + return val; \ +} /* while(0) */ + +/** +* Types which allow static initialization of "half" and "half2" until +* these become an actual builtin. Note this initialization is as a +* bitfield representation of "half", and not a conversion from short->half. +* Such a representation will be deprecated in a future version of CUDA. +* (Note these are visible to non-nvcc compilers, including C-only compilation) +*/ +typedef struct __CUDA_ALIGN__(2) { + unsigned short x; +} __half_raw; + +typedef struct __CUDA_ALIGN__(4) { + unsigned short x; + unsigned short y; +} __half2_raw; + +/* All other definitions in this file are only visible to C++ compilers */ +#if defined(__cplusplus) + +/* Hide GCC member initialization list warnings because of host/device in-function init requirement */ +#if defined(__GNUC__) +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic ignored "-Weffc++" +#endif /* __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) */ +#endif /* defined(__GNUC__) */ + +/* class' : multiple assignment operators specified + The class has multiple assignment operators of a single type. This warning is informational */ +#if defined(_MSC_VER) && _MSC_VER >= 1500 +#pragma warning( push ) +#pragma warning( disable:4522 ) +#endif /* defined(__GNUC__) */ + +struct __CUDA_ALIGN__(2) __half { +protected: + unsigned short __x; + +public: +#if defined(__CPP_VERSION_AT_LEAST_11_FP16) + __half() = default; +#else + __CUDA_HOSTDEVICE__ __half() { } +#endif /* defined(__CPP_VERSION_AT_LEAST_11_FP16) */ + + /* Convert to/from __half_raw */ + __CUDA_HOSTDEVICE__ __half(const __half_raw &hr) : __x(hr.x) { } + __CUDA_HOSTDEVICE__ __half &operator=(const __half_raw &hr) { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ volatile __half &operator=(const __half_raw &hr) volatile { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ volatile __half &operator=(const volatile __half_raw &hr) volatile { __x = hr.x; return *this; } + __CUDA_HOSTDEVICE__ operator __half_raw() const { __half_raw ret; ret.x = __x; return ret; } + __CUDA_HOSTDEVICE__ operator __half_raw() const volatile { __half_raw ret; ret.x = __x; return ret; } + +#if !defined(__CUDA_NO_HALF_CONVERSIONS__) + + /* Construct from float/double */ + __CUDA_HOSTDEVICE__ __half(const float f) { __x = __float2half(f).__x; } + __CUDA_HOSTDEVICE__ __half(const double f) { __x = __double2half(f).__x; } + + __CUDA_HOSTDEVICE__ operator float() const { return __half2float(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const float f) { __x = __float2half(f).__x; return *this; } + + /* We omit "cast to double" operator, so as to not be ambiguous about up-cast */ + __CUDA_HOSTDEVICE__ __half &operator=(const double f) { __x = __double2half(f).__x; return *this; } + +/* Member functions only available to nvcc compilation so far */ +#if defined(__CUDACC__) + /* Allow automatic construction from types supported natively in hardware */ + /* Note we do avoid constructor init-list because of special host/device compilation rules */ + __CUDA_HOSTDEVICE__ __half(const short val) { __x = __short2half_rn(val).__x; } + __CUDA_HOSTDEVICE__ __half(const unsigned short val) { __x = __ushort2half_rn(val).__x; } + __CUDA_HOSTDEVICE__ __half(const int val) { __x = __int2half_rn(val).__x; } + __CUDA_HOSTDEVICE__ __half(const unsigned int val) { __x = __uint2half_rn(val).__x; } + __CUDA_HOSTDEVICE__ __half(const long long val) { __x = __ll2half_rn(val).__x; } + __CUDA_HOSTDEVICE__ __half(const unsigned long long val) { __x = __ull2half_rn(val).__x; } + + /* Allow automatic casts to supported builtin types, matching all that are permitted with float */ + __CUDA_HOSTDEVICE__ operator short() const { return __half2short_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const short val) { __x = __short2half_rn(val).__x; return *this; } + + __CUDA_HOSTDEVICE__ operator unsigned short() const { return __half2ushort_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const unsigned short val) { __x = __ushort2half_rn(val).__x; return *this; } + + __CUDA_HOSTDEVICE__ operator int() const { return __half2int_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const int val) { __x = __int2half_rn(val).__x; return *this; } + + __CUDA_HOSTDEVICE__ operator unsigned int() const { return __half2uint_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const unsigned int val) { __x = __uint2half_rn(val).__x; return *this; } + + __CUDA_HOSTDEVICE__ operator long long() const { return __half2ll_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const long long val) { __x = __ll2half_rn(val).__x; return *this; } + + __CUDA_HOSTDEVICE__ operator unsigned long long() const { return __half2ull_rz(*this); } + __CUDA_HOSTDEVICE__ __half &operator=(const unsigned long long val) { __x = __ull2half_rn(val).__x; return *this; } + + /* Boolean conversion - note both 0 and -0 must return false */ + __CUDA_HOSTDEVICE__ operator bool() const { return (__x & 0x7FFFU) != 0U; } +#endif /* defined(__CUDACC__) */ +#endif /* !defined(__CUDA_NO_HALF_CONVERSIONS__) */ +}; + +/* Global-space operator functions are only available to nvcc compilation */ +#if defined(__CUDACC__) + +/* Arithmetic FP16 operations only supported on arch >= 5.3 */ +#if __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__) +#if !defined(__CUDA_NO_HALF_OPERATORS__) +/* Some basic arithmetic operations expected of a builtin */ +__device__ __forceinline__ __half operator+(const __half &lh, const __half &rh) { return __hadd(lh, rh); } +__device__ __forceinline__ __half operator-(const __half &lh, const __half &rh) { return __hsub(lh, rh); } +__device__ __forceinline__ __half operator*(const __half &lh, const __half &rh) { return __hmul(lh, rh); } +__device__ __forceinline__ __half operator/(const __half &lh, const __half &rh) { return __hdiv(lh, rh); } + +__device__ __forceinline__ __half &operator+=(__half &lh, const __half &rh) { lh = __hadd(lh, rh); return lh; } +__device__ __forceinline__ __half &operator-=(__half &lh, const __half &rh) { lh = __hsub(lh, rh); return lh; } +__device__ __forceinline__ __half &operator*=(__half &lh, const __half &rh) { lh = __hmul(lh, rh); return lh; } +__device__ __forceinline__ __half &operator/=(__half &lh, const __half &rh) { lh = __hdiv(lh, rh); return lh; } + +/* Note for increment and decrement we use the raw value 0x3C00U equating to half(1.0F), to avoid the extra conversion */ +__device__ __forceinline__ __half &operator++(__half &h) { __half_raw one; one.x = 0x3C00U; h += one; return h; } +__device__ __forceinline__ __half &operator--(__half &h) { __half_raw one; one.x = 0x3C00U; h -= one; return h; } +__device__ __forceinline__ __half operator++(__half &h, const int ignored) { const __half ret = h; __half_raw one; one.x = 0x3C00U; h += one; return ret; } +__device__ __forceinline__ __half operator--(__half &h, const int ignored) { const __half ret = h; __half_raw one; one.x = 0x3C00U; h -= one; return ret; } + +/* Unary plus and inverse operators */ +__device__ __forceinline__ __half operator+(const __half &h) { return h; } +__device__ __forceinline__ __half operator-(const __half &h) { return __hneg(h); } + +/* Some basic comparison operations to make it look like a builtin */ +__device__ __forceinline__ bool operator==(const __half &lh, const __half &rh) { return __heq(lh, rh); } +__device__ __forceinline__ bool operator!=(const __half &lh, const __half &rh) { return __hneu(lh, rh); } +__device__ __forceinline__ bool operator> (const __half &lh, const __half &rh) { return __hgt(lh, rh); } +__device__ __forceinline__ bool operator< (const __half &lh, const __half &rh) { return __hlt(lh, rh); } +__device__ __forceinline__ bool operator>=(const __half &lh, const __half &rh) { return __hge(lh, rh); } +__device__ __forceinline__ bool operator<=(const __half &lh, const __half &rh) { return __hle(lh, rh); } +#endif /* !defined(__CUDA_NO_HALF_OPERATORS__) */ +#endif /* __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__) */ +#endif /* defined(__CUDACC__) */ + +/* __half2 is visible to non-nvcc host compilers */ +struct __CUDA_ALIGN__(4) __half2 { + __half x; + __half y; + + // All construct/copy/assign/move +public: +#if defined(__CPP_VERSION_AT_LEAST_11_FP16) + __half2() = default; + __CUDA_HOSTDEVICE__ __half2(const __half2 &&src) { __HALF2_TO_UI(*this) = std::move(__HALF2_TO_CUI(src)); } + __CUDA_HOSTDEVICE__ __half2 &operator=(const __half2 &&src) { __HALF2_TO_UI(*this) = std::move(__HALF2_TO_CUI(src)); return *this; } +#else + __CUDA_HOSTDEVICE__ __half2() { } +#endif /* defined(__CPP_VERSION_AT_LEAST_11_FP16) */ + __CUDA_HOSTDEVICE__ __half2(const __half &a, const __half &b) : x(a), y(b) { } + __CUDA_HOSTDEVICE__ __half2(const __half2 &src) { __HALF2_TO_UI(*this) = __HALF2_TO_CUI(src); } + __CUDA_HOSTDEVICE__ __half2 &operator=(const __half2 &src) { __HALF2_TO_UI(*this) = __HALF2_TO_CUI(src); return *this; } + + /* Convert to/from __half2_raw */ + __CUDA_HOSTDEVICE__ __half2(const __half2_raw &h2r ) { __HALF2_TO_UI(*this) = __HALF2_TO_CUI(h2r); } + __CUDA_HOSTDEVICE__ __half2 &operator=(const __half2_raw &h2r) { __HALF2_TO_UI(*this) = __HALF2_TO_CUI(h2r); return *this; } + __CUDA_HOSTDEVICE__ operator __half2_raw() const { __half2_raw ret; ret.x = 0U; ret.y = 0U; __HALF2_TO_UI(ret) = __HALF2_TO_CUI(*this); return ret; } +}; + +/* Global-space operator functions are only available to nvcc compilation */ +#if defined(__CUDACC__) + +/* Arithmetic FP16x2 operations only supported on arch >= 5.3 */ +#if (__CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__)) && !defined(__CUDA_NO_HALF2_OPERATORS__) + +__device__ __forceinline__ __half2 operator+(const __half2 &lh, const __half2 &rh) { return __hadd2(lh, rh); } +__device__ __forceinline__ __half2 operator-(const __half2 &lh, const __half2 &rh) { return __hsub2(lh, rh); } +__device__ __forceinline__ __half2 operator*(const __half2 &lh, const __half2 &rh) { return __hmul2(lh, rh); } +__device__ __forceinline__ __half2 operator/(const __half2 &lh, const __half2 &rh) { return __h2div(lh, rh); } + +__device__ __forceinline__ __half2& operator+=(__half2 &lh, const __half2 &rh) { lh = __hadd2(lh, rh); return lh; } +__device__ __forceinline__ __half2& operator-=(__half2 &lh, const __half2 &rh) { lh = __hsub2(lh, rh); return lh; } +__device__ __forceinline__ __half2& operator*=(__half2 &lh, const __half2 &rh) { lh = __hmul2(lh, rh); return lh; } +__device__ __forceinline__ __half2& operator/=(__half2 &lh, const __half2 &rh) { lh = __h2div(lh, rh); return lh; } + +__device__ __forceinline__ __half2 &operator++(__half2 &h) { __half2_raw one; one.x = 0x3C00U; one.y = 0x3C00U; h = __hadd2(h, one); return h; } +__device__ __forceinline__ __half2 &operator--(__half2 &h) { __half2_raw one; one.x = 0x3C00U; one.y = 0x3C00U; h = __hsub2(h, one); return h; } +__device__ __forceinline__ __half2 operator++(__half2 &h, const int ignored) { const __half2 ret = h; __half2_raw one; one.x = 0x3C00U; one.y = 0x3C00U; h = __hadd2(h, one); return ret; } +__device__ __forceinline__ __half2 operator--(__half2 &h, const int ignored) { const __half2 ret = h; __half2_raw one; one.x = 0x3C00U; one.y = 0x3C00U; h = __hsub2(h, one); return ret; } + +__device__ __forceinline__ __half2 operator+(const __half2 &h) { return h; } +__device__ __forceinline__ __half2 operator-(const __half2 &h) { return __hneg2(h); } + +__device__ __forceinline__ bool operator==(const __half2 &lh, const __half2 &rh) { return __hbeq2(lh, rh); } +__device__ __forceinline__ bool operator!=(const __half2 &lh, const __half2 &rh) { return __hbneu2(lh, rh); } +__device__ __forceinline__ bool operator>(const __half2 &lh, const __half2 &rh) { return __hbgt2(lh, rh); } +__device__ __forceinline__ bool operator<(const __half2 &lh, const __half2 &rh) { return __hblt2(lh, rh); } +__device__ __forceinline__ bool operator>=(const __half2 &lh, const __half2 &rh) { return __hbge2(lh, rh); } +__device__ __forceinline__ bool operator<=(const __half2 &lh, const __half2 &rh) { return __hble2(lh, rh); } + +#endif /* __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__) */ +#endif /* defined(__CUDACC__) */ + +/* Restore warning for multiple assignment operators */ +#if defined(_MSC_VER) && _MSC_VER >= 1500 +#pragma warning( pop ) +#endif /* defined(_MSC_VER) && _MSC_VER >= 1500 */ + +/* Restore -Weffc++ warnings from here on */ +#if defined(__GNUC__) +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) +#pragma GCC diagnostic pop +#endif /* __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) */ +#endif /* defined(__GNUC__) */ + +#undef __CUDA_HOSTDEVICE__ +#undef __CUDA_ALIGN__ + +#ifndef __CUDACC_RTC__ /* no host functions in NVRTC mode */ +static inline unsigned short __internal_float2half(const float f, unsigned int &sign, unsigned int &remainder) +{ + unsigned int x; + unsigned int u; + unsigned int result; +#if defined(__CUDACC__) + (void)memcpy(&x, &f, sizeof(f)); +#else + (void)std::memcpy(&x, &f, sizeof(f)); +#endif + u = (x & 0x7fffffffU); + sign = ((x >> 16U) & 0x8000U); + // NaN/+Inf/-Inf + if (u >= 0x7f800000U) { + remainder = 0U; + result = ((u == 0x7f800000U) ? (sign | 0x7c00U) : 0x7fffU); + } else if (u > 0x477fefffU) { // Overflows + remainder = 0x80000000U; + result = (sign | 0x7bffU); + } else if (u >= 0x38800000U) { // Normal numbers + remainder = u << 19U; + u -= 0x38000000U; + result = (sign | (u >> 13U)); + } else if (u < 0x33000001U) { // +0/-0 + remainder = u; + result = sign; + } else { // Denormal numbers + const unsigned int exponent = u >> 23U; + const unsigned int shift = 0x7eU - exponent; + unsigned int mantissa = (u & 0x7fffffU); + mantissa |= 0x800000U; + remainder = mantissa << (32U - shift); + result = (sign | (mantissa >> shift)); + } + return static_cast(result); +} +#endif /* #if !defined(__CUDACC_RTC__) */ + +__CUDA_HOSTDEVICE_FP16_DECL__ __half __double2half(const double a) +{ +#if defined(__CUDA_ARCH__) + __half val; + asm("{ cvt.rn.f16.f64 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "d"(a)); + return val; +#else + __half result; + // Perform rounding to 11 bits of precision, convert value + // to float and call existing float to half conversion. + // By pre-rounding to 11 bits we avoid additional rounding + // in float to half conversion. + unsigned long long int absa; + unsigned long long int ua; + #if defined(__CUDACC__) + (void)memcpy(&ua, &a, sizeof(a)); + #else + (void)std::memcpy(&ua, &a, sizeof(a)); + #endif + absa = (ua & 0x7fffffffffffffffULL); + if ((absa >= 0x40f0000000000000ULL) || (absa <= 0x3e60000000000000ULL)) + { + // |a| >= 2^16 or NaN or |a| <= 2^(-25) + // double-rounding is not a problem + result = __float2half(static_cast(a)); + } + else + { + // here 2^(-25) < |a| < 2^16 + // prepare shifter value such that a + shifter + // done in double precision performs round-to-nearest-even + // and (a + shifter) - shifter results in a rounded to + // 11 bits of precision. Shifter needs to have exponent of + // a plus 53 - 11 = 42 and a leading bit in mantissa to guard + // against negative values. + // So need to have |a| capped to avoid overflow in exponent. + // For inputs that are smaller than half precision minnorm + // we prepare fixed shifter exponent. + unsigned long long shifterBits; + if (absa >= 0x3f10000000000000ULL) + { // Here if |a| >= 2^(-14) + // add 42 to exponent bits + shifterBits = (ua & 0x7ff0000000000000ULL) + 0x02A0000000000000ULL; + } + else + { // 2^(-25) < |a| < 2^(-14), potentially results in denormal + // set exponent bits to 42 - 14 + bias + shifterBits = 0x41B0000000000000ULL; + } + // set leading mantissa bit to protect against negative inputs + shifterBits |= 0x0008000000000000ULL; + double shifter; + #if defined(__CUDACC__) + (void)memcpy(&shifter, &shifterBits, sizeof(shifterBits)); + #else + (void)std::memcpy(&shifter, &shifterBits, sizeof(shifterBits)); + #endif + double aShiftRound = a + shifter; + + // Prevent the compiler from optimizing away a + shifter - shifter + // by doing intermediate memcopy and harmless bitwize operation + unsigned long long int aShiftRoundBits; + #if defined(__CUDACC__) + (void)memcpy(&aShiftRoundBits, &aShiftRound, sizeof(aShiftRound)); + #else + (void)std::memcpy(&aShiftRoundBits, &aShiftRound, sizeof(aShiftRound)); + #endif + + // the value is positive, so this operation doesn't change anything + aShiftRoundBits &= 0x7fffffffffffffffULL; + + #if defined(__CUDACC__) + (void)memcpy(&aShiftRound, &aShiftRoundBits, sizeof(aShiftRound)); + #else + (void)std::memcpy(&aShiftRound, &aShiftRoundBits, sizeof(aShiftRound)); + #endif + + result = __float2half(static_cast(aShiftRound - shifter)); + } + + return result; +#endif +} + +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half(const float a) +{ + __half val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.rn.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(a)); +#else + __half_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2half(a, sign, remainder); + if ((remainder > 0x80000000U) || ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rn(const float a) +{ + __half val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.rn.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(a)); +#else + __half_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2half(a, sign, remainder); + if ((remainder > 0x80000000U) || ((remainder == 0x80000000U) && ((r.x & 0x1U) != 0U))) { + r.x++; + } + val = r; +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rz(const float a) +{ + __half val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.rz.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(a)); +#else + __half_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2half(a, sign, remainder); + val = r; +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_rd(const float a) +{ + __half val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.rm.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(a)); +#else + __half_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2half(a, sign, remainder); + if ((remainder != 0U) && (sign != 0U)) { + r.x++; + } + val = r; +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __float2half_ru(const float a) +{ + __half val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.rp.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(a)); +#else + __half_raw r; + unsigned int sign = 0U; + unsigned int remainder = 0U; + r.x = __internal_float2half(a, sign, remainder); + if ((remainder != 0U) && (sign == 0U)) { + r.x++; + } + val = r; +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __float2half2_rn(const float a) +{ + __half2 val; +#if defined(__CUDA_ARCH__) + asm("{.reg .f16 low;\n" + " cvt.rn.f16.f32 low, %1;\n" + " mov.b32 %0, {low,low};}\n" : "=r"(__HALF2_TO_UI(val)) : "f"(a)); +#else + val = __half2(__float2half_rn(a), __float2half_rn(a)); +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __floats2half2_rn(const float a, const float b) +{ + __half2 val; +#if defined(__CUDA_ARCH__) + asm("{.reg .f16 low,high;\n" + " cvt.rn.f16.f32 low, %1;\n" + " cvt.rn.f16.f32 high, %2;\n" + " mov.b32 %0, {low,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "f"(a), "f"(b)); +#else + val = __half2(__float2half_rn(a), __float2half_rn(b)); +#endif + return val; +} + +#ifndef __CUDACC_RTC__ /* no host functions in NVRTC mode */ +static inline float __internal_half2float(const unsigned short h) +{ + unsigned int sign = ((static_cast(h) >> 15U) & 1U); + unsigned int exponent = ((static_cast(h) >> 10U) & 0x1fU); + unsigned int mantissa = ((static_cast(h) & 0x3ffU) << 13U); + float f; + if (exponent == 0x1fU) { /* NaN or Inf */ + /* discard sign of a NaN */ + sign = ((mantissa != 0U) ? (sign >> 1U) : sign); + mantissa = ((mantissa != 0U) ? 0x7fffffU : 0U); + exponent = 0xffU; + } else if (exponent == 0U) { /* Denorm or Zero */ + if (mantissa != 0U) { + unsigned int msb; + exponent = 0x71U; + do { + msb = (mantissa & 0x400000U); + mantissa <<= 1U; /* normalize */ + --exponent; + } while (msb == 0U); + mantissa &= 0x7fffffU; /* 1.mantissa is implicit */ + } + } else { + exponent += 0x70U; + } + unsigned int u = ((sign << 31U) | (exponent << 23U) | mantissa); +#if defined(__CUDACC__) + (void)memcpy(&f, &u, sizeof(u)); +#else + (void)std::memcpy(&f, &u, sizeof(u)); +#endif + return f; +} +#endif /* !defined(__CUDACC_RTC__) */ + +__CUDA_HOSTDEVICE_FP16_DECL__ float __half2float(const __half a) +{ + float val; +#if defined(__CUDA_ARCH__) + asm("{ cvt.f32.f16 %0, %1;}\n" : "=f"(val) : "h"(__HALF_TO_CUS(a))); +#else + val = __internal_half2float(static_cast<__half_raw>(a).x); +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ float __low2float(const __half2 a) +{ + float val; +#if defined(__CUDA_ARCH__) + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high},%1;\n" + " cvt.f32.f16 %0, low;}\n" : "=f"(val) : "r"(__HALF2_TO_CUI(a))); +#else + val = __internal_half2float(static_cast<__half2_raw>(a).x); +#endif + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ float __high2float(const __half2 a) +{ + float val; +#if defined(__CUDA_ARCH__) + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high},%1;\n" + " cvt.f32.f16 %0, high;}\n" : "=f"(val) : "r"(__HALF2_TO_CUI(a))); +#else + val = __internal_half2float(static_cast<__half2_raw>(a).y); +#endif + return val; +} + +/* Intrinsic functions only available to nvcc compilers */ +#if defined(__CUDACC__) + +/* CUDA vector-types compatible vector creation function (note returns __half2, not half2) */ +__VECTOR_FUNCTIONS_DECL__ __half2 make_half2(const __half x, const __half y) +{ + __half2 t; t.x = x; t.y = y; return t; +} +#undef __VECTOR_FUNCTIONS_DECL__ + + +/* Definitions of intrinsics */ +__CUDA_HOSTDEVICE_FP16_DECL__ __half2 __float22half2_rn(const float2 a) +{ + const __half2 val = __floats2half2_rn(a.x, a.y); + return val; +} +__CUDA_HOSTDEVICE_FP16_DECL__ float2 __half22float2(const __half2 a) +{ + float hi_float; + float lo_float; +#if defined(__CUDA_ARCH__) + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high},%1;\n" + " cvt.f32.f16 %0, low;}\n" : "=f"(lo_float) : "r"(__HALF2_TO_CUI(a))); + + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high},%1;\n" + " cvt.f32.f16 %0, high;}\n" : "=f"(hi_float) : "r"(__HALF2_TO_CUI(a))); +#else + lo_float = __internal_half2float(((__half2_raw)a).x); + hi_float = __internal_half2float(((__half2_raw)a).y); +#endif + return make_float2(lo_float, hi_float); +} +__CUDA_FP16_DECL__ int __half2int_rn(const __half h) +{ + int i; + asm("cvt.rni.s32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ int __half2int_rz(const __half h) +{ + int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.s32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const int max_val = (int)0x7fffffffU; + const int min_val = (int)0x80000000U; + // saturation fixup + if (f != f) { + // NaN + i = 0; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ int __half2int_rd(const __half h) +{ + int i; + asm("cvt.rmi.s32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ int __half2int_ru(const __half h) +{ + int i; + asm("cvt.rpi.s32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __int2half_rn(const int i) +{ + __half h; +#if defined(__CUDA_ARCH__) + asm("cvt.rn.f16.s32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); +#else + // double-rounding is not a problem here: if integer + // has more than 24 bits, it is already too large to + // be represented in half precision, and result will + // be infinity. + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __int2half_rz(const int i) +{ + __half h; + asm("cvt.rz.f16.s32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __int2half_rd(const int i) +{ + __half h; + asm("cvt.rm.f16.s32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __int2half_ru(const int i) +{ + __half h; + asm("cvt.rp.f16.s32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} + +__CUDA_FP16_DECL__ short int __half2short_rn(const __half h) +{ + short int i; + asm("cvt.rni.s16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ short int __half2short_rz(const __half h) +{ + short int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.s16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const short int max_val = (short int)0x7fffU; + const short int min_val = (short int)0x8000U; + // saturation fixup + if (f != f) { + // NaN + i = 0; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ short int __half2short_rd(const __half h) +{ + short int i; + asm("cvt.rmi.s16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ short int __half2short_ru(const __half h) +{ + short int i; + asm("cvt.rpi.s16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __short2half_rn(const short int i) +{ + __half h; +#if defined __CUDA_ARCH__ + asm("cvt.rn.f16.s16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); +#else + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __short2half_rz(const short int i) +{ + __half h; + asm("cvt.rz.f16.s16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __short2half_rd(const short int i) +{ + __half h; + asm("cvt.rm.f16.s16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __short2half_ru(const short int i) +{ + __half h; + asm("cvt.rp.f16.s16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} + +__CUDA_FP16_DECL__ unsigned int __half2uint_rn(const __half h) +{ + unsigned int i; + asm("cvt.rni.u32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned int __half2uint_rz(const __half h) +{ + unsigned int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.u32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const unsigned int max_val = 0xffffffffU; + const unsigned int min_val = 0U; + // saturation fixup + if (f != f) { + // NaN + i = 0U; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ unsigned int __half2uint_rd(const __half h) +{ + unsigned int i; + asm("cvt.rmi.u32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ unsigned int __half2uint_ru(const __half h) +{ + unsigned int i; + asm("cvt.rpi.u32.f16 %0, %1;" : "=r"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __uint2half_rn(const unsigned int i) +{ + __half h; +#if defined __CUDA_ARCH__ + asm("cvt.rn.f16.u32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); +#else + // double-rounding is not a problem here: if integer + // has more than 24 bits, it is already too large to + // be represented in half precision, and result will + // be infinity. + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __uint2half_rz(const unsigned int i) +{ + __half h; + asm("cvt.rz.f16.u32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __uint2half_rd(const unsigned int i) +{ + __half h; + asm("cvt.rm.f16.u32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __uint2half_ru(const unsigned int i) +{ + __half h; + asm("cvt.rp.f16.u32 %0, %1;" : "=h"(__HALF_TO_US(h)) : "r"(i)); + return h; +} + +__CUDA_FP16_DECL__ unsigned short int __half2ushort_rn(const __half h) +{ + unsigned short int i; + asm("cvt.rni.u16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned short int __half2ushort_rz(const __half h) +{ + unsigned short int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.u16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const unsigned short int max_val = 0xffffU; + const unsigned short int min_val = 0U; + // saturation fixup + if (f != f) { + // NaN + i = 0U; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ unsigned short int __half2ushort_rd(const __half h) +{ + unsigned short int i; + asm("cvt.rmi.u16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ unsigned short int __half2ushort_ru(const __half h) +{ + unsigned short int i; + asm("cvt.rpi.u16.f16 %0, %1;" : "=h"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ushort2half_rn(const unsigned short int i) +{ + __half h; +#if defined __CUDA_ARCH__ + asm("cvt.rn.f16.u16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); +#else + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __ushort2half_rz(const unsigned short int i) +{ + __half h; + asm("cvt.rz.f16.u16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ushort2half_rd(const unsigned short int i) +{ + __half h; + asm("cvt.rm.f16.u16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ushort2half_ru(const unsigned short int i) +{ + __half h; + asm("cvt.rp.f16.u16 %0, %1;" : "=h"(__HALF_TO_US(h)) : "h"(i)); + return h; +} + +__CUDA_FP16_DECL__ unsigned long long int __half2ull_rn(const __half h) +{ + unsigned long long int i; + asm("cvt.rni.u64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ unsigned long long int __half2ull_rz(const __half h) +{ + unsigned long long int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.u64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const unsigned long long int max_val = 0xffffffffffffffffULL; + const unsigned long long int min_val = 0ULL; + // saturation fixup + if (f != f) { + // NaN + i = 0x8000000000000000ULL; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ unsigned long long int __half2ull_rd(const __half h) +{ + unsigned long long int i; + asm("cvt.rmi.u64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ unsigned long long int __half2ull_ru(const __half h) +{ + unsigned long long int i; + asm("cvt.rpi.u64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ull2half_rn(const unsigned long long int i) +{ + __half h; +#if defined(__CUDA_ARCH__) + asm("cvt.rn.f16.u64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); +#else + // double-rounding is not a problem here: if integer + // has more than 24 bits, it is already too large to + // be represented in half precision, and result will + // be infinity. + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __ull2half_rz(const unsigned long long int i) +{ + __half h; + asm("cvt.rz.f16.u64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ull2half_rd(const unsigned long long int i) +{ + __half h; + asm("cvt.rm.f16.u64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ull2half_ru(const unsigned long long int i) +{ + __half h; + asm("cvt.rp.f16.u64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} + +__CUDA_FP16_DECL__ long long int __half2ll_rn(const __half h) +{ + long long int i; + asm("cvt.rni.s64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ long long int __half2ll_rz(const __half h) +{ + long long int i; +#if defined __CUDA_ARCH__ + asm("cvt.rzi.s64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); +#else + const float f = __half2float(h); + i = static_cast(f); + const long long int max_val = (long long int)0x7fffffffffffffffULL; + const long long int min_val = (long long int)0x8000000000000000ULL; + // saturation fixup + if (f != f) { + // NaN + i = min_val; + } else if (f > static_cast(max_val)) { + // saturate maximum + i = max_val; + } else if (f < static_cast(min_val)) { + // saturate minimum + i = min_val; + } +#endif + return i; +} +__CUDA_FP16_DECL__ long long int __half2ll_rd(const __half h) +{ + long long int i; + asm("cvt.rmi.s64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_FP16_DECL__ long long int __half2ll_ru(const __half h) +{ + long long int i; + asm("cvt.rpi.s64.f16 %0, %1;" : "=l"(i) : "h"(__HALF_TO_CUS(h))); + return i; +} +__CUDA_HOSTDEVICE_FP16_DECL__ __half __ll2half_rn(const long long int i) +{ + __half h; +#if defined(__CUDA_ARCH__) + asm("cvt.rn.f16.s64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); +#else + // double-rounding is not a problem here: if integer + // has more than 24 bits, it is already too large to + // be represented in half precision, and result will + // be infinity. + const float f = static_cast(i); + h = __float2half_rn(f); +#endif + return h; +} +__CUDA_FP16_DECL__ __half __ll2half_rz(const long long int i) +{ + __half h; + asm("cvt.rz.f16.s64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ll2half_rd(const long long int i) +{ + __half h; + asm("cvt.rm.f16.s64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} +__CUDA_FP16_DECL__ __half __ll2half_ru(const long long int i) +{ + __half h; + asm("cvt.rp.f16.s64 %0, %1;" : "=h"(__HALF_TO_US(h)) : "l"(i)); + return h; +} + +__CUDA_FP16_DECL__ __half htrunc(const __half h) +{ + __half r; + asm("cvt.rzi.f16.f16 %0, %1;" : "=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(h))); + return r; +} +__CUDA_FP16_DECL__ __half hceil(const __half h) +{ + __half r; + asm("cvt.rpi.f16.f16 %0, %1;" : "=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(h))); + return r; +} +__CUDA_FP16_DECL__ __half hfloor(const __half h) +{ + __half r; + asm("cvt.rmi.f16.f16 %0, %1;" : "=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(h))); + return r; +} +__CUDA_FP16_DECL__ __half hrint(const __half h) +{ + __half r; + asm("cvt.rni.f16.f16 %0, %1;" : "=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(h))); + return r; +} + +__CUDA_FP16_DECL__ __half2 h2trunc(const __half2 h) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " cvt.rzi.f16.f16 low, low;\n" + " cvt.rzi.f16.f16 high, high;\n" + " mov.b32 %0, {low,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(h))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2ceil(const __half2 h) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " cvt.rpi.f16.f16 low, low;\n" + " cvt.rpi.f16.f16 high, high;\n" + " mov.b32 %0, {low,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(h))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2floor(const __half2 h) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " cvt.rmi.f16.f16 low, low;\n" + " cvt.rmi.f16.f16 high, high;\n" + " mov.b32 %0, {low,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(h))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2rint(const __half2 h) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " cvt.rni.f16.f16 low, low;\n" + " cvt.rni.f16.f16 high, high;\n" + " mov.b32 %0, {low,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(h))); + return val; +} +__CUDA_FP16_DECL__ __half2 __lows2half2(const __half2 a, const __half2 b) +{ + __half2 val; + asm("{.reg .f16 alow,ahigh,blow,bhigh;\n" + " mov.b32 {alow,ahigh}, %1;\n" + " mov.b32 {blow,bhigh}, %2;\n" + " mov.b32 %0, {alow,blow};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)), "r"(__HALF2_TO_CUI(b))); + return val; +} +__CUDA_FP16_DECL__ __half2 __highs2half2(const __half2 a, const __half2 b) +{ + __half2 val; + asm("{.reg .f16 alow,ahigh,blow,bhigh;\n" + " mov.b32 {alow,ahigh}, %1;\n" + " mov.b32 {blow,bhigh}, %2;\n" + " mov.b32 %0, {ahigh,bhigh};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)), "r"(__HALF2_TO_CUI(b))); + return val; +} +__CUDA_FP16_DECL__ __half __low2half(const __half2 a) +{ + __half ret; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b16 %0, low;}" : "=h"(__HALF_TO_US(ret)) : "r"(__HALF2_TO_CUI(a))); + return ret; +} +__CUDA_FP16_DECL__ int __hisinf(const __half a) +{ + int retval; + if (__HALF_TO_CUS(a) == 0xFC00U) { + retval = -1; + } else if (__HALF_TO_CUS(a) == 0x7C00U) { + retval = 1; + } else { + retval = 0; + } + return retval; +} +__CUDA_FP16_DECL__ __half2 __low2half2(const __half2 a) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {low,low};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 __high2half2(const __half2 a) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {high,high};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half __high2half(const __half2 a) +{ + __half ret; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b16 %0, high;}" : "=h"(__HALF_TO_US(ret)) : "r"(__HALF2_TO_CUI(a))); + return ret; +} +__CUDA_FP16_DECL__ __half2 __halves2half2(const __half a, const __half b) +{ + __half2 val; + asm("{ mov.b32 %0, {%1,%2};}\n" + : "=r"(__HALF2_TO_UI(val)) : "h"(__HALF_TO_CUS(a)), "h"(__HALF_TO_CUS(b))); + return val; +} +__CUDA_FP16_DECL__ __half2 __half2half2(const __half a) +{ + __half2 val; + asm("{ mov.b32 %0, {%1,%1};}\n" + : "=r"(__HALF2_TO_UI(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 __lowhigh2highlow(const __half2 a) +{ + __half2 val; + asm("{.reg .f16 low,high;\n" + " mov.b32 {low,high}, %1;\n" + " mov.b32 %0, {high,low};}\n" : "=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ short int __half_as_short(const __half h) +{ + return static_cast(__HALF_TO_CUS(h)); +} +__CUDA_FP16_DECL__ unsigned short int __half_as_ushort(const __half h) +{ + return __HALF_TO_CUS(h); +} +__CUDA_FP16_DECL__ __half __short_as_half(const short int i) +{ + __half h; + __HALF_TO_US(h) = static_cast(i); + return h; +} +__CUDA_FP16_DECL__ __half __ushort_as_half(const unsigned short int i) +{ + __half h; + __HALF_TO_US(h) = i; + return h; +} + +#if __CUDA_ARCH__ >= 300 || !defined(__CUDA_ARCH__) +/****************************************************************************** +* __half, __half2 warp shuffle * +******************************************************************************/ +#define __SHUFFLE_HALF2_MACRO(name) /* do */ {\ + __half2 r; \ + asm volatile ("{"#name" %0,%1,%2,%3;\n}" \ + :"=r"(__HALF2_TO_UI(r)): "r"(__HALF2_TO_CUI(var)), "r"(delta), "r"(c)); \ + return r; \ +} /* while(0) */ + +#define __SHUFFLE_SYNC_HALF2_MACRO(name) /* do */ {\ + __half2 r; \ + asm volatile ("{"#name" %0,%1,%2,%3,%4;\n}" \ + :"=r"(__HALF2_TO_UI(r)): "r"(__HALF2_TO_CUI(var)), "r"(delta), "r"(c), "r"(mask)); \ + return r; \ +} /* while(0) */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 + +__CUDA_FP16_DECL__ __half2 __shfl(const __half2 var, const int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_HALF2_MACRO(shfl.idx.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_up(const __half2 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = (warp_size - static_cast(width)) << 8U; + __SHUFFLE_HALF2_MACRO(shfl.up.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_down(const __half2 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_HALF2_MACRO(shfl.down.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_xor(const __half2 var, const int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_HALF2_MACRO(shfl.bfly.b32) +} + +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 */ + +__CUDA_FP16_DECL__ __half2 __shfl_sync(const unsigned mask, const __half2 var, const int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_HALF2_MACRO(shfl.sync.idx.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_up_sync(const unsigned mask, const __half2 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = (warp_size - static_cast(width)) << 8U; + __SHUFFLE_SYNC_HALF2_MACRO(shfl.sync.up.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_down_sync(const unsigned mask, const __half2 var, const unsigned int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_HALF2_MACRO(shfl.sync.down.b32) +} +__CUDA_FP16_DECL__ __half2 __shfl_xor_sync(const unsigned mask, const __half2 var, const int delta, const int width) +{ + unsigned int warp_size; + asm("{mov.u32 %0, WARP_SZ;\n}" : "=r"(warp_size)); + const unsigned int c = ((warp_size - static_cast(width)) << 8U) | 0x1fU; + __SHUFFLE_SYNC_HALF2_MACRO(shfl.sync.bfly.b32) +} + +#undef __SHUFFLE_HALF2_MACRO +#undef __SHUFFLE_SYNC_HALF2_MACRO + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 + +__CUDA_FP16_DECL__ __half __shfl(const __half var, const int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl(temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_up(const __half var, const unsigned int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_up(temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_down(const __half var, const unsigned int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_down(temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_xor(const __half var, const int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_xor(temp1, delta, width); + return __low2half(temp2); +} + +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 700 */ + +__CUDA_FP16_DECL__ __half __shfl_sync(const unsigned mask, const __half var, const int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_sync(mask, temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_up_sync(const unsigned mask, const __half var, const unsigned int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_up_sync(mask, temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_down_sync(const unsigned mask, const __half var, const unsigned int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_down_sync(mask, temp1, delta, width); + return __low2half(temp2); +} +__CUDA_FP16_DECL__ __half __shfl_xor_sync(const unsigned mask, const __half var, const int delta, const int width) +{ + const __half2 temp1 = __halves2half2(var, var); + const __half2 temp2 = __shfl_xor_sync(mask, temp1, delta, width); + return __low2half(temp2); +} + +#endif /*__CUDA_ARCH__ >= 300 || !defined(__CUDA_ARCH__)*/ +/****************************************************************************** +* __half and __half2 __ldg,__ldcg,__ldca,__ldcs * +******************************************************************************/ + +#if defined(__cplusplus) && (__CUDA_ARCH__ >= 320 || !defined(__CUDA_ARCH__)) +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __LDG_PTR "l" +#else +#define __LDG_PTR "r" +#endif /*(defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)*/ +__CUDA_FP16_DECL__ __half2 __ldg(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.nc.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half __ldg(const __half *const ptr) +{ + __half ret; + asm ("ld.global.nc.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half2 __ldcg(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.cg.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half __ldcg(const __half *const ptr) +{ + __half ret; + asm ("ld.global.cg.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half2 __ldca(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.ca.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half __ldca(const __half *const ptr) +{ + __half ret; + asm ("ld.global.ca.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half2 __ldcs(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.cs.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half __ldcs(const __half *const ptr) +{ + __half ret; + asm ("ld.global.cs.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr)); + return ret; +} +__CUDA_FP16_DECL__ __half2 __ldlu(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.lu.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_FP16_DECL__ __half __ldlu(const __half *const ptr) +{ + __half ret; + asm ("ld.global.lu.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_FP16_DECL__ __half2 __ldcv(const __half2 *const ptr) +{ + __half2 ret; + asm ("ld.global.cv.b32 %0, [%1];" : "=r"(__HALF2_TO_UI(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_FP16_DECL__ __half __ldcv(const __half *const ptr) +{ + __half ret; + asm ("ld.global.cv.b16 %0, [%1];" : "=h"(__HALF_TO_US(ret)) : __LDG_PTR(ptr) : "memory"); + return ret; +} +__CUDA_FP16_DECL__ void __stwb(__half2 *const ptr, const __half2 value) +{ + asm ("st.global.wb.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__HALF2_TO_CUI(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stwb(__half *const ptr, const __half value) +{ + asm ("st.global.wb.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__HALF_TO_CUS(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stcg(__half2 *const ptr, const __half2 value) +{ + asm ("st.global.cg.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__HALF2_TO_CUI(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stcg(__half *const ptr, const __half value) +{ + asm ("st.global.cg.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__HALF_TO_CUS(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stcs(__half2 *const ptr, const __half2 value) +{ + asm ("st.global.cs.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__HALF2_TO_CUI(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stcs(__half *const ptr, const __half value) +{ + asm ("st.global.cs.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__HALF_TO_CUS(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stwt(__half2 *const ptr, const __half2 value) +{ + asm ("st.global.wt.b32 [%0], %1;" :: __LDG_PTR(ptr), "r"(__HALF2_TO_CUI(value)) : "memory"); +} +__CUDA_FP16_DECL__ void __stwt(__half *const ptr, const __half value) +{ + asm ("st.global.wt.b16 [%0], %1;" :: __LDG_PTR(ptr), "h"(__HALF_TO_CUS(value)) : "memory"); +} +#undef __LDG_PTR +#endif /*defined(__cplusplus) && (__CUDA_ARCH__ >= 320 || !defined(__CUDA_ARCH__))*/ +#if __CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__) +/****************************************************************************** +* __half2 comparison * +******************************************************************************/ +#define __COMPARISON_OP_HALF2_MACRO(name) /* do */ {\ + __half2 val; \ + asm( "{ "#name".f16x2.f16x2 %0,%1,%2;\n}" \ + :"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)),"r"(__HALF2_TO_CUI(b))); \ + return val; \ +} /* while(0) */ +__CUDA_FP16_DECL__ __half2 __heq2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.eq) +} +__CUDA_FP16_DECL__ __half2 __hne2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.ne) +} +__CUDA_FP16_DECL__ __half2 __hle2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.le) +} +__CUDA_FP16_DECL__ __half2 __hge2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.ge) +} +__CUDA_FP16_DECL__ __half2 __hlt2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.lt) +} +__CUDA_FP16_DECL__ __half2 __hgt2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.gt) +} +__CUDA_FP16_DECL__ __half2 __hequ2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.equ) +} +__CUDA_FP16_DECL__ __half2 __hneu2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.neu) +} +__CUDA_FP16_DECL__ __half2 __hleu2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.leu) +} +__CUDA_FP16_DECL__ __half2 __hgeu2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.geu) +} +__CUDA_FP16_DECL__ __half2 __hltu2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.ltu) +} +__CUDA_FP16_DECL__ __half2 __hgtu2(const __half2 a, const __half2 b) +{ + __COMPARISON_OP_HALF2_MACRO(set.gtu) +} +#undef __COMPARISON_OP_HALF2_MACRO +#define __BOOL_COMPARISON_OP_HALF2_MACRO(name) /* do */ {\ + __half2 val; \ + bool retval; \ + asm( "{ "#name".f16x2.f16x2 %0,%1,%2;\n}" \ + :"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a)),"r"(__HALF2_TO_CUI(b))); \ + if (__HALF2_TO_CUI(val) == 0x3C003C00U) {\ + retval = true; \ + } else { \ + retval = false; \ + }\ + return retval;\ +} /* while(0) */ +__CUDA_FP16_DECL__ bool __hbeq2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.eq) +} +__CUDA_FP16_DECL__ bool __hbne2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.ne) +} +__CUDA_FP16_DECL__ bool __hble2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.le) +} +__CUDA_FP16_DECL__ bool __hbge2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.ge) +} +__CUDA_FP16_DECL__ bool __hblt2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.lt) +} +__CUDA_FP16_DECL__ bool __hbgt2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.gt) +} +__CUDA_FP16_DECL__ bool __hbequ2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.equ) +} +__CUDA_FP16_DECL__ bool __hbneu2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.neu) +} +__CUDA_FP16_DECL__ bool __hbleu2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.leu) +} +__CUDA_FP16_DECL__ bool __hbgeu2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.geu) +} +__CUDA_FP16_DECL__ bool __hbltu2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.ltu) +} +__CUDA_FP16_DECL__ bool __hbgtu2(const __half2 a, const __half2 b) +{ + __BOOL_COMPARISON_OP_HALF2_MACRO(set.gtu) +} +#undef __BOOL_COMPARISON_OP_HALF2_MACRO +/****************************************************************************** +* __half comparison * +******************************************************************************/ +#define __COMPARISON_OP_HALF_MACRO(name) /* do */ {\ + unsigned short val; \ + asm( "{ .reg .pred __$temp3;\n" \ + " setp."#name".f16 __$temp3, %1, %2;\n" \ + " selp.u16 %0, 1, 0, __$temp3;}" \ + : "=h"(val) : "h"(__HALF_TO_CUS(a)), "h"(__HALF_TO_CUS(b))); \ + return (val != 0U) ? true : false; \ +} /* while(0) */ +__CUDA_FP16_DECL__ bool __heq(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(eq) +} +__CUDA_FP16_DECL__ bool __hne(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(ne) +} +__CUDA_FP16_DECL__ bool __hle(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(le) +} +__CUDA_FP16_DECL__ bool __hge(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(ge) +} +__CUDA_FP16_DECL__ bool __hlt(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(lt) +} +__CUDA_FP16_DECL__ bool __hgt(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(gt) +} +__CUDA_FP16_DECL__ bool __hequ(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(equ) +} +__CUDA_FP16_DECL__ bool __hneu(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(neu) +} +__CUDA_FP16_DECL__ bool __hleu(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(leu) +} +__CUDA_FP16_DECL__ bool __hgeu(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(geu) +} +__CUDA_FP16_DECL__ bool __hltu(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(ltu) +} +__CUDA_FP16_DECL__ bool __hgtu(const __half a, const __half b) +{ + __COMPARISON_OP_HALF_MACRO(gtu) +} +#undef __COMPARISON_OP_HALF_MACRO +/****************************************************************************** +* __half2 arithmetic * +******************************************************************************/ +__CUDA_FP16_DECL__ __half2 __hadd2(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(add) +} +__CUDA_FP16_DECL__ __half2 __hsub2(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(sub) +} +__CUDA_FP16_DECL__ __half2 __hmul2(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(mul) +} +__CUDA_FP16_DECL__ __half2 __hadd2_sat(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(add.sat) +} +__CUDA_FP16_DECL__ __half2 __hsub2_sat(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(sub.sat) +} +__CUDA_FP16_DECL__ __half2 __hmul2_sat(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(mul.sat) +} +__CUDA_FP16_DECL__ __half2 __hfma2(const __half2 a, const __half2 b, const __half2 c) +{ + __TERNARY_OP_HALF2_MACRO(fma.rn) +} +__CUDA_FP16_DECL__ __half2 __hfma2_sat(const __half2 a, const __half2 b, const __half2 c) +{ + __TERNARY_OP_HALF2_MACRO(fma.rn.sat) +} +__CUDA_FP16_DECL__ __half2 __h2div(const __half2 a, const __half2 b) { + __half ha = __low2half(a); + __half hb = __low2half(b); + + const __half v1 = __hdiv(ha, hb); + + ha = __high2half(a); + hb = __high2half(b); + + const __half v2 = __hdiv(ha, hb); + + return __halves2half2(v1, v2); +} +/****************************************************************************** +* __half arithmetic * +******************************************************************************/ +__CUDA_FP16_DECL__ __half __hadd(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(add) +} +__CUDA_FP16_DECL__ __half __hsub(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(sub) +} +__CUDA_FP16_DECL__ __half __hmul(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(mul) +} +__CUDA_FP16_DECL__ __half __hadd_sat(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(add.sat) +} +__CUDA_FP16_DECL__ __half __hsub_sat(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(sub.sat) +} +__CUDA_FP16_DECL__ __half __hmul_sat(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(mul.sat) +} + +__CUDA_FP16_DECL__ __half __hfma(const __half a, const __half b, const __half c) +{ + __TERNARY_OP_HALF_MACRO(fma.rn) +} +__CUDA_FP16_DECL__ __half __hfma_sat(const __half a, const __half b, const __half c) +{ + __TERNARY_OP_HALF_MACRO(fma.rn.sat) +} +__CUDA_FP16_DECL__ __half __hdiv(const __half a, const __half b) { + __half v; + __half abs; + __half den; + __HALF_TO_US(den) = 0x008FU; + + float rcp; + const float fa = __half2float(a); + const float fb = __half2float(b); + + asm("{rcp.approx.ftz.f32 %0, %1;\n}" :"=f"(rcp) : "f"(fb)); + + float fv = rcp * fa; + + v = __float2half(fv); + __HALF_TO_US(abs) = static_cast(static_cast(__HALF_TO_CUS(v)) & 0x00007FFFU); + if (__hlt(abs, den) && (!(__HALF_TO_CUS(abs) == 0x0000U))) { + const float err = __fmaf_rn(-fb, fv, fa); + fv = __fmaf_rn(rcp, err, fv); + v = __float2half(fv); + } + return v; +} + +/****************************************************************************** +* __half2 functions * +******************************************************************************/ +#define __SPEC_CASE2(i,r, spc, ulp) \ + "{.reg.b32 spc, ulp, p;\n"\ + " mov.b32 spc,"#spc";\n"\ + " mov.b32 ulp,"#ulp";\n"\ + " set.eq.f16x2.f16x2 p,"#i", spc;\n"\ + " fma.rn.f16x2 "#r",p,ulp,"#r";\n}\n" +#define __SPEC_CASE(i,r, spc, ulp) \ + "{.reg.b16 spc, ulp, p;\n"\ + " mov.b16 spc,"#spc";\n"\ + " mov.b16 ulp,"#ulp";\n"\ + " set.eq.f16.f16 p,"#i", spc;\n"\ + " fma.rn.f16 "#r",p,ulp,"#r";\n}\n" +#define __APPROX_FCAST(fun) /* do */ {\ + __half val;\ + asm("{.reg.b32 f; \n"\ + " .reg.b16 r; \n"\ + " mov.b16 r,%1; \n"\ + " cvt.f32.f16 f,r; \n"\ + " "#fun".approx.f32 f,f; \n"\ + " cvt.rn.f16.f32 r,f; \n"\ + " mov.b16 %0,r; \n"\ + "}": "=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a)));\ + return val;\ +} /* while(0) */ +#define __APPROX_FCAST2(fun) /* do */ {\ + __half2 val;\ + asm("{.reg.b16 hl, hu; \n"\ + " .reg.b32 fl, fu; \n"\ + " mov.b32 {hl, hu}, %1; \n"\ + " cvt.f32.f16 fl, hl; \n"\ + " cvt.f32.f16 fu, hu; \n"\ + " "#fun".approx.f32 fl, fl; \n"\ + " "#fun".approx.f32 fu, fu; \n"\ + " cvt.rn.f16.f32 hl, fl; \n"\ + " cvt.rn.f16.f32 hu, fu; \n"\ + " mov.b32 %0, {hl, hu}; \n"\ + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); \ + return val;\ +} /* while(0) */ +static __device__ __forceinline__ float __float_simpl_sinf(float a); +static __device__ __forceinline__ float __float_simpl_cosf(float a); +__CUDA_FP16_DECL__ __half __hsin_internal(const __half a) { + float f = __half2float(a); + f = __float_simpl_sinf(f); + return __float2half_rn(f); +} +__CUDA_FP16_DECL__ __half hsin(const __half a) { + __half r = __hsin_internal(a); + asm("{\n\t" + " .reg.b16 i,r,t; \n\t" + " mov.b16 r, %0; \n\t" + " mov.b16 i, %1; \n\t" + " mov.b16 t, 0x8000U; \n\t" + " and.b16 t,r,t; \n\t" + __SPEC_CASE(i, r, 0X32B3U, 0x0800U) + __SPEC_CASE(i, r, 0X5CB0U, 0x1000U) + __SPEC_CASE(i, r, 0XB2B3U, 0x8800U) + __SPEC_CASE(i, r, 0XDCB0U, 0x9000U) + " or.b16 r,r,t; \n\t" + " mov.b16 %0, r; \n" + "}\n" : "+h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(a))); + return r; +} +__CUDA_FP16_DECL__ __half2 h2sin(const __half2 a) { + const __half l = __low2half(a); + const __half h = __high2half(a); + const __half sl = __hsin_internal(l); + const __half sh = __hsin_internal(h); + __half2 r = __halves2half2(sl, sh); + asm("{\n\t" + " .reg.b32 i,r,t; \n\t" + " mov.b32 r, %0; \n\t" + " mov.b32 i, %1; \n\t" + " and.b32 t, r, 0x80008000U; \n\t" + __SPEC_CASE2(i, r, 0X32B332B3U, 0x08000800U) + __SPEC_CASE2(i, r, 0X5CB05CB0U, 0x10001000U) + __SPEC_CASE2(i, r, 0XB2B3B2B3U, 0x88008800U) + __SPEC_CASE2(i, r, 0XDCB0DCB0U, 0x90009000U) + " or.b32 r, r, t; \n\t" + " mov.b32 %0, r; \n" + "}\n" : "+r"(__HALF2_TO_UI(r)) : "r"(__HALF2_TO_CUI(a))); + return r; +} +__CUDA_FP16_DECL__ __half __hcos_internal(const __half a) { + float f = __half2float(a); + f = __float_simpl_cosf(f); + return __float2half_rn(f); +} +__CUDA_FP16_DECL__ __half hcos(const __half a) { + __half r = __hcos_internal(a); + asm("{\n\t" + " .reg.b16 i,r; \n\t" + " mov.b16 r, %0; \n\t" + " mov.b16 i, %1; \n\t" + __SPEC_CASE(i, r, 0X2B7CU, 0x1000U) + __SPEC_CASE(i, r, 0XAB7CU, 0x1000U) + " mov.b16 %0, r; \n" + "}\n" : "+h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(a))); + return r; +} +__CUDA_FP16_DECL__ __half2 h2cos(const __half2 a) { + const __half l = __low2half(a); + const __half h = __high2half(a); + const __half cl = __hcos_internal(l); + const __half ch = __hcos_internal(h); + __half2 r = __halves2half2(cl, ch); + asm("{\n\t" + " .reg.b32 i,r; \n\t" + " mov.b32 r, %0; \n\t" + " mov.b32 i, %1; \n\t" + __SPEC_CASE2(i, r, 0X2B7C2B7CU, 0x10001000U) + __SPEC_CASE2(i, r, 0XAB7CAB7CU, 0x10001000U) + " mov.b32 %0, r; \n" + "}\n" : "+r"(__HALF2_TO_UI(r)) : "r"(__HALF2_TO_CUI(a))); + return r; +} +static __device__ __forceinline__ float __internal_trig_reduction_kernel(const float a, int *quadrant) +{ + const int q = __float2int_rn(a * 0.636619772F); + const float j = static_cast(q); + float t = __fmaf_rn(-j, 1.5707962512969971e+000F, a); + t = __fmaf_rn(-j, 7.5497894158615964e-008F, t); + *quadrant = q; + return t; +} +static __device__ __forceinline__ float __internal_sin_cos_kernel(float x, const int i) +{ + float z; + const float x2 = x*x; + + if ((static_cast(i) & 1U) != 0U) { + z = 2.44331571e-5F; + z = __fmaf_rn(z, x2, -1.38873163e-3F); + } + else { + z = -1.95152959e-4F; + z = __fmaf_rn(z, x2, 8.33216087e-3F); + } + if ((static_cast(i) & 1U) != 0U) { + z = __fmaf_rn(z, x2, 4.16666457e-2F); + z = __fmaf_rn(z, x2, -5.00000000e-1F); + } + else { + z = __fmaf_rn(z, x2, -1.66666546e-1F); + z = __fmaf_rn(z, x2, 0.0F); + } + if ((static_cast(i) & 1U) != 0U) { + x = __fmaf_rn(z, x2, 1.0F); + } + else { + x = __fmaf_rn(z, x, x); + } + if ((static_cast(i) & 2U) != 0U) { + x = __fmaf_rn(x, -1.0F, 0.0F); + } + return x; +} +static __device__ __forceinline__ float __float_simpl_sinf(float a) +{ + float z; + int i; + if (::isinf(a)) { + a = a * 0.0F; + } + a = __internal_trig_reduction_kernel(a, &i); + z = __internal_sin_cos_kernel(a, i); + return z; +} +static __device__ __forceinline__ float __float_simpl_cosf(float a) +{ + float z; + int i; + if (::isinf(a)) { + a = a * 0.0F; + } + a = __internal_trig_reduction_kernel(a, &i); + i++; + z = __internal_sin_cos_kernel(a, i); + return z; +} + +__CUDA_FP16_DECL__ __half hexp(const __half a) { + __half val; + asm("{.reg.b32 f, C; \n" + " .reg.b16 h,r; \n" + " mov.b16 h,%1; \n" + " cvt.f32.f16 f,h; \n" + " mov.b32 C, 0x3fb8aa3bU; \n" + " mul.f32 f,f,C; \n" + " ex2.approx.f32 f,f; \n" + " cvt.rn.f16.f32 r,f; \n" + __SPEC_CASE(h, r, 0X1F79U, 0x9400U) + __SPEC_CASE(h, r, 0X25CFU, 0x9400U) + __SPEC_CASE(h, r, 0XC13BU, 0x0400U) + __SPEC_CASE(h, r, 0XC1EFU, 0x0200U) + " mov.b16 %0,r; \n" + "}": "=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2exp(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 h,r,fl,fu, C; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " mov.b32 C, 0x3fb8aa3bU; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " ex2.approx.f32 fl, fl; \n" + " ex2.approx.f32 fu, fu; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __SPEC_CASE2(h, r, 0X1F791F79U, 0x94009400U) + __SPEC_CASE2(h, r, 0X25CF25CFU, 0x94009400U) + __SPEC_CASE2(h, r, 0XC13BC13BU, 0x04000400U) + __SPEC_CASE2(h, r, 0XC1EFC1EFU, 0x02000200U) + " mov.b32 %0, r; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half hexp2(const __half a) { + __half val; + asm("{.reg.b32 f, ULP; \n" + " .reg.b16 r; \n" + " mov.b16 r,%1; \n" + " cvt.f32.f16 f,r; \n" + " ex2.approx.f32 f,f; \n" + " mov.b32 ULP, 0x33800000U;\n" + " fma.rn.f32 f,f,ULP,f; \n" + " cvt.rn.f16.f32 r,f; \n" + " mov.b16 %0,r; \n" + "}": "=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2exp2(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 fl, fu, ULP; \n" + " mov.b32 {hl, hu}, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " ex2.approx.f32 fl, fl; \n" + " ex2.approx.f32 fu, fu; \n" + " mov.b32 ULP, 0x33800000U;\n" + " fma.rn.f32 fl,fl,ULP,fl; \n" + " fma.rn.f32 fu,fu,ULP,fu; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 %0, {hl, hu}; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half hexp10(const __half a) { + __half val; + asm("{.reg.b16 h,r; \n" + " .reg.b32 f, C; \n" + " mov.b16 h, %1; \n" + " cvt.f32.f16 f, h; \n" + " mov.b32 C, 0x40549A78U; \n" + " mul.f32 f,f,C; \n" + " ex2.approx.f32 f, f; \n" + " cvt.rn.f16.f32 r, f; \n" + __SPEC_CASE(h, r, 0x34DEU, 0x9800U) + __SPEC_CASE(h, r, 0x9766U, 0x9000U) + __SPEC_CASE(h, r, 0x9972U, 0x1000U) + __SPEC_CASE(h, r, 0xA5C4U, 0x1000U) + __SPEC_CASE(h, r, 0xBF0AU, 0x8100U) + " mov.b16 %0, r; \n" + "}":"=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2exp10(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 h,r,fl,fu, C; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " mov.b32 C, 0x40549A78U; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " ex2.approx.f32 fl, fl; \n" + " ex2.approx.f32 fu, fu; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __SPEC_CASE2(h, r, 0x34DE34DEU, 0x98009800U) + __SPEC_CASE2(h, r, 0x97669766U, 0x90009000U) + __SPEC_CASE2(h, r, 0x99729972U, 0x10001000U) + __SPEC_CASE2(h, r, 0xA5C4A5C4U, 0x10001000U) + __SPEC_CASE2(h, r, 0xBF0ABF0AU, 0x81008100U) + " mov.b32 %0, r; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half hlog2(const __half a) { + __half val; + asm("{.reg.b16 h, r; \n" + " .reg.b32 f; \n" + " mov.b16 h, %1; \n" + " cvt.f32.f16 f, h; \n" + " lg2.approx.f32 f, f; \n" + " cvt.rn.f16.f32 r, f; \n" + __SPEC_CASE(r, r, 0xA2E2U, 0x8080U) + __SPEC_CASE(r, r, 0xBF46U, 0x9400U) + " mov.b16 %0, r; \n" + "}":"=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2log2(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 fl, fu, r, p; \n" + " mov.b32 {hl, hu}, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " lg2.approx.f32 fl, fl; \n" + " lg2.approx.f32 fu, fu; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __SPEC_CASE2(r, r, 0xA2E2A2E2U, 0x80808080U) + __SPEC_CASE2(r, r, 0xBF46BF46U, 0x94009400U) + " mov.b32 %0, r; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half hlog(const __half a) { + __half val; + asm("{.reg.b32 f, C; \n" + " .reg.b16 r,h; \n" + " mov.b16 h,%1; \n" + " cvt.f32.f16 f,h; \n" + " lg2.approx.f32 f,f; \n" + " mov.b32 C, 0x3f317218U; \n" + " mul.f32 f,f,C; \n" + " cvt.rn.f16.f32 r,f; \n" + __SPEC_CASE(h, r, 0X160DU, 0x9C00U) + __SPEC_CASE(h, r, 0X3BFEU, 0x8010U) + __SPEC_CASE(h, r, 0X3C0BU, 0x8080U) + __SPEC_CASE(h, r, 0X6051U, 0x1C00U) + " mov.b16 %0,r; \n" + "}": "=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2log(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 r, fl, fu, C, h; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " lg2.approx.f32 fl, fl; \n" + " lg2.approx.f32 fu, fu; \n" + " mov.b32 C, 0x3f317218U; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __SPEC_CASE2(h, r, 0X160D160DU, 0x9C009C00U) + __SPEC_CASE2(h, r, 0X3BFE3BFEU, 0x80108010U) + __SPEC_CASE2(h, r, 0X3C0B3C0BU, 0x80808080U) + __SPEC_CASE2(h, r, 0X60516051U, 0x1C001C00U) + " mov.b32 %0, r; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +__CUDA_FP16_DECL__ __half hlog10(const __half a) { + __half val; + asm("{.reg.b16 h, r; \n" + " .reg.b32 f, C; \n" + " mov.b16 h, %1; \n" + " cvt.f32.f16 f, h; \n" + " lg2.approx.f32 f, f; \n" + " mov.b32 C, 0x3E9A209BU; \n" + " mul.f32 f,f,C; \n" + " cvt.rn.f16.f32 r, f; \n" + __SPEC_CASE(h, r, 0x338FU, 0x1000U) + __SPEC_CASE(h, r, 0x33F8U, 0x9000U) + __SPEC_CASE(h, r, 0x57E1U, 0x9800U) + __SPEC_CASE(h, r, 0x719DU, 0x9C00U) + " mov.b16 %0, r; \n" + "}":"=h"(__HALF_TO_US(val)) : "h"(__HALF_TO_CUS(a))); + return val; +} +__CUDA_FP16_DECL__ __half2 h2log10(const __half2 a) { + __half2 val; + asm("{.reg.b16 hl, hu; \n" + " .reg.b32 r, fl, fu, C, h; \n" + " mov.b32 {hl, hu}, %1; \n" + " mov.b32 h, %1; \n" + " cvt.f32.f16 fl, hl; \n" + " cvt.f32.f16 fu, hu; \n" + " lg2.approx.f32 fl, fl; \n" + " lg2.approx.f32 fu, fu; \n" + " mov.b32 C, 0x3E9A209BU; \n" + " mul.f32 fl,fl,C; \n" + " mul.f32 fu,fu,C; \n" + " cvt.rn.f16.f32 hl, fl; \n" + " cvt.rn.f16.f32 hu, fu; \n" + " mov.b32 r, {hl, hu}; \n" + __SPEC_CASE2(h, r, 0x338F338FU, 0x10001000U) + __SPEC_CASE2(h, r, 0x33F833F8U, 0x90009000U) + __SPEC_CASE2(h, r, 0x57E157E1U, 0x98009800U) + __SPEC_CASE2(h, r, 0x719D719DU, 0x9C009C00U) + " mov.b32 %0, r; \n" + "}":"=r"(__HALF2_TO_UI(val)) : "r"(__HALF2_TO_CUI(a))); + return val; +} +#undef __SPEC_CASE2 +#undef __SPEC_CASE +__CUDA_FP16_DECL__ __half2 h2rcp(const __half2 a) { + __APPROX_FCAST2(rcp) +} +__CUDA_FP16_DECL__ __half hrcp(const __half a) { + __APPROX_FCAST(rcp) +} +__CUDA_FP16_DECL__ __half2 h2rsqrt(const __half2 a) { + __APPROX_FCAST2(rsqrt) +} +__CUDA_FP16_DECL__ __half hrsqrt(const __half a) { + __APPROX_FCAST(rsqrt) +} +__CUDA_FP16_DECL__ __half2 h2sqrt(const __half2 a) { + __APPROX_FCAST2(sqrt) +} +__CUDA_FP16_DECL__ __half hsqrt(const __half a) { + __APPROX_FCAST(sqrt) +} +#undef __APPROX_FCAST +#undef __APPROX_FCAST2 +__CUDA_FP16_DECL__ __half2 __hisnan2(const __half2 a) +{ + __half2 r; + asm("{set.nan.f16x2.f16x2 %0,%1,%2;\n}" + :"=r"(__HALF2_TO_UI(r)) : "r"(__HALF2_TO_CUI(a)), "r"(__HALF2_TO_CUI(a))); + return r; +} +__CUDA_FP16_DECL__ bool __hisnan(const __half a) +{ + __half r; + asm("{set.nan.f16.f16 %0,%1,%2;\n}" + :"=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(a)), "h"(__HALF_TO_CUS(a))); + return __HALF_TO_CUS(r) != 0U; +} +__CUDA_FP16_DECL__ __half2 __hneg2(const __half2 a) +{ + __half2 r; + asm("{neg.f16x2 %0,%1;\n}" + :"=r"(__HALF2_TO_UI(r)) : "r"(__HALF2_TO_CUI(a))); + return r; +} +__CUDA_FP16_DECL__ __half __hneg(const __half a) +{ + __half r; + asm("{neg.f16 %0,%1;\n}" + :"=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(a))); + return r; +} +__CUDA_FP16_DECL__ __half2 __habs2(const __half2 a) +{ + __half2 r; + asm("{abs.f16x2 %0,%1;\n}" + :"=r"(__HALF2_TO_UI(r)) : "r"(__HALF2_TO_CUI(a))); + return r; +} +__CUDA_FP16_DECL__ __half __habs(const __half a) +{ + __half r; + asm("{abs.f16 %0,%1;\n}" + :"=h"(__HALF_TO_US(r)) : "h"(__HALF_TO_CUS(a))); + return r; +} + +__CUDA_FP16_DECL__ __half2 __hcmadd(const __half2 a, const __half2 b, const __half2 c) +{ + // fast version of complex multiply-accumulate + // (a.re, a.im) * (b.re, b.im) + (c.re, c.im) + // acc.re = (c.re + a.re*b.re) - a.im*b.im + // acc.im = (c.im + a.re*b.im) + a.im*b.re + const __half2 a_re = __half2half2(a.x); + __half2 acc = __hfma2(a_re, b, c); + const __half2 a_im = __half2half2(a.y); + const __half2 ib = __halves2half2(__hneg(b.y), b.x); + acc = __hfma2(a_im, ib, acc); + return acc; +} +#endif /*__CUDA_ARCH__ >= 530 || !defined(__CUDA_ARCH__)*/ + +#if __CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__) +/****************************************************************************** +* __half arithmetic * +******************************************************************************/ +__CUDA_FP16_DECL__ __half __hmax(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(max) +} +__CUDA_FP16_DECL__ __half __hmin(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(min) +} +__CUDA_FP16_DECL__ __half __hmax_nan(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(max.NaN) +} +__CUDA_FP16_DECL__ __half __hmin_nan(const __half a, const __half b) +{ + __BINARY_OP_HALF_MACRO(min.NaN) +} +__CUDA_FP16_DECL__ __half __hfma_relu(const __half a, const __half b, const __half c) +{ + __TERNARY_OP_HALF_MACRO(fma.rn.relu) +} +/****************************************************************************** +* __half2 arithmetic * +******************************************************************************/ +__CUDA_FP16_DECL__ __half2 __hmax2(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(max) +} +__CUDA_FP16_DECL__ __half2 __hmin2(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(min) +} +__CUDA_FP16_DECL__ __half2 __hmax2_nan(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(max.NaN) +} +__CUDA_FP16_DECL__ __half2 __hmin2_nan(const __half2 a, const __half2 b) +{ + __BINARY_OP_HALF2_MACRO(min.NaN) +} +__CUDA_FP16_DECL__ __half2 __hfma2_relu(const __half2 a, const __half2 b, const __half2 c) +{ + __TERNARY_OP_HALF2_MACRO(fma.rn.relu) +} +#endif /*__CUDA_ARCH__ >= 800 || !defined(__CUDA_ARCH__)*/ + +/* Define __PTR for atomicAdd prototypes below, undef after done */ +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __PTR "l" +#else +#define __PTR "r" +#endif /*(defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)*/ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 600 + +__CUDA_FP16_DECL__ __half2 atomicAdd(__half2 *const address, const __half2 val) { + __half2 r; + asm volatile ("{ atom.add.noftz.f16x2 %0,[%1],%2; }\n" + : "=r"(__HALF2_TO_UI(r)) : __PTR(address), "r"(__HALF2_TO_CUI(val)) + : "memory"); + return r; +} + +#endif /*!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 600*/ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +__CUDA_FP16_DECL__ __half atomicAdd(__half *const address, const __half val) { + __half r; + asm volatile ("{ atom.add.noftz.f16 %0,[%1],%2; }\n" + : "=h"(__HALF_TO_US(r)) + : __PTR(address), "h"(__HALF_TO_CUS(val)) + : "memory"); + return r; +} + +#endif /*!defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700*/ + +#undef __PTR + +#undef __CUDA_FP16_DECL__ +#endif /* defined(__CUDACC__) */ +#endif /* defined(__cplusplus) */ + +#undef __TERNARY_OP_HALF2_MACRO +#undef __TERNARY_OP_HALF_MACRO +#undef __BINARY_OP_HALF2_MACRO +#undef __BINARY_OP_HALF_MACRO + +#undef __CUDA_HOSTDEVICE_FP16_DECL__ +#undef __CUDA_FP16_DECL__ + +/* Define first-class types "half" and "half2", unless user specifies otherwise via "#define CUDA_NO_HALF" */ +/* C cannot ever have these types defined here, because __half and __half2 are C++ classes */ +#if defined(__cplusplus) && !defined(CUDA_NO_HALF) +typedef __half half; +typedef __half2 half2; +// for consistency with __nv_bfloat16 +typedef __half __nv_half; +typedef __half2 __nv_half2; +typedef __half_raw __nv_half_raw; +typedef __half2_raw __nv_half2_raw; +typedef __half nv_half; +typedef __half2 nv_half2; +#endif /* defined(__cplusplus) && !defined(CUDA_NO_HALF) */ + +#if defined(__CPP_VERSION_AT_LEAST_11_FP16) +#undef __CPP_VERSION_AT_LEAST_11_FP16 +#endif /* defined(__CPP_VERSION_AT_LEAST_11_FP16) */ + +#endif /* end of include guard: __CUDA_FP16_HPP__ */ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_paths.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff96640d16bab02679117b3df61c546717ced39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cuda_paths.py @@ -0,0 +1,258 @@ +import sys +import re +import os +from collections import namedtuple + +from numba.core.config import IS_WIN32 +from numba.misc.findlib import find_lib, find_file + + +_env_path_tuple = namedtuple('_env_path_tuple', ['by', 'info']) + + +def _find_valid_path(options): + """Find valid path from *options*, which is a list of 2-tuple of + (name, path). Return first pair where *path* is not None. + If no valid path is found, return ('', None) + """ + for by, data in options: + if data is not None: + return by, data + else: + return '', None + + +def _get_libdevice_path_decision(): + options = [ + ('Conda environment', get_conda_ctk()), + ('Conda environment (NVIDIA package)', get_nvidia_libdevice_ctk()), + ('CUDA_HOME', get_cuda_home('nvvm', 'libdevice')), + ('System', get_system_ctk('nvvm', 'libdevice')), + ('Debian package', get_debian_pkg_libdevice()), + ] + by, libdir = _find_valid_path(options) + return by, libdir + + +def _nvvm_lib_dir(): + if IS_WIN32: + return 'nvvm', 'bin' + else: + return 'nvvm', 'lib64' + + +def _get_nvvm_path_decision(): + options = [ + ('Conda environment', get_conda_ctk()), + ('Conda environment (NVIDIA package)', get_nvidia_nvvm_ctk()), + ('CUDA_HOME', get_cuda_home(*_nvvm_lib_dir())), + ('System', get_system_ctk(*_nvvm_lib_dir())), + ] + by, path = _find_valid_path(options) + return by, path + + +def _get_libdevice_paths(): + by, libdir = _get_libdevice_path_decision() + # Search for pattern + pat = r'libdevice(\.\d+)*\.bc$' + candidates = find_file(re.compile(pat), libdir) + # Keep only the max (most recent version) of the bitcode files. + out = max(candidates, default=None) + return _env_path_tuple(by, out) + + +def _cudalib_path(): + if IS_WIN32: + return 'bin' + else: + return 'lib64' + + +def _cuda_home_static_cudalib_path(): + if IS_WIN32: + return ('lib', 'x64') + else: + return ('lib64',) + + +def _get_cudalib_dir_path_decision(): + options = [ + ('Conda environment', get_conda_ctk()), + ('Conda environment (NVIDIA package)', get_nvidia_cudalib_ctk()), + ('CUDA_HOME', get_cuda_home(_cudalib_path())), + ('System', get_system_ctk(_cudalib_path())), + ] + by, libdir = _find_valid_path(options) + return by, libdir + + +def _get_static_cudalib_dir_path_decision(): + options = [ + ('Conda environment', get_conda_ctk()), + ('Conda environment (NVIDIA package)', get_nvidia_static_cudalib_ctk()), + ('CUDA_HOME', get_cuda_home(*_cuda_home_static_cudalib_path())), + ('System', get_system_ctk(_cudalib_path())), + ] + by, libdir = _find_valid_path(options) + return by, libdir + + +def _get_cudalib_dir(): + by, libdir = _get_cudalib_dir_path_decision() + return _env_path_tuple(by, libdir) + + +def _get_static_cudalib_dir(): + by, libdir = _get_static_cudalib_dir_path_decision() + return _env_path_tuple(by, libdir) + + +def get_system_ctk(*subdirs): + """Return path to system-wide cudatoolkit; or, None if it doesn't exist. + """ + # Linux? + if sys.platform.startswith('linux'): + # Is cuda alias to /usr/local/cuda? + # We are intentionally not getting versioned cuda installation. + base = '/usr/local/cuda' + if os.path.exists(base): + return os.path.join(base, *subdirs) + + +def get_conda_ctk(): + """Return path to directory containing the shared libraries of cudatoolkit. + """ + is_conda_env = os.path.exists(os.path.join(sys.prefix, 'conda-meta')) + if not is_conda_env: + return + # Assume the existence of NVVM to imply cudatoolkit installed + paths = find_lib('nvvm') + if not paths: + return + # Use the directory name of the max path + return os.path.dirname(max(paths)) + + +def get_nvidia_nvvm_ctk(): + """Return path to directory containing the NVVM shared library. + """ + is_conda_env = os.path.exists(os.path.join(sys.prefix, 'conda-meta')) + if not is_conda_env: + return + + # Assume the existence of NVVM in the conda env implies that a CUDA toolkit + # conda package is installed. + + # First, try the location used on Linux and the Windows 11.x packages + libdir = os.path.join(sys.prefix, 'nvvm', _cudalib_path()) + if not os.path.exists(libdir) or not os.path.isdir(libdir): + # If that fails, try the location used for Windows 12.x packages + libdir = os.path.join(sys.prefix, 'Library', 'nvvm', _cudalib_path()) + if not os.path.exists(libdir) or not os.path.isdir(libdir): + # If that doesn't exist either, assume we don't have the NVIDIA + # conda package + return + + paths = find_lib('nvvm', libdir=libdir) + if not paths: + return + # Use the directory name of the max path + return os.path.dirname(max(paths)) + + +def get_nvidia_libdevice_ctk(): + """Return path to directory containing the libdevice library. + """ + nvvm_ctk = get_nvidia_nvvm_ctk() + if not nvvm_ctk: + return + nvvm_dir = os.path.dirname(nvvm_ctk) + return os.path.join(nvvm_dir, 'libdevice') + + +def get_nvidia_cudalib_ctk(): + """Return path to directory containing the shared libraries of cudatoolkit. + """ + nvvm_ctk = get_nvidia_nvvm_ctk() + if not nvvm_ctk: + return + env_dir = os.path.dirname(os.path.dirname(nvvm_ctk)) + subdir = 'bin' if IS_WIN32 else 'lib' + return os.path.join(env_dir, subdir) + + +def get_nvidia_static_cudalib_ctk(): + """Return path to directory containing the static libraries of cudatoolkit. + """ + nvvm_ctk = get_nvidia_nvvm_ctk() + if not nvvm_ctk: + return + + if IS_WIN32 and ("Library" not in nvvm_ctk): + # Location specific to CUDA 11.x packages on Windows + dirs = ('Lib', 'x64') + else: + # Linux, or Windows with CUDA 12.x packages + dirs = ('lib',) + + env_dir = os.path.dirname(os.path.dirname(nvvm_ctk)) + return os.path.join(env_dir, *dirs) + + +def get_cuda_home(*subdirs): + """Get paths of CUDA_HOME. + If *subdirs* are the subdirectory name to be appended in the resulting + path. + """ + cuda_home = os.environ.get('CUDA_HOME') + if cuda_home is None: + # Try Windows CUDA installation without Anaconda + cuda_home = os.environ.get('CUDA_PATH') + if cuda_home is not None: + return os.path.join(cuda_home, *subdirs) + + +def _get_nvvm_path(): + by, path = _get_nvvm_path_decision() + candidates = find_lib('nvvm', path) + path = max(candidates) if candidates else None + return _env_path_tuple(by, path) + + +def get_cuda_paths(): + """Returns a dictionary mapping component names to a 2-tuple + of (source_variable, info). + + The returned dictionary will have the following keys and infos: + - "nvvm": file_path + - "libdevice": List[Tuple[arch, file_path]] + - "cudalib_dir": directory_path + + Note: The result of the function is cached. + """ + # Check cache + if hasattr(get_cuda_paths, '_cached_result'): + return get_cuda_paths._cached_result + else: + # Not in cache + d = { + 'nvvm': _get_nvvm_path(), + 'libdevice': _get_libdevice_paths(), + 'cudalib_dir': _get_cudalib_dir(), + 'static_cudalib_dir': _get_static_cudalib_dir(), + } + # Cache result + get_cuda_paths._cached_result = d + return d + + +def get_debian_pkg_libdevice(): + """ + Return the Debian NVIDIA Maintainers-packaged libdevice location, if it + exists. + """ + pkg_libdevice_location = '/usr/lib/nvidia-cuda-toolkit/libdevice' + if not os.path.exists(pkg_libdevice_location): + return None + return pkg_libdevice_location diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudadecl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudadecl.py new file mode 100644 index 0000000000000000000000000000000000000000..dde8977936e79d90fb911268d767e9144d65aa9a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudadecl.py @@ -0,0 +1,806 @@ +import operator +from numba.core import types +from numba.core.typing.npydecl import (parse_dtype, parse_shape, + register_number_classes, + register_numpy_ufunc, + trigonometric_functions, + comparison_functions, + math_operations, + bit_twiddling_functions) +from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate, + AbstractTemplate, CallableTemplate, + signature, Registry) +from numba.cuda.types import dim3 +from numba.core.typeconv import Conversion +from numba import cuda +from numba.cuda.compiler import declare_device_function_template + +registry = Registry() +register = registry.register +register_attr = registry.register_attr +register_global = registry.register_global + +register_number_classes(register_global) + + +class Cuda_array_decl(CallableTemplate): + def generic(self): + def typer(shape, dtype): + + # Only integer literals and tuples of integer literals are valid + # shapes + if isinstance(shape, types.Integer): + if not isinstance(shape, types.IntegerLiteral): + return None + elif isinstance(shape, (types.Tuple, types.UniTuple)): + if any([not isinstance(s, types.IntegerLiteral) + for s in shape]): + return None + else: + return None + + ndim = parse_shape(shape) + nb_dtype = parse_dtype(dtype) + if nb_dtype is not None and ndim is not None: + return types.Array(dtype=nb_dtype, ndim=ndim, layout='C') + + return typer + + +@register +class Cuda_shared_array(Cuda_array_decl): + key = cuda.shared.array + + +@register +class Cuda_local_array(Cuda_array_decl): + key = cuda.local.array + + +@register +class Cuda_const_array_like(CallableTemplate): + key = cuda.const.array_like + + def generic(self): + def typer(ndarray): + return ndarray + return typer + + +@register +class Cuda_threadfence_device(ConcreteTemplate): + key = cuda.threadfence + cases = [signature(types.none)] + + +@register +class Cuda_threadfence_block(ConcreteTemplate): + key = cuda.threadfence_block + cases = [signature(types.none)] + + +@register +class Cuda_threadfence_system(ConcreteTemplate): + key = cuda.threadfence_system + cases = [signature(types.none)] + + +@register +class Cuda_syncwarp(ConcreteTemplate): + key = cuda.syncwarp + cases = [signature(types.none), signature(types.none, types.i4)] + + +@register +class Cuda_shfl_sync_intrinsic(ConcreteTemplate): + key = cuda.shfl_sync_intrinsic + cases = [ + signature(types.Tuple((types.i4, types.b1)), + types.i4, types.i4, types.i4, types.i4, types.i4), + signature(types.Tuple((types.i8, types.b1)), + types.i4, types.i4, types.i8, types.i4, types.i4), + signature(types.Tuple((types.f4, types.b1)), + types.i4, types.i4, types.f4, types.i4, types.i4), + signature(types.Tuple((types.f8, types.b1)), + types.i4, types.i4, types.f8, types.i4, types.i4), + ] + + +@register +class Cuda_vote_sync_intrinsic(ConcreteTemplate): + key = cuda.vote_sync_intrinsic + cases = [signature(types.Tuple((types.i4, types.b1)), + types.i4, types.i4, types.b1)] + + +@register +class Cuda_match_any_sync(ConcreteTemplate): + key = cuda.match_any_sync + cases = [ + signature(types.i4, types.i4, types.i4), + signature(types.i4, types.i4, types.i8), + signature(types.i4, types.i4, types.f4), + signature(types.i4, types.i4, types.f8), + ] + + +@register +class Cuda_match_all_sync(ConcreteTemplate): + key = cuda.match_all_sync + cases = [ + signature(types.Tuple((types.i4, types.b1)), types.i4, types.i4), + signature(types.Tuple((types.i4, types.b1)), types.i4, types.i8), + signature(types.Tuple((types.i4, types.b1)), types.i4, types.f4), + signature(types.Tuple((types.i4, types.b1)), types.i4, types.f8), + ] + + +@register +class Cuda_activemask(ConcreteTemplate): + key = cuda.activemask + cases = [signature(types.uint32)] + + +@register +class Cuda_lanemask_lt(ConcreteTemplate): + key = cuda.lanemask_lt + cases = [signature(types.uint32)] + + +@register +class Cuda_popc(ConcreteTemplate): + """ + Supported types from `llvm.popc` + [here](http://docs.nvidia.com/cuda/nvvm-ir-spec/index.html#bit-manipulations-intrinics) + """ + key = cuda.popc + cases = [ + signature(types.int8, types.int8), + signature(types.int16, types.int16), + signature(types.int32, types.int32), + signature(types.int64, types.int64), + signature(types.uint8, types.uint8), + signature(types.uint16, types.uint16), + signature(types.uint32, types.uint32), + signature(types.uint64, types.uint64), + ] + + +@register +class Cuda_fma(ConcreteTemplate): + """ + Supported types from `llvm.fma` + [here](https://docs.nvidia.com/cuda/nvvm-ir-spec/index.html#standard-c-library-intrinics) + """ + key = cuda.fma + cases = [ + signature(types.float32, types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64, types.float64), + ] + + +@register +class Cuda_hfma(ConcreteTemplate): + key = cuda.fp16.hfma + cases = [ + signature(types.float16, types.float16, types.float16, types.float16) + ] + + +@register +class Cuda_cbrt(ConcreteTemplate): + + key = cuda.cbrt + cases = [ + signature(types.float32, types.float32), + signature(types.float64, types.float64), + ] + + +@register +class Cuda_brev(ConcreteTemplate): + key = cuda.brev + cases = [ + signature(types.uint32, types.uint32), + signature(types.uint64, types.uint64), + ] + + +@register +class Cuda_clz(ConcreteTemplate): + """ + Supported types from `llvm.ctlz` + [here](http://docs.nvidia.com/cuda/nvvm-ir-spec/index.html#bit-manipulations-intrinics) + """ + key = cuda.clz + cases = [ + signature(types.int8, types.int8), + signature(types.int16, types.int16), + signature(types.int32, types.int32), + signature(types.int64, types.int64), + signature(types.uint8, types.uint8), + signature(types.uint16, types.uint16), + signature(types.uint32, types.uint32), + signature(types.uint64, types.uint64), + ] + + +@register +class Cuda_ffs(ConcreteTemplate): + """ + Supported types from `llvm.cttz` + [here](http://docs.nvidia.com/cuda/nvvm-ir-spec/index.html#bit-manipulations-intrinics) + """ + key = cuda.ffs + cases = [ + signature(types.uint32, types.int8), + signature(types.uint32, types.int16), + signature(types.uint32, types.int32), + signature(types.uint32, types.int64), + signature(types.uint32, types.uint8), + signature(types.uint32, types.uint16), + signature(types.uint32, types.uint32), + signature(types.uint32, types.uint64), + ] + + +@register +class Cuda_selp(AbstractTemplate): + key = cuda.selp + + def generic(self, args, kws): + assert not kws + test, a, b = args + + # per docs + # http://docs.nvidia.com/cuda/parallel-thread-execution/index.html#comparison-and-selection-instructions-selp + supported_types = (types.float64, types.float32, + types.int16, types.uint16, + types.int32, types.uint32, + types.int64, types.uint64) + + if a != b or a not in supported_types: + return + + return signature(a, test, a, a) + + +def _genfp16_unary(l_key): + @register + class Cuda_fp16_unary(ConcreteTemplate): + key = l_key + cases = [signature(types.float16, types.float16)] + + return Cuda_fp16_unary + + +def _genfp16_unary_operator(l_key): + @register_global(l_key) + class Cuda_fp16_unary(AbstractTemplate): + key = l_key + + def generic(self, args, kws): + assert not kws + if len(args) == 1 and args[0] == types.float16: + return signature(types.float16, types.float16) + + return Cuda_fp16_unary + + +def _genfp16_binary(l_key): + @register + class Cuda_fp16_binary(ConcreteTemplate): + key = l_key + cases = [signature(types.float16, types.float16, types.float16)] + + return Cuda_fp16_binary + + +@register_global(float) +class Float(AbstractTemplate): + + def generic(self, args, kws): + assert not kws + + [arg] = args + + if arg == types.float16: + return signature(arg, arg) + + +def _genfp16_binary_comparison(l_key): + @register + class Cuda_fp16_cmp(ConcreteTemplate): + key = l_key + + cases = [ + signature(types.b1, types.float16, types.float16) + ] + return Cuda_fp16_cmp + +# If multiple ConcreteTemplates provide typing for a single function, then +# function resolution will pick the first compatible typing it finds even if it +# involves inserting a cast that would be considered undesirable (in this +# specific case, float16s could be cast to float32s for comparisons). +# +# To work around this, we instead use an AbstractTemplate that implements +# exactly the casting logic that we desire. The AbstractTemplate gets +# considered in preference to ConcreteTemplates during typing. +# +# This is tracked as Issue #7863 (https://github.com/numba/numba/issues/7863) - +# once this is resolved it should be possible to replace this AbstractTemplate +# with a ConcreteTemplate to simplify the logic. + + +def _fp16_binary_operator(l_key, retty): + @register_global(l_key) + class Cuda_fp16_operator(AbstractTemplate): + key = l_key + + def generic(self, args, kws): + assert not kws + + if len(args) == 2 and \ + (args[0] == types.float16 or args[1] == types.float16): + if (args[0] == types.float16): + convertible = self.context.can_convert(args[1], args[0]) + else: + convertible = self.context.can_convert(args[0], args[1]) + + # We allow three cases here: + # + # 1. fp16 to fp16 - Conversion.exact + # 2. fp16 to other types fp16 can be promoted to + # - Conversion.promote + # 3. fp16 to int8 (safe conversion) - + # - Conversion.safe + + if (convertible == Conversion.exact) or \ + (convertible == Conversion.promote) or \ + (convertible == Conversion.safe): + return signature(retty, types.float16, types.float16) + + return Cuda_fp16_operator + + +def _genfp16_comparison_operator(op): + return _fp16_binary_operator(op, types.b1) + + +def _genfp16_binary_operator(op): + return _fp16_binary_operator(op, types.float16) + + +Cuda_hadd = _genfp16_binary(cuda.fp16.hadd) +Cuda_add = _genfp16_binary_operator(operator.add) +Cuda_iadd = _genfp16_binary_operator(operator.iadd) +Cuda_hsub = _genfp16_binary(cuda.fp16.hsub) +Cuda_sub = _genfp16_binary_operator(operator.sub) +Cuda_isub = _genfp16_binary_operator(operator.isub) +Cuda_hmul = _genfp16_binary(cuda.fp16.hmul) +Cuda_mul = _genfp16_binary_operator(operator.mul) +Cuda_imul = _genfp16_binary_operator(operator.imul) +Cuda_hmax = _genfp16_binary(cuda.fp16.hmax) +Cuda_hmin = _genfp16_binary(cuda.fp16.hmin) +Cuda_hneg = _genfp16_unary(cuda.fp16.hneg) +Cuda_neg = _genfp16_unary_operator(operator.neg) +Cuda_habs = _genfp16_unary(cuda.fp16.habs) +Cuda_abs = _genfp16_unary_operator(abs) +Cuda_heq = _genfp16_binary_comparison(cuda.fp16.heq) +_genfp16_comparison_operator(operator.eq) +Cuda_hne = _genfp16_binary_comparison(cuda.fp16.hne) +_genfp16_comparison_operator(operator.ne) +Cuda_hge = _genfp16_binary_comparison(cuda.fp16.hge) +_genfp16_comparison_operator(operator.ge) +Cuda_hgt = _genfp16_binary_comparison(cuda.fp16.hgt) +_genfp16_comparison_operator(operator.gt) +Cuda_hle = _genfp16_binary_comparison(cuda.fp16.hle) +_genfp16_comparison_operator(operator.le) +Cuda_hlt = _genfp16_binary_comparison(cuda.fp16.hlt) +_genfp16_comparison_operator(operator.lt) +_genfp16_binary_operator(operator.truediv) +_genfp16_binary_operator(operator.itruediv) + + +def _resolve_wrapped_unary(fname): + decl = declare_device_function_template(f'__numba_wrapper_{fname}', + types.float16, + (types.float16,)) + return types.Function(decl) + + +def _resolve_wrapped_binary(fname): + decl = declare_device_function_template(f'__numba_wrapper_{fname}', + types.float16, + (types.float16, types.float16,)) + return types.Function(decl) + + +hsin_device = _resolve_wrapped_unary('hsin') +hcos_device = _resolve_wrapped_unary('hcos') +hlog_device = _resolve_wrapped_unary('hlog') +hlog10_device = _resolve_wrapped_unary('hlog10') +hlog2_device = _resolve_wrapped_unary('hlog2') +hexp_device = _resolve_wrapped_unary('hexp') +hexp10_device = _resolve_wrapped_unary('hexp10') +hexp2_device = _resolve_wrapped_unary('hexp2') +hsqrt_device = _resolve_wrapped_unary('hsqrt') +hrsqrt_device = _resolve_wrapped_unary('hrsqrt') +hfloor_device = _resolve_wrapped_unary('hfloor') +hceil_device = _resolve_wrapped_unary('hceil') +hrcp_device = _resolve_wrapped_unary('hrcp') +hrint_device = _resolve_wrapped_unary('hrint') +htrunc_device = _resolve_wrapped_unary('htrunc') +hdiv_device = _resolve_wrapped_binary('hdiv') + + +# generate atomic operations +def _gen(l_key, supported_types): + @register + class Cuda_atomic(AbstractTemplate): + key = l_key + + def generic(self, args, kws): + assert not kws + ary, idx, val = args + + if ary.dtype not in supported_types: + return + + if ary.ndim == 1: + return signature(ary.dtype, ary, types.intp, ary.dtype) + elif ary.ndim > 1: + return signature(ary.dtype, ary, idx, ary.dtype) + return Cuda_atomic + + +all_numba_types = (types.float64, types.float32, + types.int32, types.uint32, + types.int64, types.uint64) + +integer_numba_types = (types.int32, types.uint32, + types.int64, types.uint64) + +unsigned_int_numba_types = (types.uint32, types.uint64) + +Cuda_atomic_add = _gen(cuda.atomic.add, all_numba_types) +Cuda_atomic_sub = _gen(cuda.atomic.sub, all_numba_types) +Cuda_atomic_max = _gen(cuda.atomic.max, all_numba_types) +Cuda_atomic_min = _gen(cuda.atomic.min, all_numba_types) +Cuda_atomic_nanmax = _gen(cuda.atomic.nanmax, all_numba_types) +Cuda_atomic_nanmin = _gen(cuda.atomic.nanmin, all_numba_types) +Cuda_atomic_and = _gen(cuda.atomic.and_, integer_numba_types) +Cuda_atomic_or = _gen(cuda.atomic.or_, integer_numba_types) +Cuda_atomic_xor = _gen(cuda.atomic.xor, integer_numba_types) +Cuda_atomic_inc = _gen(cuda.atomic.inc, unsigned_int_numba_types) +Cuda_atomic_dec = _gen(cuda.atomic.dec, unsigned_int_numba_types) +Cuda_atomic_exch = _gen(cuda.atomic.exch, integer_numba_types) + + +@register +class Cuda_atomic_compare_and_swap(AbstractTemplate): + key = cuda.atomic.compare_and_swap + + def generic(self, args, kws): + assert not kws + ary, old, val = args + dty = ary.dtype + + if dty in integer_numba_types and ary.ndim == 1: + return signature(dty, ary, dty, dty) + + +@register +class Cuda_atomic_cas(AbstractTemplate): + key = cuda.atomic.cas + + def generic(self, args, kws): + assert not kws + ary, idx, old, val = args + dty = ary.dtype + + if dty not in integer_numba_types: + return + + if ary.ndim == 1: + return signature(dty, ary, types.intp, dty, dty) + elif ary.ndim > 1: + return signature(dty, ary, idx, dty, dty) + + +@register +class Cuda_nanosleep(ConcreteTemplate): + key = cuda.nanosleep + + cases = [signature(types.void, types.uint32)] + + +@register_attr +class Dim3_attrs(AttributeTemplate): + key = dim3 + + def resolve_x(self, mod): + return types.int32 + + def resolve_y(self, mod): + return types.int32 + + def resolve_z(self, mod): + return types.int32 + + +@register_attr +class CudaSharedModuleTemplate(AttributeTemplate): + key = types.Module(cuda.shared) + + def resolve_array(self, mod): + return types.Function(Cuda_shared_array) + + +@register_attr +class CudaConstModuleTemplate(AttributeTemplate): + key = types.Module(cuda.const) + + def resolve_array_like(self, mod): + return types.Function(Cuda_const_array_like) + + +@register_attr +class CudaLocalModuleTemplate(AttributeTemplate): + key = types.Module(cuda.local) + + def resolve_array(self, mod): + return types.Function(Cuda_local_array) + + +@register_attr +class CudaAtomicTemplate(AttributeTemplate): + key = types.Module(cuda.atomic) + + def resolve_add(self, mod): + return types.Function(Cuda_atomic_add) + + def resolve_sub(self, mod): + return types.Function(Cuda_atomic_sub) + + def resolve_and_(self, mod): + return types.Function(Cuda_atomic_and) + + def resolve_or_(self, mod): + return types.Function(Cuda_atomic_or) + + def resolve_xor(self, mod): + return types.Function(Cuda_atomic_xor) + + def resolve_inc(self, mod): + return types.Function(Cuda_atomic_inc) + + def resolve_dec(self, mod): + return types.Function(Cuda_atomic_dec) + + def resolve_exch(self, mod): + return types.Function(Cuda_atomic_exch) + + def resolve_max(self, mod): + return types.Function(Cuda_atomic_max) + + def resolve_min(self, mod): + return types.Function(Cuda_atomic_min) + + def resolve_nanmin(self, mod): + return types.Function(Cuda_atomic_nanmin) + + def resolve_nanmax(self, mod): + return types.Function(Cuda_atomic_nanmax) + + def resolve_compare_and_swap(self, mod): + return types.Function(Cuda_atomic_compare_and_swap) + + def resolve_cas(self, mod): + return types.Function(Cuda_atomic_cas) + + +@register_attr +class CudaFp16Template(AttributeTemplate): + key = types.Module(cuda.fp16) + + def resolve_hadd(self, mod): + return types.Function(Cuda_hadd) + + def resolve_hsub(self, mod): + return types.Function(Cuda_hsub) + + def resolve_hmul(self, mod): + return types.Function(Cuda_hmul) + + def resolve_hdiv(self, mod): + return hdiv_device + + def resolve_hneg(self, mod): + return types.Function(Cuda_hneg) + + def resolve_habs(self, mod): + return types.Function(Cuda_habs) + + def resolve_hfma(self, mod): + return types.Function(Cuda_hfma) + + def resolve_hsin(self, mod): + return hsin_device + + def resolve_hcos(self, mod): + return hcos_device + + def resolve_hlog(self, mod): + return hlog_device + + def resolve_hlog10(self, mod): + return hlog10_device + + def resolve_hlog2(self, mod): + return hlog2_device + + def resolve_hexp(self, mod): + return hexp_device + + def resolve_hexp10(self, mod): + return hexp10_device + + def resolve_hexp2(self, mod): + return hexp2_device + + def resolve_hfloor(self, mod): + return hfloor_device + + def resolve_hceil(self, mod): + return hceil_device + + def resolve_hsqrt(self, mod): + return hsqrt_device + + def resolve_hrsqrt(self, mod): + return hrsqrt_device + + def resolve_hrcp(self, mod): + return hrcp_device + + def resolve_hrint(self, mod): + return hrint_device + + def resolve_htrunc(self, mod): + return htrunc_device + + def resolve_heq(self, mod): + return types.Function(Cuda_heq) + + def resolve_hne(self, mod): + return types.Function(Cuda_hne) + + def resolve_hge(self, mod): + return types.Function(Cuda_hge) + + def resolve_hgt(self, mod): + return types.Function(Cuda_hgt) + + def resolve_hle(self, mod): + return types.Function(Cuda_hle) + + def resolve_hlt(self, mod): + return types.Function(Cuda_hlt) + + def resolve_hmax(self, mod): + return types.Function(Cuda_hmax) + + def resolve_hmin(self, mod): + return types.Function(Cuda_hmin) + + +@register_attr +class CudaModuleTemplate(AttributeTemplate): + key = types.Module(cuda) + + def resolve_cg(self, mod): + return types.Module(cuda.cg) + + def resolve_threadIdx(self, mod): + return dim3 + + def resolve_blockIdx(self, mod): + return dim3 + + def resolve_blockDim(self, mod): + return dim3 + + def resolve_gridDim(self, mod): + return dim3 + + def resolve_laneid(self, mod): + return types.int32 + + def resolve_shared(self, mod): + return types.Module(cuda.shared) + + def resolve_popc(self, mod): + return types.Function(Cuda_popc) + + def resolve_brev(self, mod): + return types.Function(Cuda_brev) + + def resolve_clz(self, mod): + return types.Function(Cuda_clz) + + def resolve_ffs(self, mod): + return types.Function(Cuda_ffs) + + def resolve_fma(self, mod): + return types.Function(Cuda_fma) + + def resolve_cbrt(self, mod): + return types.Function(Cuda_cbrt) + + def resolve_threadfence(self, mod): + return types.Function(Cuda_threadfence_device) + + def resolve_threadfence_block(self, mod): + return types.Function(Cuda_threadfence_block) + + def resolve_threadfence_system(self, mod): + return types.Function(Cuda_threadfence_system) + + def resolve_syncwarp(self, mod): + return types.Function(Cuda_syncwarp) + + def resolve_shfl_sync_intrinsic(self, mod): + return types.Function(Cuda_shfl_sync_intrinsic) + + def resolve_vote_sync_intrinsic(self, mod): + return types.Function(Cuda_vote_sync_intrinsic) + + def resolve_match_any_sync(self, mod): + return types.Function(Cuda_match_any_sync) + + def resolve_match_all_sync(self, mod): + return types.Function(Cuda_match_all_sync) + + def resolve_activemask(self, mod): + return types.Function(Cuda_activemask) + + def resolve_lanemask_lt(self, mod): + return types.Function(Cuda_lanemask_lt) + + def resolve_selp(self, mod): + return types.Function(Cuda_selp) + + def resolve_nanosleep(self, mod): + return types.Function(Cuda_nanosleep) + + def resolve_atomic(self, mod): + return types.Module(cuda.atomic) + + def resolve_fp16(self, mod): + return types.Module(cuda.fp16) + + def resolve_const(self, mod): + return types.Module(cuda.const) + + def resolve_local(self, mod): + return types.Module(cuda.local) + + +register_global(cuda, types.Module(cuda)) + + +# NumPy + +for func in trigonometric_functions: + register_numpy_ufunc(func, register_global) + +for func in comparison_functions: + register_numpy_ufunc(func, register_global) + +for func in bit_twiddling_functions: + register_numpy_ufunc(func, register_global) + +for func in math_operations: + if func in ('log', 'log2', 'log10'): + register_numpy_ufunc(func, register_global) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudaimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudaimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..5de024d1c9a6da9b4cf73f76d2ad7228045bd42b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudaimpl.py @@ -0,0 +1,1055 @@ +from functools import reduce +import operator +import math + +from llvmlite import ir +import llvmlite.binding as ll + +from numba.core.imputils import Registry, lower_cast +from numba.core.typing.npydecl import parse_dtype +from numba.core.datamodel import models +from numba.core import types, cgutils +from numba.np import ufunc_db +from numba.np.npyimpl import register_ufuncs +from .cudadrv import nvvm +from numba import cuda +from numba.cuda import nvvmutils, stubs, errors +from numba.cuda.types import dim3, CUDADispatcher + +registry = Registry() +lower = registry.lower +lower_attr = registry.lower_getattr +lower_constant = registry.lower_constant + + +def initialize_dim3(builder, prefix): + x = nvvmutils.call_sreg(builder, "%s.x" % prefix) + y = nvvmutils.call_sreg(builder, "%s.y" % prefix) + z = nvvmutils.call_sreg(builder, "%s.z" % prefix) + return cgutils.pack_struct(builder, (x, y, z)) + + +@lower_attr(types.Module(cuda), 'threadIdx') +def cuda_threadIdx(context, builder, sig, args): + return initialize_dim3(builder, 'tid') + + +@lower_attr(types.Module(cuda), 'blockDim') +def cuda_blockDim(context, builder, sig, args): + return initialize_dim3(builder, 'ntid') + + +@lower_attr(types.Module(cuda), 'blockIdx') +def cuda_blockIdx(context, builder, sig, args): + return initialize_dim3(builder, 'ctaid') + + +@lower_attr(types.Module(cuda), 'gridDim') +def cuda_gridDim(context, builder, sig, args): + return initialize_dim3(builder, 'nctaid') + + +@lower_attr(types.Module(cuda), 'laneid') +def cuda_laneid(context, builder, sig, args): + return nvvmutils.call_sreg(builder, 'laneid') + + +@lower_attr(dim3, 'x') +def dim3_x(context, builder, sig, args): + return builder.extract_value(args, 0) + + +@lower_attr(dim3, 'y') +def dim3_y(context, builder, sig, args): + return builder.extract_value(args, 1) + + +@lower_attr(dim3, 'z') +def dim3_z(context, builder, sig, args): + return builder.extract_value(args, 2) + + +# ----------------------------------------------------------------------------- + +@lower(cuda.const.array_like, types.Array) +def cuda_const_array_like(context, builder, sig, args): + # This is a no-op because CUDATargetContext.make_constant_array already + # created the constant array. + return args[0] + + +_unique_smem_id = 0 + + +def _get_unique_smem_id(name): + """Due to bug with NVVM invalid internalizing of shared memory in the + PTX output. We can't mark shared memory to be internal. We have to + ensure unique name is generated for shared memory symbol. + """ + global _unique_smem_id + _unique_smem_id += 1 + return "{0}_{1}".format(name, _unique_smem_id) + + +@lower(cuda.shared.array, types.IntegerLiteral, types.Any) +def cuda_shared_array_integer(context, builder, sig, args): + length = sig.args[0].literal_value + dtype = parse_dtype(sig.args[1]) + return _generic_array(context, builder, shape=(length,), dtype=dtype, + symbol_name=_get_unique_smem_id('_cudapy_smem'), + addrspace=nvvm.ADDRSPACE_SHARED, + can_dynsized=True) + + +@lower(cuda.shared.array, types.Tuple, types.Any) +@lower(cuda.shared.array, types.UniTuple, types.Any) +def cuda_shared_array_tuple(context, builder, sig, args): + shape = [ s.literal_value for s in sig.args[0] ] + dtype = parse_dtype(sig.args[1]) + return _generic_array(context, builder, shape=shape, dtype=dtype, + symbol_name=_get_unique_smem_id('_cudapy_smem'), + addrspace=nvvm.ADDRSPACE_SHARED, + can_dynsized=True) + + +@lower(cuda.local.array, types.IntegerLiteral, types.Any) +def cuda_local_array_integer(context, builder, sig, args): + length = sig.args[0].literal_value + dtype = parse_dtype(sig.args[1]) + return _generic_array(context, builder, shape=(length,), dtype=dtype, + symbol_name='_cudapy_lmem', + addrspace=nvvm.ADDRSPACE_LOCAL, + can_dynsized=False) + + +@lower(cuda.local.array, types.Tuple, types.Any) +@lower(cuda.local.array, types.UniTuple, types.Any) +def ptx_lmem_alloc_array(context, builder, sig, args): + shape = [ s.literal_value for s in sig.args[0] ] + dtype = parse_dtype(sig.args[1]) + return _generic_array(context, builder, shape=shape, dtype=dtype, + symbol_name='_cudapy_lmem', + addrspace=nvvm.ADDRSPACE_LOCAL, + can_dynsized=False) + + +@lower(stubs.threadfence_block) +def ptx_threadfence_block(context, builder, sig, args): + assert not args + fname = 'llvm.nvvm.membar.cta' + lmod = builder.module + fnty = ir.FunctionType(ir.VoidType(), ()) + sync = cgutils.get_or_insert_function(lmod, fnty, fname) + builder.call(sync, ()) + return context.get_dummy_value() + + +@lower(stubs.threadfence_system) +def ptx_threadfence_system(context, builder, sig, args): + assert not args + fname = 'llvm.nvvm.membar.sys' + lmod = builder.module + fnty = ir.FunctionType(ir.VoidType(), ()) + sync = cgutils.get_or_insert_function(lmod, fnty, fname) + builder.call(sync, ()) + return context.get_dummy_value() + + +@lower(stubs.threadfence) +def ptx_threadfence_device(context, builder, sig, args): + assert not args + fname = 'llvm.nvvm.membar.gl' + lmod = builder.module + fnty = ir.FunctionType(ir.VoidType(), ()) + sync = cgutils.get_or_insert_function(lmod, fnty, fname) + builder.call(sync, ()) + return context.get_dummy_value() + + +@lower(stubs.syncwarp) +def ptx_syncwarp(context, builder, sig, args): + mask = context.get_constant(types.int32, 0xFFFFFFFF) + mask_sig = types.none(types.int32) + return ptx_syncwarp_mask(context, builder, mask_sig, [mask]) + + +@lower(stubs.syncwarp, types.i4) +def ptx_syncwarp_mask(context, builder, sig, args): + fname = 'llvm.nvvm.bar.warp.sync' + lmod = builder.module + fnty = ir.FunctionType(ir.VoidType(), (ir.IntType(32),)) + sync = cgutils.get_or_insert_function(lmod, fnty, fname) + builder.call(sync, args) + return context.get_dummy_value() + + +@lower(stubs.shfl_sync_intrinsic, types.i4, types.i4, types.i4, types.i4, + types.i4) +@lower(stubs.shfl_sync_intrinsic, types.i4, types.i4, types.i8, types.i4, + types.i4) +@lower(stubs.shfl_sync_intrinsic, types.i4, types.i4, types.f4, types.i4, + types.i4) +@lower(stubs.shfl_sync_intrinsic, types.i4, types.i4, types.f8, types.i4, + types.i4) +def ptx_shfl_sync_i32(context, builder, sig, args): + """ + The NVVM intrinsic for shfl only supports i32, but the cuda intrinsic + function supports both 32 and 64 bit ints and floats, so for feature parity, + i64, f32, and f64 are implemented. Floats by way of bitcasting the float to + an int, then shuffling, then bitcasting back. And 64-bit values by packing + them into 2 32bit values, shuffling thoose, and then packing back together. + """ + mask, mode, value, index, clamp = args + value_type = sig.args[2] + if value_type in types.real_domain: + value = builder.bitcast(value, ir.IntType(value_type.bitwidth)) + fname = 'llvm.nvvm.shfl.sync.i32' + lmod = builder.module + fnty = ir.FunctionType( + ir.LiteralStructType((ir.IntType(32), ir.IntType(1))), + (ir.IntType(32), ir.IntType(32), ir.IntType(32), + ir.IntType(32), ir.IntType(32)) + ) + func = cgutils.get_or_insert_function(lmod, fnty, fname) + if value_type.bitwidth == 32: + ret = builder.call(func, (mask, mode, value, index, clamp)) + if value_type == types.float32: + rv = builder.extract_value(ret, 0) + pred = builder.extract_value(ret, 1) + fv = builder.bitcast(rv, ir.FloatType()) + ret = cgutils.make_anonymous_struct(builder, (fv, pred)) + else: + value1 = builder.trunc(value, ir.IntType(32)) + value_lshr = builder.lshr(value, context.get_constant(types.i8, 32)) + value2 = builder.trunc(value_lshr, ir.IntType(32)) + ret1 = builder.call(func, (mask, mode, value1, index, clamp)) + ret2 = builder.call(func, (mask, mode, value2, index, clamp)) + rv1 = builder.extract_value(ret1, 0) + rv2 = builder.extract_value(ret2, 0) + pred = builder.extract_value(ret1, 1) + rv1_64 = builder.zext(rv1, ir.IntType(64)) + rv2_64 = builder.zext(rv2, ir.IntType(64)) + rv_shl = builder.shl(rv2_64, context.get_constant(types.i8, 32)) + rv = builder.or_(rv_shl, rv1_64) + if value_type == types.float64: + rv = builder.bitcast(rv, ir.DoubleType()) + ret = cgutils.make_anonymous_struct(builder, (rv, pred)) + return ret + + +@lower(stubs.vote_sync_intrinsic, types.i4, types.i4, types.boolean) +def ptx_vote_sync(context, builder, sig, args): + fname = 'llvm.nvvm.vote.sync' + lmod = builder.module + fnty = ir.FunctionType(ir.LiteralStructType((ir.IntType(32), + ir.IntType(1))), + (ir.IntType(32), ir.IntType(32), ir.IntType(1))) + func = cgutils.get_or_insert_function(lmod, fnty, fname) + return builder.call(func, args) + + +@lower(stubs.match_any_sync, types.i4, types.i4) +@lower(stubs.match_any_sync, types.i4, types.i8) +@lower(stubs.match_any_sync, types.i4, types.f4) +@lower(stubs.match_any_sync, types.i4, types.f8) +def ptx_match_any_sync(context, builder, sig, args): + mask, value = args + width = sig.args[1].bitwidth + if sig.args[1] in types.real_domain: + value = builder.bitcast(value, ir.IntType(width)) + fname = 'llvm.nvvm.match.any.sync.i{}'.format(width) + lmod = builder.module + fnty = ir.FunctionType(ir.IntType(32), (ir.IntType(32), ir.IntType(width))) + func = cgutils.get_or_insert_function(lmod, fnty, fname) + return builder.call(func, (mask, value)) + + +@lower(stubs.match_all_sync, types.i4, types.i4) +@lower(stubs.match_all_sync, types.i4, types.i8) +@lower(stubs.match_all_sync, types.i4, types.f4) +@lower(stubs.match_all_sync, types.i4, types.f8) +def ptx_match_all_sync(context, builder, sig, args): + mask, value = args + width = sig.args[1].bitwidth + if sig.args[1] in types.real_domain: + value = builder.bitcast(value, ir.IntType(width)) + fname = 'llvm.nvvm.match.all.sync.i{}'.format(width) + lmod = builder.module + fnty = ir.FunctionType(ir.LiteralStructType((ir.IntType(32), + ir.IntType(1))), + (ir.IntType(32), ir.IntType(width))) + func = cgutils.get_or_insert_function(lmod, fnty, fname) + return builder.call(func, (mask, value)) + + +@lower(stubs.activemask) +def ptx_activemask(context, builder, sig, args): + activemask = ir.InlineAsm(ir.FunctionType(ir.IntType(32), []), + "activemask.b32 $0;", '=r', side_effect=True) + return builder.call(activemask, []) + + +@lower(stubs.lanemask_lt) +def ptx_lanemask_lt(context, builder, sig, args): + activemask = ir.InlineAsm(ir.FunctionType(ir.IntType(32), []), + "mov.u32 $0, %lanemask_lt;", '=r', + side_effect=True) + return builder.call(activemask, []) + + +@lower(stubs.popc, types.Any) +def ptx_popc(context, builder, sig, args): + return builder.ctpop(args[0]) + + +@lower(stubs.fma, types.Any, types.Any, types.Any) +def ptx_fma(context, builder, sig, args): + return builder.fma(*args) + + +def float16_float_ty_constraint(bitwidth): + typemap = {32: ('f32', 'f'), 64: ('f64', 'd')} + + try: + return typemap[bitwidth] + except KeyError: + msg = f"Conversion between float16 and float{bitwidth} unsupported" + raise errors.CudaLoweringError(msg) + + +@lower_cast(types.float16, types.Float) +def float16_to_float_cast(context, builder, fromty, toty, val): + if fromty.bitwidth == toty.bitwidth: + return val + + ty, constraint = float16_float_ty_constraint(toty.bitwidth) + + fnty = ir.FunctionType(context.get_value_type(toty), [ir.IntType(16)]) + asm = ir.InlineAsm(fnty, f"cvt.{ty}.f16 $0, $1;", f"={constraint},h") + return builder.call(asm, [val]) + + +@lower_cast(types.Float, types.float16) +def float_to_float16_cast(context, builder, fromty, toty, val): + if fromty.bitwidth == toty.bitwidth: + return val + + ty, constraint = float16_float_ty_constraint(fromty.bitwidth) + + fnty = ir.FunctionType(ir.IntType(16), [context.get_value_type(fromty)]) + asm = ir.InlineAsm(fnty, f"cvt.rn.f16.{ty} $0, $1;", f"=h,{constraint}") + return builder.call(asm, [val]) + + +def float16_int_constraint(bitwidth): + typemap = { 8: 'c', 16: 'h', 32: 'r', 64: 'l' } + + try: + return typemap[bitwidth] + except KeyError: + msg = f"Conversion between float16 and int{bitwidth} unsupported" + raise errors.CudaLoweringError(msg) + + +@lower_cast(types.float16, types.Integer) +def float16_to_integer_cast(context, builder, fromty, toty, val): + bitwidth = toty.bitwidth + constraint = float16_int_constraint(bitwidth) + signedness = 's' if toty.signed else 'u' + + fnty = ir.FunctionType(context.get_value_type(toty), [ir.IntType(16)]) + asm = ir.InlineAsm(fnty, + f"cvt.rni.{signedness}{bitwidth}.f16 $0, $1;", + f"={constraint},h") + return builder.call(asm, [val]) + + +@lower_cast(types.Integer, types.float16) +@lower_cast(types.IntegerLiteral, types.float16) +def integer_to_float16_cast(context, builder, fromty, toty, val): + bitwidth = fromty.bitwidth + constraint = float16_int_constraint(bitwidth) + signedness = 's' if fromty.signed else 'u' + + fnty = ir.FunctionType(ir.IntType(16), + [context.get_value_type(fromty)]) + asm = ir.InlineAsm(fnty, + f"cvt.rn.f16.{signedness}{bitwidth} $0, $1;", + f"=h,{constraint}") + return builder.call(asm, [val]) + + +def lower_fp16_binary(fn, op): + @lower(fn, types.float16, types.float16) + def ptx_fp16_binary(context, builder, sig, args): + fnty = ir.FunctionType(ir.IntType(16), + [ir.IntType(16), ir.IntType(16)]) + asm = ir.InlineAsm(fnty, f'{op}.f16 $0,$1,$2;', '=h,h,h') + return builder.call(asm, args) + + +lower_fp16_binary(stubs.fp16.hadd, 'add') +lower_fp16_binary(operator.add, 'add') +lower_fp16_binary(operator.iadd, 'add') +lower_fp16_binary(stubs.fp16.hsub, 'sub') +lower_fp16_binary(operator.sub, 'sub') +lower_fp16_binary(operator.isub, 'sub') +lower_fp16_binary(stubs.fp16.hmul, 'mul') +lower_fp16_binary(operator.mul, 'mul') +lower_fp16_binary(operator.imul, 'mul') + + +@lower(stubs.fp16.hneg, types.float16) +def ptx_fp16_hneg(context, builder, sig, args): + fnty = ir.FunctionType(ir.IntType(16), [ir.IntType(16)]) + asm = ir.InlineAsm(fnty, 'neg.f16 $0, $1;', '=h,h') + return builder.call(asm, args) + + +@lower(operator.neg, types.float16) +def operator_hneg(context, builder, sig, args): + return ptx_fp16_hneg(context, builder, sig, args) + + +@lower(stubs.fp16.habs, types.float16) +def ptx_fp16_habs(context, builder, sig, args): + fnty = ir.FunctionType(ir.IntType(16), [ir.IntType(16)]) + asm = ir.InlineAsm(fnty, 'abs.f16 $0, $1;', '=h,h') + return builder.call(asm, args) + + +@lower(abs, types.float16) +def operator_habs(context, builder, sig, args): + return ptx_fp16_habs(context, builder, sig, args) + + +@lower(stubs.fp16.hfma, types.float16, types.float16, types.float16) +def ptx_hfma(context, builder, sig, args): + argtys = [ir.IntType(16), ir.IntType(16), ir.IntType(16)] + fnty = ir.FunctionType(ir.IntType(16), argtys) + asm = ir.InlineAsm(fnty, "fma.rn.f16 $0,$1,$2,$3;", "=h,h,h,h") + return builder.call(asm, args) + + +@lower(operator.truediv, types.float16, types.float16) +@lower(operator.itruediv, types.float16, types.float16) +def fp16_div_impl(context, builder, sig, args): + def fp16_div(x, y): + return cuda.fp16.hdiv(x, y) + + return context.compile_internal(builder, fp16_div, sig, args) + + +_fp16_cmp = """{{ + .reg .pred __$$f16_cmp_tmp; + setp.{op}.f16 __$$f16_cmp_tmp, $1, $2; + selp.u16 $0, 1, 0, __$$f16_cmp_tmp; + }}""" + + +def _gen_fp16_cmp(op): + def ptx_fp16_comparison(context, builder, sig, args): + fnty = ir.FunctionType(ir.IntType(16), [ir.IntType(16), ir.IntType(16)]) + asm = ir.InlineAsm(fnty, _fp16_cmp.format(op=op), '=h,h,h') + result = builder.call(asm, args) + + zero = context.get_constant(types.int16, 0) + int_result = builder.bitcast(result, ir.IntType(16)) + return builder.icmp_unsigned("!=", int_result, zero) + return ptx_fp16_comparison + + +lower(stubs.fp16.heq, types.float16, types.float16)(_gen_fp16_cmp('eq')) +lower(operator.eq, types.float16, types.float16)(_gen_fp16_cmp('eq')) +lower(stubs.fp16.hne, types.float16, types.float16)(_gen_fp16_cmp('ne')) +lower(operator.ne, types.float16, types.float16)(_gen_fp16_cmp('ne')) +lower(stubs.fp16.hge, types.float16, types.float16)(_gen_fp16_cmp('ge')) +lower(operator.ge, types.float16, types.float16)(_gen_fp16_cmp('ge')) +lower(stubs.fp16.hgt, types.float16, types.float16)(_gen_fp16_cmp('gt')) +lower(operator.gt, types.float16, types.float16)(_gen_fp16_cmp('gt')) +lower(stubs.fp16.hle, types.float16, types.float16)(_gen_fp16_cmp('le')) +lower(operator.le, types.float16, types.float16)(_gen_fp16_cmp('le')) +lower(stubs.fp16.hlt, types.float16, types.float16)(_gen_fp16_cmp('lt')) +lower(operator.lt, types.float16, types.float16)(_gen_fp16_cmp('lt')) + + +def lower_fp16_minmax(fn, fname, op): + @lower(fn, types.float16, types.float16) + def ptx_fp16_minmax(context, builder, sig, args): + choice = _gen_fp16_cmp(op)(context, builder, sig, args) + return builder.select(choice, args[0], args[1]) + + +lower_fp16_minmax(stubs.fp16.hmax, 'max', 'gt') +lower_fp16_minmax(stubs.fp16.hmin, 'min', 'lt') + +# See: +# https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cbrt.html#__nv_cbrt +# https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cbrtf.html#__nv_cbrtf + + +cbrt_funcs = { + types.float32: '__nv_cbrtf', + types.float64: '__nv_cbrt', +} + + +@lower(stubs.cbrt, types.float32) +@lower(stubs.cbrt, types.float64) +def ptx_cbrt(context, builder, sig, args): + ty = sig.return_type + fname = cbrt_funcs[ty] + fty = context.get_value_type(ty) + lmod = builder.module + fnty = ir.FunctionType(fty, [fty]) + fn = cgutils.get_or_insert_function(lmod, fnty, fname) + return builder.call(fn, args) + + +@lower(stubs.brev, types.u4) +def ptx_brev_u4(context, builder, sig, args): + # FIXME the llvm.bitreverse.i32 intrinsic isn't supported by nvcc + # return builder.bitreverse(args[0]) + + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType(ir.IntType(32), (ir.IntType(32),)), + '__nv_brev') + return builder.call(fn, args) + + +@lower(stubs.brev, types.u8) +def ptx_brev_u8(context, builder, sig, args): + # FIXME the llvm.bitreverse.i64 intrinsic isn't supported by nvcc + # return builder.bitreverse(args[0]) + + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType(ir.IntType(64), (ir.IntType(64),)), + '__nv_brevll') + return builder.call(fn, args) + + +@lower(stubs.clz, types.Any) +def ptx_clz(context, builder, sig, args): + return builder.ctlz( + args[0], + context.get_constant(types.boolean, 0)) + + +@lower(stubs.ffs, types.i4) +@lower(stubs.ffs, types.u4) +def ptx_ffs_32(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType(ir.IntType(32), (ir.IntType(32),)), + '__nv_ffs') + return builder.call(fn, args) + + +@lower(stubs.ffs, types.i8) +@lower(stubs.ffs, types.u8) +def ptx_ffs_64(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType(ir.IntType(32), (ir.IntType(64),)), + '__nv_ffsll') + return builder.call(fn, args) + + +@lower(stubs.selp, types.Any, types.Any, types.Any) +def ptx_selp(context, builder, sig, args): + test, a, b = args + return builder.select(test, a, b) + + +@lower(max, types.f4, types.f4) +def ptx_max_f4(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType( + ir.FloatType(), + (ir.FloatType(), ir.FloatType())), + '__nv_fmaxf') + return builder.call(fn, args) + + +@lower(max, types.f8, types.f4) +@lower(max, types.f4, types.f8) +@lower(max, types.f8, types.f8) +def ptx_max_f8(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType( + ir.DoubleType(), + (ir.DoubleType(), ir.DoubleType())), + '__nv_fmax') + + return builder.call(fn, [ + context.cast(builder, args[0], sig.args[0], types.double), + context.cast(builder, args[1], sig.args[1], types.double), + ]) + + +@lower(min, types.f4, types.f4) +def ptx_min_f4(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType( + ir.FloatType(), + (ir.FloatType(), ir.FloatType())), + '__nv_fminf') + return builder.call(fn, args) + + +@lower(min, types.f8, types.f4) +@lower(min, types.f4, types.f8) +@lower(min, types.f8, types.f8) +def ptx_min_f8(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType( + ir.DoubleType(), + (ir.DoubleType(), ir.DoubleType())), + '__nv_fmin') + + return builder.call(fn, [ + context.cast(builder, args[0], sig.args[0], types.double), + context.cast(builder, args[1], sig.args[1], types.double), + ]) + + +@lower(round, types.f4) +@lower(round, types.f8) +def ptx_round(context, builder, sig, args): + fn = cgutils.get_or_insert_function( + builder.module, + ir.FunctionType( + ir.IntType(64), + (ir.DoubleType(),)), + '__nv_llrint') + return builder.call(fn, [ + context.cast(builder, args[0], sig.args[0], types.double), + ]) + + +# This rounding implementation follows the algorithm used in the "fallback +# version" of double_round in CPython. +# https://github.com/python/cpython/blob/a755410e054e1e2390de5830befc08fe80706c66/Objects/floatobject.c#L964-L1007 + +@lower(round, types.f4, types.Integer) +@lower(round, types.f8, types.Integer) +def round_to_impl(context, builder, sig, args): + def round_ndigits(x, ndigits): + if math.isinf(x) or math.isnan(x): + return x + + if ndigits >= 0: + if ndigits > 22: + # pow1 and pow2 are each safe from overflow, but + # pow1*pow2 ~= pow(10.0, ndigits) might overflow. + pow1 = 10.0 ** (ndigits - 22) + pow2 = 1e22 + else: + pow1 = 10.0 ** ndigits + pow2 = 1.0 + y = (x * pow1) * pow2 + if math.isinf(y): + return x + + else: + pow1 = 10.0 ** (-ndigits) + y = x / pow1 + + z = round(y) + if (math.fabs(y - z) == 0.5): + # halfway between two integers; use round-half-even + z = 2.0 * round(y / 2.0) + + if ndigits >= 0: + z = (z / pow2) / pow1 + else: + z *= pow1 + + return z + + return context.compile_internal(builder, round_ndigits, sig, args, ) + + +def gen_deg_rad(const): + def impl(context, builder, sig, args): + argty, = sig.args + factor = context.get_constant(argty, const) + return builder.fmul(factor, args[0]) + return impl + + +_deg2rad = math.pi / 180. +_rad2deg = 180. / math.pi +lower(math.radians, types.f4)(gen_deg_rad(_deg2rad)) +lower(math.radians, types.f8)(gen_deg_rad(_deg2rad)) +lower(math.degrees, types.f4)(gen_deg_rad(_rad2deg)) +lower(math.degrees, types.f8)(gen_deg_rad(_rad2deg)) + + +def _normalize_indices(context, builder, indty, inds, aryty, valty): + """ + Convert integer indices into tuple of intp + """ + if indty in types.integer_domain: + indty = types.UniTuple(dtype=indty, count=1) + indices = [inds] + else: + indices = cgutils.unpack_tuple(builder, inds, count=len(indty)) + indices = [context.cast(builder, i, t, types.intp) + for t, i in zip(indty, indices)] + + dtype = aryty.dtype + if dtype != valty: + raise TypeError("expect %s but got %s" % (dtype, valty)) + + if aryty.ndim != len(indty): + raise TypeError("indexing %d-D array with %d-D index" % + (aryty.ndim, len(indty))) + + return indty, indices + + +def _atomic_dispatcher(dispatch_fn): + def imp(context, builder, sig, args): + # The common argument handling code + aryty, indty, valty = sig.args + ary, inds, val = args + dtype = aryty.dtype + + indty, indices = _normalize_indices(context, builder, indty, inds, + aryty, valty) + + lary = context.make_array(aryty)(context, builder, ary) + ptr = cgutils.get_item_pointer(context, builder, aryty, lary, indices, + wraparound=True) + # dispatcher to implementation base on dtype + return dispatch_fn(context, builder, dtype, ptr, val) + return imp + + +@lower(stubs.atomic.add, types.Array, types.intp, types.Any) +@lower(stubs.atomic.add, types.Array, types.UniTuple, types.Any) +@lower(stubs.atomic.add, types.Array, types.Tuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_add_tuple(context, builder, dtype, ptr, val): + if dtype == types.float32: + lmod = builder.module + return builder.call(nvvmutils.declare_atomic_add_float32(lmod), + (ptr, val)) + elif dtype == types.float64: + lmod = builder.module + return builder.call(nvvmutils.declare_atomic_add_float64(lmod), + (ptr, val)) + else: + return builder.atomic_rmw('add', ptr, val, 'monotonic') + + +@lower(stubs.atomic.sub, types.Array, types.intp, types.Any) +@lower(stubs.atomic.sub, types.Array, types.UniTuple, types.Any) +@lower(stubs.atomic.sub, types.Array, types.Tuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_sub(context, builder, dtype, ptr, val): + if dtype == types.float32: + lmod = builder.module + return builder.call(nvvmutils.declare_atomic_sub_float32(lmod), + (ptr, val)) + elif dtype == types.float64: + lmod = builder.module + return builder.call(nvvmutils.declare_atomic_sub_float64(lmod), + (ptr, val)) + else: + return builder.atomic_rmw('sub', ptr, val, 'monotonic') + + +@lower(stubs.atomic.inc, types.Array, types.intp, types.Any) +@lower(stubs.atomic.inc, types.Array, types.UniTuple, types.Any) +@lower(stubs.atomic.inc, types.Array, types.Tuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_inc(context, builder, dtype, ptr, val): + if dtype in cuda.cudadecl.unsigned_int_numba_types: + bw = dtype.bitwidth + lmod = builder.module + fn = getattr(nvvmutils, f'declare_atomic_inc_int{bw}') + return builder.call(fn(lmod), (ptr, val)) + else: + raise TypeError(f'Unimplemented atomic inc with {dtype} array') + + +@lower(stubs.atomic.dec, types.Array, types.intp, types.Any) +@lower(stubs.atomic.dec, types.Array, types.UniTuple, types.Any) +@lower(stubs.atomic.dec, types.Array, types.Tuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_dec(context, builder, dtype, ptr, val): + if dtype in cuda.cudadecl.unsigned_int_numba_types: + bw = dtype.bitwidth + lmod = builder.module + fn = getattr(nvvmutils, f'declare_atomic_dec_int{bw}') + return builder.call(fn(lmod), (ptr, val)) + else: + raise TypeError(f'Unimplemented atomic dec with {dtype} array') + + +def ptx_atomic_bitwise(stub, op): + @_atomic_dispatcher + def impl_ptx_atomic(context, builder, dtype, ptr, val): + if dtype in (cuda.cudadecl.integer_numba_types): + return builder.atomic_rmw(op, ptr, val, 'monotonic') + else: + raise TypeError(f'Unimplemented atomic {op} with {dtype} array') + + for ty in (types.intp, types.UniTuple, types.Tuple): + lower(stub, types.Array, ty, types.Any)(impl_ptx_atomic) + + +ptx_atomic_bitwise(stubs.atomic.and_, 'and') +ptx_atomic_bitwise(stubs.atomic.or_, 'or') +ptx_atomic_bitwise(stubs.atomic.xor, 'xor') + + +@lower(stubs.atomic.exch, types.Array, types.intp, types.Any) +@lower(stubs.atomic.exch, types.Array, types.UniTuple, types.Any) +@lower(stubs.atomic.exch, types.Array, types.Tuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_exch(context, builder, dtype, ptr, val): + if dtype in (cuda.cudadecl.integer_numba_types): + return builder.atomic_rmw('xchg', ptr, val, 'monotonic') + else: + raise TypeError(f'Unimplemented atomic exch with {dtype} array') + + +@lower(stubs.atomic.max, types.Array, types.intp, types.Any) +@lower(stubs.atomic.max, types.Array, types.Tuple, types.Any) +@lower(stubs.atomic.max, types.Array, types.UniTuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_max(context, builder, dtype, ptr, val): + lmod = builder.module + if dtype == types.float64: + return builder.call(nvvmutils.declare_atomic_max_float64(lmod), + (ptr, val)) + elif dtype == types.float32: + return builder.call(nvvmutils.declare_atomic_max_float32(lmod), + (ptr, val)) + elif dtype in (types.int32, types.int64): + return builder.atomic_rmw('max', ptr, val, ordering='monotonic') + elif dtype in (types.uint32, types.uint64): + return builder.atomic_rmw('umax', ptr, val, ordering='monotonic') + else: + raise TypeError('Unimplemented atomic max with %s array' % dtype) + + +@lower(stubs.atomic.min, types.Array, types.intp, types.Any) +@lower(stubs.atomic.min, types.Array, types.Tuple, types.Any) +@lower(stubs.atomic.min, types.Array, types.UniTuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_min(context, builder, dtype, ptr, val): + lmod = builder.module + if dtype == types.float64: + return builder.call(nvvmutils.declare_atomic_min_float64(lmod), + (ptr, val)) + elif dtype == types.float32: + return builder.call(nvvmutils.declare_atomic_min_float32(lmod), + (ptr, val)) + elif dtype in (types.int32, types.int64): + return builder.atomic_rmw('min', ptr, val, ordering='monotonic') + elif dtype in (types.uint32, types.uint64): + return builder.atomic_rmw('umin', ptr, val, ordering='monotonic') + else: + raise TypeError('Unimplemented atomic min with %s array' % dtype) + + +@lower(stubs.atomic.nanmax, types.Array, types.intp, types.Any) +@lower(stubs.atomic.nanmax, types.Array, types.Tuple, types.Any) +@lower(stubs.atomic.nanmax, types.Array, types.UniTuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_nanmax(context, builder, dtype, ptr, val): + lmod = builder.module + if dtype == types.float64: + return builder.call(nvvmutils.declare_atomic_nanmax_float64(lmod), + (ptr, val)) + elif dtype == types.float32: + return builder.call(nvvmutils.declare_atomic_nanmax_float32(lmod), + (ptr, val)) + elif dtype in (types.int32, types.int64): + return builder.atomic_rmw('max', ptr, val, ordering='monotonic') + elif dtype in (types.uint32, types.uint64): + return builder.atomic_rmw('umax', ptr, val, ordering='monotonic') + else: + raise TypeError('Unimplemented atomic max with %s array' % dtype) + + +@lower(stubs.atomic.nanmin, types.Array, types.intp, types.Any) +@lower(stubs.atomic.nanmin, types.Array, types.Tuple, types.Any) +@lower(stubs.atomic.nanmin, types.Array, types.UniTuple, types.Any) +@_atomic_dispatcher +def ptx_atomic_nanmin(context, builder, dtype, ptr, val): + lmod = builder.module + if dtype == types.float64: + return builder.call(nvvmutils.declare_atomic_nanmin_float64(lmod), + (ptr, val)) + elif dtype == types.float32: + return builder.call(nvvmutils.declare_atomic_nanmin_float32(lmod), + (ptr, val)) + elif dtype in (types.int32, types.int64): + return builder.atomic_rmw('min', ptr, val, ordering='monotonic') + elif dtype in (types.uint32, types.uint64): + return builder.atomic_rmw('umin', ptr, val, ordering='monotonic') + else: + raise TypeError('Unimplemented atomic min with %s array' % dtype) + + +@lower(stubs.atomic.compare_and_swap, types.Array, types.Any, types.Any) +def ptx_atomic_compare_and_swap(context, builder, sig, args): + sig = sig.return_type(sig.args[0], types.intp, sig.args[1], sig.args[2]) + args = (args[0], context.get_constant(types.intp, 0), args[1], args[2]) + return ptx_atomic_cas(context, builder, sig, args) + + +@lower(stubs.atomic.cas, types.Array, types.intp, types.Any, types.Any) +@lower(stubs.atomic.cas, types.Array, types.Tuple, types.Any, types.Any) +@lower(stubs.atomic.cas, types.Array, types.UniTuple, types.Any, types.Any) +def ptx_atomic_cas(context, builder, sig, args): + aryty, indty, oldty, valty = sig.args + ary, inds, old, val = args + + indty, indices = _normalize_indices(context, builder, indty, inds, aryty, + valty) + + lary = context.make_array(aryty)(context, builder, ary) + ptr = cgutils.get_item_pointer(context, builder, aryty, lary, indices, + wraparound=True) + + if aryty.dtype in (cuda.cudadecl.integer_numba_types): + lmod = builder.module + bitwidth = aryty.dtype.bitwidth + return nvvmutils.atomic_cmpxchg(builder, lmod, bitwidth, ptr, old, val) + else: + raise TypeError('Unimplemented atomic cas with %s array' % aryty.dtype) + + +# ----------------------------------------------------------------------------- + +@lower(stubs.nanosleep, types.uint32) +def ptx_nanosleep(context, builder, sig, args): + nanosleep = ir.InlineAsm(ir.FunctionType(ir.VoidType(), [ir.IntType(32)]), + "nanosleep.u32 $0;", 'r', side_effect=True) + ns = args[0] + builder.call(nanosleep, [ns]) + + +# ----------------------------------------------------------------------------- + + +def _generic_array(context, builder, shape, dtype, symbol_name, addrspace, + can_dynsized=False): + elemcount = reduce(operator.mul, shape, 1) + + # Check for valid shape for this type of allocation. + # Only 1d arrays can be dynamic. + dynamic_smem = elemcount <= 0 and can_dynsized and len(shape) == 1 + if elemcount <= 0 and not dynamic_smem: + raise ValueError("array length <= 0") + + # Check that we support the requested dtype + data_model = context.data_model_manager[dtype] + other_supported_type = ( + isinstance(dtype, (types.Record, types.Boolean)) + or isinstance(data_model, models.StructModel) + or dtype == types.float16 + ) + if dtype not in types.number_domain and not other_supported_type: + raise TypeError("unsupported type: %s" % dtype) + + lldtype = context.get_data_type(dtype) + laryty = ir.ArrayType(lldtype, elemcount) + + if addrspace == nvvm.ADDRSPACE_LOCAL: + # Special case local address space allocation to use alloca + # NVVM is smart enough to only use local memory if no register is + # available + dataptr = cgutils.alloca_once(builder, laryty, name=symbol_name) + else: + lmod = builder.module + + # Create global variable in the requested address space + gvmem = cgutils.add_global_variable(lmod, laryty, symbol_name, + addrspace) + # Specify alignment to avoid misalignment bug + align = context.get_abi_sizeof(lldtype) + # Alignment is required to be a power of 2 for shared memory. If it is + # not a power of 2 (e.g. for a Record array) then round up accordingly. + gvmem.align = 1 << (align - 1 ).bit_length() + + if dynamic_smem: + gvmem.linkage = 'external' + else: + ## Comment out the following line to workaround a NVVM bug + ## which generates a invalid symbol name when the linkage + ## is internal and in some situation. + ## See _get_unique_smem_id() + # gvmem.linkage = lc.LINKAGE_INTERNAL + + gvmem.initializer = ir.Constant(laryty, ir.Undefined) + + # Convert to generic address-space + dataptr = builder.addrspacecast(gvmem, ir.PointerType(ir.IntType(8)), + 'generic') + + targetdata = ll.create_target_data(nvvm.NVVM().data_layout) + lldtype = context.get_data_type(dtype) + itemsize = lldtype.get_abi_size(targetdata) + + # Compute strides + laststride = itemsize + rstrides = [] + for i, lastsize in enumerate(reversed(shape)): + rstrides.append(laststride) + laststride *= lastsize + strides = [s for s in reversed(rstrides)] + kstrides = [context.get_constant(types.intp, s) for s in strides] + + # Compute shape + if dynamic_smem: + # Compute the shape based on the dynamic shared memory configuration. + # Unfortunately NVVM does not provide an intrinsic for the + # %dynamic_smem_size register, so we must read it using inline + # assembly. + get_dynshared_size = ir.InlineAsm(ir.FunctionType(ir.IntType(32), []), + "mov.u32 $0, %dynamic_smem_size;", + '=r', side_effect=True) + dynsmem_size = builder.zext(builder.call(get_dynshared_size, []), + ir.IntType(64)) + # Only 1-D dynamic shared memory is supported so the following is a + # sufficient construction of the shape + kitemsize = context.get_constant(types.intp, itemsize) + kshape = [builder.udiv(dynsmem_size, kitemsize)] + else: + kshape = [context.get_constant(types.intp, s) for s in shape] + + # Create array object + ndim = len(shape) + aryty = types.Array(dtype=dtype, ndim=ndim, layout='C') + ary = context.make_array(aryty)(context, builder) + + context.populate_array(ary, + data=builder.bitcast(dataptr, ary.data.type), + shape=kshape, + strides=kstrides, + itemsize=context.get_constant(types.intp, itemsize), + meminfo=None) + return ary._getvalue() + + +@lower_constant(CUDADispatcher) +def cuda_dispatcher_const(context, builder, ty, pyval): + return context.get_dummy_value() + + +# NumPy + +register_ufuncs(ufunc_db.get_ufuncs(), lower) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudamath.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudamath.py new file mode 100644 index 0000000000000000000000000000000000000000..12d9715b62eb29b057d814748cf56b469b6a7bfc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/cudamath.py @@ -0,0 +1,140 @@ +import math +from numba.core import types +from numba.core.typing.templates import ConcreteTemplate, signature, Registry + + +registry = Registry() +infer_global = registry.register_global + + +@infer_global(math.acos) +@infer_global(math.acosh) +@infer_global(math.asin) +@infer_global(math.asinh) +@infer_global(math.atan) +@infer_global(math.atanh) +@infer_global(math.cosh) +@infer_global(math.degrees) +@infer_global(math.erf) +@infer_global(math.erfc) +@infer_global(math.expm1) +@infer_global(math.gamma) +@infer_global(math.lgamma) +@infer_global(math.log1p) +@infer_global(math.radians) +@infer_global(math.sinh) +@infer_global(math.tanh) +@infer_global(math.tan) +class Math_unary(ConcreteTemplate): + cases = [ + signature(types.float64, types.int64), + signature(types.float64, types.uint64), + signature(types.float32, types.float32), + signature(types.float64, types.float64), + ] + + +@infer_global(math.sin) +@infer_global(math.cos) +@infer_global(math.ceil) +@infer_global(math.floor) +@infer_global(math.sqrt) +@infer_global(math.log) +@infer_global(math.log2) +@infer_global(math.log10) +@infer_global(math.exp) +@infer_global(math.fabs) +@infer_global(math.trunc) +class Math_unary_with_fp16(ConcreteTemplate): + cases = [ + signature(types.float64, types.int64), + signature(types.float64, types.uint64), + signature(types.float32, types.float32), + signature(types.float64, types.float64), + signature(types.float16, types.float16), + ] + + +@infer_global(math.atan2) +class Math_atan2(ConcreteTemplate): + key = math.atan2 + cases = [ + signature(types.float64, types.int64, types.int64), + signature(types.float64, types.uint64, types.uint64), + signature(types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64), + ] + + +@infer_global(math.hypot) +class Math_hypot(ConcreteTemplate): + key = math.hypot + cases = [ + signature(types.float64, types.int64, types.int64), + signature(types.float64, types.uint64, types.uint64), + signature(types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64), + ] + + +@infer_global(math.copysign) +@infer_global(math.fmod) +class Math_binary(ConcreteTemplate): + cases = [ + signature(types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64), + ] + + +@infer_global(math.remainder) +class Math_remainder(ConcreteTemplate): + cases = [ + signature(types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64), + ] + + +@infer_global(math.pow) +class Math_pow(ConcreteTemplate): + cases = [ + signature(types.float32, types.float32, types.float32), + signature(types.float64, types.float64, types.float64), + signature(types.float32, types.float32, types.int32), + signature(types.float64, types.float64, types.int32), + ] + + +@infer_global(math.frexp) +class Math_frexp(ConcreteTemplate): + cases = [ + signature(types.Tuple([types.float32, types.int32]), types.float32), + signature(types.Tuple([types.float64, types.int32]), types.float64), + ] + + +@infer_global(math.ldexp) +class Math_ldexp(ConcreteTemplate): + cases = [ + signature(types.float32, types.float32, types.int32), + signature(types.float64, types.float64, types.int32), + ] + + +@infer_global(math.isinf) +@infer_global(math.isnan) +@infer_global(math.isfinite) +class Math_isnan(ConcreteTemplate): + cases = [ + signature(types.boolean, types.int64), + signature(types.boolean, types.uint64), + signature(types.boolean, types.float32), + signature(types.boolean, types.float64), + ] + + +@infer_global(math.modf) +class Math_modf(ConcreteTemplate): + cases = [ + signature(types.UniTuple(types.float64, 2), types.float64), + signature(types.UniTuple(types.float32, 2), types.float32) + ] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/decorators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..ede980780b954e5b4fcdba1f7c5000bd38c8c033 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/decorators.py @@ -0,0 +1,191 @@ +from warnings import warn +from numba.core import types, config, sigutils +from numba.core.errors import DeprecationError, NumbaInvalidConfigWarning +from numba.cuda.compiler import declare_device_function +from numba.cuda.dispatcher import CUDADispatcher +from numba.cuda.simulator.kernel import FakeCUDAKernel + + +_msg_deprecated_signature_arg = ("Deprecated keyword argument `{0}`. " + "Signatures should be passed as the first " + "positional argument.") + + +def jit(func_or_sig=None, device=False, inline=False, link=None, debug=None, + opt=True, lineinfo=False, cache=False, **kws): + """ + JIT compile a Python function for CUDA GPUs. + + :param func_or_sig: A function to JIT compile, or *signatures* of a + function to compile. If a function is supplied, then a + :class:`Dispatcher ` is returned. + Otherwise, ``func_or_sig`` may be a signature or a list of signatures, + and a function is returned. The returned function accepts another + function, which it will compile and then return a :class:`Dispatcher + `. See :ref:`jit-decorator` for + more information about passing signatures. + + .. note:: A kernel cannot have any return value. + :param device: Indicates whether this is a device function. + :type device: bool + :param link: A list of files containing PTX or CUDA C/C++ source to link + with the function + :type link: list + :param debug: If True, check for exceptions thrown when executing the + kernel. Since this degrades performance, this should only be used for + debugging purposes. If set to True, then ``opt`` should be set to False. + Defaults to False. (The default value can be overridden by setting + environment variable ``NUMBA_CUDA_DEBUGINFO=1``.) + :param fastmath: When True, enables fastmath optimizations as outlined in + the :ref:`CUDA Fast Math documentation `. + :param max_registers: Request that the kernel is limited to using at most + this number of registers per thread. The limit may not be respected if + the ABI requires a greater number of registers than that requested. + Useful for increasing occupancy. + :param opt: Whether to compile from LLVM IR to PTX with optimization + enabled. When ``True``, ``-opt=3`` is passed to NVVM. When + ``False``, ``-opt=0`` is passed to NVVM. Defaults to ``True``. + :type opt: bool + :param lineinfo: If True, generate a line mapping between source code and + assembly code. This enables inspection of the source code in NVIDIA + profiling tools and correlation with program counter sampling. + :type lineinfo: bool + :param cache: If True, enables the file-based cache for this function. + :type cache: bool + """ + + if link is None: + link = [] + if link and config.ENABLE_CUDASIM: + raise NotImplementedError('Cannot link PTX in the simulator') + + if kws.get('boundscheck'): + raise NotImplementedError("bounds checking is not supported for CUDA") + + if kws.get('argtypes') is not None: + msg = _msg_deprecated_signature_arg.format('argtypes') + raise DeprecationError(msg) + if kws.get('restype') is not None: + msg = _msg_deprecated_signature_arg.format('restype') + raise DeprecationError(msg) + if kws.get('bind') is not None: + msg = _msg_deprecated_signature_arg.format('bind') + raise DeprecationError(msg) + + debug = config.CUDA_DEBUGINFO_DEFAULT if debug is None else debug + fastmath = kws.get('fastmath', False) + extensions = kws.get('extensions', []) + + if debug and opt: + msg = ("debug=True with opt=True (the default) " + "is not supported by CUDA. This may result in a crash" + " - set debug=False or opt=False.") + warn(NumbaInvalidConfigWarning(msg)) + + if debug and lineinfo: + msg = ("debug and lineinfo are mutually exclusive. Use debug to get " + "full debug info (this disables some optimizations), or " + "lineinfo for line info only with code generation unaffected.") + warn(NumbaInvalidConfigWarning(msg)) + + if device and kws.get('link'): + raise ValueError("link keyword invalid for device function") + + if sigutils.is_signature(func_or_sig): + signatures = [func_or_sig] + specialized = True + elif isinstance(func_or_sig, list): + signatures = func_or_sig + specialized = False + else: + signatures = None + + if signatures is not None: + if config.ENABLE_CUDASIM: + def jitwrapper(func): + return FakeCUDAKernel(func, device=device, fastmath=fastmath) + return jitwrapper + + def _jit(func): + targetoptions = kws.copy() + targetoptions['debug'] = debug + targetoptions['lineinfo'] = lineinfo + targetoptions['link'] = link + targetoptions['opt'] = opt + targetoptions['fastmath'] = fastmath + targetoptions['device'] = device + targetoptions['extensions'] = extensions + + disp = CUDADispatcher(func, targetoptions=targetoptions) + + if cache: + disp.enable_caching() + + for sig in signatures: + argtypes, restype = sigutils.normalize_signature(sig) + + if restype and not device and restype != types.void: + raise TypeError("CUDA kernel must have void return type.") + + if device: + from numba.core import typeinfer + with typeinfer.register_dispatcher(disp): + disp.compile_device(argtypes, restype) + else: + disp.compile(argtypes) + + disp._specialized = specialized + disp.disable_compile() + + return disp + + return _jit + else: + if func_or_sig is None: + if config.ENABLE_CUDASIM: + def autojitwrapper(func): + return FakeCUDAKernel(func, device=device, + fastmath=fastmath) + else: + def autojitwrapper(func): + return jit(func, device=device, debug=debug, opt=opt, + lineinfo=lineinfo, link=link, cache=cache, **kws) + + return autojitwrapper + # func_or_sig is a function + else: + if config.ENABLE_CUDASIM: + return FakeCUDAKernel(func_or_sig, device=device, + fastmath=fastmath) + else: + targetoptions = kws.copy() + targetoptions['debug'] = debug + targetoptions['lineinfo'] = lineinfo + targetoptions['opt'] = opt + targetoptions['link'] = link + targetoptions['fastmath'] = fastmath + targetoptions['device'] = device + targetoptions['extensions'] = extensions + disp = CUDADispatcher(func_or_sig, targetoptions=targetoptions) + + if cache: + disp.enable_caching() + + return disp + + +def declare_device(name, sig): + """ + Declare the signature of a foreign function. Returns a descriptor that can + be used to call the function from a Python kernel. + + :param name: The name of the foreign function. + :type name: str + :param sig: The Numba signature of the function. + """ + argtypes, restype = sigutils.normalize_signature(sig) + if restype is None: + msg = 'Return type must be provided for device declarations' + raise TypeError(msg) + + return declare_device_function(name, restype, argtypes) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/descriptor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/descriptor.py new file mode 100644 index 0000000000000000000000000000000000000000..b91ddf7a1b9b1fe5eca6b92162d68b155c34204c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/descriptor.py @@ -0,0 +1,33 @@ +from numba.core.descriptors import TargetDescriptor +from numba.core.options import TargetOptions +from .target import CUDATargetContext, CUDATypingContext + + +class CUDATargetOptions(TargetOptions): + pass + + +class CUDATarget(TargetDescriptor): + def __init__(self, name): + self.options = CUDATargetOptions + # The typing and target contexts are initialized only when needed - + # this prevents an attempt to load CUDA libraries at import time on + # systems that might not have them present. + self._typingctx = None + self._targetctx = None + super().__init__(name) + + @property + def typing_context(self): + if self._typingctx is None: + self._typingctx = CUDATypingContext() + return self._typingctx + + @property + def target_context(self): + if self._targetctx is None: + self._targetctx = CUDATargetContext(self._typingctx) + return self._targetctx + + +cuda_target = CUDATarget('cuda') diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/device_init.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/device_init.py new file mode 100644 index 0000000000000000000000000000000000000000..9df5ae99d8f5ad2a40a926a1e40343d9b8797fd6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/device_init.py @@ -0,0 +1,89 @@ +# Re export +import sys +from numba.cuda import cg +from .stubs import (threadIdx, blockIdx, blockDim, gridDim, laneid, warpsize, + syncwarp, shared, local, const, atomic, + shfl_sync_intrinsic, vote_sync_intrinsic, match_any_sync, + match_all_sync, threadfence_block, threadfence_system, + threadfence, selp, popc, brev, clz, ffs, fma, cbrt, + activemask, lanemask_lt, nanosleep, fp16, + _vector_type_stubs) +from .intrinsics import (grid, gridsize, syncthreads, syncthreads_and, + syncthreads_count, syncthreads_or) +from .cudadrv.error import CudaSupportError +from numba.cuda.cudadrv.driver import (BaseCUDAMemoryManager, + HostOnlyCUDAMemoryManager, + GetIpcHandleMixin, MemoryPointer, + MappedMemory, PinnedMemory, MemoryInfo, + IpcHandle, set_memory_manager) +from numba.cuda.cudadrv.runtime import runtime +from .cudadrv import nvvm +from numba.cuda import initialize +from .errors import KernelRuntimeError + +from .decorators import jit, declare_device +from .api import * +from .api import _auto_device +from .args import In, Out, InOut + +from .intrinsic_wrapper import (all_sync, any_sync, eq_sync, ballot_sync, + shfl_sync, shfl_up_sync, shfl_down_sync, + shfl_xor_sync) + +from .kernels import reduction + +reduce = Reduce = reduction.Reduce + +# Expose vector type constructors and aliases as module level attributes. +for vector_type_stub in _vector_type_stubs: + setattr(sys.modules[__name__], vector_type_stub.__name__, vector_type_stub) + for alias in vector_type_stub.aliases: + setattr(sys.modules[__name__], alias, vector_type_stub) +del vector_type_stub, _vector_type_stubs + + +def is_available(): + """Returns a boolean to indicate the availability of a CUDA GPU. + + This will initialize the driver if it hasn't been initialized. + """ + # whilst `driver.is_available` will init the driver itself, + # the driver initialization may raise and as a result break + # test discovery/orchestration as `cuda.is_available` is often + # used as a guard for whether to run a CUDA test, the try/except + # below is to handle this case. + driver_is_available = False + try: + driver_is_available = driver.driver.is_available + except CudaSupportError: + pass + + return driver_is_available and nvvm.is_available() + + +def is_supported_version(): + """Returns True if the CUDA Runtime is a supported version. + + Unsupported versions (e.g. newer versions than those known to Numba) + may still work; this function provides a facility to check whether the + current Numba version is tested and known to work with the current + runtime version. If the current version is unsupported, the caller can + decide how to act. Options include: + + - Continuing silently, + - Emitting a warning, + - Generating an error or otherwise preventing the use of CUDA. + """ + + return runtime.is_supported_version() + + +def cuda_error(): + """Returns None if there was no error initializing the CUDA driver. + If there was an error initializing the driver, a string describing the + error is returned. + """ + return driver.driver.initialization_error + + +initialize.initialize_all() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/deviceufunc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/deviceufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..52851e1e4fdfaa7666a614b3e54e290e33f87382 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/deviceufunc.py @@ -0,0 +1,919 @@ +""" +Implements custom ufunc dispatch mechanism for non-CPU devices. +""" + +from abc import ABCMeta, abstractmethod +from collections import OrderedDict +import operator +import warnings +from functools import reduce + +import numpy as np + +from numba.np.ufunc.ufuncbuilder import _BaseUFuncBuilder, parse_identity +from numba.core import types, sigutils +from numba.core.typing import signature +from numba.np.ufunc.sigparse import parse_signature + + +def _broadcast_axis(a, b): + """ + Raises + ------ + ValueError if broadcast fails + """ + if a == b: + return a + elif a == 1: + return b + elif b == 1: + return a + else: + raise ValueError("failed to broadcast {0} and {1}".format(a, b)) + + +def _pairwise_broadcast(shape1, shape2): + """ + Raises + ------ + ValueError if broadcast fails + """ + shape1, shape2 = map(tuple, [shape1, shape2]) + + while len(shape1) < len(shape2): + shape1 = (1,) + shape1 + + while len(shape1) > len(shape2): + shape2 = (1,) + shape2 + + return tuple(_broadcast_axis(a, b) for a, b in zip(shape1, shape2)) + + +def _multi_broadcast(*shapelist): + """ + Raises + ------ + ValueError if broadcast fails + """ + assert shapelist + + result = shapelist[0] + others = shapelist[1:] + try: + for i, each in enumerate(others, start=1): + result = _pairwise_broadcast(result, each) + except ValueError: + raise ValueError("failed to broadcast argument #{0}".format(i)) + else: + return result + + +class UFuncMechanism(object): + """ + Prepare ufunc arguments for vectorize. + """ + DEFAULT_STREAM = None + SUPPORT_DEVICE_SLICING = False + + def __init__(self, typemap, args): + """Never used directly by user. Invoke by UFuncMechanism.call(). + """ + self.typemap = typemap + self.args = args + nargs = len(self.args) + self.argtypes = [None] * nargs + self.scalarpos = [] + self.signature = None + self.arrays = [None] * nargs + + def _fill_arrays(self): + """ + Get all arguments in array form + """ + for i, arg in enumerate(self.args): + if self.is_device_array(arg): + self.arrays[i] = self.as_device_array(arg) + elif isinstance(arg, (int, float, complex, np.number)): + # Is scalar + self.scalarpos.append(i) + else: + self.arrays[i] = np.asarray(arg) + + def _fill_argtypes(self): + """ + Get dtypes + """ + for i, ary in enumerate(self.arrays): + if ary is not None: + dtype = getattr(ary, 'dtype') + if dtype is None: + dtype = np.asarray(ary).dtype + self.argtypes[i] = dtype + + def _resolve_signature(self): + """Resolve signature. + May have ambiguous case. + """ + matches = [] + # Resolve scalar args exact match first + if self.scalarpos: + # Try resolve scalar arguments + for formaltys in self.typemap: + match_map = [] + for i, (formal, actual) in enumerate(zip(formaltys, + self.argtypes)): + if actual is None: + actual = np.asarray(self.args[i]).dtype + + match_map.append(actual == formal) + + if all(match_map): + matches.append(formaltys) + + # No matching with exact match; try coercing the scalar arguments + if not matches: + matches = [] + for formaltys in self.typemap: + all_matches = all(actual is None or formal == actual + for formal, actual in + zip(formaltys, self.argtypes)) + if all_matches: + matches.append(formaltys) + + if not matches: + raise TypeError("No matching version. GPU ufunc requires array " + "arguments to have the exact types. This behaves " + "like regular ufunc with casting='no'.") + + if len(matches) > 1: + raise TypeError("Failed to resolve ufunc due to ambiguous " + "signature. Too many untyped scalars. " + "Use numpy dtype object to type tag.") + + # Try scalar arguments + self.argtypes = matches[0] + + def _get_actual_args(self): + """Return the actual arguments + Casts scalar arguments to np.array. + """ + for i in self.scalarpos: + self.arrays[i] = np.array([self.args[i]], dtype=self.argtypes[i]) + + return self.arrays + + def _broadcast(self, arys): + """Perform numpy ufunc broadcasting + """ + shapelist = [a.shape for a in arys] + shape = _multi_broadcast(*shapelist) + + for i, ary in enumerate(arys): + if ary.shape == shape: + pass + + else: + if self.is_device_array(ary): + arys[i] = self.broadcast_device(ary, shape) + + else: + ax_differs = [ax for ax in range(len(shape)) + if ax >= ary.ndim + or ary.shape[ax] != shape[ax]] + + missingdim = len(shape) - len(ary.shape) + strides = [0] * missingdim + list(ary.strides) + + for ax in ax_differs: + strides[ax] = 0 + + strided = np.lib.stride_tricks.as_strided(ary, + shape=shape, + strides=strides) + + arys[i] = self.force_array_layout(strided) + + return arys + + def get_arguments(self): + """Prepare and return the arguments for the ufunc. + Does not call to_device(). + """ + self._fill_arrays() + self._fill_argtypes() + self._resolve_signature() + arys = self._get_actual_args() + return self._broadcast(arys) + + def get_function(self): + """Returns (result_dtype, function) + """ + return self.typemap[self.argtypes] + + def is_device_array(self, obj): + """Is the `obj` a device array? + Override in subclass + """ + return False + + def as_device_array(self, obj): + """Convert the `obj` to a device array + Override in subclass + + Default implementation is an identity function + """ + return obj + + def broadcast_device(self, ary, shape): + """Handles ondevice broadcasting + + Override in subclass to add support. + """ + raise NotImplementedError("broadcasting on device is not supported") + + def force_array_layout(self, ary): + """Ensures array layout met device requirement. + + Override in sublcass + """ + return ary + + @classmethod + def call(cls, typemap, args, kws): + """Perform the entire ufunc call mechanism. + """ + # Handle keywords + stream = kws.pop('stream', cls.DEFAULT_STREAM) + out = kws.pop('out', None) + + if kws: + warnings.warn("unrecognized keywords: %s" % ', '.join(kws)) + + # Begin call resolution + cr = cls(typemap, args) + args = cr.get_arguments() + resty, func = cr.get_function() + + outshape = args[0].shape + + # Adjust output value + if out is not None and cr.is_device_array(out): + out = cr.as_device_array(out) + + def attempt_ravel(a): + if cr.SUPPORT_DEVICE_SLICING: + raise NotImplementedError + + try: + # Call the `.ravel()` method + return a.ravel() + except NotImplementedError: + # If it is not a device array + if not cr.is_device_array(a): + raise + # For device array, retry ravel on the host by first + # copying it back. + else: + hostary = cr.to_host(a, stream).ravel() + return cr.to_device(hostary, stream) + + if args[0].ndim > 1: + args = [attempt_ravel(a) for a in args] + + # Prepare argument on the device + devarys = [] + any_device = False + for a in args: + if cr.is_device_array(a): + devarys.append(a) + any_device = True + else: + dev_a = cr.to_device(a, stream=stream) + devarys.append(dev_a) + + # Launch + shape = args[0].shape + if out is None: + # No output is provided + devout = cr.allocate_device_array(shape, resty, stream=stream) + + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + + if any_device: + # If any of the arguments are on device, + # Keep output on the device + return devout.reshape(outshape) + else: + # Otherwise, transfer output back to host + return devout.copy_to_host().reshape(outshape) + + elif cr.is_device_array(out): + # If output is provided and it is a device array, + # Return device array + if out.ndim > 1: + out = attempt_ravel(out) + devout = out + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + return devout.reshape(outshape) + + else: + # If output is provided and it is a host array, + # Return host array + assert out.shape == shape + assert out.dtype == resty + devout = cr.allocate_device_array(shape, resty, stream=stream) + devarys.extend([devout]) + cr.launch(func, shape[0], stream, devarys) + return devout.copy_to_host(out, stream=stream).reshape(outshape) + + def to_device(self, hostary, stream): + """Implement to device transfer + Override in subclass + """ + raise NotImplementedError + + def to_host(self, devary, stream): + """Implement to host transfer + Override in subclass + """ + raise NotImplementedError + + def allocate_device_array(self, shape, dtype, stream): + """Implements device allocation + Override in subclass + """ + raise NotImplementedError + + def launch(self, func, count, stream, args): + """Implements device function invocation + Override in subclass + """ + raise NotImplementedError + + +def to_dtype(ty): + if isinstance(ty, types.EnumMember): + ty = ty.dtype + return np.dtype(str(ty)) + + +class DeviceVectorize(_BaseUFuncBuilder): + def __init__(self, func, identity=None, cache=False, targetoptions=None): + if targetoptions is None: + targetoptions = {} + if cache: + raise TypeError("caching is not supported") + for opt in targetoptions: + if opt == 'nopython': + warnings.warn("nopython kwarg for cuda target is redundant", + RuntimeWarning) + else: + fmt = "Unrecognized options. " + fmt += "cuda vectorize target does not support option: '%s'" + raise KeyError(fmt % opt) + self.py_func = func + self.identity = parse_identity(identity) + # { arg_dtype: (return_dtype), cudakernel } + self.kernelmap = OrderedDict() + + @property + def pyfunc(self): + return self.py_func + + def add(self, sig=None): + # compile core as device function + args, return_type = sigutils.normalize_signature(sig) + devfnsig = signature(return_type, *args) + + funcname = self.pyfunc.__name__ + kernelsource = self._get_kernel_source(self._kernel_template, + devfnsig, funcname) + corefn, return_type = self._compile_core(devfnsig) + glbl = self._get_globals(corefn) + sig = signature(types.void, *([a[:] for a in args] + [return_type[:]])) + exec(kernelsource, glbl) + + stager = glbl['__vectorized_%s' % funcname] + kernel = self._compile_kernel(stager, sig) + + argdtypes = tuple(to_dtype(t) for t in devfnsig.args) + resdtype = to_dtype(return_type) + self.kernelmap[tuple(argdtypes)] = resdtype, kernel + + def build_ufunc(self): + raise NotImplementedError + + def _get_kernel_source(self, template, sig, funcname): + args = ['a%d' % i for i in range(len(sig.args))] + fmts = dict(name=funcname, + args=', '.join(args), + argitems=', '.join('%s[__tid__]' % i for i in args)) + return template.format(**fmts) + + def _compile_core(self, sig): + raise NotImplementedError + + def _get_globals(self, corefn): + raise NotImplementedError + + def _compile_kernel(self, fnobj, sig): + raise NotImplementedError + + +class DeviceGUFuncVectorize(_BaseUFuncBuilder): + def __init__( + self, + func, + sig, + identity=None, + cache=False, + targetoptions=None, + writable_args=(), + ): + if targetoptions is None: + targetoptions = {} + if cache: + raise TypeError("caching is not supported") + if writable_args: + raise TypeError("writable_args are not supported") + + # Allow nopython flag to be set. + if not targetoptions.pop('nopython', True): + raise TypeError("nopython flag must be True") + # Are there any more target options? + if targetoptions: + opts = ', '.join([repr(k) for k in targetoptions.keys()]) + fmt = "The following target options are not supported: {0}" + raise TypeError(fmt.format(opts)) + + self.py_func = func + self.identity = parse_identity(identity) + self.signature = sig + self.inputsig, self.outputsig = parse_signature(self.signature) + + # Maps from a tuple of input_dtypes to (output_dtypes, kernel) + self.kernelmap = OrderedDict() + + @property + def pyfunc(self): + return self.py_func + + def add(self, sig=None): + indims = [len(x) for x in self.inputsig] + outdims = [len(x) for x in self.outputsig] + args, return_type = sigutils.normalize_signature(sig) + + # It is only valid to specify types.none as a return type, or to not + # specify the return type (where the "Python None" is the return type) + valid_return_type = return_type in (types.none, None) + if not valid_return_type: + raise TypeError('guvectorized functions cannot return values: ' + f'signature {sig} specifies {return_type} return ' + 'type') + + funcname = self.py_func.__name__ + src = expand_gufunc_template(self._kernel_template, indims, + outdims, funcname, args) + + glbls = self._get_globals(sig) + + exec(src, glbls) + fnobj = glbls['__gufunc_{name}'.format(name=funcname)] + + outertys = list(_determine_gufunc_outer_types(args, indims + outdims)) + kernel = self._compile_kernel(fnobj, sig=tuple(outertys)) + + nout = len(outdims) + dtypes = [np.dtype(str(t.dtype)) for t in outertys] + indtypes = tuple(dtypes[:-nout]) + outdtypes = tuple(dtypes[-nout:]) + + self.kernelmap[indtypes] = outdtypes, kernel + + def _compile_kernel(self, fnobj, sig): + raise NotImplementedError + + def _get_globals(self, sig): + raise NotImplementedError + + +def _determine_gufunc_outer_types(argtys, dims): + for at, nd in zip(argtys, dims): + if isinstance(at, types.Array): + yield at.copy(ndim=nd + 1) + else: + if nd > 0: + raise ValueError("gufunc signature mismatch: ndim>0 for scalar") + yield types.Array(dtype=at, ndim=1, layout='A') + + +def expand_gufunc_template(template, indims, outdims, funcname, argtypes): + """Expand gufunc source template + """ + argdims = indims + outdims + argnames = ["arg{0}".format(i) for i in range(len(argdims))] + checkedarg = "min({0})".format(', '.join(["{0}.shape[0]".format(a) + for a in argnames])) + inputs = [_gen_src_for_indexing(aref, adims, atype) + for aref, adims, atype in zip(argnames, indims, argtypes)] + outputs = [_gen_src_for_indexing(aref, adims, atype) + for aref, adims, atype in zip(argnames[len(indims):], outdims, + argtypes[len(indims):])] + argitems = inputs + outputs + src = template.format(name=funcname, args=', '.join(argnames), + checkedarg=checkedarg, + argitems=', '.join(argitems)) + return src + + +def _gen_src_for_indexing(aref, adims, atype): + return "{aref}[{sliced}]".format(aref=aref, + sliced=_gen_src_index(adims, atype)) + + +def _gen_src_index(adims, atype): + if adims > 0: + return ','.join(['__tid__'] + [':'] * adims) + elif isinstance(atype, types.Array) and atype.ndim - 1 == adims: + # Special case for 0-nd in shape-signature but + # 1d array in type signature. + # Slice it so that the result has the same dimension. + return '__tid__:(__tid__ + 1)' + else: + return '__tid__' + + +class GUFuncEngine(object): + '''Determine how to broadcast and execute a gufunc + base on input shape and signature + ''' + + @classmethod + def from_signature(cls, signature): + return cls(*parse_signature(signature)) + + def __init__(self, inputsig, outputsig): + # signatures + self.sin = inputsig + self.sout = outputsig + # argument count + self.nin = len(self.sin) + self.nout = len(self.sout) + + def schedule(self, ishapes): + if len(ishapes) != self.nin: + raise TypeError('invalid number of input argument') + + # associate symbol values for input signature + symbolmap = {} + outer_shapes = [] + inner_shapes = [] + + for argn, (shape, symbols) in enumerate(zip(ishapes, self.sin)): + argn += 1 # start from 1 for human + inner_ndim = len(symbols) + if len(shape) < inner_ndim: + fmt = "arg #%d: insufficient inner dimension" + raise ValueError(fmt % (argn,)) + if inner_ndim: + inner_shape = shape[-inner_ndim:] + outer_shape = shape[:-inner_ndim] + else: + inner_shape = () + outer_shape = shape + + for axis, (dim, sym) in enumerate(zip(inner_shape, symbols)): + axis += len(outer_shape) + if sym in symbolmap: + if symbolmap[sym] != dim: + fmt = "arg #%d: shape[%d] mismatch argument" + raise ValueError(fmt % (argn, axis)) + symbolmap[sym] = dim + + outer_shapes.append(outer_shape) + inner_shapes.append(inner_shape) + + # solve output shape + oshapes = [] + for outsig in self.sout: + oshape = [] + for sym in outsig: + oshape.append(symbolmap[sym]) + oshapes.append(tuple(oshape)) + + # find the biggest outershape as looping dimension + sizes = [reduce(operator.mul, s, 1) for s in outer_shapes] + largest_i = np.argmax(sizes) + loopdims = outer_shapes[largest_i] + + pinned = [False] * self.nin # same argument for each iteration + for i, d in enumerate(outer_shapes): + if d != loopdims: + if d == (1,) or d == (): + pinned[i] = True + else: + fmt = "arg #%d: outer dimension mismatch" + raise ValueError(fmt % (i + 1,)) + + return GUFuncSchedule(self, inner_shapes, oshapes, loopdims, pinned) + + +class GUFuncSchedule(object): + def __init__(self, parent, ishapes, oshapes, loopdims, pinned): + self.parent = parent + # core shapes + self.ishapes = ishapes + self.oshapes = oshapes + # looping dimension + self.loopdims = loopdims + self.loopn = reduce(operator.mul, loopdims, 1) + # flags + self.pinned = pinned + + self.output_shapes = [loopdims + s for s in oshapes] + + def __str__(self): + import pprint + + attrs = 'ishapes', 'oshapes', 'loopdims', 'loopn', 'pinned' + values = [(k, getattr(self, k)) for k in attrs] + return pprint.pformat(dict(values)) + + +class GeneralizedUFunc(object): + def __init__(self, kernelmap, engine): + self.kernelmap = kernelmap + self.engine = engine + self.max_blocksize = 2 ** 30 + + def __call__(self, *args, **kws): + callsteps = self._call_steps(self.engine.nin, self.engine.nout, + args, kws) + indtypes, schedule, outdtypes, kernel = self._schedule( + callsteps.inputs, callsteps.outputs) + callsteps.adjust_input_types(indtypes) + + outputs = callsteps.prepare_outputs(schedule, outdtypes) + inputs = callsteps.prepare_inputs() + parameters = self._broadcast(schedule, inputs, outputs) + + callsteps.launch_kernel(kernel, schedule.loopn, parameters) + + return callsteps.post_process_outputs(outputs) + + def _schedule(self, inputs, outs): + input_shapes = [a.shape for a in inputs] + schedule = self.engine.schedule(input_shapes) + + # find kernel + indtypes = tuple(i.dtype for i in inputs) + try: + outdtypes, kernel = self.kernelmap[indtypes] + except KeyError: + # No exact match, then use the first compatible. + # This does not match the numpy dispatching exactly. + # Later, we may just jit a new version for the missing signature. + indtypes = self._search_matching_signature(indtypes) + # Select kernel + outdtypes, kernel = self.kernelmap[indtypes] + + # check output + for sched_shape, out in zip(schedule.output_shapes, outs): + if out is not None and sched_shape != out.shape: + raise ValueError('output shape mismatch') + + return indtypes, schedule, outdtypes, kernel + + def _search_matching_signature(self, idtypes): + """ + Given the input types in `idtypes`, return a compatible sequence of + types that is defined in `kernelmap`. + + Note: Ordering is guaranteed by `kernelmap` being a OrderedDict + """ + for sig in self.kernelmap.keys(): + if all(np.can_cast(actual, desired) + for actual, desired in zip(sig, idtypes)): + return sig + else: + raise TypeError("no matching signature") + + def _broadcast(self, schedule, params, retvals): + assert schedule.loopn > 0, "zero looping dimension" + + odim = 1 if not schedule.loopdims else schedule.loopn + newparams = [] + for p, cs in zip(params, schedule.ishapes): + if not cs and p.size == 1: + # Broadcast scalar input + devary = self._broadcast_scalar_input(p, odim) + newparams.append(devary) + else: + # Broadcast vector input + newparams.append(self._broadcast_array(p, odim, cs)) + + newretvals = [] + for retval, oshape in zip(retvals, schedule.oshapes): + newretvals.append(retval.reshape(odim, *oshape)) + return tuple(newparams) + tuple(newretvals) + + def _broadcast_array(self, ary, newdim, innerdim): + newshape = (newdim,) + innerdim + # No change in shape + if ary.shape == newshape: + return ary + + # Creating new dimension + elif len(ary.shape) < len(newshape): + assert newshape[-len(ary.shape):] == ary.shape, \ + "cannot add dim and reshape at the same time" + return self._broadcast_add_axis(ary, newshape) + + # Collapsing dimension + else: + return ary.reshape(*newshape) + + def _broadcast_add_axis(self, ary, newshape): + raise NotImplementedError("cannot add new axis") + + def _broadcast_scalar_input(self, ary, shape): + raise NotImplementedError + + +class GUFuncCallSteps(metaclass=ABCMeta): + """ + Implements memory management and kernel launch operations for GUFunc calls. + + One instance of this class is instantiated for each call, and the instance + is specific to the arguments given to the GUFunc call. + + The base class implements the overall logic; subclasses provide + target-specific implementations of individual functions. + """ + + # The base class uses these slots; subclasses may provide additional slots. + __slots__ = [ + 'outputs', + 'inputs', + '_copy_result_to_host', + ] + + @abstractmethod + def launch_kernel(self, kernel, nelem, args): + """Implement the kernel launch""" + + @abstractmethod + def is_device_array(self, obj): + """ + Return True if `obj` is a device array for this target, False + otherwise. + """ + + @abstractmethod + def as_device_array(self, obj): + """ + Return `obj` as a device array on this target. + + May return `obj` directly if it is already on the target. + """ + + @abstractmethod + def to_device(self, hostary): + """ + Copy `hostary` to the device and return the device array. + """ + + @abstractmethod + def allocate_device_array(self, shape, dtype): + """ + Allocate a new uninitialized device array with the given shape and + dtype. + """ + + def __init__(self, nin, nout, args, kwargs): + outputs = kwargs.get('out') + + # Ensure the user has passed a correct number of arguments + if outputs is None and len(args) not in (nin, (nin + nout)): + def pos_argn(n): + return f'{n} positional argument{"s" * (n != 1)}' + + msg = (f'This gufunc accepts {pos_argn(nin)} (when providing ' + f'input only) or {pos_argn(nin + nout)} (when providing ' + f'input and output). Got {pos_argn(len(args))}.') + raise TypeError(msg) + + if outputs is not None and len(args) > nin: + raise ValueError("cannot specify argument 'out' as both positional " + "and keyword") + else: + # If the user did not pass outputs either in the out kwarg or as + # positional arguments, then we need to generate an initial list of + # "placeholder" outputs using None as a sentry value + outputs = [outputs] * nout + + # Ensure all output device arrays are Numba device arrays - for + # example, any output passed in that supports the CUDA Array Interface + # is converted to a Numba CUDA device array; others are left untouched. + all_user_outputs_are_host = True + self.outputs = [] + for output in outputs: + if self.is_device_array(output): + self.outputs.append(self.as_device_array(output)) + all_user_outputs_are_host = False + else: + self.outputs.append(output) + + all_host_arrays = not any([self.is_device_array(a) for a in args]) + + # - If any of the arguments are device arrays, we leave the output on + # the device. + self._copy_result_to_host = (all_host_arrays and + all_user_outputs_are_host) + + # Normalize arguments - ensure they are either device- or host-side + # arrays (as opposed to lists, tuples, etc). + def normalize_arg(a): + if self.is_device_array(a): + convert = self.as_device_array + else: + convert = np.asarray + + return convert(a) + + normalized_args = [normalize_arg(a) for a in args] + self.inputs = normalized_args[:nin] + + # Check if there are extra arguments for outputs. + unused_inputs = normalized_args[nin:] + if unused_inputs: + self.outputs = unused_inputs + + def adjust_input_types(self, indtypes): + """ + Attempt to cast the inputs to the required types if necessary + and if they are not device arrays. + + Side effect: Only affects the elements of `inputs` that require + a type cast. + """ + for i, (ity, val) in enumerate(zip(indtypes, self.inputs)): + if ity != val.dtype: + if not hasattr(val, 'astype'): + msg = ("compatible signature is possible by casting but " + "{0} does not support .astype()").format(type(val)) + raise TypeError(msg) + # Cast types + self.inputs[i] = val.astype(ity) + + def prepare_outputs(self, schedule, outdtypes): + """ + Returns a list of output parameters that all reside on the target + device. + + Outputs that were passed-in to the GUFunc are used if they reside on the + device; other outputs are allocated as necessary. + """ + outputs = [] + for shape, dtype, output in zip(schedule.output_shapes, outdtypes, + self.outputs): + if output is None or self._copy_result_to_host: + output = self.allocate_device_array(shape, dtype) + outputs.append(output) + + return outputs + + def prepare_inputs(self): + """ + Returns a list of input parameters that all reside on the target device. + """ + def ensure_device(parameter): + if self.is_device_array(parameter): + convert = self.as_device_array + else: + convert = self.to_device + + return convert(parameter) + + return [ensure_device(p) for p in self.inputs] + + def post_process_outputs(self, outputs): + """ + Moves the given output(s) to the host if necessary. + + Returns a single value (e.g. an array) if there was one output, or a + tuple of arrays if there were multiple. Although this feels a little + jarring, it is consistent with the behavior of GUFuncs in general. + """ + if self._copy_result_to_host: + outputs = [self.to_host(output, self_output) + for output, self_output in zip(outputs, self.outputs)] + elif self.outputs[0] is not None: + outputs = self.outputs + + if len(outputs) == 1: + return outputs[0] + else: + return tuple(outputs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/dispatcher.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..b406cd0ba4892fa81b239ae11f41a26d7b5d836f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/dispatcher.py @@ -0,0 +1,1057 @@ +import numpy as np +import os +import sys +import ctypes +import functools + +from numba.core import config, serialize, sigutils, types, typing, utils +from numba.core.caching import Cache, CacheImpl +from numba.core.compiler_lock import global_compiler_lock +from numba.core.dispatcher import Dispatcher +from numba.core.errors import NumbaPerformanceWarning, NumbaValueError +from numba.core.typing.typeof import Purpose, typeof + +from numba.cuda.api import get_current_device +from numba.cuda.args import wrap_arg +from numba.cuda.compiler import compile_cuda, CUDACompiler +from numba.cuda.cudadrv import driver +from numba.cuda.cudadrv.devices import get_context +from numba.cuda.descriptor import cuda_target +from numba.cuda.errors import (missing_launch_config_msg, + normalize_kernel_dimensions) +from numba.cuda import types as cuda_types + +from numba import cuda +from numba import _dispatcher + +from warnings import warn + +cuda_fp16_math_funcs = ['hsin', 'hcos', + 'hlog', 'hlog10', + 'hlog2', + 'hexp', 'hexp10', + 'hexp2', + 'hsqrt', 'hrsqrt', + 'hfloor', 'hceil', + 'hrcp', 'hrint', + 'htrunc', 'hdiv'] + + +class _Kernel(serialize.ReduceMixin): + ''' + CUDA Kernel specialized for a given set of argument types. When called, this + object launches the kernel on the device. + ''' + + @global_compiler_lock + def __init__(self, py_func, argtypes, link=None, debug=False, + lineinfo=False, inline=False, fastmath=False, extensions=None, + max_registers=None, opt=True, device=False): + + if device: + raise RuntimeError('Cannot compile a device function as a kernel') + + super().__init__() + + # _DispatcherBase.nopython_signatures() expects this attribute to be + # present, because it assumes an overload is a CompileResult. In the + # CUDA target, _Kernel instances are stored instead, so we provide this + # attribute here to avoid duplicating nopython_signatures() in the CUDA + # target with slight modifications. + self.objectmode = False + + # The finalizer constructed by _DispatcherBase._make_finalizer also + # expects overloads to be a CompileResult. It uses the entry_point to + # remove a CompileResult from a target context. However, since we never + # insert kernels into a target context (there is no need because they + # cannot be called by other functions, only through the dispatcher) it + # suffices to pretend we have an entry point of None. + self.entry_point = None + + self.py_func = py_func + self.argtypes = argtypes + self.debug = debug + self.lineinfo = lineinfo + self.extensions = extensions or [] + + nvvm_options = { + 'fastmath': fastmath, + 'opt': 3 if opt else 0 + } + + cc = get_current_device().compute_capability + cres = compile_cuda(self.py_func, types.void, self.argtypes, + debug=self.debug, + lineinfo=lineinfo, + inline=inline, + fastmath=fastmath, + nvvm_options=nvvm_options, + cc=cc) + tgt_ctx = cres.target_context + code = self.py_func.__code__ + filename = code.co_filename + linenum = code.co_firstlineno + lib, kernel = tgt_ctx.prepare_cuda_kernel(cres.library, cres.fndesc, + debug, lineinfo, nvvm_options, + filename, linenum, + max_registers) + + if not link: + link = [] + + # A kernel needs cooperative launch if grid_sync is being used. + self.cooperative = 'cudaCGGetIntrinsicHandle' in lib.get_asm_str() + # We need to link against cudadevrt if grid sync is being used. + if self.cooperative: + lib.needs_cudadevrt = True + + res = [fn for fn in cuda_fp16_math_funcs + if (f'__numba_wrapper_{fn}' in lib.get_asm_str())] + + if res: + # Path to the source containing the foreign function + basedir = os.path.dirname(os.path.abspath(__file__)) + functions_cu_path = os.path.join(basedir, + 'cpp_function_wrappers.cu') + link.append(functions_cu_path) + + for filepath in link: + lib.add_linking_file(filepath) + + # populate members + self.entry_name = kernel.name + self.signature = cres.signature + self._type_annotation = cres.type_annotation + self._codelibrary = lib + self.call_helper = cres.call_helper + + # The following are referred to by the cache implementation. Note: + # - There are no referenced environments in CUDA. + # - Kernels don't have lifted code. + # - reload_init is only for parfors. + self.target_context = tgt_ctx + self.fndesc = cres.fndesc + self.environment = cres.environment + self._referenced_environments = [] + self.lifted = [] + self.reload_init = [] + + @property + def library(self): + return self._codelibrary + + @property + def type_annotation(self): + return self._type_annotation + + def _find_referenced_environments(self): + return self._referenced_environments + + @property + def codegen(self): + return self.target_context.codegen() + + @property + def argument_types(self): + return tuple(self.signature.args) + + @classmethod + def _rebuild(cls, cooperative, name, signature, codelibrary, + debug, lineinfo, call_helper, extensions): + """ + Rebuild an instance. + """ + instance = cls.__new__(cls) + # invoke parent constructor + super(cls, instance).__init__() + # populate members + instance.entry_point = None + instance.cooperative = cooperative + instance.entry_name = name + instance.signature = signature + instance._type_annotation = None + instance._codelibrary = codelibrary + instance.debug = debug + instance.lineinfo = lineinfo + instance.call_helper = call_helper + instance.extensions = extensions + return instance + + def _reduce_states(self): + """ + Reduce the instance for serialization. + Compiled definitions are serialized in PTX form. + Type annotation are discarded. + Thread, block and shared memory configuration are serialized. + Stream information is discarded. + """ + return dict(cooperative=self.cooperative, name=self.entry_name, + signature=self.signature, codelibrary=self._codelibrary, + debug=self.debug, lineinfo=self.lineinfo, + call_helper=self.call_helper, extensions=self.extensions) + + def bind(self): + """ + Force binding to current CUDA context + """ + self._codelibrary.get_cufunc() + + @property + def regs_per_thread(self): + ''' + The number of registers used by each thread for this kernel. + ''' + return self._codelibrary.get_cufunc().attrs.regs + + @property + def const_mem_size(self): + ''' + The amount of constant memory used by this kernel. + ''' + return self._codelibrary.get_cufunc().attrs.const + + @property + def shared_mem_per_block(self): + ''' + The amount of shared memory used per block for this kernel. + ''' + return self._codelibrary.get_cufunc().attrs.shared + + @property + def max_threads_per_block(self): + ''' + The maximum allowable threads per block. + ''' + return self._codelibrary.get_cufunc().attrs.maxthreads + + @property + def local_mem_per_thread(self): + ''' + The amount of local memory used per thread for this kernel. + ''' + return self._codelibrary.get_cufunc().attrs.local + + def inspect_llvm(self): + ''' + Returns the LLVM IR for this kernel. + ''' + return self._codelibrary.get_llvm_str() + + def inspect_asm(self, cc): + ''' + Returns the PTX code for this kernel. + ''' + return self._codelibrary.get_asm_str(cc=cc) + + def inspect_sass_cfg(self): + ''' + Returns the CFG of the SASS for this kernel. + + Requires nvdisasm to be available on the PATH. + ''' + return self._codelibrary.get_sass_cfg() + + def inspect_sass(self): + ''' + Returns the SASS code for this kernel. + + Requires nvdisasm to be available on the PATH. + ''' + return self._codelibrary.get_sass() + + def inspect_types(self, file=None): + ''' + Produce a dump of the Python source of this function annotated with the + corresponding Numba IR and type information. The dump is written to + *file*, or *sys.stdout* if *file* is *None*. + ''' + if self._type_annotation is None: + raise ValueError("Type annotation is not available") + + if file is None: + file = sys.stdout + + print("%s %s" % (self.entry_name, self.argument_types), file=file) + print('-' * 80, file=file) + print(self._type_annotation, file=file) + print('=' * 80, file=file) + + def max_cooperative_grid_blocks(self, blockdim, dynsmemsize=0): + ''' + Calculates the maximum number of blocks that can be launched for this + kernel in a cooperative grid in the current context, for the given block + and dynamic shared memory sizes. + + :param blockdim: Block dimensions, either as a scalar for a 1D block, or + a tuple for 2D or 3D blocks. + :param dynsmemsize: Dynamic shared memory size in bytes. + :return: The maximum number of blocks in the grid. + ''' + ctx = get_context() + cufunc = self._codelibrary.get_cufunc() + + if isinstance(blockdim, tuple): + blockdim = functools.reduce(lambda x, y: x * y, blockdim) + active_per_sm = ctx.get_active_blocks_per_multiprocessor(cufunc, + blockdim, + dynsmemsize) + sm_count = ctx.device.MULTIPROCESSOR_COUNT + return active_per_sm * sm_count + + def launch(self, args, griddim, blockdim, stream=0, sharedmem=0): + # Prepare kernel + cufunc = self._codelibrary.get_cufunc() + + if self.debug: + excname = cufunc.name + "__errcode__" + excmem, excsz = cufunc.module.get_global_symbol(excname) + assert excsz == ctypes.sizeof(ctypes.c_int) + excval = ctypes.c_int() + excmem.memset(0, stream=stream) + + # Prepare arguments + retr = [] # hold functors for writeback + + kernelargs = [] + for t, v in zip(self.argument_types, args): + self._prepare_args(t, v, stream, retr, kernelargs) + + if driver.USE_NV_BINDING: + zero_stream = driver.binding.CUstream(0) + else: + zero_stream = None + + stream_handle = stream and stream.handle or zero_stream + + # Invoke kernel + driver.launch_kernel(cufunc.handle, + *griddim, + *blockdim, + sharedmem, + stream_handle, + kernelargs, + cooperative=self.cooperative) + + if self.debug: + driver.device_to_host(ctypes.addressof(excval), excmem, excsz) + if excval.value != 0: + # An error occurred + def load_symbol(name): + mem, sz = cufunc.module.get_global_symbol("%s__%s__" % + (cufunc.name, + name)) + val = ctypes.c_int() + driver.device_to_host(ctypes.addressof(val), mem, sz) + return val.value + + tid = [load_symbol("tid" + i) for i in 'zyx'] + ctaid = [load_symbol("ctaid" + i) for i in 'zyx'] + code = excval.value + exccls, exc_args, loc = self.call_helper.get_exception(code) + # Prefix the exception message with the source location + if loc is None: + locinfo = '' + else: + sym, filepath, lineno = loc + filepath = os.path.abspath(filepath) + locinfo = 'In function %r, file %s, line %s, ' % (sym, + filepath, + lineno,) + # Prefix the exception message with the thread position + prefix = "%stid=%s ctaid=%s" % (locinfo, tid, ctaid) + if exc_args: + exc_args = ("%s: %s" % (prefix, exc_args[0]),) + \ + exc_args[1:] + else: + exc_args = prefix, + raise exccls(*exc_args) + + # retrieve auto converted arrays + for wb in retr: + wb() + + def _prepare_args(self, ty, val, stream, retr, kernelargs): + """ + Convert arguments to ctypes and append to kernelargs + """ + + # map the arguments using any extension you've registered + for extension in reversed(self.extensions): + ty, val = extension.prepare_args( + ty, + val, + stream=stream, + retr=retr) + + if isinstance(ty, types.Array): + devary = wrap_arg(val).to_device(retr, stream) + + c_intp = ctypes.c_ssize_t + + meminfo = ctypes.c_void_p(0) + parent = ctypes.c_void_p(0) + nitems = c_intp(devary.size) + itemsize = c_intp(devary.dtype.itemsize) + + ptr = driver.device_pointer(devary) + + if driver.USE_NV_BINDING: + ptr = int(ptr) + + data = ctypes.c_void_p(ptr) + + kernelargs.append(meminfo) + kernelargs.append(parent) + kernelargs.append(nitems) + kernelargs.append(itemsize) + kernelargs.append(data) + for ax in range(devary.ndim): + kernelargs.append(c_intp(devary.shape[ax])) + for ax in range(devary.ndim): + kernelargs.append(c_intp(devary.strides[ax])) + + elif isinstance(ty, types.Integer): + cval = getattr(ctypes, "c_%s" % ty)(val) + kernelargs.append(cval) + + elif ty == types.float16: + cval = ctypes.c_uint16(np.float16(val).view(np.uint16)) + kernelargs.append(cval) + + elif ty == types.float64: + cval = ctypes.c_double(val) + kernelargs.append(cval) + + elif ty == types.float32: + cval = ctypes.c_float(val) + kernelargs.append(cval) + + elif ty == types.boolean: + cval = ctypes.c_uint8(int(val)) + kernelargs.append(cval) + + elif ty == types.complex64: + kernelargs.append(ctypes.c_float(val.real)) + kernelargs.append(ctypes.c_float(val.imag)) + + elif ty == types.complex128: + kernelargs.append(ctypes.c_double(val.real)) + kernelargs.append(ctypes.c_double(val.imag)) + + elif isinstance(ty, (types.NPDatetime, types.NPTimedelta)): + kernelargs.append(ctypes.c_int64(val.view(np.int64))) + + elif isinstance(ty, types.Record): + devrec = wrap_arg(val).to_device(retr, stream) + ptr = devrec.device_ctypes_pointer + if driver.USE_NV_BINDING: + ptr = ctypes.c_void_p(int(ptr)) + kernelargs.append(ptr) + + elif isinstance(ty, types.BaseTuple): + assert len(ty) == len(val) + for t, v in zip(ty, val): + self._prepare_args(t, v, stream, retr, kernelargs) + + elif isinstance(ty, types.EnumMember): + try: + self._prepare_args( + ty.dtype, val.value, stream, retr, kernelargs + ) + except NotImplementedError: + raise NotImplementedError(ty, val) + + else: + raise NotImplementedError(ty, val) + + +class ForAll(object): + def __init__(self, dispatcher, ntasks, tpb, stream, sharedmem): + if ntasks < 0: + raise ValueError("Can't create ForAll with negative task count: %s" + % ntasks) + self.dispatcher = dispatcher + self.ntasks = ntasks + self.thread_per_block = tpb + self.stream = stream + self.sharedmem = sharedmem + + def __call__(self, *args): + if self.ntasks == 0: + return + + if self.dispatcher.specialized: + specialized = self.dispatcher + else: + specialized = self.dispatcher.specialize(*args) + blockdim = self._compute_thread_per_block(specialized) + griddim = (self.ntasks + blockdim - 1) // blockdim + + return specialized[griddim, blockdim, self.stream, + self.sharedmem](*args) + + def _compute_thread_per_block(self, dispatcher): + tpb = self.thread_per_block + # Prefer user-specified config + if tpb != 0: + return tpb + # Else, ask the driver to give a good config + else: + ctx = get_context() + # Dispatcher is specialized, so there's only one definition - get + # it so we can get the cufunc from the code library + kernel = next(iter(dispatcher.overloads.values())) + kwargs = dict( + func=kernel._codelibrary.get_cufunc(), + b2d_func=0, # dynamic-shared memory is constant to blksz + memsize=self.sharedmem, + blocksizelimit=1024, + ) + _, tpb = ctx.get_max_potential_block_size(**kwargs) + return tpb + + +class _LaunchConfiguration: + def __init__(self, dispatcher, griddim, blockdim, stream, sharedmem): + self.dispatcher = dispatcher + self.griddim = griddim + self.blockdim = blockdim + self.stream = stream + self.sharedmem = sharedmem + + if config.CUDA_LOW_OCCUPANCY_WARNINGS: + # Warn when the grid has fewer than 128 blocks. This number is + # chosen somewhat heuristically - ideally the minimum is 2 times + # the number of SMs, but the number of SMs varies between devices - + # some very small GPUs might only have 4 SMs, but an H100-SXM5 has + # 132. In general kernels should be launched with large grids + # (hundreds or thousands of blocks), so warning when fewer than 128 + # blocks are used will likely catch most beginner errors, where the + # grid tends to be very small (single-digit or low tens of blocks). + min_grid_size = 128 + grid_size = griddim[0] * griddim[1] * griddim[2] + if grid_size < min_grid_size: + msg = (f"Grid size {grid_size} will likely result in GPU " + "under-utilization due to low occupancy.") + warn(NumbaPerformanceWarning(msg)) + + def __call__(self, *args): + return self.dispatcher.call(args, self.griddim, self.blockdim, + self.stream, self.sharedmem) + + +class CUDACacheImpl(CacheImpl): + def reduce(self, kernel): + return kernel._reduce_states() + + def rebuild(self, target_context, payload): + return _Kernel._rebuild(**payload) + + def check_cachable(self, cres): + # CUDA Kernels are always cachable - the reasons for an entity not to + # be cachable are: + # + # - The presence of lifted loops, or + # - The presence of dynamic globals. + # + # neither of which apply to CUDA kernels. + return True + + +class CUDACache(Cache): + """ + Implements a cache that saves and loads CUDA kernels and compile results. + """ + _impl_class = CUDACacheImpl + + def load_overload(self, sig, target_context): + # Loading an overload refreshes the context to ensure it is + # initialized. To initialize the correct (i.e. CUDA) target, we need to + # enforce that the current target is the CUDA target. + from numba.core.target_extension import target_override + with target_override('cuda'): + return super().load_overload(sig, target_context) + + +class CUDADispatcher(Dispatcher, serialize.ReduceMixin): + ''' + CUDA Dispatcher object. When configured and called, the dispatcher will + specialize itself for the given arguments (if no suitable specialized + version already exists) & compute capability, and launch on the device + associated with the current context. + + Dispatcher objects are not to be constructed by the user, but instead are + created using the :func:`numba.cuda.jit` decorator. + ''' + + # Whether to fold named arguments and default values. Default values are + # presently unsupported on CUDA, so we can leave this as False in all + # cases. + _fold_args = False + + targetdescr = cuda_target + + def __init__(self, py_func, targetoptions, pipeline_class=CUDACompiler): + super().__init__(py_func, targetoptions=targetoptions, + pipeline_class=pipeline_class) + + # The following properties are for specialization of CUDADispatchers. A + # specialized CUDADispatcher is one that is compiled for exactly one + # set of argument types, and bypasses some argument type checking for + # faster kernel launches. + + # Is this a specialized dispatcher? + self._specialized = False + + # If we produced specialized dispatchers, we cache them for each set of + # argument types + self.specializations = {} + + @property + def _numba_type_(self): + return cuda_types.CUDADispatcher(self) + + def enable_caching(self): + self._cache = CUDACache(self.py_func) + + @functools.lru_cache(maxsize=128) + def configure(self, griddim, blockdim, stream=0, sharedmem=0): + griddim, blockdim = normalize_kernel_dimensions(griddim, blockdim) + return _LaunchConfiguration(self, griddim, blockdim, stream, sharedmem) + + def __getitem__(self, args): + if len(args) not in [2, 3, 4]: + raise ValueError('must specify at least the griddim and blockdim') + return self.configure(*args) + + def forall(self, ntasks, tpb=0, stream=0, sharedmem=0): + """Returns a 1D-configured dispatcher for a given number of tasks. + + This assumes that: + + - the kernel maps the Global Thread ID ``cuda.grid(1)`` to tasks on a + 1-1 basis. + - the kernel checks that the Global Thread ID is upper-bounded by + ``ntasks``, and does nothing if it is not. + + :param ntasks: The number of tasks. + :param tpb: The size of a block. An appropriate value is chosen if this + parameter is not supplied. + :param stream: The stream on which the configured dispatcher will be + launched. + :param sharedmem: The number of bytes of dynamic shared memory required + by the kernel. + :return: A configured dispatcher, ready to launch on a set of + arguments.""" + + return ForAll(self, ntasks, tpb=tpb, stream=stream, sharedmem=sharedmem) + + @property + def extensions(self): + ''' + A list of objects that must have a `prepare_args` function. When a + specialized kernel is called, each argument will be passed through + to the `prepare_args` (from the last object in this list to the + first). The arguments to `prepare_args` are: + + - `ty` the numba type of the argument + - `val` the argument value itself + - `stream` the CUDA stream used for the current call to the kernel + - `retr` a list of zero-arg functions that you may want to append + post-call cleanup work to. + + The `prepare_args` function must return a tuple `(ty, val)`, which + will be passed in turn to the next right-most `extension`. After all + the extensions have been called, the resulting `(ty, val)` will be + passed into Numba's default argument marshalling logic. + ''' + return self.targetoptions.get('extensions') + + def __call__(self, *args, **kwargs): + # An attempt to launch an unconfigured kernel + raise ValueError(missing_launch_config_msg) + + def call(self, args, griddim, blockdim, stream, sharedmem): + ''' + Compile if necessary and invoke this kernel with *args*. + ''' + if self.specialized: + kernel = next(iter(self.overloads.values())) + else: + kernel = _dispatcher.Dispatcher._cuda_call(self, *args) + + kernel.launch(args, griddim, blockdim, stream, sharedmem) + + def _compile_for_args(self, *args, **kws): + # Based on _DispatcherBase._compile_for_args. + assert not kws + argtypes = [self.typeof_pyval(a) for a in args] + return self.compile(tuple(argtypes)) + + def typeof_pyval(self, val): + # Based on _DispatcherBase.typeof_pyval, but differs from it to support + # the CUDA Array Interface. + try: + return typeof(val, Purpose.argument) + except (NumbaValueError, ValueError): + if cuda.is_cuda_array(val): + # When typing, we don't need to synchronize on the array's + # stream - this is done when the kernel is launched. + return typeof(cuda.as_cuda_array(val, sync=False), + Purpose.argument) + else: + raise + + def specialize(self, *args): + ''' + Create a new instance of this dispatcher specialized for the given + *args*. + ''' + if self.specialized: + raise RuntimeError('Dispatcher already specialized') + + cc = get_current_device().compute_capability + argtypes = tuple(self.typeof_pyval(a) for a in args) + + specialization = self.specializations.get((cc, argtypes)) + if specialization: + return specialization + + targetoptions = self.targetoptions + specialization = CUDADispatcher(self.py_func, + targetoptions=targetoptions) + specialization.compile(argtypes) + specialization.disable_compile() + specialization._specialized = True + self.specializations[cc, argtypes] = specialization + return specialization + + @property + def specialized(self): + """ + True if the Dispatcher has been specialized. + """ + return self._specialized + + def get_regs_per_thread(self, signature=None): + ''' + Returns the number of registers used by each thread in this kernel for + the device in the current context. + + :param signature: The signature of the compiled kernel to get register + usage for. This may be omitted for a specialized + kernel. + :return: The number of registers used by the compiled variant of the + kernel for the given signature and current device. + ''' + if signature is not None: + return self.overloads[signature.args].regs_per_thread + if self.specialized: + return next(iter(self.overloads.values())).regs_per_thread + else: + return {sig: overload.regs_per_thread + for sig, overload in self.overloads.items()} + + def get_const_mem_size(self, signature=None): + ''' + Returns the size in bytes of constant memory used by this kernel for + the device in the current context. + + :param signature: The signature of the compiled kernel to get constant + memory usage for. This may be omitted for a + specialized kernel. + :return: The size in bytes of constant memory allocated by the + compiled variant of the kernel for the given signature and + current device. + ''' + if signature is not None: + return self.overloads[signature.args].const_mem_size + if self.specialized: + return next(iter(self.overloads.values())).const_mem_size + else: + return {sig: overload.const_mem_size + for sig, overload in self.overloads.items()} + + def get_shared_mem_per_block(self, signature=None): + ''' + Returns the size in bytes of statically allocated shared memory + for this kernel. + + :param signature: The signature of the compiled kernel to get shared + memory usage for. This may be omitted for a + specialized kernel. + :return: The amount of shared memory allocated by the compiled variant + of the kernel for the given signature and current device. + ''' + if signature is not None: + return self.overloads[signature.args].shared_mem_per_block + if self.specialized: + return next(iter(self.overloads.values())).shared_mem_per_block + else: + return {sig: overload.shared_mem_per_block + for sig, overload in self.overloads.items()} + + def get_max_threads_per_block(self, signature=None): + ''' + Returns the maximum allowable number of threads per block + for this kernel. Exceeding this threshold will result in + the kernel failing to launch. + + :param signature: The signature of the compiled kernel to get the max + threads per block for. This may be omitted for a + specialized kernel. + :return: The maximum allowable threads per block for the compiled + variant of the kernel for the given signature and current + device. + ''' + if signature is not None: + return self.overloads[signature.args].max_threads_per_block + if self.specialized: + return next(iter(self.overloads.values())).max_threads_per_block + else: + return {sig: overload.max_threads_per_block + for sig, overload in self.overloads.items()} + + def get_local_mem_per_thread(self, signature=None): + ''' + Returns the size in bytes of local memory per thread + for this kernel. + + :param signature: The signature of the compiled kernel to get local + memory usage for. This may be omitted for a + specialized kernel. + :return: The amount of local memory allocated by the compiled variant + of the kernel for the given signature and current device. + ''' + if signature is not None: + return self.overloads[signature.args].local_mem_per_thread + if self.specialized: + return next(iter(self.overloads.values())).local_mem_per_thread + else: + return {sig: overload.local_mem_per_thread + for sig, overload in self.overloads.items()} + + def get_call_template(self, args, kws): + # Originally copied from _DispatcherBase.get_call_template. This + # version deviates slightly from the _DispatcherBase version in order + # to force casts when calling device functions. See e.g. + # TestDeviceFunc.test_device_casting, added in PR #7496. + """ + Get a typing.ConcreteTemplate for this dispatcher and the given + *args* and *kws* types. This allows resolution of the return type. + + A (template, pysig, args, kws) tuple is returned. + """ + # Ensure an exactly-matching overload is available if we can + # compile. We proceed with the typing even if we can't compile + # because we may be able to force a cast on the caller side. + if self._can_compile: + self.compile_device(tuple(args)) + + # Create function type for typing + func_name = self.py_func.__name__ + name = "CallTemplate({0})".format(func_name) + + call_template = typing.make_concrete_template( + name, key=func_name, signatures=self.nopython_signatures) + pysig = utils.pysignature(self.py_func) + + return call_template, pysig, args, kws + + def compile_device(self, args, return_type=None): + """Compile the device function for the given argument types. + + Each signature is compiled once by caching the compiled function inside + this object. + + Returns the `CompileResult`. + """ + if args not in self.overloads: + with self._compiling_counter: + + debug = self.targetoptions.get('debug') + lineinfo = self.targetoptions.get('lineinfo') + inline = self.targetoptions.get('inline') + fastmath = self.targetoptions.get('fastmath') + + nvvm_options = { + 'opt': 3 if self.targetoptions.get('opt') else 0, + 'fastmath': fastmath + } + + cc = get_current_device().compute_capability + cres = compile_cuda(self.py_func, return_type, args, + debug=debug, + lineinfo=lineinfo, + inline=inline, + fastmath=fastmath, + nvvm_options=nvvm_options, + cc=cc) + self.overloads[args] = cres + + cres.target_context.insert_user_function(cres.entry_point, + cres.fndesc, + [cres.library]) + else: + cres = self.overloads[args] + + return cres + + def add_overload(self, kernel, argtypes): + c_sig = [a._code for a in argtypes] + self._insert(c_sig, kernel, cuda=True) + self.overloads[argtypes] = kernel + + def compile(self, sig): + ''' + Compile and bind to the current context a version of this kernel + specialized for the given signature. + ''' + argtypes, return_type = sigutils.normalize_signature(sig) + assert return_type is None or return_type == types.none + + # Do we already have an in-memory compiled kernel? + if self.specialized: + return next(iter(self.overloads.values())) + else: + kernel = self.overloads.get(argtypes) + if kernel is not None: + return kernel + + # Can we load from the disk cache? + kernel = self._cache.load_overload(sig, self.targetctx) + + if kernel is not None: + self._cache_hits[sig] += 1 + else: + # We need to compile a new kernel + self._cache_misses[sig] += 1 + if not self._can_compile: + raise RuntimeError("Compilation disabled") + + kernel = _Kernel(self.py_func, argtypes, **self.targetoptions) + # We call bind to force codegen, so that there is a cubin to cache + kernel.bind() + self._cache.save_overload(sig, kernel) + + self.add_overload(kernel, argtypes) + + return kernel + + def inspect_llvm(self, signature=None): + ''' + Return the LLVM IR for this kernel. + + :param signature: A tuple of argument types. + :return: The LLVM IR for the given signature, or a dict of LLVM IR + for all previously-encountered signatures. + + ''' + device = self.targetoptions.get('device') + if signature is not None: + if device: + return self.overloads[signature].library.get_llvm_str() + else: + return self.overloads[signature].inspect_llvm() + else: + if device: + return {sig: overload.library.get_llvm_str() + for sig, overload in self.overloads.items()} + else: + return {sig: overload.inspect_llvm() + for sig, overload in self.overloads.items()} + + def inspect_asm(self, signature=None): + ''' + Return this kernel's PTX assembly code for for the device in the + current context. + + :param signature: A tuple of argument types. + :return: The PTX code for the given signature, or a dict of PTX codes + for all previously-encountered signatures. + ''' + cc = get_current_device().compute_capability + device = self.targetoptions.get('device') + if signature is not None: + if device: + return self.overloads[signature].library.get_asm_str(cc) + else: + return self.overloads[signature].inspect_asm(cc) + else: + if device: + return {sig: overload.library.get_asm_str(cc) + for sig, overload in self.overloads.items()} + else: + return {sig: overload.inspect_asm(cc) + for sig, overload in self.overloads.items()} + + def inspect_sass_cfg(self, signature=None): + ''' + Return this kernel's CFG for the device in the current context. + + :param signature: A tuple of argument types. + :return: The CFG for the given signature, or a dict of CFGs + for all previously-encountered signatures. + + The CFG for the device in the current context is returned. + + Requires nvdisasm to be available on the PATH. + ''' + if self.targetoptions.get('device'): + raise RuntimeError('Cannot get the CFG of a device function') + + if signature is not None: + return self.overloads[signature].inspect_sass_cfg() + else: + return {sig: defn.inspect_sass_cfg() + for sig, defn in self.overloads.items()} + + def inspect_sass(self, signature=None): + ''' + Return this kernel's SASS assembly code for for the device in the + current context. + + :param signature: A tuple of argument types. + :return: The SASS code for the given signature, or a dict of SASS codes + for all previously-encountered signatures. + + SASS for the device in the current context is returned. + + Requires nvdisasm to be available on the PATH. + ''' + if self.targetoptions.get('device'): + raise RuntimeError('Cannot inspect SASS of a device function') + + if signature is not None: + return self.overloads[signature].inspect_sass() + else: + return {sig: defn.inspect_sass() + for sig, defn in self.overloads.items()} + + def inspect_types(self, file=None): + ''' + Produce a dump of the Python source of this function annotated with the + corresponding Numba IR and type information. The dump is written to + *file*, or *sys.stdout* if *file* is *None*. + ''' + if file is None: + file = sys.stdout + + for _, defn in self.overloads.items(): + defn.inspect_types(file=file) + + @classmethod + def _rebuild(cls, py_func, targetoptions): + """ + Rebuild an instance. + """ + instance = cls(py_func, targetoptions) + return instance + + def _reduce_states(self): + """ + Reduce the instance for serialization. + Compiled definitions are discarded. + """ + return dict(py_func=self.py_func, + targetoptions=self.targetoptions) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/errors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..653a0db6ef2f80e50aebc14c6c576fe3570606ee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/errors.py @@ -0,0 +1,59 @@ +import numbers +from numba.core.errors import LoweringError + + +class KernelRuntimeError(RuntimeError): + def __init__(self, msg, tid=None, ctaid=None): + self.tid = tid + self.ctaid = ctaid + self.msg = msg + t = ("An exception was raised in thread=%s block=%s\n" + "\t%s") + msg = t % (self.tid, self.ctaid, self.msg) + super(KernelRuntimeError, self).__init__(msg) + + +class CudaLoweringError(LoweringError): + pass + + +_launch_help_url = ("https://numba.readthedocs.io/en/stable/cuda/" + "kernels.html#kernel-invocation") +missing_launch_config_msg = """ +Kernel launch configuration was not specified. Use the syntax: + +kernel_function[blockspergrid, threadsperblock](arg0, arg1, ..., argn) + +See {} for help. + +""".format(_launch_help_url) + + +def normalize_kernel_dimensions(griddim, blockdim): + """ + Normalize and validate the user-supplied kernel dimensions. + """ + + def check_dim(dim, name): + if not isinstance(dim, (tuple, list)): + dim = [dim] + else: + dim = list(dim) + if len(dim) > 3: + raise ValueError('%s must be a sequence of 1, 2 or 3 integers, ' + 'got %r' % (name, dim)) + for v in dim: + if not isinstance(v, numbers.Integral): + raise TypeError('%s must be a sequence of integers, got %r' + % (name, dim)) + while len(dim) < 3: + dim.append(1) + return tuple(dim) + + if None in (griddim, blockdim): + raise ValueError(missing_launch_config_msg) + + griddim = check_dim(griddim, 'griddim') + blockdim = check_dim(blockdim, 'blockdim') + + return griddim, blockdim diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/extending.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/extending.py new file mode 100644 index 0000000000000000000000000000000000000000..cbc482aaac40c6ec995466581a5079ef280f9595 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/extending.py @@ -0,0 +1,7 @@ +""" +Added for symmetry with the core API +""" + +from numba.core.extending import intrinsic as _intrinsic + +intrinsic = _intrinsic(target='cuda') diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/initialize.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..e90c95b3110c65387fdd8a7a1714109ce2d05aff --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/initialize.py @@ -0,0 +1,13 @@ +def initialize_all(): + # Import models to register them with the data model manager + import numba.cuda.models # noqa: F401 + + from numba.cuda.decorators import jit + from numba.cuda.dispatcher import CUDADispatcher + from numba.core.target_extension import (target_registry, + dispatcher_registry, + jit_registry) + + cuda_target = target_registry["cuda"] + jit_registry[cuda_target] = jit + dispatcher_registry[cuda_target] = CUDADispatcher diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsic_wrapper.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsic_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..e02639f2122e2d6ca2b0c6ceecf2de63b4cf5395 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsic_wrapper.py @@ -0,0 +1,77 @@ +from .decorators import jit +import numba + + +@jit(device=True) +def all_sync(mask, predicate): + """ + If for all threads in the masked warp the predicate is true, then + a non-zero value is returned, otherwise 0 is returned. + """ + return numba.cuda.vote_sync_intrinsic(mask, 0, predicate)[1] + + +@jit(device=True) +def any_sync(mask, predicate): + """ + If for any thread in the masked warp the predicate is true, then + a non-zero value is returned, otherwise 0 is returned. + """ + return numba.cuda.vote_sync_intrinsic(mask, 1, predicate)[1] + + +@jit(device=True) +def eq_sync(mask, predicate): + """ + If for all threads in the masked warp the boolean predicate is the same, + then a non-zero value is returned, otherwise 0 is returned. + """ + return numba.cuda.vote_sync_intrinsic(mask, 2, predicate)[1] + + +@jit(device=True) +def ballot_sync(mask, predicate): + """ + Returns a mask of all threads in the warp whose predicate is true, + and are within the given mask. + """ + return numba.cuda.vote_sync_intrinsic(mask, 3, predicate)[0] + + +@jit(device=True) +def shfl_sync(mask, value, src_lane): + """ + Shuffles value across the masked warp and returns the value + from src_lane. If this is outside the warp, then the + given value is returned. + """ + return numba.cuda.shfl_sync_intrinsic(mask, 0, value, src_lane, 0x1f)[0] + + +@jit(device=True) +def shfl_up_sync(mask, value, delta): + """ + Shuffles value across the masked warp and returns the value + from (laneid - delta). If this is outside the warp, then the + given value is returned. + """ + return numba.cuda.shfl_sync_intrinsic(mask, 1, value, delta, 0)[0] + + +@jit(device=True) +def shfl_down_sync(mask, value, delta): + """ + Shuffles value across the masked warp and returns the value + from (laneid + delta). If this is outside the warp, then the + given value is returned. + """ + return numba.cuda.shfl_sync_intrinsic(mask, 2, value, delta, 0x1f)[0] + + +@jit(device=True) +def shfl_xor_sync(mask, value, lane_mask): + """ + Shuffles value across the masked warp and returns the value + from (laneid ^ lane_mask). + """ + return numba.cuda.shfl_sync_intrinsic(mask, 3, value, lane_mask, 0x1f)[0] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsics.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsics.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf0b59932c93e60e716bc4550a683dc0e53a983 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/intrinsics.py @@ -0,0 +1,198 @@ +from llvmlite import ir + +from numba import cuda, types +from numba.core import cgutils +from numba.core.errors import RequireLiteralValue, NumbaValueError +from numba.core.typing import signature +from numba.core.extending import overload_attribute +from numba.cuda import nvvmutils +from numba.cuda.extending import intrinsic + + +#------------------------------------------------------------------------------- +# Grid functions + +def _type_grid_function(ndim): + val = ndim.literal_value + if val == 1: + restype = types.int64 + elif val in (2, 3): + restype = types.UniTuple(types.int64, val) + else: + raise NumbaValueError('argument can only be 1, 2, 3') + + return signature(restype, types.int32) + + +@intrinsic +def grid(typingctx, ndim): + '''grid(ndim) + + Return the absolute position of the current thread in the entire grid of + blocks. *ndim* should correspond to the number of dimensions declared when + instantiating the kernel. If *ndim* is 1, a single integer is returned. + If *ndim* is 2 or 3, a tuple of the given number of integers is returned. + + Computation of the first integer is as follows:: + + cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x + + and is similar for the other two indices, but using the ``y`` and ``z`` + attributes. + ''' + + if not isinstance(ndim, types.IntegerLiteral): + raise RequireLiteralValue(ndim) + + sig = _type_grid_function(ndim) + + def codegen(context, builder, sig, args): + restype = sig.return_type + if restype == types.int64: + return nvvmutils.get_global_id(builder, dim=1) + elif isinstance(restype, types.UniTuple): + ids = nvvmutils.get_global_id(builder, dim=restype.count) + return cgutils.pack_array(builder, ids) + + return sig, codegen + + +@intrinsic +def gridsize(typingctx, ndim): + '''gridsize(ndim) + + Return the absolute size (or shape) in threads of the entire grid of + blocks. *ndim* should correspond to the number of dimensions declared when + instantiating the kernel. If *ndim* is 1, a single integer is returned. + If *ndim* is 2 or 3, a tuple of the given number of integers is returned. + + Computation of the first integer is as follows:: + + cuda.blockDim.x * cuda.gridDim.x + + and is similar for the other two indices, but using the ``y`` and ``z`` + attributes. + ''' + + if not isinstance(ndim, types.IntegerLiteral): + raise RequireLiteralValue(ndim) + + sig = _type_grid_function(ndim) + + def _nthreads_for_dim(builder, dim): + i64 = ir.IntType(64) + ntid = nvvmutils.call_sreg(builder, f"ntid.{dim}") + nctaid = nvvmutils.call_sreg(builder, f"nctaid.{dim}") + return builder.mul(builder.sext(ntid, i64), builder.sext(nctaid, i64)) + + def codegen(context, builder, sig, args): + restype = sig.return_type + nx = _nthreads_for_dim(builder, 'x') + + if restype == types.int64: + return nx + elif isinstance(restype, types.UniTuple): + ny = _nthreads_for_dim(builder, 'y') + + if restype.count == 2: + return cgutils.pack_array(builder, (nx, ny)) + elif restype.count == 3: + nz = _nthreads_for_dim(builder, 'z') + return cgutils.pack_array(builder, (nx, ny, nz)) + + return sig, codegen + + +@intrinsic +def _warpsize(typingctx): + sig = signature(types.int32) + + def codegen(context, builder, sig, args): + return nvvmutils.call_sreg(builder, 'warpsize') + + return sig, codegen + + +@overload_attribute(types.Module(cuda), 'warpsize', target='cuda') +def cuda_warpsize(mod): + ''' + The size of a warp. All architectures implemented to date have a warp size + of 32. + ''' + def get(mod): + return _warpsize() + return get + + +#------------------------------------------------------------------------------- +# syncthreads + +@intrinsic +def syncthreads(typingctx): + ''' + Synchronize all threads in the same thread block. This function implements + the same pattern as barriers in traditional multi-threaded programming: this + function waits until all threads in the block call it, at which point it + returns control to all its callers. + ''' + sig = signature(types.none) + + def codegen(context, builder, sig, args): + fname = 'llvm.nvvm.barrier0' + lmod = builder.module + fnty = ir.FunctionType(ir.VoidType(), ()) + sync = cgutils.get_or_insert_function(lmod, fnty, fname) + builder.call(sync, ()) + return context.get_dummy_value() + + return sig, codegen + + +def _syncthreads_predicate(typingctx, predicate, fname): + if not isinstance(predicate, types.Integer): + return None + + sig = signature(types.i4, types.i4) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType(ir.IntType(32), (ir.IntType(32),)) + sync = cgutils.get_or_insert_function(builder.module, fnty, fname) + return builder.call(sync, args) + + return sig, codegen + + +@intrinsic +def syncthreads_count(typingctx, predicate): + ''' + syncthreads_count(predicate) + + An extension to numba.cuda.syncthreads where the return value is a count + of the threads where predicate is true. + ''' + fname = 'llvm.nvvm.barrier0.popc' + return _syncthreads_predicate(typingctx, predicate, fname) + + +@intrinsic +def syncthreads_and(typingctx, predicate): + ''' + syncthreads_and(predicate) + + An extension to numba.cuda.syncthreads where 1 is returned if predicate is + true for all threads or 0 otherwise. + ''' + fname = 'llvm.nvvm.barrier0.and' + return _syncthreads_predicate(typingctx, predicate, fname) + + +@intrinsic +def syncthreads_or(typingctx, predicate): + ''' + syncthreads_or(predicate) + + An extension to numba.cuda.syncthreads where 1 is returned if predicate is + true for any thread or 0 otherwise. + ''' + fname = 'llvm.nvvm.barrier0.or' + return _syncthreads_predicate(typingctx, predicate, fname) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevice.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..303ade74b650b6176cbd7f6590cddd5dc9c0278a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevice.py @@ -0,0 +1,3382 @@ +def abs(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_abs.html + + :param x: Argument. + :type x: int32 + :rtype: int32 +""" + + +def acos(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_acos.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def acosf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_acosf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def acosh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_acosh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def acoshf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_acoshf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def asin(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_asin.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def asinf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_asinf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def asinh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_asinh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def asinhf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_asinhf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def atan(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atan.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def atan2(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atan2.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def atan2f(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atan2f.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def atanf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atanf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def atanh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atanh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def atanhf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_atanhf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def brev(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_brev.html + + :param x: Argument. + :type x: int32 + :rtype: int32 +""" + + +def brevll(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_brevll.html + + :param x: Argument. + :type x: int64 + :rtype: int64 +""" + + +def byte_perm(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_byte_perm.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :param z: Argument. + :type z: int32 + :rtype: int32 +""" + + +def cbrt(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cbrt.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def cbrtf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cbrtf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def ceil(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ceil.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def ceilf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ceilf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def clz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_clz.html + + :param x: Argument. + :type x: int32 + :rtype: int32 +""" + + +def clzll(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_clzll.html + + :param x: Argument. + :type x: int64 + :rtype: int32 +""" + + +def copysign(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_copysign.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def copysignf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_copysignf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def cos(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cos.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def cosf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cosf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def cosh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cosh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def coshf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_coshf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def cospi(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cospi.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def cospif(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_cospif.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def dadd_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dadd_rd.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dadd_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dadd_rn.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dadd_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dadd_ru.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dadd_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dadd_rz.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def ddiv_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ddiv_rd.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def ddiv_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ddiv_rn.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def ddiv_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ddiv_ru.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def ddiv_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ddiv_rz.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dmul_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dmul_rd.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dmul_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dmul_rn.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dmul_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dmul_ru.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def dmul_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dmul_rz.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def double2float_rd(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2float_rd.html + + :param d: Argument. + :type d: float64 + :rtype: float32 +""" + + +def double2float_rn(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2float_rn.html + + :param d: Argument. + :type d: float64 + :rtype: float32 +""" + + +def double2float_ru(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2float_ru.html + + :param d: Argument. + :type d: float64 + :rtype: float32 +""" + + +def double2float_rz(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2float_rz.html + + :param d: Argument. + :type d: float64 + :rtype: float32 +""" + + +def double2hiint(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2hiint.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2int_rd(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2int_rd.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2int_rn(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2int_rn.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2int_ru(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2int_ru.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2int_rz(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2int_rz.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2ll_rd(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ll_rd.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ll_rn(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ll_rn.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ll_ru(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ll_ru.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ll_rz(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ll_rz.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2loint(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2loint.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2uint_rd(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2uint_rd.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2uint_rn(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2uint_rn.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2uint_ru(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2uint_ru.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2uint_rz(d): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2uint_rz.html + + :param d: Argument. + :type d: float64 + :rtype: int32 +""" + + +def double2ull_rd(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ull_rd.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ull_rn(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ull_rn.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ull_ru(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ull_ru.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double2ull_rz(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double2ull_rz.html + + :param f: Argument. + :type f: float64 + :rtype: int64 +""" + + +def double_as_longlong(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_double_as_longlong.html + + :param x: Argument. + :type x: float64 + :rtype: int64 +""" + + +def drcp_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_drcp_rd.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def drcp_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_drcp_rn.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def drcp_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_drcp_ru.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def drcp_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_drcp_rz.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def dsqrt_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dsqrt_rd.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def dsqrt_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dsqrt_rn.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def dsqrt_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dsqrt_ru.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def dsqrt_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_dsqrt_rz.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erf.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erfc(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfc.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erfcf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfcf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def erfcinv(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfcinv.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erfcinvf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfcinvf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def erfcx(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfcx.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erfcxf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfcxf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def erff(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erff.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def erfinv(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfinv.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def erfinvf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_erfinvf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def exp(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_exp.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def exp10(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_exp10.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def exp10f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_exp10f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def exp2(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_exp2.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def exp2f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_exp2f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def expf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_expf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def expm1(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_expm1.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def expm1f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_expm1f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fabs(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fabs.html + + :param f: Argument. + :type f: float64 + :rtype: float64 +""" + + +def fabsf(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fabsf.html + + :param f: Argument. + :type f: float32 + :rtype: float32 +""" + + +def fadd_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fadd_rd.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fadd_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fadd_rn.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fadd_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fadd_ru.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fadd_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fadd_rz.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fast_cosf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_cosf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_exp10f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_exp10f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_expf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_expf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_fdividef(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_fdividef.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fast_log10f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_log10f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_log2f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_log2f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_logf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_logf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_powf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_powf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fast_sincosf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_sincosf.html + + :param x: Argument. + :type x: float32 + :rtype: UniTuple(float32 x 2) +""" + + +def fast_sinf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_sinf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fast_tanf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_tanf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fdim(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdim.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def fdimf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdimf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fdiv_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdiv_rd.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fdiv_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdiv_rn.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fdiv_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdiv_ru.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fdiv_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fdiv_rz.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def ffs(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ffs.html + + :param x: Argument. + :type x: int32 + :rtype: int32 +""" + + +def ffsll(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ffsll.html + + :param x: Argument. + :type x: int64 + :rtype: int32 +""" + + +def finitef(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_finitef.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def float2half_rn(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2half_rn.html + + :param f: Argument. + :type f: float32 + :rtype: int16 +""" + + +def float2int_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2int_rd.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2int_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2int_rn.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2int_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2int_ru.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2int_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2int_rz.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2ll_rd(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ll_rd.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ll_rn(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ll_rn.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ll_ru(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ll_ru.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ll_rz(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ll_rz.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2uint_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2uint_rd.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2uint_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2uint_rn.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2uint_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2uint_ru.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2uint_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2uint_rz.html + + :param in: Argument. + :type in: float32 + :rtype: int32 +""" + + +def float2ull_rd(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ull_rd.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ull_rn(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ull_rn.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ull_ru(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ull_ru.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float2ull_rz(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2ull_rz.html + + :param f: Argument. + :type f: float32 + :rtype: int64 +""" + + +def float_as_int(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float_as_int.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def floor(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_floor.html + + :param f: Argument. + :type f: float64 + :rtype: float64 +""" + + +def floorf(f): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_floorf.html + + :param f: Argument. + :type f: float32 + :rtype: float32 +""" + + +def fma(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :param z: Argument. + :type z: float64 + :rtype: float64 +""" + + +def fma_rd(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma_rd.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :param z: Argument. + :type z: float64 + :rtype: float64 +""" + + +def fma_rn(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma_rn.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :param z: Argument. + :type z: float64 + :rtype: float64 +""" + + +def fma_ru(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma_ru.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :param z: Argument. + :type z: float64 + :rtype: float64 +""" + + +def fma_rz(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma_rz.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :param z: Argument. + :type z: float64 + :rtype: float64 +""" + + +def fmaf(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :param z: Argument. + :type z: float32 + :rtype: float32 +""" + + +def fmaf_rd(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaf_rd.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :param z: Argument. + :type z: float32 + :rtype: float32 +""" + + +def fmaf_rn(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaf_rn.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :param z: Argument. + :type z: float32 + :rtype: float32 +""" + + +def fmaf_ru(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaf_ru.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :param z: Argument. + :type z: float32 + :rtype: float32 +""" + + +def fmaf_rz(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaf_rz.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :param z: Argument. + :type z: float32 + :rtype: float32 +""" + + +def fmax(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmax.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def fmaxf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmaxf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmin(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmin.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def fminf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fminf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmod(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmod.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def fmodf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmodf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmul_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_rd.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmul_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_rn.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmul_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_ru.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fmul_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fmul_rz.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def frcp_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rd.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def frcp_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rn.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def frcp_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_ru.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def frcp_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frcp_rz.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def frexp(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frexp.html + + :param x: Argument. + :type x: float64 + :rtype: Tuple(float64, int32) +""" + + +def frexpf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frexpf.html + + :param x: Argument. + :type x: float32 + :rtype: Tuple(float32, int32) +""" + + +def frsqrt_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_frsqrt_rn.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fsqrt_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsqrt_rd.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fsqrt_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsqrt_rn.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fsqrt_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsqrt_ru.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fsqrt_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsqrt_rz.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def fsub_rd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsub_rd.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fsub_rn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsub_rn.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fsub_ru(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsub_ru.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def fsub_rz(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fsub_rz.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def hadd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_hadd.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def half2float(h): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_half2float.html + + :param h: Argument. + :type h: int16 + :rtype: float32 +""" + + +def hiloint2double(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_hiloint2double.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: float64 +""" + + +def hypot(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_hypot.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def hypotf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_hypotf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def ilogb(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ilogb.html + + :param x: Argument. + :type x: float64 + :rtype: int32 +""" + + +def ilogbf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ilogbf.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def int2double_rn(i): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2double_rn.html + + :param i: Argument. + :type i: int32 + :rtype: float64 +""" + + +def int2float_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2float_rd.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def int2float_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2float_rn.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def int2float_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2float_ru.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def int2float_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int2float_rz.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def int_as_float(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_int_as_float.html + + :param x: Argument. + :type x: int32 + :rtype: float32 +""" + + +def isfinited(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_isfinited.html + + :param x: Argument. + :type x: float64 + :rtype: int32 +""" + + +def isinfd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_isinfd.html + + :param x: Argument. + :type x: float64 + :rtype: int32 +""" + + +def isinff(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_isinff.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def isnand(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_isnand.html + + :param x: Argument. + :type x: float64 + :rtype: int32 +""" + + +def isnanf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_isnanf.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def j0(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_j0.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def j0f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_j0f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def j1(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_j1.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def j1f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_j1f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def jn(n, x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_jn.html + + :param n: Argument. + :type n: int32 + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def jnf(n, x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_jnf.html + + :param n: Argument. + :type n: int32 + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def ldexp(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ldexp.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: int32 + :rtype: float64 +""" + + +def ldexpf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ldexpf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: int32 + :rtype: float32 +""" + + +def lgamma(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_lgamma.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def lgammaf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_lgammaf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def ll2double_rd(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2double_rd.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ll2double_rn(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2double_rn.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ll2double_ru(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2double_ru.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ll2double_rz(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2double_rz.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ll2float_rd(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2float_rd.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ll2float_rn(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2float_rn.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ll2float_ru(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2float_ru.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ll2float_rz(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ll2float_rz.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def llabs(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llabs.html + + :param x: Argument. + :type x: int64 + :rtype: int64 +""" + + +def llmax(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llmax.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def llmin(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llmin.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def llrint(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llrint.html + + :param x: Argument. + :type x: float64 + :rtype: int64 +""" + + +def llrintf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llrintf.html + + :param x: Argument. + :type x: float32 + :rtype: int64 +""" + + +def llround(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llround.html + + :param x: Argument. + :type x: float64 + :rtype: int64 +""" + + +def llroundf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_llroundf.html + + :param x: Argument. + :type x: float32 + :rtype: int64 +""" + + +def log(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def log10(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log10.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def log10f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log10f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def log1p(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log1p.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def log1pf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log1pf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def log2(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log2.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def log2f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_log2f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def logb(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_logb.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def logbf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_logbf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def logf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_logf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def longlong_as_double(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_longlong_as_double.html + + :param x: Argument. + :type x: int64 + :rtype: float64 +""" + + +def max(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_max.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def min(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_min.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def modf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_modf.html + + :param x: Argument. + :type x: float64 + :rtype: UniTuple(float64 x 2) +""" + + +def modff(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_modff.html + + :param x: Argument. + :type x: float32 + :rtype: UniTuple(float32 x 2) +""" + + +def mul24(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_mul24.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def mul64hi(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_mul64hi.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def mulhi(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_mulhi.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def nearbyint(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_nearbyint.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def nearbyintf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_nearbyintf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def nextafter(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_nextafter.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def nextafterf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_nextafterf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def normcdf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_normcdf.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def normcdff(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_normcdff.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def normcdfinv(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_normcdfinv.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def normcdfinvf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_normcdfinvf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def popc(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_popc.html + + :param x: Argument. + :type x: int32 + :rtype: int32 +""" + + +def popcll(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_popcll.html + + :param x: Argument. + :type x: int64 + :rtype: int32 +""" + + +def pow(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_pow.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def powf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_powf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def powi(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_powi.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: int32 + :rtype: float64 +""" + + +def powif(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_powif.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: int32 + :rtype: float32 +""" + + +def rcbrt(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rcbrt.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def rcbrtf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rcbrtf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def remainder(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_remainder.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: float64 +""" + + +def remainderf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_remainderf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: float32 +""" + + +def remquo(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_remquo.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: float64 + :rtype: Tuple(float64, int32) +""" + + +def remquof(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_remquof.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: float32 + :rtype: Tuple(float32, int32) +""" + + +def rhadd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rhadd.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def rint(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rint.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def rintf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rintf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def round(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_round.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def roundf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_roundf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def rsqrt(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rsqrt.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def rsqrtf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rsqrtf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def sad(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sad.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :param z: Argument. + :type z: int32 + :rtype: int32 +""" + + +def saturatef(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_saturatef.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def scalbn(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_scalbn.html + + :param x: Argument. + :type x: float64 + :param y: Argument. + :type y: int32 + :rtype: float64 +""" + + +def scalbnf(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_scalbnf.html + + :param x: Argument. + :type x: float32 + :param y: Argument. + :type y: int32 + :rtype: float32 +""" + + +def signbitd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_signbitd.html + + :param x: Argument. + :type x: float64 + :rtype: int32 +""" + + +def signbitf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_signbitf.html + + :param x: Argument. + :type x: float32 + :rtype: int32 +""" + + +def sin(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sin.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def sincos(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sincos.html + + :param x: Argument. + :type x: float64 + :rtype: UniTuple(float64 x 2) +""" + + +def sincosf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sincosf.html + + :param x: Argument. + :type x: float32 + :rtype: UniTuple(float32 x 2) +""" + + +def sincospi(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sincospi.html + + :param x: Argument. + :type x: float64 + :rtype: UniTuple(float64 x 2) +""" + + +def sincospif(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sincospif.html + + :param x: Argument. + :type x: float32 + :rtype: UniTuple(float32 x 2) +""" + + +def sinf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sinf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def sinh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sinh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def sinhf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sinhf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def sinpi(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sinpi.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def sinpif(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sinpif.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def sqrt(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sqrt.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def sqrtf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_sqrtf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def tan(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tan.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def tanf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tanf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def tanh(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tanh.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def tanhf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tanhf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def tgamma(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tgamma.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def tgammaf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_tgammaf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def trunc(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_trunc.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def truncf(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_truncf.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def uhadd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uhadd.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def uint2double_rn(i): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uint2double_rn.html + + :param i: Argument. + :type i: int32 + :rtype: float64 +""" + + +def uint2float_rd(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uint2float_rd.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def uint2float_rn(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uint2float_rn.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def uint2float_ru(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uint2float_ru.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def uint2float_rz(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_uint2float_rz.html + + :param in: Argument. + :type in: int32 + :rtype: float32 +""" + + +def ull2double_rd(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2double_rd.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ull2double_rn(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2double_rn.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ull2double_ru(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2double_ru.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ull2double_rz(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2double_rz.html + + :param l: Argument. + :type l: int64 + :rtype: float64 +""" + + +def ull2float_rd(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2float_rd.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ull2float_rn(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2float_rn.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ull2float_ru(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2float_ru.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ull2float_rz(l): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ull2float_rz.html + + :param l: Argument. + :type l: int64 + :rtype: float32 +""" + + +def ullmax(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ullmax.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def ullmin(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ullmin.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def umax(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_umax.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def umin(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_umin.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def umul24(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_umul24.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def umul64hi(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_umul64hi.html + + :param x: Argument. + :type x: int64 + :param y: Argument. + :type y: int64 + :rtype: int64 +""" + + +def umulhi(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_umulhi.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def urhadd(x, y): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_urhadd.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :rtype: int32 +""" + + +def usad(x, y, z): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_usad.html + + :param x: Argument. + :type x: int32 + :param y: Argument. + :type y: int32 + :param z: Argument. + :type z: int32 + :rtype: int32 +""" + + +def y0(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_y0.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def y0f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_y0f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def y1(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_y1.html + + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def y1f(x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_y1f.html + + :param x: Argument. + :type x: float32 + :rtype: float32 +""" + + +def yn(n, x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_yn.html + + :param n: Argument. + :type n: int32 + :param x: Argument. + :type x: float64 + :rtype: float64 +""" + + +def ynf(n, x): + """ + See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_ynf.html + + :param n: Argument. + :type n: int32 + :param x: Argument. + :type x: float32 + :rtype: float32 +""" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicedecl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicedecl.py new file mode 100644 index 0000000000000000000000000000000000000000..e82646dca585232ec86496875d5dc3e00a940ccc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicedecl.py @@ -0,0 +1,17 @@ +from numba.cuda import libdevice, libdevicefuncs +from numba.core.typing.templates import ConcreteTemplate, Registry + +registry = Registry() +register_global = registry.register_global + + +def libdevice_declare(func, retty, args): + class Libdevice_function(ConcreteTemplate): + cases = [libdevicefuncs.create_signature(retty, args)] + + pyfunc = getattr(libdevice, func[5:]) + register_global(pyfunc)(Libdevice_function) + + +for func, (retty, args) in libdevicefuncs.functions.items(): + libdevice_declare(func, retty, args) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicefuncs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicefuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bb5accaa55cb96bb369350eaf80bf356ddd89 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdevicefuncs.py @@ -0,0 +1,1057 @@ +from collections import namedtuple +from textwrap import indent + +from numba.types import float32, float64, int16, int32, int64, void, Tuple +from numba.core.typing.templates import signature + +arg = namedtuple("arg", ("name", "ty", "is_ptr")) + +functions = { + "__nv_abs": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_acos": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_acosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_acosh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_acoshf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_asin": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_asinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_asinh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_asinhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_atan": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_atan2": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_atan2f": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_atanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_atanh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_atanhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_brev": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_brevll": (int64, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_byte_perm": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_cbrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cbrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_ceil": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_ceilf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_clz": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_clzll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_copysign": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_copysignf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_cos": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_cosh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_coshf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_cospi": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_cospif": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_dadd_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dadd_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_ddiv_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_dmul_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_double2float_rd": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_rn": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_ru": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2float_rz": ( + float32, + [arg(name="d", ty=float64, is_ptr=False)], + ), + "__nv_double2hiint": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rd": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rn": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_ru": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2int_rz": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2ll_rd": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_rn": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_ru": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ll_rz": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2loint": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rd": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rn": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_ru": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2uint_rz": (int32, [arg(name="d", ty=float64, is_ptr=False)]), + "__nv_double2ull_rd": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_rn": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_ru": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double2ull_rz": (int64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_double_as_longlong": ( + int64, + [arg(name="x", ty=float64, is_ptr=False)], + ), + "__nv_drcp_rd": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_rn": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_ru": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_drcp_rz": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rd": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rn": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_ru": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_dsqrt_rz": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erf": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfc": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfcinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfcx": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfcxf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erff": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_erfinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_erfinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_exp": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp10": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_exp2": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_exp2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_expf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_expm1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_expm1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fabs": (float64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_fabsf": (float32, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_fadd_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fadd_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_cosf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_exp10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_expf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_fdividef": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_log10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_log2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_logf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_powf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fast_sincosf": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_fast_sinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fast_tanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fdim": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fdimf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fdiv_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_ffs": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_ffsll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_finitef": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_float2half_rn": (int16, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2int_rd": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_rn": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_ru": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2int_rz": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2ll_rd": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_rn": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_ru": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ll_rz": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2uint_rd": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_rn": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_ru": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2uint_rz": (int32, [arg(name="in", ty=float32, is_ptr=False)]), + "__nv_float2ull_rd": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_rn": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_ru": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float2ull_rz": (int64, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_float_as_int": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_floor": (float64, [arg(name="f", ty=float64, is_ptr=False)]), + "__nv_floorf": (float32, [arg(name="f", ty=float32, is_ptr=False)]), + "__nv_fma": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rd": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_ru": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fma_rz": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="z", ty=float64, is_ptr=False), + ], + ), + "__nv_fmaf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmaf_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="z", ty=float32, is_ptr=False), + ], + ), + "__nv_fmax": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fmaxf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmin": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fminf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmod": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_fmodf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fmul_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_frcp_rd": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_ru": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frcp_rz": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_frexp": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="b", ty=int32, is_ptr=True), + ], + ), + "__nv_frexpf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="b", ty=int32, is_ptr=True), + ], + ), + "__nv_frsqrt_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rd": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rn": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_ru": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsqrt_rz": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_fsub_rd": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_rn": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_ru": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_fsub_rz": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_hadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_half2float": (float32, [arg(name="h", ty=int16, is_ptr=False)]), + "__nv_hiloint2double": ( + float64, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_hypot": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_hypotf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_ilogb": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_ilogbf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_int2double_rn": (float64, [arg(name="i", ty=int32, is_ptr=False)]), + "__nv_int2float_rd": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_rn": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_ru": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int2float_rz": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_int_as_float": (float32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_isfinited": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isinfd": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isinff": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_isnand": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_isnanf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_j0": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_j0f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_j1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_j1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_jn": ( + float64, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float64, is_ptr=False), + ], + ), + "__nv_jnf": ( + float32, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float32, is_ptr=False), + ], + ), + "__nv_ldexp": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_ldexpf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_lgamma": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_lgammaf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_ll2double_rd": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_rn": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_ru": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2double_rz": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rd": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rn": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_ru": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ll2float_rz": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_llabs": (int64, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_llmax": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_llmin": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_llrint": (int64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_llrintf": (int64, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_llround": (int64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_llroundf": (int64, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log10": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log10f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log1p": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log1pf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_log2": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_log2f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_logb": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_logbf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_logf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_longlong_as_double": ( + float64, + [arg(name="x", ty=int64, is_ptr=False)], + ), + "__nv_max": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_min": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_modf": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="b", ty=float64, is_ptr=True), + ], + ), + "__nv_modff": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="b", ty=float32, is_ptr=True), + ], + ), + "__nv_mul24": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_mul64hi": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_mulhi": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + # __nv_nan and __nv_nanf are excluded - they return a representation of a + # quiet NaN, but the argument they take seems to be undocumented, and + # follows a strange form - it is not an output like every other pointer + # argument. If a NaN is required, one can be obtained in CUDA Python by + # other means, e.g. `math.nan`. They are left in this list for completeness + # / reference. + # "__nv_nan": (float64, [arg(name="tagp", ty=int8, is_ptr=True)]), + # "__nv_nanf": (float32, [arg(name="tagp", ty=int8, is_ptr=True)]), + "__nv_nearbyint": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_nearbyintf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_nextafter": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_nextafterf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_normcdf": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_normcdff": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_normcdfinv": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_normcdfinvf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_popc": (int32, [arg(name="x", ty=int32, is_ptr=False)]), + "__nv_popcll": (int32, [arg(name="x", ty=int64, is_ptr=False)]), + "__nv_pow": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_powf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_powi": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_powif": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_rcbrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rcbrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_remainder": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + ], + ), + "__nv_remainderf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + ], + ), + "__nv_remquo": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=float64, is_ptr=False), + arg(name="c", ty=int32, is_ptr=True), + ], + ), + "__nv_remquof": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=float32, is_ptr=False), + arg(name="quo", ty=int32, is_ptr=True), + ], + ), + "__nv_rhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_rint": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rintf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_round": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_roundf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_rsqrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_rsqrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sad": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_saturatef": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_scalbn": ( + float64, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_scalbnf": ( + float32, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_signbitd": (int32, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_signbitf": (int32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sin": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sincos": ( + void, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="sptr", ty=float64, is_ptr=True), + arg(name="cptr", ty=float64, is_ptr=True), + ], + ), + "__nv_sincosf": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_sincospi": ( + void, + [ + arg(name="x", ty=float64, is_ptr=False), + arg(name="sptr", ty=float64, is_ptr=True), + arg(name="cptr", ty=float64, is_ptr=True), + ], + ), + "__nv_sincospif": ( + void, + [ + arg(name="x", ty=float32, is_ptr=False), + arg(name="sptr", ty=float32, is_ptr=True), + arg(name="cptr", ty=float32, is_ptr=True), + ], + ), + "__nv_sinf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sinh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sinhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sinpi": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sinpif": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_sqrt": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_sqrtf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tan": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tanf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tanh": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tanhf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_tgamma": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_tgammaf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_trunc": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_truncf": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_uhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_uint2double_rn": (float64, [arg(name="i", ty=int32, is_ptr=False)]), + "__nv_uint2float_rd": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_rn": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_ru": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_uint2float_rz": (float32, [arg(name="in", ty=int32, is_ptr=False)]), + "__nv_ull2double_rd": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_rn": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_ru": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2double_rz": (float64, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rd": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rn": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_ru": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ull2float_rz": (float32, [arg(name="l", ty=int64, is_ptr=False)]), + "__nv_ullmax": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_ullmin": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_umax": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umin": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umul24": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_umul64hi": ( + int64, + [ + arg(name="x", ty=int64, is_ptr=False), + arg(name="y", ty=int64, is_ptr=False), + ], + ), + "__nv_umulhi": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_urhadd": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + ], + ), + "__nv_usad": ( + int32, + [ + arg(name="x", ty=int32, is_ptr=False), + arg(name="y", ty=int32, is_ptr=False), + arg(name="z", ty=int32, is_ptr=False), + ], + ), + "__nv_y0": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_y0f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_y1": (float64, [arg(name="x", ty=float64, is_ptr=False)]), + "__nv_y1f": (float32, [arg(name="x", ty=float32, is_ptr=False)]), + "__nv_yn": ( + float64, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float64, is_ptr=False), + ], + ), + "__nv_ynf": ( + float32, + [ + arg(name="n", ty=int32, is_ptr=False), + arg(name="x", ty=float32, is_ptr=False), + ], + ), +} + + +def create_signature(retty, args): + """ + Given the return type and arguments for a libdevice function, return the + signature of the stub function used to call it from CUDA Python. + """ + + # Any pointer arguments should be part of the return type. + return_types = [arg.ty for arg in args if arg.is_ptr] + # If the return type is void, there is no point adding it to the list of + # return types. + if retty != void: + return_types.insert(0, retty) + + if len(return_types) > 1: + retty = Tuple(return_types) + else: + retty = return_types[0] + + argtypes = [arg.ty for arg in args if not arg.is_ptr] + + return signature(retty, *argtypes) + + +# The following code generates the stubs for libdevice functions. +# +# Stubs can be regenerated (e.g. if the functions dict above is modified) with: +# +# python -c "from numba.cuda.libdevicefuncs import generate_stubs; \ +# generate_stubs()" > numba/cuda/libdevice.py + +docstring_template = """ +See https://docs.nvidia.com/cuda/libdevice-users-guide/{func}.html + +{param_types} +:rtype: {retty} +""" + +param_template = """\ +:param {a.name}: Argument. +:type {a.name}: {a.ty}""" + + +def generate_stubs(): + for name, (retty, args) in functions.items(): + # Some libdevice functions have arguments called `in`, which causes a + # syntax error in Python, so we rename these to `x`. + def argname(arg): + if arg.name == "in": + return "x" + else: + return arg.name + + argnames = [argname(a) for a in args if not a.is_ptr] + argstr = ", ".join(argnames) + signature = create_signature(retty, args) + + param_types = "\n".join( + [param_template.format(a=a) for a in args if not a.is_ptr] + ) + docstring = docstring_template.format( + param_types=param_types, retty=signature.return_type, func=name + ) + docstring = indent(docstring, " ") + print(f'def {name[5:]}({argstr}):\n """{docstring}"""\n\n') diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdeviceimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdeviceimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb2e905e033d02cb74d1f83d9749387ce58954d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/libdeviceimpl.py @@ -0,0 +1,83 @@ +from llvmlite import ir +from numba.core import cgutils, types +from numba.core.imputils import Registry +from numba.cuda import libdevice, libdevicefuncs + +registry = Registry() +lower = registry.lower + + +def libdevice_implement(func, retty, nbargs): + def core(context, builder, sig, args): + lmod = builder.module + fretty = context.get_value_type(retty) + fargtys = [context.get_value_type(arg.ty) for arg in nbargs] + fnty = ir.FunctionType(fretty, fargtys) + fn = cgutils.get_or_insert_function(lmod, fnty, func) + return builder.call(fn, args) + + key = getattr(libdevice, func[5:]) + + argtys = [arg.ty for arg in args if not arg.is_ptr] + lower(key, *argtys)(core) + + +def libdevice_implement_multiple_returns(func, retty, prototype_args): + sig = libdevicefuncs.create_signature(retty, prototype_args) + nb_retty = sig.return_type + + def core(context, builder, sig, args): + lmod = builder.module + + fargtys = [] + for arg in prototype_args: + ty = context.get_value_type(arg.ty) + if arg.is_ptr: + ty = ty.as_pointer() + fargtys.append(ty) + + fretty = context.get_value_type(retty) + + fnty = ir.FunctionType(fretty, fargtys) + fn = cgutils.get_or_insert_function(lmod, fnty, func) + + # For returned values that are returned through a pointer, we need to + # allocate variables on the stack and pass a pointer to them. + actual_args = [] + virtual_args = [] + arg_idx = 0 + for arg in prototype_args: + if arg.is_ptr: + # Allocate space for return value and add to args + tmp_arg = cgutils.alloca_once(builder, + context.get_value_type(arg.ty)) + actual_args.append(tmp_arg) + virtual_args.append(tmp_arg) + else: + actual_args.append(args[arg_idx]) + arg_idx += 1 + + ret = builder.call(fn, actual_args) + + # Following the call, we need to assemble the returned values into a + # tuple for returning back to the caller. + tuple_args = [] + if retty != types.void: + tuple_args.append(ret) + for arg in virtual_args: + tuple_args.append(builder.load(arg)) + + if isinstance(nb_retty, types.UniTuple): + return cgutils.pack_array(builder, tuple_args) + else: + return cgutils.pack_struct(builder, tuple_args) + + key = getattr(libdevice, func[5:]) + lower(key, *sig.args)(core) + + +for func, (retty, args) in libdevicefuncs.functions.items(): + if any([arg.is_ptr for arg in args]): + libdevice_implement_multiple_returns(func, retty, args) + else: + libdevice_implement(func, retty, args) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/mathimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/mathimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..c22deb56470e553407c07d3820af0f31a584823b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/mathimpl.py @@ -0,0 +1,448 @@ +import math +import operator +from llvmlite import ir +from numba.core import types, typing, cgutils, targetconfig +from numba.core.imputils import Registry +from numba.types import float32, float64, int64, uint64 +from numba.cuda import libdevice +from numba import cuda + +registry = Registry() +lower = registry.lower + + +booleans = [] +booleans += [('isnand', 'isnanf', math.isnan)] +booleans += [('isinfd', 'isinff', math.isinf)] +booleans += [('isfinited', 'finitef', math.isfinite)] + +unarys = [] +unarys += [('ceil', 'ceilf', math.ceil)] +unarys += [('floor', 'floorf', math.floor)] +unarys += [('fabs', 'fabsf', math.fabs)] +unarys += [('exp', 'expf', math.exp)] +unarys += [('expm1', 'expm1f', math.expm1)] +unarys += [('erf', 'erff', math.erf)] +unarys += [('erfc', 'erfcf', math.erfc)] +unarys += [('tgamma', 'tgammaf', math.gamma)] +unarys += [('lgamma', 'lgammaf', math.lgamma)] +unarys += [('sqrt', 'sqrtf', math.sqrt)] +unarys += [('log', 'logf', math.log)] +unarys += [('log2', 'log2f', math.log2)] +unarys += [('log10', 'log10f', math.log10)] +unarys += [('log1p', 'log1pf', math.log1p)] +unarys += [('acosh', 'acoshf', math.acosh)] +unarys += [('acos', 'acosf', math.acos)] +unarys += [('cos', 'cosf', math.cos)] +unarys += [('cosh', 'coshf', math.cosh)] +unarys += [('asinh', 'asinhf', math.asinh)] +unarys += [('asin', 'asinf', math.asin)] +unarys += [('sin', 'sinf', math.sin)] +unarys += [('sinh', 'sinhf', math.sinh)] +unarys += [('atan', 'atanf', math.atan)] +unarys += [('atanh', 'atanhf', math.atanh)] +unarys += [('tan', 'tanf', math.tan)] +unarys += [('trunc', 'truncf', math.trunc)] + +unarys_fastmath = {} +unarys_fastmath['cosf'] = 'fast_cosf' +unarys_fastmath['sinf'] = 'fast_sinf' +unarys_fastmath['tanf'] = 'fast_tanf' +unarys_fastmath['expf'] = 'fast_expf' +unarys_fastmath['log2f'] = 'fast_log2f' +unarys_fastmath['log10f'] = 'fast_log10f' +unarys_fastmath['logf'] = 'fast_logf' + +binarys = [] +binarys += [('copysign', 'copysignf', math.copysign)] +binarys += [('atan2', 'atan2f', math.atan2)] +binarys += [('pow', 'powf', math.pow)] +binarys += [('fmod', 'fmodf', math.fmod)] +binarys += [('hypot', 'hypotf', math.hypot)] +binarys += [('remainder', 'remainderf', math.remainder)] + +binarys_fastmath = {} +binarys_fastmath['powf'] = 'fast_powf' + + +@lower(math.isinf, types.Integer) +@lower(math.isnan, types.Integer) +def math_isinf_isnan_int(context, builder, sig, args): + return context.get_constant(types.boolean, 0) + + +@lower(operator.truediv, types.float32, types.float32) +def maybe_fast_truediv(context, builder, sig, args): + if context.fastmath: + sig = typing.signature(float32, float32, float32) + impl = context.get_function(libdevice.fast_fdividef, sig) + return impl(builder, args) + else: + with cgutils.if_zero(builder, args[1]): + context.error_model.fp_zero_division(builder, ("division by zero",)) + res = builder.fdiv(*args) + return res + + +@lower(math.isfinite, types.Integer) +def math_isfinite_int(context, builder, sig, args): + return context.get_constant(types.boolean, 1) + + +@lower(math.sin, types.float16) +def fp16_sin_impl(context, builder, sig, args): + def fp16_sin(x): + return cuda.fp16.hsin(x) + + return context.compile_internal(builder, fp16_sin, sig, args) + + +@lower(math.cos, types.float16) +def fp16_cos_impl(context, builder, sig, args): + def fp16_cos(x): + return cuda.fp16.hcos(x) + + return context.compile_internal(builder, fp16_cos, sig, args) + + +@lower(math.log, types.float16) +def fp16_log_impl(context, builder, sig, args): + def fp16_log(x): + return cuda.fp16.hlog(x) + + return context.compile_internal(builder, fp16_log, sig, args) + + +@lower(math.log10, types.float16) +def fp16_log10_impl(context, builder, sig, args): + def fp16_log10(x): + return cuda.fp16.hlog10(x) + + return context.compile_internal(builder, fp16_log10, sig, args) + + +@lower(math.log2, types.float16) +def fp16_log2_impl(context, builder, sig, args): + def fp16_log2(x): + return cuda.fp16.hlog2(x) + + return context.compile_internal(builder, fp16_log2, sig, args) + + +@lower(math.exp, types.float16) +def fp16_exp_impl(context, builder, sig, args): + def fp16_exp(x): + return cuda.fp16.hexp(x) + + return context.compile_internal(builder, fp16_exp, sig, args) + + +@lower(math.floor, types.float16) +def fp16_floor_impl(context, builder, sig, args): + def fp16_floor(x): + return cuda.fp16.hfloor(x) + + return context.compile_internal(builder, fp16_floor, sig, args) + + +@lower(math.ceil, types.float16) +def fp16_ceil_impl(context, builder, sig, args): + def fp16_ceil(x): + return cuda.fp16.hceil(x) + + return context.compile_internal(builder, fp16_ceil, sig, args) + + +@lower(math.sqrt, types.float16) +def fp16_sqrt_impl(context, builder, sig, args): + def fp16_sqrt(x): + return cuda.fp16.hsqrt(x) + + return context.compile_internal(builder, fp16_sqrt, sig, args) + + +@lower(math.fabs, types.float16) +def fp16_fabs_impl(context, builder, sig, args): + def fp16_fabs(x): + return cuda.fp16.habs(x) + + return context.compile_internal(builder, fp16_fabs, sig, args) + + +@lower(math.trunc, types.float16) +def fp16_trunc_impl(context, builder, sig, args): + def fp16_trunc(x): + return cuda.fp16.htrunc(x) + + return context.compile_internal(builder, fp16_trunc, sig, args) + + +def impl_boolean(key, ty, libfunc): + def lower_boolean_impl(context, builder, sig, args): + libfunc_impl = context.get_function(libfunc, + typing.signature(types.int32, ty)) + result = libfunc_impl(builder, args) + return context.cast(builder, result, types.int32, types.boolean) + + lower(key, ty)(lower_boolean_impl) + + +def get_lower_unary_impl(key, ty, libfunc): + def lower_unary_impl(context, builder, sig, args): + actual_libfunc = libfunc + fast_replacement = None + if ty == float32 and context.fastmath: + fast_replacement = unarys_fastmath.get(libfunc.__name__) + + if fast_replacement is not None: + actual_libfunc = getattr(libdevice, fast_replacement) + + libfunc_impl = context.get_function(actual_libfunc, + typing.signature(ty, ty)) + return libfunc_impl(builder, args) + return lower_unary_impl + + +def get_unary_impl_for_fn_and_ty(fn, ty): + # tanh is a special case - because it is not registered like the other + # unary implementations, it does not appear in the unarys list. However, + # its implementation can be looked up by key like the other + # implementations, so we add it to the list we search here. + tanh_impls = ('tanh', 'tanhf', math.tanh) + for fname64, fname32, key in unarys + [tanh_impls]: + if fn == key: + if ty == float32: + impl = getattr(libdevice, fname32) + elif ty == float64: + impl = getattr(libdevice, fname64) + + return get_lower_unary_impl(key, ty, impl) + + raise RuntimeError(f"Implementation of {fn} for {ty} not found") + + +def impl_unary(key, ty, libfunc): + lower_unary_impl = get_lower_unary_impl(key, ty, libfunc) + lower(key, ty)(lower_unary_impl) + + +def impl_unary_int(key, ty, libfunc): + def lower_unary_int_impl(context, builder, sig, args): + if sig.args[0] == int64: + convert = builder.sitofp + elif sig.args[0] == uint64: + convert = builder.uitofp + else: + m = 'Only 64-bit integers are supported for generic unary int ops' + raise TypeError(m) + + arg = convert(args[0], ir.DoubleType()) + sig = typing.signature(float64, float64) + libfunc_impl = context.get_function(libfunc, sig) + return libfunc_impl(builder, [arg]) + + lower(key, ty)(lower_unary_int_impl) + + +def get_lower_binary_impl(key, ty, libfunc): + def lower_binary_impl(context, builder, sig, args): + actual_libfunc = libfunc + fast_replacement = None + if ty == float32 and context.fastmath: + fast_replacement = binarys_fastmath.get(libfunc.__name__) + + if fast_replacement is not None: + actual_libfunc = getattr(libdevice, fast_replacement) + + libfunc_impl = context.get_function(actual_libfunc, + typing.signature(ty, ty, ty)) + return libfunc_impl(builder, args) + return lower_binary_impl + + +def get_binary_impl_for_fn_and_ty(fn, ty): + for fname64, fname32, key in binarys: + if fn == key: + if ty == float32: + impl = getattr(libdevice, fname32) + elif ty == float64: + impl = getattr(libdevice, fname64) + + return get_lower_binary_impl(key, ty, impl) + + raise RuntimeError(f"Implementation of {fn} for {ty} not found") + + +def impl_binary(key, ty, libfunc): + lower_binary_impl = get_lower_binary_impl(key, ty, libfunc) + lower(key, ty, ty)(lower_binary_impl) + + +def impl_binary_int(key, ty, libfunc): + def lower_binary_int_impl(context, builder, sig, args): + if sig.args[0] == int64: + convert = builder.sitofp + elif sig.args[0] == uint64: + convert = builder.uitofp + else: + m = 'Only 64-bit integers are supported for generic binary int ops' + raise TypeError(m) + + args = [convert(arg, ir.DoubleType()) for arg in args] + sig = typing.signature(float64, float64, float64) + libfunc_impl = context.get_function(libfunc, sig) + return libfunc_impl(builder, args) + + lower(key, ty, ty)(lower_binary_int_impl) + + +for fname64, fname32, key in booleans: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_boolean(key, float32, impl32) + impl_boolean(key, float64, impl64) + + +for fname64, fname32, key in unarys: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_unary(key, float32, impl32) + impl_unary(key, float64, impl64) + impl_unary_int(key, int64, impl64) + impl_unary_int(key, uint64, impl64) + + +for fname64, fname32, key in binarys: + impl32 = getattr(libdevice, fname32) + impl64 = getattr(libdevice, fname64) + impl_binary(key, float32, impl32) + impl_binary(key, float64, impl64) + impl_binary_int(key, int64, impl64) + impl_binary_int(key, uint64, impl64) + + +def impl_pow_int(ty, libfunc): + def lower_pow_impl_int(context, builder, sig, args): + powi_sig = typing.signature(ty, ty, types.int32) + libfunc_impl = context.get_function(libfunc, powi_sig) + return libfunc_impl(builder, args) + + lower(math.pow, ty, types.int32)(lower_pow_impl_int) + + +impl_pow_int(types.float32, libdevice.powif) +impl_pow_int(types.float64, libdevice.powi) + + +def impl_modf(ty, libfunc): + retty = types.UniTuple(ty, 2) + + def lower_modf_impl(context, builder, sig, args): + modf_sig = typing.signature(retty, ty) + libfunc_impl = context.get_function(libfunc, modf_sig) + return libfunc_impl(builder, args) + + lower(math.modf, ty)(lower_modf_impl) + + +impl_modf(types.float32, libdevice.modff) +impl_modf(types.float64, libdevice.modf) + + +def impl_frexp(ty, libfunc): + retty = types.Tuple((ty, types.int32)) + + def lower_frexp_impl(context, builder, sig, args): + frexp_sig = typing.signature(retty, ty) + libfunc_impl = context.get_function(libfunc, frexp_sig) + return libfunc_impl(builder, args) + + lower(math.frexp, ty)(lower_frexp_impl) + + +impl_frexp(types.float32, libdevice.frexpf) +impl_frexp(types.float64, libdevice.frexp) + + +def impl_ldexp(ty, libfunc): + def lower_ldexp_impl(context, builder, sig, args): + ldexp_sig = typing.signature(ty, ty, types.int32) + libfunc_impl = context.get_function(libfunc, ldexp_sig) + return libfunc_impl(builder, args) + + lower(math.ldexp, ty, types.int32)(lower_ldexp_impl) + + +impl_ldexp(types.float32, libdevice.ldexpf) +impl_ldexp(types.float64, libdevice.ldexp) + + +def impl_tanh(ty, libfunc): + def lower_tanh_impl(context, builder, sig, args): + def get_compute_capability(): + flags = targetconfig.ConfigStack().top() + return flags.compute_capability + + def tanh_impl_libdevice(): + tanh_sig = typing.signature(ty, ty) + libfunc_impl = context.get_function(libfunc, tanh_sig) + return libfunc_impl(builder, args) + + def tanhf_impl_fastmath(): + fnty = ir.FunctionType(ir.FloatType(), [ir.FloatType()]) + asm = ir.InlineAsm(fnty, 'tanh.approx.f32 $0, $1;', '=f,f') + return builder.call(asm, args) + + if ty == float32 and context.fastmath: + cc = get_compute_capability() + if cc >= (7,5): + return tanhf_impl_fastmath() + + return tanh_impl_libdevice() + + lower(math.tanh, ty)(lower_tanh_impl) + + +impl_tanh(types.float32, libdevice.tanhf) +impl_tanh(types.float64, libdevice.tanh) + +impl_unary_int(math.tanh, int64, libdevice.tanh) +impl_unary_int(math.tanh, uint64, libdevice.tanh) + +# Complex power implementations - translations of _Py_c_pow from CPython +# https://github.com/python/cpython/blob/a755410e054e1e2390de5830befc08fe80706c66/Objects/complexobject.c#L123-L151 +# +# The complex64 variant casts all constants and some variables to ensure that +# as much computation is done in single precision as possible. A small number +# of operations are still done in 64-bit, but these come from libdevice code. + + +def cpow_implement(fty, cty): + def core(context, builder, sig, args): + def cpow_internal(a, b): + + if b.real == fty(0.0) and b.imag == fty(0.0): + return cty(1.0) + cty(0.0j) + elif a.real == fty(0.0) and b.real == fty(0.0): + return cty(0.0) + cty(0.0j) + + vabs = math.hypot(a.real, a.imag) + len = math.pow(vabs, b.real) + at = math.atan2(a.imag, a.real) + phase = at * b.real + if b.imag != fty(0.0): + len /= math.exp(at * b.imag) + phase += b.imag * math.log(vabs) + + return len * (cty(math.cos(phase)) + + cty(math.sin(phase) * cty(1.0j))) + + return context.compile_internal(builder, cpow_internal, sig, args) + + lower(operator.pow, cty, cty)(core) + lower(operator.ipow, cty, cty)(core) + lower(pow, cty, cty)(core) + + +cpow_implement(types.float32, types.complex64) +cpow_implement(types.float64, types.complex128) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/models.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/models.py new file mode 100644 index 0000000000000000000000000000000000000000..21d115125150a284f463a2c0c2ad2f52a78a434f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/models.py @@ -0,0 +1,48 @@ +import functools + +from llvmlite import ir + +from numba.core.datamodel.registry import DataModelManager, register +from numba.core.extending import models +from numba.core import types +from numba.cuda.types import Dim3, GridGroup, CUDADispatcher + + +cuda_data_manager = DataModelManager() + +register_model = functools.partial(register, cuda_data_manager) + + +@register_model(Dim3) +class Dim3Model(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('x', types.int32), + ('y', types.int32), + ('z', types.int32) + ] + super().__init__(dmm, fe_type, members) + + +@register_model(GridGroup) +class GridGroupModel(models.PrimitiveModel): + def __init__(self, dmm, fe_type): + be_type = ir.IntType(64) + super().__init__(dmm, fe_type, be_type) + + +@register_model(types.Float) +class FloatModel(models.PrimitiveModel): + def __init__(self, dmm, fe_type): + if fe_type == types.float16: + be_type = ir.IntType(16) + elif fe_type == types.float32: + be_type = ir.FloatType() + elif fe_type == types.float64: + be_type = ir.DoubleType() + else: + raise NotImplementedError(fe_type) + super(FloatModel, self).__init__(dmm, fe_type, be_type) + + +register_model(CUDADispatcher)(models.OpaqueModel) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/nvvmutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/nvvmutils.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7dcde02b4f15c8d0b15aa4501cd6efc278b81a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/nvvmutils.py @@ -0,0 +1,235 @@ +import itertools +from llvmlite import ir +from numba.core import cgutils, targetconfig +from .cudadrv import nvvm + + +def declare_atomic_cas_int(lmod, isize): + fname = '___numba_atomic_i' + str(isize) + '_cas_hack' + fnty = ir.FunctionType(ir.IntType(isize), + (ir.PointerType(ir.IntType(isize)), + ir.IntType(isize), + ir.IntType(isize))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def atomic_cmpxchg(builder, lmod, isize, ptr, cmp, val): + out = builder.cmpxchg(ptr, cmp, val, 'monotonic', 'monotonic') + return builder.extract_value(out, 0) + + +def declare_atomic_add_float32(lmod): + fname = 'llvm.nvvm.atomic.load.add.f32.p0f32' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType(), 0), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_add_float64(lmod): + flags = targetconfig.ConfigStack().top() + if flags.compute_capability >= (6, 0): + fname = 'llvm.nvvm.atomic.load.add.f64.p0f64' + else: + fname = '___numba_atomic_double_add' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_sub_float32(lmod): + fname = '___numba_atomic_float_sub' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType()), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_sub_float64(lmod): + fname = '___numba_atomic_double_sub' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_inc_int32(lmod): + fname = 'llvm.nvvm.atomic.load.inc.32.p0i32' + fnty = ir.FunctionType(ir.IntType(32), + (ir.PointerType(ir.IntType(32)), ir.IntType(32))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_inc_int64(lmod): + fname = '___numba_atomic_u64_inc' + fnty = ir.FunctionType(ir.IntType(64), + (ir.PointerType(ir.IntType(64)), ir.IntType(64))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_dec_int32(lmod): + fname = 'llvm.nvvm.atomic.load.dec.32.p0i32' + fnty = ir.FunctionType(ir.IntType(32), + (ir.PointerType(ir.IntType(32)), ir.IntType(32))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_dec_int64(lmod): + fname = '___numba_atomic_u64_dec' + fnty = ir.FunctionType(ir.IntType(64), + (ir.PointerType(ir.IntType(64)), ir.IntType(64))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_max_float32(lmod): + fname = '___numba_atomic_float_max' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType()), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_max_float64(lmod): + fname = '___numba_atomic_double_max' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_min_float32(lmod): + fname = '___numba_atomic_float_min' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType()), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_min_float64(lmod): + fname = '___numba_atomic_double_min' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_nanmax_float32(lmod): + fname = '___numba_atomic_float_nanmax' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType()), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_nanmax_float64(lmod): + fname = '___numba_atomic_double_nanmax' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_nanmin_float32(lmod): + fname = '___numba_atomic_float_nanmin' + fnty = ir.FunctionType(ir.FloatType(), + (ir.PointerType(ir.FloatType()), ir.FloatType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_atomic_nanmin_float64(lmod): + fname = '___numba_atomic_double_nanmin' + fnty = ir.FunctionType(ir.DoubleType(), + (ir.PointerType(ir.DoubleType()), ir.DoubleType())) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_cudaCGGetIntrinsicHandle(lmod): + fname = 'cudaCGGetIntrinsicHandle' + fnty = ir.FunctionType(ir.IntType(64), + (ir.IntType(32),)) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_cudaCGSynchronize(lmod): + fname = 'cudaCGSynchronize' + fnty = ir.FunctionType(ir.IntType(32), + (ir.IntType(64), ir.IntType(32))) + return cgutils.get_or_insert_function(lmod, fnty, fname) + + +def declare_string(builder, value): + lmod = builder.basic_block.function.module + cval = cgutils.make_bytearray(value.encode("utf-8") + b"\x00") + gl = cgutils.add_global_variable(lmod, cval.type, name="_str", + addrspace=nvvm.ADDRSPACE_CONSTANT) + gl.linkage = 'internal' + gl.global_constant = True + gl.initializer = cval + + return builder.addrspacecast(gl, ir.PointerType(ir.IntType(8)), 'generic') + + +def declare_vprint(lmod): + voidptrty = ir.PointerType(ir.IntType(8)) + # NOTE: the second argument to vprintf() points to the variable-length + # array of arguments (after the format) + vprintfty = ir.FunctionType(ir.IntType(32), [voidptrty, voidptrty]) + vprintf = cgutils.get_or_insert_function(lmod, vprintfty, "vprintf") + return vprintf + + +# ----------------------------------------------------------------------------- + +SREG_MAPPING = { + 'tid.x': 'llvm.nvvm.read.ptx.sreg.tid.x', + 'tid.y': 'llvm.nvvm.read.ptx.sreg.tid.y', + 'tid.z': 'llvm.nvvm.read.ptx.sreg.tid.z', + + 'ntid.x': 'llvm.nvvm.read.ptx.sreg.ntid.x', + 'ntid.y': 'llvm.nvvm.read.ptx.sreg.ntid.y', + 'ntid.z': 'llvm.nvvm.read.ptx.sreg.ntid.z', + + 'ctaid.x': 'llvm.nvvm.read.ptx.sreg.ctaid.x', + 'ctaid.y': 'llvm.nvvm.read.ptx.sreg.ctaid.y', + 'ctaid.z': 'llvm.nvvm.read.ptx.sreg.ctaid.z', + + 'nctaid.x': 'llvm.nvvm.read.ptx.sreg.nctaid.x', + 'nctaid.y': 'llvm.nvvm.read.ptx.sreg.nctaid.y', + 'nctaid.z': 'llvm.nvvm.read.ptx.sreg.nctaid.z', + + 'warpsize': 'llvm.nvvm.read.ptx.sreg.warpsize', + 'laneid': 'llvm.nvvm.read.ptx.sreg.laneid', +} + + +def call_sreg(builder, name): + module = builder.module + fnty = ir.FunctionType(ir.IntType(32), ()) + fn = cgutils.get_or_insert_function(module, fnty, SREG_MAPPING[name]) + return builder.call(fn, ()) + + +class SRegBuilder(object): + def __init__(self, builder): + self.builder = builder + + def tid(self, xyz): + return call_sreg(self.builder, 'tid.%s' % xyz) + + def ctaid(self, xyz): + return call_sreg(self.builder, 'ctaid.%s' % xyz) + + def ntid(self, xyz): + return call_sreg(self.builder, 'ntid.%s' % xyz) + + def nctaid(self, xyz): + return call_sreg(self.builder, 'nctaid.%s' % xyz) + + def getdim(self, xyz): + i64 = ir.IntType(64) + tid = self.builder.sext(self.tid(xyz), i64) + ntid = self.builder.sext(self.ntid(xyz), i64) + nctaid = self.builder.sext(self.ctaid(xyz), i64) + res = self.builder.add(self.builder.mul(ntid, nctaid), tid) + return res + + +def get_global_id(builder, dim): + sreg = SRegBuilder(builder) + it = (sreg.getdim(xyz) for xyz in 'xyz') + seq = list(itertools.islice(it, None, dim)) + if dim == 1: + return seq[0] + else: + return seq diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/printimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/printimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..dac1780706bb4fa512d66fa36ea18134b2e5d4c8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/printimpl.py @@ -0,0 +1,86 @@ +from functools import singledispatch +from llvmlite import ir +from numba.core import types, cgutils +from numba.core.errors import NumbaWarning +from numba.core.imputils import Registry +from numba.cuda import nvvmutils +from warnings import warn + +registry = Registry() +lower = registry.lower + +voidptr = ir.PointerType(ir.IntType(8)) + + +# NOTE: we don't use @lower here since print_item() doesn't return a LLVM value + +@singledispatch +def print_item(ty, context, builder, val): + """ + Handle printing of a single value of the given Numba type. + A (format string, [list of arguments]) is returned that will allow + forming the final printf()-like call. + """ + raise NotImplementedError("printing unimplemented for values of type %s" + % (ty,)) + + +@print_item.register(types.Integer) +@print_item.register(types.IntegerLiteral) +def int_print_impl(ty, context, builder, val): + if ty in types.unsigned_domain: + rawfmt = "%llu" + dsttype = types.uint64 + else: + rawfmt = "%lld" + dsttype = types.int64 + lld = context.cast(builder, val, ty, dsttype) + return rawfmt, [lld] + + +@print_item.register(types.Float) +def real_print_impl(ty, context, builder, val): + lld = context.cast(builder, val, ty, types.float64) + return "%f", [lld] + + +@print_item.register(types.StringLiteral) +def const_print_impl(ty, context, builder, sigval): + pyval = ty.literal_value + assert isinstance(pyval, str) # Ensured by lowering + rawfmt = "%s" + val = context.insert_string_const_addrspace(builder, pyval) + return rawfmt, [val] + + +@lower(print, types.VarArg(types.Any)) +def print_varargs(context, builder, sig, args): + """This function is a generic 'print' wrapper for arbitrary types. + It dispatches to the appropriate 'print' implementations above + depending on the detected real types in the signature.""" + + vprint = nvvmutils.declare_vprint(builder.module) + + formats = [] + values = [] + + for i, (argtype, argval) in enumerate(zip(sig.args, args)): + argfmt, argvals = print_item(argtype, context, builder, argval) + formats.append(argfmt) + values.extend(argvals) + + rawfmt = " ".join(formats) + "\n" + if len(args) > 32: + msg = ('CUDA print() cannot print more than 32 items. ' + 'The raw format string will be emitted by the kernel instead.') + warn(msg, NumbaWarning) + + rawfmt = rawfmt.replace('%', '%%') + fmt = context.insert_string_const_addrspace(builder, rawfmt) + array = cgutils.make_anonymous_struct(builder, values) + arrayptr = cgutils.alloca_once_value(builder, array) + + vprint = nvvmutils.declare_vprint(builder.module) + builder.call(vprint, (fmt, builder.bitcast(arrayptr, voidptr))) + + return context.get_dummy_value() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/random.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/random.py new file mode 100644 index 0000000000000000000000000000000000000000..460c7fc212077742e728e5c5c981ef2c1b1e6af0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/random.py @@ -0,0 +1,292 @@ +import math + +from numba import (config, cuda, float32, float64, uint32, int64, uint64, + from_dtype, jit) + +import numpy as np + +# This implementation is based upon the xoroshiro128+ and splitmix64 algorithms +# described at: +# +# http://xoroshiro.di.unimi.it/ +# +# and originally implemented by David Blackman and Sebastiano Vigna. +# +# The implementations below are based on the C source code: +# +# * http://xoroshiro.di.unimi.it/xoroshiro128plus.c +# * http://xoroshiro.di.unimi.it/splitmix64.c +# +# Splitmix64 is used to generate the initial state of the xoroshiro128+ +# generator to ensure that small seeds don't result in predictable output. + +# **WARNING**: There is a lot of verbose casting in this file to ensure that +# NumPy casting conventions (which cast uint64 [op] int32 to float64) don't +# turn integers into floats when using these functions in the CUDA simulator. +# +# There are also no function type signatures to ensure that compilation is +# deferred so that import is quick, and Sphinx autodoc works. We are also +# using the CPU @jit decorator everywhere to create functions that work as +# both CPU and CUDA device functions. + +xoroshiro128p_dtype = np.dtype([('s0', np.uint64), ('s1', np.uint64)], + align=True) +xoroshiro128p_type = from_dtype(xoroshiro128p_dtype) + +# When cudasim is enabled, Fake CUDA arrays are passed to some of the +# @jit-decorated functions. This required fallback to object mode. With +# Numba 0.59.0 object mode must be explicitly enabled. +# https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit +# In order to avoid the warning / future error, we explicitly specify that +# object mode with loop lifting is acceptable when using the simulator. +_forceobj = _looplift = config.ENABLE_CUDASIM +_nopython = not config.ENABLE_CUDASIM + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def init_xoroshiro128p_state(states, index, seed): + '''Use SplitMix64 to generate an xoroshiro128p state from 64-bit seed. + + This ensures that manually set small seeds don't result in a predictable + initial sequence from the random number generator. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: uint64 + :param index: offset in states to update + :type seed: int64 + :param seed: seed value to use when initializing state + ''' + index = int64(index) + seed = uint64(seed) + + z = seed + uint64(0x9E3779B97F4A7C15) + z = (z ^ (z >> uint32(30))) * uint64(0xBF58476D1CE4E5B9) + z = (z ^ (z >> uint32(27))) * uint64(0x94D049BB133111EB) + z = z ^ (z >> uint32(31)) + + states[index]['s0'] = z + states[index]['s1'] = z + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def rotl(x, k): + '''Left rotate x by k bits.''' + x = uint64(x) + k = uint32(k) + return (x << k) | (x >> uint32(64 - k)) + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_next(states, index): + '''Return the next random uint64 and advance the RNG in states[index]. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + :rtype: uint64 + ''' + index = int64(index) + s0 = states[index]['s0'] + s1 = states[index]['s1'] + result = s0 + s1 + + s1 ^= s0 + states[index]['s0'] = uint64(rotl(s0, uint32(55))) ^ s1 ^ (s1 << uint32(14)) + states[index]['s1'] = uint64(rotl(s1, uint32(36))) + + return result + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_jump(states, index): + '''Advance the RNG in ``states[index]`` by 2**64 steps. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + ''' + index = int64(index) + + jump = (uint64(0xbeac0467eba5facb), uint64(0xd86b048b86aa9922)) + + s0 = uint64(0) + s1 = uint64(0) + + for i in range(2): + for b in range(64): + if jump[i] & (uint64(1) << uint32(b)): + s0 ^= states[index]['s0'] + s1 ^= states[index]['s1'] + xoroshiro128p_next(states, index) + + states[index]['s0'] = s0 + states[index]['s1'] = s1 + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def uint64_to_unit_float64(x): + '''Convert uint64 to float64 value in the range [0.0, 1.0)''' + x = uint64(x) + return (x >> uint32(11)) * (float64(1) / (uint64(1) << uint32(53))) + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def uint64_to_unit_float32(x): + '''Convert uint64 to float32 value in the range [0.0, 1.0)''' + x = uint64(x) + return float32(uint64_to_unit_float64(x)) + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_uniform_float32(states, index): + '''Return a float32 in range [0.0, 1.0) and advance ``states[index]``. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + :rtype: float32 + ''' + index = int64(index) + return uint64_to_unit_float32(xoroshiro128p_next(states, index)) + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_uniform_float64(states, index): + '''Return a float64 in range [0.0, 1.0) and advance ``states[index]``. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + :rtype: float64 + ''' + index = int64(index) + return uint64_to_unit_float64(xoroshiro128p_next(states, index)) + + +TWO_PI_FLOAT32 = np.float32(2 * math.pi) +TWO_PI_FLOAT64 = np.float64(2 * math.pi) + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_normal_float32(states, index): + '''Return a normally distributed float32 and advance ``states[index]``. + + The return value is drawn from a Gaussian of mean=0 and sigma=1 using the + Box-Muller transform. This advances the RNG sequence by two steps. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + :rtype: float32 + ''' + index = int64(index) + + u1 = xoroshiro128p_uniform_float32(states, index) + u2 = xoroshiro128p_uniform_float32(states, index) + + z0 = math.sqrt(-float32(2.0) * math.log(u1)) * math.cos(TWO_PI_FLOAT32 * u2) + # discarding second normal value + # z1 = math.sqrt(-float32(2.0) * math.log(u1)) + # * math.sin(TWO_PI_FLOAT32 * u2) + return z0 + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def xoroshiro128p_normal_float64(states, index): + '''Return a normally distributed float32 and advance ``states[index]``. + + The return value is drawn from a Gaussian of mean=0 and sigma=1 using the + Box-Muller transform. This advances the RNG sequence by two steps. + + :type states: 1D array, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type index: int64 + :param index: offset in states to update + :rtype: float64 + ''' + index = int64(index) + + u1 = xoroshiro128p_uniform_float32(states, index) + u2 = xoroshiro128p_uniform_float32(states, index) + + z0 = math.sqrt(-float64(2.0) * math.log(u1)) * math.cos(TWO_PI_FLOAT64 * u2) + # discarding second normal value + # z1 = math.sqrt(-float64(2.0) * math.log(u1)) + # * math.sin(TWO_PI_FLOAT64 * u2) + return z0 + + +@jit(forceobj=_forceobj, looplift=_looplift, nopython=_nopython) +def init_xoroshiro128p_states_cpu(states, seed, subsequence_start): + n = states.shape[0] + seed = uint64(seed) + subsequence_start = uint64(subsequence_start) + + if n >= 1: + init_xoroshiro128p_state(states, 0, seed) + + # advance to starting subsequence number + for _ in range(subsequence_start): + xoroshiro128p_jump(states, 0) + + # populate the rest of the array + for i in range(1, n): + states[i] = states[i - 1] # take state of previous generator + xoroshiro128p_jump(states, i) # and jump forward 2**64 steps + + +def init_xoroshiro128p_states(states, seed, subsequence_start=0, stream=0): + '''Initialize RNG states on the GPU for parallel generators. + + This initializes the RNG states so that each state in the array corresponds + subsequences in the separated by 2**64 steps from each other in the main + sequence. Therefore, as long no CUDA thread requests more than 2**64 + random numbers, all of the RNG states produced by this function are + guaranteed to be independent. + + The subsequence_start parameter can be used to advance the first RNG state + by a multiple of 2**64 steps. + + :type states: 1D DeviceNDArray, dtype=xoroshiro128p_dtype + :param states: array of RNG states + :type seed: uint64 + :param seed: starting seed for list of generators + ''' + + # Initialization on CPU is much faster than the GPU + states_cpu = np.empty(shape=states.shape, dtype=xoroshiro128p_dtype) + init_xoroshiro128p_states_cpu(states_cpu, seed, subsequence_start) + + states.copy_to_device(states_cpu, stream=stream) + + +def create_xoroshiro128p_states(n, seed, subsequence_start=0, stream=0): + '''Returns a new device array initialized for n random number generators. + + This initializes the RNG states so that each state in the array corresponds + subsequences in the separated by 2**64 steps from each other in the main + sequence. Therefore, as long no CUDA thread requests more than 2**64 + random numbers, all of the RNG states produced by this function are + guaranteed to be independent. + + The subsequence_start parameter can be used to advance the first RNG state + by a multiple of 2**64 steps. + + :type n: int + :param n: number of RNG states to create + :type seed: uint64 + :param seed: starting seed for list of generators + :type subsequence_start: uint64 + :param subsequence_start: + :type stream: CUDA stream + :param stream: stream to run initialization kernel on + ''' + states = cuda.device_array(n, dtype=xoroshiro128p_dtype, stream=stream) + init_xoroshiro128p_states(states, seed, subsequence_start, stream) + return states diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/simulator_init.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/simulator_init.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7dd124a9ef539a85545c017653a9fab9264261 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/simulator_init.py @@ -0,0 +1,17 @@ +# We import * from simulator here because * is imported from simulator_init by +# numba.cuda.__init__. +from .simulator import * # noqa: F403, F401 + + +def is_available(): + """Returns a boolean to indicate the availability of a CUDA GPU. + """ + # Simulator is always available + return True + + +def cuda_error(): + """Returns None or an exception if the CUDA driver fails to initialize. + """ + # Simulator never fails to initialize + return None diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/stubs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..fb6979a448185945a8ce1e5dbad83f2f23cc36a3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/stubs.py @@ -0,0 +1,902 @@ +""" +This scripts specifies all PTX special objects. +""" +import numpy as np +from collections import defaultdict +import functools +import itertools +from inspect import Signature, Parameter + + +class Stub(object): + ''' + A stub object to represent special objects that are meaningless + outside the context of a CUDA kernel + ''' + _description_ = '' + __slots__ = () # don't allocate __dict__ + + def __new__(cls): + raise NotImplementedError("%s is not instantiable" % cls) + + def __repr__(self): + return self._description_ + + +def stub_function(fn): + ''' + A stub function to represent special functions that are meaningless + outside the context of a CUDA kernel + ''' + @functools.wraps(fn) + def wrapped(*args, **kwargs): + raise NotImplementedError("%s cannot be called from host code" % fn) + return wrapped + + +#------------------------------------------------------------------------------- +# Thread and grid indices and dimensions + + +class Dim3(Stub): + '''A triple, (x, y, z)''' + _description_ = '' + + @property + def x(self): + pass + + @property + def y(self): + pass + + @property + def z(self): + pass + + +class threadIdx(Dim3): + ''' + The thread indices in the current thread block. Each index is an integer + spanning the range from 0 inclusive to the corresponding value of the + attribute in :attr:`numba.cuda.blockDim` exclusive. + ''' + _description_ = '' + + +class blockIdx(Dim3): + ''' + The block indices in the grid of thread blocks. Each index is an integer + spanning the range from 0 inclusive to the corresponding value of the + attribute in :attr:`numba.cuda.gridDim` exclusive. + ''' + _description_ = '' + + +class blockDim(Dim3): + ''' + The shape of a block of threads, as declared when instantiating the kernel. + This value is the same for all threads in a given kernel launch, even if + they belong to different blocks (i.e. each block is "full"). + ''' + _description_ = '' + + +class gridDim(Dim3): + ''' + The shape of the grid of blocks. This value is the same for all threads in + a given kernel launch. + ''' + _description_ = '' + + +class warpsize(Stub): + ''' + The size of a warp. All architectures implemented to date have a warp size + of 32. + ''' + _description_ = '' + + +class laneid(Stub): + ''' + This thread's lane within a warp. Ranges from 0 to + :attr:`numba.cuda.warpsize` - 1. + ''' + _description_ = '' + + +#------------------------------------------------------------------------------- +# Array creation + +class shared(Stub): + ''' + Shared memory namespace + ''' + _description_ = '' + + @stub_function + def array(shape, dtype): + ''' + Allocate a shared array of the given *shape* and *type*. *shape* is + either an integer or a tuple of integers representing the array's + dimensions. *type* is a :ref:`Numba type ` of the + elements needing to be stored in the array. + + The returned array-like object can be read and written to like any + normal device array (e.g. through indexing). + ''' + + +class local(Stub): + ''' + Local memory namespace + ''' + _description_ = '' + + @stub_function + def array(shape, dtype): + ''' + Allocate a local array of the given *shape* and *type*. The array is + private to the current thread, and resides in global memory. An + array-like object is returned which can be read and written to like any + standard array (e.g. through indexing). + ''' + + +class const(Stub): + ''' + Constant memory namespace + ''' + + @stub_function + def array_like(ndarray): + ''' + Create a const array from *ndarry*. The resulting const array will have + the same shape, type, and values as *ndarray*. + ''' + + +# ------------------------------------------------------------------------------- +# warp level operations + +class syncwarp(Stub): + ''' + syncwarp(mask=0xFFFFFFFF) + + Synchronizes a masked subset of threads in a warp. + ''' + _description_ = '' + + +class shfl_sync_intrinsic(Stub): + ''' + shfl_sync_intrinsic(mask, mode, value, mode_offset, clamp) + + Nvvm intrinsic for shuffling data across a warp + docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-datamove + ''' + _description_ = '' + + +class vote_sync_intrinsic(Stub): + ''' + vote_sync_intrinsic(mask, mode, predictate) + + Nvvm intrinsic for performing a reduce and broadcast across a warp + docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-vote + ''' + _description_ = '' + + +class match_any_sync(Stub): + ''' + match_any_sync(mask, value) + + Nvvm intrinsic for performing a compare and broadcast across a warp. + Returns a mask of threads that have same value as the given value from + within the masked warp. + ''' + _description_ = '' + + +class match_all_sync(Stub): + ''' + match_all_sync(mask, value) + + Nvvm intrinsic for performing a compare and broadcast across a warp. + Returns a tuple of (mask, pred), where mask is a mask of threads that have + same value as the given value from within the masked warp, if they + all have the same value, otherwise it is 0. Pred is a boolean of whether + or not all threads in the mask warp have the same warp. + ''' + _description_ = '' + + +class activemask(Stub): + ''' + activemask() + + Returns a 32-bit integer mask of all currently active threads in the + calling warp. The Nth bit is set if the Nth lane in the warp is active when + activemask() is called. Inactive threads are represented by 0 bits in the + returned mask. Threads which have exited the kernel are always marked as + inactive. + ''' + _description_ = '' + + +class lanemask_lt(Stub): + ''' + lanemask_lt() + + Returns a 32-bit integer mask of all lanes (including inactive ones) with + ID less than the current lane. + ''' + _description_ = '' + + +# ------------------------------------------------------------------------------- +# memory fences + +class threadfence_block(Stub): + ''' + A memory fence at thread block level + ''' + _description_ = '' + + +class threadfence_system(Stub): + ''' + A memory fence at system level: across devices + ''' + _description_ = '' + + +class threadfence(Stub): + ''' + A memory fence at device level + ''' + _description_ = '' + + +#------------------------------------------------------------------------------- +# bit manipulation + +class popc(Stub): + """ + popc(x) + + Returns the number of set bits in x. + """ + + +class brev(Stub): + """ + brev(x) + + Returns the reverse of the bit pattern of x. For example, 0b10110110 + becomes 0b01101101. + """ + + +class clz(Stub): + """ + clz(x) + + Returns the number of leading zeros in z. + """ + + +class ffs(Stub): + """ + ffs(x) + + Returns the position of the first (least significant) bit set to 1 in x, + where the least significant bit position is 1. ffs(0) returns 0. + """ + + +#------------------------------------------------------------------------------- +# comparison and selection instructions + +class selp(Stub): + """ + selp(a, b, c) + + Select between source operands, based on the value of the predicate source + operand. + """ + + +#------------------------------------------------------------------------------- +# single / double precision arithmetic + +class fma(Stub): + """ + fma(a, b, c) + + Perform the fused multiply-add operation. + """ + + +class cbrt(Stub): + """" + cbrt(a) + + Perform the cube root operation. + """ + + +#------------------------------------------------------------------------------- +# atomic + +class atomic(Stub): + """Namespace for atomic operations + """ + _description_ = '' + + class add(Stub): + """add(ary, idx, val) + + Perform atomic ``ary[idx] += val``. Supported on int32, float32, and + float64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class sub(Stub): + """sub(ary, idx, val) + + Perform atomic ``ary[idx] -= val``. Supported on int32, float32, and + float64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class and_(Stub): + """and_(ary, idx, val) + + Perform atomic ``ary[idx] &= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class or_(Stub): + """or_(ary, idx, val) + + Perform atomic ``ary[idx] |= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class xor(Stub): + """xor(ary, idx, val) + + Perform atomic ``ary[idx] ^= val``. Supported on int32, int64, uint32 + and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class inc(Stub): + """inc(ary, idx, val) + + Perform atomic ``ary[idx] += 1`` up to val, then reset to 0. Supported + on uint32, and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class dec(Stub): + """dec(ary, idx, val) + + Performs:: + + ary[idx] = (value if (array[idx] == 0) or + (array[idx] > value) else array[idx] - 1) + + Supported on uint32, and uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class exch(Stub): + """exch(ary, idx, val) + + Perform atomic ``ary[idx] = val``. Supported on int32, int64, uint32 and + uint64 operands only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class max(Stub): + """max(ary, idx, val) + + Perform atomic ``ary[idx] = max(ary[idx], val)``. + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class min(Stub): + """min(ary, idx, val) + + Perform atomic ``ary[idx] = min(ary[idx], val)``. + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class nanmax(Stub): + """nanmax(ary, idx, val) + + Perform atomic ``ary[idx] = max(ary[idx], val)``. + + NOTE: NaN is treated as a missing value such that: + nanmax(NaN, n) == n, nanmax(n, NaN) == n + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class nanmin(Stub): + """nanmin(ary, idx, val) + + Perform atomic ``ary[idx] = min(ary[idx], val)``. + + NOTE: NaN is treated as a missing value, such that: + nanmin(NaN, n) == n, nanmin(n, NaN) == n + + Supported on int32, int64, uint32, uint64, float32, float64 operands + only. + + Returns the old value at the index location as if it is loaded + atomically. + """ + + class compare_and_swap(Stub): + """compare_and_swap(ary, old, val) + + Conditionally assign ``val`` to the first element of an 1D array ``ary`` + if the current value matches ``old``. + + Supported on int32, int64, uint32, uint64 operands only. + + Returns the old value as if it is loaded atomically. + """ + + class cas(Stub): + """cas(ary, idx, old, val) + + Conditionally assign ``val`` to the element ``idx`` of an array + ``ary`` if the current value of ``ary[idx]`` matches ``old``. + + Supported on int32, int64, uint32, uint64 operands only. + + Returns the old value as if it is loaded atomically. + """ + + +#------------------------------------------------------------------------------- +# timers + +class nanosleep(Stub): + ''' + nanosleep(ns) + + Suspends the thread for a sleep duration approximately close to the delay + `ns`, specified in nanoseconds. + ''' + _description_ = '' + +#------------------------------------------------------------------------------- +# Floating point 16 + + +class fp16(Stub): + """Namespace for fp16 operations + """ + _description_ = '' + + class hadd(Stub): + """hadd(a, b) + + Perform fp16 addition, (a + b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the addition. + + """ + + class hsub(Stub): + """hsub(a, b) + + Perform fp16 subtraction, (a - b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the subtraction. + + """ + + class hmul(Stub): + """hmul(a, b) + + Perform fp16 multiplication, (a * b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the multiplication. + + """ + + class hdiv(Stub): + """hdiv(a, b) + + Perform fp16 division, (a / b) in round to nearest mode. Supported + on fp16 operands only. + + Returns the fp16 result of the division + + """ + + class hfma(Stub): + """hfma(a, b, c) + + Perform fp16 multiply and accumulate, (a * b) + c in round to nearest + mode. Supported on fp16 operands only. + + Returns the fp16 result of the multiplication. + + """ + + class hneg(Stub): + """hneg(a) + + Perform fp16 negation, -(a). Supported on fp16 operands only. + + Returns the fp16 result of the negation. + + """ + + class habs(Stub): + """habs(a) + + Perform fp16 absolute value, |a|. Supported on fp16 operands only. + + Returns the fp16 result of the absolute value. + + """ + + class hsin(Stub): + """hsin(a) + + Calculate sine in round to nearest even mode. Supported on fp16 + operands only. + + Returns the sine result. + + """ + + class hcos(Stub): + """hsin(a) + + Calculate cosine in round to nearest even mode. Supported on fp16 + operands only. + + Returns the cosine result. + + """ + + class hlog(Stub): + """hlog(a) + + Calculate natural logarithm in round to nearest even mode. Supported + on fp16 operands only. + + Returns the natural logarithm result. + + """ + + class hlog10(Stub): + """hlog10(a) + + Calculate logarithm base 10 in round to nearest even mode. Supported + on fp16 operands only. + + Returns the logarithm base 10 result. + + """ + + class hlog2(Stub): + """hlog2(a) + + Calculate logarithm base 2 in round to nearest even mode. Supported + on fp16 operands only. + + Returns the logarithm base 2 result. + + """ + + class hexp(Stub): + """hexp(a) + + Calculate natural exponential, exp(a), in round to nearest mode. + Supported on fp16 operands only. + + Returns the natural exponential result. + + """ + + class hexp10(Stub): + """hexp10(a) + + Calculate exponential base 10 (10 ** a) in round to nearest mode. + Supported on fp16 operands only. + + Returns the exponential base 10 result. + + """ + + class hexp2(Stub): + """hexp2(a) + + Calculate exponential base 2 (2 ** a) in round to nearest mode. + Supported on fp16 operands only. + + Returns the exponential base 2 result. + + """ + + class hfloor(Stub): + """hfloor(a) + + Calculate the floor, the largest integer less than or equal to 'a'. + Supported on fp16 operands only. + + Returns the floor result. + + """ + + class hceil(Stub): + """hceil(a) + + Calculate the ceil, the smallest integer greater than or equal to 'a'. + Supported on fp16 operands only. + + Returns the ceil result. + + """ + + class hsqrt(Stub): + """hsqrt(a) + + Calculate the square root of the input argument in round to nearest + mode. Supported on fp16 operands only. + + Returns the square root result. + + """ + + class hrsqrt(Stub): + """hrsqrt(a) + + Calculate the reciprocal square root of the input argument in round + to nearest even mode. Supported on fp16 operands only. + + Returns the reciprocal square root result. + + """ + + class hrcp(Stub): + """hrcp(a) + + Calculate the reciprocal of the input argument in round to nearest + even mode. Supported on fp16 operands only. + + Returns the reciprocal result. + + """ + + class hrint(Stub): + """hrint(a) + + Round the input argument to nearest integer value. Supported on fp16 + operands only. + + Returns the rounded result. + + """ + + class htrunc(Stub): + """htrunc(a) + + Truncate the input argument to its integer portion. Supported + on fp16 operands only. + + Returns the truncated result. + + """ + + class heq(Stub): + """heq(a, b) + + Perform fp16 comparison, (a == b). Supported + on fp16 operands only. + + Returns True if a and b are equal and False otherwise. + + """ + + class hne(Stub): + """hne(a, b) + + Perform fp16 comparison, (a != b). Supported + on fp16 operands only. + + Returns True if a and b are not equal and False otherwise. + + """ + + class hge(Stub): + """hge(a, b) + + Perform fp16 comparison, (a >= b). Supported + on fp16 operands only. + + Returns True if a is >= b and False otherwise. + + """ + + class hgt(Stub): + """hgt(a, b) + + Perform fp16 comparison, (a > b). Supported + on fp16 operands only. + + Returns True if a is > b and False otherwise. + + """ + + class hle(Stub): + """hle(a, b) + + Perform fp16 comparison, (a <= b). Supported + on fp16 operands only. + + Returns True if a is <= b and False otherwise. + + """ + + class hlt(Stub): + """hlt(a, b) + + Perform fp16 comparison, (a < b). Supported + on fp16 operands only. + + Returns True if a is < b and False otherwise. + + """ + + class hmax(Stub): + """hmax(a, b) + + Perform fp16 maximum operation, max(a,b) Supported + on fp16 operands only. + + Returns a if a is greater than b, returns b otherwise. + + """ + + class hmin(Stub): + """hmin(a, b) + + Perform fp16 minimum operation, min(a,b). Supported + on fp16 operands only. + + Returns a if a is less than b, returns b otherwise. + + """ + + +#------------------------------------------------------------------------------- +# vector types + +def make_vector_type_stubs(): + """Make user facing objects for vector types""" + vector_type_stubs = [] + vector_type_prefix = ( + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float32", + "float64" + ) + vector_type_element_counts = (1, 2, 3, 4) + vector_type_attribute_names = ("x", "y", "z", "w") + + for prefix, nelem in itertools.product( + vector_type_prefix, vector_type_element_counts + ): + type_name = f"{prefix}x{nelem}" + attr_names = vector_type_attribute_names[:nelem] + + vector_type_stub = type( + type_name, (Stub,), + { + **{attr: lambda self: None for attr in attr_names}, + **{ + "_description_": f"<{type_name}>", + "__signature__": Signature(parameters=[ + Parameter( + name=attr_name, kind=Parameter.POSITIONAL_ONLY + ) for attr_name in attr_names[:nelem] + ]), + "__doc__": f"A stub for {type_name} to be used in " + "CUDA kernels." + }, + **{"aliases": []} + } + ) + vector_type_stubs.append(vector_type_stub) + return vector_type_stubs + + +def map_vector_type_stubs_to_alias(vector_type_stubs): + """For each of the stubs, create its aliases. + + For example: float64x3 -> double3 + """ + # C-compatible type mapping, see: + # https://numpy.org/devdocs/reference/arrays.scalars.html#integer-types + base_type_to_alias = { + "char": f"int{np.dtype(np.byte).itemsize * 8}", + "short": f"int{np.dtype(np.short).itemsize * 8}", + "int": f"int{np.dtype(np.intc).itemsize * 8}", + "long": f"int{np.dtype(np.int_).itemsize * 8}", + "longlong": f"int{np.dtype(np.longlong).itemsize * 8}", + "uchar": f"uint{np.dtype(np.ubyte).itemsize * 8}", + "ushort": f"uint{np.dtype(np.ushort).itemsize * 8}", + "uint": f"uint{np.dtype(np.uintc).itemsize * 8}", + "ulong": f"uint{np.dtype(np.uint).itemsize * 8}", + "ulonglong": f"uint{np.dtype(np.ulonglong).itemsize * 8}", + "float": f"float{np.dtype(np.single).itemsize * 8}", + "double": f"float{np.dtype(np.double).itemsize * 8}" + } + + base_type_to_vector_type = defaultdict(list) + for stub in vector_type_stubs: + base_type_to_vector_type[stub.__name__[:-2]].append(stub) + + for alias, base_type in base_type_to_alias.items(): + vector_type_stubs = base_type_to_vector_type[base_type] + for stub in vector_type_stubs: + nelem = stub.__name__[-1] + stub.aliases.append(f"{alias}{nelem}") + + +_vector_type_stubs = make_vector_type_stubs() +map_vector_type_stubs_to_alias(_vector_type_stubs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/target.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/target.py new file mode 100644 index 0000000000000000000000000000000000000000..6402ff3574abf3a4e17a0515c80e3ab703754ca9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/target.py @@ -0,0 +1,440 @@ +import re +from functools import cached_property +import llvmlite.binding as ll +from llvmlite import ir + +from numba.core import (cgutils, config, debuginfo, itanium_mangler, types, + typing, utils) +from numba.core.dispatcher import Dispatcher +from numba.core.base import BaseContext +from numba.core.callconv import BaseCallConv, MinimalCallConv +from numba.core.typing import cmathdecl +from numba.core import datamodel + +from .cudadrv import nvvm +from numba.cuda import codegen, nvvmutils, ufuncs +from numba.cuda.models import cuda_data_manager + +# ----------------------------------------------------------------------------- +# Typing + + +class CUDATypingContext(typing.BaseContext): + def load_additional_registries(self): + from . import cudadecl, cudamath, libdevicedecl, vector_types + from numba.core.typing import enumdecl, cffi_utils + + self.install_registry(cudadecl.registry) + self.install_registry(cffi_utils.registry) + self.install_registry(cudamath.registry) + self.install_registry(cmathdecl.registry) + self.install_registry(libdevicedecl.registry) + self.install_registry(enumdecl.registry) + self.install_registry(vector_types.typing_registry) + + def resolve_value_type(self, val): + # treat other dispatcher object as another device function + from numba.cuda.dispatcher import CUDADispatcher + if (isinstance(val, Dispatcher) and not + isinstance(val, CUDADispatcher)): + try: + # use cached device function + val = val.__dispatcher + except AttributeError: + if not val._can_compile: + raise ValueError('using cpu function on device ' + 'but its compilation is disabled') + targetoptions = val.targetoptions.copy() + targetoptions['device'] = True + targetoptions['debug'] = targetoptions.get('debug', False) + targetoptions['opt'] = targetoptions.get('opt', True) + disp = CUDADispatcher(val.py_func, targetoptions) + # cache the device function for future use and to avoid + # duplicated copy of the same function. + val.__dispatcher = disp + val = disp + + # continue with parent logic + return super(CUDATypingContext, self).resolve_value_type(val) + +# ----------------------------------------------------------------------------- +# Implementation + + +VALID_CHARS = re.compile(r'[^a-z0-9]', re.I) + + +class CUDATargetContext(BaseContext): + implement_powi_as_math_call = True + strict_alignment = True + + def __init__(self, typingctx, target='cuda'): + super().__init__(typingctx, target) + self.data_model_manager = cuda_data_manager.chain( + datamodel.default_manager + ) + + @property + def DIBuilder(self): + return debuginfo.DIBuilder + + @property + def enable_boundscheck(self): + # Unconditionally disabled + return False + + # Overrides + def create_module(self, name): + return self._internal_codegen._create_empty_module(name) + + def init(self): + self._internal_codegen = codegen.JITCUDACodegen("numba.cuda.jit") + self._target_data = None + + def load_additional_registries(self): + # side effect of import needed for numba.cpython.*, the builtins + # registry is updated at import time. + from numba.cpython import numbers, tupleobj, slicing # noqa: F401 + from numba.cpython import rangeobj, iterators, enumimpl # noqa: F401 + from numba.cpython import unicode, charseq # noqa: F401 + from numba.cpython import cmathimpl + from numba.misc import cffiimpl + from numba.np import arrayobj # noqa: F401 + from numba.np import npdatetime # noqa: F401 + from . import ( + cudaimpl, printimpl, libdeviceimpl, mathimpl, vector_types + ) + # fix for #8940 + from numba.np.unsafe import ndarray # noqa F401 + + self.install_registry(cudaimpl.registry) + self.install_registry(cffiimpl.registry) + self.install_registry(printimpl.registry) + self.install_registry(libdeviceimpl.registry) + self.install_registry(cmathimpl.registry) + self.install_registry(mathimpl.registry) + self.install_registry(vector_types.impl_registry) + + def codegen(self): + return self._internal_codegen + + @property + def target_data(self): + if self._target_data is None: + self._target_data = ll.create_target_data(nvvm.NVVM().data_layout) + return self._target_data + + @cached_property + def nonconst_module_attrs(self): + """ + Some CUDA intrinsics are at the module level, but cannot be treated as + constants, because they are loaded from a special register in the PTX. + These include threadIdx, blockDim, etc. + """ + from numba import cuda + nonconsts = ('threadIdx', 'blockDim', 'blockIdx', 'gridDim', 'laneid', + 'warpsize') + nonconsts_with_mod = tuple([(types.Module(cuda), nc) + for nc in nonconsts]) + return nonconsts_with_mod + + @cached_property + def call_conv(self): + return CUDACallConv(self) + + def mangler(self, name, argtypes, *, abi_tags=(), uid=None): + return itanium_mangler.mangle(name, argtypes, abi_tags=abi_tags, + uid=uid) + + def prepare_cuda_kernel(self, codelib, fndesc, debug, lineinfo, + nvvm_options, filename, linenum, + max_registers=None): + """ + Adapt a code library ``codelib`` with the numba compiled CUDA kernel + with name ``fname`` and arguments ``argtypes`` for NVVM. + A new library is created with a wrapper function that can be used as + the kernel entry point for the given kernel. + + Returns the new code library and the wrapper function. + + Parameters: + + codelib: The CodeLibrary containing the device function to wrap + in a kernel call. + fndesc: The FunctionDescriptor of the source function. + debug: Whether to compile with debug. + lineinfo: Whether to emit line info. + nvvm_options: Dict of NVVM options used when compiling the new library. + filename: The source filename that the function is contained in. + linenum: The source line that the function is on. + max_registers: The max_registers argument for the code library. + """ + kernel_name = itanium_mangler.prepend_namespace( + fndesc.llvm_func_name, ns='cudapy', + ) + library = self.codegen().create_library(f'{codelib.name}_kernel_', + entry_name=kernel_name, + nvvm_options=nvvm_options, + max_registers=max_registers) + library.add_linking_library(codelib) + wrapper = self.generate_kernel_wrapper(library, fndesc, kernel_name, + debug, lineinfo, filename, + linenum) + return library, wrapper + + def generate_kernel_wrapper(self, library, fndesc, kernel_name, debug, + lineinfo, filename, linenum): + """ + Generate the kernel wrapper in the given ``library``. + The function being wrapped is described by ``fndesc``. + The wrapper function is returned. + """ + + argtypes = fndesc.argtypes + arginfo = self.get_arg_packer(argtypes) + argtys = list(arginfo.argument_types) + wrapfnty = ir.FunctionType(ir.VoidType(), argtys) + wrapper_module = self.create_module("cuda.kernel.wrapper") + fnty = ir.FunctionType(ir.IntType(32), + [self.call_conv.get_return_type(types.pyobject)] + + argtys) + func = ir.Function(wrapper_module, fnty, fndesc.llvm_func_name) + + prefixed = itanium_mangler.prepend_namespace(func.name, ns='cudapy') + wrapfn = ir.Function(wrapper_module, wrapfnty, prefixed) + builder = ir.IRBuilder(wrapfn.append_basic_block('')) + + if debug or lineinfo: + directives_only = lineinfo and not debug + debuginfo = self.DIBuilder(module=wrapper_module, + filepath=filename, + cgctx=self, + directives_only=directives_only) + debuginfo.mark_subprogram( + wrapfn, kernel_name, fndesc.args, argtypes, linenum, + ) + debuginfo.mark_location(builder, linenum) + + # Define error handling variable + def define_error_gv(postfix): + name = wrapfn.name + postfix + gv = cgutils.add_global_variable(wrapper_module, ir.IntType(32), + name) + gv.initializer = ir.Constant(gv.type.pointee, None) + return gv + + gv_exc = define_error_gv("__errcode__") + gv_tid = [] + gv_ctaid = [] + for i in 'xyz': + gv_tid.append(define_error_gv("__tid%s__" % i)) + gv_ctaid.append(define_error_gv("__ctaid%s__" % i)) + + callargs = arginfo.from_arguments(builder, wrapfn.args) + status, _ = self.call_conv.call_function( + builder, func, types.void, argtypes, callargs) + + if debug: + # Check error status + with cgutils.if_likely(builder, status.is_ok): + builder.ret_void() + + with builder.if_then(builder.not_(status.is_python_exc)): + # User exception raised + old = ir.Constant(gv_exc.type.pointee, None) + + # Use atomic cmpxchg to prevent rewriting the error status + # Only the first error is recorded + + xchg = builder.cmpxchg(gv_exc, old, status.code, + 'monotonic', 'monotonic') + changed = builder.extract_value(xchg, 1) + + # If the xchange is successful, save the thread ID. + sreg = nvvmutils.SRegBuilder(builder) + with builder.if_then(changed): + for dim, ptr, in zip("xyz", gv_tid): + val = sreg.tid(dim) + builder.store(val, ptr) + + for dim, ptr, in zip("xyz", gv_ctaid): + val = sreg.ctaid(dim) + builder.store(val, ptr) + + builder.ret_void() + + nvvm.set_cuda_kernel(wrapfn) + library.add_ir_module(wrapper_module) + if debug or lineinfo: + debuginfo.finalize() + library.finalize() + + if config.DUMP_LLVM: + utils.dump_llvm(fndesc, wrapper_module) + + return library.get_function(wrapfn.name) + + def make_constant_array(self, builder, aryty, arr): + """ + Unlike the parent version. This returns a a pointer in the constant + addrspace. + """ + + lmod = builder.module + + constvals = [ + self.get_constant(types.byte, i) + for i in iter(arr.tobytes(order='A')) + ] + constaryty = ir.ArrayType(ir.IntType(8), len(constvals)) + constary = ir.Constant(constaryty, constvals) + + addrspace = nvvm.ADDRSPACE_CONSTANT + gv = cgutils.add_global_variable(lmod, constary.type, "_cudapy_cmem", + addrspace=addrspace) + gv.linkage = 'internal' + gv.global_constant = True + gv.initializer = constary + + # Preserve the underlying alignment + lldtype = self.get_data_type(aryty.dtype) + align = self.get_abi_sizeof(lldtype) + gv.align = 2 ** (align - 1).bit_length() + + # Convert to generic address-space + ptrty = ir.PointerType(ir.IntType(8)) + genptr = builder.addrspacecast(gv, ptrty, 'generic') + + # Create array object + ary = self.make_array(aryty)(self, builder) + kshape = [self.get_constant(types.intp, s) for s in arr.shape] + kstrides = [self.get_constant(types.intp, s) for s in arr.strides] + self.populate_array(ary, data=builder.bitcast(genptr, ary.data.type), + shape=kshape, + strides=kstrides, + itemsize=ary.itemsize, parent=ary.parent, + meminfo=None) + + return ary._getvalue() + + def insert_const_string(self, mod, string): + """ + Unlike the parent version. This returns a a pointer in the constant + addrspace. + """ + text = cgutils.make_bytearray(string.encode("utf-8") + b"\x00") + name = '$'.join(["__conststring__", + itanium_mangler.mangle_identifier(string)]) + # Try to reuse existing global + gv = mod.globals.get(name) + if gv is None: + # Not defined yet + gv = cgutils.add_global_variable(mod, text.type, name, + addrspace=nvvm.ADDRSPACE_CONSTANT) + gv.linkage = 'internal' + gv.global_constant = True + gv.initializer = text + + # Cast to a i8* pointer + charty = gv.type.pointee.element + return gv.bitcast(charty.as_pointer(nvvm.ADDRSPACE_CONSTANT)) + + def insert_string_const_addrspace(self, builder, string): + """ + Insert a constant string in the constant addresspace and return a + generic i8 pointer to the data. + + This function attempts to deduplicate. + """ + lmod = builder.module + gv = self.insert_const_string(lmod, string) + charptrty = ir.PointerType(ir.IntType(8)) + return builder.addrspacecast(gv, charptrty, 'generic') + + def optimize_function(self, func): + """Run O1 function passes + """ + pass + ## XXX skipped for now + # fpm = lp.FunctionPassManager.new(func.module) + # + # lp.PassManagerBuilder.new().populate(fpm) + # + # fpm.initialize() + # fpm.run(func) + # fpm.finalize() + + def get_ufunc_info(self, ufunc_key): + return ufuncs.get_ufunc_info(ufunc_key) + + +class CUDACallConv(MinimalCallConv): + pass + + +class CUDACABICallConv(BaseCallConv): + """ + Calling convention aimed at matching the CUDA C/C++ ABI. The implemented + function signature is: + + () + + Exceptions are unsupported in this convention. + """ + + def _make_call_helper(self, builder): + # Call helpers are used to help report exceptions back to Python, so + # none is required here. + return None + + def return_value(self, builder, retval): + return builder.ret(retval) + + def return_user_exc(self, builder, exc, exc_args=None, loc=None, + func_name=None): + msg = "Python exceptions are unsupported in the CUDA C/C++ ABI" + raise NotImplementedError(msg) + + def return_status_propagate(self, builder, status): + msg = "Return status is unsupported in the CUDA C/C++ ABI" + raise NotImplementedError(msg) + + def get_function_type(self, restype, argtypes): + """ + Get the LLVM IR Function type for *restype* and *argtypes*. + """ + arginfo = self._get_arg_packer(argtypes) + argtypes = list(arginfo.argument_types) + fnty = ir.FunctionType(self.get_return_type(restype), argtypes) + return fnty + + def decorate_function(self, fn, args, fe_argtypes, noalias=False): + """ + Set names and attributes of function arguments. + """ + assert not noalias + arginfo = self._get_arg_packer(fe_argtypes) + arginfo.assign_names(self.get_arguments(fn), + ['arg.' + a for a in args]) + + def get_arguments(self, func): + """ + Get the Python-level arguments of LLVM *func*. + """ + return func.args + + def call_function(self, builder, callee, resty, argtys, args): + """ + Call the Numba-compiled *callee*. + """ + arginfo = self._get_arg_packer(argtys) + realargs = arginfo.as_arguments(builder, args) + code = builder.call(callee, realargs) + # No status required as we don't support exceptions or a distinct None + # value in a C ABI. + status = None + out = self.context.get_returned_value(builder, resty, code) + return status, out + + def get_return_type(self, ty): + return self.context.data_model_manager[ty].get_return_type() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/testing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..ae62d3368662c0f8ff43ee403845b66d29410c77 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/testing.py @@ -0,0 +1,202 @@ +import os +import platform +import shutil + +from numba.tests.support import SerialMixin +from numba.cuda.cuda_paths import get_conda_ctk +from numba.cuda.cudadrv import driver, devices, libs +from numba.core import config +from numba.tests.support import TestCase +from pathlib import Path +import unittest + +numba_cuda_dir = Path(__file__).parent +test_data_dir = numba_cuda_dir / 'tests' / 'data' + + +class CUDATestCase(SerialMixin, TestCase): + """ + For tests that use a CUDA device. Test methods in a CUDATestCase must not + be run out of module order, because the ContextResettingTestCase may reset + the context and destroy resources used by a normal CUDATestCase if any of + its tests are run between tests from a CUDATestCase. + """ + + def setUp(self): + self._low_occupancy_warnings = config.CUDA_LOW_OCCUPANCY_WARNINGS + self._warn_on_implicit_copy = config.CUDA_WARN_ON_IMPLICIT_COPY + + # Disable warnings about low gpu utilization in the test suite + config.CUDA_LOW_OCCUPANCY_WARNINGS = 0 + # Disable warnings about host arrays in the test suite + config.CUDA_WARN_ON_IMPLICIT_COPY = 0 + + def tearDown(self): + config.CUDA_LOW_OCCUPANCY_WARNINGS = self._low_occupancy_warnings + config.CUDA_WARN_ON_IMPLICIT_COPY = self._warn_on_implicit_copy + + def skip_if_lto(self, reason): + # Some linkers need the compute capability to be specified, so we + # always specify it here. + cc = devices.get_context().device.compute_capability + linker = driver.Linker.new(cc=cc) + if linker.lto: + self.skipTest(reason) + + +class ContextResettingTestCase(CUDATestCase): + """ + For tests where the context needs to be reset after each test. Typically + these inspect or modify parts of the context that would usually be expected + to be internal implementation details (such as the state of allocations and + deallocations, etc.). + """ + + def tearDown(self): + super().tearDown() + from numba.cuda.cudadrv.devices import reset + reset() + + +def ensure_supported_ccs_initialized(): + from numba.cuda import is_available as cuda_is_available + from numba.cuda.cudadrv import nvvm + + if cuda_is_available(): + # Ensure that cudart.so is loaded and the list of supported compute + # capabilities in the nvvm module is populated before a fork. This is + # needed because some compilation tests don't require a CUDA context, + # but do use NVVM, and it is required that libcudart.so should be + # loaded before a fork (note that the requirement is not explicitly + # documented). + nvvm.get_supported_ccs() + + +def skip_on_cudasim(reason): + """Skip this test if running on the CUDA simulator""" + return unittest.skipIf(config.ENABLE_CUDASIM, reason) + + +def skip_unless_cudasim(reason): + """Skip this test if running on CUDA hardware""" + return unittest.skipUnless(config.ENABLE_CUDASIM, reason) + + +def skip_unless_conda_cudatoolkit(reason): + """Skip test if the CUDA toolkit was not installed by Conda""" + return unittest.skipUnless(get_conda_ctk() is not None, reason) + + +def skip_if_external_memmgr(reason): + """Skip test if an EMM Plugin is in use""" + return unittest.skipIf(config.CUDA_MEMORY_MANAGER != 'default', reason) + + +def skip_under_cuda_memcheck(reason): + return unittest.skipIf(os.environ.get('CUDA_MEMCHECK') is not None, reason) + + +def skip_without_nvdisasm(reason): + nvdisasm_path = shutil.which('nvdisasm') + return unittest.skipIf(nvdisasm_path is None, reason) + + +def skip_with_nvdisasm(reason): + nvdisasm_path = shutil.which('nvdisasm') + return unittest.skipIf(nvdisasm_path is not None, reason) + + +def skip_on_arm(reason): + cpu = platform.processor() + is_arm = cpu.startswith('arm') or cpu.startswith('aarch') + return unittest.skipIf(is_arm, reason) + + +def skip_if_cuda_includes_missing(fn): + # Skip when cuda.h is not available - generally this should indicate + # whether the CUDA includes are available or not + cuda_h = os.path.join(config.CUDA_INCLUDE_PATH, 'cuda.h') + cuda_h_file = (os.path.exists(cuda_h) and os.path.isfile(cuda_h)) + reason = 'CUDA include dir not available on this system' + return unittest.skipUnless(cuda_h_file, reason)(fn) + + +def skip_if_mvc_enabled(reason): + """Skip a test if Minor Version Compatibility is enabled""" + return unittest.skipIf(config.CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY, + reason) + + +def skip_if_mvc_libraries_unavailable(fn): + libs_available = False + try: + import cubinlinker # noqa: F401 + import ptxcompiler # noqa: F401 + libs_available = True + except ImportError: + pass + + return unittest.skipUnless(libs_available, + "Requires cubinlinker and ptxcompiler")(fn) + + +def cc_X_or_above(major, minor): + if not config.ENABLE_CUDASIM: + cc = devices.get_context().device.compute_capability + return cc >= (major, minor) + else: + return True + + +def skip_unless_cc_50(fn): + return unittest.skipUnless(cc_X_or_above(5, 0), "requires cc >= 5.0")(fn) + + +def skip_unless_cc_53(fn): + return unittest.skipUnless(cc_X_or_above(5, 3), "requires cc >= 5.3")(fn) + + +def skip_unless_cc_60(fn): + return unittest.skipUnless(cc_X_or_above(6, 0), "requires cc >= 6.0")(fn) + + +def skip_unless_cc_75(fn): + return unittest.skipUnless(cc_X_or_above(7, 5), "requires cc >= 7.5")(fn) + + +def xfail_unless_cudasim(fn): + if config.ENABLE_CUDASIM: + return fn + else: + return unittest.expectedFailure(fn) + + +def skip_with_cuda_python(reason): + return unittest.skipIf(driver.USE_NV_BINDING, reason) + + +def cudadevrt_missing(): + if config.ENABLE_CUDASIM: + return False + try: + path = libs.get_cudalib('cudadevrt', static=True) + libs.check_static_lib(path) + except FileNotFoundError: + return True + return False + + +def skip_if_cudadevrt_missing(fn): + return unittest.skipIf(cudadevrt_missing(), 'cudadevrt missing')(fn) + + +class ForeignArray(object): + """ + Class for emulating an array coming from another library through the CUDA + Array interface. This just hides a DeviceNDArray so that it doesn't look + like a DeviceNDArray. + """ + + def __init__(self, arr): + self._arr = arr + self.__cuda_array_interface__ = arr.__cuda_array_interface__ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/types.py new file mode 100644 index 0000000000000000000000000000000000000000..531dcb2ccb22abcfea9f103df4ddb616728b4ca5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/types.py @@ -0,0 +1,37 @@ +from numba.core import types + + +class Dim3(types.Type): + """ + A 3-tuple (x, y, z) representing the position of a block or thread. + """ + def __init__(self): + super().__init__(name='Dim3') + + +class GridGroup(types.Type): + """ + The grid of all threads in a cooperative kernel launch. + """ + def __init__(self): + super().__init__(name='GridGroup') + + +dim3 = Dim3() +grid_group = GridGroup() + + +class CUDADispatcher(types.Dispatcher): + """The type of CUDA dispatchers""" + # This type exists (instead of using types.Dispatcher as the type of CUDA + # dispatchers) so that we can have an alternative lowering for them to the + # lowering of CPU dispatchers - the CPU target lowers all dispatchers as a + # constant address, but we need to lower to a dummy value because it's not + # generally valid to use the address of CUDA kernels and functions. + # + # Notes: it may be a bug in the CPU target that it lowers all dispatchers to + # a constant address - it should perhaps only lower dispatchers acting as + # first-class functions to a constant address. Even if that bug is fixed, it + # is still probably a good idea to have a separate type for CUDA + # dispatchers, and this type might get other differentiation from the CPU + # dispatcher type in future. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/ufuncs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/ufuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..f552370480e3df5d19095351b4cea8b3fc4069d6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/ufuncs.py @@ -0,0 +1,662 @@ +"""Contains information on how to translate different ufuncs for the CUDA +target. It is a database of different ufuncs and how each of its loops maps to +a function that implements the inner kernel of that ufunc (the inner kernel +being the per-element function). + +Use get_ufunc_info() to get the information related to a ufunc. +""" + +import math +import numpy as np +from functools import lru_cache +from numba.core import typing + + +def get_ufunc_info(ufunc_key): + return ufunc_db()[ufunc_key] + + +@lru_cache +def ufunc_db(): + # Imports here are at function scope to avoid circular imports + from numba.cpython import cmathimpl, mathimpl, numbers + from numba.np import npyfuncs + from numba.np.numpy_support import numpy_version + from numba.cuda.mathimpl import (get_unary_impl_for_fn_and_ty, + get_binary_impl_for_fn_and_ty) + + def np_unary_impl(fn, context, builder, sig, args): + npyfuncs._check_arity_and_homogeneity(sig, args, 1) + impl = get_unary_impl_for_fn_and_ty(fn, sig.args[0]) + return impl(context, builder, sig, args) + + def np_binary_impl(fn, context, builder, sig, args): + npyfuncs._check_arity_and_homogeneity(sig, args, 2) + impl = get_binary_impl_for_fn_and_ty(fn, sig.args[0]) + return impl(context, builder, sig, args) + + def np_real_log_impl(context, builder, sig, args): + return np_unary_impl(math.log, context, builder, sig, args) + + def np_real_log2_impl(context, builder, sig, args): + return np_unary_impl(math.log2, context, builder, sig, args) + + def np_real_log10_impl(context, builder, sig, args): + return np_unary_impl(math.log10, context, builder, sig, args) + + def np_real_sin_impl(context, builder, sig, args): + return np_unary_impl(math.sin, context, builder, sig, args) + + def np_real_cos_impl(context, builder, sig, args): + return np_unary_impl(math.cos, context, builder, sig, args) + + def np_real_tan_impl(context, builder, sig, args): + return np_unary_impl(math.tan, context, builder, sig, args) + + def np_real_asin_impl(context, builder, sig, args): + return np_unary_impl(math.asin, context, builder, sig, args) + + def np_real_acos_impl(context, builder, sig, args): + return np_unary_impl(math.acos, context, builder, sig, args) + + def np_real_atan_impl(context, builder, sig, args): + return np_unary_impl(math.atan, context, builder, sig, args) + + def np_real_atan2_impl(context, builder, sig, args): + return np_binary_impl(math.atan2, context, builder, sig, args) + + def np_real_hypot_impl(context, builder, sig, args): + return np_binary_impl(math.hypot, context, builder, sig, args) + + def np_real_sinh_impl(context, builder, sig, args): + return np_unary_impl(math.sinh, context, builder, sig, args) + + def np_complex_sinh_impl(context, builder, sig, args): + # npymath does not provide a complex sinh. The code in funcs.inc.src + # is translated here... + npyfuncs._check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty] * 2) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + xr = x.real + xi = x.imag + + sxi = np_real_sin_impl(context, builder, fsig1, [xi]) + shxr = np_real_sinh_impl(context, builder, fsig1, [xr]) + cxi = np_real_cos_impl(context, builder, fsig1, [xi]) + chxr = np_real_cosh_impl(context, builder, fsig1, [xr]) + + out.real = builder.fmul(cxi, shxr) + out.imag = builder.fmul(sxi, chxr) + + return out._getvalue() + + def np_real_cosh_impl(context, builder, sig, args): + return np_unary_impl(math.cosh, context, builder, sig, args) + + def np_complex_cosh_impl(context, builder, sig, args): + # npymath does not provide a complex cosh. The code in funcs.inc.src + # is translated here... + npyfuncs._check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty] * 2) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + xr = x.real + xi = x.imag + + cxi = np_real_cos_impl(context, builder, fsig1, [xi]) + chxr = np_real_cosh_impl(context, builder, fsig1, [xr]) + sxi = np_real_sin_impl(context, builder, fsig1, [xi]) + shxr = np_real_sinh_impl(context, builder, fsig1, [xr]) + + out.real = builder.fmul(cxi, chxr) + out.imag = builder.fmul(sxi, shxr) + + return out._getvalue() + + def np_real_tanh_impl(context, builder, sig, args): + return np_unary_impl(math.tanh, context, builder, sig, args) + + def np_complex_tanh_impl(context, builder, sig, args): + # npymath does not provide complex tan functions. The code + # in funcs.inc.src for tanh is translated here... + npyfuncs._check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty] * 2) + ONE = context.get_constant(fty, 1.0) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + + xr = x.real + xi = x.imag + si = np_real_sin_impl(context, builder, fsig1, [xi]) + ci = np_real_cos_impl(context, builder, fsig1, [xi]) + shr = np_real_sinh_impl(context, builder, fsig1, [xr]) + chr_ = np_real_cosh_impl(context, builder, fsig1, [xr]) + rs = builder.fmul(ci, shr) + is_ = builder.fmul(si, chr_) + rc = builder.fmul(ci, chr_) + # Note: opposite sign for `ic` from code in funcs.inc.src + ic = builder.fmul(si, shr) + sqr_rc = builder.fmul(rc, rc) + sqr_ic = builder.fmul(ic, ic) + d = builder.fadd(sqr_rc, sqr_ic) + inv_d = builder.fdiv(ONE, d) + rs_rc = builder.fmul(rs, rc) + is_ic = builder.fmul(is_, ic) + is_rc = builder.fmul(is_, rc) + rs_ic = builder.fmul(rs, ic) + numr = builder.fadd(rs_rc, is_ic) + numi = builder.fsub(is_rc, rs_ic) + out.real = builder.fmul(numr, inv_d) + out.imag = builder.fmul(numi, inv_d) + + return out._getvalue() + + def np_real_asinh_impl(context, builder, sig, args): + return np_unary_impl(math.asinh, context, builder, sig, args) + + def np_real_acosh_impl(context, builder, sig, args): + return np_unary_impl(math.acosh, context, builder, sig, args) + + def np_real_atanh_impl(context, builder, sig, args): + return np_unary_impl(math.atanh, context, builder, sig, args) + + db = {} + + db[np.sin] = { + 'f->f': np_real_sin_impl, + 'd->d': np_real_sin_impl, + 'F->F': npyfuncs.np_complex_sin_impl, + 'D->D': npyfuncs.np_complex_sin_impl, + } + + db[np.cos] = { + 'f->f': np_real_cos_impl, + 'd->d': np_real_cos_impl, + 'F->F': npyfuncs.np_complex_cos_impl, + 'D->D': npyfuncs.np_complex_cos_impl, + } + + db[np.tan] = { + 'f->f': np_real_tan_impl, + 'd->d': np_real_tan_impl, + 'F->F': cmathimpl.tan_impl, + 'D->D': cmathimpl.tan_impl, + } + + db[np.arcsin] = { + 'f->f': np_real_asin_impl, + 'd->d': np_real_asin_impl, + 'F->F': cmathimpl.asin_impl, + 'D->D': cmathimpl.asin_impl, + } + + db[np.arccos] = { + 'f->f': np_real_acos_impl, + 'd->d': np_real_acos_impl, + 'F->F': cmathimpl.acos_impl, + 'D->D': cmathimpl.acos_impl, + } + + db[np.arctan] = { + 'f->f': np_real_atan_impl, + 'd->d': np_real_atan_impl, + 'F->F': cmathimpl.atan_impl, + 'D->D': cmathimpl.atan_impl, + } + + db[np.arctan2] = { + 'ff->f': np_real_atan2_impl, + 'dd->d': np_real_atan2_impl, + } + + db[np.hypot] = { + 'ff->f': np_real_hypot_impl, + 'dd->d': np_real_hypot_impl, + } + + db[np.sinh] = { + 'f->f': np_real_sinh_impl, + 'd->d': np_real_sinh_impl, + 'F->F': np_complex_sinh_impl, + 'D->D': np_complex_sinh_impl, + } + + db[np.cosh] = { + 'f->f': np_real_cosh_impl, + 'd->d': np_real_cosh_impl, + 'F->F': np_complex_cosh_impl, + 'D->D': np_complex_cosh_impl, + } + + db[np.tanh] = { + 'f->f': np_real_tanh_impl, + 'd->d': np_real_tanh_impl, + 'F->F': np_complex_tanh_impl, + 'D->D': np_complex_tanh_impl, + } + + db[np.arcsinh] = { + 'f->f': np_real_asinh_impl, + 'd->d': np_real_asinh_impl, + 'F->F': cmathimpl.asinh_impl, + 'D->D': cmathimpl.asinh_impl, + } + + db[np.arccosh] = { + 'f->f': np_real_acosh_impl, + 'd->d': np_real_acosh_impl, + 'F->F': npyfuncs.np_complex_acosh_impl, + 'D->D': npyfuncs.np_complex_acosh_impl, + } + + db[np.arctanh] = { + 'f->f': np_real_atanh_impl, + 'd->d': np_real_atanh_impl, + 'F->F': cmathimpl.atanh_impl, + 'D->D': cmathimpl.atanh_impl, + } + + db[np.deg2rad] = { + 'f->f': mathimpl.radians_float_impl, + 'd->d': mathimpl.radians_float_impl, + } + + db[np.radians] = db[np.deg2rad] + + db[np.rad2deg] = { + 'f->f': mathimpl.degrees_float_impl, + 'd->d': mathimpl.degrees_float_impl, + } + + db[np.degrees] = db[np.rad2deg] + + db[np.greater] = { + '??->?': numbers.int_ugt_impl, + 'bb->?': numbers.int_sgt_impl, + 'BB->?': numbers.int_ugt_impl, + 'hh->?': numbers.int_sgt_impl, + 'HH->?': numbers.int_ugt_impl, + 'ii->?': numbers.int_sgt_impl, + 'II->?': numbers.int_ugt_impl, + 'll->?': numbers.int_sgt_impl, + 'LL->?': numbers.int_ugt_impl, + 'qq->?': numbers.int_sgt_impl, + 'QQ->?': numbers.int_ugt_impl, + 'ff->?': numbers.real_gt_impl, + 'dd->?': numbers.real_gt_impl, + 'FF->?': npyfuncs.np_complex_gt_impl, + 'DD->?': npyfuncs.np_complex_gt_impl, + } + if numpy_version >= (1, 25): + db[np.greater].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('>'), + 'Qq->?': numbers.int_unsigned_signed_cmp('>')}) + + db[np.greater_equal] = { + '??->?': numbers.int_uge_impl, + 'bb->?': numbers.int_sge_impl, + 'BB->?': numbers.int_uge_impl, + 'hh->?': numbers.int_sge_impl, + 'HH->?': numbers.int_uge_impl, + 'ii->?': numbers.int_sge_impl, + 'II->?': numbers.int_uge_impl, + 'll->?': numbers.int_sge_impl, + 'LL->?': numbers.int_uge_impl, + 'qq->?': numbers.int_sge_impl, + 'QQ->?': numbers.int_uge_impl, + 'ff->?': numbers.real_ge_impl, + 'dd->?': numbers.real_ge_impl, + 'FF->?': npyfuncs.np_complex_ge_impl, + 'DD->?': npyfuncs.np_complex_ge_impl, + } + if numpy_version >= (1, 25): + db[np.greater_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('>='), + 'Qq->?': numbers.int_unsigned_signed_cmp('>=')}) + + db[np.less] = { + '??->?': numbers.int_ult_impl, + 'bb->?': numbers.int_slt_impl, + 'BB->?': numbers.int_ult_impl, + 'hh->?': numbers.int_slt_impl, + 'HH->?': numbers.int_ult_impl, + 'ii->?': numbers.int_slt_impl, + 'II->?': numbers.int_ult_impl, + 'll->?': numbers.int_slt_impl, + 'LL->?': numbers.int_ult_impl, + 'qq->?': numbers.int_slt_impl, + 'QQ->?': numbers.int_ult_impl, + 'ff->?': numbers.real_lt_impl, + 'dd->?': numbers.real_lt_impl, + 'FF->?': npyfuncs.np_complex_lt_impl, + 'DD->?': npyfuncs.np_complex_lt_impl, + } + if numpy_version >= (1, 25): + db[np.less].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('<'), + 'Qq->?': numbers.int_unsigned_signed_cmp('<')}) + + db[np.less_equal] = { + '??->?': numbers.int_ule_impl, + 'bb->?': numbers.int_sle_impl, + 'BB->?': numbers.int_ule_impl, + 'hh->?': numbers.int_sle_impl, + 'HH->?': numbers.int_ule_impl, + 'ii->?': numbers.int_sle_impl, + 'II->?': numbers.int_ule_impl, + 'll->?': numbers.int_sle_impl, + 'LL->?': numbers.int_ule_impl, + 'qq->?': numbers.int_sle_impl, + 'QQ->?': numbers.int_ule_impl, + 'ff->?': numbers.real_le_impl, + 'dd->?': numbers.real_le_impl, + 'FF->?': npyfuncs.np_complex_le_impl, + 'DD->?': npyfuncs.np_complex_le_impl, + } + if numpy_version >= (1, 25): + db[np.less_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('<='), + 'Qq->?': numbers.int_unsigned_signed_cmp('<=')}) + + db[np.not_equal] = { + '??->?': numbers.int_ne_impl, + 'bb->?': numbers.int_ne_impl, + 'BB->?': numbers.int_ne_impl, + 'hh->?': numbers.int_ne_impl, + 'HH->?': numbers.int_ne_impl, + 'ii->?': numbers.int_ne_impl, + 'II->?': numbers.int_ne_impl, + 'll->?': numbers.int_ne_impl, + 'LL->?': numbers.int_ne_impl, + 'qq->?': numbers.int_ne_impl, + 'QQ->?': numbers.int_ne_impl, + 'ff->?': numbers.real_ne_impl, + 'dd->?': numbers.real_ne_impl, + 'FF->?': npyfuncs.np_complex_ne_impl, + 'DD->?': npyfuncs.np_complex_ne_impl, + } + if numpy_version >= (1, 25): + db[np.not_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('!='), + 'Qq->?': numbers.int_unsigned_signed_cmp('!=')}) + + db[np.equal] = { + '??->?': numbers.int_eq_impl, + 'bb->?': numbers.int_eq_impl, + 'BB->?': numbers.int_eq_impl, + 'hh->?': numbers.int_eq_impl, + 'HH->?': numbers.int_eq_impl, + 'ii->?': numbers.int_eq_impl, + 'II->?': numbers.int_eq_impl, + 'll->?': numbers.int_eq_impl, + 'LL->?': numbers.int_eq_impl, + 'qq->?': numbers.int_eq_impl, + 'QQ->?': numbers.int_eq_impl, + 'ff->?': numbers.real_eq_impl, + 'dd->?': numbers.real_eq_impl, + 'FF->?': npyfuncs.np_complex_eq_impl, + 'DD->?': npyfuncs.np_complex_eq_impl, + } + if numpy_version >= (1, 25): + db[np.equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('=='), + 'Qq->?': numbers.int_unsigned_signed_cmp('==')}) + + db[np.logical_and] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->?': npyfuncs.np_logical_and_impl, + 'BB->?': npyfuncs.np_logical_and_impl, + 'hh->?': npyfuncs.np_logical_and_impl, + 'HH->?': npyfuncs.np_logical_and_impl, + 'ii->?': npyfuncs.np_logical_and_impl, + 'II->?': npyfuncs.np_logical_and_impl, + 'll->?': npyfuncs.np_logical_and_impl, + 'LL->?': npyfuncs.np_logical_and_impl, + 'qq->?': npyfuncs.np_logical_and_impl, + 'QQ->?': npyfuncs.np_logical_and_impl, + 'ff->?': npyfuncs.np_logical_and_impl, + 'dd->?': npyfuncs.np_logical_and_impl, + 'FF->?': npyfuncs.np_complex_logical_and_impl, + 'DD->?': npyfuncs.np_complex_logical_and_impl, + } + + db[np.logical_or] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->?': npyfuncs.np_logical_or_impl, + 'BB->?': npyfuncs.np_logical_or_impl, + 'hh->?': npyfuncs.np_logical_or_impl, + 'HH->?': npyfuncs.np_logical_or_impl, + 'ii->?': npyfuncs.np_logical_or_impl, + 'II->?': npyfuncs.np_logical_or_impl, + 'll->?': npyfuncs.np_logical_or_impl, + 'LL->?': npyfuncs.np_logical_or_impl, + 'qq->?': npyfuncs.np_logical_or_impl, + 'QQ->?': npyfuncs.np_logical_or_impl, + 'ff->?': npyfuncs.np_logical_or_impl, + 'dd->?': npyfuncs.np_logical_or_impl, + 'FF->?': npyfuncs.np_complex_logical_or_impl, + 'DD->?': npyfuncs.np_complex_logical_or_impl, + } + + db[np.logical_xor] = { + '??->?': npyfuncs.np_logical_xor_impl, + 'bb->?': npyfuncs.np_logical_xor_impl, + 'BB->?': npyfuncs.np_logical_xor_impl, + 'hh->?': npyfuncs.np_logical_xor_impl, + 'HH->?': npyfuncs.np_logical_xor_impl, + 'ii->?': npyfuncs.np_logical_xor_impl, + 'II->?': npyfuncs.np_logical_xor_impl, + 'll->?': npyfuncs.np_logical_xor_impl, + 'LL->?': npyfuncs.np_logical_xor_impl, + 'qq->?': npyfuncs.np_logical_xor_impl, + 'QQ->?': npyfuncs.np_logical_xor_impl, + 'ff->?': npyfuncs.np_logical_xor_impl, + 'dd->?': npyfuncs.np_logical_xor_impl, + 'FF->?': npyfuncs.np_complex_logical_xor_impl, + 'DD->?': npyfuncs.np_complex_logical_xor_impl, + } + + db[np.logical_not] = { + '?->?': npyfuncs.np_logical_not_impl, + 'b->?': npyfuncs.np_logical_not_impl, + 'B->?': npyfuncs.np_logical_not_impl, + 'h->?': npyfuncs.np_logical_not_impl, + 'H->?': npyfuncs.np_logical_not_impl, + 'i->?': npyfuncs.np_logical_not_impl, + 'I->?': npyfuncs.np_logical_not_impl, + 'l->?': npyfuncs.np_logical_not_impl, + 'L->?': npyfuncs.np_logical_not_impl, + 'q->?': npyfuncs.np_logical_not_impl, + 'Q->?': npyfuncs.np_logical_not_impl, + 'f->?': npyfuncs.np_logical_not_impl, + 'd->?': npyfuncs.np_logical_not_impl, + 'F->?': npyfuncs.np_complex_logical_not_impl, + 'D->?': npyfuncs.np_complex_logical_not_impl, + } + + db[np.maximum] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->b': npyfuncs.np_int_smax_impl, + 'BB->B': npyfuncs.np_int_umax_impl, + 'hh->h': npyfuncs.np_int_smax_impl, + 'HH->H': npyfuncs.np_int_umax_impl, + 'ii->i': npyfuncs.np_int_smax_impl, + 'II->I': npyfuncs.np_int_umax_impl, + 'll->l': npyfuncs.np_int_smax_impl, + 'LL->L': npyfuncs.np_int_umax_impl, + 'qq->q': npyfuncs.np_int_smax_impl, + 'QQ->Q': npyfuncs.np_int_umax_impl, + 'ff->f': npyfuncs.np_real_maximum_impl, + 'dd->d': npyfuncs.np_real_maximum_impl, + 'FF->F': npyfuncs.np_complex_maximum_impl, + 'DD->D': npyfuncs.np_complex_maximum_impl, + } + + db[np.minimum] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->b': npyfuncs.np_int_smin_impl, + 'BB->B': npyfuncs.np_int_umin_impl, + 'hh->h': npyfuncs.np_int_smin_impl, + 'HH->H': npyfuncs.np_int_umin_impl, + 'ii->i': npyfuncs.np_int_smin_impl, + 'II->I': npyfuncs.np_int_umin_impl, + 'll->l': npyfuncs.np_int_smin_impl, + 'LL->L': npyfuncs.np_int_umin_impl, + 'qq->q': npyfuncs.np_int_smin_impl, + 'QQ->Q': npyfuncs.np_int_umin_impl, + 'ff->f': npyfuncs.np_real_minimum_impl, + 'dd->d': npyfuncs.np_real_minimum_impl, + 'FF->F': npyfuncs.np_complex_minimum_impl, + 'DD->D': npyfuncs.np_complex_minimum_impl, + } + + db[np.fmax] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->b': npyfuncs.np_int_smax_impl, + 'BB->B': npyfuncs.np_int_umax_impl, + 'hh->h': npyfuncs.np_int_smax_impl, + 'HH->H': npyfuncs.np_int_umax_impl, + 'ii->i': npyfuncs.np_int_smax_impl, + 'II->I': npyfuncs.np_int_umax_impl, + 'll->l': npyfuncs.np_int_smax_impl, + 'LL->L': npyfuncs.np_int_umax_impl, + 'qq->q': npyfuncs.np_int_smax_impl, + 'QQ->Q': npyfuncs.np_int_umax_impl, + 'ff->f': npyfuncs.np_real_fmax_impl, + 'dd->d': npyfuncs.np_real_fmax_impl, + 'FF->F': npyfuncs.np_complex_fmax_impl, + 'DD->D': npyfuncs.np_complex_fmax_impl, + } + + db[np.fmin] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->b': npyfuncs.np_int_smin_impl, + 'BB->B': npyfuncs.np_int_umin_impl, + 'hh->h': npyfuncs.np_int_smin_impl, + 'HH->H': npyfuncs.np_int_umin_impl, + 'ii->i': npyfuncs.np_int_smin_impl, + 'II->I': npyfuncs.np_int_umin_impl, + 'll->l': npyfuncs.np_int_smin_impl, + 'LL->L': npyfuncs.np_int_umin_impl, + 'qq->q': npyfuncs.np_int_smin_impl, + 'QQ->Q': npyfuncs.np_int_umin_impl, + 'ff->f': npyfuncs.np_real_fmin_impl, + 'dd->d': npyfuncs.np_real_fmin_impl, + 'FF->F': npyfuncs.np_complex_fmin_impl, + 'DD->D': npyfuncs.np_complex_fmin_impl, + } + + db[np.bitwise_and] = { + '??->?': numbers.int_and_impl, + 'bb->b': numbers.int_and_impl, + 'BB->B': numbers.int_and_impl, + 'hh->h': numbers.int_and_impl, + 'HH->H': numbers.int_and_impl, + 'ii->i': numbers.int_and_impl, + 'II->I': numbers.int_and_impl, + 'll->l': numbers.int_and_impl, + 'LL->L': numbers.int_and_impl, + 'qq->q': numbers.int_and_impl, + 'QQ->Q': numbers.int_and_impl, + } + + db[np.bitwise_or] = { + '??->?': numbers.int_or_impl, + 'bb->b': numbers.int_or_impl, + 'BB->B': numbers.int_or_impl, + 'hh->h': numbers.int_or_impl, + 'HH->H': numbers.int_or_impl, + 'ii->i': numbers.int_or_impl, + 'II->I': numbers.int_or_impl, + 'll->l': numbers.int_or_impl, + 'LL->L': numbers.int_or_impl, + 'qq->q': numbers.int_or_impl, + 'QQ->Q': numbers.int_or_impl, + } + + db[np.bitwise_xor] = { + '??->?': numbers.int_xor_impl, + 'bb->b': numbers.int_xor_impl, + 'BB->B': numbers.int_xor_impl, + 'hh->h': numbers.int_xor_impl, + 'HH->H': numbers.int_xor_impl, + 'ii->i': numbers.int_xor_impl, + 'II->I': numbers.int_xor_impl, + 'll->l': numbers.int_xor_impl, + 'LL->L': numbers.int_xor_impl, + 'qq->q': numbers.int_xor_impl, + 'QQ->Q': numbers.int_xor_impl, + } + + db[np.invert] = { + '?->?': numbers.int_invert_impl, + 'b->b': numbers.int_invert_impl, + 'B->B': numbers.int_invert_impl, + 'h->h': numbers.int_invert_impl, + 'H->H': numbers.int_invert_impl, + 'i->i': numbers.int_invert_impl, + 'I->I': numbers.int_invert_impl, + 'l->l': numbers.int_invert_impl, + 'L->L': numbers.int_invert_impl, + 'q->q': numbers.int_invert_impl, + 'Q->Q': numbers.int_invert_impl, + } + + db[np.left_shift] = { + 'bb->b': numbers.int_shl_impl, + 'BB->B': numbers.int_shl_impl, + 'hh->h': numbers.int_shl_impl, + 'HH->H': numbers.int_shl_impl, + 'ii->i': numbers.int_shl_impl, + 'II->I': numbers.int_shl_impl, + 'll->l': numbers.int_shl_impl, + 'LL->L': numbers.int_shl_impl, + 'qq->q': numbers.int_shl_impl, + 'QQ->Q': numbers.int_shl_impl, + } + + db[np.right_shift] = { + 'bb->b': numbers.int_shr_impl, + 'BB->B': numbers.int_shr_impl, + 'hh->h': numbers.int_shr_impl, + 'HH->H': numbers.int_shr_impl, + 'ii->i': numbers.int_shr_impl, + 'II->I': numbers.int_shr_impl, + 'll->l': numbers.int_shr_impl, + 'LL->L': numbers.int_shr_impl, + 'qq->q': numbers.int_shr_impl, + 'QQ->Q': numbers.int_shr_impl, + } + + db[np.log] = { + 'f->f': np_real_log_impl, + 'd->d': np_real_log_impl, + 'F->F': npyfuncs.np_complex_log_impl, + 'D->D': npyfuncs.np_complex_log_impl, + } + + db[np.log2] = { + 'f->f': np_real_log2_impl, + 'd->d': np_real_log2_impl, + 'F->F': npyfuncs.np_complex_log2_impl, + 'D->D': npyfuncs.np_complex_log2_impl, + } + + db[np.log10] = { + 'f->f': np_real_log10_impl, + 'd->d': np_real_log10_impl, + 'F->F': npyfuncs.np_complex_log10_impl, + 'D->D': npyfuncs.np_complex_log10_impl, + } + + return db diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vector_types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vector_types.py new file mode 100644 index 0000000000000000000000000000000000000000..5174e2b20d389be8e0b7a58534808a56ac742c35 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vector_types.py @@ -0,0 +1,209 @@ +# CUDA built-in Vector Types +# https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#built-in-vector-types + +from typing import List, Tuple, Dict + +from numba import types +from numba.core import cgutils +from numba.core.extending import make_attribute_wrapper, models, register_model +from numba.core.imputils import Registry as ImplRegistry +from numba.core.typing.templates import ConcreteTemplate +from numba.core.typing.templates import Registry as TypingRegistry +from numba.core.typing.templates import signature +from numba.cuda import stubs +from numba.cuda.errors import CudaLoweringError + +typing_registry = TypingRegistry() +impl_registry = ImplRegistry() + +register = typing_registry.register +register_attr = typing_registry.register_attr +register_global = typing_registry.register_global +lower = impl_registry.lower + + +class VectorType(types.Type): + def __init__(self, name, base_type, attr_names, user_facing_object): + self._base_type = base_type + self._attr_names = attr_names + self._user_facing_object = user_facing_object + super().__init__(name=name) + + @property + def base_type(self): + return self._base_type + + @property + def attr_names(self): + return self._attr_names + + @property + def num_elements(self): + return len(self._attr_names) + + @property + def user_facing_object(self): + return self._user_facing_object + + +def make_vector_type( + name: str, + base_type: types.Type, + attr_names: Tuple[str, ...], + user_facing_object +) -> types.Type: + """Create a vector type. + + Parameters + ---------- + name: str + The name of the type. + base_type: numba.types.Type + The primitive type for each element in the vector. + attr_names: tuple of str + Name for each attribute. + user_facing_object: object + The handle to be used in cuda kernel. + """ + + class _VectorType(VectorType): + """Internal instantiation of VectorType.""" + + pass + + class VectorTypeModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [(attr_name, base_type) for attr_name in attr_names] + super().__init__(dmm, fe_type, members) + + vector_type = _VectorType(name, base_type, attr_names, user_facing_object) + register_model(_VectorType)(VectorTypeModel) + for attr_name in attr_names: + make_attribute_wrapper(_VectorType, attr_name, attr_name) + + return vector_type + + +def enable_vector_type_ctor( + vector_type: VectorType, overloads: List[List[types.Type]] +): + """Create typing and lowering for vector type constructor. + + Parameters + ---------- + vector_type: VectorType + The type whose constructor to type and lower. + overloads: List of argument types + A list containing different overloads of the constructor. Each base type + in the argument list should either be primitive type or VectorType. + """ + ctor = vector_type.user_facing_object + + @register + class CtorTemplate(ConcreteTemplate): + key = ctor + cases = [signature(vector_type, *arglist) for arglist in overloads] + + register_global(ctor, types.Function(CtorTemplate)) + + # Lowering + + def make_lowering(fml_arg_list): + """Meta function to create a lowering for the constructor. Flattens + the arguments by converting vector_type into load instructions for each + of its attributes. Such as float2 -> float2.x, float2.y. + """ + + def lowering(context, builder, sig, actual_args): + # A list of elements to assign from + source_list = [] + # Convert the list of argument types to a list of load IRs. + for argidx, fml_arg in enumerate(fml_arg_list): + if isinstance(fml_arg, VectorType): + pxy = cgutils.create_struct_proxy(fml_arg)( + context, builder, actual_args[argidx] + ) + source_list += [ + getattr(pxy, attr) for attr in fml_arg.attr_names + ] + else: + # assumed primitive type + source_list.append(actual_args[argidx]) + + if len(source_list) != vector_type.num_elements: + raise CudaLoweringError( + f"Unmatched number of source elements ({len(source_list)}) " + "and target elements ({vector_type.num_elements})." + ) + + out = cgutils.create_struct_proxy(vector_type)(context, builder) + + for attr_name, source in zip(vector_type.attr_names, source_list): + setattr(out, attr_name, source) + return out._getvalue() + + return lowering + + for arglist in overloads: + lowering = make_lowering(arglist) + lower(ctor, *arglist)(lowering) + + +vector_types : Dict[str, VectorType] = {} + + +def build_constructor_overloads(base_type, vty_name, num_elements, arglists, l): + """ + For a given vector type, build a list of overloads for its constructor. + """ + + # TODO: speed up with memoization + if num_elements == 0: + arglists.append(l[:]) + + for i in range(1, num_elements + 1): + if i == 1: + # For 1-element component, it can construct with either a + # primitive type or other 1-element component. + l.append(base_type) + build_constructor_overloads( + base_type, vty_name, num_elements - i, arglists, l + ) + l.pop(-1) + + l.append(vector_types[f"{vty_name[:-1]}1"]) + build_constructor_overloads( + base_type, vty_name, num_elements - i, arglists, l + ) + l.pop(-1) + else: + l.append(vector_types[f"{vty_name[:-1]}{i}"]) + build_constructor_overloads( + base_type, vty_name, num_elements - i, arglists, l + ) + l.pop(-1) + + +def _initialize(): + """ + Construct the vector types, populate `vector_types` dictionary, and + enable the constructors. + """ + vector_type_attribute_names = ("x", "y", "z", "w") + for stub in stubs._vector_type_stubs: + type_name = stub.__name__ + base_type = getattr(types, type_name[:-2]) + num_elements = int(type_name[-1]) + attributes = vector_type_attribute_names[:num_elements] + vector_type = make_vector_type(type_name, base_type, attributes, stub) + vector_types[type_name] = vector_type + + for vty in vector_types.values(): + arglists, l = [], [] + build_constructor_overloads( + vty.base_type, vty.name, vty.num_elements, arglists, l + ) + enable_vector_type_ctor(vty, arglists) + + +_initialize() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vectorizers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vectorizers.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c6bcf5d451f05d2d822beaaa1d740e5e91d460 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/cuda/vectorizers.py @@ -0,0 +1,252 @@ +from numba import cuda +from numpy import array as np_array +from numba.cuda import deviceufunc +from numba.cuda.deviceufunc import (UFuncMechanism, GeneralizedUFunc, + GUFuncCallSteps) + + +class CUDAUFuncDispatcher(object): + """ + Invoke the CUDA ufunc specialization for the given inputs. + """ + + def __init__(self, types_to_retty_kernels, pyfunc): + self.functions = types_to_retty_kernels + self.__name__ = pyfunc.__name__ + + def __call__(self, *args, **kws): + """ + *args: numpy arrays or DeviceArrayBase (created by cuda.to_device). + Cannot mix the two types in one call. + + **kws: + stream -- cuda stream; when defined, asynchronous mode is used. + out -- output array. Can be a numpy array or DeviceArrayBase + depending on the input arguments. Type must match + the input arguments. + """ + return CUDAUFuncMechanism.call(self.functions, args, kws) + + def reduce(self, arg, stream=0): + assert len(list(self.functions.keys())[0]) == 2, "must be a binary " \ + "ufunc" + assert arg.ndim == 1, "must use 1d array" + + n = arg.shape[0] + gpu_mems = [] + + if n == 0: + raise TypeError("Reduction on an empty array.") + elif n == 1: # nothing to do + return arg[0] + + # always use a stream + stream = stream or cuda.stream() + with stream.auto_synchronize(): + # transfer memory to device if necessary + if cuda.cudadrv.devicearray.is_cuda_ndarray(arg): + mem = arg + else: + mem = cuda.to_device(arg, stream) + # do reduction + out = self.__reduce(mem, gpu_mems, stream) + # use a small buffer to store the result element + buf = np_array((1,), dtype=arg.dtype) + out.copy_to_host(buf, stream=stream) + + return buf[0] + + def __reduce(self, mem, gpu_mems, stream): + n = mem.shape[0] + if n % 2 != 0: # odd? + fatcut, thincut = mem.split(n - 1) + # prevent freeing during async mode + gpu_mems.append(fatcut) + gpu_mems.append(thincut) + # execute the kernel + out = self.__reduce(fatcut, gpu_mems, stream) + gpu_mems.append(out) + return self(out, thincut, out=out, stream=stream) + else: # even? + left, right = mem.split(n // 2) + # prevent freeing during async mode + gpu_mems.append(left) + gpu_mems.append(right) + # execute the kernel + self(left, right, out=left, stream=stream) + if n // 2 > 1: + return self.__reduce(left, gpu_mems, stream) + else: + return left + + +class _CUDAGUFuncCallSteps(GUFuncCallSteps): + __slots__ = [ + '_stream', + ] + + def __init__(self, nin, nout, args, kwargs): + super().__init__(nin, nout, args, kwargs) + self._stream = kwargs.get('stream', 0) + + def is_device_array(self, obj): + return cuda.is_cuda_array(obj) + + def as_device_array(self, obj): + # We don't want to call as_cuda_array on objects that are already Numba + # device arrays, because this results in exporting the array as a + # Producer then importing it as a Consumer, which causes a + # synchronization on the array's stream (if it has one) by default. + # When we have a Numba device array, we can simply return it. + if cuda.cudadrv.devicearray.is_cuda_ndarray(obj): + return obj + return cuda.as_cuda_array(obj) + + def to_device(self, hostary): + return cuda.to_device(hostary, stream=self._stream) + + def to_host(self, devary, hostary): + out = devary.copy_to_host(hostary, stream=self._stream) + return out + + def allocate_device_array(self, shape, dtype): + return cuda.device_array(shape=shape, dtype=dtype, stream=self._stream) + + def launch_kernel(self, kernel, nelem, args): + kernel.forall(nelem, stream=self._stream)(*args) + + +class CUDAGeneralizedUFunc(GeneralizedUFunc): + def __init__(self, kernelmap, engine, pyfunc): + self.__name__ = pyfunc.__name__ + super().__init__(kernelmap, engine) + + @property + def _call_steps(self): + return _CUDAGUFuncCallSteps + + def _broadcast_scalar_input(self, ary, shape): + return cuda.cudadrv.devicearray.DeviceNDArray(shape=shape, + strides=(0,), + dtype=ary.dtype, + gpu_data=ary.gpu_data) + + def _broadcast_add_axis(self, ary, newshape): + newax = len(newshape) - len(ary.shape) + # Add 0 strides for missing dimension + newstrides = (0,) * newax + ary.strides + return cuda.cudadrv.devicearray.DeviceNDArray(shape=newshape, + strides=newstrides, + dtype=ary.dtype, + gpu_data=ary.gpu_data) + + +class CUDAUFuncMechanism(UFuncMechanism): + """ + Provide CUDA specialization + """ + DEFAULT_STREAM = 0 + + def launch(self, func, count, stream, args): + func.forall(count, stream=stream)(*args) + + def is_device_array(self, obj): + return cuda.is_cuda_array(obj) + + def as_device_array(self, obj): + # We don't want to call as_cuda_array on objects that are already Numba + # device arrays, because this results in exporting the array as a + # Producer then importing it as a Consumer, which causes a + # synchronization on the array's stream (if it has one) by default. + # When we have a Numba device array, we can simply return it. + if cuda.cudadrv.devicearray.is_cuda_ndarray(obj): + return obj + return cuda.as_cuda_array(obj) + + def to_device(self, hostary, stream): + return cuda.to_device(hostary, stream=stream) + + def to_host(self, devary, stream): + return devary.copy_to_host(stream=stream) + + def allocate_device_array(self, shape, dtype, stream): + return cuda.device_array(shape=shape, dtype=dtype, stream=stream) + + def broadcast_device(self, ary, shape): + ax_differs = [ax for ax in range(len(shape)) + if ax >= ary.ndim + or ary.shape[ax] != shape[ax]] + + missingdim = len(shape) - len(ary.shape) + strides = [0] * missingdim + list(ary.strides) + + for ax in ax_differs: + strides[ax] = 0 + + return cuda.cudadrv.devicearray.DeviceNDArray(shape=shape, + strides=strides, + dtype=ary.dtype, + gpu_data=ary.gpu_data) + + +vectorizer_stager_source = ''' +def __vectorized_{name}({args}, __out__): + __tid__ = __cuda__.grid(1) + if __tid__ < __out__.shape[0]: + __out__[__tid__] = __core__({argitems}) +''' + + +class CUDAVectorize(deviceufunc.DeviceVectorize): + def _compile_core(self, sig): + cudevfn = cuda.jit(sig, device=True, inline=True)(self.pyfunc) + return cudevfn, cudevfn.overloads[sig.args].signature.return_type + + def _get_globals(self, corefn): + glbl = self.pyfunc.__globals__.copy() + glbl.update({'__cuda__': cuda, + '__core__': corefn}) + return glbl + + def _compile_kernel(self, fnobj, sig): + return cuda.jit(fnobj) + + def build_ufunc(self): + return CUDAUFuncDispatcher(self.kernelmap, self.pyfunc) + + @property + def _kernel_template(self): + return vectorizer_stager_source + + +# ------------------------------------------------------------------------------ +# Generalized CUDA ufuncs + +_gufunc_stager_source = ''' +def __gufunc_{name}({args}): + __tid__ = __cuda__.grid(1) + if __tid__ < {checkedarg}: + __core__({argitems}) +''' + + +class CUDAGUFuncVectorize(deviceufunc.DeviceGUFuncVectorize): + def build_ufunc(self): + engine = deviceufunc.GUFuncEngine(self.inputsig, self.outputsig) + return CUDAGeneralizedUFunc(kernelmap=self.kernelmap, + engine=engine, + pyfunc=self.pyfunc) + + def _compile_kernel(self, fnobj, sig): + return cuda.jit(sig)(fnobj) + + @property + def _kernel_template(self): + return _gufunc_stager_source + + def _get_globals(self, sig): + corefn = cuda.jit(sig, device=True)(self.pyfunc) + glbls = self.py_func.__globals__.copy() + glbls.update({'__cuda__': cuda, + '__core__': corefn}) + return glbls diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc3359e90ec5403f4eb3fd6e4be121a1a7228ce --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/__init__.py @@ -0,0 +1 @@ +from .jitclass import jitclass \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/function_type.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/function_type.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8527865ef00afc793c22ebfd045f339ca60d40 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/function_type.py @@ -0,0 +1,332 @@ +"""Provides Numba type, FunctionType, that makes functions as +instances of a first-class function type. +""" +from functools import partial + +from numba.extending import typeof_impl +from numba.extending import models, register_model +from numba.extending import unbox, NativeValue, box +from numba.core.imputils import lower_constant, lower_cast +from numba.core.ccallback import CFunc +from numba.core import cgutils +from llvmlite import ir +from numba.core import types, errors +from numba.core.types import (FunctionType, UndefinedFunctionType, + FunctionPrototype, WrapperAddressProtocol) +from numba.core.dispatcher import Dispatcher + + +@typeof_impl.register(WrapperAddressProtocol) +@typeof_impl.register(CFunc) +def typeof_function_type(val, c): + if isinstance(val, CFunc): + sig = val._sig + elif isinstance(val, WrapperAddressProtocol): + sig = val.signature() + else: + raise NotImplementedError( + f'function type from {type(val).__name__}') + return FunctionType(sig) + + +@register_model(FunctionPrototype) +class FunctionProtoModel(models.PrimitiveModel): + """FunctionProtoModel describes the signatures of first-class functions + """ + def __init__(self, dmm, fe_type): + if isinstance(fe_type, FunctionType): + ftype = fe_type.ftype + elif isinstance(fe_type, FunctionPrototype): + ftype = fe_type + else: + raise NotImplementedError((type(fe_type))) + retty = dmm.lookup(ftype.rtype).get_value_type() + args = [dmm.lookup(t).get_value_type() for t in ftype.atypes] + be_type = ir.PointerType(ir.FunctionType(retty, args)) + super(FunctionProtoModel, self).__init__(dmm, fe_type, be_type) + + +@register_model(FunctionType) +@register_model(UndefinedFunctionType) +class FunctionModel(models.StructModel): + """FunctionModel holds addresses of function implementations + """ + def __init__(self, dmm, fe_type): + members = [ + # Address of cfunc wrapper function. + # This uses a C callconv and doesn't not support exceptions. + ('c_addr', types.voidptr), + # Address of PyObject* referencing the Python function + # object: + ('py_addr', types.voidptr), + # Address of the underlying function object. + # Calling through this function pointer supports all features of + # regular numba function as it follows the same Numba callconv. + ('jit_addr', types.voidptr), + ] + super(FunctionModel, self).__init__(dmm, fe_type, members) + + +@lower_constant(types.Dispatcher) +def lower_constant_dispatcher(context, builder, typ, pyval): + return context.add_dynamic_addr(builder, id(pyval), + info=type(pyval).__name__) + + +@lower_constant(FunctionType) +def lower_constant_function_type(context, builder, typ, pyval): + typ = typ.get_precise() + + if isinstance(pyval, CFunc): + addr = pyval._wrapper_address + sfunc = cgutils.create_struct_proxy(typ)(context, builder) + sfunc.c_addr = context.add_dynamic_addr(builder, addr, + info=str(typ)) + sfunc.py_addr = context.add_dynamic_addr(builder, id(pyval), + info=type(pyval).__name__) + return sfunc._getvalue() + + if isinstance(pyval, Dispatcher): + sfunc = cgutils.create_struct_proxy(typ)(context, builder) + sfunc.py_addr = context.add_dynamic_addr(builder, id(pyval), + info=type(pyval).__name__) + return sfunc._getvalue() + + if isinstance(pyval, WrapperAddressProtocol): + addr = pyval.__wrapper_address__() + assert typ.check_signature(pyval.signature()) + sfunc = cgutils.create_struct_proxy(typ)(context, builder) + sfunc.c_addr = context.add_dynamic_addr(builder, addr, + info=str(typ)) + sfunc.py_addr = context.add_dynamic_addr(builder, id(pyval), + info=type(pyval).__name__) + return sfunc._getvalue() + + # TODO: implement support for pytypes.FunctionType, ctypes.CFUNCTYPE + raise NotImplementedError( + 'lower_constant_struct_function_type({}, {}, {}, {})' + .format(context, builder, typ, pyval)) + + +def _get_wrapper_address(func, sig): + """Return the address of a compiled cfunc wrapper function of `func`. + + Warning: The compiled function must be compatible with the given + signature `sig`. If it is not, then result of calling the compiled + function is undefined. The compatibility is ensured when passing + in a first-class function to a Numba njit compiled function either + as an argument or via namespace scoping. + + Parameters + ---------- + func : object + A Numba cfunc or jit decoreated function or an object that + implements the wrapper address protocol (see note below). + sig : Signature + The expected function signature. + + Returns + ------- + addr : int + An address in memory (pointer value) of the compiled function + corresponding to the specified signature. + + Note: wrapper address protocol + ------------------------------ + + An object implements the wrapper address protocol iff the object + provides a callable attribute named __wrapper_address__ that takes + a Signature instance as the argument, and returns an integer + representing the address or pointer value of a compiled function + for the given signature. + + """ + if not sig.is_precise(): + # addr==-1 will indicate that no implementation is available + # for cases where type-inference did not identified the + # function type. For example, the type of an unused + # jit-decorated function argument will be undefined but also + # irrelevant. + addr = -1 + elif hasattr(func, '__wrapper_address__'): + # func can be any object that implements the + # __wrapper_address__ protocol. + addr = func.__wrapper_address__() + elif isinstance(func, CFunc): + assert sig == func._sig + addr = func.address + elif isinstance(func, Dispatcher): + cres = func.get_compile_result(sig) + wrapper_name = cres.fndesc.llvm_cfunc_wrapper_name + addr = cres.library.get_pointer_to_function(wrapper_name) + else: + raise NotImplementedError( + f'get wrapper address of {type(func)} instance with {sig!r}') + if not isinstance(addr, int): + raise TypeError( + f'wrapper address must be integer, got {type(addr)} instance') + if addr <= 0 and addr != -1: + raise ValueError(f'wrapper address of {type(func)} instance must be' + f' a positive integer but got {addr} [sig={sig}]') + # print(f'_get_wrapper_address[{func}]({sig=}) -> {addr}') + return addr + + +def _get_jit_address(func, sig): + """Similar to ``_get_wrapper_address()`` but get the `.jit_addr` instead. + """ + if isinstance(func, Dispatcher): + cres = func.get_compile_result(sig) + jit_name = cres.fndesc.llvm_func_name + addr = cres.library.get_pointer_to_function(jit_name) + else: + addr = 0 + if not isinstance(addr, int): + raise TypeError( + f'jit address must be integer, got {type(addr)} instance') + return addr + + +def _lower_get_address(context, builder, func, sig, failure_mode, + *, function_name): + """Low-level call to (func, sig). + + When calling this function, GIL must be acquired. + """ + pyapi = context.get_python_api(builder) + + # Get the cfunc wrapper address. The code below trusts that the + # function numba.function._get_wrapper_address exists and can be + # called with two arguments. However, if an exception is raised in + # the function, then it will be caught and propagated to the + # caller. + + modname = context.insert_const_string(builder.module, __name__) + numba_mod = pyapi.import_module(modname) + numba_func = pyapi.object_getattr_string(numba_mod, function_name) + pyapi.decref(numba_mod) + sig_obj = pyapi.unserialize(pyapi.serialize_object(sig)) + + addr = pyapi.call_function_objargs(numba_func, (func, sig_obj)) + + if failure_mode != 'ignore': + with builder.if_then(cgutils.is_null(builder, addr), likely=False): + # *function_name* has raised an exception, propagate it + # to the caller. + if failure_mode == 'return_exc': + context.call_conv.return_exc(builder) + elif failure_mode == 'return_null': + builder.ret(pyapi.get_null_object()) + else: + raise NotImplementedError(failure_mode) + # else the caller will handle addr == NULL + return addr # new reference or NULL + + +lower_get_wrapper_address = partial( + _lower_get_address, + function_name="_get_wrapper_address", +) + + +lower_get_jit_address = partial( + _lower_get_address, + function_name="_get_jit_address", +) + + +@unbox(FunctionType) +def unbox_function_type(typ, obj, c): + typ = typ.get_precise() + + sfunc = cgutils.create_struct_proxy(typ)(c.context, c.builder) + + addr = lower_get_wrapper_address( + c.context, c.builder, obj, typ.signature, failure_mode='return_null') + sfunc.c_addr = c.pyapi.long_as_voidptr(addr) + c.pyapi.decref(addr) + + llty = c.context.get_value_type(types.voidptr) + sfunc.py_addr = c.builder.ptrtoint(obj, llty) + + addr = lower_get_jit_address( + c.context, c.builder, obj, typ.signature, failure_mode='return_null') + sfunc.jit_addr = c.pyapi.long_as_voidptr(addr) + c.pyapi.decref(addr) + + return NativeValue(sfunc._getvalue()) + + +@box(FunctionType) +def box_function_type(typ, val, c): + typ = typ.get_precise() + + sfunc = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val) + pyaddr_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj) + raw_ptr = c.builder.inttoptr(sfunc.py_addr, c.pyapi.pyobj) + with c.builder.if_then(cgutils.is_null(c.builder, raw_ptr), + likely=False): + cstr = f"first-class function {typ} parent object not set" + c.pyapi.err_set_string("PyExc_MemoryError", cstr) + c.builder.ret(c.pyapi.get_null_object()) + c.builder.store(raw_ptr, pyaddr_ptr) + cfunc = c.builder.load(pyaddr_ptr) + c.pyapi.incref(cfunc) + return cfunc + + +@lower_cast(UndefinedFunctionType, FunctionType) +def lower_cast_function_type_to_function_type( + context, builder, fromty, toty, val): + return val + + +@lower_cast(types.Dispatcher, FunctionType) +def lower_cast_dispatcher_to_function_type(context, builder, fromty, toty, val): + toty = toty.get_precise() + + sig = toty.signature + dispatcher = fromty.dispatcher + llvoidptr = context.get_value_type(types.voidptr) + sfunc = cgutils.create_struct_proxy(toty)(context, builder) + # Always store the python function + sfunc.py_addr = builder.ptrtoint(val, llvoidptr) + + # Attempt to compile the Dispatcher to the expected function type + try: + cres = dispatcher.get_compile_result(sig) + except errors.NumbaError: + cres = None + + # If compilation is successful, we can by-pass using GIL to get the cfunc + if cres is not None: + # Declare cfunc in the current module + wrapper_name = cres.fndesc.llvm_cfunc_wrapper_name + llfnptr = context.get_value_type(toty.ftype) + llfnty = llfnptr.pointee + fn = cgutils.get_or_insert_function( + builder.module, llfnty, wrapper_name, + ) + addr = builder.bitcast(fn, llvoidptr) + # Store the cfunc + sfunc.c_addr = addr + # Store the jit func + fn = context.declare_function(builder.module, cres.fndesc) + sfunc.jit_addr = builder.bitcast(fn, llvoidptr) + # Link-in the dispatcher library + context.active_code_library.add_linking_library(cres.library) + + else: + # Use lower_get_wrapper_address() to get the cfunc + lower_get_wrapper_address + pyapi = context.get_python_api(builder) + + gil_state = pyapi.gil_ensure() + addr = lower_get_wrapper_address( + context, builder, val, toty.signature, + failure_mode='return_exc') + sfunc.c_addr = pyapi.long_as_voidptr(addr) + pyapi.decref(addr) + pyapi.gil_release(gil_state) + + return sfunc._getvalue() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/structref.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/structref.py new file mode 100644 index 0000000000000000000000000000000000000000..89f96a8da4c753c89bbdb3269c7c042603bce6bb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/experimental/structref.py @@ -0,0 +1,400 @@ +"""Utilities for defining a mutable struct. + +A mutable struct is passed by reference; +hence, structref (a reference to a struct). + +""" +import operator +from numba.core.cgutils import create_struct_proxy +from numba import njit +from numba.core import types, imputils, cgutils +from numba.core.datamodel import default_manager, models +from numba.core.extending import ( + infer_getattr, + lower_getattr_generic, + lower_setattr_generic, + lower_builtin, + box, + unbox, + NativeValue, + intrinsic, + overload, +) +from numba.core.typing.templates import AttributeTemplate + + +class _Utils: + """Internal builder-code utils for structref definitions. + """ + def __init__(self, context, builder, struct_type): + """ + Parameters + ---------- + context : + a numba target context + builder : + a llvmlite IRBuilder + struct_type : numba.core.types.StructRef + """ + self.context = context + self.builder = builder + self.struct_type = struct_type + + def new_struct_ref(self, mi): + """Encapsulate the MemInfo from a `StructRefPayload` in a `StructRef` + """ + context = self.context + builder = self.builder + struct_type = self.struct_type + + st = cgutils.create_struct_proxy(struct_type)(context, builder) + st.meminfo = mi + return st + + def get_struct_ref(self, val): + """Return a helper for accessing a StructRefType + """ + context = self.context + builder = self.builder + struct_type = self.struct_type + + return cgutils.create_struct_proxy(struct_type)( + context, builder, value=val + ) + + def get_data_pointer(self, val): + """Get the data pointer to the payload from a `StructRefType`. + """ + context = self.context + builder = self.builder + struct_type = self.struct_type + + structval = self.get_struct_ref(val) + meminfo = structval.meminfo + data_ptr = context.nrt.meminfo_data(builder, meminfo) + + valtype = struct_type.get_data_type() + model = context.data_model_manager[valtype] + alloc_type = model.get_value_type() + data_ptr = builder.bitcast(data_ptr, alloc_type.as_pointer()) + return data_ptr + + def get_data_struct(self, val): + """Get a getter/setter helper for accessing a `StructRefPayload` + """ + context = self.context + builder = self.builder + struct_type = self.struct_type + + data_ptr = self.get_data_pointer(val) + valtype = struct_type.get_data_type() + dataval = cgutils.create_struct_proxy(valtype)( + context, builder, ref=data_ptr + ) + return dataval + + +def define_attributes(struct_typeclass): + """Define attributes on `struct_typeclass`. + + Defines both setters and getters in jit-code. + + This is called directly in `register()`. + """ + @infer_getattr + class StructAttribute(AttributeTemplate): + key = struct_typeclass + + def generic_resolve(self, typ, attr): + if attr in typ.field_dict: + attrty = typ.field_dict[attr] + return attrty + + @lower_getattr_generic(struct_typeclass) + def struct_getattr_impl(context, builder, typ, val, attr): + utils = _Utils(context, builder, typ) + dataval = utils.get_data_struct(val) + ret = getattr(dataval, attr) + fieldtype = typ.field_dict[attr] + return imputils.impl_ret_borrowed(context, builder, fieldtype, ret) + + @lower_setattr_generic(struct_typeclass) + def struct_setattr_impl(context, builder, sig, args, attr): + [inst_type, val_type] = sig.args + [instance, val] = args + utils = _Utils(context, builder, inst_type) + dataval = utils.get_data_struct(instance) + # cast val to the correct type + field_type = inst_type.field_dict[attr] + casted = context.cast(builder, val, val_type, field_type) + # read old + old_value = getattr(dataval, attr) + # incref new value + context.nrt.incref(builder, val_type, casted) + # decref old value (must be last in case new value is old value) + context.nrt.decref(builder, val_type, old_value) + # write new + setattr(dataval, attr, casted) + + +def define_boxing(struct_type, obj_class): + """Define the boxing & unboxing logic for `struct_type` to `obj_class`. + + Defines both boxing and unboxing. + + - boxing turns an instance of `struct_type` into a PyObject of `obj_class` + - unboxing turns an instance of `obj_class` into an instance of + `struct_type` in jit-code. + + + Use this directly instead of `define_proxy()` when the user does not + want any constructor to be defined. + """ + if struct_type is types.StructRef: + raise ValueError(f"cannot register {types.StructRef}") + + obj_ctor = obj_class._numba_box_ + + @box(struct_type) + def box_struct_ref(typ, val, c): + """ + Convert a raw pointer to a Python int. + """ + utils = _Utils(c.context, c.builder, typ) + struct_ref = utils.get_struct_ref(val) + meminfo = struct_ref.meminfo + + mip_type = types.MemInfoPointer(types.voidptr) + boxed_meminfo = c.box(mip_type, meminfo) + + ctor_pyfunc = c.pyapi.unserialize(c.pyapi.serialize_object(obj_ctor)) + ty_pyobj = c.pyapi.unserialize(c.pyapi.serialize_object(typ)) + + res = c.pyapi.call_function_objargs( + ctor_pyfunc, [ty_pyobj, boxed_meminfo], + ) + c.pyapi.decref(ctor_pyfunc) + c.pyapi.decref(ty_pyobj) + c.pyapi.decref(boxed_meminfo) + return res + + @unbox(struct_type) + def unbox_struct_ref(typ, obj, c): + mi_obj = c.pyapi.object_getattr_string(obj, "_meminfo") + + mip_type = types.MemInfoPointer(types.voidptr) + + mi = c.unbox(mip_type, mi_obj).value + + utils = _Utils(c.context, c.builder, typ) + struct_ref = utils.new_struct_ref(mi) + out = struct_ref._getvalue() + + c.pyapi.decref(mi_obj) + return NativeValue(out) + + +def define_constructor(py_class, struct_typeclass, fields): + """Define the jit-code constructor for `struct_typeclass` using the + Python type `py_class` and the required `fields`. + + Use this instead of `define_proxy()` if the user does not want boxing + logic defined. + """ + # Build source code for the constructor + params = ', '.join(fields) + indent = ' ' * 8 + init_fields_buf = [] + for k in fields: + init_fields_buf.append(f"st.{k} = {k}") + init_fields = f'\n{indent}'.join(init_fields_buf) + + source = f""" +def ctor({params}): + struct_type = struct_typeclass(list(zip({list(fields)}, [{params}]))) + def impl({params}): + st = new(struct_type) + {init_fields} + return st + return impl +""" + + glbs = dict(struct_typeclass=struct_typeclass, new=new) + exec(source, glbs) + ctor = glbs['ctor'] + # Make it an overload + overload(py_class)(ctor) + + +def define_proxy(py_class, struct_typeclass, fields): + """Defines a PyObject proxy for a structref. + + This makes `py_class` a valid constructor for creating a instance of + `struct_typeclass` that contains the members as defined by `fields`. + + Parameters + ---------- + py_class : type + The Python class for constructing an instance of `struct_typeclass`. + struct_typeclass : numba.core.types.Type + The structref type class to bind to. + fields : Sequence[str] + A sequence of field names. + + Returns + ------- + None + """ + define_constructor(py_class, struct_typeclass, fields) + define_boxing(struct_typeclass, py_class) + + +def register(struct_type): + """Register a `numba.core.types.StructRef` for use in jit-code. + + This defines the data-model for lowering an instance of `struct_type`. + This defines attributes accessor and mutator for an instance of + `struct_type`. + + Parameters + ---------- + struct_type : type + A subclass of `numba.core.types.StructRef`. + + Returns + ------- + struct_type : type + Returns the input argument so this can act like a decorator. + + Examples + -------- + + .. code-block:: + + class MyStruct(numba.core.types.StructRef): + ... # the simplest subclass can be empty + + numba.experimental.structref.register(MyStruct) + + """ + if struct_type is types.StructRef: + raise ValueError(f"cannot register {types.StructRef}") + default_manager.register(struct_type, models.StructRefModel) + define_attributes(struct_type) + return struct_type + + +@intrinsic +def new(typingctx, struct_type): + """new(struct_type) + + A jit-code only intrinsic. Used to allocate an **empty** mutable struct. + The fields are zero-initialized and must be set manually after calling + the function. + + Example: + + instance = new(MyStruct) + instance.field = field_value + """ + from numba.experimental.jitclass.base import imp_dtor + + inst_type = struct_type.instance_type + + def codegen(context, builder, signature, args): + # FIXME: mostly the same as jitclass ctor_impl() + model = context.data_model_manager[inst_type.get_data_type()] + alloc_type = model.get_value_type() + alloc_size = context.get_abi_sizeof(alloc_type) + + meminfo = context.nrt.meminfo_alloc_dtor( + builder, + context.get_constant(types.uintp, alloc_size), + imp_dtor(context, builder.module, inst_type), + ) + data_pointer = context.nrt.meminfo_data(builder, meminfo) + data_pointer = builder.bitcast(data_pointer, alloc_type.as_pointer()) + + # Nullify all data + builder.store(cgutils.get_null_value(alloc_type), data_pointer) + + inst_struct = context.make_helper(builder, inst_type) + inst_struct.meminfo = meminfo + + return inst_struct._getvalue() + + sig = inst_type(struct_type) + return sig, codegen + + +class StructRefProxy: + """A PyObject proxy to the Numba allocated structref data structure. + + Notes + ----- + + * Subclasses should not define ``__init__``. + * Subclasses can override ``__new__``. + """ + __slots__ = ('_type', '_meminfo') + + @classmethod + def _numba_box_(cls, ty, mi): + """Called by boxing logic, the conversion of Numba internal + representation into a PyObject. + + Parameters + ---------- + ty : + a Numba type instance. + mi : + a wrapped MemInfoPointer. + + Returns + ------- + instance : + a StructRefProxy instance. + """ + instance = super().__new__(cls) + instance._type = ty + instance._meminfo = mi + return instance + + def __new__(cls, *args): + """Construct a new instance of the structref. + + This takes positional-arguments only due to limitation of the compiler. + The arguments are mapped to ``cls(*args)`` in jit-code. + """ + try: + # use cached ctor if available + ctor = cls.__numba_ctor + except AttributeError: + # lazily define the ctor + @njit + def ctor(*args): + return cls(*args) + # cache it to attribute to avoid recompilation + cls.__numba_ctor = ctor + return ctor(*args) + + @property + def _numba_type_(self): + """Returns the Numba type instance for this structref instance. + + Subclasses should NOT override. + """ + return self._type + + +@lower_builtin(operator.is_, types.StructRef, types.StructRef) +def structref_is(context, builder, sig, args): + """ + Define the 'is' operator for structrefs by comparing the memory addresses. + This is the identity check for structref objects. + """ + a, b = args + aty, bty = sig.args + a_ptr = create_struct_proxy(aty)(context, builder, value=a).meminfo + b_ptr = create_struct_proxy(bty)(context, builder, value=b).meminfo + return builder.icmp_unsigned("==", a_ptr, b_ptr) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/POST.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/POST.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12e208765538f884123ccd27cd07ec86d1d31c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/POST.py @@ -0,0 +1,34 @@ +""" Numba's POWER ON SELF TEST script. Used by CI to check: +0. That Numba imports ok! +1. That Numba can find an appropriate number of its own tests to run. +2. That Numba can manage to correctly compile and execute at least one thing. +""" +from numba.tests import test_runtests +from numba import njit + + +def _check_runtests(): + test_inst = test_runtests.TestCase() + test_inst.test_default() # will raise an exception if there is a problem + + +def _check_cpu_compilation(): + @njit + def foo(x): + return x + 1 + + result = foo(1) + + if result != 2: + msg = ("Unexpected result from trial compilation. " + f"Expected: 2, Got: {result}.") + raise AssertionError(msg) + + +def check(): + _check_runtests() + _check_cpu_compilation() + + +if __name__ == "__main__": + check() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/appdirs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ce1ab5b907cdb6bb0dc9ecc008204cc3749bf0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/appdirs.py @@ -0,0 +1,551 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (c) 2005-2010 ActiveState Software Inc. +# Copyright (c) 2013 Eddy Petrișor + +"""Utilities for determining application-specific dirs. + +See for details and usage. +""" +# Dev Notes: +# - MSDN on where to store app data files: +# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 +# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html +# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + +__version_info__ = (1, 4, 1) +__version__ = '.'.join(map(str, __version_info__)) + + +import sys +import os + +unicode = str + +if sys.platform.startswith('java'): + import platform + os_name = platform.java_ver()[3][0] + if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. + system = 'win32' + elif os_name.startswith('Mac'): # "Mac OS X", etc. + system = 'darwin' + else: # "Linux", "SunOS", "FreeBSD", etc. + # Setting this to "linux2" is not ideal, but only Windows or Mac + # are actually checked for and the rest of the module expects + # *sys.platform* style strings. + system = 'linux2' +else: + system = sys.platform + + + +def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user data directories are: + Mac OS X: ~/Library/Application Support/ + Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined + Win XP (not roaming): C:\Documents and Settings\\Application Data\\ + Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ + Win 7 (not roaming): C:\Users\\AppData\Local\\ + Win 7 (roaming): C:\Users\\AppData\Roaming\\ + + For Unix, we follow the XDG spec and support $XDG_DATA_HOME. + That means, by default "~/.local/share/". + """ + if system == "win32": + if appauthor is None: + appauthor = appname + const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" + path = os.path.normpath(_get_win_folder(const)) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == 'darwin': + path = os.path.expanduser('~/Library/Application Support/') + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of data dirs should be + returned. By default, the first item from XDG_DATA_DIRS is + returned, or '/usr/local/share/', + if XDG_DATA_DIRS is not set + + Typical user data directories are: + Mac OS X: /Library/Application Support/ + Unix: /usr/local/share/ or /usr/share/ + Win XP: C:\Documents and Settings\All Users\Application Data\\ + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. + + For Unix, this is using the $XDG_DATA_DIRS[0] default. + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == 'darwin': + path = os.path.expanduser('/Library/Application Support') + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_DATA_DIRS + # only first, if multipath is False + path = os.getenv('XDG_DATA_DIRS', + os.pathsep.join(['/usr/local/share', '/usr/share'])) + pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + if appname and version: + path = os.path.join(path, version) + return path + + +def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific config dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user data directories are: + Mac OS X: same as user_data_dir + Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. + That means, by default "~/.config/". + """ + if system in ["win32", "darwin"]: + path = user_data_dir(appname, appauthor, None, roaming) + else: + path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of config dirs should be + returned. By default, the first item from XDG_CONFIG_DIRS is + returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set + + Typical user data directories are: + Mac OS X: same as site_data_dir + Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in + $XDG_CONFIG_DIRS + Win *: same as site_data_dir + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + + For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system in ["win32", "darwin"]: + path = site_data_dir(appname, appauthor) + if appname and version: + path = os.path.join(path, version) + else: + # XDG default for $XDG_CONFIG_DIRS + # only first, if multipath is False + path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') + pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + +def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific cache dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Cache" to the base app data dir for Windows. See + discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Caches/ + Unix: ~/.cache/ (XDG default) + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache + Vista: C:\Users\\AppData\Local\\\Cache + + On Windows the only suggestion in the MSDN docs is that local settings go in + the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming + app data dir (the default returned by `user_data_dir` above). Apps typically + put cache data somewhere *under* the given dir here. Some examples: + ...\Mozilla\Firefox\Profiles\\Cache + ...\Acme\SuperApp\Cache\1.0 + OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. + This can be disabled with the `opinion=False` option. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + if opinion: + path = os.path.join(path, "Cache") + elif system == 'darwin': + path = os.path.expanduser('~/Library/Caches') + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific log dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Logs" to the base app data dir for Windows, and "log" to the + base cache dir for Unix. See discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Logs/ + Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs + Vista: C:\Users\\AppData\Local\\\Logs + + On Windows the only suggestion in the MSDN docs is that local settings + go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in + examples of what some windows apps use for a logs dir.) + + OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` + value for Windows and appends "log" to the user cache dir for Unix. + This can be disabled with the `opinion=False` option. + """ + if system == "darwin": + path = os.path.join( + os.path.expanduser('~/Library/Logs'), + appname) + elif system == "win32": + path = user_data_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "Logs") + else: + path = user_cache_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "log") + if appname and version: + path = os.path.join(path, version) + return path + + +class AppDirs(object): + """Convenience wrapper for getting application dirs.""" + def __init__(self, appname, appauthor=None, version=None, roaming=False, + multipath=False): + self.appname = appname + self.appauthor = appauthor + self.version = version + self.roaming = roaming + self.multipath = multipath + + @property + def user_data_dir(self): + return user_data_dir(self.appname, self.appauthor, + version=self.version, roaming=self.roaming) + + @property + def site_data_dir(self): + return site_data_dir(self.appname, self.appauthor, + version=self.version, multipath=self.multipath) + + @property + def user_config_dir(self): + return user_config_dir(self.appname, self.appauthor, + version=self.version, roaming=self.roaming) + + @property + def site_config_dir(self): + return site_config_dir(self.appname, self.appauthor, + version=self.version, multipath=self.multipath) + + @property + def user_cache_dir(self): + return user_cache_dir(self.appname, self.appauthor, + version=self.version) + + @property + def user_log_dir(self): + return user_log_dir(self.appname, self.appauthor, + version=self.version) + + +#---- internal support stuff + +def _get_win_folder_from_registry(csidl_name): + """This is a fallback technique at best. I'm not sure if using the + registry for this guarantees us the correct answer for all CSIDL_* + names. + """ + import winreg as _winreg + + shell_folder_name = { + "CSIDL_APPDATA": "AppData", + "CSIDL_COMMON_APPDATA": "Common AppData", + "CSIDL_LOCAL_APPDATA": "Local AppData", + }[csidl_name] + + key = _winreg.OpenKey( + _winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" + ) + dir, type = _winreg.QueryValueEx(key, shell_folder_name) + return dir + + +def _get_win_folder_with_pywin32(csidl_name): + from win32com.shell import shellcon, shell + dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) + # Try to make this a unicode path because SHGetFolderPath does + # not return unicode strings when there is unicode data in the + # path. + try: + dir = unicode(dir) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + try: + import win32api + dir = win32api.GetShortPathName(dir) + except ImportError: + pass + except UnicodeError: + pass + return dir + + +def _get_win_folder_with_ctypes(csidl_name): + import ctypes + + csidl_const = { + "CSIDL_APPDATA": 26, + "CSIDL_COMMON_APPDATA": 35, + "CSIDL_LOCAL_APPDATA": 28, + }[csidl_name] + + buf = ctypes.create_unicode_buffer(1024) + ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in buf: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf2 = ctypes.create_unicode_buffer(1024) + if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): + buf = buf2 + + return buf.value + +def _get_win_folder_with_jna(csidl_name): + import array + from com.sun import jna + from com.sun.jna.platform import win32 + + buf_size = win32.WinDef.MAX_PATH * 2 + buf = array.zeros('c', buf_size) + shell = win32.Shell32.INSTANCE + shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf = array.zeros('c', buf_size) + kernel = win32.Kernel32.INSTANCE + if kernel.GetShortPathName(dir, buf, buf_size): + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + return dir + +if system == "win32": + try: + import win32com.shell + _get_win_folder = _get_win_folder_with_pywin32 + except ImportError: + try: + from ctypes import windll + _get_win_folder = _get_win_folder_with_ctypes + except ImportError: + try: + import com.sun.jna + _get_win_folder = _get_win_folder_with_jna + except ImportError: + _get_win_folder = _get_win_folder_from_registry + + +#---- self test code + +if __name__ == "__main__": + appname = "MyApp" + appauthor = "MyCompany" + + props = ("user_data_dir", "site_data_dir", + "user_config_dir", "site_config_dir", + "user_cache_dir", "user_log_dir") + + print("-- app dirs %s --" % __version__) + + print("-- app dirs (with optional 'version')") + dirs = AppDirs(appname, appauthor, version="1.0") + for prop in props: + print("%s: %s" % (prop, getattr(dirs, prop))) + + print("\n-- app dirs (without optional 'version')") + dirs = AppDirs(appname, appauthor) + for prop in props: + print("%s: %s" % (prop, getattr(dirs, prop))) + + print("\n-- app dirs (without optional 'appauthor')") + dirs = AppDirs(appname) + for prop in props: + print("%s: %s" % (prop, getattr(dirs, prop))) + + print("\n-- app dirs (with disabled 'appauthor')") + dirs = AppDirs(appname, appauthor=False) + for prop in props: + print("%s: %s" % (prop, getattr(dirs, prop))) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cffiimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cffiimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..2266465666fc490c970c76bd967feace6498549c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cffiimpl.py @@ -0,0 +1,22 @@ +""" +Implementation of some CFFI functions +""" + + +from numba.core.imputils import Registry +from numba.core import types +from numba.np import arrayobj + +registry = Registry('cffiimpl') + +@registry.lower('ffi.from_buffer', types.Buffer) +def from_buffer(context, builder, sig, args): + assert len(sig.args) == 1 + assert len(args) == 1 + [fromty] = sig.args + [val] = args + # Type inference should have prevented passing a buffer from an + # array to a pointer of the wrong type + assert fromty.dtype == sig.return_type.dtype + ary = arrayobj.make_array(fromty)(context, builder, val) + return ary.data diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cmdlang.gdb b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cmdlang.gdb new file mode 100644 index 0000000000000000000000000000000000000000..f5c1eed2c015f6e8196aabb4fb478c1fabecd0e5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/cmdlang.gdb @@ -0,0 +1,5 @@ +# this file is used with the numba.gdb* functionality +break numba_gdb_breakpoint +commands +return +end diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/coverage_support.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/coverage_support.py new file mode 100644 index 0000000000000000000000000000000000000000..14b34465e5c738c669eafa6705349af6424c78fa --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/coverage_support.py @@ -0,0 +1,201 @@ +""" +Implement code coverage support. + +Currently contains logic to extend ``coverage`` with lines covered by the +compiler. +""" + +from typing import Optional, Sequence, Callable, no_type_check +from collections.abc import Mapping +from dataclasses import dataclass, field +from abc import ABC, abstractmethod + +from numba.core import ir, config + + +try: + import coverage +except ImportError: + coverage_available = False +else: + coverage_available = True + + +@no_type_check +def get_active_coverage(): + """Get active coverage instance or return None if not found. + """ + cov = None + if coverage_available: + cov = coverage.Coverage.current() + return cov + + +_the_registry: Callable[[], Optional["NotifyLocBase"]] = [] + + +def get_registered_loc_notify() -> Sequence["NotifyLocBase"]: + """ + Returns a list of the registered NotifyLocBase instances. + """ + if not config.JIT_COVERAGE: + # Coverage disabled. + return [] + return list(filter(lambda x: x is not None, + (factory() for factory in _the_registry))) + + +class NotifyLocBase(ABC): + """Interface for notifying visiting of a ``numba.core.ir.Loc``.""" + + @abstractmethod + def notify(self, loc: ir.Loc) -> None: + pass + + @abstractmethod + def close(self) -> None: + pass + + +class NotifyCompilerCoverage(NotifyLocBase): + """ + Use to notify ``coverage`` about compiled lines. + + The compiled lines are under the "numba_compiled" context in the coverage + data. + """ + + def __init__(self, collector): + self._collector = collector + + # see https://github.com/nedbat/coveragepy/blob/e7c05fe91ee36c0c94e144bb88d25db4fc3d02fd/coverage/collector.py#L261 # noqa E501 + tracer_kwargs = collector.core.tracer_kwargs.copy() + tracer_kwargs.update( + dict( + data=collector.data, + lock_data=collector.lock_data, + unlock_data=collector.unlock_data, + trace_arcs=collector.branch, + should_trace=collector.should_trace, + should_trace_cache=collector.should_trace_cache, + warn=collector.warn, + should_start_context=collector.should_start_context, + switch_context=collector.switch_context, + packed_arcs=collector.core.packed_arcs, + ) + ) + self._tracer = NumbaTracer(**tracer_kwargs) + collector.tracers.append(self._tracer) + + def notify(self, loc: ir.Loc): + tracer = self._tracer + if loc.filename.endswith(".py"): + tracer.switch_context("numba_compiled") + tracer.trace(loc) + tracer.switch_context(None) + + def close(self): + pass + + +@_the_registry.append +def _register_coverage_notifier(): + cov = get_active_coverage() + if cov is not None: + col = cov._collector + # Is coverage started? + if col.tracers: + return NotifyCompilerCoverage(col) + + +if coverage_available: + + @dataclass(kw_only=True) + class NumbaTracer(coverage.types.Tracer): + """ + Not actually a tracer as in the coverage implementation, which will + setup a Python trace function. This implementation pretends to trace + but instead receives fake trace events for each line the compiler has + visited. + + See coverage.PyTracer + """ + + data: coverage.types.TTraceData + trace_arcs: bool + should_trace: coverage.types.TShouldTraceFn + should_trace_cache: Mapping[ + str, coverage.types.TFileDisposition | None + ] + should_start_context: coverage.types.TShouldStartContextFn | None + switch_context: Callable[[str | None], None] | None + lock_data: Callable[[], None] + unlock_data: Callable[[], None] + warn: coverage.types.TWarnFn + packed_arcs: bool + + _activity: bool = field(default=False) + + def start(self) -> coverage.types.TTraceFn | None: + """Start this tracer, return a trace function if based on + sys.settrace.""" + return None + + def stop(self) -> None: + """Stop this tracer.""" + return None + + def activity(self) -> bool: + """Has there been any activity?""" + return self._activity + + def reset_activity(self) -> None: + """Reset the activity() flag.""" + self._activity = False + + def get_stats(self) -> dict[str, int] | None: + """Return a dictionary of statistics, or None.""" + return None + + def trace(self, loc: ir.Loc) -> None: + """Insert coverage data given source location. + """ + # Check whether the file should be traced + disp = self.should_trace_cache.get(loc.filename) + if disp is None: + disp = self.should_trace(loc.filename, None) + self.should_trace_cache[loc.filename] = disp + if not disp.trace: + # Bail if not tracing the file + return + # Insert trace data + tracename = disp.source_filename + self.lock_data() + cur_file_data = self.data.setdefault(tracename, set()) + if self.trace_arcs: + if self.packed_arcs: + cur_file_data.add(_pack_arcs(loc.line, loc.line)) + else: + cur_file_data.add((loc.line, loc.line)) + else: + cur_file_data.add(loc.line) + self.unlock_data() + # Mark activity for this tracer + self._activity = True + + def _pack_arcs(l1: int, l2: int) -> int: + """Pack arcs into a single integer for compatibility with .packed_arcs + option. + + See + https://github.com/nedbat/coveragepy/blob/e7c05fe91ee36c0c94e144bb88d25db4fc3d02fd/coverage/ctracer/tracer.c#L171 + """ + packed = 0 + if l1 < 0: + packed |= 1 << 40 + l1 = -l1 + if l2 < 0: + packed |= 1 << 41 + l2 = -l2 + packed |= (l2 << 20) + l1 + return packed diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/dump_style.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/dump_style.py new file mode 100644 index 0000000000000000000000000000000000000000..95b5ed5be5b126e6f4662e073f776c232a4e046c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/dump_style.py @@ -0,0 +1,84 @@ +try: + from pygments.styles.default import DefaultStyle +except ImportError: + msg = "Please install pygments to see highlighted dumps" + raise ImportError(msg) + +import numba.core.config +from pygments.styles.manni import ManniStyle +from pygments.styles.monokai import MonokaiStyle +from pygments.styles.native import NativeStyle + +from pygments.lexer import RegexLexer, include, bygroups, words +from pygments.token import Text, Name, String, Punctuation, Keyword, \ + Operator, Number + +from pygments.style import Style + + +class NumbaIRLexer(RegexLexer): + """ + Pygments style lexer for Numba IR (for use with highlighting etc). + """ + name = 'Numba_IR' + aliases = ['numba_ir'] + filenames = ['*.numba_ir'] + + identifier = r'\$[a-zA-Z0-9._]+' + fun_or_var = r'([a-zA-Z_]+[a-zA-Z0-9]*)' + + tokens = { + 'root' : [ + (r'(label)(\ [0-9]+)(:)$', + bygroups(Keyword, Name.Label, Punctuation)), + + (r' = ', Operator), + include('whitespace'), + include('keyword'), + + (identifier, Name.Variable), + (fun_or_var + r'(\()', + bygroups(Name.Function, Punctuation)), + (fun_or_var + r'(\=)', + bygroups(Name.Attribute, Punctuation)), + (fun_or_var, Name.Constant), + (r'[0-9]+', Number), + + # + (r'<[^>\n]*>', String), + + (r'[=<>{}\[\]()*.,!\':]|x\b', Punctuation) + ], + + 'keyword':[ + (words(( + 'del', 'jump', 'call', 'branch', + ), suffix=' '), Keyword), + ], + + 'whitespace': [ + (r'(\n|\s)', Text), + ], + } + + +def by_colorscheme(): + """ + Get appropriate style for highlighting according to + NUMBA_COLOR_SCHEME setting + """ + styles = DefaultStyle.styles.copy() + styles.update({ + Name.Variable: "#888888", + }) + custom_default = type('CustomDefaultStyle', (Style, ), {'styles': styles}) + + style_map = { + 'no_color' : custom_default, + 'dark_bg' : MonokaiStyle, + 'light_bg' : ManniStyle, + 'blue_bg' : NativeStyle, + 'jupyter_nb' : DefaultStyle, + } + + return style_map[numba.core.config.COLOR_SCHEME] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/findlib.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/findlib.py new file mode 100644 index 0000000000000000000000000000000000000000..3b48ab5706d69f57791c975e7288125bb24a7f8a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/findlib.py @@ -0,0 +1,63 @@ +import sys +import os +import re + + +def get_lib_dirs(): + """ + Anaconda specific + """ + if sys.platform == 'win32': + # on windows, historically `DLLs` has been used for CUDA libraries, + # since approximately CUDA 9.2, `Library\bin` has been used. + dirnames = ['DLLs', os.path.join('Library', 'bin')] + else: + dirnames = ['lib', ] + libdirs = [os.path.join(sys.prefix, x) for x in dirnames] + return libdirs + + +DLLNAMEMAP = { + 'linux': r'lib%(name)s\.so\.%(ver)s$', + 'linux2': r'lib%(name)s\.so\.%(ver)s$', + 'linux-static': r'lib%(name)s\.a$', + 'darwin': r'lib%(name)s\.%(ver)s\.dylib$', + 'win32': r'%(name)s%(ver)s\.dll$', + 'win32-static': r'%(name)s\.lib$', + 'bsd': r'lib%(name)s\.so\.%(ver)s$', +} + +RE_VER = r'[0-9]*([_\.][0-9]+)*' + + +def find_lib(libname, libdir=None, platform=None, static=False): + platform = platform or sys.platform + platform = 'bsd' if 'bsd' in platform else platform + if static: + platform = f"{platform}-static" + if platform not in DLLNAMEMAP: + # Return empty list if platform name is undefined. + # Not all platforms define their static library paths. + return [] + pat = DLLNAMEMAP[platform] % {"name": libname, "ver": RE_VER} + regex = re.compile(pat) + return find_file(regex, libdir) + + +def find_file(pat, libdir=None): + if libdir is None: + libdirs = get_lib_dirs() + elif isinstance(libdir, str): + libdirs = [libdir,] + else: + libdirs = list(libdir) + files = [] + for ldir in libdirs: + try: + entries = os.listdir(ldir) + except FileNotFoundError: + continue + candidates = [os.path.join(ldir, ent) + for ent in entries if pat.match(ent)] + files.extend([c for c in candidates if os.path.isfile(c)]) + return files diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/firstlinefinder.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/firstlinefinder.py new file mode 100644 index 0000000000000000000000000000000000000000..54d790206f627f8617e64ff4c925805e7baae6c4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/firstlinefinder.py @@ -0,0 +1,104 @@ +""" +This module provides helper functions to find the first line of a function +body. +""" + +import ast +import inspect +import textwrap + + +class FindDefFirstLine(ast.NodeVisitor): + """ + Attributes + ---------- + first_stmt_line : int or None + This stores the first statement line number if the definition is found. + Or, ``None`` if the definition is not found. + """ + + def __init__(self, name, firstlineno): + """ + Parameters + ---------- + code : + The function's code object. + """ + self._co_name = name + self._co_firstlineno = firstlineno + self.first_stmt_line = None + + def _visit_children(self, node): + for child in ast.iter_child_nodes(node): + super().visit(child) + + def visit_FunctionDef(self, node: ast.FunctionDef): + if node.name == self._co_name: + # Name of function matches. + + # The `def` line may match co_firstlineno. + possible_start_lines = set([node.lineno]) + if node.decorator_list: + # Has decorators. + # The first decorator line may match co_firstlineno. + first_decor = node.decorator_list[0] + possible_start_lines.add(first_decor.lineno) + # Does the first lineno match? + if self._co_firstlineno in possible_start_lines: + # Yes, we found the function. + # So, use the first statement line as the first line. + if node.body: + first_stmt = node.body[0] + if _is_docstring(first_stmt): + # Skip docstring + first_stmt = node.body[1] + self.first_stmt_line = first_stmt.lineno + return + else: + # This is probably unreachable. + # Function body cannot be bare. It must at least have + # A const string for docstring or a `pass`. + pass + self._visit_children(node) + + +def _is_docstring(node): + if isinstance(node, ast.Expr): + if (isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str)): + return True + return False + + +def get_func_body_first_lineno(pyfunc): + """ + Look up the first line of function body using the file in + ``pyfunc.__code__.co_filename``. + + Returns + ------- + lineno : int; or None + The first line number of the function body; or ``None`` if the first + line cannot be determined. + """ + co = pyfunc.__code__ + try: + with open(co.co_filename) as fin: + source = fin.read() + offset = 0 + except (FileNotFoundError, OSError): + try: + lines, offset = inspect.getsourcelines(pyfunc) + source = "".join(lines) + offset = offset - 1 + except (OSError, TypeError): + return None + + tree = ast.parse(textwrap.dedent(source)) + finder = FindDefFirstLine(co.co_name, co.co_firstlineno - offset) + finder.visit(tree) + if finder.first_stmt_line: + return finder.first_stmt_line + offset + else: + # No first line found. + return None diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_hook.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae877ec5d3f56ec8707fab6c81f6f248eb67484 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_hook.py @@ -0,0 +1,228 @@ +import os +import sys + +from llvmlite import ir + +from numba.core import types, utils, config, cgutils, errors +from numba import gdb, gdb_init, gdb_breakpoint +from numba.core.extending import overload, intrinsic + +_path = os.path.dirname(__file__) + +_platform = sys.platform +_unix_like = (_platform.startswith('linux') or + _platform.startswith('darwin') or + ('bsd' in _platform)) + + +def _confirm_gdb(need_ptrace_attach=True): + """ + Set need_ptrace_attach to True/False to indicate whether the ptrace attach + permission is needed for this gdb use case. Mode 0 (classic) or 1 + (restricted ptrace) is required if need_ptrace_attach is True. See: + https://www.kernel.org/doc/Documentation/admin-guide/LSM/Yama.rst + for details on the modes. + """ + if not _unix_like: + msg = 'gdb support is only available on unix-like systems' + raise errors.NumbaRuntimeError(msg) + gdbloc = config.GDB_BINARY + if not (os.path.exists(gdbloc) and os.path.isfile(gdbloc)): + msg = ('Is gdb present? Location specified (%s) does not exist. The gdb' + ' binary location can be set using Numba configuration, see: ' + 'https://numba.readthedocs.io/en/stable/reference/envvars.html' # noqa: E501 + ) + raise RuntimeError(msg % config.GDB_BINARY) + # Is Yama being used as a kernel security module and if so is ptrace_scope + # limited? In this case ptracing non-child processes requires special + # permission so raise an exception. + ptrace_scope_file = os.path.join(os.sep, 'proc', 'sys', 'kernel', 'yama', + 'ptrace_scope') + has_ptrace_scope = os.path.exists(ptrace_scope_file) + if has_ptrace_scope: + with open(ptrace_scope_file, 'rt') as f: + value = f.readline().strip() + if need_ptrace_attach and value not in ("0", "1"): + msg = ("gdb can launch but cannot attach to the executing program" + " because ptrace permissions have been restricted at the " + "system level by the Linux security module 'Yama'.\n\n" + "Documentation for this module and the security " + "implications of making changes to its behaviour can be " + "found in the Linux Kernel documentation " + "https://www.kernel.org/doc/Documentation/admin-guide/LSM/Yama.rst" # noqa: E501 + "\n\nDocumentation on how to adjust the behaviour of Yama " + "on Ubuntu Linux with regards to 'ptrace_scope' can be " + "found here " + "https://wiki.ubuntu.com/Security/Features#ptrace.") + raise RuntimeError(msg) + + +@overload(gdb) +def hook_gdb(*args): + _confirm_gdb() + gdbimpl = gen_gdb_impl(args, True) + + def impl(*args): + gdbimpl() + return impl + + +@overload(gdb_init) +def hook_gdb_init(*args): + _confirm_gdb() + gdbimpl = gen_gdb_impl(args, False) + + def impl(*args): + gdbimpl() + return impl + + +def init_gdb_codegen(cgctx, builder, signature, args, + const_args, do_break=False): + + int8_t = ir.IntType(8) + int32_t = ir.IntType(32) + intp_t = ir.IntType(utils.MACHINE_BITS) + char_ptr = ir.PointerType(ir.IntType(8)) + zero_i32t = int32_t(0) + + mod = builder.module + pid = cgutils.alloca_once(builder, int32_t, size=1) + + # 32bit pid, 11 char max + terminator + pidstr = cgutils.alloca_once(builder, int8_t, size=12) + + # str consts + intfmt = cgctx.insert_const_string(mod, '%d') + gdb_str = cgctx.insert_const_string(mod, config.GDB_BINARY) + attach_str = cgctx.insert_const_string(mod, 'attach') + + new_args = [] + # add break point command to known location + # this command file thing is due to commands attached to a breakpoint + # requiring an interactive prompt + # https://sourceware.org/bugzilla/show_bug.cgi?id=10079 + new_args.extend(['-x', os.path.join(_path, 'cmdlang.gdb')]) + # issue command to continue execution from sleep function + new_args.extend(['-ex', 'c']) + # then run the user defined args if any + if any([not isinstance(x, types.StringLiteral) for x in const_args]): + raise errors.RequireLiteralValue(const_args) + new_args.extend([x.literal_value for x in const_args]) + cmdlang = [cgctx.insert_const_string(mod, x) for x in new_args] + + # insert getpid, getpid is always successful, call without concern! + fnty = ir.FunctionType(int32_t, tuple()) + getpid = cgutils.get_or_insert_function(mod, fnty, "getpid") + + # insert snprintf + # int snprintf(char *str, size_t size, const char *format, ...); + fnty = ir.FunctionType( + int32_t, (char_ptr, intp_t, char_ptr), var_arg=True) + snprintf = cgutils.get_or_insert_function(mod, fnty, "snprintf") + + # insert fork + fnty = ir.FunctionType(int32_t, tuple()) + fork = cgutils.get_or_insert_function(mod, fnty, "fork") + + # insert execl + fnty = ir.FunctionType(int32_t, (char_ptr, char_ptr), var_arg=True) + execl = cgutils.get_or_insert_function(mod, fnty, "execl") + + # insert sleep + fnty = ir.FunctionType(int32_t, (int32_t,)) + sleep = cgutils.get_or_insert_function(mod, fnty, "sleep") + + # insert break point + fnty = ir.FunctionType(ir.VoidType(), tuple()) + breakpoint = cgutils.get_or_insert_function(mod, fnty, + "numba_gdb_breakpoint") + + # do the work + parent_pid = builder.call(getpid, tuple()) + builder.store(parent_pid, pid) + pidstr_ptr = builder.gep(pidstr, [zero_i32t], inbounds=True) + pid_val = builder.load(pid) + + # call snprintf to write the pid into a char * + stat = builder.call( + snprintf, (pidstr_ptr, intp_t(12), intfmt, pid_val)) + invalid_write = builder.icmp_signed('>', stat, int32_t(12)) + with builder.if_then(invalid_write, likely=False): + msg = "Internal error: `snprintf` buffer would have overflowed." + cgctx.call_conv.return_user_exc(builder, RuntimeError, (msg,)) + + # fork, check pids etc + child_pid = builder.call(fork, tuple()) + fork_failed = builder.icmp_signed('==', child_pid, int32_t(-1)) + with builder.if_then(fork_failed, likely=False): + msg = "Internal error: `fork` failed." + cgctx.call_conv.return_user_exc(builder, RuntimeError, (msg,)) + + is_child = builder.icmp_signed('==', child_pid, zero_i32t) + with builder.if_else(is_child) as (then, orelse): + with then: + # is child + nullptr = ir.Constant(char_ptr, None) + gdb_str_ptr = builder.gep( + gdb_str, [zero_i32t], inbounds=True) + attach_str_ptr = builder.gep( + attach_str, [zero_i32t], inbounds=True) + cgutils.printf( + builder, "Attaching to PID: %s\n", pidstr) + buf = ( + gdb_str_ptr, + gdb_str_ptr, + attach_str_ptr, + pidstr_ptr) + buf = buf + tuple(cmdlang) + (nullptr,) + builder.call(execl, buf) + with orelse: + # is parent + builder.call(sleep, (int32_t(10),)) + # if breaking is desired, break now + if do_break is True: + builder.call(breakpoint, tuple()) + + +def gen_gdb_impl(const_args, do_break): + @intrinsic + def gdb_internal(tyctx): + function_sig = types.void() + + def codegen(cgctx, builder, signature, args): + init_gdb_codegen(cgctx, builder, signature, args, const_args, + do_break=do_break) + return cgctx.get_constant(types.none, None) + return function_sig, codegen + return gdb_internal + + +@overload(gdb_breakpoint) +def hook_gdb_breakpoint(): + """ + Adds the Numba break point into the source + """ + if not sys.platform.startswith('linux'): + raise RuntimeError('gdb is only available on linux') + bp_impl = gen_bp_impl() + + def impl(): + bp_impl() + return impl + + +def gen_bp_impl(): + @intrinsic + def bp_internal(tyctx): + function_sig = types.void() + + def codegen(cgctx, builder, signature, args): + mod = builder.module + fnty = ir.FunctionType(ir.VoidType(), tuple()) + breakpoint = cgutils.get_or_insert_function(mod, fnty, + "numba_gdb_breakpoint") + builder.call(breakpoint, tuple()) + return cgctx.get_constant(types.none, None) + return function_sig, codegen + return bp_internal diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_print_extension.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_print_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..982aacf26e55eb76b852e1fe4ce5ea95a432c45c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/gdb_print_extension.py @@ -0,0 +1,204 @@ +"""gdb printing extension for Numba types. +""" +import re + +try: + import gdb.printing + import gdb +except ImportError: + raise ImportError("GDB python support is not available.") + + +class NumbaArrayPrinter: + + def __init__(self, val): + self.val = val + + def to_string(self): + try: + import numpy as np + HAVE_NUMPY = True + except ImportError: + HAVE_NUMPY = False + + try: + NULL = 0x0 + + # Raw data references, these need unpacking/interpreting. + + # Member "data" is... + # DW_TAG_member of DIDerivedType, tag of DW_TAG_pointer_type + # encoding e.g. DW_ATE_float + data = self.val["data"] + + # Member "itemsize" is... + # DW_TAG_member of DIBasicType encoding DW_ATE_signed + itemsize = self.val["itemsize"] + + # Members "shape" and "strides" are... + # DW_TAG_member of DIDerivedType, the type is a DICompositeType + # (it's a Numba UniTuple) with tag: DW_TAG_array_type, i.e. it's an + # array repr, it has a basetype of e.g. DW_ATE_unsigned and also + # "elements" which are referenced with a DISubrange(count: ) + # to say how many elements are in the array. + rshp = self.val["shape"] + rstrides = self.val["strides"] + + # bool on whether the data is aligned. + is_aligned = False + + # type information decode, simple type: + ty_str = str(self.val.type) + if HAVE_NUMPY and ('aligned' in ty_str or 'Record' in ty_str): + ty_str = ty_str.replace('unaligned ','').strip() + matcher = re.compile(r"array\((Record.*), (.*), (.*)\)\ \(.*") + # NOTE: need to deal with "Alignment" else dtype size is wrong + arr_info = [x.strip() for x in matcher.match(ty_str).groups()] + dtype_str, ndim_str, order_str = arr_info + rstr = r'Record\((.*\[.*\]);([0-9]+);(True|False)' + rstr_match = re.match(rstr, dtype_str) + # balign is unused, it's the alignment + fields, balign, is_aligned_str = rstr_match.groups() + is_aligned = is_aligned_str == 'True' + field_dts = fields.split(',') + struct_entries = [] + for f in field_dts: + splitted = f.split('[') + name = splitted[0] + dt_part = splitted[1:] + if len(dt_part) > 1: + raise TypeError('Unsupported sub-type: %s' % f) + else: + dt_part = dt_part[0] + if "nestedarray" in dt_part: + raise TypeError('Unsupported sub-type: %s' % f) + dt_as_str = dt_part.split(';')[0].split('=')[1] + dtype = np.dtype(dt_as_str) + struct_entries.append((name, dtype)) + # The dtype is actually a record of some sort + dtype_str = struct_entries + else: # simple type + matcher = re.compile(r"array\((.*),(.*),(.*)\)\ \(.*") + arr_info = [x.strip() for x in matcher.match(ty_str).groups()] + dtype_str, ndim_str, order_str = arr_info + # fix up unichr dtype + if 'unichr x ' in dtype_str: + dtype_str = dtype_str[1:-1].replace('unichr x ', '= 1 else None + minor = try_int(parts[1]) if len(parts) >= 2 else None + patch = try_int(parts[2]) if len(parts) >= 3 else None + short = (major, minor) + full = (major, minor, patch) + string = version + tup = tuple(parts) + git_revision = tup[3] if len(tup) >= 4 else None + return version_info(major, minor, patch, short, full, string, tup, + git_revision) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/inspection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/inspection.py new file mode 100644 index 0000000000000000000000000000000000000000..a92c9430805ae1d4e388a1ca3222075fe1330847 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/inspection.py @@ -0,0 +1,103 @@ +"""Miscellaneous inspection tools +""" +from tempfile import NamedTemporaryFile, TemporaryDirectory +import os +import warnings + +from numba.core.errors import NumbaWarning + + +def disassemble_elf_to_cfg(elf, mangled_symbol): + """ + Gets the CFG of the disassembly of an ELF object, elf, at mangled name, + mangled_symbol, and renders it appropriately depending on the execution + environment (terminal/notebook). + """ + try: + import r2pipe + except ImportError: + raise RuntimeError("r2pipe package needed for disasm CFG") + + def get_rendering(cmd=None): + from numba.pycc.platform import Toolchain # import local, circular ref + if cmd is None: + raise ValueError("No command given") + + with TemporaryDirectory() as tmpdir: + # Write ELF as a temporary file in the temporary dir, do not delete! + with NamedTemporaryFile(delete=False, dir=tmpdir) as f: + f.write(elf) + f.flush() # force write, radare2 needs a binary blob on disk + + # Now try and link the ELF, this helps radare2 _a lot_ + linked = False + try: + raw_dso_name = f'{os.path.basename(f.name)}.so' + linked_dso = os.path.join(tmpdir, raw_dso_name) + tc = Toolchain() + tc.link_shared(linked_dso, (f.name,)) + obj_to_analyse = linked_dso + linked = True + except Exception as e: + # link failed, mention it to user, radare2 will still be able to + # analyse the object, but things like dwarf won't appear in the + # asm as comments. + msg = ('Linking the ELF object with the distutils toolchain ' + f'failed with: {e}. Disassembly will still work but ' + 'might be less accurate and will not use DWARF ' + 'information.') + warnings.warn(NumbaWarning(msg)) + obj_to_analyse = f.name + + # catch if r2pipe can actually talk to radare2 + try: + flags = ['-2', # close stderr to hide warnings + '-e io.cache=true', # fix relocations in disassembly + '-e scr.color=1', # 16 bit ANSI colour terminal + '-e asm.dwarf=true', # DWARF decode + '-e scr.utf8=true', # UTF8 output looks better + ] + r = r2pipe.open(obj_to_analyse, flags=flags) + r.cmd('aaaaaa') # analyse as much as possible + # If the elf is linked then it's necessary to seek as the + # DSO ctor/dtor is at the default position + if linked: + # r2 only matches up to 61 chars?! found this by experiment! + mangled_symbol_61char = mangled_symbol[:61] + # switch off demangle, the seek is on a mangled symbol + r.cmd('e bin.demangle=false') + # seek to the mangled symbol address + r.cmd(f's `is~ {mangled_symbol_61char}[1]`') + # switch demangling back on for output purposes + r.cmd('e bin.demangle=true') + data = r.cmd('%s' % cmd) # print graph + r.quit() + except Exception as e: + if "radare2 in PATH" in str(e): + msg = ("This feature requires 'radare2' to be " + "installed and available on the system see: " + "https://github.com/radareorg/radare2. " + "Cannot find 'radare2' in $PATH.") + raise RuntimeError(msg) + else: + raise e + return data + + class DisasmCFG(object): + + def _repr_svg_(self): + try: + import graphviz + except ImportError: + raise RuntimeError("graphviz package needed for disasm CFG") + jupyter_rendering = get_rendering(cmd='agfd') + # this just makes it read slightly better in jupyter notebooks + jupyter_rendering.replace('fontname="Courier",', + 'fontname="Courier",fontsize=6,') + src = graphviz.Source(jupyter_rendering) + return src.pipe('svg').decode('UTF-8') + + def __repr__(self): + return get_rendering(cmd='agf') + + return DisasmCFG() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/literal.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/literal.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc1225b7e4b8428854b5f39b26a1f0ab6766d30 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/literal.py @@ -0,0 +1,24 @@ +from numba.core.extending import overload +from numba.core import types +from numba.misc.special import literally, literal_unroll +from numba.core.errors import TypingError + + +@overload(literally) +def _ov_literally(obj): + if isinstance(obj, (types.Literal, types.InitialValue)): + return lambda obj: obj + else: + m = "Invalid use of non-Literal type in literally({})".format(obj) + raise TypingError(m) + + +@overload(literal_unroll) +def literal_unroll_impl(container): + if isinstance(container, types.Poison): + m = f"Invalid use of non-Literal type in literal_unroll({container})" + raise TypingError(m) + + def impl(container): + return container + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/llvm_pass_timings.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/llvm_pass_timings.py new file mode 100644 index 0000000000000000000000000000000000000000..231ff43fa5337933e48e8913bf56e9081d7c4fc1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/llvm_pass_timings.py @@ -0,0 +1,471 @@ +import re +import operator +import heapq +from collections import namedtuple +from collections.abc import Sequence +from contextlib import contextmanager +from functools import cached_property + +from numba.core import config + +import llvmlite.binding as llvm + + +class RecordLLVMPassTimingsLegacy: + """A helper context manager to track LLVM pass timings. + """ + + __slots__ = ["_data"] + + def __enter__(self): + """Enables the pass timing in LLVM. + """ + llvm.set_time_passes(True) + return self + + def __exit__(self, exc_val, exc_type, exc_tb): + """Reset timings and save report internally. + """ + self._data = llvm.report_and_reset_timings() + llvm.set_time_passes(False) + return + + def get(self): + """Retrieve timing data for processing. + + Returns + ------- + timings: ProcessedPassTimings + """ + return ProcessedPassTimings(self._data) + + +class RecordLLVMPassTimings: + """A helper context manager to track LLVM pass timings. + """ + + __slots__ = ["_data", "_pb"] + + def __init__(self, pb): + self._pb = pb + self._data = None + + def __enter__(self): + """Enables the pass timing in LLVM. + """ + self._pb.start_pass_timing() + return self + + def __exit__(self, exc_val, exc_type, exc_tb): + """Reset timings and save report internally. + """ + self._data = self._pb.finish_pass_timing() + return + + def get(self): + """Retrieve timing data for processing. + + Returns + ------- + timings: ProcessedPassTimings + """ + return ProcessedPassTimings(self._data) + + +PassTimingRecord = namedtuple( + "PassTimingRecord", + [ + "user_time", + "user_percent", + "system_time", + "system_percent", + "user_system_time", + "user_system_percent", + "wall_time", + "wall_percent", + "pass_name", + "instruction", + ], +) + + +def _adjust_timings(records): + """Adjust timing records because of truncated information. + + Details: The percent information can be used to improve the timing + information. + + Returns + ------- + res: List[PassTimingRecord] + """ + total_rec = records[-1] + assert total_rec.pass_name == "Total" # guard for implementation error + + def make_adjuster(attr): + time_attr = f"{attr}_time" + percent_attr = f"{attr}_percent" + time_getter = operator.attrgetter(time_attr) + + def adjust(d): + """Compute percent x total_time = adjusted""" + total = time_getter(total_rec) + adjusted = total * d[percent_attr] * 0.01 + d[time_attr] = adjusted + return d + + return adjust + + # Make adjustment functions for each field + adj_fns = [ + make_adjuster(x) for x in ["user", "system", "user_system", "wall"] + ] + + # Extract dictionaries from the namedtuples + dicts = map(lambda x: x._asdict(), records) + + def chained(d): + # Chain the adjustment functions + for fn in adj_fns: + d = fn(d) + # Reconstruct the namedtuple + return PassTimingRecord(**d) + + return list(map(chained, dicts)) + + +class ProcessedPassTimings: + """A class for processing raw timing report from LLVM. + + The processing is done lazily so we don't waste time processing unused + timing information. + """ + + def __init__(self, raw_data): + self._raw_data = raw_data + + def __bool__(self): + return bool(self._raw_data) + + def get_raw_data(self): + """Returns the raw string data. + + Returns + ------- + res: str + """ + return self._raw_data + + def get_total_time(self): + """Compute the total time spend in all passes. + + Returns + ------- + res: float + """ + return self.list_records()[-1].wall_time + + def list_records(self): + """Get the processed data for the timing report. + + Returns + ------- + res: List[PassTimingRecord] + """ + return self._processed + + def list_top(self, n): + """Returns the top(n) most time-consuming (by wall-time) passes. + + Parameters + ---------- + n: int + This limits the maximum number of items to show. + This function will show the ``n`` most time-consuming passes. + + Returns + ------- + res: List[PassTimingRecord] + Returns the top(n) most time-consuming passes in descending order. + """ + records = self.list_records() + key = operator.attrgetter("wall_time") + return heapq.nlargest(n, records[:-1], key) + + def summary(self, topn=5, indent=0): + """Return a string summarizing the timing information. + + Parameters + ---------- + topn: int; optional + This limits the maximum number of items to show. + This function will show the ``topn`` most time-consuming passes. + indent: int; optional + Set the indentation level. Defaults to 0 for no indentation. + + Returns + ------- + res: str + """ + buf = [] + prefix = " " * indent + + def ap(arg): + buf.append(f"{prefix}{arg}") + + ap(f"Total {self.get_total_time():.4f}s") + ap("Top timings:") + for p in self.list_top(topn): + ap(f" {p.wall_time:.4f}s ({p.wall_percent:5}%) {p.pass_name}") + return "\n".join(buf) + + @cached_property + def _processed(self): + """A cached property for lazily processing the data and returning it. + + See ``_process()`` for details. + """ + return self._process() + + def _process(self): + """Parses the raw string data from LLVM timing report and attempts + to improve the data by recomputing the times + (See `_adjust_timings()``). + """ + + def parse(raw_data): + """A generator that parses the raw_data line-by-line to extract + timing information for each pass. + """ + lines = raw_data.splitlines() + colheader = r"[a-zA-Z+ ]+" + # Take at least one column header. + multicolheaders = fr"(?:\s*-+{colheader}-+)+" + + line_iter = iter(lines) + # find column headers + header_map = { + "User Time": "user", + "System Time": "system", + "User+System": "user_system", + "Wall Time": "wall", + "Instr": "instruction", + "Name": "pass_name", + } + for ln in line_iter: + m = re.match(multicolheaders, ln) + if m: + # Get all the column headers + raw_headers = re.findall(r"[a-zA-Z][a-zA-Z+ ]+", ln) + headers = [header_map[k.strip()] for k in raw_headers] + break + + assert headers[-1] == 'pass_name' + # compute the list of available attributes from the column headers + attrs = [] + n = r"\s*((?:[0-9]+\.)?[0-9]+)" + pat = "" + for k in headers[:-1]: + if k == "instruction": + pat += n + else: + attrs.append(f"{k}_time") + attrs.append(f"{k}_percent") + pat += rf"\s+(?:{n}\s*\({n}%\)|-+)" + + # put default value 0.0 to all missing attributes + missing = {} + for k in PassTimingRecord._fields: + if k not in attrs and k != 'pass_name': + missing[k] = 0.0 + # parse timings + pat += r"\s*(.*)" + for ln in line_iter: + m = re.match(pat, ln) + if m is not None: + raw_data = list(m.groups()) + data = {k: float(v) if v is not None else 0.0 + for k, v in zip(attrs, raw_data)} + data.update(missing) + pass_name = raw_data[-1] + rec = PassTimingRecord( + pass_name=pass_name, **data, + ) + yield rec + if rec.pass_name == "Total": + # "Total" means the report has ended + break + # Check that we have reach the end of the report + remaining = '\n'.join(line_iter) + + # FIXME: Need to handle parsing of Analysis execution timing report + if "Analysis execution timing report" in remaining: + return + + if remaining: + raise ValueError( + f"unexpected text after parser finished:\n{remaining}" + ) + + # Parse raw data + records = list(parse(self._raw_data)) + return _adjust_timings(records) + + +NamedTimings = namedtuple("NamedTimings", ["name", "timings"]) + + +class PassTimingsCollection(Sequence): + """A collection of pass timings. + + This class implements the ``Sequence`` protocol for accessing the + individual timing records. + """ + + def __init__(self, name): + self._name = name + self._records = [] + + @contextmanager + def record_legacy(self, name): + """Record new timings and append to this collection. + + Note: this is mainly for internal use inside the compiler pipeline. + + See also ``RecordLLVMPassTimingsLegacy`` + + Parameters + ---------- + name: str + Name for the records. + """ + if config.LLVM_PASS_TIMINGS: + # Recording of pass timings is enabled + with RecordLLVMPassTimingsLegacy() as timings: + yield + rec = timings.get() + # Only keep non-empty records + if rec: + self._append(name, rec) + else: + # Do nothing. Recording of pass timings is disabled. + yield + + @contextmanager + def record(self, name, pb): + """Record new timings and append to this collection. + + Note: this is mainly for internal use inside the compiler pipeline. + + See also ``RecordLLVMPassTimings`` + + Parameters + ---------- + name: str + Name for the records. + """ + if config.LLVM_PASS_TIMINGS: + # Recording of pass timings is enabled + with RecordLLVMPassTimings(pb) as timings: + yield + rec = timings.get() + # Only keep non-empty records + if rec: + self._append(name, rec) + else: + # Do nothing. Recording of pass timings is disabled. + yield + + def _append(self, name, timings): + """Append timing records + + Parameters + ---------- + name: str + Name for the records. + timings: ProcessedPassTimings + the timing records. + """ + self._records.append(NamedTimings(name, timings)) + + def get_total_time(self): + """Computes the sum of the total time across all contained timings. + + Returns + ------- + res: float or None + Returns the total number of seconds or None if no timings were + recorded + """ + if self._records: + return sum(r.timings.get_total_time() for r in self._records) + else: + return None + + def list_longest_first(self): + """Returns the timings in descending order of total time duration. + + Returns + ------- + res: List[ProcessedPassTimings] + """ + return sorted(self._records, + key=lambda x: x.timings.get_total_time(), + reverse=True) + + @property + def is_empty(self): + """ + """ + return not self._records + + def summary(self, topn=5): + """Return a string representing the summary of the timings. + + Parameters + ---------- + topn: int; optional, default=5. + This limits the maximum number of items to show. + This function will show the ``topn`` most time-consuming passes. + + Returns + ------- + res: str + + See also ``ProcessedPassTimings.summary()`` + """ + if self.is_empty: + return "No pass timings were recorded" + else: + buf = [] + ap = buf.append + ap(f"Printing pass timings for {self._name}") + overall_time = self.get_total_time() + ap(f"Total time: {overall_time:.4f}") + for i, r in enumerate(self._records): + ap(f"== #{i} {r.name}") + percent = r.timings.get_total_time() / overall_time * 100 + ap(f" Percent: {percent:.1f}%") + ap(r.timings.summary(topn=topn, indent=1)) + return "\n".join(buf) + + def __getitem__(self, i): + """Get the i-th timing record. + + Returns + ------- + res: (name, timings) + A named tuple with two fields: + + - name: str + - timings: ProcessedPassTimings + """ + return self._records[i] + + def __len__(self): + """Length of this collection. + """ + return len(self._records) + + def __str__(self): + return self.summary() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/memoryutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/memoryutils.py new file mode 100644 index 0000000000000000000000000000000000000000..49495cd269d8f461d56037d87b2391577483b149 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/memoryutils.py @@ -0,0 +1,196 @@ +""" +Memory monitoring utilities for measuring memory usage. + +Example usage: + tracker = MemoryTracker("my_function") + with tracker.monitor(): + my_function() + # Access data: tracker.rss_delta, tracker.duration, etc. + # Get formatted string: tracker.get_summary() +""" +from __future__ import annotations +import os +import contextlib +import time +from typing import Dict, Optional + + +try: + import psutil + _HAS_PSUTIL = True +except ImportError: + _HAS_PSUTIL = False + + +IS_SUPPORTED = _HAS_PSUTIL + + +def get_available_memory() -> Optional[int]: + """ + Get current available system memory in bytes. + + Used for memory threshold checking in parallel test execution. + + Returns: + int or None: Available memory in bytes, or None if unavailable + """ + if _HAS_PSUTIL: + try: + sys_mem = psutil.virtual_memory() + return sys_mem.available + except Exception: + pass + + return None + + +def get_memory_usage() -> Dict[str, Optional[int]]: + """ + Get memory usage information needed for monitoring. + + Returns only RSS and available memory which are the fields + actually used by the MemoryTracker. + + Returns: + dict: Memory usage information including: + - rss: Current process RSS (physical memory currently used) + - available: Available system memory + """ + memory_info = {} + + if _HAS_PSUTIL: + try: + # Get current process RSS + process = psutil.Process(os.getpid()) + mem_info = process.memory_info() + memory_info["rss"] = mem_info.rss + + # Get system available memory + sys_mem = psutil.virtual_memory() + memory_info["available"] = sys_mem.available + + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + + # Set defaults if unavailable + if "rss" not in memory_info: + memory_info["rss"] = None + if "available" not in memory_info: + memory_info["available"] = None + + return memory_info + + +class MemoryTracker: + """ + A simple memory monitor that tracks RSS delta and timing. + + Stores monitoring data in instance attributes for later access. + Each instance is typically used for monitoring a single operation. + """ + pid: int + name: str + start_time: float | None + end_time: float | None + start_memory: Dict[str, int | None] | None + end_memory: Dict[str, int | None] | None + duration: float | None + rss_delta: int | None + + def __init__(self, name: str): + """Initialize a MemoryTracker with empty monitoring data.""" + self.pid = os.getpid() + self.name = name + self.start_time = None + self.end_time = None + self.start_memory = None + self.end_memory = None + self.duration = None + self.rss_delta = None + + @contextlib.contextmanager + def monitor(self): + """ + Context manager to monitor memory usage during function execution. + + Records start/end memory usage and timing, calculates RSS delta, + and stores all data in instance attributes. + + Args: + name (str): Name/identifier for the function or operation being + monitored + + Yields: + self: The MemoryTracker instance for accessing stored data + """ + # Store data in self and record start time and memory usage + self.start_time = time.time() + self.start_memory = get_memory_usage() + + try: + yield self + finally: + # Record end time and memory usage + self.end_time = time.time() + self.end_memory = get_memory_usage() + self.duration = self.end_time - self.start_time + + # Calculate RSS delta + start_rss = self.start_memory.get("rss", 0) + end_rss = self.end_memory.get("rss", 0) + self.rss_delta = ((end_rss - start_rss) + if start_rss and end_rss else 0) + + def get_summary(self) -> str: + """ + Return a formatted summary of the memory monitoring data. + + Formats the stored monitoring data into a human-readable string + containing name, PID, RSS delta, available memory, duration, + and start time. + + Returns: + str: Formatted summary string with monitoring results + + Note: + Should be called after monitor() context has completed + to ensure all data is available. + """ + if self.start_memory is None or self.end_memory is None: + raise ValueError("Memory monitoring data not available") + + current_available = self.end_memory.get("available") + + def format_bytes(bytes_val, show_sign=False): + """Convert bytes to human readable format""" + if bytes_val is None: + return "N/A" + if bytes_val == 0: + return "0 B" + + sign = "" + if show_sign: + sign = "-" if bytes_val < 0 else "+" + bytes_val = abs(bytes_val) + + for unit in ["B", "KB", "MB", "GB"]: + if bytes_val < 1024.0: + return f"{sign}{bytes_val:.2f} {unit}" + bytes_val /= 1024.0 + return f"{sign}{bytes_val:.2f} TB" + + start_ts = time.strftime("%H:%M:%S", time.localtime(self.start_time)) + start_rss = self.start_memory.get("rss", 0) + end_rss = self.end_memory.get("rss", 0) + + buf = [ + f"Name: {self.name}", + f"PID: {self.pid}", + f"Start: {start_ts}", + f"Duration: {self.duration:.3f}s", + f"Start RSS: {format_bytes(start_rss)}", + f"End RSS: {format_bytes(end_rss)}", + f"RSS delta: {format_bytes(self.rss_delta, show_sign=True)}", + f"Avail memory: {format_bytes(current_available)}", + ] + return ' | '.join(buf) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/mergesort.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/mergesort.py new file mode 100644 index 0000000000000000000000000000000000000000..cba5f3318b7ef55398df4f5e921e1f2c7a68aed3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/mergesort.py @@ -0,0 +1,126 @@ +""" +The same algorithm as translated from numpy. +See numpy/core/src/npysort/mergesort.c.src. +The high-level numba code is adding a little overhead comparing to +the pure-C implementation in numpy. +""" +import numpy as np +from collections import namedtuple + +# Array size smaller than this will be sorted by insertion sort +SMALL_MERGESORT = 20 + + +MergesortImplementation = namedtuple('MergesortImplementation', [ + 'run_mergesort', +]) + + +def make_mergesort_impl(wrap, lt=None, is_argsort=False): + kwargs_lite = dict(no_cpython_wrapper=True, _nrt=False) + + # The less than + if lt is None: + @wrap(**kwargs_lite) + def lt(a, b): + return a < b + else: + lt = wrap(**kwargs_lite)(lt) + + if is_argsort: + @wrap(**kwargs_lite) + def lessthan(a, b, vals): + return lt(vals[a], vals[b]) + else: + @wrap(**kwargs_lite) + def lessthan(a, b, vals): + return lt(a, b) + + @wrap(**kwargs_lite) + def argmergesort_inner(arr, vals, ws): + """The actual mergesort function + + Parameters + ---------- + arr : array [read+write] + The values being sorted inplace. For argsort, this is the + indices. + vals : array [readonly] + ``None`` for normal sort. In argsort, this is the actual array values. + ws : array [write] + The workspace. Must be of size ``arr.size // 2`` + """ + if arr.size > SMALL_MERGESORT: + # Merge sort + mid = arr.size // 2 + + argmergesort_inner(arr[:mid], vals, ws) + argmergesort_inner(arr[mid:], vals, ws) + + # Copy left half into workspace so we don't overwrite it + for i in range(mid): + ws[i] = arr[i] + + # Merge + left = ws[:mid] + right = arr[mid:] + out = arr + + i = j = k = 0 + while i < left.size and j < right.size: + if not lessthan(right[j], left[i], vals): + out[k] = left[i] + i += 1 + else: + out[k] = right[j] + j += 1 + k += 1 + + # Leftovers + while i < left.size: + out[k] = left[i] + i += 1 + k += 1 + + while j < right.size: + out[k] = right[j] + j += 1 + k += 1 + else: + # Insertion sort + i = 1 + while i < arr.size: + j = i + while j > 0 and lessthan(arr[j], arr[j - 1], vals): + arr[j - 1], arr[j] = arr[j], arr[j - 1] + j -= 1 + i += 1 + + # The top-level entry points + + @wrap(no_cpython_wrapper=True) + def mergesort(arr): + "Inplace" + ws = np.empty(arr.size // 2, dtype=arr.dtype) + argmergesort_inner(arr, None, ws) + return arr + + + @wrap(no_cpython_wrapper=True) + def argmergesort(arr): + "Out-of-place" + idxs = np.arange(arr.size) + ws = np.empty(arr.size // 2, dtype=idxs.dtype) + argmergesort_inner(idxs, arr, ws) + return idxs + + return MergesortImplementation( + run_mergesort=(argmergesort if is_argsort else mergesort) + ) + + +def make_jit_mergesort(*args, **kwargs): + from numba import njit + # NOTE: wrap with njit to allow recursion + # because @register_jitable => @overload doesn't support recursion + return make_mergesort_impl(njit, *args, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_entry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..b95f9dd06b44a23b84ac7efc508f41718eb40b92 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_entry.py @@ -0,0 +1,72 @@ +import sys +import argparse +import os +import subprocess +import json + +from .numba_sysinfo import display_sysinfo, get_sysinfo +from .numba_gdbinfo import display_gdbinfo + + +def make_parser(): + parser = argparse.ArgumentParser() + parser.add_argument('--annotate', help='Annotate source', + action='store_true') + parser.add_argument('--dump-llvm', action="store_true", + help='Print generated llvm assembly') + parser.add_argument('--dump-optimized', action='store_true', + help='Dump the optimized llvm assembly') + parser.add_argument('--dump-assembly', action='store_true', + help='Dump the LLVM generated assembly') + parser.add_argument('--annotate-html', nargs=1, + help='Output source annotation as html') + parser.add_argument('-s', '--sysinfo', action="store_true", + help='Output system information for bug reporting') + parser.add_argument('-g', '--gdbinfo', action="store_true", + help='Output system information about gdb') + parser.add_argument('--sys-json', nargs=1, + help='Saves the system info dict as a json file') + parser.add_argument('filename', nargs='?', help='Python source filename') + return parser + + +def main(): + parser = make_parser() + args = parser.parse_args() + + if args.sysinfo: + print("System info:") + display_sysinfo() + + if args.gdbinfo: + print("GDB info:") + display_gdbinfo() + + if args.sysinfo or args.gdbinfo: + sys.exit(0) + + if args.sys_json: + info = get_sysinfo() + info.update({'Start': info['Start'].isoformat()}) + info.update({'Start UTC': info['Start UTC'].isoformat()}) + with open(args.sys_json[0], 'w') as f: + json.dump(info, f, indent=4) + sys.exit(0) + + os.environ['NUMBA_DUMP_ANNOTATION'] = str(int(args.annotate)) + if args.annotate_html is not None: + try: + from jinja2 import Template + except ImportError: + raise ImportError("Please install the 'jinja2' package") + os.environ['NUMBA_DUMP_HTML'] = str(args.annotate_html[0]) + os.environ['NUMBA_DUMP_LLVM'] = str(int(args.dump_llvm)) + os.environ['NUMBA_DUMP_OPTIMIZED'] = str(int(args.dump_optimized)) + os.environ['NUMBA_DUMP_ASSEMBLY'] = str(int(args.dump_assembly)) + + if args.filename: + cmd = [sys.executable, args.filename] + subprocess.call(cmd) + else: + print("numba: error: the following arguments are required: filename") + sys.exit(1) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_gdbinfo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_gdbinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..db92cd24b6c120368b0560497bd28d75bba5c37d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_gdbinfo.py @@ -0,0 +1,161 @@ +"""Module for displaying information about Numba's gdb set up""" +from collections import namedtuple +import os +import re +import subprocess +from textwrap import dedent +from numba import config + +# Container for the output of the gdb info data collection +_fields = ('binary_loc, extension_loc, py_ver, np_ver, supported') +_gdb_info = namedtuple('_gdb_info', _fields) + + +class _GDBTestWrapper(): + """Wraps the gdb binary and has methods for checking what the gdb binary + has support for (Python and NumPy).""" + + def __init__(self,): + gdb_binary = config.GDB_BINARY + if gdb_binary is None: + msg = ("No valid binary could be found for gdb named: " + f"{config.GDB_BINARY}") + raise ValueError(msg) + self._gdb_binary = gdb_binary + + def _run_cmd(self, cmd=()): + gdb_call = [self.gdb_binary, '-q',] + for x in cmd: + gdb_call.append('-ex') + gdb_call.append(x) + gdb_call.extend(['-ex', 'q']) + return subprocess.run(gdb_call, capture_output=True, timeout=10, + text=True) + + @property + def gdb_binary(self): + return self._gdb_binary + + @classmethod + def success(cls, status): + return status.returncode == 0 + + def check_launch(self): + """Checks that gdb will launch ok""" + return self._run_cmd() + + def check_python(self): + cmd = ("python from __future__ import print_function; " + "import sys; print(sys.version_info[:2])") + return self._run_cmd((cmd,)) + + def check_numpy(self): + cmd = ("python from __future__ import print_function; " + "import types; import numpy; " + "print(isinstance(numpy, types.ModuleType))") + return self._run_cmd((cmd,)) + + def check_numpy_version(self): + cmd = ("python from __future__ import print_function; " + "import types; import numpy;" + "print(numpy.__version__)") + return self._run_cmd((cmd,)) + + +def collect_gdbinfo(): + """Prints information to stdout about the gdb setup that Numba has found""" + + # State flags: + gdb_state = None + gdb_has_python = False + gdb_has_numpy = False + gdb_python_version = 'No Python support' + gdb_python_numpy_version = "No NumPy support" + + # There are so many ways for gdb to not be working as expected. Surround + # the "is it working" tests with try/except and if there's an exception + # store it for processing later. + try: + # Check gdb exists + gdb_wrapper = _GDBTestWrapper() + + # Check gdb works + status = gdb_wrapper.check_launch() + if not gdb_wrapper.success(status): + msg = (f"gdb at '{gdb_wrapper.gdb_binary}' does not appear to work." + f"\nstdout: {status.stdout}\nstderr: {status.stderr}") + raise ValueError(msg) + gdb_state = gdb_wrapper.gdb_binary + except Exception as e: + gdb_state = f"Testing gdb binary failed. Reported Error: {e}" + else: + # Got this far, so gdb works, start checking what it supports + status = gdb_wrapper.check_python() + if gdb_wrapper.success(status): + version_match = re.match(r'\((\d+),\s+(\d+)\)', + status.stdout.strip()) + if version_match is not None: + pymajor, pyminor = version_match.groups() + gdb_python_version = f"{pymajor}.{pyminor}" + gdb_has_python = True + + status = gdb_wrapper.check_numpy() + if gdb_wrapper.success(status): + if "Traceback" not in status.stderr.strip(): + if status.stdout.strip() == 'True': + gdb_has_numpy = True + gdb_python_numpy_version = "Unknown" + # NumPy is present find the version + status = gdb_wrapper.check_numpy_version() + if gdb_wrapper.success(status): + if "Traceback" not in status.stderr.strip(): + gdb_python_numpy_version = \ + status.stdout.strip() + + # Work out what level of print-extension support is present in this gdb + if gdb_has_python: + if gdb_has_numpy: + print_ext_supported = "Full (Python and NumPy supported)" + else: + print_ext_supported = "Partial (Python only, no NumPy support)" + else: + print_ext_supported = "None" + + # Work out print ext location + print_ext_file = "gdb_print_extension.py" + print_ext_path = os.path.join(os.path.dirname(__file__), print_ext_file) + + # return! + return _gdb_info(gdb_state, print_ext_path, gdb_python_version, + gdb_python_numpy_version, print_ext_supported) + + +def display_gdbinfo(sep_pos=45): + """Displays the information collected by collect_gdbinfo. + """ + gdb_info = collect_gdbinfo() + print('-' * 80) + fmt = f'%-{sep_pos}s : %-s' + # Display the information + print(fmt % ("Binary location", gdb_info.binary_loc)) + print(fmt % ("Print extension location", gdb_info.extension_loc)) + print(fmt % ("Python version", gdb_info.py_ver)) + print(fmt % ("NumPy version", gdb_info.np_ver)) + print(fmt % ("Numba printing extension support", gdb_info.supported)) + + print("") + print("To load the Numba gdb printing extension, execute the following " + "from the gdb prompt:") + print(f"\nsource {gdb_info.extension_loc}\n") + print('-' * 80) + warn = """ + ============================================================= + IMPORTANT: Before sharing you should remove any information + in the above that you wish to keep private e.g. paths. + ============================================================= + """ + print(dedent(warn)) + + +if __name__ == '__main__': + display_gdbinfo() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_sysinfo.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_sysinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..a50d2956f74a84678eceba1165e9c7439ee7910d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/numba_sysinfo.py @@ -0,0 +1,706 @@ +import json +import locale +import multiprocessing +import os +import platform +import textwrap +import sys +from contextlib import redirect_stdout +from datetime import datetime +from io import StringIO +from subprocess import check_output, PIPE, CalledProcessError +import numpy as np +import llvmlite.binding as llvmbind +from llvmlite import __version__ as llvmlite_version +from numba import cuda as cu, __version__ as version_number +from numba.cuda import cudadrv +from numba.cuda.cudadrv.driver import driver as cudriver +from numba.cuda.cudadrv.runtime import runtime as curuntime +from numba.core import config + +_psutil_import = False +try: + import psutil +except ImportError: + pass +else: + _psutil_import = True + +__all__ = ['get_sysinfo', 'display_sysinfo'] + +# Keys of a `sysinfo` dictionary + +# Time info +_start, _start_utc, _runtime = 'Start', 'Start UTC', 'Runtime' +_numba_version = 'Numba Version' +# Hardware info +_machine = 'Machine' +_cpu_name, _cpu_count = 'CPU Name', 'CPU Count' +_cpus_allowed, _cpus_list = 'CPUs Allowed', 'List CPUs Allowed' +_cpu_features = 'CPU Features' +_cfs_quota, _cfs_period = 'CFS Quota', 'CFS Period', +_cfs_restrict = 'CFS Restriction' +_mem_total, _mem_available = 'Mem Total', 'Mem Available' +# OS info +_platform_name, _platform_release = 'Platform Name', 'Platform Release' +_os_name, _os_version = 'OS Name', 'OS Version' +_os_spec_version = 'OS Specific Version' +_libc_version = 'Libc Version' +# Python info +_python_comp = 'Python Compiler' +_python_impl = 'Python Implementation' +_python_version = 'Python Version' +_python_locale = 'Python Locale' +# LLVM info +_llvmlite_version = 'llvmlite Version' +_llvm_version = 'LLVM Version' +# CUDA info +_cu_target_impl = 'CUDA Target Impl' +_cu_dev_init = 'CUDA Device Init' +_cu_drv_ver = 'CUDA Driver Version' +_cu_rt_ver = 'CUDA Runtime Version' +_cu_nvidia_bindings = 'NVIDIA CUDA Bindings' +_cu_nvidia_bindings_used = 'NVIDIA CUDA Bindings In Use' +_cu_detect_out, _cu_lib_test = 'CUDA Detect Output', 'CUDA Lib Test' +_cu_mvc_available = 'NVIDIA CUDA Minor Version Compatibility Available' +_cu_mvc_needed = 'NVIDIA CUDA Minor Version Compatibility Needed' +_cu_mvc_in_use = 'NVIDIA CUDA Minor Version Compatibility In Use' +# NumPy info +_numpy_version = 'NumPy Version' +_numpy_supported_simd_features = 'NumPy Supported SIMD features' +_numpy_supported_simd_dispatch = 'NumPy Supported SIMD dispatch' +_numpy_supported_simd_baseline = 'NumPy Supported SIMD baseline' +_numpy_AVX512_SKX_detected = 'NumPy AVX512_SKX detected' +# SVML info +_svml_state, _svml_loaded = 'SVML State', 'SVML Lib Loaded' +_llvm_svml_patched = 'LLVM SVML Patched' +_svml_operational = 'SVML Operational' +# Threading layer info +_tbb_thread, _tbb_error = 'TBB Threading', 'TBB Threading Error' +_openmp_thread, _openmp_error = 'OpenMP Threading', 'OpenMP Threading Error' +_openmp_vendor = 'OpenMP vendor' +_wkq_thread, _wkq_error = 'Workqueue Threading', 'Workqueue Threading Error' +# Numba info +_numba_env_vars = 'Numba Env Vars' +# Conda info +_conda_build_ver, _conda_env_ver = 'Conda Build', 'Conda Env' +_conda_platform, _conda_python_ver = 'Conda Platform', 'Conda Python Version' +_conda_root_writable = 'Conda Root Writable' +# Packages info +_inst_pkg = 'Installed Packages' +# Psutil info +_psutil = 'Psutil Available' +# Errors and warnings +_errors = 'Errors' +_warnings = 'Warnings' + +# Error and warning log +_error_log = [] +_warning_log = [] + + +def get_os_spec_info(os_name): + # Linux man page for `/proc`: + # http://man7.org/linux/man-pages/man5/proc.5.html + + # WMIC is deprecated in windows-2025, using powershell instead + # https://techcommunity.microsoft.com/t5/windows-it-pro-blog/wmi-command-line-wmic-utility-deprecation-next-steps/ba-p/4039242 + # Windows documentation for `powershell`: + # https://learn.microsoft.com/en-us/powershell/ + + # MacOS man page for `sysctl`: + # https://www.unix.com/man-page/osx/3/sysctl/ + # MacOS man page for `vm_stat`: + # https://www.unix.com/man-page/osx/1/vm_stat/ + + class CmdBufferOut(tuple): + buffer_output_flag = True + + class CmdReadFile(tuple): + read_file_flag = True + + shell_params = { + 'Linux': { + 'cmd': ( + CmdReadFile(('/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us',)), + CmdReadFile(('/sys/fs/cgroup/cpuacct/cpu.cfs_period_us',)), + ), + 'cmd_optional': ( + CmdReadFile(('/proc/meminfo',)), + CmdReadFile(('/proc/self/status',)), + ), + 'kwds': { + # output string fragment -> result dict key + 'MemTotal:': _mem_total, + 'MemAvailable:': _mem_available, + 'Cpus_allowed:': _cpus_allowed, + 'Cpus_allowed_list:': _cpus_list, + '/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us': _cfs_quota, + '/sys/fs/cgroup/cpuacct/cpu.cfs_period_us': _cfs_period, + }, + }, + 'Windows': { + 'cmd': (), + 'cmd_optional': ( + CmdBufferOut(('powershell', '-NoProfile', '-Command', + "'TotalVirtualMemorySize ' + " + "(Get-CimInstance -ClassName " + "Win32_OperatingSystem).TotalVirtualMemorySize")), + CmdBufferOut(('powershell', '-NoProfile', '-Command', + "'FreeVirtualMemory ' + " + "(Get-CimInstance -ClassName " + "Win32_OperatingSystem).FreeVirtualMemory")), + ), + 'kwds': { + # output string fragment -> result dict key + 'TotalVirtualMemorySize': _mem_total, + 'FreeVirtualMemory': _mem_available, + }, + }, + 'Darwin': { + 'cmd': (), + 'cmd_optional': ( + ('sysctl', 'hw.memsize'), + ('vm_stat'), + ), + 'kwds': { + # output string fragment -> result dict key + 'hw.memsize:': _mem_total, + 'free:': _mem_available, + }, + 'units': { + _mem_total: 1, # Size is given in bytes. + _mem_available: 4096, # Size is given in 4kB pages. + }, + }, + } + + os_spec_info = {} + params = shell_params.get(os_name, {}) + cmd_selected = params.get('cmd', ()) + + if _psutil_import: + vm = psutil.virtual_memory() + os_spec_info.update({ + _mem_total: vm.total, + _mem_available: vm.available, + }) + p = psutil.Process() + cpus_allowed = p.cpu_affinity() if hasattr(p, 'cpu_affinity') else [] + if cpus_allowed: + os_spec_info[_cpus_allowed] = len(cpus_allowed) + os_spec_info[_cpus_list] = ' '.join(str(n) for n in cpus_allowed) + + else: + _warning_log.append( + "Warning (psutil): psutil cannot be imported. " + "For more accuracy, consider installing it.") + # Fallback to internal heuristics + cmd_selected += params.get('cmd_optional', ()) + + # Assuming the shell cmd returns a unique (k, v) pair per line + # or a unique (k, v) pair spread over several lines: + # Gather output in a list of strings containing a keyword and some value. + output = [] + for cmd in cmd_selected: + if hasattr(cmd, 'read_file_flag'): + # Open file within Python + if os.path.exists(cmd[0]): + try: + with open(cmd[0], 'r') as f: + out = f.readlines() + if out: + out[0] = ' '.join((cmd[0], out[0])) + output.extend(out) + except OSError as e: + _error_log.append(f'Error (file read): {e}') + continue + else: + _warning_log.append('Warning (no file): {}'.format(cmd[0])) + continue + else: + # Spawn a subprocess + try: + out = check_output(cmd, stderr=PIPE) + except (OSError, CalledProcessError) as e: + _error_log.append(f'Error (subprocess): {e}') + continue + if hasattr(cmd, 'buffer_output_flag'): + out = b' '.join(line for line in out.splitlines()) + b'\n' + output.extend(out.decode().splitlines()) + + # Extract (k, output) pairs by searching for keywords in output + kwds = params.get('kwds', {}) + for line in output: + match = kwds.keys() & line.split() + if match and len(match) == 1: + k = kwds[match.pop()] + os_spec_info[k] = line + elif len(match) > 1: + print(f'Ambiguous output: {line}') + + # Try to extract something meaningful from output string + def format(): + # CFS restrictions + split = os_spec_info.get(_cfs_quota, '').split() + if split: + os_spec_info[_cfs_quota] = float(split[-1]) + split = os_spec_info.get(_cfs_period, '').split() + if split: + os_spec_info[_cfs_period] = float(split[-1]) + if os_spec_info.get(_cfs_quota, -1) != -1: + cfs_quota = os_spec_info.get(_cfs_quota, '') + cfs_period = os_spec_info.get(_cfs_period, '') + runtime_amount = cfs_quota / cfs_period + os_spec_info[_cfs_restrict] = runtime_amount + + def format_optional(): + # Memory + units = {_mem_total: 1024, _mem_available: 1024} + units.update(params.get('units', {})) + for k in (_mem_total, _mem_available): + digits = ''.join(d for d in os_spec_info.get(k, '') if d.isdigit()) + os_spec_info[k] = int(digits or 0) * units[k] + # Accessible CPUs + split = os_spec_info.get(_cpus_allowed, '').split() + if split: + n = split[-1] + n = n.split(',')[-1] + os_spec_info[_cpus_allowed] = str(bin(int(n or 0, 16))).count('1') + split = os_spec_info.get(_cpus_list, '').split() + if split: + os_spec_info[_cpus_list] = split[-1] + + try: + format() + if not _psutil_import: + format_optional() + except Exception as e: + _error_log.append(f'Error (format shell output): {e}') + + # Call OS specific functions + os_specific_funcs = { + 'Linux': { + _libc_version: lambda: ' '.join(platform.libc_ver()) + }, + 'Windows': { + _os_spec_version: lambda: ' '.join( + s for s in platform.win32_ver()), + }, + 'Darwin': { + _os_spec_version: lambda: ''.join( + i or ' ' for s in tuple(platform.mac_ver()) for i in s), + }, + } + key_func = os_specific_funcs.get(os_name, {}) + os_spec_info.update({k: f() for k, f in key_func.items()}) + return os_spec_info + + +def get_sysinfo(): + + # Gather the information that shouldn't raise exceptions + sys_info = { + _start: datetime.now(), + _start_utc: datetime.utcnow(), + _machine: platform.machine(), + _cpu_name: llvmbind.get_host_cpu_name(), + _cpu_count: multiprocessing.cpu_count(), + _platform_name: platform.platform(aliased=True), + _platform_release: platform.release(), + _os_name: platform.system(), + _os_version: platform.version(), + _python_comp: platform.python_compiler(), + _python_impl: platform.python_implementation(), + _python_version: platform.python_version(), + _numba_env_vars: {k: v for (k, v) in os.environ.items() + if k.startswith('NUMBA_')}, + _numba_version: version_number, + _llvm_version: '.'.join(str(i) for i in llvmbind.llvm_version_info), + _llvmlite_version: llvmlite_version, + _psutil: _psutil_import, + } + + # CPU features + try: + feature_map = llvmbind.get_host_cpu_features() + except RuntimeError as e: + _error_log.append(f'Error (CPU features): {e}') + else: + features = sorted([key for key, value in feature_map.items() if value]) + sys_info[_cpu_features] = ' '.join(features) + + # Python locale + # On MacOSX, getdefaultlocale can raise. Check again if Py > 3.7.5 + try: + # If $LANG is unset, getdefaultlocale() can return (None, None), make + # sure we can encode this as strings by casting explicitly. + sys_info[_python_locale] = '.'.join([str(i) for i in + locale.getdefaultlocale()]) + except Exception as e: + _error_log.append(f'Error (locale): {e}') + + # CUDA information + try: + sys_info[_cu_target_impl] = cu.implementation + except AttributeError: + # On the offchance an out-of-tree target did not set the + # implementation, we can try to continue + pass + + try: + cu.list_devices()[0] # will a device initialise? + except Exception as e: + sys_info[_cu_dev_init] = False + msg_not_found = "CUDA driver library cannot be found" + msg_disabled_by_user = "CUDA is disabled" + msg_end = " or no CUDA enabled devices are present." + msg_generic_problem = "CUDA device initialisation problem." + msg = getattr(e, 'msg', None) + if msg is not None: + if msg_not_found in msg: + err_msg = msg_not_found + msg_end + elif msg_disabled_by_user in msg: + err_msg = msg_disabled_by_user + msg_end + else: + err_msg = msg_generic_problem + " Message:" + msg + else: + err_msg = msg_generic_problem + " " + str(e) + # Best effort error report + _warning_log.append("Warning (cuda): %s\nException class: %s" % + (err_msg, str(type(e)))) + else: + try: + sys_info[_cu_dev_init] = True + + output = StringIO() + with redirect_stdout(output): + cu.detect() + sys_info[_cu_detect_out] = output.getvalue() + output.close() + + cu_drv_ver = cudriver.get_version() + cu_rt_ver = curuntime.get_version() + sys_info[_cu_drv_ver] = '%s.%s' % cu_drv_ver + sys_info[_cu_rt_ver] = '%s.%s' % cu_rt_ver + + output = StringIO() + with redirect_stdout(output): + cudadrv.libs.test() + sys_info[_cu_lib_test] = output.getvalue() + output.close() + + try: + from cuda import cuda # noqa: F401 + nvidia_bindings_available = True + except ImportError: + nvidia_bindings_available = False + sys_info[_cu_nvidia_bindings] = nvidia_bindings_available + + nv_binding_used = bool(cudadrv.driver.USE_NV_BINDING) + sys_info[_cu_nvidia_bindings_used] = nv_binding_used + + try: + from ptxcompiler import compile_ptx # noqa: F401 + from cubinlinker import CubinLinker # noqa: F401 + sys_info[_cu_mvc_available] = True + except ImportError: + sys_info[_cu_mvc_available] = False + + sys_info[_cu_mvc_needed] = cu_rt_ver > cu_drv_ver + sys_info[_cu_mvc_in_use] = bool( + config.CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY) + except Exception as e: + _warning_log.append( + "Warning (cuda): Probing CUDA failed " + "(device and driver present, runtime problem?)\n" + f"(cuda) {type(e)}: {e}") + + # NumPy information + sys_info[_numpy_version] = np.version.full_version + try: + # NOTE: These consts were added in NumPy 1.20 + from numpy.core._multiarray_umath import (__cpu_features__, + __cpu_dispatch__, + __cpu_baseline__,) + except ImportError: + sys_info[_numpy_AVX512_SKX_detected] = False + else: + feat_filtered = [k for k, v in __cpu_features__.items() if v] + sys_info[_numpy_supported_simd_features] = feat_filtered + sys_info[_numpy_supported_simd_dispatch] = __cpu_dispatch__ + sys_info[_numpy_supported_simd_baseline] = __cpu_baseline__ + sys_info[_numpy_AVX512_SKX_detected] = \ + __cpu_features__.get("AVX512_SKX", False) + + # SVML information + # Replicate some SVML detection logic from numba.__init__ here. + # If SVML load fails in numba.__init__ the splitting of the logic + # here will help diagnosing the underlying issue. + svml_lib_loaded = True + try: + if sys.platform.startswith('linux'): + llvmbind.load_library_permanently("libsvml.so") + elif sys.platform.startswith('darwin'): + llvmbind.load_library_permanently("libsvml.dylib") + elif sys.platform.startswith('win'): + llvmbind.load_library_permanently("svml_dispmd") + else: + svml_lib_loaded = False + except Exception: + svml_lib_loaded = False + func = getattr(llvmbind.targets, "has_svml", None) + sys_info[_llvm_svml_patched] = func() if func else False + sys_info[_svml_state] = config.USING_SVML + sys_info[_svml_loaded] = svml_lib_loaded + sys_info[_svml_operational] = all(( + sys_info[_svml_state], + sys_info[_svml_loaded], + sys_info[_llvm_svml_patched], + )) + + # Check which threading backends are available. + def parse_error(e, backend): + # parses a linux based error message, this is to provide feedback + # and hide user paths etc + try: + path, problem, symbol = [x.strip() for x in e.msg.split(':')] + extn_dso = os.path.split(path)[1] + if backend in extn_dso: + return "%s: %s" % (problem, symbol) + except Exception: + pass + return "Unknown import problem." + + try: + # check import is ok, this means the DSO linkage is working + from numba.np.ufunc import tbbpool # NOQA + # check that the version is compatible, this is a check performed at + # runtime (well, compile time), it will also ImportError if there's + # a problem. + from numba.np.ufunc.parallel import _check_tbb_version_compatible + _check_tbb_version_compatible() + sys_info[_tbb_thread] = True + except ImportError as e: + # might be a missing symbol due to e.g. tbb libraries missing + sys_info[_tbb_thread] = False + sys_info[_tbb_error] = parse_error(e, 'tbbpool') + + try: + from numba.np.ufunc import omppool + sys_info[_openmp_thread] = True + sys_info[_openmp_vendor] = omppool.openmp_vendor + except ImportError as e: + sys_info[_openmp_thread] = False + sys_info[_openmp_error] = parse_error(e, 'omppool') + + try: + from numba.np.ufunc import workqueue # NOQA + sys_info[_wkq_thread] = True + except ImportError as e: + sys_info[_wkq_thread] = True + sys_info[_wkq_error] = parse_error(e, 'workqueue') + + # Look for conda and installed packages information + cmd = ('conda', 'info', '--json') + try: + conda_out = check_output(cmd) + except Exception as e: + _warning_log.append(f'Warning: Conda not available.\n Error was {e}\n') + # Conda is not available, try pip list to list installed packages + cmd = (sys.executable, '-m', 'pip', 'list') + try: + reqs = check_output(cmd) + except Exception as e: + _error_log.append(f'Error (pip): {e}') + else: + sys_info[_inst_pkg] = reqs.decode().splitlines() + + else: + jsond = json.loads(conda_out.decode()) + keys = { + 'conda_build_version': _conda_build_ver, + 'conda_env_version': _conda_env_ver, + 'platform': _conda_platform, + 'python_version': _conda_python_ver, + 'root_writable': _conda_root_writable, + } + for conda_k, sysinfo_k in keys.items(): + sys_info[sysinfo_k] = jsond.get(conda_k, 'N/A') + + # Get info about packages in current environment + cmd = ('conda', 'list') + try: + conda_out = check_output(cmd) + except CalledProcessError as e: + _error_log.append(f'Error (conda): {e}') + else: + data = conda_out.decode().splitlines() + sys_info[_inst_pkg] = [l for l in data if not l.startswith('#')] + + sys_info.update(get_os_spec_info(sys_info[_os_name])) + sys_info[_errors] = _error_log + sys_info[_warnings] = _warning_log + sys_info[_runtime] = (datetime.now() - sys_info[_start]).total_seconds() + return sys_info + + +def display_sysinfo(info=None, sep_pos=45): + class DisplayMap(dict): + display_map_flag = True + + class DisplaySeq(tuple): + display_seq_flag = True + + class DisplaySeqMaps(tuple): + display_seqmaps_flag = True + + if info is None: + info = get_sysinfo() + + fmt = f'%-{sep_pos}s : %-s' + MB = 1024**2 + template = ( + ("-" * 80,), + ("__Time Stamp__",), + ("Report started (local time)", info.get(_start, '?')), + ("UTC start time", info.get(_start_utc, '?')), + ("Running time (s)", info.get(_runtime, '?')), + ("",), + ("__Hardware Information__",), + ("Machine", info.get(_machine, '?')), + ("CPU Name", info.get(_cpu_name, '?')), + ("CPU Count", info.get(_cpu_count, '?')), + ("Number of accessible CPUs", info.get(_cpus_allowed, '?')), + ("List of accessible CPUs cores", info.get(_cpus_list, '?')), + ("CFS Restrictions (CPUs worth of runtime)", + info.get(_cfs_restrict, 'None')), + ("",), + ("CPU Features", '\n'.join( + ' ' * (sep_pos + 3) + l if i else l + for i, l in enumerate( + textwrap.wrap( + info.get(_cpu_features, '?'), + width=79 - sep_pos + ) + ) + )), + ("",), + ("Memory Total (MB)", info.get(_mem_total, 0) // MB or '?'), + ("Memory Available (MB)" + if info.get(_os_name, '') != 'Darwin' or info.get(_psutil, False) + else "Free Memory (MB)", info.get(_mem_available, 0) // MB or '?'), + ("",), + ("__OS Information__",), + ("Platform Name", info.get(_platform_name, '?')), + ("Platform Release", info.get(_platform_release, '?')), + ("OS Name", info.get(_os_name, '?')), + ("OS Version", info.get(_os_version, '?')), + ("OS Specific Version", info.get(_os_spec_version, '?')), + ("Libc Version", info.get(_libc_version, '?')), + ("",), + ("__Python Information__",), + DisplayMap({k: v for k, v in info.items() if k.startswith('Python')}), + ("",), + ("__Numba Toolchain Versions__",), + ("Numba Version", info.get(_numba_version, '?')), + ("llvmlite Version", info.get(_llvmlite_version, '?')), + ("",), + ("__LLVM Information__",), + ("LLVM Version", info.get(_llvm_version, '?')), + ("",), + ("__CUDA Information__",), + ("CUDA Target Implementation", info.get(_cu_target_impl, '?')), + ("CUDA Device Initialized", info.get(_cu_dev_init, '?')), + ("CUDA Driver Version", info.get(_cu_drv_ver, '?')), + ("CUDA Runtime Version", info.get(_cu_rt_ver, '?')), + ("CUDA NVIDIA Bindings Available", info.get(_cu_nvidia_bindings, '?')), + ("CUDA NVIDIA Bindings In Use", + info.get(_cu_nvidia_bindings_used, '?')), + ("CUDA Minor Version Compatibility Available", + info.get(_cu_mvc_available, '?')), + ("CUDA Minor Version Compatibility Needed", + info.get(_cu_mvc_needed, '?')), + ("CUDA Minor Version Compatibility In Use", + info.get(_cu_mvc_in_use, '?')), + ("CUDA Detect Output:",), + (info.get(_cu_detect_out, "None"),), + ("CUDA Libraries Test Output:",), + (info.get(_cu_lib_test, "None"),), + ("",), + ("__NumPy Information__",), + ("NumPy Version", info.get(_numpy_version, '?')), + ("NumPy Supported SIMD features", + DisplaySeq(info.get(_numpy_supported_simd_features, []) + or ('None found.',))), + ("NumPy Supported SIMD dispatch", + DisplaySeq(info.get(_numpy_supported_simd_dispatch, []) + or ('None found.',))), + ("NumPy Supported SIMD baseline", + DisplaySeq(info.get(_numpy_supported_simd_baseline, []) + or ('None found.',))), + ("NumPy AVX512_SKX support detected", + info.get(_numpy_AVX512_SKX_detected, '?')), + ("",), + ("__SVML Information__",), + ("SVML State, config.USING_SVML", info.get(_svml_state, '?')), + ("SVML Library Loaded", info.get(_svml_loaded, '?')), + ("llvmlite Using SVML Patched LLVM", info.get(_llvm_svml_patched, '?')), + ("SVML Operational", info.get(_svml_operational, '?')), + ("",), + ("__Threading Layer Information__",), + ("TBB Threading Layer Available", info.get(_tbb_thread, '?')), + ("+-->TBB imported successfully." if info.get(_tbb_thread, '?') + else f"+--> Disabled due to {info.get(_tbb_error, '?')}",), + ("OpenMP Threading Layer Available", info.get(_openmp_thread, '?')), + (f"+-->Vendor: {info.get(_openmp_vendor, '?')}" + if info.get(_openmp_thread, False) + else f"+--> Disabled due to {info.get(_openmp_error, '?')}",), + ("Workqueue Threading Layer Available", info.get(_wkq_thread, '?')), + ("+-->Workqueue imported successfully." if info.get(_wkq_thread, False) + else f"+--> Disabled due to {info.get(_wkq_error, '?')}",), + ("",), + ("__Numba Environment Variable Information__",), + (DisplayMap(info.get(_numba_env_vars, {})) or ('None found.',)), + ("",), + ("__Conda Information__",), + (DisplayMap({k: v for k, v in info.items() + if k.startswith('Conda')}) or ("Conda not available.",)), + ("",), + ("__Installed Packages__",), + DisplaySeq(info.get(_inst_pkg, ("Couldn't retrieve packages info.",))), + ("",), + ("__Error log__" if info.get(_errors, []) + else "No errors reported.",), + DisplaySeq(info.get(_errors, [])), + ("",), + ("__Warning log__" if info.get(_warnings, []) + else "No warnings reported.",), + DisplaySeq(info.get(_warnings, [])), + ("-" * 80,), + ("If requested, please copy and paste the information between\n" + "the dashed (----) lines, or from a given specific section as\n" + "appropriate.\n\n" + "=============================================================\n" + "IMPORTANT: Please ensure that you are happy with sharing the\n" + "contents of the information present, any information that you\n" + "wish to keep private you should remove before sharing.\n" + "=============================================================\n",), + ) + for t in template: + if hasattr(t, 'display_seq_flag'): + print(*t, sep='\n') + elif hasattr(t, 'display_map_flag'): + print(*tuple(fmt % (k, v) for (k, v) in t.items()), sep='\n') + elif hasattr(t, 'display_seqmaps_flag'): + for d in t: + print(*tuple(fmt % ('\t' + k, v) for (k, v) in d.items()), + sep='\n', end='\n') + elif len(t) == 2: + print(fmt % t) + else: + print(*t) + + +if __name__ == '__main__': + display_sysinfo() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/quicksort.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/quicksort.py new file mode 100644 index 0000000000000000000000000000000000000000..788726fa8b775946d3fb1fab37408641c4a8f404 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/quicksort.py @@ -0,0 +1,258 @@ +import collections + +import numpy as np + +from numba.core import types, config + + +QuicksortImplementation = collections.namedtuple( + 'QuicksortImplementation', + (# The compile function itself + 'compile', + # All subroutines exercised by test_sort + 'partition', 'partition3', 'insertion_sort', + # The top-level function + 'run_quicksort', + )) + + +Partition = collections.namedtuple('Partition', ('start', 'stop')) + +# Under this size, switch to a simple insertion sort +SMALL_QUICKSORT = 15 + +MAX_STACK = 100 + + +def make_quicksort_impl(wrap, lt=None, is_argsort=False, is_list=False, is_np_array=False): + + intp = types.intp + zero = intp(0) + + # Two subroutines to make the core algorithm generic wrt. argsort + # or normal sorting. Note the genericity may make basic sort() + # slightly slower (~5%) + if is_argsort: + if is_list: + @wrap + def make_res(A): + return [x for x in range(len(A))] + else: + @wrap + def make_res(A): + return np.arange(A.size) + + @wrap + def GET(A, idx_or_val): + return A[idx_or_val] + + else: + @wrap + def make_res(A): + return A + + @wrap + def GET(A, idx_or_val): + return idx_or_val + + def default_lt(a, b): + """ + Trivial comparison function between two keys. + """ + return a < b + + LT = wrap(lt if lt is not None else default_lt) + + @wrap + def insertion_sort(A, R, low, high): + """ + Insertion sort A[low:high + 1]. Note the inclusive bounds. + """ + assert low >= 0 + if high <= low: + return + + for i in range(low + 1, high + 1): + k = R[i] + v = GET(A, k) + # Insert v into A[low:i] + j = i + while j > low and LT(v, GET(A, R[j - 1])): + # Make place for moving A[i] downwards + R[j] = R[j - 1] + j -= 1 + R[j] = k + + @wrap + def partition(A, R, low, high): + """ + Partition A[low:high + 1] around a chosen pivot. The pivot's index + is returned. + """ + assert low >= 0 + assert high > low + + mid = (low + high) >> 1 + # NOTE: the pattern of swaps below for the pivot choice and the + # partitioning gives good results (i.e. regular O(n log n)) + # on sorted, reverse-sorted, and uniform arrays. Subtle changes + # risk breaking this property. + + # median of three {low, middle, high} + if LT(GET(A, R[mid]), GET(A, R[low])): + R[low], R[mid] = R[mid], R[low] + if LT(GET(A, R[high]), GET(A, R[mid])): + R[high], R[mid] = R[mid], R[high] + if LT(GET(A, R[mid]), GET(A, R[low])): + R[low], R[mid] = R[mid], R[low] + pivot = GET(A, R[mid]) + + # Temporarily stash the pivot at the end + R[high], R[mid] = R[mid], R[high] + i = low + j = high - 1 + while True: + while i < high and LT(GET(A, R[i]), pivot): + i += 1 + while j >= low and LT(pivot, GET(A, R[j])): + j -= 1 + if i >= j: + break + R[i], R[j] = R[j], R[i] + i += 1 + j -= 1 + # Put the pivot back in its final place (all items before `i` + # are smaller than the pivot, all items at/after `i` are larger) + R[i], R[high] = R[high], R[i] + return i + + @wrap + def partition3(A, low, high): + """ + Three-way partition [low, high) around a chosen pivot. + A tuple (lt, gt) is returned such that: + - all elements in [low, lt) are < pivot + - all elements in [lt, gt] are == pivot + - all elements in (gt, high] are > pivot + """ + mid = (low + high) >> 1 + # median of three {low, middle, high} + if LT(A[mid], A[low]): + A[low], A[mid] = A[mid], A[low] + if LT(A[high], A[mid]): + A[high], A[mid] = A[mid], A[high] + if LT(A[mid], A[low]): + A[low], A[mid] = A[mid], A[low] + pivot = A[mid] + + A[low], A[mid] = A[mid], A[low] + lt = low + gt = high + i = low + 1 + while i <= gt: + if LT(A[i], pivot): + A[lt], A[i] = A[i], A[lt] + lt += 1 + i += 1 + elif LT(pivot, A[i]): + A[gt], A[i] = A[i], A[gt] + gt -= 1 + else: + i += 1 + return lt, gt + + @wrap + def run_quicksort1(A): + R = make_res(A) + + if len(A) < 2: + return R + + stack = [Partition(zero, zero)] * MAX_STACK + stack[0] = Partition(zero, len(A) - 1) + n = 1 + + while n > 0: + n -= 1 + low, high = stack[n] + # Partition until it becomes more efficient to do an insertion sort + while high - low >= SMALL_QUICKSORT: + assert n < MAX_STACK + i = partition(A, R, low, high) + # Push largest partition on the stack + if high - i > i - low: + # Right is larger + if high > i: + stack[n] = Partition(i + 1, high) + n += 1 + high = i - 1 + else: + if i > low: + stack[n] = Partition(low, i - 1) + n += 1 + low = i + 1 + + insertion_sort(A, R, low, high) + + return R + + if is_np_array: + @wrap + def run_quicksort(A): + if A.ndim == 1: + return run_quicksort1(A) + else: + for idx in np.ndindex(A.shape[:-1]): + run_quicksort1(A[idx]) + return A + else: + @wrap + def run_quicksort(A): + return run_quicksort1(A) + + # Unused quicksort implementation based on 3-way partitioning; the + # partitioning scheme turns out exhibiting bad behaviour on sorted arrays. + @wrap + def _run_quicksort(A): + stack = [Partition(zero, zero)] * 100 + stack[0] = Partition(zero, len(A) - 1) + n = 1 + + while n > 0: + n -= 1 + low, high = stack[n] + # Partition until it becomes more efficient to do an insertion sort + while high - low >= SMALL_QUICKSORT: + assert n < MAX_STACK + l, r = partition3(A, low, high) + # One trivial (empty) partition => iterate on the other + if r == high: + high = l - 1 + elif l == low: + low = r + 1 + # Push largest partition on the stack + elif high - r > l - low: + # Right is larger + stack[n] = Partition(r + 1, high) + n += 1 + high = l - 1 + else: + stack[n] = Partition(low, l - 1) + n += 1 + low = r + 1 + + insertion_sort(A, low, high) + + + return QuicksortImplementation(wrap, + partition, partition3, insertion_sort, + run_quicksort) + + +def make_py_quicksort(*args, **kwargs): + return make_quicksort_impl((lambda f: f), *args, **kwargs) + +def make_jit_quicksort(*args, **kwargs): + from numba.core.extending import register_jitable + return make_quicksort_impl((lambda f: register_jitable(f)), + *args, **kwargs) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/special.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/special.py new file mode 100644 index 0000000000000000000000000000000000000000..36a44cebe74ba00ab82b88150c2cd11b5ae9a25e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/special.py @@ -0,0 +1,104 @@ +import numpy as np + +from numba.core.typing.typeof import typeof +from numba.core.typing.asnumbatype import as_numba_type + + +def pndindex(*args): + """ Provides an n-dimensional parallel iterator that generates index tuples + for each iteration point. Sequentially, pndindex is identical to np.ndindex. + """ + return np.ndindex(*args) + + +class prange(object): + """ Provides a 1D parallel iterator that generates a sequence of integers. + In non-parallel contexts, prange is identical to range. + """ + def __new__(cls, *args): + return range(*args) + + +def _gdb_python_call_gen(func_name, *args): + # generates a call to a function containing a compiled in gdb command, + # this is to make `numba.gdb*` work in the interpreter. + import numba + fn = getattr(numba, func_name) + argstr = ','.join(['"%s"' for _ in args]) % args + defn = """def _gdb_func_injection():\n\t%s(%s)\n + """ % (func_name, argstr) + l = {} + exec(defn, {func_name: fn}, l) + return numba.njit(l['_gdb_func_injection']) + + +def gdb(*args): + """ + Calling this function will invoke gdb and attach it to the current process + at the call site. Arguments are strings in the gdb command language syntax + which will be executed by gdb once initialisation has occurred. + """ + _gdb_python_call_gen('gdb', *args)() + + +def gdb_breakpoint(): + """ + Calling this function will inject a breakpoint at the call site that is + recognised by both `gdb` and `gdb_init`, this is to allow breaking at + multiple points. gdb will stop in the user defined code just after the frame + employed by the breakpoint returns. + """ + _gdb_python_call_gen('gdb_breakpoint')() + + +def gdb_init(*args): + """ + Calling this function will invoke gdb and attach it to the current process + at the call site, then continue executing the process under gdb's control. + Arguments are strings in the gdb command language syntax which will be + executed by gdb once initialisation has occurred. + """ + _gdb_python_call_gen('gdb_init', *args)() + + +def literally(obj): + """Forces Numba to interpret *obj* as an Literal value. + + *obj* must be either a literal or an argument of the caller function, where + the argument must be bound to a literal. The literal requirement + propagates up the call stack. + + This function is intercepted by the compiler to alter the compilation + behavior to wrap the corresponding function parameters as ``Literal``. + It has **no effect** outside of nopython-mode (interpreter, and objectmode). + + The current implementation detects literal arguments in two ways: + + 1. Scans for uses of ``literally`` via a compiler pass. + 2. ``literally`` is overloaded to raise ``numba.errors.ForceLiteralArg`` + to signal the dispatcher to treat the corresponding parameter + differently. This mode is to support indirect use (via a function call). + + The execution semantic of this function is equivalent to an identity + function. + + See :ghfile:`numba/tests/test_literal_dispatch.py` for examples. + """ + return obj + + +def literal_unroll(container): + return container + + +__all__ = [ + 'typeof', + 'as_numba_type', + 'prange', + 'pndindex', + 'gdb', + 'gdb_breakpoint', + 'gdb_init', + 'literally', + 'literal_unroll', +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/timsort.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/timsort.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1560e399ec73fbaad95c2060097a617b9415c7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/misc/timsort.py @@ -0,0 +1,943 @@ +""" +Timsort implementation. Mostly adapted from CPython's listobject.c. + +For more information, see listsort.txt in CPython's source tree. +""" + + +import collections + +from numba.core import types + + +TimsortImplementation = collections.namedtuple( + 'TimsortImplementation', + (# The compile function itself + 'compile', + # All subroutines exercised by test_sort + 'count_run', 'binarysort', 'gallop_left', 'gallop_right', + 'merge_init', 'merge_append', 'merge_pop', + 'merge_compute_minrun', 'merge_lo', 'merge_hi', 'merge_at', + 'merge_force_collapse', 'merge_collapse', + # The top-level functions + 'run_timsort', 'run_timsort_with_values' + )) + + +# The maximum number of entries in a MergeState's pending-runs stack. +# This is enough to sort arrays of size up to about +# 32 * phi ** MAX_MERGE_PENDING +# where phi ~= 1.618. 85 is ridiculously large enough, good for an array +# with 2**64 elements. +# NOTE this implementation doesn't depend on it (the stack is dynamically +# allocated), but it's still good to check as an invariant. +MAX_MERGE_PENDING = 85 + +# When we get into galloping mode, we stay there until both runs win less +# often than MIN_GALLOP consecutive times. See listsort.txt for more info. +MIN_GALLOP = 7 + +# Start size for temp arrays. +MERGESTATE_TEMP_SIZE = 256 + +# A mergestate is a named tuple with the following members: +# - *min_gallop* is an integer controlling when we get into galloping mode +# - *keys* is a temp list for merging keys +# - *values* is a temp list for merging values, if needed +# - *pending* is a stack of pending runs to be merged +# - *n* is the current stack length of *pending* + +MergeState = collections.namedtuple( + 'MergeState', ('min_gallop', 'keys', 'values', 'pending', 'n')) + + +MergeRun = collections.namedtuple('MergeRun', ('start', 'size')) + + +def make_timsort_impl(wrap, make_temp_area): + + make_temp_area = wrap(make_temp_area) + intp = types.intp + zero = intp(0) + + @wrap + def has_values(keys, values): + return values is not keys + + @wrap + def merge_init(keys): + """ + Initialize a MergeState for a non-keyed sort. + """ + temp_size = min(len(keys) // 2 + 1, MERGESTATE_TEMP_SIZE) + temp_keys = make_temp_area(keys, temp_size) + temp_values = temp_keys + pending = [MergeRun(zero, zero)] * MAX_MERGE_PENDING + return MergeState(intp(MIN_GALLOP), temp_keys, temp_values, pending, zero) + + @wrap + def merge_init_with_values(keys, values): + """ + Initialize a MergeState for a keyed sort. + """ + temp_size = min(len(keys) // 2 + 1, MERGESTATE_TEMP_SIZE) + temp_keys = make_temp_area(keys, temp_size) + temp_values = make_temp_area(values, temp_size) + pending = [MergeRun(zero, zero)] * MAX_MERGE_PENDING + return MergeState(intp(MIN_GALLOP), temp_keys, temp_values, pending, zero) + + @wrap + def merge_append(ms, run): + """ + Append a run on the merge stack. + """ + n = ms.n + assert n < MAX_MERGE_PENDING + ms.pending[n] = run + return MergeState(ms.min_gallop, ms.keys, ms.values, ms.pending, n + 1) + + @wrap + def merge_pop(ms): + """ + Pop the top run from the merge stack. + """ + return MergeState(ms.min_gallop, ms.keys, ms.values, ms.pending, ms.n - 1) + + @wrap + def merge_getmem(ms, need): + """ + Ensure enough temp memory for 'need' items is available. + """ + alloced = len(ms.keys) + if need <= alloced: + return ms + # Over-allocate + while alloced < need: + alloced = alloced << 1 + # Don't realloc! That can cost cycles to copy the old data, but + # we don't care what's in the block. + temp_keys = make_temp_area(ms.keys, alloced) + if has_values(ms.keys, ms.values): + temp_values = make_temp_area(ms.values, alloced) + else: + temp_values = temp_keys + return MergeState(ms.min_gallop, temp_keys, temp_values, ms.pending, ms.n) + + @wrap + def merge_adjust_gallop(ms, new_gallop): + """ + Modify the MergeState's min_gallop. + """ + return MergeState(intp(new_gallop), ms.keys, ms.values, ms.pending, ms.n) + + + @wrap + def LT(a, b): + """ + Trivial comparison function between two keys. This is factored out to + make it clear where comparisons occur. + """ + return a < b + + @wrap + def binarysort(keys, values, lo, hi, start): + """ + binarysort is the best method for sorting small arrays: it does + few compares, but can do data movement quadratic in the number of + elements. + [lo, hi) is a contiguous slice of a list, and is sorted via + binary insertion. This sort is stable. + On entry, must have lo <= start <= hi, and that [lo, start) is already + sorted (pass start == lo if you don't know!). + """ + assert lo <= start and start <= hi + _has_values = has_values(keys, values) + if lo == start: + start += 1 + while start < hi: + pivot = keys[start] + # Bisect to find where to insert `pivot` + # NOTE: bisection only wins over linear search if the comparison + # function is much more expensive than simply moving data. + l = lo + r = start + # Invariants: + # pivot >= all in [lo, l). + # pivot < all in [r, start). + # The second is vacuously true at the start. + while l < r: + p = l + ((r - l) >> 1) + if LT(pivot, keys[p]): + r = p + else: + l = p+1 + + # The invariants still hold, so pivot >= all in [lo, l) and + # pivot < all in [l, start), so pivot belongs at l. Note + # that if there are elements equal to pivot, l points to the + # first slot after them -- that's why this sort is stable. + # Slide over to make room (aka memmove()). + for p in range(start, l, -1): + keys[p] = keys[p - 1] + keys[l] = pivot + if _has_values: + pivot_val = values[start] + for p in range(start, l, -1): + values[p] = values[p - 1] + values[l] = pivot_val + + start += 1 + + + @wrap + def count_run(keys, lo, hi): + """ + Return the length of the run beginning at lo, in the slice [lo, hi). + lo < hi is required on entry. "A run" is the longest ascending sequence, with + + lo[0] <= lo[1] <= lo[2] <= ... + + or the longest descending sequence, with + + lo[0] > lo[1] > lo[2] > ... + + A tuple (length, descending) is returned, where boolean *descending* + is set to 0 in the former case, or to 1 in the latter. + For its intended use in a stable mergesort, the strictness of the defn of + "descending" is needed so that the caller can safely reverse a descending + sequence without violating stability (strict > ensures there are no equal + elements to get out of order). + """ + assert lo < hi + if lo + 1 == hi: + # Trivial 1-long run + return 1, False + if LT(keys[lo + 1], keys[lo]): + # Descending run + for k in range(lo + 2, hi): + if not LT(keys[k], keys[k - 1]): + return k - lo, True + return hi - lo, True + else: + # Ascending run + for k in range(lo + 2, hi): + if LT(keys[k], keys[k - 1]): + return k - lo, False + return hi - lo, False + + + @wrap + def gallop_left(key, a, start, stop, hint): + """ + Locate the proper position of key in a sorted vector; if the vector contains + an element equal to key, return the position immediately to the left of + the leftmost equal element. [gallop_right() does the same except returns + the position to the right of the rightmost equal element (if any).] + + "a" is a sorted vector with stop elements, starting at a[start]. + stop must be > start. + + "hint" is an index at which to begin the search, start <= hint < stop. + The closer hint is to the final result, the faster this runs. + + The return value is the int k in start..stop such that + + a[k-1] < key <= a[k] + + pretending that a[start-1] is minus infinity and a[stop] is plus infinity. + IOW, key belongs at index k; or, IOW, the first k elements of a should + precede key, and the last stop-start-k should follow key. + + See listsort.txt for info on the method. + """ + assert stop > start + assert hint >= start and hint < stop + n = stop - start + + # First, gallop from the hint to find a "good" subinterval for bisecting + lastofs = 0 + ofs = 1 + if LT(a[hint], key): + # a[hint] < key => gallop right, until + # a[hint + lastofs] < key <= a[hint + ofs] + maxofs = stop - hint + while ofs < maxofs: + if LT(a[hint + ofs], key): + lastofs = ofs + ofs = (ofs << 1) + 1 + if ofs <= 0: + # Int overflow + ofs = maxofs + else: + # key <= a[hint + ofs] + break + if ofs > maxofs: + ofs = maxofs + # Translate back to offsets relative to a[0] + lastofs += hint + ofs += hint + else: + # key <= a[hint] => gallop left, until + # a[hint - ofs] < key <= a[hint - lastofs] + maxofs = hint - start + 1 + while ofs < maxofs: + if LT(a[hint - ofs], key): + break + else: + # key <= a[hint - ofs] + lastofs = ofs + ofs = (ofs << 1) + 1 + if ofs <= 0: + # Int overflow + ofs = maxofs + if ofs > maxofs: + ofs = maxofs + # Translate back to positive offsets relative to a[0] + lastofs, ofs = hint - ofs, hint - lastofs + + assert start - 1 <= lastofs and lastofs < ofs and ofs <= stop + # Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the + # right of lastofs but no farther right than ofs. Do a binary + # search, with invariant a[lastofs-1] < key <= a[ofs]. + lastofs += 1 + while lastofs < ofs: + m = lastofs + ((ofs - lastofs) >> 1) + if LT(a[m], key): + # a[m] < key + lastofs = m + 1 + else: + # key <= a[m] + ofs = m + # Now lastofs == ofs, so a[ofs - 1] < key <= a[ofs] + return ofs + + + @wrap + def gallop_right(key, a, start, stop, hint): + """ + Exactly like gallop_left(), except that if key already exists in a[start:stop], + finds the position immediately to the right of the rightmost equal value. + + The return value is the int k in start..stop such that + + a[k-1] <= key < a[k] + + The code duplication is massive, but this is enough different given that + we're sticking to "<" comparisons that it's much harder to follow if + written as one routine with yet another "left or right?" flag. + """ + assert stop > start + assert hint >= start and hint < stop + n = stop - start + + # First, gallop from the hint to find a "good" subinterval for bisecting + lastofs = 0 + ofs = 1 + if LT(key, a[hint]): + # key < a[hint] => gallop left, until + # a[hint - ofs] <= key < a[hint - lastofs] + maxofs = hint - start + 1 + while ofs < maxofs: + if LT(key, a[hint - ofs]): + lastofs = ofs + ofs = (ofs << 1) + 1 + if ofs <= 0: + # Int overflow + ofs = maxofs + else: + # a[hint - ofs] <= key + break + if ofs > maxofs: + ofs = maxofs + # Translate back to positive offsets relative to a[0] + lastofs, ofs = hint - ofs, hint - lastofs + else: + # a[hint] <= key -- gallop right, until + # a[hint + lastofs] <= key < a[hint + ofs] + maxofs = stop - hint + while ofs < maxofs: + if LT(key, a[hint + ofs]): + break + else: + # a[hint + ofs] <= key + lastofs = ofs + ofs = (ofs << 1) + 1 + if ofs <= 0: + # Int overflow + ofs = maxofs + if ofs > maxofs: + ofs = maxofs + # Translate back to offsets relative to a[0] + lastofs += hint + ofs += hint + + assert start - 1 <= lastofs and lastofs < ofs and ofs <= stop + # Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the + # right of lastofs but no farther right than ofs. Do a binary + # search, with invariant a[lastofs-1] <= key < a[ofs]. + lastofs += 1 + while lastofs < ofs: + m = lastofs + ((ofs - lastofs) >> 1) + if LT(key, a[m]): + # key < a[m] + ofs = m + else: + # a[m] <= key + lastofs = m + 1 + # Now lastofs == ofs, so a[ofs - 1] <= key < a[ofs] + return ofs + + + @wrap + def merge_compute_minrun(n): + """ + Compute a good value for the minimum run length; natural runs shorter + than this are boosted artificially via binary insertion. + + If n < 64, return n (it's too small to bother with fancy stuff). + Else if n is an exact power of 2, return 32. + Else return an int k, 32 <= k <= 64, such that n/k is close to, but + strictly less than, an exact power of 2. + + See listsort.txt for more info. + """ + r = 0 + assert n >= 0 + while n >= 64: + r |= n & 1 + n >>= 1 + return n + r + + + @wrap + def sortslice_copy(dest_keys, dest_values, dest_start, + src_keys, src_values, src_start, + nitems): + """ + Upwards memcpy(). + """ + assert src_start >= 0 + assert dest_start >= 0 + for i in range(nitems): + dest_keys[dest_start + i] = src_keys[src_start + i] + if has_values(src_keys, src_values): + for i in range(nitems): + dest_values[dest_start + i] = src_values[src_start + i] + + @wrap + def sortslice_copy_down(dest_keys, dest_values, dest_start, + src_keys, src_values, src_start, + nitems): + """ + Downwards memcpy(). + """ + assert src_start >= 0 + assert dest_start >= 0 + for i in range(nitems): + dest_keys[dest_start - i] = src_keys[src_start - i] + if has_values(src_keys, src_values): + for i in range(nitems): + dest_values[dest_start - i] = src_values[src_start - i] + + + # Disable this for debug or perf comparison + DO_GALLOP = 1 + + @wrap + def merge_lo(ms, keys, values, ssa, na, ssb, nb): + """ + Merge the na elements starting at ssa with the nb elements starting at + ssb = ssa + na in a stable way, in-place. na and nb must be > 0, + and should have na <= nb. See listsort.txt for more info. + + An updated MergeState is returned (with possibly a different min_gallop + or larger temp arrays). + + NOTE: compared to CPython's timsort, the requirement that + "Must also have that keys[ssa + na - 1] belongs at the end of the merge" + + is removed. This makes the code a bit simpler and easier to reason about. + """ + assert na > 0 and nb > 0 and na <= nb + assert ssb == ssa + na + # First copy [ssa, ssa + na) into the temp space + ms = merge_getmem(ms, na) + sortslice_copy(ms.keys, ms.values, 0, + keys, values, ssa, + na) + a_keys = ms.keys + a_values = ms.values + b_keys = keys + b_values = values + dest = ssa + ssa = 0 + + _has_values = has_values(a_keys, a_values) + min_gallop = ms.min_gallop + + # Now start merging into the space left from [ssa, ...) + + while nb > 0 and na > 0: + # Do the straightforward thing until (if ever) one run + # appears to win consistently. + acount = 0 + bcount = 0 + + while True: + if LT(b_keys[ssb], a_keys[ssa]): + keys[dest] = b_keys[ssb] + if _has_values: + values[dest] = b_values[ssb] + dest += 1 + ssb += 1 + nb -= 1 + if nb == 0: + break + # It's a B run + bcount += 1 + acount = 0 + if bcount >= min_gallop: + break + else: + keys[dest] = a_keys[ssa] + if _has_values: + values[dest] = a_values[ssa] + dest += 1 + ssa += 1 + na -= 1 + if na == 0: + break + # It's a A run + acount += 1 + bcount = 0 + if acount >= min_gallop: + break + + # One run is winning so consistently that galloping may + # be a huge win. So try that, and continue galloping until + # (if ever) neither run appears to be winning consistently + # anymore. + if DO_GALLOP and na > 0 and nb > 0: + min_gallop += 1 + + while acount >= MIN_GALLOP or bcount >= MIN_GALLOP: + # As long as we gallop without leaving this loop, make + # the heuristic more likely + min_gallop -= min_gallop > 1 + + # Gallop in A to find where keys[ssb] should end up + k = gallop_right(b_keys[ssb], a_keys, ssa, ssa + na, ssa) + # k is an index, make it a size + k -= ssa + acount = k + if k > 0: + # Copy everything from A before k + sortslice_copy(keys, values, dest, + a_keys, a_values, ssa, + k) + dest += k + ssa += k + na -= k + if na == 0: + # Finished merging + break + # Copy keys[ssb] + keys[dest] = b_keys[ssb] + if _has_values: + values[dest] = b_values[ssb] + dest += 1 + ssb += 1 + nb -= 1 + if nb == 0: + # Finished merging + break + + # Gallop in B to find where keys[ssa] should end up + k = gallop_left(a_keys[ssa], b_keys, ssb, ssb + nb, ssb) + # k is an index, make it a size + k -= ssb + bcount = k + if k > 0: + # Copy everything from B before k + # NOTE: source and dest are the same buffer, but the + # destination index is below the source index + sortslice_copy(keys, values, dest, + b_keys, b_values, ssb, + k) + dest += k + ssb += k + nb -= k + if nb == 0: + # Finished merging + break + # Copy keys[ssa] + keys[dest] = a_keys[ssa] + if _has_values: + values[dest] = a_values[ssa] + dest += 1 + ssa += 1 + na -= 1 + if na == 0: + # Finished merging + break + + # Penalize it for leaving galloping mode + min_gallop += 1 + + # Merge finished, now handle the remaining areas + if nb == 0: + # Only A remaining to copy at the end of the destination area + sortslice_copy(keys, values, dest, + a_keys, a_values, ssa, + na) + else: + assert na == 0 + assert dest == ssb + # B's tail is already at the right place, do nothing + + return merge_adjust_gallop(ms, min_gallop) + + + @wrap + def merge_hi(ms, keys, values, ssa, na, ssb, nb): + """ + Merge the na elements starting at ssa with the nb elements starting at + ssb = ssa + na in a stable way, in-place. na and nb must be > 0, + and should have na >= nb. See listsort.txt for more info. + + An updated MergeState is returned (with possibly a different min_gallop + or larger temp arrays). + + NOTE: compared to CPython's timsort, the requirement that + "Must also have that keys[ssa + na - 1] belongs at the end of the merge" + + is removed. This makes the code a bit simpler and easier to reason about. + """ + assert na > 0 and nb > 0 and na >= nb + assert ssb == ssa + na + # First copy [ssb, ssb + nb) into the temp space + ms = merge_getmem(ms, nb) + sortslice_copy(ms.keys, ms.values, 0, + keys, values, ssb, + nb) + a_keys = keys + a_values = values + b_keys = ms.keys + b_values = ms.values + + # Now start merging *in descending order* into the space left + # from [..., ssb + nb). + dest = ssb + nb - 1 + ssb = nb - 1 + ssa = ssa + na - 1 + + _has_values = has_values(b_keys, b_values) + min_gallop = ms.min_gallop + + while nb > 0 and na > 0: + # Do the straightforward thing until (if ever) one run + # appears to win consistently. + acount = 0 + bcount = 0 + + while True: + if LT(b_keys[ssb], a_keys[ssa]): + # We merge in descending order, so copy the larger value + keys[dest] = a_keys[ssa] + if _has_values: + values[dest] = a_values[ssa] + dest -= 1 + ssa -= 1 + na -= 1 + if na == 0: + break + # It's a A run + acount += 1 + bcount = 0 + if acount >= min_gallop: + break + else: + keys[dest] = b_keys[ssb] + if _has_values: + values[dest] = b_values[ssb] + dest -= 1 + ssb -= 1 + nb -= 1 + if nb == 0: + break + # It's a B run + bcount += 1 + acount = 0 + if bcount >= min_gallop: + break + + # One run is winning so consistently that galloping may + # be a huge win. So try that, and continue galloping until + # (if ever) neither run appears to be winning consistently + # anymore. + if DO_GALLOP and na > 0 and nb > 0: + min_gallop += 1 + + while acount >= MIN_GALLOP or bcount >= MIN_GALLOP: + # As long as we gallop without leaving this loop, make + # the heuristic more likely + min_gallop -= min_gallop > 1 + + # Gallop in A to find where keys[ssb] should end up + k = gallop_right(b_keys[ssb], a_keys, ssa - na + 1, ssa + 1, ssa) + # k is an index, make it a size from the end + k = ssa + 1 - k + acount = k + if k > 0: + # Copy everything from A after k. + # Destination and source are the same buffer, and destination + # index is greater, so copy from the end to the start. + sortslice_copy_down(keys, values, dest, + a_keys, a_values, ssa, + k) + dest -= k + ssa -= k + na -= k + if na == 0: + # Finished merging + break + # Copy keys[ssb] + keys[dest] = b_keys[ssb] + if _has_values: + values[dest] = b_values[ssb] + dest -= 1 + ssb -= 1 + nb -= 1 + if nb == 0: + # Finished merging + break + + # Gallop in B to find where keys[ssa] should end up + k = gallop_left(a_keys[ssa], b_keys, ssb - nb + 1, ssb + 1, ssb) + # k is an index, make it a size from the end + k = ssb + 1 - k + bcount = k + if k > 0: + # Copy everything from B before k + sortslice_copy_down(keys, values, dest, + b_keys, b_values, ssb, + k) + dest -= k + ssb -= k + nb -= k + if nb == 0: + # Finished merging + break + # Copy keys[ssa] + keys[dest] = a_keys[ssa] + if _has_values: + values[dest] = a_values[ssa] + dest -= 1 + ssa -= 1 + na -= 1 + if na == 0: + # Finished merging + break + + # Penalize it for leaving galloping mode + min_gallop += 1 + + # Merge finished, now handle the remaining areas + if na == 0: + # Only B remaining to copy at the front of the destination area + sortslice_copy(keys, values, dest - nb + 1, + b_keys, b_values, ssb - nb + 1, + nb) + else: + assert nb == 0 + assert dest == ssa + # A's front is already at the right place, do nothing + + return merge_adjust_gallop(ms, min_gallop) + + + @wrap + def merge_at(ms, keys, values, i): + """ + Merge the two runs at stack indices i and i+1. + + An updated MergeState is returned. + """ + n = ms.n + assert n >= 2 + assert i >= 0 + assert i == n - 2 or i == n - 3 + + ssa, na = ms.pending[i] + ssb, nb = ms.pending[i + 1] + assert na > 0 and nb > 0 + assert ssa + na == ssb + + # Record the length of the combined runs; if i is the 3rd-last + # run now, also slide over the last run (which isn't involved + # in this merge). The current run i+1 goes away in any case. + ms.pending[i] = MergeRun(ssa, na + nb) + if i == n - 3: + ms.pending[i + 1] = ms.pending[i + 2] + ms = merge_pop(ms) + + # Where does b start in a? Elements in a before that can be + # ignored (already in place). + k = gallop_right(keys[ssb], keys, ssa, ssa + na, ssa) + # [k, ssa + na) remains to be merged + na -= k - ssa + ssa = k + if na == 0: + return ms + + # Where does a end in b? Elements in b after that can be + # ignored (already in place). + k = gallop_left(keys[ssa + na - 1], keys, ssb, ssb + nb, ssb + nb - 1) + # [ssb, k) remains to be merged + nb = k - ssb + + # Merge what remains of the runs, using a temp array with + # min(na, nb) elements. + if na <= nb: + return merge_lo(ms, keys, values, ssa, na, ssb, nb) + else: + return merge_hi(ms, keys, values, ssa, na, ssb, nb) + + + @wrap + def merge_collapse(ms, keys, values): + """ + Examine the stack of runs waiting to be merged, merging adjacent runs + until the stack invariants are re-established: + + 1. len[-3] > len[-2] + len[-1] + 2. len[-2] > len[-1] + + An updated MergeState is returned. + + See listsort.txt for more info. + """ + while ms.n > 1: + pending = ms.pending + n = ms.n - 2 + if ((n > 0 and pending[n-1].size <= pending[n].size + pending[n+1].size) or + (n > 1 and pending[n-2].size <= pending[n-1].size + pending[n].size)): + if pending[n - 1].size < pending[n + 1].size: + # Merge smaller one first + n -= 1 + ms = merge_at(ms, keys, values, n) + elif pending[n].size < pending[n + 1].size: + ms = merge_at(ms, keys, values, n) + else: + break + return ms + + @wrap + def merge_force_collapse(ms, keys, values): + """ + Regardless of invariants, merge all runs on the stack until only one + remains. This is used at the end of the mergesort. + + An updated MergeState is returned. + """ + while ms.n > 1: + pending = ms.pending + n = ms.n - 2 + if n > 0: + if pending[n - 1].size < pending[n + 1].size: + # Merge the smaller one first + n -= 1 + ms = merge_at(ms, keys, values, n) + return ms + + + @wrap + def reverse_slice(keys, values, start, stop): + """ + Reverse a slice, in-place. + """ + i = start + j = stop - 1 + while i < j: + keys[i], keys[j] = keys[j], keys[i] + i += 1 + j -= 1 + if has_values(keys, values): + i = start + j = stop - 1 + while i < j: + values[i], values[j] = values[j], values[i] + i += 1 + j -= 1 + + + @wrap + def run_timsort_with_mergestate(ms, keys, values): + """ + Run timsort with the mergestate. + """ + nremaining = len(keys) + if nremaining < 2: + return + + # March over the array once, left to right, finding natural runs, + # and extending short natural runs to minrun elements. + minrun = merge_compute_minrun(nremaining) + + lo = zero + while nremaining > 0: + n, desc = count_run(keys, lo, lo + nremaining) + if desc: + # Descending run => reverse + reverse_slice(keys, values, lo, lo + n) + # If short, extend to min(minrun, nremaining) + if n < minrun: + force = min(minrun, nremaining) + binarysort(keys, values, lo, lo + force, lo + n) + n = force + # Push run onto stack, and maybe merge. + ms = merge_append(ms, MergeRun(lo, n)) + ms = merge_collapse(ms, keys, values) + # Advance to find next run. + lo += n + nremaining -= n + + # All initial runs have been discovered, now finish merging. + ms = merge_force_collapse(ms, keys, values) + assert ms.n == 1 + assert ms.pending[0] == (0, len(keys)) + + + @wrap + def run_timsort(keys): + """ + Run timsort over the given keys. + """ + values = keys + run_timsort_with_mergestate(merge_init(keys), keys, values) + + + @wrap + def run_timsort_with_values(keys, values): + """ + Run timsort over the given keys and values. + """ + run_timsort_with_mergestate(merge_init_with_values(keys, values), + keys, values) + + return TimsortImplementation( + wrap, + count_run, binarysort, gallop_left, gallop_right, + merge_init, merge_append, merge_pop, + merge_compute_minrun, merge_lo, merge_hi, merge_at, + merge_force_collapse, merge_collapse, + run_timsort, run_timsort_with_values) + + +def make_py_timsort(*args): + return make_timsort_impl((lambda f: f), *args) + +def make_jit_timsort(*args): + from numba import jit + return make_timsort_impl((lambda f: jit(nopython=True)(f)), + *args) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arraymath.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arraymath.py new file mode 100644 index 0000000000000000000000000000000000000000..4b48346bd09762853f0ea339fe15c7cbe8bbed09 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arraymath.py @@ -0,0 +1,5103 @@ +""" +Implementation of math operations on Array objects. +""" + + +import math +from collections import namedtuple +import operator +import warnings + +import llvmlite.ir +import numpy as np + +from numba.core import types, cgutils +from numba.core.extending import overload, overload_method, register_jitable +from numba.np.numpy_support import (as_dtype, type_can_asarray, type_is_scalar, + numpy_version, is_nonelike, + check_is_integer, lt_floats, lt_complex) +from numba.core.imputils import (lower_builtin, impl_ret_borrowed, + impl_ret_new_ref, impl_ret_untracked) +from numba.np.arrayobj import (make_array, load_item, store_item, + _empty_nd_impl) +from numba.np.linalg import ensure_blas + +from numba.core.extending import intrinsic +from numba.core.errors import (RequireLiteralValue, TypingError, + NumbaValueError, NumbaNotImplementedError, + NumbaTypeError, NumbaDeprecationWarning) +from numba.cpython.unsafe.tuple import tuple_setitem + + +def _check_blas(): + # Checks if a BLAS is available so e.g. dot will work + try: + ensure_blas() + except ImportError: + return False + return True + + +_HAVE_BLAS = _check_blas() + + +@intrinsic +def _create_tuple_result_shape(tyctx, shape_list, shape_tuple): + """ + This routine converts shape list where the axis dimension has already + been popped to a tuple for indexing of the same size. The original shape + tuple is also required because it contains a length field at compile time + whereas the shape list does not. + """ + + # The new tuple's size is one less than the original tuple since axis + # dimension removed. + nd = len(shape_tuple) - 1 + # The return type of this intrinsic is an int tuple of length nd. + tupty = types.UniTuple(types.intp, nd) + # The function signature for this intrinsic. + function_sig = tupty(shape_list, shape_tuple) + + def codegen(cgctx, builder, signature, args): + lltupty = cgctx.get_value_type(tupty) + # Create an empty int tuple. + tup = cgutils.get_null_value(lltupty) + + # Get the shape list from the args and we don't need shape tuple. + [in_shape, _] = args + + def array_indexer(a, i): + return a[i] + + # loop to fill the tuple + for i in range(nd): + dataidx = cgctx.get_constant(types.intp, i) + # compile and call array_indexer + data = cgctx.compile_internal(builder, array_indexer, + types.intp(shape_list, types.intp), + [in_shape, dataidx]) + tup = builder.insert_value(tup, data, i) + return tup + + return function_sig, codegen + + +@intrinsic +def _gen_index_tuple(tyctx, shape_tuple, value, axis): + """ + Generates a tuple that can be used to index a specific slice from an + array for sum with axis. shape_tuple is the size of the dimensions of + the input array. 'value' is the value to put in the indexing tuple + in the axis dimension and 'axis' is that dimension. For this to work, + axis has to be a const. + """ + if not isinstance(axis, types.Literal): + raise RequireLiteralValue('axis argument must be a constant') + # Get the value of the axis constant. + axis_value = axis.literal_value + # The length of the indexing tuple to be output. + nd = len(shape_tuple) + + # If the axis value is impossible for the given size array then + # just fake it like it was for axis 0. This will stop compile errors + # when it looks like it could be called from array_sum_axis but really + # can't because that routine checks the axis mismatch and raise an + # exception. + if axis_value >= nd: + axis_value = 0 + + # Calculate the type of the indexing tuple. All the non-axis + # dimensions have slice2 type and the axis dimension has int type. + before = axis_value + after = nd - before - 1 + + types_list = [] + types_list += [types.slice2_type] * before + types_list += [types.intp] + types_list += [types.slice2_type] * after + + # Creates the output type of the function. + tupty = types.Tuple(types_list) + # Defines the signature of the intrinsic. + function_sig = tupty(shape_tuple, value, axis) + + def codegen(cgctx, builder, signature, args): + lltupty = cgctx.get_value_type(tupty) + # Create an empty indexing tuple. + tup = cgutils.get_null_value(lltupty) + + # We only need value of the axis dimension here. + # The rest are constants defined above. + [_, value_arg, _] = args + + def create_full_slice(): + return slice(None, None) + + # loop to fill the tuple with slice(None,None) before + # the axis dimension. + + # compile and call create_full_slice + slice_data = cgctx.compile_internal(builder, create_full_slice, + types.slice2_type(), + []) + for i in range(0, axis_value): + tup = builder.insert_value(tup, slice_data, i) + + # Add the axis dimension 'value'. + tup = builder.insert_value(tup, value_arg, axis_value) + + # loop to fill the tuple with slice(None,None) after + # the axis dimension. + for i in range(axis_value + 1, nd): + tup = builder.insert_value(tup, slice_data, i) + return tup + + return function_sig, codegen + + +#---------------------------------------------------------------------------- +# Basic stats and aggregates + +@lower_builtin(np.sum, types.Array) +@lower_builtin("array.sum", types.Array) +def array_sum(context, builder, sig, args): + zero = sig.return_type(0) + + def array_sum_impl(arr): + c = zero + for v in np.nditer(arr): + c += v.item() + return c + + res = context.compile_internal(builder, array_sum_impl, sig, args, + locals=dict(c=sig.return_type)) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@register_jitable +def _array_sum_axis_nop(arr, v): + return arr + + +def gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero): + def inner(arr, axis): + """ + function that performs sums over one specific axis + + The third parameter to gen_index_tuple that generates the indexing + tuples has to be a const so we can't just pass "axis" through since + that isn't const. We can check for specific values and have + different instances that do take consts. Supporting axis summation + only up to the fourth dimension for now. + + typing/arraydecl.py:sum_expand defines the return type for sum with + axis. It is one dimension less than the input array. + """ + ndim = arr.ndim + + if not is_axis_const: + # Catch where axis is negative or greater than 3. + if axis < 0 or axis > 3: + raise ValueError("Numba does not support sum with axis " + "parameter outside the range 0 to 3.") + + # Catch the case where the user misspecifies the axis to be + # more than the number of the array's dimensions. + if axis >= ndim: + raise ValueError("axis is out of bounds for array") + + # Convert the shape of the input array to a list. + ashape = list(arr.shape) + # Get the length of the axis dimension. + axis_len = ashape[axis] + # Remove the axis dimension from the list of dimensional lengths. + ashape.pop(axis) + # Convert this shape list back to a tuple using above intrinsic. + ashape_without_axis = _create_tuple_result_shape(ashape, arr.shape) + # Tuple needed here to create output array with correct size. + result = np.full(ashape_without_axis, zero, type(zero)) + + # Iterate through the axis dimension. + for axis_index in range(axis_len): + if is_axis_const: + # constant specialized version works for any valid axis value + index_tuple_generic = _gen_index_tuple(arr.shape, axis_index, + const_axis_val) + result += arr[index_tuple_generic] + else: + # Generate a tuple used to index the input array. + # The tuple is ":" in all dimensions except the axis + # dimension where it is "axis_index". + if axis == 0: + index_tuple1 = _gen_index_tuple(arr.shape, axis_index, 0) + result += arr[index_tuple1] + elif axis == 1: + index_tuple2 = _gen_index_tuple(arr.shape, axis_index, 1) + result += arr[index_tuple2] + elif axis == 2: + index_tuple3 = _gen_index_tuple(arr.shape, axis_index, 2) + result += arr[index_tuple3] + elif axis == 3: + index_tuple4 = _gen_index_tuple(arr.shape, axis_index, 3) + result += arr[index_tuple4] + return op(result, 0) + return inner + + +@lower_builtin(np.sum, types.Array, types.intp, types.DTypeSpec) +@lower_builtin(np.sum, types.Array, types.IntegerLiteral, types.DTypeSpec) +@lower_builtin("array.sum", types.Array, types.intp, types.DTypeSpec) +@lower_builtin("array.sum", types.Array, types.IntegerLiteral, types.DTypeSpec) +def array_sum_axis_dtype(context, builder, sig, args): + retty = sig.return_type + zero = getattr(retty, 'dtype', retty)(0) + # if the return is scalar in type then "take" the 0th element of the + # 0d array accumulator as the return value + if getattr(retty, 'ndim', None) is None: + op = np.take + else: + op = _array_sum_axis_nop + [ty_array, ty_axis, ty_dtype] = sig.args + is_axis_const = False + const_axis_val = 0 + if isinstance(ty_axis, types.Literal): + # this special-cases for constant axis + const_axis_val = ty_axis.literal_value + # fix negative axis + if const_axis_val < 0: + const_axis_val = ty_array.ndim + const_axis_val + if const_axis_val < 0 or const_axis_val > ty_array.ndim: + raise ValueError("'axis' entry is out of bounds") + + ty_axis = context.typing_context.resolve_value_type(const_axis_val) + axis_val = context.get_constant(ty_axis, const_axis_val) + # rewrite arguments + args = args[0], axis_val, args[2] + # rewrite sig + sig = sig.replace(args=[ty_array, ty_axis, ty_dtype]) + is_axis_const = True + + gen_impl = gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero) + compiled = register_jitable(gen_impl) + + def array_sum_impl_axis(arr, axis, dtype): + return compiled(arr, axis) + + res = context.compile_internal(builder, array_sum_impl_axis, sig, args) + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +@lower_builtin(np.sum, types.Array, types.DTypeSpec) +@lower_builtin("array.sum", types.Array, types.DTypeSpec) +def array_sum_dtype(context, builder, sig, args): + zero = sig.return_type(0) + + def array_sum_impl(arr, dtype): + c = zero + for v in np.nditer(arr): + c += v.item() + return c + + res = context.compile_internal(builder, array_sum_impl, sig, args, + locals=dict(c=sig.return_type)) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(np.sum, types.Array, types.intp) +@lower_builtin(np.sum, types.Array, types.IntegerLiteral) +@lower_builtin("array.sum", types.Array, types.intp) +@lower_builtin("array.sum", types.Array, types.IntegerLiteral) +def array_sum_axis(context, builder, sig, args): + retty = sig.return_type + zero = getattr(retty, 'dtype', retty)(0) + # if the return is scalar in type then "take" the 0th element of the + # 0d array accumulator as the return value + if getattr(retty, 'ndim', None) is None: + op = np.take + else: + op = _array_sum_axis_nop + [ty_array, ty_axis] = sig.args + is_axis_const = False + const_axis_val = 0 + if isinstance(ty_axis, types.Literal): + # this special-cases for constant axis + const_axis_val = ty_axis.literal_value + # fix negative axis + if const_axis_val < 0: + const_axis_val = ty_array.ndim + const_axis_val + if const_axis_val < 0 or const_axis_val > ty_array.ndim: + msg = f"'axis' entry ({const_axis_val}) is out of bounds" + raise NumbaValueError(msg) + + ty_axis = context.typing_context.resolve_value_type(const_axis_val) + axis_val = context.get_constant(ty_axis, const_axis_val) + # rewrite arguments + args = args[0], axis_val + # rewrite sig + sig = sig.replace(args=[ty_array, ty_axis]) + is_axis_const = True + + gen_impl = gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero) + compiled = register_jitable(gen_impl) + + def array_sum_impl_axis(arr, axis): + return compiled(arr, axis) + + res = context.compile_internal(builder, array_sum_impl_axis, sig, args) + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +def get_accumulator(dtype, value): + if dtype.type == np.timedelta64: + acc_init = np.int64(value).view(dtype) + else: + acc_init = dtype.type(value) + return acc_init + + +@overload(np.prod) +@overload_method(types.Array, "prod") +def array_prod(a): + if isinstance(a, types.Array): + dtype = as_dtype(a.dtype) + + acc_init = get_accumulator(dtype, 1) + + def array_prod_impl(a): + c = acc_init + for v in np.nditer(a): + c *= v.item() + return c + + return array_prod_impl + elif isinstance(a, (types.Number, types.Boolean)): + acc_init = as_dtype(a).type(1) + + def scalar_prod_impl(a): + return acc_init * a + + return scalar_prod_impl + + +@overload(np.cumsum) +@overload_method(types.Array, "cumsum") +def array_cumsum(a): + if isinstance(a, types.Array): + is_integer = a.dtype in types.signed_domain + is_bool = a.dtype == types.bool_ + if (is_integer and a.dtype.bitwidth < types.intp.bitwidth)\ + or is_bool: + dtype = as_dtype(types.intp) + else: + dtype = as_dtype(a.dtype) + + acc_init = get_accumulator(dtype, 0) + + def array_cumsum_impl(a): + out = np.empty(a.size, dtype) + c = acc_init + for idx, v in enumerate(a.flat): + c += v + out[idx] = c + return out + + return array_cumsum_impl + + +@overload(np.cumprod) +@overload_method(types.Array, "cumprod") +def array_cumprod(a): + if isinstance(a, types.Array): + is_integer = a.dtype in types.signed_domain + is_bool = a.dtype == types.bool_ + if (is_integer and a.dtype.bitwidth < types.intp.bitwidth)\ + or is_bool: + dtype = as_dtype(types.intp) + else: + dtype = as_dtype(a.dtype) + + acc_init = get_accumulator(dtype, 1) + + def array_cumprod_impl(a): + out = np.empty(a.size, dtype) + c = acc_init + for idx, v in enumerate(a.flat): + c *= v + out[idx] = c + return out + + return array_cumprod_impl + + +@overload(np.mean) +@overload_method(types.Array, "mean") +def array_mean(a): + if isinstance(a, (types.Integer, types.Boolean)): + # Integers and Booleans default to float64 in numpy.mean + def _scalar_mean(a): + return np.float64(a) + 0.0 + return _scalar_mean + elif isinstance(a, (types.Float, types.Complex)): + typed_zero = as_dtype(a).type(0) + + def _scalar_mean(a): + return a + typed_zero + return _scalar_mean + elif isinstance(a, types.Array): + is_number = a.dtype in types.integer_domain | frozenset([types.bool_]) + if is_number: + dtype = as_dtype(types.float64) + else: + dtype = as_dtype(a.dtype) + + acc_init = get_accumulator(dtype, 0) + + def array_mean_impl(a): + # Can't use the naive `arr.sum() / arr.size`, as it would return + # a wrong result on integer sum overflow. + c = acc_init + for v in np.nditer(a): + c += v.item() + return c / a.size + + return array_mean_impl + return None + + +@overload(np.var) +@overload_method(types.Array, "var") +def array_var(a): + if isinstance(a, types.Array): + def array_var_impl(a): + # Compute the mean + m = a.mean() + + # Compute the sum of square diffs + ssd = 0 + for v in np.nditer(a): + val = (v.item() - m) + ssd += np.real(val * np.conj(val)) + return ssd / a.size + + return array_var_impl + + +@overload(np.std) +@overload_method(types.Array, "std") +def array_std(a): + if isinstance(a, types.Array): + def array_std_impl(a): + return a.var() ** 0.5 + + return array_std_impl + + +@register_jitable +def min_comparator(a, min_val): + return a < min_val + + +@register_jitable +def max_comparator(a, min_val): + return a > min_val + + +@register_jitable +def return_false(a): + return False + + +@overload(np.min) +@overload(np.amin) +@overload_method(types.Array, "min") +def npy_min(a): + #scalar case + if isinstance(a, (types.Number,types.Boolean)): + def scalar_min(a): + return a + return scalar_min + + if not isinstance(a, types.Array): + return + + if isinstance(a.dtype, (types.NPDatetime, types.NPTimedelta)): + pre_return_func = np.isnat + comparator = min_comparator + elif isinstance(a.dtype, types.Complex): + pre_return_func = return_false + + def comp_func(a, min_val): + if a.real < min_val.real: + return True + elif a.real == min_val.real: + if a.imag < min_val.imag: + return True + return False + + comparator = register_jitable(comp_func) + elif isinstance(a.dtype, types.Float): + pre_return_func = np.isnan + comparator = min_comparator + else: + pre_return_func = return_false + comparator = min_comparator + + def impl_min(a): + if a.size == 0: + raise ValueError("zero-size array to reduction operation " + "minimum which has no identity") + + it = np.nditer(a) + min_value = next(it).take(0) + if pre_return_func(min_value): + return min_value + + for view in it: + v = view.item() + if pre_return_func(v): + return v + if comparator(v, min_value): + min_value = v + return min_value + + return impl_min + + +@overload(np.max) +@overload(np.amax) +@overload_method(types.Array, "max") +def npy_max(a): + #scalar case + if isinstance(a, (types.Number,types.Boolean)): + def scalar_max(a): + return a + return scalar_max + + if not isinstance(a, types.Array): + return + + if isinstance(a.dtype, (types.NPDatetime, types.NPTimedelta)): + pre_return_func = np.isnat + comparator = max_comparator + elif isinstance(a.dtype, types.Complex): + pre_return_func = return_false + + def comp_func(a, max_val): + if a.real > max_val.real: + return True + elif a.real == max_val.real: + if a.imag > max_val.imag: + return True + return False + + comparator = register_jitable(comp_func) + elif isinstance(a.dtype, types.Float): + pre_return_func = np.isnan + comparator = max_comparator + else: + pre_return_func = return_false + comparator = max_comparator + + def impl_max(a): + if a.size == 0: + raise ValueError("zero-size array to reduction operation " + "maximum which has no identity") + + it = np.nditer(a) + max_value = next(it).take(0) + if pre_return_func(max_value): + return max_value + + for view in it: + v = view.item() + if pre_return_func(v): + return v + if comparator(v, max_value): + max_value = v + return max_value + + return impl_max + + +@register_jitable +def array_argmin_impl_datetime(arry): + if arry.size == 0: + raise ValueError("attempt to get argmin of an empty sequence") + it = np.nditer(arry) + min_value = next(it).take(0) + min_idx = 0 + if np.isnat(min_value): + return min_idx + + idx = 1 + for view in it: + v = view.item() + if np.isnat(v): + return idx + if v < min_value: + min_value = v + min_idx = idx + idx += 1 + return min_idx + + +@register_jitable +def array_argmin_impl_float(arry): + if arry.size == 0: + raise ValueError("attempt to get argmin of an empty sequence") + for v in arry.flat: + min_value = v + min_idx = 0 + break + if np.isnan(min_value): + return min_idx + + idx = 0 + for v in arry.flat: + if np.isnan(v): + return idx + if v < min_value: + min_value = v + min_idx = idx + idx += 1 + return min_idx + + +@register_jitable +def array_argmin_impl_generic(arry): + if arry.size == 0: + raise ValueError("attempt to get argmin of an empty sequence") + for v in arry.flat: + min_value = v + min_idx = 0 + break + else: + raise RuntimeError('unreachable') + + idx = 0 + for v in arry.flat: + if v < min_value: + min_value = v + min_idx = idx + idx += 1 + return min_idx + + +@overload(np.argmin) +@overload_method(types.Array, "argmin") +def array_argmin(a, axis=None): + if isinstance(a.dtype, (types.NPDatetime, types.NPTimedelta)): + flatten_impl = array_argmin_impl_datetime + elif isinstance(a.dtype, types.Float): + flatten_impl = array_argmin_impl_float + else: + flatten_impl = array_argmin_impl_generic + + if is_nonelike(axis): + def array_argmin_impl(a, axis=None): + return flatten_impl(a) + else: + array_argmin_impl = build_argmax_or_argmin_with_axis_impl( + a, axis, flatten_impl + ) + return array_argmin_impl + + +@register_jitable +def array_argmax_impl_datetime(arry): + if arry.size == 0: + raise ValueError("attempt to get argmax of an empty sequence") + it = np.nditer(arry) + max_value = next(it).take(0) + max_idx = 0 + if np.isnat(max_value): + return max_idx + + idx = 1 + for view in it: + v = view.item() + if np.isnat(v): + return idx + if v > max_value: + max_value = v + max_idx = idx + idx += 1 + return max_idx + + +@register_jitable +def array_argmax_impl_float(arry): + if arry.size == 0: + raise ValueError("attempt to get argmax of an empty sequence") + for v in arry.flat: + max_value = v + max_idx = 0 + break + if np.isnan(max_value): + return max_idx + + idx = 0 + for v in arry.flat: + if np.isnan(v): + return idx + if v > max_value: + max_value = v + max_idx = idx + idx += 1 + return max_idx + + +@register_jitable +def array_argmax_impl_generic(arry): + if arry.size == 0: + raise ValueError("attempt to get argmax of an empty sequence") + for v in arry.flat: + max_value = v + max_idx = 0 + break + + idx = 0 + for v in arry.flat: + if v > max_value: + max_value = v + max_idx = idx + idx += 1 + return max_idx + + +def build_argmax_or_argmin_with_axis_impl(a, axis, flatten_impl): + """ + Given a function that implements the logic for handling a flattened + array, return the implementation function. + """ + check_is_integer(axis, "axis") + retty = types.intp + + tuple_buffer = tuple(range(a.ndim)) + + def impl(a, axis=None): + if axis < 0: + axis = a.ndim + axis + + if axis < 0 or axis >= a.ndim: + raise ValueError("axis is out of bounds") + + # Short circuit 1-dimensional arrays: + if a.ndim == 1: + return flatten_impl(a) + + # Make chosen axis the last axis: + tmp = tuple_buffer + for i in range(axis, a.ndim - 1): + tmp = tuple_setitem(tmp, i, i + 1) + transpose_index = tuple_setitem(tmp, a.ndim - 1, axis) + transposed_arr = a.transpose(transpose_index) + + # Flatten along that axis; since we've transposed, we can just get + # batches off the overall flattened array. + m = transposed_arr.shape[-1] + raveled = transposed_arr.ravel() + assert raveled.size == a.size + assert transposed_arr.size % m == 0 + out = np.empty(transposed_arr.size // m, retty) + for i in range(out.size): + out[i] = flatten_impl(raveled[i * m:(i + 1) * m]) + + # Reshape based on axis we didn't flatten over: + return out.reshape(transposed_arr.shape[:-1]) + + return impl + + +@overload(np.argmax) +@overload_method(types.Array, "argmax") +def array_argmax(a, axis=None): + if isinstance(a.dtype, (types.NPDatetime, types.NPTimedelta)): + flatten_impl = array_argmax_impl_datetime + elif isinstance(a.dtype, types.Float): + flatten_impl = array_argmax_impl_float + else: + flatten_impl = array_argmax_impl_generic + + if is_nonelike(axis): + def array_argmax_impl(a, axis=None): + return flatten_impl(a) + else: + array_argmax_impl = build_argmax_or_argmin_with_axis_impl( + a, axis, flatten_impl + ) + return array_argmax_impl + + +@overload(np.all) +@overload_method(types.Array, "all") +def np_all(a): + + # for scalar + if isinstance(a, (types.Number, types.Boolean)): + def scalar_all(a): + return bool(a) + return scalar_all + + # for array + if isinstance(a, types.Array): + def flat_all(a): + for v in np.nditer(a): + if not v.item(): + return False + return True + return flat_all + + return None + + +@register_jitable +def _allclose_scalars(a_v, b_v, rtol=1e-05, atol=1e-08, equal_nan=False): + a_v_isnan = np.isnan(a_v) + b_v_isnan = np.isnan(b_v) + + # only one of the values is NaN and the + # other is not. + if ( (not a_v_isnan and b_v_isnan) or + (a_v_isnan and not b_v_isnan) ): + return False + + # either both of the values are NaN + # or both are numbers + if a_v_isnan and b_v_isnan: + if not equal_nan: + return False + else: + if np.isinf(a_v) or np.isinf(b_v): + return a_v == b_v + + if np.abs(a_v - b_v) > atol + rtol * np.abs(b_v * 1.0): + return False + + return True + + +@overload(np.allclose) +@overload_method(types.Array, "allclose") +def np_allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + + if not type_can_asarray(a): + raise TypingError('The first argument "a" must be array-like') + + if not type_can_asarray(b): + raise TypingError('The second argument "b" must be array-like') + + if not isinstance(rtol, (float, types.Float)): + raise TypingError('The third argument "rtol" must be a ' + 'floating point') + + if not isinstance(atol, (float, types.Float)): + raise TypingError('The fourth argument "atol" must be a ' + 'floating point') + + if not isinstance(equal_nan, (bool, types.Boolean)): + raise TypingError('The fifth argument "equal_nan" must be a ' + 'boolean') + + is_a_scalar = isinstance(a, types.Number) + is_b_scalar = isinstance(b, types.Number) + + if is_a_scalar and is_b_scalar: + def np_allclose_impl_scalar_scalar(a, b, rtol=1e-05, atol=1e-08, + equal_nan=False): + return _allclose_scalars(a, b, rtol=rtol, atol=atol, + equal_nan=equal_nan) + return np_allclose_impl_scalar_scalar + elif is_a_scalar and not is_b_scalar: + def np_allclose_impl_scalar_array(a, b, rtol=1e-05, atol=1e-08, + equal_nan=False): + b = np.asarray(b) + for bv in np.nditer(b): + if not _allclose_scalars(a, bv.item(), rtol=rtol, atol=atol, + equal_nan=equal_nan): + return False + return True + return np_allclose_impl_scalar_array + elif not is_a_scalar and is_b_scalar: + def np_allclose_impl_array_scalar(a, b, rtol=1e-05, atol=1e-08, + equal_nan=False): + a = np.asarray(a) + for av in np.nditer(a): + if not _allclose_scalars(av.item(), b, rtol=rtol, atol=atol, + equal_nan=equal_nan): + return False + return True + return np_allclose_impl_array_scalar + elif not is_a_scalar and not is_b_scalar: + def np_allclose_impl_array_array(a, b, rtol=1e-05, atol=1e-08, + equal_nan=False): + a = np.asarray(a) + b = np.asarray(b) + a_a, b_b = np.broadcast_arrays(a, b) + + for av, bv in np.nditer((a_a, b_b)): + if not _allclose_scalars(av.item(), bv.item(), rtol=rtol, + atol=atol, equal_nan=equal_nan): + return False + + return True + + return np_allclose_impl_array_array + + +@overload(np.any) +@overload_method(types.Array, "any") +def np_any(a): + # for scalar + if isinstance(a, (types.Number, types.Boolean)): + def scalar_any(a): + return bool(a) + return scalar_any + + # for array + if isinstance(a, types.Array): + def flat_any(a): + for v in np.nditer(a): + if v.item(): + return True + return False + return flat_any + + return None + + +@overload(np.average) +def np_average(a, axis=None, weights=None): + if axis is not None and not isinstance(axis, types.NoneType): + def np_average_impl(a, axis=None, weights=None): + raise TypeError("Numba does not support average with axis.") + else: + if weights is None or isinstance(weights, types.NoneType): + def np_average_impl(a, axis=None, weights=None): + arr = np.asarray(a) + return np.mean(arr) + else: + def np_average_impl(a, axis=None, weights=None): + arr = np.asarray(a) + weights = np.asarray(weights) + + if arr.shape != weights.shape: + if weights.ndim != 1: + raise TypeError( + "1D weights expected when shapes of " + "a and weights differ.") + + scl = np.sum(weights) + if scl == 0.0: + raise ZeroDivisionError( + "Weights sum to zero, can't be normalized.") + + avg = np.sum(np.multiply(arr, weights)) / scl + return avg + + return np_average_impl + + +def get_isnan(dtype): + """ + A generic isnan() function + """ + if isinstance(dtype, (types.Float, types.Complex)): + return np.isnan + else: + @register_jitable + def _trivial_isnan(x): + return False + return _trivial_isnan + + +@overload(np.iscomplex) +def np_iscomplex(x): + if type_can_asarray(x): + # NumPy uses asanyarray here! + return lambda x: np.asarray(x).imag != 0 + return None + + +@overload(np.isreal) +def np_isreal(x): + if type_can_asarray(x): + # NumPy uses asanyarray here! + return lambda x: np.asarray(x).imag == 0 + return None + + +@overload(np.iscomplexobj) +def iscomplexobj(x): + # Implementation based on NumPy + # https://github.com/numpy/numpy/blob/d9b1e32cb8ef90d6b4a47853241db2a28146a57d/numpy/lib/type_check.py#L282-L320 + dt = determine_dtype(x) + if isinstance(x, types.Optional): + dt = determine_dtype(x.type) + iscmplx = np.issubdtype(dt, np.complexfloating) + + if isinstance(x, types.Optional): + def impl(x): + if x is None: + return False + return iscmplx + else: + def impl(x): + return iscmplx + return impl + + +@overload(np.isrealobj) +def isrealobj(x): + # Return True if x is not a complex type. + # Implementation based on NumPy + # https://github.com/numpy/numpy/blob/ccfbcc1cd9a4035a467f2e982a565ab27de25b6b/numpy/lib/type_check.py#L290-L322 + def impl(x): + return not np.iscomplexobj(x) + return impl + + +@overload(np.isscalar) +def np_isscalar(element): + res = type_is_scalar(element) + + def impl(element): + return res + return impl + + +def is_np_inf_impl(x, out, fn): + + # if/else branch should be unified after PR #5606 is merged + if is_nonelike(out): + def impl(x, out=None): + return np.logical_and(np.isinf(x), fn(np.signbit(x))) + else: + def impl(x, out=None): + return np.logical_and(np.isinf(x), fn(np.signbit(x)), out) + + return impl + + +@overload(np.isneginf) +def isneginf(x, out=None): + fn = register_jitable(lambda x: x) + return is_np_inf_impl(x, out, fn) + + +@overload(np.isposinf) +def isposinf(x, out=None): + fn = register_jitable(lambda x: ~x) + return is_np_inf_impl(x, out, fn) + + +@register_jitable +def less_than(a, b): + return a < b + + +@register_jitable +def greater_than(a, b): + return a > b + + +@register_jitable +def check_array(a): + if a.size == 0: + raise ValueError('zero-size array to reduction operation not possible') + + +def nan_min_max_factory(comparison_op, is_complex_dtype): + if is_complex_dtype: + def impl(a): + arr = np.asarray(a) + check_array(arr) + it = np.nditer(arr) + return_val = next(it).take(0) + for view in it: + v = view.item() + if np.isnan(return_val.real) and not np.isnan(v.real): + return_val = v + else: + if comparison_op(v.real, return_val.real): + return_val = v + elif v.real == return_val.real: + if comparison_op(v.imag, return_val.imag): + return_val = v + return return_val + else: + def impl(a): + arr = np.asarray(a) + check_array(arr) + it = np.nditer(arr) + return_val = next(it).take(0) + for view in it: + v = view.item() + if not np.isnan(v): + if not comparison_op(return_val, v): + return_val = v + return return_val + + return impl + + +real_nanmin = register_jitable( + nan_min_max_factory(less_than, is_complex_dtype=False) +) +real_nanmax = register_jitable( + nan_min_max_factory(greater_than, is_complex_dtype=False) +) +complex_nanmin = register_jitable( + nan_min_max_factory(less_than, is_complex_dtype=True) +) +complex_nanmax = register_jitable( + nan_min_max_factory(greater_than, is_complex_dtype=True) +) + + +@register_jitable +def _isclose_item(x, y, rtol, atol, equal_nan): + if np.isnan(x) and np.isnan(y): + return equal_nan + elif np.isinf(x) and np.isinf(y): + return (x > 0) == (y > 0) + elif np.isinf(x) or np.isinf(y): + return False + else: + return abs(x - y) <= atol + rtol * abs(y) + + +@overload(np.isclose) +def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + if not type_can_asarray(a): + raise TypingError('The first argument "a" must be array-like') + + if not type_can_asarray(b): + raise TypingError('The second argument "b" must be array-like') + + if not isinstance(rtol, (float, types.Float)): + raise TypingError('The third argument "rtol" must be a ' + 'floating point') + + if not isinstance(atol, (float, types.Float)): + raise TypingError('The fourth argument "atol" must be a ' + 'floating point') + + if not isinstance(equal_nan, (bool, types.Boolean)): + raise TypingError('The fifth argument "equal_nan" must be a ' + 'boolean') + + if isinstance(a, types.Array) and isinstance(b, types.Number): + def isclose_impl(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + x = a.reshape(-1) + y = b + out = np.zeros(len(x), np.bool_) + for i in range(len(out)): + out[i] = _isclose_item(x[i], y, rtol, atol, equal_nan) + return out.reshape(a.shape) + + elif isinstance(a, types.Number) and isinstance(b, types.Array): + def isclose_impl(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + x = a + y = b.reshape(-1) + out = np.zeros(len(y), np.bool_) + for i in range(len(out)): + out[i] = _isclose_item(x, y[i], rtol, atol, equal_nan) + return out.reshape(b.shape) + + elif isinstance(a, types.Array) and isinstance(b, types.Array): + def isclose_impl(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + shape = np.broadcast_shapes(a.shape, b.shape) + a_ = np.broadcast_to(a, shape) + b_ = np.broadcast_to(b, shape) + + out = np.zeros(len(a_), dtype=np.bool_) + for i, (av, bv) in enumerate(np.nditer((a_, b_))): + out[i] = _isclose_item(av.item(), bv.item(), rtol, atol, + equal_nan) + return np.broadcast_to(out, shape) + + else: + def isclose_impl(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + return _isclose_item(a, b, rtol, atol, equal_nan) + + return isclose_impl + + +@overload(np.nanmin) +def np_nanmin(a): + dt = determine_dtype(a) + if np.issubdtype(dt, np.complexfloating): + return complex_nanmin + else: + return real_nanmin + + +@overload(np.nanmax) +def np_nanmax(a): + dt = determine_dtype(a) + if np.issubdtype(dt, np.complexfloating): + return complex_nanmax + else: + return real_nanmax + + +@overload(np.nanmean) +def np_nanmean(a): + if not isinstance(a, types.Array): + return + isnan = get_isnan(a.dtype) + + def nanmean_impl(a): + c = 0.0 + count = 0 + for view in np.nditer(a): + v = view.item() + if not isnan(v): + c += v.item() + count += 1 + # np.divide() doesn't raise ZeroDivisionError + return np.divide(c, count) + + return nanmean_impl + + +@overload(np.nanvar) +def np_nanvar(a): + if not isinstance(a, types.Array): + return + isnan = get_isnan(a.dtype) + + def nanvar_impl(a): + # Compute the mean + m = np.nanmean(a) + + # Compute the sum of square diffs + ssd = 0.0 + count = 0 + for view in np.nditer(a): + v = view.item() + if not isnan(v): + val = (v.item() - m) + ssd += np.real(val * np.conj(val)) + count += 1 + # np.divide() doesn't raise ZeroDivisionError + return np.divide(ssd, count) + + return nanvar_impl + + +@overload(np.nanstd) +def np_nanstd(a): + if not isinstance(a, types.Array): + return + + def nanstd_impl(a): + return np.nanvar(a) ** 0.5 + + return nanstd_impl + + +@overload(np.nansum) +def np_nansum(a): + if not isinstance(a, types.Array): + return + if isinstance(a.dtype, types.Integer): + retty = types.intp + else: + retty = a.dtype + zero = retty(0) + isnan = get_isnan(a.dtype) + + def nansum_impl(a): + c = zero + for view in np.nditer(a): + v = view.item() + if not isnan(v): + c += v + return c + + return nansum_impl + + +@overload(np.nanprod) +def np_nanprod(a): + if not isinstance(a, types.Array): + return + if isinstance(a.dtype, types.Integer): + retty = types.intp + else: + retty = a.dtype + one = retty(1) + isnan = get_isnan(a.dtype) + + def nanprod_impl(a): + c = one + for view in np.nditer(a): + v = view.item() + if not isnan(v): + c *= v + return c + + return nanprod_impl + + +@overload(np.nancumprod) +def np_nancumprod(a): + if not isinstance(a, types.Array): + return + + if isinstance(a.dtype, (types.Boolean, types.Integer)): + # dtype cannot possibly contain NaN + return lambda a: np.cumprod(a) + else: + retty = a.dtype + is_nan = get_isnan(retty) + one = retty(1) + + def nancumprod_impl(a): + out = np.empty(a.size, retty) + c = one + for idx, v in enumerate(a.flat): + if ~is_nan(v): + c *= v + out[idx] = c + return out + + return nancumprod_impl + + +@overload(np.nancumsum) +def np_nancumsum(a): + if not isinstance(a, types.Array): + return + + if isinstance(a.dtype, (types.Boolean, types.Integer)): + # dtype cannot possibly contain NaN + return lambda a: np.cumsum(a) + else: + retty = a.dtype + is_nan = get_isnan(retty) + zero = retty(0) + + def nancumsum_impl(a): + out = np.empty(a.size, retty) + c = zero + for idx, v in enumerate(a.flat): + if ~is_nan(v): + c += v + out[idx] = c + return out + + return nancumsum_impl + + +@register_jitable +def prepare_ptp_input(a): + arr = _asarray(a) + if len(arr) == 0: + raise ValueError('zero-size array reduction not possible') + else: + return arr + + +def _compute_current_val_impl_gen(op, current_val, val): + if isinstance(current_val, types.Complex): + # The sort order for complex numbers is lexicographic. If both the + # real and imaginary parts are non-nan then the order is determined + # by the real parts except when they are equal, in which case the + # order is determined by the imaginary parts. + # https://github.com/numpy/numpy/blob/577a86e/numpy/core/fromnumeric.py#L874-L877 # noqa: E501 + def impl(current_val, val): + if op(val.real, current_val.real): + return val + elif (val.real == current_val.real + and op(val.imag, current_val.imag)): + return val + return current_val + else: + def impl(current_val, val): + return val if op(val, current_val) else current_val + return impl + + +def _compute_a_max(current_val, val): + pass + + +def _compute_a_min(current_val, val): + pass + + +@overload(_compute_a_max) +def _compute_a_max_impl(current_val, val): + return _compute_current_val_impl_gen(operator.gt, current_val, val) + + +@overload(_compute_a_min) +def _compute_a_min_impl(current_val, val): + return _compute_current_val_impl_gen(operator.lt, current_val, val) + + +def _early_return(val): + pass + + +@overload(_early_return) +def _early_return_impl(val): + UNUSED = 0 + if isinstance(val, types.Complex): + def impl(val): + if np.isnan(val.real): + if np.isnan(val.imag): + return True, np.nan + np.nan * 1j + else: + return True, np.nan + 0j + else: + return False, UNUSED + elif isinstance(val, types.Float): + def impl(val): + if np.isnan(val): + return True, np.nan + else: + return False, UNUSED + else: + def impl(val): + return False, UNUSED + return impl + + +@overload(np.ptp) +def np_ptp(a): + + if hasattr(a, 'dtype'): + if isinstance(a.dtype, types.Boolean): + raise TypingError("Boolean dtype is unsupported (as per NumPy)") + # Numpy raises a TypeError + + def np_ptp_impl(a): + arr = prepare_ptp_input(a) + + a_flat = arr.flat + a_min = a_flat[0] + a_max = a_flat[0] + + for i in range(arr.size): + val = a_flat[i] + take_branch, retval = _early_return(val) + if take_branch: + return retval + a_max = _compute_a_max(a_max, val) + a_min = _compute_a_min(a_min, val) + + return a_max - a_min + + return np_ptp_impl + + +if numpy_version < (2, 0): + overload_method(types.Array, 'ptp')(np_ptp) + +#---------------------------------------------------------------------------- +# Median and partitioning + + +@register_jitable +def nan_aware_less_than(a, b): + if np.isnan(a): + return False + else: + if np.isnan(b): + return True + else: + return a < b + + +def _partition_factory(pivotimpl, argpartition=False): + def _partition(A, low, high, I=None): + mid = (low + high) >> 1 + # NOTE: the pattern of swaps below for the pivot choice and the + # partitioning gives good results (i.e. regular O(n log n)) + # on sorted, reverse-sorted, and uniform arrays. Subtle changes + # risk breaking this property. + + # Use median of three {low, middle, high} as the pivot + if pivotimpl(A[mid], A[low]): + A[low], A[mid] = A[mid], A[low] + if argpartition: + I[low], I[mid] = I[mid], I[low] + if pivotimpl(A[high], A[mid]): + A[high], A[mid] = A[mid], A[high] + if argpartition: + I[high], I[mid] = I[mid], I[high] + if pivotimpl(A[mid], A[low]): + A[low], A[mid] = A[mid], A[low] + if argpartition: + I[low], I[mid] = I[mid], I[low] + pivot = A[mid] + + A[high], A[mid] = A[mid], A[high] + if argpartition: + I[high], I[mid] = I[mid], I[high] + i = low + j = high - 1 + while True: + while i < high and pivotimpl(A[i], pivot): + i += 1 + while j >= low and pivotimpl(pivot, A[j]): + j -= 1 + if i >= j: + break + A[i], A[j] = A[j], A[i] + if argpartition: + I[i], I[j] = I[j], I[i] + i += 1 + j -= 1 + # Put the pivot back in its final place (all items before `i` + # are smaller than the pivot, all items at/after `i` are larger) + A[i], A[high] = A[high], A[i] + if argpartition: + I[i], I[high] = I[high], I[i] + return i + return _partition + + +_partition = register_jitable(_partition_factory(less_than)) +_partition_w_nan = register_jitable(_partition_factory(nan_aware_less_than)) +_argpartition_w_nan = register_jitable(_partition_factory( + nan_aware_less_than, + argpartition=True) +) + + +def _select_factory(partitionimpl): + def _select(arry, k, low, high, idx=None): + """ + Select the k'th smallest element in array[low:high + 1]. + """ + i = partitionimpl(arry, low, high, idx) + while i != k: + if i < k: + low = i + 1 + i = partitionimpl(arry, low, high, idx) + else: + high = i - 1 + i = partitionimpl(arry, low, high, idx) + return arry[k] + return _select + + +_select = register_jitable(_select_factory(_partition)) +_select_w_nan = register_jitable(_select_factory(_partition_w_nan)) +_arg_select_w_nan = register_jitable(_select_factory(_argpartition_w_nan)) + + +@register_jitable +def _select_two(arry, k, low, high): + """ + Select the k'th and k+1'th smallest elements in array[low:high + 1]. + + This is significantly faster than doing two independent selections + for k and k+1. + """ + while True: + assert high > low # by construction + i = _partition(arry, low, high) + if i < k: + low = i + 1 + elif i > k + 1: + high = i - 1 + elif i == k: + _select(arry, k + 1, i + 1, high) + break + else: # i == k + 1 + _select(arry, k, low, i - 1) + break + + return arry[k], arry[k + 1] + + +@register_jitable +def _median_inner(temp_arry, n): + """ + The main logic of the median() call. *temp_arry* must be disposable, + as this function will mutate it. + """ + low = 0 + high = n - 1 + half = n >> 1 + if n & 1 == 0: + a, b = _select_two(temp_arry, half - 1, low, high) + return (a + b) / 2 + else: + return _select(temp_arry, half, low, high) + + +@overload(np.median) +def np_median(a): + if not isinstance(a, types.Array): + return + + is_datetime = as_dtype(a.dtype).char in 'mM' + + def median_impl(a): + # np.median() works on the flattened array, and we need a temporary + # workspace anyway + temp_arry = a.flatten() + n = temp_arry.shape[0] + if not is_datetime and n == 0: + return np.nan + return _median_inner(temp_arry, n) + return median_impl + + +@register_jitable +def _collect_percentiles_inner(a, q): + #TODO: This needs rewriting to be closer to NumPy, particularly the nan/inf + # handling which is generally subject to algorithmic changes. + n = len(a) + + if n == 1: + # single element array; output same for all percentiles + out = np.full(len(q), a[0], dtype=np.float64) + else: + out = np.empty(len(q), dtype=np.float64) + for i in range(len(q)): + percentile = q[i] + + # bypass pivoting where requested percentile is 100 + if percentile == 100: + val = np.max(a) + # heuristics to handle infinite values a la NumPy + if ~np.all(np.isfinite(a)): + if ~np.isfinite(val): + val = np.nan + + # bypass pivoting where requested percentile is 0 + elif percentile == 0: + val = np.min(a) + # convoluted heuristics to handle infinite values a la NumPy + if ~np.all(np.isfinite(a)): + num_pos_inf = np.sum(a == np.inf) + num_neg_inf = np.sum(a == -np.inf) + num_finite = n - (num_neg_inf + num_pos_inf) + if num_finite == 0: + val = np.nan + if num_pos_inf == 1 and n == 2: + val = np.nan + if num_neg_inf > 1: + val = np.nan + if num_finite == 1: + if num_pos_inf > 1: + if num_neg_inf != 1: + val = np.nan + + else: + # linear interp between closest ranks + rank = 1 + (n - 1) * np.true_divide(percentile, 100.0) + f = math.floor(rank) + m = rank - f + lower, upper = _select_two(a, k=int(f - 1), low=0, high=(n - 1)) + val = lower * (1 - m) + upper * m + out[i] = val + + return out + + +@register_jitable +def _can_collect_percentiles(a, nan_mask, skip_nan): + if skip_nan: + a = a[~nan_mask] + if len(a) == 0: + return False # told to skip nan, but no elements remain + else: + if np.any(nan_mask): + return False # told *not* to skip nan, but nan encountered + + if len(a) == 1: # single element array + val = a[0] + return np.isfinite(val) # can collect percentiles if element is finite + else: + return True + + +@register_jitable +def check_valid(q, q_upper_bound): + valid = True + + # avoid expensive reductions where possible + if q.ndim == 1 and q.size < 10: + for i in range(q.size): + if q[i] < 0.0 or q[i] > q_upper_bound or np.isnan(q[i]): + valid = False + break + else: + if np.any(np.isnan(q)) or np.any(q < 0.0) or np.any(q > q_upper_bound): + valid = False + + return valid + + +@register_jitable +def percentile_is_valid(q): + if not check_valid(q, q_upper_bound=100.0): + raise ValueError('Percentiles must be in the range [0, 100]') + + +@register_jitable +def quantile_is_valid(q): + if not check_valid(q, q_upper_bound=1.0): + raise ValueError('Quantiles must be in the range [0, 1]') + + +@register_jitable +def _collect_percentiles(a, q, check_q, factor, skip_nan): + q = np.asarray(q, dtype=np.float64).flatten() + check_q(q) + q = q * factor + + temp_arry = np.asarray(a, dtype=np.float64).flatten() + nan_mask = np.isnan(temp_arry) + + if _can_collect_percentiles(temp_arry, nan_mask, skip_nan): + temp_arry = temp_arry[~nan_mask] + out = _collect_percentiles_inner(temp_arry, q) + else: + out = np.full(len(q), np.nan) + + return out + + +def _percentile_quantile_inner(a, q, skip_nan, factor, check_q): + """ + The underlying algorithm to find percentiles and quantiles + is the same, hence we converge onto the same code paths + in this inner function implementation + """ + dt = determine_dtype(a) + if np.issubdtype(dt, np.complexfloating): + raise TypingError('Not supported for complex dtype') + # this could be supported, but would require a + # lexicographic comparison + + def np_percentile_q_scalar_impl(a, q): + return _collect_percentiles(a, q, check_q, factor, skip_nan)[0] + + def np_percentile_impl(a, q): + return _collect_percentiles(a, q, check_q, factor, skip_nan) + + if isinstance(q, (types.Number, types.Boolean)): + return np_percentile_q_scalar_impl + elif isinstance(q, types.Array) and q.ndim == 0: + return np_percentile_q_scalar_impl + else: + return np_percentile_impl + + +@overload(np.percentile) +def np_percentile(a, q): + return _percentile_quantile_inner( + a, q, skip_nan=False, factor=1.0, check_q=percentile_is_valid + ) + + +@overload(np.nanpercentile) +def np_nanpercentile(a, q): + return _percentile_quantile_inner( + a, q, skip_nan=True, factor=1.0, check_q=percentile_is_valid + ) + + +@overload(np.quantile) +def np_quantile(a, q): + return _percentile_quantile_inner( + a, q, skip_nan=False, factor=100.0, check_q=quantile_is_valid + ) + + +@overload(np.nanquantile) +def np_nanquantile(a, q): + return _percentile_quantile_inner( + a, q, skip_nan=True, factor=100.0, check_q=quantile_is_valid + ) + + +@overload(np.nanmedian) +def np_nanmedian(a): + if not isinstance(a, types.Array): + return + isnan = get_isnan(a.dtype) + + def nanmedian_impl(a): + # Create a temporary workspace with only non-NaN values + temp_arry = np.empty(a.size, a.dtype) + n = 0 + for view in np.nditer(a): + v = view.item() + if not isnan(v): + temp_arry[n] = v + n += 1 + + # all NaNs + if n == 0: + return np.nan + + return _median_inner(temp_arry, n) + + return nanmedian_impl + + +@register_jitable +def np_partition_impl_inner(a, kth_array): + + # allocate and fill empty array rather than copy a and mutate in place + # as the latter approach fails to preserve strides + out = np.empty_like(a) + + idx = np.ndindex(a.shape[:-1]) # Numpy default partition axis is -1 + for s in idx: + arry = a[s].copy() + low = 0 + high = len(arry) - 1 + + for kth in kth_array: + _select_w_nan(arry, kth, low, high) + low = kth # narrow span of subsequent partition + + out[s] = arry + return out + + +@register_jitable +def np_argpartition_impl_inner(a, kth_array): + + # allocate and fill empty array rather than copy a and mutate in place + # as the latter approach fails to preserve strides + out = np.empty_like(a, dtype=np.intp) + + idx = np.ndindex(a.shape[:-1]) # Numpy default partition axis is -1 + for s in idx: + arry = a[s].copy() + idx_arry = np.arange(len(arry)) + low = 0 + high = len(arry) - 1 + + for kth in kth_array: + _arg_select_w_nan(arry, kth, low, high, idx_arry) + low = kth # narrow span of subsequent partition + + out[s] = idx_arry + return out + + +@register_jitable +def valid_kths(a, kth): + """ + Returns a sorted, unique array of kth values which serve + as indexers for partitioning the input array, a. + + If the absolute value of any of the provided values + is greater than a.shape[-1] an exception is raised since + we are partitioning along the last axis (per Numpy default + behaviour). + + Values less than 0 are transformed to equivalent positive + index values. + """ + # cast boolean to int, where relevant + kth_array = _asarray(kth).astype(np.int64) + + if kth_array.ndim != 1: + raise ValueError('kth must be scalar or 1-D') + # numpy raises ValueError: object too deep for desired array + + if np.any(np.abs(kth_array) >= a.shape[-1]): + raise ValueError("kth out of bounds") + + out = np.empty_like(kth_array) + + for index, val in np.ndenumerate(kth_array): + if val < 0: + out[index] = val + a.shape[-1] # equivalent positive index + else: + out[index] = val + + return np.unique(out) + + +@overload(np.partition) +def np_partition(a, kth): + + if not isinstance(a, (types.Array, types.Sequence, types.Tuple)): + raise NumbaTypeError('The first argument must be an array-like') + + if isinstance(a, types.Array) and a.ndim == 0: + msg = 'The first argument must be at least 1-D (found 0-D)' + raise NumbaTypeError(msg) + + kthdt = getattr(kth, 'dtype', kth) + if numpy_version >= (2, 3): + kth_types = types.Integer + else: + kth_types = (types.Boolean, types.Integer) + if not isinstance(kthdt, kth_types): + # bool gets cast to int subsequently + raise NumbaTypeError('Partition index must be integer') + + def np_partition_impl(a, kth): + a_tmp = _asarray(a) + if a_tmp.size == 0: + return a_tmp.copy() + else: + kth_array = valid_kths(a_tmp, kth) + return np_partition_impl_inner(a_tmp, kth_array) + + return np_partition_impl + + +@overload(np.argpartition) +def np_argpartition(a, kth): + + if not isinstance(a, (types.Array, types.Sequence, types.Tuple)): + raise NumbaTypeError('The first argument must be an array-like') + + if isinstance(a, types.Array) and a.ndim == 0: + msg = 'The first argument must be at least 1-D (found 0-D)' + raise NumbaTypeError(msg) + + kthdt = getattr(kth, 'dtype', kth) + if numpy_version >= (2, 3): + kth_types = types.Integer + else: + kth_types = (types.Boolean, types.Integer) + if not isinstance(kthdt, kth_types): + # bool gets cast to int subsequently + raise NumbaTypeError('Partition index must be integer') + + def np_argpartition_impl(a, kth): + a_tmp = _asarray(a) + if a_tmp.size == 0: + return a_tmp.copy().astype('intp') + else: + kth_array = valid_kths(a_tmp, kth) + return np_argpartition_impl_inner(a_tmp, kth_array) + + return np_argpartition_impl + + +#---------------------------------------------------------------------------- +# Building matrices + +@register_jitable +def _tri_impl(N, M, k): + shape = max(0, N), max(0, M) # numpy floors each dimension at 0 + out = np.empty(shape, dtype=np.float64) # numpy default dtype + + for i in range(shape[0]): + m_max = min(max(0, i + k + 1), shape[1]) + out[i, :m_max] = 1 + out[i, m_max:] = 0 + + return out + + +@overload(np.tri) +def np_tri(N, M=None, k=0): + + # we require k to be integer, unlike numpy + check_is_integer(k, 'k') + + def tri_impl(N, M=None, k=0): + if M is None: + M = N + return _tri_impl(N, M, k) + + return tri_impl + + +@register_jitable +def _make_square(m): + """ + Takes a 1d array and tiles it to form a square matrix + - i.e. a facsimile of np.tile(m, (len(m), 1)) + """ + assert m.ndim == 1 + + len_m = len(m) + out = np.empty((len_m, len_m), dtype=m.dtype) + + for i in range(len_m): + out[i] = m + + return out + + +@register_jitable +def np_tril_impl_2d(m, k=0): + mask = np.tri(m.shape[-2], M=m.shape[-1], k=k).astype(np.uint) + return np.where(mask, m, np.zeros_like(m, dtype=m.dtype)) + + +@overload(np.tril) +def my_tril(m, k=0): + + # we require k to be integer, unlike numpy + check_is_integer(k, 'k') + + def np_tril_impl_1d(m, k=0): + m_2d = _make_square(m) + return np_tril_impl_2d(m_2d, k) + + def np_tril_impl_multi(m, k=0): + mask = np.tri(m.shape[-2], M=m.shape[-1], k=k).astype(np.uint) + idx = np.ndindex(m.shape[:-2]) + z = np.empty_like(m) + zero_opt = np.zeros_like(mask, dtype=m.dtype) + for sel in idx: + z[sel] = np.where(mask, m[sel], zero_opt) + return z + + if m.ndim == 1: + return np_tril_impl_1d + elif m.ndim == 2: + return np_tril_impl_2d + else: + return np_tril_impl_multi + + +@overload(np.tril_indices) +def np_tril_indices(n, k=0, m=None): + + # we require integer arguments, unlike numpy + check_is_integer(n, 'n') + check_is_integer(k, 'k') + if not is_nonelike(m): + check_is_integer(m, 'm') + + def np_tril_indices_impl(n, k=0, m=None): + return np.nonzero(np.tri(n, m, k=k)) + return np_tril_indices_impl + + +@overload(np.tril_indices_from) +def np_tril_indices_from(arr, k=0): + + # we require k to be integer, unlike numpy + check_is_integer(k, 'k') + + if arr.ndim != 2: + raise TypingError("input array must be 2-d") + + def np_tril_indices_from_impl(arr, k=0): + return np.tril_indices(arr.shape[0], k=k, m=arr.shape[1]) + return np_tril_indices_from_impl + + +@register_jitable +def np_triu_impl_2d(m, k=0): + mask = np.tri(m.shape[-2], M=m.shape[-1], k=k - 1).astype(np.uint) + return np.where(mask, np.zeros_like(m, dtype=m.dtype), m) + + +@overload(np.triu) +def my_triu(m, k=0): + # we require k to be integer, unlike numpy + check_is_integer(k, 'k') + + def np_triu_impl_1d(m, k=0): + m_2d = _make_square(m) + return np_triu_impl_2d(m_2d, k) + + def np_triu_impl_multi(m, k=0): + mask = np.tri(m.shape[-2], M=m.shape[-1], k=k - 1).astype(np.uint) + idx = np.ndindex(m.shape[:-2]) + z = np.empty_like(m) + zero_opt = np.zeros_like(mask, dtype=m.dtype) + for sel in idx: + z[sel] = np.where(mask, zero_opt, m[sel]) + return z + + if m.ndim == 1: + return np_triu_impl_1d + elif m.ndim == 2: + return np_triu_impl_2d + else: + return np_triu_impl_multi + + +@overload(np.triu_indices) +def np_triu_indices(n, k=0, m=None): + + # we require integer arguments, unlike numpy + check_is_integer(n, 'n') + check_is_integer(k, 'k') + if not is_nonelike(m): + check_is_integer(m, 'm') + + def np_triu_indices_impl(n, k=0, m=None): + return np.nonzero(1 - np.tri(n, m, k=k - 1)) + return np_triu_indices_impl + + +@overload(np.triu_indices_from) +def np_triu_indices_from(arr, k=0): + + # we require k to be integer, unlike numpy + check_is_integer(k, 'k') + + if arr.ndim != 2: + raise TypingError("input array must be 2-d") + + def np_triu_indices_from_impl(arr, k=0): + return np.triu_indices(arr.shape[0], k=k, m=arr.shape[1]) + return np_triu_indices_from_impl + + +def _prepare_array(arr): + pass + + +@overload(_prepare_array) +def _prepare_array_impl(arr): + if arr in (None, types.none): + return lambda arr: np.array(()) + else: + return lambda arr: _asarray(arr).ravel() + + +def _dtype_of_compound(inobj): + obj = inobj + while True: + if isinstance(obj, (types.Number, types.Boolean)): + return as_dtype(obj) + l = getattr(obj, '__len__', None) + if l is not None and l() == 0: # empty tuple or similar + return np.float64 + dt = getattr(obj, 'dtype', None) + if dt is None: + raise NumbaTypeError("type has no dtype attr") + if isinstance(obj, types.Sequence): + obj = obj.dtype + else: + return as_dtype(dt) + + +@overload(np.ediff1d) +def np_ediff1d(ary, to_end=None, to_begin=None): + + if isinstance(ary, types.Array): + if isinstance(ary.dtype, types.Boolean): + raise NumbaTypeError("Boolean dtype is unsupported (as per NumPy)") + # Numpy tries to do this: return ary[1:] - ary[:-1] which + # results in a TypeError exception being raised + + # Check that to_end and to_begin are compatible with ary + ary_dt = _dtype_of_compound(ary) + to_begin_dt = None + if not (is_nonelike(to_begin)): + to_begin_dt = _dtype_of_compound(to_begin) + to_end_dt = None + if not (is_nonelike(to_end)): + to_end_dt = _dtype_of_compound(to_end) + + if to_begin_dt is not None and not np.can_cast(to_begin_dt, ary_dt): + msg = "dtype of to_begin must be compatible with input ary" + raise NumbaTypeError(msg) + + if to_end_dt is not None and not np.can_cast(to_end_dt, ary_dt): + msg = "dtype of to_end must be compatible with input ary" + raise NumbaTypeError(msg) + + def np_ediff1d_impl(ary, to_end=None, to_begin=None): + # transform each input into an equivalent 1d array + start = _prepare_array(to_begin) + mid = _prepare_array(ary) + end = _prepare_array(to_end) + + out_dtype = mid.dtype + # output array dtype determined by ary dtype, per NumPy + # (for the most part); an exception to the rule is a zero length + # array-like, where NumPy falls back to np.float64; this behaviour + # is *not* replicated + + if len(mid) > 0: + out = np.empty((len(start) + len(mid) + len(end) - 1), + dtype=out_dtype) + start_idx = len(start) + mid_idx = len(start) + len(mid) - 1 + out[:start_idx] = start + out[start_idx:mid_idx] = np.diff(mid) + out[mid_idx:] = end + else: + out = np.empty((len(start) + len(end)), dtype=out_dtype) + start_idx = len(start) + out[:start_idx] = start + out[start_idx:] = end + return out + + return np_ediff1d_impl + + +def _select_element(arr): + pass + + +@overload(_select_element) +def _select_element_impl(arr): + zerod = getattr(arr, 'ndim', None) == 0 + if zerod: + def impl(arr): + x = np.array((1,), dtype=arr.dtype) + x[:] = arr + return x[0] + return impl + else: + def impl(arr): + return arr + return impl + + +def _get_d(dx, x): + pass + + +@overload(_get_d) +def get_d_impl(x, dx): + if is_nonelike(x): + def impl(x, dx): + return np.asarray(dx) + else: + def impl(x, dx): + return np.diff(np.asarray(x)) + return impl + + +def _trapz_impl(y, x=None, dx=1.0): + """Shared implementation for both np.trapz and np.trapezoid.""" + if isinstance(y, (types.Number, types.Boolean)): + raise TypingError('y cannot be a scalar') + elif isinstance(y, types.Array) and y.ndim == 0: + raise TypingError('y cannot be 0D') + # NumPy raises IndexError: list assignment index out of range + + # inspired by: + # https://github.com/numpy/numpy/blob/7ee52003/numpy/lib/function_base.py#L4040-L4065 # noqa: E501 + def impl(y, x=None, dx=1.0): + yarr = np.asarray(y) + d = _get_d(x, dx) + y_ave = (yarr[..., slice(1, None)] + yarr[..., slice(None, -1)]) / 2.0 + ret = np.sum(d * y_ave, -1) + processed = _select_element(ret) + return processed + + return impl + + +# np.trapz exists in NumPy < 2.4 (deprecated in 2.0, removed in 2.4) +if numpy_version < (2, 4): + @overload(np.trapz) + def np_trapz(y, x=None, dx=1.0): + return _trapz_impl(y, x, dx) + + +# np.trapezoid introduced in NumPy 2.0 as replacement for np.trapz +if numpy_version >= (2, 0): + @overload(np.trapezoid) + def np_trapezoid(y, x=None, dx=1.0): + return _trapz_impl(y, x, dx) + + +@register_jitable +def _np_vander(x, N, increasing, out): + """ + Generate an N-column Vandermonde matrix from a supplied 1-dimensional + array, x. Store results in an output matrix, out, which is assumed to + be of the required dtype. + + Values are accumulated using np.multiply to match the floating point + precision behaviour of numpy.vander. + """ + m, n = out.shape + assert m == len(x) + assert n == N + + if increasing: + for i in range(N): + if i == 0: + out[:, i] = 1 + else: + out[:, i] = np.multiply(x, out[:, (i - 1)]) + else: + for i in range(N - 1, -1, -1): + if i == N - 1: + out[:, i] = 1 + else: + out[:, i] = np.multiply(x, out[:, (i + 1)]) + + +@register_jitable +def _check_vander_params(x, N): + if x.ndim > 1: + raise ValueError('x must be a one-dimensional array or sequence.') + if N < 0: + raise ValueError('Negative dimensions are not allowed') + + +@overload(np.vander) +def np_vander(x, N=None, increasing=False): + if N not in (None, types.none): + if not isinstance(N, types.Integer): + raise TypingError('Second argument N must be None or an integer') + + def np_vander_impl(x, N=None, increasing=False): + if N is None: + N = len(x) + + _check_vander_params(x, N) + + # allocate output matrix using dtype determined in closure + out = np.empty((len(x), int(N)), dtype=dtype) + + _np_vander(x, N, increasing, out) + return out + + def np_vander_seq_impl(x, N=None, increasing=False): + if N is None: + N = len(x) + + x_arr = np.array(x) + _check_vander_params(x_arr, N) + + # allocate output matrix using dtype inferred when x_arr was created + out = np.empty((len(x), int(N)), dtype=x_arr.dtype) + + _np_vander(x_arr, N, increasing, out) + return out + + if isinstance(x, types.Array): + x_dt = as_dtype(x.dtype) + # replicate numpy behaviour w.r.t.type promotion + dtype = np.promote_types(x_dt, int) + return np_vander_impl + elif isinstance(x, (types.Tuple, types.Sequence)): + return np_vander_seq_impl + + +@overload(np.roll) +def np_roll(a, shift): + if not isinstance(shift, (types.Integer, types.Boolean)): + raise TypingError('shift must be an integer') + + def np_roll_impl(a, shift): + arr = np.asarray(a) + out = np.empty(arr.shape, dtype=arr.dtype) + # empty_like might result in different contiguity vs NumPy + + arr_flat = arr.flat + for i in range(arr.size): + idx = (i + shift) % arr.size + out.flat[idx] = arr_flat[i] + + return out + + if isinstance(a, (types.Number, types.Boolean)): + return lambda a, shift: np.asarray(a) + else: + return np_roll_impl + + +#---------------------------------------------------------------------------- +# Mathematical functions + +LIKELY_IN_CACHE_SIZE = 8 + + +@register_jitable +def binary_search_with_guess(key, arr, length, guess): + # NOTE: Do not refactor... see note in np_interp function impl below + # this is a facsimile of binary_search_with_guess prior to 1.15: + # https://github.com/numpy/numpy/blob/maintenance/1.15.x/numpy/core/src/multiarray/compiled_base.c # noqa: E501 + # Permanent reference: + # https://github.com/numpy/numpy/blob/3430d78c01a3b9a19adad75f1acb5ae18286da73/numpy/core/src/multiarray/compiled_base.c#L447 # noqa: E501 + imin = 0 + imax = length + + # Handle keys outside of the arr range first + if key > arr[length - 1]: + return length + elif key < arr[0]: + return -1 + + # If len <= 4 use linear search. + # From above we know key >= arr[0] when we start. + if length <= 4: + i = 1 + while i < length and key >= arr[i]: + i += 1 + return i - 1 + + if guess > length - 3: + guess = length - 3 + + if guess < 1: + guess = 1 + + # check most likely values: guess - 1, guess, guess + 1 + if key < arr[guess]: + if key < arr[guess - 1]: + imax = guess - 1 + + # last attempt to restrict search to items in cache + if guess > LIKELY_IN_CACHE_SIZE and \ + key >= arr[guess - LIKELY_IN_CACHE_SIZE]: + imin = guess - LIKELY_IN_CACHE_SIZE + else: + # key >= arr[guess - 1] + return guess - 1 + else: + # key >= arr[guess] + if key < arr[guess + 1]: + return guess + else: + # key >= arr[guess + 1] + if key < arr[guess + 2]: + return guess + 1 + else: + # key >= arr[guess + 2] + imin = guess + 2 + # last attempt to restrict search to items in cache + if (guess < (length - LIKELY_IN_CACHE_SIZE - 1)) and \ + (key < arr[guess + LIKELY_IN_CACHE_SIZE]): + imax = guess + LIKELY_IN_CACHE_SIZE + + # finally, find index by bisection + while imin < imax: + imid = imin + ((imax - imin) >> 1) + if key >= arr[imid]: + imin = imid + 1 + else: + imax = imid + + return imin - 1 + + +@register_jitable +def np_interp_impl_complex_inner(x, xp, fp, dtype): + # NOTE: Do not refactor... see note in np_interp function impl below + # this is a facsimile of arr_interp_complex post 1.16 with added + # branching to support np1.17 style NaN handling. + # https://github.com/numpy/numpy/blob/maintenance/1.16.x/numpy/core/src/multiarray/compiled_base.c # noqa: E501 + # Permanent reference: + # https://github.com/numpy/numpy/blob/971e2e89d08deeae0139d3011d15646fdac13c92/numpy/core/src/multiarray/compiled_base.c#L628 # noqa: E501 + dz = np.asarray(x) + dx = np.asarray(xp) + dy = np.asarray(fp) + + if len(dx) == 0: + raise ValueError('array of sample points is empty') + + if len(dx) != len(dy): + raise ValueError('fp and xp are not of the same size.') + + if dx.size == 1: + return np.full(dz.shape, fill_value=dy[0], dtype=dtype) + + dres = np.empty(dz.shape, dtype=dtype) + + lenx = dz.size + lenxp = len(dx) + lval = dy[0] + rval = dy[lenxp - 1] + + if lenxp == 1: + xp_val = dx[0] + fp_val = dy[0] + + for i in range(lenx): + x_val = dz.flat[i] + if x_val < xp_val: + dres.flat[i] = lval + elif x_val > xp_val: + dres.flat[i] = rval + else: + dres.flat[i] = fp_val + + else: + j = 0 + + # only pre-calculate slopes if there are relatively few of them. + if lenxp <= lenx: + slopes = np.empty((lenxp - 1), dtype=dtype) + else: + slopes = np.empty(0, dtype=dtype) + + if slopes.size: + for i in range(lenxp - 1): + inv_dx = 1 / (dx[i + 1] - dx[i]) + real = (dy[i + 1].real - dy[i].real) * inv_dx + imag = (dy[i + 1].imag - dy[i].imag) * inv_dx + slopes[i] = real + 1j * imag + + for i in range(lenx): + x_val = dz.flat[i] + + if np.isnan(x_val): + real = x_val + imag = 0.0 + dres.flat[i] = real + 1j * imag + continue + + j = binary_search_with_guess(x_val, dx, lenxp, j) + + if j == -1: + dres.flat[i] = lval + elif j == lenxp: + dres.flat[i] = rval + elif j == lenxp - 1: + dres.flat[i] = dy[j] + elif dx[j] == x_val: + # Avoid potential non-finite interpolation + dres.flat[i] = dy[j] + else: + if slopes.size: + slope = slopes[j] + else: + inv_dx = 1 / (dx[j + 1] - dx[j]) + real = (dy[j + 1].real - dy[j].real) * inv_dx + imag = (dy[j + 1].imag - dy[j].imag) * inv_dx + slope = real + 1j * imag + + # NumPy 1.17 handles NaN correctly - this is a copy of + # innermost part of arr_interp_complex post 1.17: + # https://github.com/numpy/numpy/blob/maintenance/1.17.x/numpy/core/src/multiarray/compiled_base.c # noqa: E501 + # Permanent reference: + # https://github.com/numpy/numpy/blob/91fbe4dde246559fa5b085ebf4bc268e2b89eea8/numpy/core/src/multiarray/compiled_base.c#L798-L812 # noqa: E501 + + # If we get NaN in one direction, try the other + real = slope.real * (x_val - dx[j]) + dy[j].real + if np.isnan(real): + real = slope.real * (x_val - dx[j + 1]) + dy[j + 1].real + if np.isnan(real) and dy[j].real == dy[j + 1].real: + real = dy[j].real + + imag = slope.imag * (x_val - dx[j]) + dy[j].imag + if np.isnan(imag): + imag = slope.imag * (x_val - dx[j + 1]) + dy[j + 1].imag + if np.isnan(imag) and dy[j].imag == dy[j + 1].imag: + imag = dy[j].imag + + dres.flat[i] = real + 1j * imag + + return dres + + +@register_jitable +def np_interp_impl_inner(x, xp, fp, dtype): + # NOTE: Do not refactor... see note in np_interp function impl below + # this is a facsimile of arr_interp post 1.16: + # https://github.com/numpy/numpy/blob/maintenance/1.16.x/numpy/core/src/multiarray/compiled_base.c # noqa: E501 + # Permanent reference: + # https://github.com/numpy/numpy/blob/971e2e89d08deeae0139d3011d15646fdac13c92/numpy/core/src/multiarray/compiled_base.c#L473 # noqa: E501 + dz = np.asarray(x, dtype=np.float64) + dx = np.asarray(xp, dtype=np.float64) + dy = np.asarray(fp, dtype=np.float64) + + if len(dx) == 0: + raise ValueError('array of sample points is empty') + + if len(dx) != len(dy): + raise ValueError('fp and xp are not of the same size.') + + if dx.size == 1: + return np.full(dz.shape, fill_value=dy[0], dtype=dtype) + + dres = np.empty(dz.shape, dtype=dtype) + + lenx = dz.size + lenxp = len(dx) + lval = dy[0] + rval = dy[lenxp - 1] + + if lenxp == 1: + xp_val = dx[0] + fp_val = dy[0] + + for i in range(lenx): + x_val = dz.flat[i] + if x_val < xp_val: + dres.flat[i] = lval + elif x_val > xp_val: + dres.flat[i] = rval + else: + dres.flat[i] = fp_val + + else: + j = 0 + + # only pre-calculate slopes if there are relatively few of them. + if lenxp <= lenx: + slopes = (dy[1:] - dy[:-1]) / (dx[1:] - dx[:-1]) + else: + slopes = np.empty(0, dtype=dtype) + + for i in range(lenx): + x_val = dz.flat[i] + + if np.isnan(x_val): + dres.flat[i] = x_val + continue + + j = binary_search_with_guess(x_val, dx, lenxp, j) + + if j == -1: + dres.flat[i] = lval + elif j == lenxp: + dres.flat[i] = rval + elif j == lenxp - 1: + dres.flat[i] = dy[j] + elif dx[j] == x_val: + # Avoid potential non-finite interpolation + dres.flat[i] = dy[j] + else: + if slopes.size: + slope = slopes[j] + else: + slope = (dy[j + 1] - dy[j]) / (dx[j + 1] - dx[j]) + + dres.flat[i] = slope * (x_val - dx[j]) + dy[j] + + # NOTE: this is in np1.17 + # https://github.com/numpy/numpy/blob/maintenance/1.17.x/numpy/core/src/multiarray/compiled_base.c # noqa: E501 + # Permanent reference: + # https://github.com/numpy/numpy/blob/91fbe4dde246559fa5b085ebf4bc268e2b89eea8/numpy/core/src/multiarray/compiled_base.c#L610-L616 # noqa: E501 + # + # If we get nan in one direction, try the other + if np.isnan(dres.flat[i]): + dres.flat[i] = slope * (x_val - dx[j + 1]) + dy[j + 1] # noqa: E501 + if np.isnan(dres.flat[i]) and dy[j] == dy[j + 1]: + dres.flat[i] = dy[j] + + return dres + + +@overload(np.interp) +def np_interp(x, xp, fp): + # Replicating basic interp is relatively simple, but matching the behaviour + # of NumPy for edge cases is really quite hard. After a couple of attempts + # to avoid translation of the C source it was deemed necessary. + + if hasattr(xp, 'ndim') and xp.ndim > 1: + raise TypingError('xp must be 1D') + if hasattr(fp, 'ndim') and fp.ndim > 1: + raise TypingError('fp must be 1D') + + complex_dtype_msg = ( + "Cannot cast array data from complex dtype to float64 dtype" + ) + + xp_dt = determine_dtype(xp) + if np.issubdtype(xp_dt, np.complexfloating): + raise TypingError(complex_dtype_msg) + + fp_dt = determine_dtype(fp) + dtype = np.result_type(fp_dt, np.float64) + + if np.issubdtype(dtype, np.complexfloating): + inner = np_interp_impl_complex_inner + else: + inner = np_interp_impl_inner + + def np_interp_impl(x, xp, fp): + return inner(x, xp, fp, dtype) + + def np_interp_scalar_impl(x, xp, fp): + return inner(x, xp, fp, dtype).flat[0] + + if isinstance(x, types.Number): + if isinstance(x, types.Complex): + raise TypingError(complex_dtype_msg) + return np_interp_scalar_impl + + return np_interp_impl + + +#---------------------------------------------------------------------------- +# Statistics + +@register_jitable +def row_wise_average(a): + assert a.ndim == 2 + + m, n = a.shape + out = np.empty((m, 1), dtype=a.dtype) + + for i in range(m): + out[i, 0] = np.sum(a[i, :]) / n + + return out + + +@register_jitable +def np_cov_impl_inner(X, bias, ddof): + + # determine degrees of freedom + if ddof is None: + if bias: + ddof = 0 + else: + ddof = 1 + + # determine the normalization factor + fact = X.shape[1] - ddof + + # numpy warns if less than 0 and floors at 0 + fact = max(fact, 0.0) + + # de-mean + X -= row_wise_average(X) + + # calculate result - requires blas + c = np.dot(X, np.conj(X.T)) + c *= np.true_divide(1, fact) + return c + + +def _prepare_cov_input_inner(): + pass + + +@overload(_prepare_cov_input_inner) +def _prepare_cov_input_impl(m, y, rowvar, dtype): + if y in (None, types.none): + def _prepare_cov_input_inner(m, y, rowvar, dtype): + m_arr = np.atleast_2d(_asarray(m)) + + if not rowvar: + m_arr = m_arr.T + + return m_arr + else: + def _prepare_cov_input_inner(m, y, rowvar, dtype): + m_arr = np.atleast_2d(_asarray(m)) + y_arr = np.atleast_2d(_asarray(y)) + + # transpose if asked to and not a (1, n) vector - this looks + # wrong as you might end up transposing one and not the other, + # but it's what numpy does + if not rowvar: + if m_arr.shape[0] != 1: + m_arr = m_arr.T + if y_arr.shape[0] != 1: + y_arr = y_arr.T + + m_rows, m_cols = m_arr.shape + y_rows, y_cols = y_arr.shape + + if m_cols != y_cols: + raise ValueError("m and y have incompatible dimensions") + + # allocate and fill output array + out = np.empty((m_rows + y_rows, m_cols), dtype=dtype) + out[:m_rows, :] = m_arr + out[-y_rows:, :] = y_arr + + return out + + return _prepare_cov_input_inner + + +@register_jitable +def _handle_m_dim_change(m): + if m.ndim == 2 and m.shape[0] == 1: + msg = ("2D array containing a single row is unsupported due to " + "ambiguity in type inference. To use numpy.cov in this case " + "simply pass the row as a 1D array, i.e. m[0].") + raise RuntimeError(msg) + + +_handle_m_dim_nop = register_jitable(lambda x: x) + + +def determine_dtype(array_like): + array_like_dt = np.float64 + if isinstance(array_like, types.Array): + array_like_dt = as_dtype(array_like.dtype) + elif isinstance(array_like, (types.Number, types.Boolean)): + array_like_dt = as_dtype(array_like) + elif isinstance(array_like, (types.UniTuple, types.Tuple)): + coltypes = set() + for val in array_like: + if hasattr(val, 'count'): + [coltypes.add(v) for v in val] + else: + coltypes.add(val) + if len(coltypes) > 1: + array_like_dt = np.promote_types(*[as_dtype(ty) for ty in coltypes]) + elif len(coltypes) == 1: + array_like_dt = as_dtype(coltypes.pop()) + + return array_like_dt + + +def check_dimensions(array_like, name): + if isinstance(array_like, types.Array): + if array_like.ndim > 2: + raise NumbaTypeError("{0} has more than 2 dimensions".format(name)) + elif isinstance(array_like, types.Sequence): + if isinstance(array_like.key[0], types.Sequence): + if isinstance(array_like.key[0].key[0], types.Sequence): + msg = "{0} has more than 2 dimensions".format(name) + raise NumbaTypeError(msg) + + +@register_jitable +def _handle_ddof(ddof): + if not np.isfinite(ddof): + raise ValueError('Cannot convert non-finite ddof to integer') + if ddof - int(ddof) != 0: + raise ValueError('ddof must be integral value') + + +_handle_ddof_nop = register_jitable(lambda x: x) + + +@register_jitable +def _prepare_cov_input(m, y, rowvar, dtype, ddof, _DDOF_HANDLER, + _M_DIM_HANDLER): + _M_DIM_HANDLER(m) + _DDOF_HANDLER(ddof) + return _prepare_cov_input_inner(m, y, rowvar, dtype) + + +def scalar_result_expected(mandatory_input, optional_input): + opt_is_none = optional_input in (None, types.none) + + if isinstance(mandatory_input, types.Array) and mandatory_input.ndim == 1: + return opt_is_none + + if isinstance(mandatory_input, types.BaseTuple): + if all(isinstance(x, (types.Number, types.Boolean)) + for x in mandatory_input.types): + return opt_is_none + else: + if (len(mandatory_input.types) == 1 and + isinstance(mandatory_input.types[0], types.BaseTuple)): + return opt_is_none + + if isinstance(mandatory_input, (types.Number, types.Boolean)): + return opt_is_none + + if isinstance(mandatory_input, types.Sequence): + if (not isinstance(mandatory_input.key[0], types.Sequence) and + opt_is_none): + return True + + return False + + +@register_jitable +def _clip_corr(x): + return np.where(np.fabs(x) > 1, np.sign(x), x) + + +@register_jitable +def _clip_complex(x): + real = _clip_corr(x.real) + imag = _clip_corr(x.imag) + return real + 1j * imag + + +@overload(np.cov) +def np_cov(m, y=None, rowvar=True, bias=False, ddof=None): + + # reject problem if m and / or y are more than 2D + check_dimensions(m, 'm') + check_dimensions(y, 'y') + + # reject problem if ddof invalid (either upfront if type is + # obviously invalid, or later if value found to be non-integral) + if ddof in (None, types.none): + _DDOF_HANDLER = _handle_ddof_nop + else: + if isinstance(ddof, (types.Integer, types.Boolean)): + _DDOF_HANDLER = _handle_ddof_nop + elif isinstance(ddof, types.Float): + _DDOF_HANDLER = _handle_ddof + else: + raise TypingError('ddof must be a real numerical scalar type') + + # special case for 2D array input with 1 row of data - select + # handler function which we'll call later when we have access + # to the shape of the input array + _M_DIM_HANDLER = _handle_m_dim_nop + if isinstance(m, types.Array): + _M_DIM_HANDLER = _handle_m_dim_change + + # infer result dtype + m_dt = determine_dtype(m) + y_dt = determine_dtype(y) + dtype = np.result_type(m_dt, y_dt, np.float64) + + def np_cov_impl(m, y=None, rowvar=True, bias=False, ddof=None): + X = _prepare_cov_input(m, y, rowvar, dtype, ddof, _DDOF_HANDLER, + _M_DIM_HANDLER).astype(dtype) + + if np.any(np.array(X.shape) == 0): + return np.full((X.shape[0], X.shape[0]), fill_value=np.nan, + dtype=dtype) + else: + return np_cov_impl_inner(X, bias, ddof) + + def np_cov_impl_single_variable(m, y=None, rowvar=True, bias=False, + ddof=None): + X = _prepare_cov_input(m, y, rowvar, ddof, dtype, _DDOF_HANDLER, + _M_DIM_HANDLER).astype(dtype) + + if np.any(np.array(X.shape) == 0): + variance = np.nan + else: + variance = np_cov_impl_inner(X, bias, ddof).flat[0] + + return np.array(variance) + + if scalar_result_expected(m, y): + return np_cov_impl_single_variable + else: + return np_cov_impl + + +@overload(np.corrcoef) +def np_corrcoef(x, y=None, rowvar=True): + + x_dt = determine_dtype(x) + y_dt = determine_dtype(y) + dtype = np.result_type(x_dt, y_dt, np.float64) + + if dtype == np.complex128: + clip_fn = _clip_complex + else: + clip_fn = _clip_corr + + def np_corrcoef_impl(x, y=None, rowvar=True): + c = np.cov(x, y, rowvar) + d = np.diag(c) + stddev = np.sqrt(d.real) + + for i in range(c.shape[0]): + c[i, :] /= stddev + c[:, i] /= stddev + + return clip_fn(c) + + def np_corrcoef_impl_single_variable(x, y=None, rowvar=True): + c = np.cov(x, y, rowvar) + return c / c + + if scalar_result_expected(x, y): + return np_corrcoef_impl_single_variable + else: + return np_corrcoef_impl + + +#---------------------------------------------------------------------------- +# Element-wise computations + + +@overload(np.argwhere) +def np_argwhere(a): + # needs to be much more array-like for the array impl to work, Numba bug + # in one of the underlying function calls? + + use_scalar = isinstance(a, (types.Number, types.Boolean)) + if type_can_asarray(a) and not use_scalar: + def impl(a): + arr = np.asarray(a) + if arr.shape == (): + return np.zeros((0, 1), dtype=types.intp) + return np.transpose(np.vstack(np.nonzero(arr))) + else: + falseish = (0, 0) + trueish = (1, 0) + + def impl(a): + if a is not None and bool(a): + return np.zeros(trueish, dtype=types.intp) + else: + return np.zeros(falseish, dtype=types.intp) + + return impl + + +@overload(np.flatnonzero) +def np_flatnonzero(a): + + if type_can_asarray(a): + def impl(a): + arr = np.asarray(a) + return np.nonzero(np.ravel(arr))[0] + else: + def impl(a): + if a is not None and bool(a): + data = [0] + else: + data = [x for x in range(0)] + return np.array(data, dtype=types.intp) + + return impl + + +@register_jitable +def _fill_diagonal_params(a, wrap): + if a.ndim == 2: + m = a.shape[0] + n = a.shape[1] + step = 1 + n + if wrap: + end = n * m + else: + end = n * min(m, n) + else: + shape = np.array(a.shape) + + if not np.all(np.diff(shape) == 0): + raise ValueError("All dimensions of input must be of equal length") + + step = 1 + (np.cumprod(shape[:-1])).sum() + end = shape.prod() + + return end, step + + +@register_jitable +def _fill_diagonal_scalar(a, val, wrap): + end, step = _fill_diagonal_params(a, wrap) + + for i in range(0, end, step): + a.flat[i] = val + + +@register_jitable +def _fill_diagonal(a, val, wrap): + end, step = _fill_diagonal_params(a, wrap) + ctr = 0 + v_len = len(val) + + for i in range(0, end, step): + a.flat[i] = val[ctr] + ctr += 1 + ctr = ctr % v_len + + +@register_jitable +def _check_val_int(a, val): + iinfo = np.iinfo(a.dtype) + v_min = iinfo.min + v_max = iinfo.max + + # check finite values are within bounds + if np.any(~np.isfinite(val)) or np.any(val < v_min) or np.any(val > v_max): + raise ValueError('Unable to safely conform val to a.dtype') + + +@register_jitable +def _check_val_float(a, val): + finfo = np.finfo(a.dtype) + v_min = finfo.min + v_max = finfo.max + + # check finite values are within bounds + finite_vals = val[np.isfinite(val)] + if np.any(finite_vals < v_min) or np.any(finite_vals > v_max): + raise ValueError('Unable to safely conform val to a.dtype') + + +# no check performed, needed for pathway where no check is required +_check_nop = register_jitable(lambda x, y: x) + + +def _asarray(x): + pass + + +@overload(_asarray) +def _asarray_impl(x): + if isinstance(x, types.Array): + return lambda x: x + elif isinstance(x, (types.Sequence, types.Tuple)): + return lambda x: np.array(x) + elif isinstance(x, (types.Number, types.Boolean)): + ty = as_dtype(x) + return lambda x: np.array([x], dtype=ty) + + +@overload(np.fill_diagonal) +def np_fill_diagonal(a, val, wrap=False): + + if a.ndim > 1: + # the following can be simplified after #3088; until then, employ + # a basic mechanism for catching cases where val is of a type/value + # which cannot safely be cast to a.dtype + if isinstance(a.dtype, types.Integer): + checker = _check_val_int + elif isinstance(a.dtype, types.Float): + checker = _check_val_float + else: + checker = _check_nop + + def scalar_impl(a, val, wrap=False): + tmpval = _asarray(val).flatten() + checker(a, tmpval) + _fill_diagonal_scalar(a, val, wrap) + + def non_scalar_impl(a, val, wrap=False): + tmpval = _asarray(val).flatten() + checker(a, tmpval) + _fill_diagonal(a, tmpval, wrap) + + if isinstance(val, (types.Float, types.Integer, types.Boolean)): + return scalar_impl + elif isinstance(val, (types.Tuple, types.Sequence, types.Array)): + return non_scalar_impl + else: + msg = "The first argument must be at least 2-D (found %s-D)" % a.ndim + raise TypingError(msg) + + +def _np_round_intrinsic(tp): + # np.round() always rounds half to even + return "llvm.rint.f%d" % (tp.bitwidth,) + + +@intrinsic +def _np_round_float(typingctx, val): + sig = val(val) + + def codegen(context, builder, sig, args): + [val] = args + tp = sig.args[0] + llty = context.get_value_type(tp) + module = builder.module + fnty = llvmlite.ir.FunctionType(llty, [llty]) + fn = cgutils.get_or_insert_function(module, fnty, + _np_round_intrinsic(tp)) + res = builder.call(fn, (val,)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + return sig, codegen + + +@register_jitable +def round_ndigits(x, ndigits): + if math.isinf(x) or math.isnan(x): + return x + + # NOTE: this is CPython's algorithm, but perhaps this is overkill + # when emulating Numpy's behaviour. + if ndigits >= 0: + if ndigits > 22: + # pow1 and pow2 are each safe from overflow, but + # pow1*pow2 ~= pow(10.0, ndigits) might overflow. + pow1 = 10.0 ** (ndigits - 22) + pow2 = 1e22 + else: + pow1 = 10.0 ** ndigits + pow2 = 1.0 + y = (x * pow1) * pow2 + if math.isinf(y): + return x + return (_np_round_float(y) / pow2) / pow1 + + else: + pow1 = 10.0 ** (-ndigits) + y = x / pow1 + return _np_round_float(y) * pow1 + + +@overload(np.around) +@overload(np.round) +def impl_np_round(a, decimals=0, out=None): + if not type_can_asarray(a): + raise TypingError('The argument "a" must be array-like') + + if not (isinstance(out, types.Array) or is_nonelike(out)): + msg = 'The argument "out" must be an array if it is provided' + raise TypingError(msg) + + if isinstance(a, (types.Float, types.Integer, types.Complex)): + if is_nonelike(out): + if isinstance(a, types.Float): + def impl(a, decimals=0, out=None): + if decimals == 0: + return _np_round_float(a) + else: + return round_ndigits(a, decimals) + return impl + elif isinstance(a, types.Integer): + def impl(a, decimals=0, out=None): + if decimals == 0: + return a + else: + return int(round_ndigits(a, decimals)) + return impl + elif isinstance(a, types.Complex): + def impl(a, decimals=0, out=None): + if decimals == 0: + real = _np_round_float(a.real) + imag = _np_round_float(a.imag) + else: + real = round_ndigits(a.real, decimals) + imag = round_ndigits(a.imag, decimals) + return complex(real, imag) + return impl + else: + def impl(a, decimals=0, out=None): + out[0] = np.round(a, decimals) + return out + return impl + elif isinstance(a, types.Array): + if is_nonelike(out): + def impl(a, decimals=0, out=None): + out = np.empty_like(a) + return np.round(a, decimals, out) + return impl + else: + def impl(a, decimals=0, out=None): + if a.shape != out.shape: + raise ValueError("invalid output shape") + for index, val in np.ndenumerate(a): + out[index] = np.round(val, decimals) + return out + return impl + + +if numpy_version < (2, 0): + overload(np.round_)(impl_np_round) + + +@overload(np.sinc) +def impl_np_sinc(x): + if isinstance(x, types.Number): + def impl(x): + if x == 0.e0: # to match np impl + x = 1e-20 + x *= np.pi # np sinc is the normalised variant + return np.sin(x) / x + return impl + elif isinstance(x, types.Array): + def impl(x): + out = np.zeros_like(x) + for index, val in np.ndenumerate(x): + out[index] = np.sinc(val) + return out + return impl + else: + raise NumbaTypeError('Argument "x" must be a Number or array-like.') + + +@overload(np.angle) +def ov_np_angle(z, deg=False): + deg_mult = float(180 / np.pi) + + # non-complex scalar values are accepted as well + if isinstance(z, types.Number): + def impl(z, deg=False): + if deg: + return np.arctan2(z.imag, z.real) * deg_mult + else: + return np.arctan2(z.imag, z.real) + return impl + elif isinstance(z, types.Array): + dtype = z.dtype + + if isinstance(dtype, types.Complex): + ret_dtype = dtype.underlying_float + elif isinstance(dtype, types.Float): + ret_dtype = dtype + else: + return + + def impl(z, deg=False): + out = np.zeros_like(z, dtype=ret_dtype) + for index, val in np.ndenumerate(z): + out[index] = np.angle(val, deg) + return out + return impl + else: + raise NumbaTypeError('Argument "z" must be a complex ' + f'or Array[complex]. Got {z}') + + +@lower_builtin(np.nonzero, types.Array) +@lower_builtin("array.nonzero", types.Array) +def array_nonzero(context, builder, sig, args): + aryty = sig.args[0] + # Return type is a N-tuple of 1D C-contiguous arrays + retty = sig.return_type + outaryty = retty.dtype + nouts = retty.count + + ary = make_array(aryty)(context, builder, args[0]) + shape = cgutils.unpack_tuple(builder, ary.shape) + strides = cgutils.unpack_tuple(builder, ary.strides) + data = ary.data + layout = aryty.layout + + # First count the number of non-zero elements + zero = context.get_constant(types.intp, 0) + one = context.get_constant(types.intp, 1) + count = cgutils.alloca_once_value(builder, zero) + with cgutils.loop_nest(builder, shape, zero.type) as indices: + ptr = cgutils.get_item_pointer2(context, builder, data, shape, strides, + layout, indices) + val = load_item(context, builder, aryty, ptr) + nz = context.is_true(builder, aryty.dtype, val) + with builder.if_then(nz): + builder.store(builder.add(builder.load(count), one), count) + + # Then allocate output arrays of the right size + out_shape = (builder.load(count),) + outs = [_empty_nd_impl(context, builder, outaryty, out_shape)._getvalue() + for i in range(nouts)] + outarys = [make_array(outaryty)(context, builder, out) for out in outs] + out_datas = [out.data for out in outarys] + + # And fill them up + index = cgutils.alloca_once_value(builder, zero) + with cgutils.loop_nest(builder, shape, zero.type) as indices: + ptr = cgutils.get_item_pointer2(context, builder, data, shape, strides, + layout, indices) + val = load_item(context, builder, aryty, ptr) + nz = context.is_true(builder, aryty.dtype, val) + with builder.if_then(nz): + # Store element indices in output arrays + if not indices: + # For a 0-d array, store 0 in the unique output array + indices = (zero,) + cur = builder.load(index) + for i in range(nouts): + ptr = cgutils.get_item_pointer2(context, builder, out_datas[i], + out_shape, (), + 'C', [cur]) + store_item(context, builder, outaryty, indices[i], ptr) + builder.store(builder.add(cur, one), index) + + tup = context.make_tuple(builder, sig.return_type, outs) + return impl_ret_new_ref(context, builder, sig.return_type, tup) + + +def _where_zero_size_array_impl(dtype): + def impl(condition, x, y): + x_ = np.asarray(x).astype(dtype) + y_ = np.asarray(y).astype(dtype) + return x_ if condition else y_ + return impl + + +@register_jitable +def _where_generic_inner_impl(cond, x, y, res): + for idx, c in np.ndenumerate(cond): + res[idx] = x[idx] if c else y[idx] + return res + + +@register_jitable +def _where_fast_inner_impl(cond, x, y, res): + cf = cond.flat + xf = x.flat + yf = y.flat + rf = res.flat + for i in range(cond.size): + rf[i] = xf[i] if cf[i] else yf[i] + return res + + +def _where_generic_impl(dtype, layout): + use_faster_impl = layout in [{'C'}, {'F'}] + + def impl(condition, x, y): + cond1, x1, y1 = np.asarray(condition), np.asarray(x), np.asarray(y) + shape = np.broadcast_shapes(cond1.shape, x1.shape, y1.shape) + cond_ = np.broadcast_to(cond1, shape) + x_ = np.broadcast_to(x1, shape) + y_ = np.broadcast_to(y1, shape) + + if layout == 'F': + res = np.empty(shape[::-1], dtype=dtype).T + else: + res = np.empty(shape, dtype=dtype) + + if use_faster_impl: + return _where_fast_inner_impl(cond_, x_, y_, res) + else: + return _where_generic_inner_impl(cond_, x_, y_, res) + + return impl + + +@overload(np.where) +def ov_np_where(condition): + if not type_can_asarray(condition): + msg = 'The argument "condition" must be array-like' + raise NumbaTypeError(msg) + + def where_cond_none_none(condition): + return np.asarray(condition).nonzero() + return where_cond_none_none + + +@overload(np.where) +def ov_np_where_x_y(condition, x, y): + if not type_can_asarray(condition): + msg = 'The argument "condition" must be array-like' + raise NumbaTypeError(msg) + + # corner case: None is a valid value for np.where: + # >>> np.where([0, 1], None, 2) + # array([None, 2]) + # + # >>> np.where([0, 1], 2, None) + # array([2, None]) + # + # >>> np.where([0, 1], None, None) + # array([None, None]) + if is_nonelike(x) or is_nonelike(y): + # skip it for now as np.asarray(None) is not supported + raise NumbaTypeError('Argument "x" or "y" cannot be None') + + for arg, name in zip((x, y), ('x', 'y')): + if not type_can_asarray(arg): + msg = 'The argument "{}" must be array-like if provided' + raise NumbaTypeError(msg.format(name)) + + cond_arr = isinstance(condition, types.Array) + x_arr = isinstance(x, types.Array) + y_arr = isinstance(y, types.Array) + + if cond_arr: + x_dt = determine_dtype(x) + y_dt = determine_dtype(y) + dtype = np.promote_types(x_dt, y_dt) + + # corner case - 0 dim values + def check_0_dim(arg): + return isinstance(arg, types.Number) or ( + isinstance(arg, types.Array) and arg.ndim == 0) + special_0_case = all([check_0_dim(a) for a in (condition, x, y)]) + if special_0_case: + return _where_zero_size_array_impl(dtype) + + layout = condition.layout + if x_arr and y_arr: + if x.layout == y.layout == condition.layout: + layout = x.layout + else: + layout = 'A' + return _where_generic_impl(dtype, layout) + else: + def impl(condition, x, y): + return np.where(np.asarray(condition), np.asarray(x), np.asarray(y)) + return impl + + +@overload(np.real) +def np_real(val): + def np_real_impl(val): + return val.real + + return np_real_impl + + +@overload(np.imag) +def np_imag(val): + def np_imag_impl(val): + return val.imag + + return np_imag_impl + + +#---------------------------------------------------------------------------- +# Misc functions + +@overload(operator.contains) +def np_contains(arr, key): + if not isinstance(arr, types.Array): + return + + def np_contains_impl(arr, key): + for x in np.nditer(arr): + if x == key: + return True + return False + + return np_contains_impl + + +@overload(np.count_nonzero) +def np_count_nonzero(a, axis=None): + if not type_can_asarray(a): + raise TypingError("The argument to np.count_nonzero must be array-like") + + if is_nonelike(axis): + def impl(a, axis=None): + arr2 = np.ravel(a) + return np.sum(arr2 != 0) + return impl + else: + def impl(a, axis=None): + arr2 = a.astype(np.bool_) + return np.sum(arr2, axis=axis) + return impl + + +np_delete_handler_isslice = register_jitable(lambda x : x) +np_delete_handler_isarray = register_jitable(lambda x : np.asarray(x)) + + +@overload(np.delete) +def np_delete(arr, obj): + # Implementation based on numpy + # https://github.com/numpy/numpy/blob/af66e487a57bfd4850f4306e3b85d1dac3c70412/numpy/lib/function_base.py#L4065-L4267 # noqa: E501 + + if not isinstance(arr, (types.Array, types.Sequence)): + raise TypingError("arr must be either an Array or a Sequence") + + if isinstance(obj, (types.Array, types.Sequence, types.SliceType)): + if isinstance(obj, (types.SliceType)): + handler = np_delete_handler_isslice + else: + if not isinstance(obj.dtype, types.Integer): + raise TypingError('obj should be of Integer dtype') + handler = np_delete_handler_isarray + + def np_delete_impl(arr, obj): + arr = np.ravel(np.asarray(arr)) + N = arr.size + + keep = np.ones(N, dtype=np.bool_) + obj = handler(obj) + keep[obj] = False + return arr[keep] + return np_delete_impl + + else: # scalar value + if not isinstance(obj, types.Integer): + raise TypingError('obj should be of Integer dtype') + + def np_delete_scalar_impl(arr, obj): + arr = np.ravel(np.asarray(arr)) + N = arr.size + pos = obj + + if (pos < -N or pos >= N): + raise IndexError('obj must be less than the len(arr)') + # NumPy raises IndexError: index 'i' is out of + # bounds for axis 'x' with size 'n' + + if (pos < 0): + pos += N + + return np.concatenate((arr[:pos], arr[pos + 1:])) + return np_delete_scalar_impl + + +@overload(np.diff) +def np_diff_impl(a, n=1): + if not isinstance(a, types.Array) or a.ndim == 0: + return + + def diff_impl(a, n=1): + if n == 0: + return a.copy() + if n < 0: + raise ValueError("diff(): order must be non-negative") + size = a.shape[-1] + out_shape = a.shape[:-1] + (max(size - n, 0),) + out = np.empty(out_shape, a.dtype) + if out.size == 0: + return out + + # np.diff() works on each last dimension subarray independently. + # To make things easier, normalize input and output into 2d arrays + a2 = a.reshape((-1, size)) + out2 = out.reshape((-1, out.shape[-1])) + # A scratchpad for subarrays + work = np.empty(size, a.dtype) + + for major in range(a2.shape[0]): + # First iteration: diff a2 into work + for i in range(size - 1): + work[i] = a2[major, i + 1] - a2[major, i] + # Other iterations: diff work into itself + for niter in range(1, n): + for i in range(size - niter - 1): + work[i] = work[i + 1] - work[i] + # Copy final diff into out2 + out2[major] = work[:size - n] + + return out + + return diff_impl + + +@overload(np.array_equal) +def np_array_equal(a1, a2): + + if not (type_can_asarray(a1) and type_can_asarray(a2)): + raise TypingError('Both arguments to "array_equals" must be array-like') + + accepted = (types.Boolean, types.Number) + if isinstance(a1, accepted) and isinstance(a2, accepted): + # special case + def impl(a1, a2): + return a1 == a2 + else: + def impl(a1, a2): + a = np.asarray(a1) + b = np.asarray(a2) + if a.shape == b.shape: + return np.all(a == b) + return False + + return impl + + +@overload(np.intersect1d) +def jit_np_intersect1d(ar1, ar2, assume_unique=False): + # Not implemented to support return_indices + # https://github.com/numpy/numpy/blob/v1.19.0/numpy/lib + # /arraysetops.py#L347-L441 + if not (type_can_asarray(ar1) or type_can_asarray(ar2)): + raise TypingError('intersect1d: first two args must be array-like') + if not isinstance(assume_unique, (types.Boolean, bool)): + raise TypingError('intersect1d: ' + 'argument "assume_unique" must be boolean') + + def np_intersects1d_impl(ar1, ar2, assume_unique=False): + ar1 = np.asarray(ar1) + ar2 = np.asarray(ar2) + + if not assume_unique: + ar1 = np.unique(ar1) + ar2 = np.unique(ar2) + else: + ar1 = ar1.ravel() + ar2 = ar2.ravel() + + aux = np.concatenate((ar1, ar2)) + aux.sort() + mask = aux[1:] == aux[:-1] + int1d = aux[:-1][mask] + return int1d + return np_intersects1d_impl + + +def validate_1d_array_like(func_name, seq): + if isinstance(seq, types.Array): + if seq.ndim != 1: + raise NumbaTypeError("{0}(): input should have dimension 1" + .format(func_name)) + elif not isinstance(seq, types.Sequence): + raise NumbaTypeError("{0}(): input should be an array or sequence" + .format(func_name)) + + +@overload(np.bincount) +def np_bincount(a, weights=None, minlength=0): + validate_1d_array_like("bincount", a) + + if not isinstance(a.dtype, types.Integer): + return + + check_is_integer(minlength, 'minlength') + + if weights not in (None, types.none): + validate_1d_array_like("bincount", weights) + # weights is promoted to double in C impl + # https://github.com/numpy/numpy/blob/maintenance/1.16.x/numpy/core/src/multiarray/compiled_base.c#L93-L95 # noqa: E501 + out_dtype = np.float64 + + @register_jitable + def validate_inputs(a, weights, minlength): + if len(a) != len(weights): + raise ValueError("bincount(): weights and list don't have " + "the same length") + + @register_jitable + def count_item(out, idx, val, weights): + out[val] += weights[idx] + + else: + out_dtype = types.intp + + @register_jitable + def validate_inputs(a, weights, minlength): + pass + + @register_jitable + def count_item(out, idx, val, weights): + out[val] += 1 + + def bincount_impl(a, weights=None, minlength=0): + validate_inputs(a, weights, minlength) + if minlength < 0: + raise ValueError("'minlength' must not be negative") + + n = len(a) + a_max = a[0] if n > 0 else -1 + for i in range(1, n): + if a[i] < 0: + raise ValueError("bincount(): first argument must be " + "non-negative") + a_max = max(a_max, a[i]) + + out_length = max(a_max + 1, minlength) + out = np.zeros(out_length, out_dtype) + for i in range(n): + count_item(out, i, a[i], weights) + return out + + return bincount_impl + + +less_than_float = register_jitable(lt_floats) +less_than_complex = register_jitable(lt_complex) + + +@register_jitable +def less_than_or_equal_complex(a, b): + if np.isnan(a.real): + if np.isnan(b.real): + if np.isnan(a.imag): + return np.isnan(b.imag) + else: + if np.isnan(b.imag): + return True + else: + return a.imag <= b.imag + else: + return False + + else: + if np.isnan(b.real): + return True + else: + if np.isnan(a.imag): + if np.isnan(b.imag): + return a.real <= b.real + else: + return False + else: + if np.isnan(b.imag): + return True + else: + if a.real < b.real: + return True + elif a.real == b.real: + return a.imag <= b.imag + return False + + +@register_jitable +def _less_than_or_equal(a, b): + if isinstance(a, complex) or isinstance(b, complex): + return less_than_or_equal_complex(a, b) + + elif isinstance(b, (float, types.float32, types.float64)): + if np.isnan(b): + return True + + return a <= b + + +@register_jitable +def _less_than(a, b): + if isinstance(a, complex) or isinstance(b, complex): + return less_than_complex(a, b) + + elif isinstance(b, (float, types.float32, types.float64)): + return less_than_float(a, b) + + return a < b + + +@register_jitable +def _less_then_datetime64(a, b): + # Original numpy code is at: + # https://github.com/numpy/numpy/blob/3dad50936a8dc534a81a545365f69ee9ab162ffe/numpy/_core/src/npysort/npysort_common.h#L334-L346 + if np.isnat(a): + return 0 + + if np.isnat(b): + return 1 + + return a < b + + +@register_jitable +def _less_then_or_equal_datetime64(a, b): + return not _less_then_datetime64(b, a) + + +def _searchsorted(cmp): + # a facsimile of: + # https://github.com/numpy/numpy/blob/4f84d719657eb455a35fcdf9e75b83eb1f97024a/numpy/core/src/npysort/binsearch.cpp#L61 # noqa: E501 + + def impl(a, key_val, min_idx, max_idx): + while min_idx < max_idx: + # to avoid overflow + mid_idx = min_idx + ((max_idx - min_idx) >> 1) + mid_val = a[mid_idx] + if cmp(mid_val, key_val): + min_idx = mid_idx + 1 + else: + max_idx = mid_idx + return min_idx, max_idx + + return impl + + +VALID_SEARCHSORTED_SIDES = frozenset({'left', 'right'}) + + +def make_searchsorted_implementation(np_dtype, side): + assert side in VALID_SEARCHSORTED_SIDES + + if np_dtype.char in 'mM': + # is datetime + lt = _less_then_datetime64 + le = _less_then_or_equal_datetime64 + else: + lt = _less_than + le = _less_than_or_equal + + if side == 'left': + _impl = _searchsorted(lt) + _cmp = lt + else: + if np.issubdtype(np_dtype, np.inexact) and numpy_version < (1, 23): + # change in behaviour for inexact types + # introduced by: + # https://github.com/numpy/numpy/pull/21867 + _impl = _searchsorted(le) + _cmp = lt + else: + _impl = _searchsorted(le) + _cmp = le + + return register_jitable(_impl), register_jitable(_cmp) + + +@overload(np.searchsorted) +def searchsorted(a, v, side='left'): + side_val = getattr(side, 'literal_value', side) + + if side_val not in VALID_SEARCHSORTED_SIDES: + # could change this so that side doesn't need to be + # a compile-time constant + raise NumbaValueError(f"Invalid value given for 'side': {side_val}") + + if isinstance(v, (types.Array, types.Sequence)): + v_dt = as_dtype(v.dtype) + else: + v_dt = as_dtype(v) + + np_dt = np.promote_types(as_dtype(a.dtype), v_dt) + _impl, _cmp = make_searchsorted_implementation(np_dt, side_val) + + if isinstance(v, types.Array): + def impl(a, v, side='left'): + out = np.empty(v.size, dtype=np.intp) + last_key_val = v.flat[0] + min_idx = 0 + max_idx = len(a) + + for i in range(v.size): + key_val = v.flat[i] + + if _cmp(last_key_val, key_val): + max_idx = len(a) + else: + min_idx = 0 + if max_idx < len(a): + max_idx += 1 + else: + max_idx = len(a) + + last_key_val = key_val + min_idx, max_idx = _impl(a, key_val, min_idx, max_idx) + out[i] = min_idx + + return out.reshape(v.shape) + elif isinstance(v, types.Sequence): + def impl(a, v, side='left'): + v = np.asarray(v) + return np.searchsorted(a, v, side=side) + else: # presumably `v` is scalar + def impl(a, v, side='left'): + r, _ = _impl(a, v, 0, len(a)) + return r + return impl + + +@overload(np.digitize) +def np_digitize(x, bins, right=False): + + if isinstance(x, types.Array) and x.dtype in types.complex_domain: + raise TypingError('x may not be complex') + + @register_jitable + def _monotonicity(bins): + + # all bin edges hold the same value + if len(bins) == 0: + return 1 + + # Skip repeated values at the beginning of the array + last_value = bins[0] + i = 1 + while i < len(bins) and bins[i] == last_value: + i += 1 + + # all bin edges hold the same value + if i == len(bins): + return 1 + + next_value = bins[i] + + if last_value < next_value: + # Possibly monotonic increasing + for i in range(i + 1, len(bins)): + last_value = next_value + next_value = bins[i] + if last_value > next_value: + return 0 + return 1 + + else: + # last > next, possibly monotonic decreasing + for i in range(i + 1, len(bins)): + last_value = next_value + next_value = bins[i] + if last_value < next_value: + return 0 + return -1 + + def digitize_impl(x, bins, right=False): + + mono = _monotonicity(bins) + + if mono == 0: + raise ValueError( + "bins must be monotonically increasing or decreasing" + ) + + # this is backwards because the arguments below are swapped + if right: + if mono == -1: + # reverse the bins, and invert the results + return len(bins) - np.searchsorted(bins[::-1], x, side='left') + else: + return np.searchsorted(bins, x, side='left') + else: + if mono == -1: + # reverse the bins, and invert the results + return len(bins) - np.searchsorted(bins[::-1], x, side='right') + else: + return np.searchsorted(bins, x, side='right') + + return digitize_impl + + +_range = range + + +@overload(np.histogram) +def np_histogram(a, bins=10, range=None): + if isinstance(bins, (int, types.Integer)): + # With a uniform distribution of bins, use a fast algorithm + # independent of the number of bins + + if range in (None, types.none): + inf = float('inf') + + def histogram_impl(a, bins=10, range=None): + bin_min = inf + bin_max = -inf + for view in np.nditer(a): + v = view.item() + if bin_min > v: + bin_min = v + if bin_max < v: + bin_max = v + return np.histogram(a, bins, (bin_min, bin_max)) + + else: + def histogram_impl(a, bins=10, range=None): + if bins <= 0: + raise ValueError("histogram(): `bins` should be a " + "positive integer") + bin_min, bin_max = range + if not bin_min <= bin_max: + raise ValueError("histogram(): max must be larger than " + "min in range parameter") + + hist = np.zeros(bins, np.intp) + if bin_max > bin_min: + bin_ratio = bins / (bin_max - bin_min) + for view in np.nditer(a): + v = view.item() + b = math.floor((v - bin_min) * bin_ratio) + if 0 <= b < bins: + hist[int(b)] += 1 + elif v == bin_max: + hist[bins - 1] += 1 + + bins_array = np.linspace(bin_min, bin_max, bins + 1) + return hist, bins_array + + else: + # With a custom bins array, use a bisection search + + def histogram_impl(a, bins=10, range=None): + nbins = len(bins) - 1 + for i in _range(nbins): + # Note this also catches NaNs + if not bins[i] <= bins[i + 1]: + raise ValueError("histogram(): bins must increase " + "monotonically") + + bin_min = bins[0] + bin_max = bins[nbins] + hist = np.zeros(nbins, np.intp) + + if nbins > 0: + for view in np.nditer(a): + v = view.item() + if not bin_min <= v <= bin_max: + # Value is out of bounds, ignore (also catches NaNs) + continue + # Bisect in bins[:-1] + lo = 0 + hi = nbins - 1 + while lo < hi: + # Note the `+ 1` is necessary to avoid an infinite + # loop where mid = lo => lo = mid + mid = (lo + hi + 1) >> 1 + if v < bins[mid]: + hi = mid - 1 + else: + lo = mid + hist[lo] += 1 + + return hist, bins + + return histogram_impl + + +# Create np.finfo, np.iinfo and np.MachAr +# machar +_mach_ar_supported = ('ibeta', 'it', 'machep', 'eps', 'negep', 'epsneg', + 'iexp', 'minexp', 'xmin', 'maxexp', 'xmax', 'irnd', + 'ngrd', 'epsilon', 'tiny', 'huge', 'precision', + 'resolution',) +MachAr = namedtuple('MachAr', _mach_ar_supported) + +# Do not support MachAr field +# finfo +_finfo_supported = ('eps', 'epsneg', 'iexp', 'machep', 'max', 'maxexp', 'min', + 'minexp', 'negep', 'nexp', 'nmant', 'precision', + 'resolution', 'tiny', 'bits',) + + +finfo = namedtuple('finfo', _finfo_supported) + +# iinfo +_iinfo_supported = ('min', 'max', 'bits',) + +iinfo = namedtuple('iinfo', _iinfo_supported) + + +# This module is imported under the compiler lock which should deal with the +# lack of thread safety in the warning filter. +def _gen_np_machar(): + # NumPy 1.24 removed np.MachAr + if numpy_version >= (1, 24): + return + + w = None + with warnings.catch_warnings(record=True) as w: + msg = r'`np.MachAr` is deprecated \(NumPy 1.22\)' + warnings.filterwarnings("always", message=msg, + category=DeprecationWarning, + module=r'.*numba.*arraymath') + np_MachAr = np.MachAr + + @overload(np_MachAr) + def MachAr_impl(): + f = np_MachAr() + _mach_ar_data = tuple([getattr(f, x) for x in _mach_ar_supported]) + + if w: + wmsg = w[0] + warnings.warn_explicit(wmsg.message.args[0], + NumbaDeprecationWarning, + wmsg.filename, + wmsg.lineno) + + def impl(): + return MachAr(*_mach_ar_data) + return impl + + +_gen_np_machar() + + +def generate_xinfo_body(arg, np_func, container, attr): + nbty = getattr(arg, 'dtype', arg) + np_dtype = as_dtype(nbty) + try: + f = np_func(np_dtype) + except ValueError: # This exception instance comes from NumPy + # The np function might not support the dtype + return None + data = tuple([getattr(f, x) for x in attr]) + + @register_jitable + def impl(arg): + return container(*data) + return impl + + +@overload(np.finfo) +def ol_np_finfo(dtype): + fn = generate_xinfo_body(dtype, np.finfo, finfo, _finfo_supported) + + def impl(dtype): + return fn(dtype) + return impl + + +@overload(np.iinfo) +def ol_np_iinfo(int_type): + fn = generate_xinfo_body(int_type, np.iinfo, iinfo, _iinfo_supported) + + def impl(int_type): + return fn(int_type) + return impl + + +def _get_inner_prod(dta, dtb): + # gets an inner product implementation, if both types are float then + # BLAS is used else a local function + + @register_jitable + def _innerprod(a, b): + acc = 0 + for i in range(len(a)): + acc = acc + a[i] * b[i] + return acc + + # no BLAS... use local function regardless + if not _HAVE_BLAS: + return _innerprod + + flty = types.real_domain | types.complex_domain + floats = dta in flty and dtb in flty + if not floats: + return _innerprod + else: + a_dt = as_dtype(dta) + b_dt = as_dtype(dtb) + dt = np.promote_types(a_dt, b_dt) + + @register_jitable + def _dot_wrap(a, b): + return np.dot(a.astype(dt), b.astype(dt)) + return _dot_wrap + + +def _assert_1d(a, func_name): + if isinstance(a, types.Array): + if not a.ndim <= 1: + raise TypingError("%s() only supported on 1D arrays " % func_name) + + +def _np_correlate_core(ap1, ap2, mode, direction): + pass + + +@overload(_np_correlate_core) +def _np_correlate_core_impl(ap1, ap2, mode, direction): + a_dt = as_dtype(ap1.dtype) + b_dt = as_dtype(ap2.dtype) + dt = np.promote_types(a_dt, b_dt) + innerprod = _get_inner_prod(ap1.dtype, ap2.dtype) + + def impl(ap1, ap2, mode, direction): + # Implementation loosely based on `_pyarray_correlate` from + # https://github.com/numpy/numpy/blob/3bce2be74f228684ca2895ad02b63953f37e2a9d/numpy/core/src/multiarray/multiarraymodule.c#L1191 # noqa: E501 + # For "mode": + # Convolve uses 'full' by default. + # Correlate uses 'valid' by default. + # For "direction", +1 to write the return values out in order 0->N + # -1 to write them out N->0. + + n1 = len(ap1) + n2 = len(ap2) + + if n1 < n2: + # This should never occur when called by np.convolve because + # _np_correlate.impl swaps arguments based on length. + # The same applies for np.correlate. + raise ValueError("'len(ap1)' must greater than 'len(ap2)'") + + length = n1 + n = n2 + if mode == "valid": + length = length - n + 1 + n_left = 0 + n_right = 0 + elif mode == "full": + n_right = n - 1 + n_left = n - 1 + length = length + n - 1 + elif mode == "same": + n_left = n // 2 + n_right = n - n_left - 1 + else: + raise ValueError( + "Invalid 'mode', " + "valid are 'full', 'same', 'valid'" + ) + + ret = np.zeros(length, dt) + + if direction == 1: + idx = 0 + inc = 1 + elif direction == -1: + idx = length - 1 + inc = -1 + else: + raise ValueError("Invalid direction") + + for i in range(n_left): + k = i + n - n_left + ret[idx] = innerprod(ap1[:k], ap2[-k:]) + idx = idx + inc + + for i in range(n1 - n2 + 1): + ret[idx] = innerprod(ap1[i : i + n2], ap2) + idx = idx + inc + + for i in range(n_right): + k = n - i - 1 + ret[idx] = innerprod(ap1[-k:], ap2[:k]) + idx = idx + inc + + return ret + + return impl + + +@overload(np.correlate) +def _np_correlate(a, v, mode="valid"): + _assert_1d(a, 'np.correlate') + _assert_1d(v, 'np.correlate') + + @register_jitable + def op_conj(x): + return np.conj(x) + + @register_jitable + def op_nop(x): + return x + + if a.dtype in types.complex_domain: + if v.dtype in types.complex_domain: + a_op = op_nop + b_op = op_conj + else: + a_op = op_nop + b_op = op_nop + else: + if v.dtype in types.complex_domain: + a_op = op_nop + b_op = op_conj + else: + a_op = op_conj + b_op = op_nop + + def impl(a, v, mode="valid"): + la = len(a) + lv = len(v) + + if la == 0: + raise ValueError("'a' cannot be empty") + if lv == 0: + raise ValueError("'v' cannot be empty") + + if la < lv: + return _np_correlate_core(b_op(v), a_op(a), mode, -1) + else: + return _np_correlate_core(a_op(a), b_op(v), mode, 1) + + return impl + + +@overload(np.convolve) +def np_convolve(a, v, mode="full"): + _assert_1d(a, 'np.convolve') + _assert_1d(v, 'np.convolve') + + def impl(a, v, mode="full"): + la = len(a) + lv = len(v) + + if la == 0: + raise ValueError("'a' cannot be empty") + if lv == 0: + raise ValueError("'v' cannot be empty") + + if la < lv: + return _np_correlate_core(v, a[::-1], mode, 1) + else: + return _np_correlate_core(a, v[::-1], mode, 1) + + return impl + + +@overload(np.asarray) +def np_asarray(a, dtype=None): + + # developer note... keep this function (type_can_asarray) in sync with the + # accepted types implementations below! + if not type_can_asarray(a): + return None + + if isinstance(a, types.Array): + if is_nonelike(dtype) or a.dtype == dtype.dtype: + def impl(a, dtype=None): + return a + else: + def impl(a, dtype=None): + return a.astype(dtype) + elif isinstance(a, (types.Sequence, types.Tuple)): + # Nested lists cannot be unpacked, therefore only single lists are + # permitted and these conform to Sequence and can be unpacked along on + # the same path as Tuple. + if is_nonelike(dtype): + def impl(a, dtype=None): + return np.array(a) + else: + def impl(a, dtype=None): + return np.array(a, dtype) + elif isinstance(a, (types.Number, types.Boolean)): + dt_conv = a if is_nonelike(dtype) else dtype + ty = as_dtype(dt_conv) + + def impl(a, dtype=None): + return np.array(a, ty) + elif isinstance(a, types.containers.ListType): + if not isinstance(a.dtype, (types.Number, types.Boolean)): + raise TypingError( + "asarray support for List is limited " + "to Boolean and Number types") + + target_dtype = a.dtype if is_nonelike(dtype) else dtype + + def impl(a, dtype=None): + l = len(a) + ret = np.empty(l, dtype=target_dtype) + for i, v in enumerate(a): + ret[i] = v + return ret + elif isinstance(a, types.StringLiteral): + arr = np.asarray(a.literal_value) + + def impl(a, dtype=None): + return arr.copy() + else: + impl = None + + return impl + + +if numpy_version < (2, 0): + @overload(np.asfarray) + def np_asfarray(a, dtype=np.float64): + # convert numba dtype types into NumPy dtype + if isinstance(dtype, types.Type): + dtype = as_dtype(dtype) + if not np.issubdtype(dtype, np.inexact): + dx = types.float64 + else: + dx = dtype + + def impl(a, dtype=np.float64): + return np.asarray(a, dx) + return impl + + +@overload(np.extract) +def np_extract(condition, arr): + + def np_extract_impl(condition, arr): + cond = np.asarray(condition).flatten() + a = np.asarray(arr) + + if a.size == 0: + raise ValueError('Cannot extract from an empty array') + + # the following looks odd but replicates NumPy... + # https://github.com/numpy/numpy/issues/12859 + if np.any(cond[a.size:]) and cond.size > a.size: + msg = 'condition shape inconsistent with arr shape' + raise ValueError(msg) + # NumPy raises IndexError: index 'm' is out of + # bounds for size 'n' + + max_len = min(a.size, cond.size) + out = [a.flat[idx] for idx in range(max_len) if cond[idx]] + + return np.array(out) + + return np_extract_impl + + +@overload(np.select) +def np_select(condlist, choicelist, default=0): + + def np_select_arr_impl(condlist, choicelist, default=0): + if len(condlist) != len(choicelist): + raise ValueError('list of cases must be same length as list ' + 'of conditions') + out = default * np.ones(choicelist[0].shape, choicelist[0].dtype) + # should use reversed+zip, but reversed is not available + for i in range(len(condlist) - 1, -1, -1): + cond = condlist[i] + choice = choicelist[i] + out = np.where(cond, choice, out) + return out + + # first we check the types of the input parameters + if not isinstance(condlist, (types.List, types.UniTuple)): + raise NumbaTypeError('condlist must be a List or a Tuple') + if not isinstance(choicelist, (types.List, types.UniTuple)): + raise NumbaTypeError('choicelist must be a List or a Tuple') + if not isinstance(default, (int, types.Number, types.Boolean)): + raise NumbaTypeError('default must be a scalar (number or boolean)') + # the types of the parameters have been checked, now we test the types + # of the content of the parameters + # implementation note: if in the future numba's np.where accepts tuples + # as elements of condlist, then the check below should be extended to + # accept tuples + if not isinstance(condlist[0], types.Array): + raise NumbaTypeError('items of condlist must be arrays') + if not isinstance(choicelist[0], types.Array): + raise NumbaTypeError('items of choicelist must be arrays') + # the types of the parameters and their contents have been checked, + # now we test the dtypes of the content of parameters + if isinstance(condlist[0], types.Array): + if not isinstance(condlist[0].dtype, types.Boolean): + raise NumbaTypeError('condlist arrays must contain booleans') + if isinstance(condlist[0], types.UniTuple): + if not (isinstance(condlist[0], types.UniTuple) + and isinstance(condlist[0][0], types.Boolean)): + raise NumbaTypeError('condlist tuples must only contain booleans') + # the input types are correct, now we perform checks on the dimensions + if (isinstance(condlist[0], types.Array) and + condlist[0].ndim != choicelist[0].ndim): + raise NumbaTypeError('condlist and choicelist elements must have the ' + 'same number of dimensions') + if isinstance(condlist[0], types.Array) and condlist[0].ndim < 1: + raise NumbaTypeError('condlist arrays must be of at least dimension 1') + + return np_select_arr_impl + + +@overload(np.union1d) +def np_union1d(ar1, ar2): + if not type_can_asarray(ar1) or not type_can_asarray(ar2): + raise TypingError("The arguments to np.union1d must be array-like") + if (('unichr' in ar1.dtype.name or 'unichr' in ar2.dtype.name) and + ar1.dtype.name != ar2.dtype.name): + raise TypingError("For Unicode arrays, arrays must have same dtype") + + def union_impl(ar1, ar2): + a = np.ravel(np.asarray(ar1)) + b = np.ravel(np.asarray(ar2)) + return np.unique(np.concatenate((a, b))) + + return union_impl + + +@overload(np.asarray_chkfinite) +def np_asarray_chkfinite(a, dtype=None): + + msg = "The argument to np.asarray_chkfinite must be array-like" + if not isinstance(a, (types.Array, types.Sequence, types.Tuple)): + raise TypingError(msg) + + if is_nonelike(dtype): + dt = a.dtype + else: + try: + dt = as_dtype(dtype) + except NumbaNotImplementedError: + raise TypingError('dtype must be a valid Numpy dtype') + + def impl(a, dtype=None): + a = np.asarray(a, dtype=dt) + for i in np.nditer(a): + if not np.isfinite(i): + raise ValueError("array must not contain infs or NaNs") + return a + + return impl + + +@overload(np.unwrap) +def numpy_unwrap(p, discont=None, axis=-1, period=6.283185307179586): + if not isinstance(axis, (int, types.Integer)): + msg = 'The argument "axis" must be an integer' + raise TypingError(msg) + + if not type_can_asarray(p): + msg = 'The argument "p" must be array-like' + raise TypingError(msg) + + if (not isinstance(discont, (types.Integer, types.Float)) + and not cgutils.is_nonelike(discont)): + msg = 'The argument "discont" must be a scalar' + raise TypingError(msg) + + if not isinstance(period, (float, types.Number)): + msg = 'The argument "period" must be a scalar' + raise TypingError(msg) + + slice1 = (slice(1, None, None),) + if isinstance(period, types.Number): + dtype = np.result_type(as_dtype(p.dtype), as_dtype(period)) + else: + dtype = np.result_type(as_dtype(p.dtype), np.float64) + + integer_input = np.issubdtype(dtype, np.integer) + + def impl(p, discont=None, axis=-1, period=6.283185307179586): + if axis != -1: + msg = 'Value for argument "axis" is not supported' + raise ValueError(msg) + # Flatten to a 2D array, keeping axis -1 + p_init = np.asarray(p).astype(dtype) + init_shape = p_init.shape + last_axis = init_shape[-1] + p_new = p_init.reshape((p_init.size // last_axis, last_axis)) + # Manipulate discont and period + if discont is None: + discont = period / 2 + if integer_input: + interval_high, rem = divmod(period, 2) + boundary_ambiguous = rem == 0 + else: + interval_high = period / 2 + boundary_ambiguous = True + interval_low = -interval_high + + # Work on each row separately + for i in range(p_init.size // last_axis): + row = p_new[i] + dd = np.diff(row) + ddmod = np.mod(dd - interval_low, period) + interval_low + if boundary_ambiguous: + ddmod = np.where((ddmod == interval_low) & (dd > 0), + interval_high, ddmod) + ph_correct = ddmod - dd + + ph_correct = np.where(np.array([abs(x) for x in dd]) < discont, 0, + ph_correct) + ph_ravel = np.where(np.array([abs(x) for x in dd]) < discont, 0, + ph_correct) + ph_correct = np.reshape(ph_ravel, ph_correct.shape) + up = np.copy(row) + up[slice1] = row[slice1] + ph_correct.cumsum() + p_new[i] = up + + return p_new.reshape(init_shape) + + return impl + +#---------------------------------------------------------------------------- +# Windowing functions +# - translated from the numpy implementations found in: +# https://github.com/numpy/numpy/blob/v1.16.1/numpy/lib/function_base.py#L2543-L3233 # noqa: E501 +# at commit: f1c4c758e1c24881560dd8ab1e64ae750 +# - and also, for NumPy >= 1.20, translated from implementations in +# https://github.com/numpy/numpy/blob/156cd054e007b05d4ac4829e10a369d19dd2b0b1/numpy/lib/function_base.py#L2655-L3065 # noqa: E501 + + +@register_jitable +def np_bartlett_impl(M): + n = np.arange(1. - M, M, 2) + return np.where(np.less_equal(n, 0), 1 + n / (M - 1), 1 - n / (M - 1)) + + +@register_jitable +def np_blackman_impl(M): + n = np.arange(1. - M, M, 2) + return (0.42 + 0.5 * np.cos(np.pi * n / (M - 1)) + + 0.08 * np.cos(2.0 * np.pi * n / (M - 1))) + + +@register_jitable +def np_hamming_impl(M): + n = np.arange(1 - M, M, 2) + return 0.54 + 0.46 * np.cos(np.pi * n / (M - 1)) + + +@register_jitable +def np_hanning_impl(M): + n = np.arange(1 - M, M, 2) + return 0.5 + 0.5 * np.cos(np.pi * n / (M - 1)) + + +def window_generator(func): + def window_overload(M): + if not isinstance(M, types.Integer): + raise TypingError('M must be an integer') + + def window_impl(M): + + if M < 1: + return np.array((), dtype=np.float64) + if M == 1: + return np.ones(1, dtype=np.float64) + return func(M) + + return window_impl + return window_overload + + +overload(np.bartlett)(window_generator(np_bartlett_impl)) +overload(np.blackman)(window_generator(np_blackman_impl)) +overload(np.hamming)(window_generator(np_hamming_impl)) +overload(np.hanning)(window_generator(np_hanning_impl)) + + +_i0A = np.array([ + -4.41534164647933937950E-18, + 3.33079451882223809783E-17, + -2.43127984654795469359E-16, + 1.71539128555513303061E-15, + -1.16853328779934516808E-14, + 7.67618549860493561688E-14, + -4.85644678311192946090E-13, + 2.95505266312963983461E-12, + -1.72682629144155570723E-11, + 9.67580903537323691224E-11, + -5.18979560163526290666E-10, + 2.65982372468238665035E-9, + -1.30002500998624804212E-8, + 6.04699502254191894932E-8, + -2.67079385394061173391E-7, + 1.11738753912010371815E-6, + -4.41673835845875056359E-6, + 1.64484480707288970893E-5, + -5.75419501008210370398E-5, + 1.88502885095841655729E-4, + -5.76375574538582365885E-4, + 1.63947561694133579842E-3, + -4.32430999505057594430E-3, + 1.05464603945949983183E-2, + -2.37374148058994688156E-2, + 4.93052842396707084878E-2, + -9.49010970480476444210E-2, + 1.71620901522208775349E-1, + -3.04682672343198398683E-1, + 6.76795274409476084995E-1, +]) + +_i0B = np.array([ + -7.23318048787475395456E-18, + -4.83050448594418207126E-18, + 4.46562142029675999901E-17, + 3.46122286769746109310E-17, + -2.82762398051658348494E-16, + -3.42548561967721913462E-16, + 1.77256013305652638360E-15, + 3.81168066935262242075E-15, + -9.55484669882830764870E-15, + -4.15056934728722208663E-14, + 1.54008621752140982691E-14, + 3.85277838274214270114E-13, + 7.18012445138366623367E-13, + -1.79417853150680611778E-12, + -1.32158118404477131188E-11, + -3.14991652796324136454E-11, + 1.18891471078464383424E-11, + 4.94060238822496958910E-10, + 3.39623202570838634515E-9, + 2.26666899049817806459E-8, + 2.04891858946906374183E-7, + 2.89137052083475648297E-6, + 6.88975834691682398426E-5, + 3.36911647825569408990E-3, + 8.04490411014108831608E-1, +]) + + +@register_jitable +def _chbevl(x, vals): + b0 = vals[0] + b1 = 0.0 + + for i in range(1, len(vals)): + b2 = b1 + b1 = b0 + b0 = x * b1 - b2 + vals[i] + + return 0.5 * (b0 - b2) + + +@register_jitable +def _i0(x): + if x < 0: + x = -x + if x <= 8.0: + y = (0.5 * x) - 2.0 + return np.exp(x) * _chbevl(y, _i0A) + + return np.exp(x) * _chbevl(32.0 / x - 2.0, _i0B) / np.sqrt(x) + + +@register_jitable +def _i0n(n, alpha, beta): + y = np.empty_like(n, dtype=np.float64) + t = _i0(np.float64(beta)) + for i in range(len(y)): + y[i] = _i0(beta * np.sqrt(1 - ((n[i] - alpha) / alpha)**2.0)) / t + + return y + + +@overload(np.kaiser) +def np_kaiser(M, beta): + if not isinstance(M, types.Integer): + raise TypingError('M must be an integer') + + if not isinstance(beta, (types.Integer, types.Float)): + raise TypingError('beta must be an integer or float') + + def np_kaiser_impl(M, beta): + if M < 1: + return np.array((), dtype=np.float64) + if M == 1: + return np.ones(1, dtype=np.float64) + + n = np.arange(0, M) + alpha = (M - 1) / 2.0 + + return _i0n(n, alpha, beta) + + return np_kaiser_impl + + +@register_jitable +def _cross_operation(a, b, out): + + def _cross_preprocessing(x): + x0 = x[..., 0] + x1 = x[..., 1] + if x.shape[-1] == 3: + x2 = x[..., 2] + else: + x2 = np.multiply(x.dtype.type(0), x0) + return x0, x1, x2 + + a0, a1, a2 = _cross_preprocessing(a) + b0, b1, b2 = _cross_preprocessing(b) + + cp0 = np.multiply(a1, b2) - np.multiply(a2, b1) + cp1 = np.multiply(a2, b0) - np.multiply(a0, b2) + cp2 = np.multiply(a0, b1) - np.multiply(a1, b0) + + out[..., 0] = cp0 + out[..., 1] = cp1 + out[..., 2] = cp2 + + +def _cross(a, b): + pass + + +@overload(_cross) +def _cross_impl(a, b): + dtype = np.promote_types(as_dtype(a.dtype), as_dtype(b.dtype)) + if a.ndim == 1 and b.ndim == 1: + def impl(a, b): + cp = np.empty((3,), dtype) + _cross_operation(a, b, cp) + return cp + else: + def impl(a, b): + shape = np.add(a[..., 0], b[..., 0]).shape + cp = np.empty(shape + (3,), dtype) + _cross_operation(a, b, cp) + return cp + return impl + + +@overload(np.cross) +def np_cross(a, b): + if not type_can_asarray(a) or not type_can_asarray(b): + raise TypingError("Inputs must be array-like.") + + def impl(a, b): + a_ = np.asarray(a) + b_ = np.asarray(b) + if a_.shape[-1] not in (2, 3) or b_.shape[-1] not in (2, 3): + raise ValueError(( + "Incompatible dimensions for cross product\n" + "(dimension must be 2 or 3)" + )) + + if a_.shape[-1] == 3 or b_.shape[-1] == 3: + return _cross(a_, b_) + else: + raise ValueError(( + "Dimensions for both inputs is 2.\n" + "Please replace your numpy.cross(a, b) call with " + "a call to `cross2d(a, b)` from `numba.np.extensions`." + )) + return impl + + +@register_jitable +def _cross2d_operation(a, b): + + def _cross_preprocessing(x): + x0 = x[..., 0] + x1 = x[..., 1] + return x0, x1 + + a0, a1 = _cross_preprocessing(a) + b0, b1 = _cross_preprocessing(b) + + cp = np.multiply(a0, b1) - np.multiply(a1, b0) + # If ndim of a and b is 1, cp is a scalar. + # In this case np.cross returns a 0-D array, containing the scalar. + # np.asarray is used to reconcile this case, without introducing + # overhead in the case where cp is an actual N-D array. + # (recall that np.asarray does not copy existing arrays) + return np.asarray(cp) + + +def cross2d(a, b): + pass + + +@overload(cross2d) +def cross2d_impl(a, b): + if not type_can_asarray(a) or not type_can_asarray(b): + raise TypingError("Inputs must be array-like.") + + def impl(a, b): + a_ = np.asarray(a) + b_ = np.asarray(b) + if a_.shape[-1] != 2 or b_.shape[-1] != 2: + raise ValueError(( + "Incompatible dimensions for 2D cross product\n" + "(dimension must be 2 for both inputs)" + )) + return _cross2d_operation(a_, b_) + + return impl + + +@overload(np.trim_zeros) +def np_trim_zeros(filt, trim='fb'): + if not isinstance(filt, types.Array): + raise NumbaTypeError('The first argument must be an array') + + if filt.ndim > 1: + raise NumbaTypeError('array must be 1D') + + if not isinstance(trim, (str, types.UnicodeType)): + raise NumbaTypeError('The second argument must be a string') + + trim_escapes = numpy_version >= (2, 2) + + def impl(filt, trim='fb'): + a_ = np.asarray(filt) + first = 0 + trim = trim.lower() + if 'f' in trim: + for i in a_: + if i == 0 or (trim_escapes and i == ''): + first = first + 1 + else: + break + last = len(filt) + if 'b' in trim: + for i in a_[::-1]: + if i == 0 or (trim_escapes and i == ''): + last = last - 1 + else: + break + return a_[first:last] + + return impl + + +@overload(np.setxor1d) +def jit_np_setxor1d(ar1, ar2, assume_unique=False): + if not (type_can_asarray(ar1) or type_can_asarray(ar2)): + raise TypingError('setxor1d: first two args must be array-like') + if not (isinstance(assume_unique, (types.Boolean, bool))): + raise TypingError('setxor1d: Argument "assume_unique" must be boolean') + + # https://github.com/numpy/numpy/blob/03b62604eead0f7d279a5a4c094743eb29647368/numpy/lib/arraysetops.py#L477 # noqa: E501 + def np_setxor1d_impl(ar1, ar2, assume_unique=False): + a = np.asarray(ar1) + b = np.asarray(ar2) + + if not assume_unique: + a = np.unique(a) + b = np.unique(b) + else: + a = a.ravel() + b = b.ravel() + + # Implementation very similar to np_intersect1d_impl: + # We want union minus the intersect + aux = np.concatenate((a, b)) + aux.sort() + + flag = np.empty(aux.shape[0] + 1, dtype=np.bool_) + flag[0] = True + flag[-1] = True + flag[1:-1] = aux[1:] != aux[:-1] + return aux[flag[1:] & flag[:-1]] + + return np_setxor1d_impl + + +# Internal helper for in1d functionality, used by isin and setdiff1d +# This is needed because np.in1d was removed in NumPy 2.4 +@register_jitable +def _in1d_impl(ar1, ar2, assume_unique=False, invert=False): + # https://github.com/numpy/numpy/blob/03b62604eead0f7d279a5a4c094743eb29647368/numpy/lib/arraysetops.py#L525 # noqa: E501 + + # Ravel both arrays, behavior for the first array could be different + ar1 = np.asarray(ar1).ravel() + ar2 = np.asarray(ar2).ravel() + + # This code is run when it would make the code significantly faster + # Sorting is also not guaranteed to work on objects but numba does + # not support object arrays. + if len(ar2) < 10 * len(ar1) ** 0.145: + if invert: + mask = np.ones(len(ar1), dtype=np.bool_) + for a in ar2: + mask &= (ar1 != a) + else: + mask = np.zeros(len(ar1), dtype=np.bool_) + for a in ar2: + mask |= (ar1 == a) + return mask + + # Otherwise use sorting + if not assume_unique: + # Equivalent to ar1, inv_idx = np.unique(ar1, return_inverse=True) + # https://github.com/numpy/numpy/blob/03b62604eead0f7d279a5a4c094743eb29647368/numpy/lib/arraysetops.py#L358C8-L358C8 # noqa: E501 + order1 = np.argsort(ar1) + aux = ar1[order1] + mask = np.empty(aux.shape, dtype=np.bool_) + mask[:1] = True + mask[1:] = aux[1:] != aux[:-1] + ar1 = aux[mask] + imask = np.cumsum(mask) - 1 + inv_idx = np.empty(mask.shape, dtype=np.intp) + inv_idx[order1] = imask + ar2 = np.unique(ar2) + + ar = np.concatenate((ar1, ar2)) + # We need this to be a stable sort, so always use 'mergesort' + # here. The values from the first array should always come before + # the values from the second array. + order = ar.argsort(kind='mergesort') + sar = ar[order] + flag = np.empty(sar.size, np.bool_) + if invert: + flag[:-1] = (sar[1:] != sar[:-1]) + else: + flag[:-1] = (sar[1:] == sar[:-1]) + flag[-1:] = invert + ret = np.empty(ar.shape, dtype=np.bool_) + ret[order] = flag + + # return ret[:len(ar1)] + if assume_unique: + return ret[:len(ar1)] + else: + return ret[inv_idx] + + +@overload(np.setdiff1d) +def jit_np_setdiff1d(ar1, ar2, assume_unique=False): + if not (type_can_asarray(ar1) or type_can_asarray(ar2)): + raise TypingError('setdiff1d: first two args must be array-like') + if not (isinstance(assume_unique, (types.Boolean, bool))): + raise TypingError('setdiff1d: Argument "assume_unique" must be boolean') + + # https://github.com/numpy/numpy/blob/03b62604eead0f7d279a5a4c094743eb29647368/numpy/lib/arraysetops.py#L940 # noqa: E501 + def np_setdiff1d_impl(ar1, ar2, assume_unique=False): + ar1 = np.asarray(ar1) + ar2 = np.asarray(ar2) + if assume_unique: + ar1 = ar1.ravel() + ar2 = ar2.ravel() + else: + ar1 = np.unique(ar1) + ar2 = np.unique(ar2) + return ar1[_in1d_impl(ar1, ar2, assume_unique=True, invert=True)] + + return np_setdiff1d_impl + + +def jit_np_in1d(ar1, ar2, assume_unique=False, invert=False): + if not (type_can_asarray(ar1) or type_can_asarray(ar2)): + raise TypingError('in1d: first two args must be array-like') + if not isinstance(assume_unique, (types.Boolean, bool)): + raise TypingError('in1d: Argument "assume_unique" must be boolean') + if not isinstance(invert, (types.Boolean, bool)): + raise TypingError('in1d: Argument "invert" must be boolean') + + def np_in1d_impl(ar1, ar2, assume_unique=False, invert=False): + return _in1d_impl(ar1, ar2, assume_unique, invert) + + return np_in1d_impl + + +# np.in1d was removed in NumPy 2.4 +if numpy_version < (2, 4): + overload(np.in1d)(jit_np_in1d) + + +@overload(np.isin) +def jit_np_isin(element, test_elements, assume_unique=False, invert=False): + if not (type_can_asarray(element) or type_can_asarray(test_elements)): + raise TypingError('isin: first two args must be array-like') + if not (isinstance(assume_unique, (types.Boolean, bool))): + raise TypingError('isin: Argument "assume_unique" must be boolean') + if not (isinstance(invert, (types.Boolean, bool))): + raise TypingError('isin: Argument "invert" must be boolean') + + # https://github.com/numpy/numpy/blob/03b62604eead0f7d279a5a4c094743eb29647368/numpy/lib/arraysetops.py#L889 # noqa: E501 + def np_isin_impl(element, test_elements, assume_unique=False, invert=False): + + element = np.asarray(element) + return _in1d_impl(element, test_elements, assume_unique=assume_unique, + invert=invert).reshape(element.shape) + + return np_isin_impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arrayobj.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arrayobj.py new file mode 100644 index 0000000000000000000000000000000000000000..ef31d9dd2422eff774865a5d5dbd6d38c5603314 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/arrayobj.py @@ -0,0 +1,7296 @@ +""" +Implementation of operations on Array objects and objects supporting +the buffer protocol. +""" + +import functools +import math +import operator +import textwrap + +from llvmlite import ir +from llvmlite.ir import Constant + +import numpy as np + +from numba import pndindex, literal_unroll +from numba.core import types, typing, errors, cgutils, extending +from numba.np.numpy_support import (as_dtype, from_dtype, carray, farray, + is_contiguous, is_fortran, + check_is_integer, type_is_scalar, + lt_complex, lt_floats) +from numba.np.numpy_support import type_can_asarray, is_nonelike, numpy_version +from numba.core.imputils import (lower_builtin, lower_getattr, + lower_getattr_generic, + lower_setattr_generic, + lower_cast, lower_constant, + iternext_impl, impl_ret_borrowed, + impl_ret_new_ref, impl_ret_untracked, + RefType) +from numba.core.typing import signature +from numba.core.types import StringLiteral +from numba.core.extending import (register_jitable, overload, overload_method, + intrinsic, overload_attribute) +from numba.misc import quicksort, mergesort +from numba.cpython import slicing +from numba.cpython.charseq import _make_constant_bytes, bytes_type +from numba.cpython.unsafe.tuple import tuple_setitem, build_full_slice_tuple +from numba.core.extending import overload_classmethod +from numba.core.typing.npydecl import (parse_dtype as ty_parse_dtype, + parse_shape as ty_parse_shape, + _parse_nested_sequence, + _sequence_of_arrays, + _choose_concatenation_layout) + + +def set_range_metadata(builder, load, lower_bound, upper_bound): + """ + Set the "range" metadata on a load instruction. + Note the interval is in the form [lower_bound, upper_bound). + """ + range_operands = [Constant(load.type, lower_bound), + Constant(load.type, upper_bound)] + md = builder.module.add_metadata(range_operands) + load.set_metadata("range", md) + + +def mark_positive(builder, load): + """ + Mark the result of a load instruction as positive (or zero). + """ + upper_bound = (1 << (load.type.width - 1)) - 1 + set_range_metadata(builder, load, 0, upper_bound) + + +def make_array(array_type): + """ + Return the Structure representation of the given *array_type* + (an instance of types.ArrayCompatible). + + Note this does not call __array_wrap__ in case a new array structure + is being created (rather than populated). + """ + real_array_type = array_type.as_array + base = cgutils.create_struct_proxy(real_array_type) + ndim = real_array_type.ndim + + class ArrayStruct(base): + + def _make_refs(self, ref): + sig = signature(real_array_type, array_type) + try: + array_impl = self._context.get_function('__array__', sig) + except NotImplementedError: + return super(ArrayStruct, self)._make_refs(ref) + + # Return a wrapped structure and its unwrapped reference + datamodel = self._context.data_model_manager[array_type] + be_type = self._get_be_type(datamodel) + if ref is None: + outer_ref = cgutils.alloca_once(self._builder, be_type, + zfill=True) + else: + outer_ref = ref + # NOTE: __array__ is called with a pointer and expects a pointer + # in return! + ref = array_impl(self._builder, (outer_ref,)) + return outer_ref, ref + + @property + def shape(self): + """ + Override .shape to inform LLVM that its elements are all positive. + """ + builder = self._builder + if ndim == 0: + return base.__getattr__(self, "shape") + + # Unfortunately, we can't use llvm.assume as its presence can + # seriously pessimize performance, + # *and* the range metadata currently isn't improving anything here, + # see https://llvm.org/bugs/show_bug.cgi?id=23848 ! + ptr = self._get_ptr_by_name("shape") + dims = [] + for i in range(ndim): + dimptr = cgutils.gep_inbounds(builder, ptr, 0, i) + load = builder.load(dimptr) + dims.append(load) + mark_positive(builder, load) + + return cgutils.pack_array(builder, dims) + + return ArrayStruct + + +def get_itemsize(context, array_type): + """ + Return the item size for the given array or buffer type. + """ + llty = context.get_data_type(array_type.dtype) + return context.get_abi_sizeof(llty) + + +def load_item(context, builder, arrayty, ptr): + """ + Load the item at the given array pointer. + """ + align = None if arrayty.aligned else 1 + return context.unpack_value(builder, arrayty.dtype, ptr, + align=align) + + +def store_item(context, builder, arrayty, val, ptr): + """ + Store the item at the given array pointer. + """ + align = None if arrayty.aligned else 1 + return context.pack_value(builder, arrayty.dtype, val, ptr, align=align) + + +def fix_integer_index(context, builder, idxty, idx, size): + """ + Fix the integer index' type and value for the given dimension size. + """ + if idxty.signed: + ind = context.cast(builder, idx, idxty, types.intp) + ind = slicing.fix_index(builder, ind, size) + else: + ind = context.cast(builder, idx, idxty, types.uintp) + return ind + + +def normalize_index(context, builder, idxty, idx): + """ + Normalize the index type and value. 0-d arrays are converted to scalars. + """ + if isinstance(idxty, types.Array) and idxty.ndim == 0: + assert isinstance(idxty.dtype, types.Integer) + idxary = make_array(idxty)(context, builder, idx) + idxval = load_item(context, builder, idxty, idxary.data) + return idxty.dtype, idxval + else: + return idxty, idx + + +def normalize_indices(context, builder, index_types, indices): + """ + Same as normalize_index(), but operating on sequences of + index types and values. + """ + if len(indices): + index_types, indices = zip(*[normalize_index(context, builder, idxty, + idx) + for idxty, idx in zip(index_types, indices) + ]) + return index_types, indices + + +def populate_array(array, data, shape, strides, itemsize, meminfo, + parent=None): + """ + Helper function for populating array structures. + This avoids forgetting to set fields. + + *shape* and *strides* can be Python tuples or LLVM arrays. + """ + context = array._context + builder = array._builder + datamodel = array._datamodel + # doesn't matter what this array type instance is, it's just to get the + # fields for the datamodel of the standard array type in this context + standard_array = types.Array(types.float64, 1, 'C') + standard_array_type_datamodel = context.data_model_manager[standard_array] + required_fields = set(standard_array_type_datamodel._fields) + datamodel_fields = set(datamodel._fields) + # Make sure that the presented array object has a data model that is close + # enough to an array for this function to proceed. + if (required_fields & datamodel_fields) != required_fields: + missing = required_fields - datamodel_fields + msg = (f"The datamodel for type {array._fe_type} is missing " + f"field{'s' if len(missing) > 1 else ''} {missing}.") + raise ValueError(msg) + + if meminfo is None: + meminfo = Constant(context.get_value_type( + datamodel.get_type('meminfo')), None) + + intp_t = context.get_value_type(types.intp) + if isinstance(shape, (tuple, list)): + shape = cgutils.pack_array(builder, shape, intp_t) + if isinstance(strides, (tuple, list)): + strides = cgutils.pack_array(builder, strides, intp_t) + if isinstance(itemsize, int): + itemsize = intp_t(itemsize) + + attrs = dict(shape=shape, + strides=strides, + data=data, + itemsize=itemsize, + meminfo=meminfo,) + + # Set `parent` attribute + if parent is None: + attrs['parent'] = Constant(context.get_value_type( + datamodel.get_type('parent')), None) + else: + attrs['parent'] = parent + # Calc num of items from shape + nitems = context.get_constant(types.intp, 1) + unpacked_shape = cgutils.unpack_tuple(builder, shape, shape.type.count) + # (note empty shape => 0d array therefore nitems = 1) + for axlen in unpacked_shape: + nitems = builder.mul(nitems, axlen, flags=['nsw']) + attrs['nitems'] = nitems + + # Make sure that we have all the fields + got_fields = set(attrs.keys()) + if got_fields != required_fields: + raise ValueError("missing {0}".format(required_fields - got_fields)) + + # Set field value + for k, v in attrs.items(): + setattr(array, k, v) + + return array + + +def update_array_info(aryty, array): + """ + Update some auxiliary information in *array* after some of its fields + were changed. `itemsize` and `nitems` are updated. + """ + context = array._context + builder = array._builder + + # Calc num of items from shape + nitems = context.get_constant(types.intp, 1) + unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim) + for axlen in unpacked_shape: + nitems = builder.mul(nitems, axlen, flags=['nsw']) + array.nitems = nitems + + array.itemsize = context.get_constant(types.intp, + get_itemsize(context, aryty)) + + +def normalize_axis(func_name, arg_name, ndim, axis): + """Constrain axis values to valid positive values.""" + raise NotImplementedError() + + +@overload(normalize_axis) +def normalize_axis_overloads(func_name, arg_name, ndim, axis): + if not isinstance(func_name, StringLiteral): + raise errors.TypingError("func_name must be a str literal.") + if not isinstance(arg_name, StringLiteral): + raise errors.TypingError("arg_name must be a str literal.") + + msg = ( + f"{func_name.literal_value}: Argument {arg_name.literal_value} " + "out of bounds for dimensions of the array" + ) + + def impl(func_name, arg_name, ndim, axis): + if axis < 0: + axis += ndim + if axis < 0 or axis >= ndim: + raise ValueError(msg) + + return axis + + return impl + + +def normalize_axis_tuple(func_name, arg_name, ndim, axis): + """Normalizes an axis argument into a tuple of non-negative integer axes.""" + raise NotImplementedError() + + +@overload(normalize_axis_tuple) +def normalize_axis_tuple_overloads(func_name, arg_name, ndim, axis): + if not isinstance(func_name, StringLiteral): + raise errors.TypingError("func_name must be a str literal.") + if not isinstance(arg_name, StringLiteral): + raise errors.TypingError("arg_name must be a str literal.") + + invalid_axis_msg = ( + f"{func_name.literal_value}: Argument {arg_name.literal_value} " + "out of bounds for dimensions of the array" + ) + + repeated_axis_msg = ( + f"{func_name.literal_value}: repeated axis in " + f"{arg_name.literal_value} argument" + ) + + if isinstance(axis, types.Integer): + + def impl(func_name, arg_name, ndim, axis): + if axis < 0: + axis += ndim + if axis < 0 or axis >= ndim: + raise ValueError(invalid_axis_msg) + + return (axis,) + + else: + axis_len = len(axis) + norm_axis_init = (0,) * axis_len + + def impl(func_name, arg_name, ndim, axis): + norm_axis = norm_axis_init + for i, ax in enumerate(axis): + if ax < 0: + ax += ndim + if ax < 0 or ax >= ndim: + raise ValueError(invalid_axis_msg) + norm_axis = tuple_setitem(norm_axis, i, ax) + + if len(set(norm_axis)) != axis_len: + raise ValueError(repeated_axis_msg) + + return norm_axis + + return impl + + +@lower_builtin('getiter', types.Buffer) +def getiter_array(context, builder, sig, args): + [arrayty] = sig.args + [array] = args + + iterobj = context.make_helper(builder, sig.return_type) + + zero = context.get_constant(types.intp, 0) + indexptr = cgutils.alloca_once_value(builder, zero) + + iterobj.index = indexptr + iterobj.array = array + + # Incref array + if context.enable_nrt: + context.nrt.incref(builder, arrayty, array) + + res = iterobj._getvalue() + + # Note: a decref on the iterator will dereference all internal MemInfo* + out = impl_ret_new_ref(context, builder, sig.return_type, res) + return out + + +def _getitem_array_single_int(context, builder, return_type, aryty, ary, idx): + """ Evaluate `ary[idx]`, where idx is a single int. """ + # optimized form of _getitem_array_generic + shapes = cgutils.unpack_tuple(builder, ary.shape, count=aryty.ndim) + strides = cgutils.unpack_tuple(builder, ary.strides, count=aryty.ndim) + offset = builder.mul(strides[0], idx) + dataptr = cgutils.pointer_add(builder, ary.data, offset) + view_shapes = shapes[1:] + view_strides = strides[1:] + + if isinstance(return_type, types.Buffer): + # Build array view + retary = make_view(context, builder, aryty, ary, return_type, + dataptr, view_shapes, view_strides) + return retary._getvalue() + else: + # Load scalar from 0-d result + assert not view_shapes + return load_item(context, builder, aryty, dataptr) + + +@lower_builtin('iternext', types.ArrayIterator) +@iternext_impl(RefType.BORROWED) +def iternext_array(context, builder, sig, args, result): + [iterty] = sig.args + [iter] = args + arrayty = iterty.array_type + + iterobj = context.make_helper(builder, iterty, value=iter) + ary = make_array(arrayty)(context, builder, value=iterobj.array) + + nitems, = cgutils.unpack_tuple(builder, ary.shape, count=1) + + index = builder.load(iterobj.index) + is_valid = builder.icmp_signed('<', index, nitems) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + value = _getitem_array_single_int( + context, builder, iterty.yield_type, arrayty, ary, index + ) + result.yield_(value) + nindex = cgutils.increment_index(builder, index) + builder.store(nindex, iterobj.index) + + +# ------------------------------------------------------------------------------ +# Basic indexing (with integers and slices only) + +def basic_indexing(context, builder, aryty, ary, index_types, indices, + boundscheck=None): + """ + Perform basic indexing on the given array. + A (data pointer, shapes, strides) tuple is returned describing + the corresponding view. + """ + zero = context.get_constant(types.intp, 0) + one = context.get_constant(types.intp, 1) + + shapes = cgutils.unpack_tuple(builder, ary.shape, aryty.ndim) + strides = cgutils.unpack_tuple(builder, ary.strides, aryty.ndim) + + output_indices = [] + output_shapes = [] + output_strides = [] + + num_newaxes = len([idx for idx in index_types if is_nonelike(idx)]) + ax = 0 + for indexval, idxty in zip(indices, index_types): + if idxty is types.ellipsis: + # Fill up missing dimensions at the middle + n_missing = aryty.ndim - len(indices) + 1 + num_newaxes + for i in range(n_missing): + output_indices.append(zero) + output_shapes.append(shapes[ax]) + output_strides.append(strides[ax]) + ax += 1 + continue + # Regular index value + if isinstance(idxty, types.SliceType): + slice = context.make_helper(builder, idxty, value=indexval) + slicing.guard_invalid_slice(context, builder, idxty, slice) + slicing.fix_slice(builder, slice, shapes[ax]) + output_indices.append(slice.start) + sh = slicing.get_slice_length(builder, slice) + st = slicing.fix_stride(builder, slice, strides[ax]) + output_shapes.append(sh) + output_strides.append(st) + elif isinstance(idxty, types.Integer): + ind = fix_integer_index(context, builder, idxty, indexval, + shapes[ax]) + if boundscheck: + cgutils.do_boundscheck(context, builder, ind, shapes[ax], ax) + output_indices.append(ind) + elif is_nonelike(idxty): + output_shapes.append(one) + output_strides.append(zero) + ax -= 1 + else: + raise NotImplementedError("unexpected index type: %s" % (idxty,)) + ax += 1 + + # Fill up missing dimensions at the end + assert ax <= aryty.ndim + while ax < aryty.ndim: + output_shapes.append(shapes[ax]) + output_strides.append(strides[ax]) + ax += 1 + + # No need to check wraparound, as negative indices were already + # fixed in the loop above. + dataptr = cgutils.get_item_pointer(context, builder, aryty, ary, + output_indices, + wraparound=False, boundscheck=False) + return (dataptr, output_shapes, output_strides) + + +def make_view(context, builder, aryty, ary, return_type, + data, shapes, strides): + """ + Build a view over the given array with the given parameters. + """ + retary = make_array(return_type)(context, builder) + populate_array(retary, + data=data, + shape=shapes, + strides=strides, + itemsize=ary.itemsize, + meminfo=ary.meminfo, + parent=ary.parent) + return retary + + +def _getitem_array_generic(context, builder, return_type, aryty, ary, + index_types, indices): + """ + Return the result of indexing *ary* with the given *indices*, + returning either a scalar or a view. + """ + dataptr, view_shapes, view_strides = \ + basic_indexing(context, builder, aryty, ary, index_types, indices, + boundscheck=context.enable_boundscheck) + + if isinstance(return_type, types.Buffer): + # Build array view + retary = make_view(context, builder, aryty, ary, return_type, + dataptr, view_shapes, view_strides) + return retary._getvalue() + else: + # Load scalar from 0-d result + assert not view_shapes + return load_item(context, builder, aryty, dataptr) + + +@lower_builtin(operator.getitem, types.Buffer, types.Integer) +@lower_builtin(operator.getitem, types.Buffer, types.SliceType) +@lower_builtin(operator.getitem, types.Buffer, types.NoneType) +def getitem_arraynd_intp(context, builder, sig, args): + """ + Basic indexing with an integer, slice, or None. + """ + aryty, idxty = sig.args + ary, idx = args + + # for 0d arrays, a[None] is valid + if not isinstance(idxty, types.NoneType): + assert aryty.ndim >= 1 + ary = make_array(aryty)(context, builder, ary) + + res = _getitem_array_generic(context, builder, sig.return_type, + aryty, ary, (idxty,), (idx,)) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(operator.getitem, types.Buffer, types.BaseTuple) +def getitem_array_tuple(context, builder, sig, args): + """ + Basic or advanced indexing with a tuple. + """ + aryty, tupty = sig.args + ary, tup = args + ary = make_array(aryty)(context, builder, ary) + + index_types = tupty.types + indices = cgutils.unpack_tuple(builder, tup, count=len(tupty)) + + index_types, indices = normalize_indices(context, builder, + index_types, indices) + + if any(isinstance(ty, types.Array) for ty in index_types): + # Advanced indexing + return fancy_getitem(context, builder, sig, args, + aryty, ary, index_types, indices) + + res = _getitem_array_generic(context, builder, sig.return_type, + aryty, ary, index_types, indices) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(operator.setitem, types.Buffer, types.Any, types.Any) +def setitem_array(context, builder, sig, args): + """ + array[a] = scalar_or_array + array[a,..,b] = scalar_or_array + """ + aryty, idxty, valty = sig.args + ary, idx, val = args + + if isinstance(idxty, types.BaseTuple): + index_types = idxty.types + indices = cgutils.unpack_tuple(builder, idx, count=len(idxty)) + else: + index_types = (idxty,) + indices = (idx,) + + ary = make_array(aryty)(context, builder, ary) + + # First try basic indexing to see if a single array location is denoted. + index_types, indices = normalize_indices(context, builder, + index_types, indices) + try: + dataptr, shapes, strides = \ + basic_indexing(context, builder, aryty, ary, index_types, indices, + boundscheck=context.enable_boundscheck) + except NotImplementedError: + use_fancy_indexing = True + else: + use_fancy_indexing = bool(shapes) + + if use_fancy_indexing: + # Index describes a non-trivial view => use generic slice assignment + # (NOTE: this also handles scalar broadcasting) + return fancy_setslice(context, builder, sig, args, + index_types, indices) + + # Store source value the given location + val = context.cast(builder, val, valty, aryty.dtype) + store_item(context, builder, aryty, val, dataptr) + + +@lower_builtin(len, types.Buffer) +def array_len(context, builder, sig, args): + (aryty,) = sig.args + (ary,) = args + arystty = make_array(aryty) + ary = arystty(context, builder, ary) + shapeary = ary.shape + res = builder.extract_value(shapeary, 0) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin("array.item", types.Array) +def array_item(context, builder, sig, args): + aryty, = sig.args + ary, = args + ary = make_array(aryty)(context, builder, ary) + + nitems = ary.nitems + with builder.if_then(builder.icmp_signed('!=', nitems, nitems.type(1)), + likely=False): + msg = "item(): can only convert an array of size 1 to a Python scalar" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + return load_item(context, builder, aryty, ary.data) + + +if numpy_version < (2, 0): + @lower_builtin("array.itemset", types.Array, types.Any) + def array_itemset(context, builder, sig, args): + aryty, valty = sig.args + ary, val = args + assert valty == aryty.dtype + ary = make_array(aryty)(context, builder, ary) + + nitems = ary.nitems + with builder.if_then(builder.icmp_signed('!=', nitems, nitems.type(1)), + likely=False): + msg = "itemset(): can only write to an array of size 1" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + store_item(context, builder, aryty, val, ary.data) + return context.get_dummy_value() + + +# ------------------------------------------------------------------------------ +# Advanced / fancy indexing + + +class Indexer(object): + """ + Generic indexer interface, for generating indices over a fancy indexed + array on a single dimension. + """ + + def prepare(self): + """ + Prepare the indexer by initializing any required variables, basic + blocks... + """ + raise NotImplementedError + + def get_size(self): + """ + Return this dimension's size as an integer. + """ + raise NotImplementedError + + def get_shape(self): + """ + Return this dimension's shape as a tuple. + """ + raise NotImplementedError + + def get_index_bounds(self): + """ + Return a half-open [lower, upper) range of indices this dimension + is guaranteed not to step out of. + """ + raise NotImplementedError + + def loop_head(self): + """ + Start indexation loop. Return a (index, count) tuple. + *index* is an integer LLVM value representing the index over this + dimension. + *count* is either an integer LLVM value representing the current + iteration count, or None if this dimension should be omitted from + the indexation result. + """ + raise NotImplementedError + + def loop_tail(self): + """ + Finish indexation loop. + """ + raise NotImplementedError + + +class EntireIndexer(Indexer): + """ + Compute indices along an entire array dimension. + """ + + def __init__(self, context, builder, aryty, ary, dim): + self.context = context + self.builder = builder + self.aryty = aryty + self.ary = ary + self.dim = dim + self.ll_intp = self.context.get_value_type(types.intp) + + def prepare(self): + builder = self.builder + self.size = builder.extract_value(self.ary.shape, self.dim) + self.index = cgutils.alloca_once(builder, self.ll_intp) + self.bb_start = builder.append_basic_block() + self.bb_end = builder.append_basic_block() + + def get_size(self): + return self.size + + def get_shape(self): + return (self.size,) + + def get_index_bounds(self): + # [0, size) + return (self.ll_intp(0), self.size) + + def loop_head(self): + builder = self.builder + # Initialize loop variable + self.builder.store(Constant(self.ll_intp, 0), self.index) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_start) + cur_index = builder.load(self.index) + with builder.if_then(builder.icmp_signed('>=', cur_index, self.size), + likely=False): + builder.branch(self.bb_end) + return cur_index, cur_index + + def loop_tail(self): + builder = self.builder + next_index = cgutils.increment_index(builder, builder.load(self.index)) + builder.store(next_index, self.index) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_end) + + +class IntegerIndexer(Indexer): + """ + Compute indices from a single integer. + """ + + def __init__(self, context, builder, idx): + self.context = context + self.builder = builder + self.idx = idx + self.ll_intp = self.context.get_value_type(types.intp) + + def prepare(self): + pass + + def get_size(self): + return Constant(self.ll_intp, 1) + + def get_shape(self): + return () + + def get_index_bounds(self): + # [idx, idx+1) + return (self.idx, self.builder.add(self.idx, self.get_size())) + + def loop_head(self): + return self.idx, None + + def loop_tail(self): + pass + + +class IntegerArrayIndexer(Indexer): + """ + Compute indices from an array of integer indices. + """ + + def __init__(self, context, builder, idxty, idxary, size): + self.context = context + self.builder = builder + self.idxty = idxty + self.idxary = idxary + self.size = size + assert idxty.ndim == 1 + self.ll_intp = self.context.get_value_type(types.intp) + + def prepare(self): + builder = self.builder + self.idx_size = cgutils.unpack_tuple(builder, self.idxary.shape)[0] + self.idx_index = cgutils.alloca_once(builder, self.ll_intp) + self.bb_start = builder.append_basic_block() + self.bb_end = builder.append_basic_block() + + def get_size(self): + return self.idx_size + + def get_shape(self): + return (self.idx_size,) + + def get_index_bounds(self): + # Pessimal heuristic, as we don't want to scan for the min and max + return (self.ll_intp(0), self.size) + + def loop_head(self): + builder = self.builder + # Initialize loop variable + self.builder.store(Constant(self.ll_intp, 0), self.idx_index) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_start) + cur_index = builder.load(self.idx_index) + with builder.if_then( + builder.icmp_signed('>=', cur_index, self.idx_size), + likely=False + ): + builder.branch(self.bb_end) + # Load the actual index from the array of indices + index = _getitem_array_single_int( + self.context, builder, self.idxty.dtype, self.idxty, self.idxary, + cur_index + ) + index = fix_integer_index(self.context, builder, + self.idxty.dtype, index, self.size) + return index, cur_index + + def loop_tail(self): + builder = self.builder + next_index = cgutils.increment_index(builder, + builder.load(self.idx_index)) + builder.store(next_index, self.idx_index) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_end) + + +class BooleanArrayIndexer(Indexer): + """ + Compute indices from an array of boolean predicates. + """ + + def __init__(self, context, builder, idxty, idxary): + self.context = context + self.builder = builder + self.idxty = idxty + self.idxary = idxary + assert idxty.ndim == 1 + self.ll_intp = self.context.get_value_type(types.intp) + self.zero = Constant(self.ll_intp, 0) + + def prepare(self): + builder = self.builder + self.size = cgutils.unpack_tuple(builder, self.idxary.shape)[0] + self.idx_index = cgutils.alloca_once(builder, self.ll_intp) + self.count = cgutils.alloca_once(builder, self.ll_intp) + self.bb_start = builder.append_basic_block() + self.bb_tail = builder.append_basic_block() + self.bb_end = builder.append_basic_block() + + def get_size(self): + builder = self.builder + count = cgutils.alloca_once_value(builder, self.zero) + # Sum all true values + with cgutils.for_range(builder, self.size) as loop: + c = builder.load(count) + pred = _getitem_array_single_int( + self.context, builder, self.idxty.dtype, + self.idxty, self.idxary, loop.index + ) + c = builder.add(c, builder.zext(pred, c.type)) + builder.store(c, count) + + return builder.load(count) + + def get_shape(self): + return (self.get_size(),) + + def get_index_bounds(self): + # Pessimal heuristic, as we don't want to scan for the + # first and last true items + return (self.ll_intp(0), self.size) + + def loop_head(self): + builder = self.builder + # Initialize loop variable + self.builder.store(self.zero, self.idx_index) + self.builder.store(self.zero, self.count) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_start) + cur_index = builder.load(self.idx_index) + cur_count = builder.load(self.count) + with builder.if_then(builder.icmp_signed('>=', cur_index, self.size), + likely=False): + builder.branch(self.bb_end) + # Load the predicate and branch if false + pred = _getitem_array_single_int( + self.context, builder, self.idxty.dtype, self.idxty, self.idxary, + cur_index + ) + with builder.if_then(builder.not_(pred)): + builder.branch(self.bb_tail) + # Increment the count for next iteration + next_count = cgutils.increment_index(builder, cur_count) + builder.store(next_count, self.count) + return cur_index, cur_count + + def loop_tail(self): + builder = self.builder + builder.branch(self.bb_tail) + builder.position_at_end(self.bb_tail) + next_index = cgutils.increment_index(builder, + builder.load(self.idx_index)) + builder.store(next_index, self.idx_index) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_end) + + +class SliceIndexer(Indexer): + """ + Compute indices along a slice. + """ + + def __init__(self, context, builder, aryty, ary, dim, idxty, slice): + self.context = context + self.builder = builder + self.aryty = aryty + self.ary = ary + self.dim = dim + self.idxty = idxty + self.slice = slice + self.ll_intp = self.context.get_value_type(types.intp) + self.zero = Constant(self.ll_intp, 0) + + def prepare(self): + builder = self.builder + # Fix slice for the dimension's size + self.dim_size = builder.extract_value(self.ary.shape, self.dim) + slicing.guard_invalid_slice(self.context, builder, self.idxty, + self.slice) + slicing.fix_slice(builder, self.slice, self.dim_size) + self.is_step_negative = cgutils.is_neg_int(builder, self.slice.step) + # Create loop entities + self.index = cgutils.alloca_once(builder, self.ll_intp) + self.count = cgutils.alloca_once(builder, self.ll_intp) + self.bb_start = builder.append_basic_block() + self.bb_end = builder.append_basic_block() + + def get_size(self): + return slicing.get_slice_length(self.builder, self.slice) + + def get_shape(self): + return (self.get_size(),) + + def get_index_bounds(self): + lower, upper = slicing.get_slice_bounds(self.builder, self.slice) + return lower, upper + + def loop_head(self): + builder = self.builder + # Initialize loop variable + self.builder.store(self.slice.start, self.index) + self.builder.store(self.zero, self.count) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_start) + cur_index = builder.load(self.index) + cur_count = builder.load(self.count) + is_finished = builder.select(self.is_step_negative, + builder.icmp_signed('<=', cur_index, + self.slice.stop), + builder.icmp_signed('>=', cur_index, + self.slice.stop)) + with builder.if_then(is_finished, likely=False): + builder.branch(self.bb_end) + return cur_index, cur_count + + def loop_tail(self): + builder = self.builder + next_index = builder.add(builder.load(self.index), self.slice.step, + flags=['nsw']) + builder.store(next_index, self.index) + next_count = cgutils.increment_index(builder, builder.load(self.count)) + builder.store(next_count, self.count) + builder.branch(self.bb_start) + builder.position_at_end(self.bb_end) + + +class FancyIndexer(object): + """ + Perform fancy indexing on the given array. + """ + + def __init__(self, context, builder, aryty, ary, index_types, indices): + self.context = context + self.builder = builder + self.aryty = aryty + self.shapes = cgutils.unpack_tuple(builder, ary.shape, aryty.ndim) + self.strides = cgutils.unpack_tuple(builder, ary.strides, aryty.ndim) + self.ll_intp = self.context.get_value_type(types.intp) + self.newaxes = [] + + indexers = [] + num_newaxes = len([idx for idx in index_types if is_nonelike(idx)]) + + ax = 0 # keeps track of position of original axes + new_ax = 0 # keeps track of position for inserting new axes + for indexval, idxty in zip(indices, index_types): + if idxty is types.ellipsis: + # Fill up missing dimensions at the middle + n_missing = aryty.ndim - len(indices) + 1 + num_newaxes + for i in range(n_missing): + indexer = EntireIndexer(context, builder, aryty, ary, ax) + indexers.append(indexer) + ax += 1 + new_ax += 1 + continue + + # Regular index value + if isinstance(idxty, types.SliceType): + slice = context.make_helper(builder, idxty, indexval) + indexer = SliceIndexer(context, builder, aryty, ary, ax, + idxty, slice) + indexers.append(indexer) + elif isinstance(idxty, types.Integer): + ind = fix_integer_index(context, builder, idxty, indexval, + self.shapes[ax]) + indexer = IntegerIndexer(context, builder, ind) + indexers.append(indexer) + elif isinstance(idxty, types.Array): + idxary = make_array(idxty)(context, builder, indexval) + if isinstance(idxty.dtype, types.Integer): + indexer = IntegerArrayIndexer(context, builder, + idxty, idxary, + self.shapes[ax]) + elif isinstance(idxty.dtype, types.Boolean): + indexer = BooleanArrayIndexer(context, builder, + idxty, idxary) + else: + assert 0 + indexers.append(indexer) + elif is_nonelike(idxty): + self.newaxes.append(new_ax) + ax -= 1 + else: + raise AssertionError("unexpected index type: %s" % (idxty,)) + ax += 1 + new_ax += 1 + + # Fill up missing dimensions at the end + assert ax <= aryty.ndim, (ax, aryty.ndim) + while ax < aryty.ndim: + indexer = EntireIndexer(context, builder, aryty, ary, ax) + indexers.append(indexer) + ax += 1 + + assert len(indexers) == aryty.ndim, (len(indexers), aryty.ndim) + self.indexers = indexers + + def prepare(self): + for i in self.indexers: + i.prepare() + + one = self.context.get_constant(types.intp, 1) + + # Compute the resulting shape given by the indices + res_shape = [i.get_shape() for i in self.indexers] + + # At every position where newaxis/None is present insert + # one as a constant shape in the resulting list of shapes. + for i in self.newaxes: + res_shape.insert(i, (one,)) + + # Store the shape as a tuple, we can't do a simple + # tuple(res_shape) here since res_shape is a list + # of tuples which may be differently sized. + self.indexers_shape = sum(res_shape, ()) + + def get_shape(self): + """ + Get the resulting data shape as Python tuple. + """ + return self.indexers_shape + + def get_offset_bounds(self, strides, itemsize): + """ + Get a half-open [lower, upper) range of byte offsets spanned by + the indexer with the given strides and itemsize. The indexer is + guaranteed to not go past those bounds. + """ + assert len(strides) == self.aryty.ndim + builder = self.builder + is_empty = cgutils.false_bit + zero = self.ll_intp(0) + one = self.ll_intp(1) + lower = zero + upper = zero + for indexer, shape, stride in zip(self.indexers, self.indexers_shape, + strides): + is_empty = builder.or_(is_empty, + builder.icmp_unsigned('==', shape, zero)) + # Compute [lower, upper) indices on this dimension + lower_index, upper_index = indexer.get_index_bounds() + lower_offset = builder.mul(stride, lower_index) + upper_offset = builder.mul(stride, builder.sub(upper_index, one)) + # Adjust total interval + is_downwards = builder.icmp_signed('<', stride, zero) + lower = builder.add(lower, + builder.select(is_downwards, + upper_offset, + lower_offset)) + upper = builder.add(upper, + builder.select(is_downwards, + lower_offset, + upper_offset)) + # Make interval half-open + upper = builder.add(upper, itemsize) + # Adjust for empty shape + lower = builder.select(is_empty, zero, lower) + upper = builder.select(is_empty, zero, upper) + return lower, upper + + def begin_loops(self): + indices, counts = zip(*(i.loop_head() for i in self.indexers)) + return indices, counts + + def end_loops(self): + for i in reversed(self.indexers): + i.loop_tail() + + +def fancy_getitem(context, builder, sig, args, + aryty, ary, index_types, indices): + + shapes = cgutils.unpack_tuple(builder, ary.shape) + strides = cgutils.unpack_tuple(builder, ary.strides) + data = ary.data + + indexer = FancyIndexer(context, builder, aryty, ary, + index_types, indices) + indexer.prepare() + + # Construct output array + out_ty = sig.return_type + out_shapes = indexer.get_shape() + + out = _empty_nd_impl(context, builder, out_ty, out_shapes) + out_data = out.data + out_idx = cgutils.alloca_once_value(builder, + context.get_constant(types.intp, 0)) + + # Loop on source and copy to destination + indices, _ = indexer.begin_loops() + + # No need to check for wraparound, as the indexers all ensure + # a positive index is returned. + ptr = cgutils.get_item_pointer2(context, builder, data, shapes, strides, + aryty.layout, indices, wraparound=False, + boundscheck=context.enable_boundscheck) + val = load_item(context, builder, aryty, ptr) + + # Since the destination is C-contiguous, no need for multi-dimensional + # indexing. + cur = builder.load(out_idx) + ptr = builder.gep(out_data, [cur]) + store_item(context, builder, out_ty, val, ptr) + next_idx = cgutils.increment_index(builder, cur) + builder.store(next_idx, out_idx) + + indexer.end_loops() + + return impl_ret_new_ref(context, builder, out_ty, out._getvalue()) + + +@lower_builtin(operator.getitem, types.Buffer, types.Array) +def fancy_getitem_array(context, builder, sig, args): + """ + Advanced or basic indexing with an array. + """ + aryty, idxty = sig.args + ary, idx = args + ary = make_array(aryty)(context, builder, ary) + if idxty.ndim == 0: + # 0-d array index acts as a basic integer index + idxty, idx = normalize_index(context, builder, idxty, idx) + res = _getitem_array_generic(context, builder, sig.return_type, + aryty, ary, (idxty,), (idx,)) + return impl_ret_borrowed(context, builder, sig.return_type, res) + else: + # Advanced indexing + return fancy_getitem(context, builder, sig, args, + aryty, ary, (idxty,), (idx,)) + + +def offset_bounds_from_strides(context, builder, arrty, arr, shapes, strides): + """ + Compute a half-open range [lower, upper) of byte offsets from the + array's data pointer, that bound the in-memory extent of the array. + + This mimics offset_bounds_from_strides() from + numpy/core/src/private/mem_overlap.c + """ + itemsize = arr.itemsize + zero = itemsize.type(0) + one = zero.type(1) + if arrty.layout in 'CF': + # Array is contiguous: contents are laid out sequentially + # starting from arr.data and upwards + lower = zero + upper = builder.mul(itemsize, arr.nitems) + else: + # Non-contiguous array: need to examine strides + lower = zero + upper = zero + for i in range(arrty.ndim): + # Compute the largest byte offset on this dimension + # max_axis_offset = strides[i] * (shapes[i] - 1) + # (shapes[i] == 0 is catered for by the empty array case below) + max_axis_offset = builder.mul(strides[i], + builder.sub(shapes[i], one)) + is_upwards = builder.icmp_signed('>=', max_axis_offset, zero) + # Expand either upwards or downwards depending on stride + upper = builder.select(is_upwards, + builder.add(upper, max_axis_offset), upper) + lower = builder.select(is_upwards, + lower, builder.add(lower, max_axis_offset)) + # Return a half-open range + upper = builder.add(upper, itemsize) + # Adjust for empty arrays + is_empty = builder.icmp_signed('==', arr.nitems, zero) + upper = builder.select(is_empty, zero, upper) + lower = builder.select(is_empty, zero, lower) + + return lower, upper + + +def compute_memory_extents(context, builder, lower, upper, data): + """ + Given [lower, upper) byte offsets and a base data pointer, + compute the memory pointer bounds as pointer-sized integers. + """ + data_ptr_as_int = builder.ptrtoint(data, lower.type) + start = builder.add(data_ptr_as_int, lower) + end = builder.add(data_ptr_as_int, upper) + return start, end + + +def get_array_memory_extents(context, builder, arrty, arr, shapes, strides, + data): + """ + Compute a half-open range [start, end) of pointer-sized integers + which fully contain the array data. + """ + lower, upper = offset_bounds_from_strides(context, builder, arrty, arr, + shapes, strides) + return compute_memory_extents(context, builder, lower, upper, data) + + +def extents_may_overlap(context, builder, a_start, a_end, b_start, b_end): + """ + Whether two memory extents [a_start, a_end) and [b_start, b_end) + may overlap. + """ + # Comparisons are unsigned, since we are really comparing pointers + may_overlap = builder.and_( + builder.icmp_unsigned('<', a_start, b_end), + builder.icmp_unsigned('<', b_start, a_end), + ) + return may_overlap + + +def maybe_copy_source(context, builder, use_copy, + srcty, src, src_shapes, src_strides, src_data): + ptrty = src_data.type + + copy_layout = 'C' + copy_data = cgutils.alloca_once_value(builder, src_data) + copy_shapes = src_shapes + copy_strides = None # unneeded for contiguous arrays + + with builder.if_then(use_copy, likely=False): + # Allocate temporary scratchpad + # XXX: should we use a stack-allocated array for very small + # data sizes? + allocsize = builder.mul(src.itemsize, src.nitems) + data = context.nrt.allocate(builder, allocsize) + voidptrty = data.type + data = builder.bitcast(data, ptrty) + builder.store(data, copy_data) + + # Copy source data into scratchpad + intp_t = context.get_value_type(types.intp) + + with cgutils.loop_nest(builder, src_shapes, intp_t) as indices: + src_ptr = cgutils.get_item_pointer2(context, builder, src_data, + src_shapes, src_strides, + srcty.layout, indices) + dest_ptr = cgutils.get_item_pointer2(context, builder, data, + copy_shapes, copy_strides, + copy_layout, indices) + builder.store(builder.load(src_ptr), dest_ptr) + + def src_getitem(source_indices): + src_ptr = cgutils.alloca_once(builder, ptrty) + with builder.if_else(use_copy, likely=False) as (if_copy, otherwise): + with if_copy: + builder.store( + cgutils.get_item_pointer2(context, builder, + builder.load(copy_data), + copy_shapes, copy_strides, + copy_layout, source_indices, + wraparound=False), + src_ptr) + with otherwise: + builder.store( + cgutils.get_item_pointer2(context, builder, src_data, + src_shapes, src_strides, + srcty.layout, source_indices, + wraparound=False), + src_ptr) + return load_item(context, builder, srcty, builder.load(src_ptr)) + + def src_cleanup(): + # Deallocate memory + with builder.if_then(use_copy, likely=False): + data = builder.load(copy_data) + data = builder.bitcast(data, voidptrty) + context.nrt.free(builder, data) + + return src_getitem, src_cleanup + + +def _bc_adjust_dimension(context, builder, shapes, strides, target_shape): + """ + Preprocess dimension for broadcasting. + Returns (shapes, strides) such that the ndim match *target_shape*. + When expanding to higher ndim, the returning shapes and strides are + prepended with ones and zeros, respectively. + When truncating to lower ndim, the shapes are checked (in runtime). + All extra dimension must have size of 1. + """ + zero = context.get_constant(types.uintp, 0) + one = context.get_constant(types.uintp, 1) + + # Adjust for broadcasting to higher dimension + if len(target_shape) > len(shapes): + nd_diff = len(target_shape) - len(shapes) + # Fill missing shapes with one, strides with zeros + shapes = [one] * nd_diff + shapes + strides = [zero] * nd_diff + strides + # Adjust for broadcasting to lower dimension + elif len(target_shape) < len(shapes): + # Accepted if all extra dims has shape 1 + nd_diff = len(shapes) - len(target_shape) + dim_is_one = [builder.icmp_unsigned('==', sh, one) + for sh in shapes[:nd_diff]] + accepted = functools.reduce(builder.and_, dim_is_one, + cgutils.true_bit) + # Check error + with builder.if_then(builder.not_(accepted), likely=False): + msg = "cannot broadcast source array for assignment" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + # Truncate extra shapes, strides + shapes = shapes[nd_diff:] + strides = strides[nd_diff:] + + return shapes, strides + + +def _bc_adjust_shape_strides(context, builder, shapes, strides, target_shape): + """ + Broadcast shapes and strides to target_shape given that their ndim already + matches. For each location where the shape is 1 and does not match the + dim for target, it is set to the value at the target and the stride is + set to zero. + """ + bc_shapes = [] + bc_strides = [] + zero = context.get_constant(types.uintp, 0) + one = context.get_constant(types.uintp, 1) + # Adjust all mismatching ones in shape + mismatch = [builder.icmp_signed('!=', tar, old) + for tar, old in zip(target_shape, shapes)] + src_is_one = [builder.icmp_signed('==', old, one) for old in shapes] + preds = [builder.and_(x, y) for x, y in zip(mismatch, src_is_one)] + bc_shapes = [builder.select(p, tar, old) + for p, tar, old in zip(preds, target_shape, shapes)] + bc_strides = [builder.select(p, zero, old) + for p, old in zip(preds, strides)] + return bc_shapes, bc_strides + + +def _broadcast_to_shape(context, builder, arrtype, arr, target_shape): + """ + Broadcast the given array to the target_shape. + Returns (array_type, array) + """ + # Compute broadcasted shape and strides + shapes = cgutils.unpack_tuple(builder, arr.shape) + strides = cgutils.unpack_tuple(builder, arr.strides) + + shapes, strides = _bc_adjust_dimension(context, builder, shapes, strides, + target_shape) + shapes, strides = _bc_adjust_shape_strides(context, builder, shapes, + strides, target_shape) + new_arrtype = arrtype.copy(ndim=len(target_shape), layout='A') + # Create new view + new_arr = make_array(new_arrtype)(context, builder) + populate_array(new_arr, + data=arr.data, + shape=cgutils.pack_array(builder, shapes), + strides=cgutils.pack_array(builder, strides), + itemsize=arr.itemsize, + meminfo=arr.meminfo, + parent=arr.parent) + return new_arrtype, new_arr + + +@intrinsic +def _numpy_broadcast_to(typingctx, array, shape): + ret = array.copy(ndim=shape.count, layout='A', readonly=True) + sig = ret(array, shape) + + def codegen(context, builder, sig, args): + src, shape_ = args + srcty = sig.args[0] + + src = make_array(srcty)(context, builder, src) + shape_ = cgutils.unpack_tuple(builder, shape_) + _, dest = _broadcast_to_shape(context, builder, srcty, src, shape_,) + + # Hack to get np.broadcast_to to return a read-only array + setattr(dest, 'parent', Constant( + context.get_value_type(dest._datamodel.get_type('parent')), + None)) + + res = dest._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + return sig, codegen + + +@intrinsic +def get_readonly_array(typingctx, arr): + # returns a copy of arr which is readonly + ret = arr.copy(readonly=True) + sig = ret(arr) + + def codegen(context, builder, sig, args): + [src] = args + srcty = sig.args[0] + + dest = make_array(srcty)(context, builder, src) + # Hack to return a read-only array + dest.parent = cgutils.get_null_value(dest.parent.type) + res = dest._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + return sig, codegen + + +@register_jitable +def _can_broadcast(array, dest_shape): + src_shape = array.shape + src_ndim = len(src_shape) + dest_ndim = len(dest_shape) + if src_ndim > dest_ndim: + raise ValueError('input operand has more dimensions than allowed ' + 'by the axis remapping') + for size in dest_shape: + if size < 0: + raise ValueError('all elements of broadcast shape must be ' + 'non-negative') + + # based on _broadcast_onto function in numba/np/npyimpl.py + src_index = 0 + dest_index = dest_ndim - src_ndim + while src_index < src_ndim: + src_dim = src_shape[src_index] + dest_dim = dest_shape[dest_index] + # possible cases for (src_dim, dest_dim): + # * (1, 1) -> Ok + # * (>1, 1) -> Error! + # * (>1, >1) -> src_dim == dest_dim else error! + # * (1, >1) -> Ok + if src_dim == dest_dim or src_dim == 1: + src_index += 1 + dest_index += 1 + else: + raise ValueError('operands could not be broadcast together ' + 'with remapped shapes') + + +def _default_broadcast_to_impl(array, shape): + array = np.asarray(array) + _can_broadcast(array, shape) + return _numpy_broadcast_to(array, shape) + + +@overload(np.broadcast_to) +def numpy_broadcast_to(array, shape): + if not type_can_asarray(array): + raise errors.TypingError('The first argument "array" must ' + 'be array-like') + + if isinstance(shape, types.Integer): + def impl(array, shape): + return np.broadcast_to(array, (shape,)) + return impl + + elif isinstance(shape, types.UniTuple): + if not isinstance(shape.dtype, types.Integer): + msg = 'The second argument "shape" must be a tuple of integers' + raise errors.TypingError(msg) + return _default_broadcast_to_impl + + elif isinstance(shape, types.Tuple) and shape.count > 0: + # check if all types are integers + if not all([isinstance(typ, types.IntegerLiteral) for typ in shape]): + msg = f'"{shape}" object cannot be interpreted as an integer' + raise errors.TypingError(msg) + return _default_broadcast_to_impl + elif isinstance(shape, types.Tuple) and shape.count == 0: + is_scalar_array = isinstance(array, types.Array) and array.ndim == 0 + if type_is_scalar(array) or is_scalar_array: + + def impl(array, shape): # broadcast_to(array, ()) + # Array type must be supported by "type_can_asarray" + # Quick note that unicode types are not supported! + array = np.asarray(array) + return get_readonly_array(array) + return impl + + else: + msg = 'Cannot broadcast a non-scalar to a scalar array' + raise errors.TypingError(msg) + else: + msg = ('The argument "shape" must be a tuple or an integer. ' + 'Got %s' % shape) + raise errors.TypingError(msg) + + +@register_jitable +def numpy_broadcast_shapes_list(r, m, shape): + for i in range(len(shape)): + k = m - len(shape) + i + tmp = shape[i] + if tmp < 0: + raise ValueError("negative dimensions are not allowed") + if tmp == 1: + continue + if r[k] == 1: + r[k] = tmp + elif r[k] != tmp: + raise ValueError("shape mismatch: objects" + " cannot be broadcast" + " to a single shape") + + +@overload(np.broadcast_shapes) +def ol_numpy_broadcast_shapes(*args): + # Based on https://github.com/numpy/numpy/blob/f702b26fff3271ba6a6ba29a021fc19051d1f007/numpy/core/src/multiarray/iterators.c#L1129-L1212 # noqa + for idx, arg in enumerate(args): + is_int = isinstance(arg, types.Integer) + is_int_tuple = isinstance(arg, types.UniTuple) and \ + isinstance(arg.dtype, types.Integer) + is_empty_tuple = isinstance(arg, types.Tuple) and len(arg.types) == 0 + if not (is_int or is_int_tuple or is_empty_tuple): + msg = (f'Argument {idx} must be either an int or tuple[int]. ' + f'Got {arg}') + raise errors.TypingError(msg) + + # discover the number of dimensions + m = 0 + for arg in args: + if isinstance(arg, types.Integer): + m = max(m, 1) + elif isinstance(arg, types.BaseTuple): + m = max(m, len(arg)) + + if m == 0: + return lambda *args: () + else: + tup_init = (1,) * m + + def impl(*args): + # propagate args + r = [1] * m + tup = tup_init + for arg in literal_unroll(args): + if isinstance(arg, tuple) and len(arg) > 0: + numpy_broadcast_shapes_list(r, m, arg) + elif isinstance(arg, int): + numpy_broadcast_shapes_list(r, m, (arg,)) + for idx, elem in enumerate(r): + tup = tuple_setitem(tup, idx, elem) + return tup + return impl + + +@overload(np.broadcast_arrays) +def numpy_broadcast_arrays(*args): + + for idx, arg in enumerate(args): + if not type_can_asarray(arg): + raise errors.TypingError(f'Argument "{idx}" must ' + 'be array-like') + + unified_dtype = None + dt = None + for arg in args: + if isinstance(arg, (types.Array, types.BaseTuple)): + dt = arg.dtype + else: + dt = arg + + if unified_dtype is None: + unified_dtype = dt + elif unified_dtype != dt: + raise errors.TypingError('Mismatch of argument types. Numba cannot ' + 'broadcast arrays with different types. ' + f'Got {args}') + + # number of dimensions + m = 0 + for idx, arg in enumerate(args): + if isinstance(arg, types.ArrayCompatible): + m = max(m, arg.ndim) + elif isinstance(arg, (types.Number, types.Boolean, types.BaseTuple)): + m = max(m, 1) + else: + raise errors.TypingError(f'Unhandled type {arg}') + + tup_init = (0,) * m + + def impl(*args): + # find out the output shape + # we can't call np.broadcast_shapes here since args may have arrays + # with different shapes and it is not possible to create a list + # with those shapes dynamically + shape = [1] * m + for array in literal_unroll(args): + numpy_broadcast_shapes_list(shape, m, np.asarray(array).shape) + + tup = tup_init + + for i in range(m): + tup = tuple_setitem(tup, i, shape[i]) + + # numpy checks if the input arrays have the same shape as `shape` + outs = [] + for array in literal_unroll(args): + outs.append(np.broadcast_to(np.asarray(array), tup)) + return outs + + return impl + + +def raise_with_shape_context(src_shapes, index_shape): + """Targets should implement this if they wish to specialize the error + handling/messages. The overload implementation takes two tuples as arguments + and should raise a ValueError.""" + raise NotImplementedError + + +@overload(raise_with_shape_context, target="generic") +def ol_raise_with_shape_context_generic(src_shapes, index_shape): + # This overload is for a "generic" target, which makes no assumption about + # the NRT or string support, but does assume exceptions can be raised. + if (isinstance(src_shapes, types.UniTuple) and + isinstance(index_shape, types.UniTuple) and + src_shapes.dtype == index_shape.dtype and + isinstance(src_shapes.dtype, types.Integer)): + + def impl(src_shapes, index_shape): + raise ValueError("cannot assign slice from input of different size") + return impl + + +@overload(raise_with_shape_context, target="CPU") +def ol_raise_with_shape_context_cpu(src_shapes, index_shape): + if (isinstance(src_shapes, types.UniTuple) and + isinstance(index_shape, types.UniTuple) and + src_shapes.dtype == index_shape.dtype and + isinstance(src_shapes.dtype, types.Integer)): + + def impl(src_shapes, index_shape): + if len(src_shapes) == 1: + shape_str = f"({src_shapes[0]},)" + else: + shape_str = f"({', '.join([str(x) for x in src_shapes])})" + if len(index_shape) == 1: + index_str = f"({index_shape[0]},)" + else: + index_str = f"({', '.join([str(x) for x in index_shape])})" + msg = (f"cannot assign slice of shape {shape_str} from input of " + f"shape {index_str}") + raise ValueError(msg) + return impl + + +def fancy_setslice(context, builder, sig, args, index_types, indices): + """ + Implement slice assignment for arrays. This implementation works for + basic as well as fancy indexing, since there's no functional difference + between the two for indexed assignment. + """ + aryty, _, srcty = sig.args + ary, _, src = args + + ary = make_array(aryty)(context, builder, ary) + dest_shapes = cgutils.unpack_tuple(builder, ary.shape) + dest_strides = cgutils.unpack_tuple(builder, ary.strides) + dest_data = ary.data + + indexer = FancyIndexer(context, builder, aryty, ary, + index_types, indices) + indexer.prepare() + + def raise_shape_mismatch_error(context, builder, src_shapes, index_shape): + # This acts as the "trampoline" to raise a ValueError in the case + # of the source and destination shapes mismatch at runtime. It resolves + # the public overload stub `raise_with_shape_context` + fnty = context.typing_context.resolve_value_type( + raise_with_shape_context) + argtys = (types.UniTuple(types.int64, len(src_shapes)), + types.UniTuple(types.int64, len(index_shape))) + raise_sig = fnty.get_call_type(context.typing_context, argtys, {}) + func = context.get_function(fnty, raise_sig) + func(builder, (context.make_tuple(builder, raise_sig.args[0], + src_shapes), + context.make_tuple(builder, raise_sig.args[1], + index_shape))) + + if isinstance(srcty, types.Buffer): + # Source is an array + src_dtype = srcty.dtype + index_shape = indexer.get_shape() + src = make_array(srcty)(context, builder, src) + # Broadcast source array to shape + srcty, src = _broadcast_to_shape(context, builder, srcty, src, + index_shape) + src_shapes = cgutils.unpack_tuple(builder, src.shape) + src_strides = cgutils.unpack_tuple(builder, src.strides) + src_data = src.data + + # Check shapes are equal + shape_error = cgutils.false_bit + assert len(index_shape) == len(src_shapes) + + for u, v in zip(src_shapes, index_shape): + shape_error = builder.or_(shape_error, + builder.icmp_signed('!=', u, v)) + + with builder.if_then(shape_error, likely=False): + raise_shape_mismatch_error(context, builder, src_shapes, + index_shape) + + # Check for array overlap + src_start, src_end = get_array_memory_extents(context, builder, srcty, + src, src_shapes, + src_strides, src_data) + + dest_lower, dest_upper = indexer.get_offset_bounds(dest_strides, + ary.itemsize) + dest_start, dest_end = compute_memory_extents(context, builder, + dest_lower, dest_upper, + dest_data) + + use_copy = extents_may_overlap(context, builder, src_start, src_end, + dest_start, dest_end) + + src_getitem, src_cleanup = maybe_copy_source(context, builder, use_copy, + srcty, src, src_shapes, + src_strides, src_data) + + elif isinstance(srcty, types.Sequence): + src_dtype = srcty.dtype + + # Check shape is equal to sequence length + index_shape = indexer.get_shape() + assert len(index_shape) == 1 + len_impl = context.get_function(len, signature(types.intp, srcty)) + seq_len = len_impl(builder, (src,)) + + shape_error = builder.icmp_signed('!=', index_shape[0], seq_len) + + with builder.if_then(shape_error, likely=False): + raise_shape_mismatch_error(context, builder, (seq_len,), + (index_shape[0],)) + + def src_getitem(source_indices): + idx, = source_indices + getitem_impl = context.get_function( + operator.getitem, + signature(src_dtype, srcty, types.intp), + ) + return getitem_impl(builder, (src, idx)) + + def src_cleanup(): + pass + + else: + # Source is a scalar (broadcast or not, depending on destination + # shape). + src_dtype = srcty + + def src_getitem(source_indices): + return src + + def src_cleanup(): + pass + + zero = context.get_constant(types.uintp, 0) + # Loop on destination and copy from source to destination + dest_indices, counts = indexer.begin_loops() + + # Source is iterated in natural order + + # Counts represent a counter for the number of times a specified axis + # is being accessed, during setitem they are used as source + # indices + counts = list(counts) + + # We need to artifically introduce the index zero wherever a + # newaxis is present within the indexer. These always remain + # zero. + for i in indexer.newaxes: + counts.insert(i, zero) + + source_indices = [c for c in counts if c is not None] + + val = src_getitem(source_indices) + + # Cast to the destination dtype (cross-dtype slice assignment is allowed) + val = context.cast(builder, val, src_dtype, aryty.dtype) + + # No need to check for wraparound, as the indexers all ensure + # a positive index is returned. + dest_ptr = cgutils.get_item_pointer2(context, builder, dest_data, + dest_shapes, dest_strides, + aryty.layout, dest_indices, + wraparound=False, + boundscheck=context.enable_boundscheck) + store_item(context, builder, aryty, val, dest_ptr) + + indexer.end_loops() + + src_cleanup() + + return context.get_dummy_value() + + +# ------------------------------------------------------------------------------ +# Shape / layout altering + +def vararg_to_tuple(context, builder, sig, args): + aryty = sig.args[0] + dimtys = sig.args[1:] + # values + ary = args[0] + dims = args[1:] + # coerce all types to intp + dims = [context.cast(builder, val, ty, types.intp) + for ty, val in zip(dimtys, dims)] + # make a tuple + shape = cgutils.pack_array(builder, dims, dims[0].type) + + shapety = types.UniTuple(dtype=types.intp, count=len(dims)) + new_sig = typing.signature(sig.return_type, aryty, shapety) + new_args = ary, shape + + return new_sig, new_args + + +@lower_builtin('array.transpose', types.Array) +def array_transpose(context, builder, sig, args): + return array_T(context, builder, sig.args[0], args[0]) + + +def permute_arrays(axis, shape, strides): + if len(axis) != len(set(axis)): + raise ValueError("repeated axis in transpose") + dim = len(shape) + for x in axis: + if x >= dim or abs(x) > dim: + raise ValueError("axis is out of bounds for array of " + "given dimension") + + shape[:] = shape[axis] + strides[:] = strides[axis] + + +# Transposing an array involves permuting the shape and strides of the array +# based on the given axes. +@lower_builtin('array.transpose', types.Array, types.BaseTuple) +def array_transpose_tuple(context, builder, sig, args): + aryty = sig.args[0] + ary = make_array(aryty)(context, builder, args[0]) + + axisty, axis = sig.args[1], args[1] + num_axis, dtype = axisty.count, axisty.dtype + + ll_intp = context.get_value_type(types.intp) + ll_ary_size = ir.ArrayType(ll_intp, num_axis) + + # Allocate memory for axes, shapes, and strides arrays. + arys = [axis, ary.shape, ary.strides] + ll_arys = [cgutils.alloca_once(builder, ll_ary_size) for _ in arys] + + # Store axes, shapes, and strides arrays to the allocated memory. + for src, dst in zip(arys, ll_arys): + builder.store(src, dst) + + np_ary_ty = types.Array(dtype=dtype, ndim=1, layout='C') + np_itemsize = context.get_constant(types.intp, + context.get_abi_sizeof(ll_intp)) + + # Form NumPy arrays for axes, shapes, and strides arrays. + np_arys = [make_array(np_ary_ty)(context, builder) for _ in arys] + + # Roughly, `np_ary = np.array(ll_ary)` for each of axes, shapes, and strides + for np_ary, ll_ary in zip(np_arys, ll_arys): + populate_array(np_ary, + data=builder.bitcast(ll_ary, ll_intp.as_pointer()), + shape=[context.get_constant(types.intp, num_axis)], + strides=[np_itemsize], + itemsize=np_itemsize, + meminfo=None) + + # Pass NumPy arrays formed above to permute_arrays function that permutes + # shapes and strides based on axis contents. + context.compile_internal(builder, permute_arrays, + typing.signature(types.void, + np_ary_ty, np_ary_ty, np_ary_ty), + [a._getvalue() for a in np_arys]) + + # Make a new array based on permuted shape and strides and return it. + ret = make_array(sig.return_type)(context, builder) + populate_array(ret, + data=ary.data, + shape=builder.load(ll_arys[1]), + strides=builder.load(ll_arys[2]), + itemsize=ary.itemsize, + meminfo=ary.meminfo, + parent=ary.parent) + res = ret._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('array.transpose', types.Array, types.VarArg(types.Any)) +def array_transpose_vararg(context, builder, sig, args): + new_sig, new_args = vararg_to_tuple(context, builder, sig, args) + return array_transpose_tuple(context, builder, new_sig, new_args) + + +@overload(np.transpose) +def numpy_transpose(a, axes=None): + if isinstance(a, types.BaseTuple): + raise errors.TypingError("np.transpose does not accept tuples") + + if axes is None: + def np_transpose_impl(a, axes=None): + return a.transpose() + else: + def np_transpose_impl(a, axes=None): + return a.transpose(axes) + + return np_transpose_impl + + +@lower_getattr(types.Array, 'T') +def array_T(context, builder, typ, value): + if typ.ndim <= 1: + res = value + else: + ary = make_array(typ)(context, builder, value) + ret = make_array(typ)(context, builder) + shapes = cgutils.unpack_tuple(builder, ary.shape, typ.ndim) + strides = cgutils.unpack_tuple(builder, ary.strides, typ.ndim) + populate_array(ret, + data=ary.data, + shape=cgutils.pack_array(builder, shapes[::-1]), + strides=cgutils.pack_array(builder, strides[::-1]), + itemsize=ary.itemsize, + meminfo=ary.meminfo, + parent=ary.parent) + res = ret._getvalue() + return impl_ret_borrowed(context, builder, typ, res) + + +@overload(np.logspace) +def numpy_logspace(start, stop, num=50): + if not isinstance(start, types.Number): + raise errors.TypingError('The first argument "start" must be a number') + if not isinstance(stop, types.Number): + raise errors.TypingError('The second argument "stop" must be a number') + if not isinstance(num, (int, types.Integer)): + raise errors.TypingError('The third argument "num" must be an integer') + + def impl(start, stop, num=50): + y = np.linspace(start, stop, num) + return np.power(10.0, y) + + return impl + + +@overload(np.geomspace) +def numpy_geomspace(start, stop, num=50): + if not isinstance(start, types.Number): + msg = 'The argument "start" must be a number' + raise errors.TypingError(msg) + + if not isinstance(stop, types.Number): + msg = 'The argument "stop" must be a number' + raise errors.TypingError(msg) + + if not isinstance(num, (int, types.Integer)): + msg = 'The argument "num" must be an integer' + raise errors.TypingError(msg) + + if any(isinstance(arg, types.Complex) for arg in [start, stop]): + result_dtype = from_dtype(np.result_type(as_dtype(start), + as_dtype(stop), None)) + + def impl(start, stop, num=50): + if start == 0 or stop == 0: + raise ValueError('Geometric sequence cannot include zero') + start = result_dtype(start) + stop = result_dtype(stop) + if numpy_version < (2, 0): + both_imaginary = (start.real == 0) & (stop.real == 0) + both_negative = (np.sign(start) == -1) & (np.sign(stop) == -1) + out_sign = 1 + if both_imaginary: + start = start.imag + stop = stop.imag + out_sign = 1j + if both_negative: + start = -start + stop = -stop + out_sign = -out_sign + else: + out_sign = np.sign(start) + start /= out_sign + stop /= out_sign + + logstart = np.log10(start) + logstop = np.log10(stop) + result = np.logspace(logstart, logstop, num) + # Make sure the endpoints match the start and stop arguments. + # This is necessary because np.exp(np.log(x)) is not necessarily + # equal to x. + if num > 0: + result[0] = start + if num > 1: + result[-1] = stop + return out_sign * result + + else: + def impl(start, stop, num=50): + if start == 0 or stop == 0: + raise ValueError('Geometric sequence cannot include zero') + both_negative = (np.sign(start) == -1) & (np.sign(stop) == -1) + out_sign = 1 + if both_negative: + start = -start + stop = -stop + out_sign = -out_sign + logstart = np.log10(start) + logstop = np.log10(stop) + result = np.logspace(logstart, logstop, num) + # Make sure the endpoints match the start and stop arguments. + # This is necessary because np.exp(np.log(x)) is not necessarily + # equal to x. + if num > 0: + result[0] = start + if num > 1: + result[-1] = stop + return out_sign * result + + return impl + + +@overload(np.rot90) +def numpy_rot90(m, k=1): + # supporting axes argument it needs to be included in np.flip + if not isinstance(k, (int, types.Integer)): + raise errors.TypingError('The second argument "k" must be an integer') + if not isinstance(m, types.Array): + raise errors.TypingError('The first argument "m" must be an array') + + if m.ndim < 2: + raise errors.NumbaValueError('Input must be >= 2-d.') + + def impl(m, k=1): + k = k % 4 + if k == 0: + return m[:] + elif k == 1: + return np.swapaxes(np.fliplr(m), 0, 1) + elif k == 2: + return np.flipud(np.fliplr(m)) + elif k == 3: + return np.fliplr(np.swapaxes(m, 0, 1)) + else: + raise AssertionError # unreachable + + return impl + + +def _attempt_nocopy_reshape(context, builder, aryty, ary, + newnd, newshape, newstrides): + """ + Call into Numba_attempt_nocopy_reshape() for the given array type + and instance, and the specified new shape. + + Return value is non-zero if successful, and the array pointed to + by *newstrides* will be filled up with the computed results. + """ + ll_intp = context.get_value_type(types.intp) + ll_intp_star = ll_intp.as_pointer() + ll_intc = context.get_value_type(types.intc) + fnty = ir.FunctionType(ll_intc, [ + # nd, *dims, *strides + ll_intp, ll_intp_star, ll_intp_star, + # newnd, *newdims, *newstrides + ll_intp, ll_intp_star, ll_intp_star, + # itemsize, is_f_order + ll_intp, ll_intc]) + fn = cgutils.get_or_insert_function(builder.module, fnty, + "numba_attempt_nocopy_reshape") + + nd = ll_intp(aryty.ndim) + shape = cgutils.gep_inbounds(builder, ary._get_ptr_by_name('shape'), 0, 0) + strides = cgutils.gep_inbounds(builder, ary._get_ptr_by_name('strides'), + 0, 0) + newnd = ll_intp(newnd) + newshape = cgutils.gep_inbounds(builder, newshape, 0, 0) + newstrides = cgutils.gep_inbounds(builder, newstrides, 0, 0) + is_f_order = ll_intc(0) + res = builder.call(fn, [nd, shape, strides, + newnd, newshape, newstrides, + ary.itemsize, is_f_order]) + return res + + +def normalize_reshape_value(origsize, shape): + num_neg_value = 0 + known_size = 1 + for ax, s in enumerate(shape): + if s < 0: + num_neg_value += 1 + neg_ax = ax + else: + known_size *= s + + if num_neg_value == 0: + if origsize != known_size: + raise ValueError("total size of new array must be unchanged") + + elif num_neg_value == 1: + # Infer negative dimension + if known_size == 0: + inferred = 0 + ok = origsize == 0 + else: + inferred = origsize // known_size + ok = origsize % known_size == 0 + if not ok: + raise ValueError("total size of new array must be unchanged") + shape[neg_ax] = inferred + + else: + raise ValueError("multiple negative shape values") + + +@lower_builtin('array.reshape', types.Array, types.BaseTuple) +def array_reshape(context, builder, sig, args): + aryty = sig.args[0] + retty = sig.return_type + + shapety = sig.args[1] + shape = args[1] + + ll_intp = context.get_value_type(types.intp) + ll_shape = ir.ArrayType(ll_intp, shapety.count) + + ary = make_array(aryty)(context, builder, args[0]) + + # We will change the target shape in this slot + # (see normalize_reshape_value() below) + newshape = cgutils.alloca_once(builder, ll_shape) + builder.store(shape, newshape) + + # Create a shape array pointing to the value of newshape. + # (roughly, `shape_ary = np.array(ary.shape)`) + shape_ary_ty = types.Array(dtype=shapety.dtype, ndim=1, layout='C') + shape_ary = make_array(shape_ary_ty)(context, builder) + shape_itemsize = context.get_constant(types.intp, + context.get_abi_sizeof(ll_intp)) + populate_array(shape_ary, + data=builder.bitcast(newshape, ll_intp.as_pointer()), + shape=[context.get_constant(types.intp, shapety.count)], + strides=[shape_itemsize], + itemsize=shape_itemsize, + meminfo=None) + + # Compute the original array size + size = ary.nitems + + # Call our normalizer which will fix the shape array in case of negative + # shape value + context.compile_internal(builder, normalize_reshape_value, + typing.signature(types.void, + types.uintp, shape_ary_ty), + [size, shape_ary._getvalue()]) + + # Perform reshape (nocopy) + newnd = shapety.count + newstrides = cgutils.alloca_once(builder, ll_shape) + + ok = _attempt_nocopy_reshape(context, builder, aryty, ary, newnd, + newshape, newstrides) + fail = builder.icmp_unsigned('==', ok, ok.type(0)) + + with builder.if_then(fail): + msg = "incompatible shape for array" + context.call_conv.return_user_exc(builder, NotImplementedError, (msg,)) + + ret = make_array(retty)(context, builder) + populate_array(ret, + data=ary.data, + shape=builder.load(newshape), + strides=builder.load(newstrides), + itemsize=ary.itemsize, + meminfo=ary.meminfo, + parent=ary.parent) + res = ret._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('array.reshape', types.Array, types.VarArg(types.Any)) +def array_reshape_vararg(context, builder, sig, args): + new_sig, new_args = vararg_to_tuple(context, builder, sig, args) + return array_reshape(context, builder, new_sig, new_args) + + +if numpy_version < (2, 1): + @overload(np.reshape) + def np_reshape(a, newshape): + def np_reshape_impl(a, newshape): + return a.reshape(newshape) + return np_reshape_impl +else: + @overload(np.reshape) + def np_reshape(a, shape): + def np_reshape_impl(a, shape): + return a.reshape(shape) + return np_reshape_impl + + +@overload(np.resize) +def numpy_resize(a, new_shape): + + if not type_can_asarray(a): + msg = 'The argument "a" must be array-like' + raise errors.TypingError(msg) + + if not ((isinstance(new_shape, types.UniTuple) + and + isinstance(new_shape.dtype, types.Integer)) + or + isinstance(new_shape, types.Integer)): + msg = ('The argument "new_shape" must be an integer or ' + 'a tuple of integers') + raise errors.TypingError(msg) + + def impl(a, new_shape): + a = np.asarray(a) + a = np.ravel(a) + + if isinstance(new_shape, tuple): + new_size = 1 + for dim_length in np.asarray(new_shape): + new_size *= dim_length + if dim_length < 0: + msg = 'All elements of `new_shape` must be non-negative' + raise ValueError(msg) + else: + if new_shape < 0: + msg2 = 'All elements of `new_shape` must be non-negative' + raise ValueError(msg2) + new_size = new_shape + + if a.size == 0: + return np.zeros(new_shape).astype(a.dtype) + + repeats = -(-new_size // a.size) # ceil division + res = a + for i in range(repeats - 1): + res = np.concatenate((res, a)) + res = res[:new_size] + + return np.reshape(res, new_shape) + + return impl + + +@overload(np.append) +def np_append(arr, values, axis=None): + + if not type_can_asarray(arr): + raise errors.TypingError('The first argument "arr" must be array-like') + + if not type_can_asarray(values): + raise errors.TypingError('The second argument "values" must be ' + 'array-like') + + if is_nonelike(axis): + def impl(arr, values, axis=None): + arr = np.ravel(np.asarray(arr)) + values = np.ravel(np.asarray(values)) + return np.concatenate((arr, values)) + else: + + if not isinstance(axis, types.Integer): + raise errors.TypingError('The third argument "axis" must be an ' + 'integer') + + def impl(arr, values, axis=None): + return np.concatenate((arr, values), axis=axis) + return impl + + +@lower_builtin('array.ravel', types.Array) +def array_ravel(context, builder, sig, args): + # Only support no argument version (default order='C') + def imp_nocopy(ary): + """No copy version""" + return ary.reshape(ary.size) + + def imp_copy(ary): + """Copy version""" + return ary.flatten() + + # If the input array is C layout already, use the nocopy version + if sig.args[0].layout == 'C': + imp = imp_nocopy + # otherwise, use flatten under-the-hood + else: + imp = imp_copy + + res = context.compile_internal(builder, imp, sig, args) + res = impl_ret_new_ref(context, builder, sig.return_type, res) + return res + + +@lower_builtin(np.ravel, types.Array) +def np_ravel(context, builder, sig, args): + def np_ravel_impl(a): + return a.ravel() + + return context.compile_internal(builder, np_ravel_impl, sig, args) + + +@lower_builtin('array.flatten', types.Array) +def array_flatten(context, builder, sig, args): + # Only support flattening to C layout currently. + def imp(ary): + return ary.copy().reshape(ary.size) + + res = context.compile_internal(builder, imp, sig, args) + res = impl_ret_new_ref(context, builder, sig.return_type, res) + return res + + +@register_jitable +def _np_clip_impl(a, a_min, a_max, out): + # Both a_min and a_max are numpy arrays + ret = np.empty_like(a) if out is None else out + a_b, a_min_b, a_max_b = np.broadcast_arrays(a, a_min, a_max) + for index in np.ndindex(a_b.shape): + val_a = a_b[index] + val_a_min = a_min_b[index] + val_a_max = a_max_b[index] + ret[index] = min(max(val_a, val_a_min), val_a_max) + + return ret + + +@register_jitable +def _np_clip_impl_none(a, b, use_min, out): + for index in np.ndindex(a.shape): + val_a = a[index] + val_b = b[index] + if use_min: + out[index] = min(val_a, val_b) + else: + out[index] = max(val_a, val_b) + return out + + +@overload(np.clip) +def np_clip(a, a_min, a_max, out=None): + if not type_can_asarray(a): + raise errors.TypingError('The argument "a" must be array-like') + + if (not isinstance(a_min, types.NoneType) and + not type_can_asarray(a_min)): + raise errors.TypingError(('The argument "a_min" must be a number ' + 'or an array-like')) + + if (not isinstance(a_max, types.NoneType) and + not type_can_asarray(a_max)): + raise errors.TypingError('The argument "a_max" must be a number ' + 'or an array-like') + + if not (isinstance(out, types.Array) or is_nonelike(out)): + msg = 'The argument "out" must be an array if it is provided' + raise errors.TypingError(msg) + + # TODO: support scalar a (issue #3469) + a_min_is_none = a_min is None or isinstance(a_min, types.NoneType) + a_max_is_none = a_max is None or isinstance(a_max, types.NoneType) + + if a_min_is_none and a_max_is_none: + # Raises value error when both a_min and a_max are None + def np_clip_nn(a, a_min, a_max, out=None): + raise ValueError("array_clip: must set either max or min") + + return np_clip_nn + + a_min_is_scalar = isinstance(a_min, types.Number) + a_max_is_scalar = isinstance(a_max, types.Number) + + if a_min_is_scalar and a_max_is_scalar: + def np_clip_ss(a, a_min, a_max, out=None): + # a_min and a_max are scalars + # since their shape will be empty + # so broadcasting is not needed at all + ret = np.empty_like(a) if out is None else out + for index in np.ndindex(a.shape): + val_a = a[index] + ret[index] = min(max(val_a, a_min), a_max) + + return ret + + return np_clip_ss + elif a_min_is_scalar and not a_max_is_scalar: + if a_max_is_none: + def np_clip_sn(a, a_min, a_max, out=None): + # a_min is a scalar + # since its shape will be empty + # so broadcasting is not needed at all + ret = np.empty_like(a) if out is None else out + for index in np.ndindex(a.shape): + val_a = a[index] + ret[index] = max(val_a, a_min) + + return ret + + return np_clip_sn + else: + def np_clip_sa(a, a_min, a_max, out=None): + # a_min is a scalar + # since its shape will be empty + # broadcast it to shape of a + # by using np.full_like + a_min_full = np.full_like(a, a_min) + return _np_clip_impl(a, a_min_full, a_max, out) + + return np_clip_sa + elif not a_min_is_scalar and a_max_is_scalar: + if a_min_is_none: + def np_clip_ns(a, a_min, a_max, out=None): + # a_max is a scalar + # since its shape will be empty + # so broadcasting is not needed at all + ret = np.empty_like(a) if out is None else out + for index in np.ndindex(a.shape): + val_a = a[index] + ret[index] = min(val_a, a_max) + + return ret + + return np_clip_ns + else: + def np_clip_as(a, a_min, a_max, out=None): + # a_max is a scalar + # since its shape will be empty + # broadcast it to shape of a + # by using np.full_like + a_max_full = np.full_like(a, a_max) + return _np_clip_impl(a, a_min, a_max_full, out) + + return np_clip_as + else: + # Case where exactly one of a_min or a_max is None + if a_min_is_none: + def np_clip_na(a, a_min, a_max, out=None): + # a_max is a numpy array but a_min is None + ret = np.empty_like(a) if out is None else out + a_b, a_max_b = np.broadcast_arrays(a, a_max) + return _np_clip_impl_none(a_b, a_max_b, True, ret) + + return np_clip_na + elif a_max_is_none: + def np_clip_an(a, a_min, a_max, out=None): + # a_min is a numpy array but a_max is None + ret = np.empty_like(a) if out is None else out + a_b, a_min_b = np.broadcast_arrays(a, a_min) + return _np_clip_impl_none(a_b, a_min_b, False, ret) + + return np_clip_an + else: + def np_clip_aa(a, a_min, a_max, out=None): + # Both a_min and a_max are clearly arrays + # because none of the above branches + # returned + return _np_clip_impl(a, a_min, a_max, out) + + return np_clip_aa + + +@overload_method(types.Array, 'clip') +def array_clip(a, a_min=None, a_max=None, out=None): + def impl(a, a_min=None, a_max=None, out=None): + return np.clip(a, a_min, a_max, out) + return impl + + +def _change_dtype(context, builder, oldty, newty, ary): + """ + Attempt to fix up *ary* for switching from *oldty* to *newty*. + + See Numpy's array_descr_set() + (np/core/src/multiarray/getset.c). + Attempt to fix the array's shape and strides for a new dtype. + False is returned on failure, True on success. + """ + assert oldty.ndim == newty.ndim + assert oldty.layout == newty.layout + + new_layout = ord(newty.layout) + any_layout = ord('A') + c_layout = ord('C') + f_layout = ord('F') + + int8 = types.int8 + + def imp(nd, dims, strides, old_itemsize, new_itemsize, layout): + # Attempt to update the layout due to limitation of the numba + # type system. + if layout == any_layout: + # Test rightmost stride to be contiguous + if strides[-1] == old_itemsize: + # Process this as if it is C contiguous + layout = int8(c_layout) + # Test leftmost stride to be F contiguous + elif strides[0] == old_itemsize: + # Process this as if it is F contiguous + layout = int8(f_layout) + + if old_itemsize != new_itemsize and (layout == any_layout or nd == 0): + return False + + if layout == c_layout: + i = nd - 1 + else: + i = 0 + + if new_itemsize < old_itemsize: + # If it is compatible, increase the size of the dimension + # at the end (or at the front if F-contiguous) + if (old_itemsize % new_itemsize) != 0: + return False + + newdim = old_itemsize // new_itemsize + dims[i] *= newdim + strides[i] = new_itemsize + + elif new_itemsize > old_itemsize: + # Determine if last (or first if F-contiguous) dimension + # is compatible + bytelength = dims[i] * old_itemsize + if (bytelength % new_itemsize) != 0: + return False + + dims[i] = bytelength // new_itemsize + strides[i] = new_itemsize + + else: + # Same item size: nothing to do (this also works for + # non-contiguous arrays). + pass + + return True + + old_itemsize = context.get_constant(types.intp, + get_itemsize(context, oldty)) + new_itemsize = context.get_constant(types.intp, + get_itemsize(context, newty)) + + nd = context.get_constant(types.intp, newty.ndim) + shape_data = cgutils.gep_inbounds(builder, ary._get_ptr_by_name('shape'), + 0, 0) + strides_data = cgutils.gep_inbounds(builder, + ary._get_ptr_by_name('strides'), 0, 0) + + shape_strides_array_type = types.Array(dtype=types.intp, ndim=1, layout='C') + arycls = context.make_array(shape_strides_array_type) + + shape_constant = cgutils.pack_array(builder, + [context.get_constant(types.intp, + newty.ndim)]) + + sizeof_intp = context.get_abi_sizeof(context.get_data_type(types.intp)) + sizeof_intp = context.get_constant(types.intp, sizeof_intp) + strides_constant = cgutils.pack_array(builder, [sizeof_intp]) + + shape_ary = arycls(context, builder) + + populate_array(shape_ary, + data=shape_data, + shape=shape_constant, + strides=strides_constant, + itemsize=sizeof_intp, + meminfo=None) + + strides_ary = arycls(context, builder) + populate_array(strides_ary, + data=strides_data, + shape=shape_constant, + strides=strides_constant, + itemsize=sizeof_intp, + meminfo=None) + + shape = shape_ary._getvalue() + strides = strides_ary._getvalue() + args = [nd, shape, strides, old_itemsize, new_itemsize, + context.get_constant(types.int8, new_layout)] + + sig = signature(types.boolean, + types.intp, # nd + shape_strides_array_type, # dims + shape_strides_array_type, # strides + types.intp, # old_itemsize + types.intp, # new_itemsize + types.int8, # layout + ) + + res = context.compile_internal(builder, imp, sig, args) + update_array_info(newty, ary) + res = impl_ret_borrowed(context, builder, sig.return_type, res) + return res + + +@overload(np.shape) +def np_shape(a): + if not type_can_asarray(a): + raise errors.TypingError("The argument to np.shape must be array-like") + + def impl(a): + return np.asarray(a).shape + return impl + + +@overload(np.size) +def np_size(a): + if not type_can_asarray(a): + raise errors.TypingError("The argument to np.size must be array-like") + + def impl(a): + return np.asarray(a).size + return impl + +# ------------------------------------------------------------------------------ + + +@overload(np.unique) +def np_unique(ar): + def np_unique_impl(ar): + def isnan(x): + # instead of np.isnan because it can't handle non-numeric type + return not (x == x) + b = np.sort(ar.ravel()) + head = list(b[:1]) + tail = [ + x for i, x in enumerate(b[1:]) + if b[i] != x and not (isnan(b[i]) and isnan(x)) + ] + return np.array(head + tail) + return np_unique_impl + + +@overload(np.repeat) +def np_repeat(a, repeats): + # Implementation for repeats being a scalar is a module global function + # (see below) because it might be called from the implementation below. + + def np_repeat_impl_repeats_array_like(a, repeats): + # implementation if repeats is an array like + repeats_array = np.asarray(repeats, dtype=np.int64) + # if it is a singleton array, invoke the scalar implementation + if repeats_array.shape[0] == 1: + return np_repeat_impl_repeats_scaler(a, repeats_array[0]) + if np.any(repeats_array < 0): + raise ValueError("negative dimensions are not allowed") + asa = np.asarray(a) + aravel = asa.ravel() + n = aravel.shape[0] + if aravel.shape != repeats_array.shape: + raise ValueError( + "operands could not be broadcast together") + to_return = np.empty(np.sum(repeats_array), dtype=asa.dtype) + pos = 0 + for i in range(n): + to_return[pos : pos + repeats_array[i]] = aravel[i] + pos += repeats_array[i] + return to_return + + # type checking + if isinstance(a, (types.Array, + types.List, + types.BaseTuple, + types.Number, + types.Boolean, + ) + ): + if isinstance(repeats, types.Integer): + return np_repeat_impl_repeats_scaler + elif isinstance(repeats, (types.Array, types.List)): + if isinstance(repeats.dtype, types.Integer): + return np_repeat_impl_repeats_array_like + + raise errors.TypingError( + "The repeats argument must be an integer " + "or an array-like of integer dtype") + + +@register_jitable +def np_repeat_impl_repeats_scaler(a, repeats): + if repeats < 0: + raise ValueError("negative dimensions are not allowed") + asa = np.asarray(a) + aravel = asa.ravel() + n = aravel.shape[0] + if repeats == 0: + return np.empty(0, dtype=asa.dtype) + elif repeats == 1: + return np.copy(aravel) + else: + to_return = np.empty(n * repeats, dtype=asa.dtype) + for i in range(n): + to_return[i * repeats : (i + 1) * repeats] = aravel[i] + return to_return + + +@extending.overload_method(types.Array, 'repeat') +def array_repeat(a, repeats): + def array_repeat_impl(a, repeats): + return np.repeat(a, repeats) + + return array_repeat_impl + + +@intrinsic +def _intrin_get_itemsize(tyctx, dtype): + """Computes the itemsize of the dtype""" + sig = types.intp(dtype) + + def codegen(cgctx, builder, sig, llargs): + llty = cgctx.get_data_type(sig.args[0].dtype) + llintp = cgctx.get_data_type(sig.return_type) + return llintp(cgctx.get_abi_sizeof(llty)) + return sig, codegen + + +def _compatible_view(a, dtype): + pass + + +@overload(_compatible_view, target='generic') +def ol_compatible_view(a, dtype): + """Determines if the array and dtype are compatible for forming a view.""" + # NOTE: NumPy 1.23+ uses this check. + # Code based on: + # https://github.com/numpy/numpy/blob/750ad21258cfc00663586d5a466e24f91b48edc7/numpy/core/src/multiarray/getset.c#L500-L555 # noqa: E501 + def impl(a, dtype): + dtype_size = _intrin_get_itemsize(dtype) + if dtype_size != a.itemsize: + # catch forbidden cases + if a.ndim == 0: + msg1 = ("Changing the dtype of a 0d array is only supported " + "if the itemsize is unchanged") + raise ValueError(msg1) + else: + # NumPy has a check here for subarray type conversion which + # Numba doesn't support + pass + + # Resize on last axis only + axis = a.ndim - 1 + p1 = a.shape[axis] != 1 + p2 = a.size != 0 + p3 = a.strides[axis] != a.itemsize + if (p1 and p2 and p3): + msg2 = ("To change to a dtype of a different size, the last " + "axis must be contiguous") + raise ValueError(msg2) + + if dtype_size < a.itemsize: + if dtype_size == 0 or a.itemsize % dtype_size != 0: + msg3 = ("When changing to a smaller dtype, its size must " + "be a divisor of the size of original dtype") + raise ValueError(msg3) + else: + newdim = a.shape[axis] * a.itemsize + if newdim % dtype_size != 0: + msg4 = ("When changing to a larger dtype, its size must be " + "a divisor of the total size in bytes of the last " + "axis of the array.") + raise ValueError(msg4) + return impl + + +@lower_builtin('array.view', types.Array, types.DTypeSpec) +def array_view(context, builder, sig, args): + aryty = sig.args[0] + retty = sig.return_type + + ary = make_array(aryty)(context, builder, args[0]) + ret = make_array(retty)(context, builder) + # Copy all fields, casting the "data" pointer appropriately + fields = set(ret._datamodel._fields) + for k in sorted(fields): + val = getattr(ary, k) + if k == 'data': + ptrty = ret.data.type + ret.data = builder.bitcast(val, ptrty) + else: + setattr(ret, k, val) + + if numpy_version >= (1, 23): + # NumPy 1.23+ bans views using a dtype that is a different size to that + # of the array when the last axis is not contiguous. For example, this + # manifests at runtime when a dtype size altering view is requested + # on a Fortran ordered array. + + tyctx = context.typing_context + fnty = tyctx.resolve_value_type(_compatible_view) + _compatible_view_sig = fnty.get_call_type(tyctx, (*sig.args,), {}) + impl = context.get_function(fnty, _compatible_view_sig) + impl(builder, args) + + ok = _change_dtype(context, builder, aryty, retty, ret) + fail = builder.icmp_unsigned('==', ok, Constant(ok.type, 0)) + + with builder.if_then(fail): + msg = "new type not compatible with array" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + res = ret._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +# ------------------------------------------------------------------------------ +# Array attributes + +@lower_getattr(types.Array, "dtype") +def array_dtype(context, builder, typ, value): + res = context.get_dummy_value() + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "shape") +@lower_getattr(types.MemoryView, "shape") +def array_shape(context, builder, typ, value): + arrayty = make_array(typ) + array = arrayty(context, builder, value) + res = array.shape + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "strides") +@lower_getattr(types.MemoryView, "strides") +def array_strides(context, builder, typ, value): + arrayty = make_array(typ) + array = arrayty(context, builder, value) + res = array.strides + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "ndim") +@lower_getattr(types.MemoryView, "ndim") +def array_ndim(context, builder, typ, value): + res = context.get_constant(types.intp, typ.ndim) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "size") +def array_size(context, builder, typ, value): + arrayty = make_array(typ) + array = arrayty(context, builder, value) + res = array.nitems + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "itemsize") +@lower_getattr(types.MemoryView, "itemsize") +def array_itemsize(context, builder, typ, value): + arrayty = make_array(typ) + array = arrayty(context, builder, value) + res = array.itemsize + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.Array, "nbytes") +@lower_getattr(types.MemoryView, "nbytes") +def array_nbytes(context, builder, typ, value): + """ + nbytes = size * itemsize + """ + arrayty = make_array(typ) + array = arrayty(context, builder, value) + res = builder.mul(array.nitems, array.itemsize) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.MemoryView, "contiguous") +def array_contiguous(context, builder, typ, value): + res = context.get_constant(types.boolean, typ.is_contig) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.MemoryView, "c_contiguous") +def array_c_contiguous(context, builder, typ, value): + res = context.get_constant(types.boolean, typ.is_c_contig) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.MemoryView, "f_contiguous") +def array_f_contiguous(context, builder, typ, value): + res = context.get_constant(types.boolean, typ.is_f_contig) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.MemoryView, "readonly") +def array_readonly(context, builder, typ, value): + res = context.get_constant(types.boolean, not typ.mutable) + return impl_ret_untracked(context, builder, typ, res) + + +# array.ctypes + +@lower_getattr(types.Array, "ctypes") +def array_ctypes(context, builder, typ, value): + arrayty = make_array(typ) + array = arrayty(context, builder, value) + # Create new ArrayCType structure + act = types.ArrayCTypes(typ) + ctinfo = context.make_helper(builder, act) + ctinfo.data = array.data + ctinfo.meminfo = array.meminfo + res = ctinfo._getvalue() + return impl_ret_borrowed(context, builder, act, res) + + +@lower_getattr(types.ArrayCTypes, "data") +def array_ctypes_data(context, builder, typ, value): + ctinfo = context.make_helper(builder, typ, value=value) + res = ctinfo.data + # Convert it to an integer + res = builder.ptrtoint(res, context.get_value_type(types.intp)) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_cast(types.ArrayCTypes, types.CPointer) +@lower_cast(types.ArrayCTypes, types.voidptr) +def array_ctypes_to_pointer(context, builder, fromty, toty, val): + ctinfo = context.make_helper(builder, fromty, value=val) + res = ctinfo.data + res = builder.bitcast(res, context.get_value_type(toty)) + return impl_ret_untracked(context, builder, toty, res) + + +def _call_contiguous_check(checker, context, builder, aryty, ary): + """Helper to invoke the contiguous checker function on an array + + Args + ---- + checker : + ``numba.numpy_supports.is_contiguous``, or + ``numba.numpy_supports.is_fortran``. + context : target context + builder : llvm ir builder + aryty : numba type + ary : llvm value + """ + ary = make_array(aryty)(context, builder, value=ary) + tup_intp = types.UniTuple(types.intp, aryty.ndim) + itemsize = context.get_abi_sizeof(context.get_value_type(aryty.dtype)) + check_sig = signature(types.bool_, tup_intp, tup_intp, types.intp) + check_args = [ary.shape, ary.strides, + context.get_constant(types.intp, itemsize)] + is_contig = context.compile_internal(builder, checker, check_sig, + check_args) + return is_contig + + +# array.flags + +@lower_getattr(types.Array, "flags") +def array_flags(context, builder, typ, value): + flagsobj = context.make_helper(builder, types.ArrayFlags(typ)) + flagsobj.parent = value + res = flagsobj._getvalue() + context.nrt.incref(builder, typ, value) + return impl_ret_new_ref(context, builder, typ, res) + + +@lower_getattr(types.ArrayFlags, "contiguous") +@lower_getattr(types.ArrayFlags, "c_contiguous") +def array_flags_c_contiguous(context, builder, typ, value): + if typ.array_type.layout != 'C': + # any layout can still be contiguous + flagsobj = context.make_helper(builder, typ, value=value) + res = _call_contiguous_check(is_contiguous, context, builder, + typ.array_type, flagsobj.parent) + else: + val = typ.array_type.layout == 'C' + res = context.get_constant(types.boolean, val) + return impl_ret_untracked(context, builder, typ, res) + + +@lower_getattr(types.ArrayFlags, "f_contiguous") +def array_flags_f_contiguous(context, builder, typ, value): + if typ.array_type.layout != 'F': + # any layout can still be contiguous + flagsobj = context.make_helper(builder, typ, value=value) + res = _call_contiguous_check(is_fortran, context, builder, + typ.array_type, flagsobj.parent) + else: + layout = typ.array_type.layout + val = layout == 'F' if typ.array_type.ndim > 1 else layout in 'CF' + res = context.get_constant(types.boolean, val) + return impl_ret_untracked(context, builder, typ, res) + + +# ------------------------------------------------------------------------------ +# .real / .imag + +@lower_getattr(types.Array, "real") +def array_real_part(context, builder, typ, value): + if typ.dtype in types.complex_domain: + return array_complex_attr(context, builder, typ, value, attr='real') + elif typ.dtype in types.number_domain: + # as an identity function + return impl_ret_borrowed(context, builder, typ, value) + else: + raise NotImplementedError('unsupported .real for {}'.format(type.dtype)) + + +@lower_getattr(types.Array, "imag") +def array_imag_part(context, builder, typ, value): + if typ.dtype in types.complex_domain: + return array_complex_attr(context, builder, typ, value, attr='imag') + elif typ.dtype in types.number_domain: + # return a readonly zero array + sig = signature(typ.copy(readonly=True), typ) + arrtype, shapes = _parse_empty_like_args(context, builder, sig, [value]) + ary = _empty_nd_impl(context, builder, arrtype, shapes) + cgutils.memset(builder, ary.data, builder.mul(ary.itemsize, + ary.nitems), 0) + return impl_ret_new_ref(context, builder, sig.return_type, + ary._getvalue()) + else: + raise NotImplementedError('unsupported .imag for {}'.format(type.dtype)) + + +def array_complex_attr(context, builder, typ, value, attr): + """ + Given a complex array, it's memory layout is: + + R C R C R C + ^ ^ ^ + + (`R` indicates a float for the real part; + `C` indicates a float for the imaginary part; + the `^` indicates the start of each element) + + To get the real part, we can simply change the dtype and itemsize to that + of the underlying float type. The new layout is: + + R x R x R x + ^ ^ ^ + + (`x` indicates unused) + + A load operation will use the dtype to determine the number of bytes to + load. + + To get the imaginary part, we shift the pointer by 1 float offset and + change the dtype and itemsize. The new layout is: + + x C x C x C + ^ ^ ^ + """ + if attr not in ['real', 'imag'] or typ.dtype not in types.complex_domain: + raise NotImplementedError("cannot get attribute `{}`".format(attr)) + + arrayty = make_array(typ) + array = arrayty(context, builder, value) + + # sizeof underlying float type + flty = typ.dtype.underlying_float + sizeof_flty = context.get_abi_sizeof(context.get_data_type(flty)) + itemsize = array.itemsize.type(sizeof_flty) + + # cast data pointer to float type + llfltptrty = context.get_value_type(flty).as_pointer() + dataptr = builder.bitcast(array.data, llfltptrty) + + # add offset + if attr == 'imag': + dataptr = builder.gep(dataptr, [ir.IntType(32)(1)]) + + # make result + resultty = typ.copy(dtype=flty, layout='A') + result = make_array(resultty)(context, builder) + repl = dict(data=dataptr, itemsize=itemsize) + cgutils.copy_struct(result, array, repl) + return impl_ret_borrowed(context, builder, resultty, result._getvalue()) + + +@overload_method(types.Array, 'conj') +@overload_method(types.Array, 'conjugate') +def array_conj(arr): + def impl(arr): + return np.conj(arr) + return impl + +# ------------------------------------------------------------------------------ +# DType attribute + + +def dtype_type(context, builder, dtypety, dtypeval): + # Just return a dummy opaque value + return context.get_dummy_value() + + +lower_getattr(types.DType, 'type')(dtype_type) +lower_getattr(types.DType, 'kind')(dtype_type) + + +# ------------------------------------------------------------------------------ +# static_getitem on Numba numerical types to create "array" types + + +@lower_builtin('static_getitem', types.NumberClass, types.Any) +def static_getitem_number_clazz(context, builder, sig, args): + """This handles the "static_getitem" when a Numba type is subscripted e.g: + var = typed.List.empty_list(float64[::1, :]) + It only allows this on simple numerical types. Compound types, like + records, are not supported. + """ + retty = sig.return_type + if isinstance(retty, types.Array): + # This isn't used or practically accessible, but has to exist, so just + # put in a NULL of the right type. + res = context.get_value_type(retty)(None) + return impl_ret_untracked(context, builder, retty, res) + else: + # This should be unreachable unless the implementation on the Type + # metaclass is changed. + msg = ("Unreachable; the definition of __getitem__ on the " + "numba.types.abstract.Type metaclass should prevent access.") + raise errors.LoweringError(msg) + + +# ------------------------------------------------------------------------------ +# Structured / record lookup + +@lower_getattr_generic(types.Array) +def array_record_getattr(context, builder, typ, value, attr): + """ + Generic getattr() implementation for record arrays: fetch the given + record member, i.e. a subarray. + """ + arrayty = make_array(typ) + array = arrayty(context, builder, value) + + rectype = typ.dtype + if not isinstance(rectype, types.Record): + raise NotImplementedError("attribute %r of %s not defined" + % (attr, typ)) + dtype = rectype.typeof(attr) + offset = rectype.offset(attr) + + if isinstance(dtype, types.NestedArray): + resty = typ.copy( + dtype=dtype.dtype, ndim=typ.ndim + dtype.ndim, layout='A') + else: + resty = typ.copy(dtype=dtype, layout='A') + + raryty = make_array(resty) + + rary = raryty(context, builder) + + constoffset = context.get_constant(types.intp, offset) + + newdataptr = cgutils.pointer_add( + builder, array.data, constoffset, return_type=rary.data.type, + ) + if isinstance(dtype, types.NestedArray): + # new shape = recarray shape + inner dimension from nestedarray + shape = cgutils.unpack_tuple(builder, array.shape, typ.ndim) + shape += [context.get_constant(types.intp, i) for i in dtype.shape] + # new strides = recarray strides + strides of the inner nestedarray + strides = cgutils.unpack_tuple(builder, array.strides, typ.ndim) + strides += [context.get_constant(types.intp, i) for i in dtype.strides] + # New datasize = size of elements of the nestedarray + datasize = context.get_abi_sizeof(context.get_data_type(dtype.dtype)) + else: + # New shape, strides, and datasize match the underlying array + shape = array.shape + strides = array.strides + datasize = context.get_abi_sizeof(context.get_data_type(dtype)) + populate_array(rary, + data=newdataptr, + shape=shape, + strides=strides, + itemsize=context.get_constant(types.intp, datasize), + meminfo=array.meminfo, + parent=array.parent) + res = rary._getvalue() + return impl_ret_borrowed(context, builder, resty, res) + + +@lower_builtin('static_getitem', types.Array, types.StringLiteral) +def array_record_getitem(context, builder, sig, args): + index = args[1] + if not isinstance(index, str): + # This will fallback to normal getitem + raise NotImplementedError + return array_record_getattr(context, builder, sig.args[0], args[0], index) + + +@lower_getattr_generic(types.Record) +def record_getattr(context, builder, typ, value, attr): + """ + Generic getattr() implementation for records: get the given record member. + """ + context.sentry_record_alignment(typ, attr) + offset = typ.offset(attr) + elemty = typ.typeof(attr) + + if isinstance(elemty, types.NestedArray): + # Only a nested array's *data* is stored in a structured array, + # so we create an array structure to point to that data. + aryty = make_array(elemty) + ary = aryty(context, builder) + dtype = elemty.dtype + newshape = [context.get_constant(types.intp, s) for s in + elemty.shape] + newstrides = [context.get_constant(types.intp, s) for s in + elemty.strides] + newdata = cgutils.get_record_member(builder, value, offset, + context.get_data_type(dtype)) + populate_array( + ary, + data=newdata, + shape=cgutils.pack_array(builder, newshape), + strides=cgutils.pack_array(builder, newstrides), + itemsize=context.get_constant(types.intp, elemty.size), + meminfo=None, + parent=None, + ) + res = ary._getvalue() + return impl_ret_borrowed(context, builder, typ, res) + else: + dptr = cgutils.get_record_member(builder, value, offset, + context.get_data_type(elemty)) + align = None if typ.aligned else 1 + res = context.unpack_value(builder, elemty, dptr, align) + return impl_ret_borrowed(context, builder, typ, res) + + +@lower_setattr_generic(types.Record) +def record_setattr(context, builder, sig, args, attr): + """ + Generic setattr() implementation for records: set the given record member. + """ + typ, valty = sig.args + target, val = args + + context.sentry_record_alignment(typ, attr) + offset = typ.offset(attr) + elemty = typ.typeof(attr) + + if isinstance(elemty, types.NestedArray): + # Copy the data from the RHS into the nested array + val_struct = cgutils.create_struct_proxy(valty)(context, builder, + value=args[1]) + src = val_struct.data + dest = cgutils.get_record_member(builder, target, offset, + src.type.pointee) + cgutils.memcpy(builder, dest, src, + context.get_constant(types.intp, elemty.nitems)) + else: + # Set the given scalar record member + dptr = cgutils.get_record_member(builder, target, offset, + context.get_data_type(elemty)) + val = context.cast(builder, val, valty, elemty) + align = None if typ.aligned else 1 + context.pack_value(builder, elemty, val, dptr, align=align) + + +@lower_builtin('static_getitem', types.Record, types.StringLiteral) +def record_static_getitem_str(context, builder, sig, args): + """ + Record.__getitem__ redirects to getattr() + """ + impl = context.get_getattr(sig.args[0], args[1]) + return impl(context, builder, sig.args[0], args[0], args[1]) + + +@lower_builtin('static_getitem', types.Record, types.IntegerLiteral) +def record_static_getitem_int(context, builder, sig, args): + """ + Record.__getitem__ redirects to getattr() + """ + idx = sig.args[1].literal_value + fields = list(sig.args[0].fields) + ll_field = context.insert_const_string(builder.module, fields[idx]) + impl = context.get_getattr(sig.args[0], ll_field) + return impl(context, builder, sig.args[0], args[0], fields[idx]) + + +@lower_builtin('static_setitem', types.Record, types.StringLiteral, types.Any) +def record_static_setitem_str(context, builder, sig, args): + """ + Record.__setitem__ redirects to setattr() + """ + recty, _, valty = sig.args + rec, idx, val = args + getattr_sig = signature(sig.return_type, recty, valty) + impl = context.get_setattr(idx, getattr_sig) + assert impl is not None + return impl(builder, (rec, val)) + + +@lower_builtin('static_setitem', types.Record, types.IntegerLiteral, types.Any) +def record_static_setitem_int(context, builder, sig, args): + """ + Record.__setitem__ redirects to setattr() + """ + recty, _, valty = sig.args + rec, idx, val = args + getattr_sig = signature(sig.return_type, recty, valty) + fields = list(sig.args[0].fields) + impl = context.get_setattr(fields[idx], getattr_sig) + assert impl is not None + return impl(builder, (rec, val)) + + +# ------------------------------------------------------------------------------ +# Constant arrays and records + + +@lower_constant(types.Array) +def constant_array(context, builder, ty, pyval): + """ + Create a constant array (mechanism is target-dependent). + """ + return context.make_constant_array(builder, ty, pyval) + + +@lower_constant(types.Record) +def constant_record(context, builder, ty, pyval): + """ + Create a record constant as a stack-allocated array of bytes. + """ + lty = ir.ArrayType(ir.IntType(8), pyval.nbytes) + val = lty(bytearray(pyval.tobytes())) + return cgutils.alloca_once_value(builder, val) + + +@lower_constant(types.Bytes) +def constant_bytes(context, builder, ty, pyval): + """ + Create a constant array from bytes (mechanism is target-dependent). + """ + buf = np.array(bytearray(pyval), dtype=np.uint8) + return context.make_constant_array(builder, ty, buf) + +# ------------------------------------------------------------------------------ +# Comparisons + + +@lower_builtin(operator.is_, types.Array, types.Array) +def array_is(context, builder, sig, args): + aty, bty = sig.args + if aty != bty: + return cgutils.false_bit + + def array_is_impl(a, b): + return (a.shape == b.shape and + a.strides == b.strides and + a.ctypes.data == b.ctypes.data) + + return context.compile_internal(builder, array_is_impl, sig, args) + +# ------------------------------------------------------------------------------ +# Hash + + +@overload_attribute(types.Array, "__hash__") +def ol_array_hash(arr): + return lambda arr: None + + +# ------------------------------------------------------------------------------ +# builtin `np.flat` implementation + +def make_array_flat_cls(flatiterty): + """ + Return the Structure representation of the given *flatiterty* (an + instance of types.NumpyFlatType). + """ + return _make_flattening_iter_cls(flatiterty, 'flat') + + +def make_array_ndenumerate_cls(nditerty): + """ + Return the Structure representation of the given *nditerty* (an + instance of types.NumpyNdEnumerateType). + """ + return _make_flattening_iter_cls(nditerty, 'ndenumerate') + + +def _increment_indices(context, builder, ndim, shape, indices, end_flag=None, + loop_continue=None, loop_break=None): + zero = context.get_constant(types.intp, 0) + + bbend = builder.append_basic_block('end_increment') + + if end_flag is not None: + builder.store(cgutils.false_byte, end_flag) + + for dim in reversed(range(ndim)): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + idx = cgutils.increment_index(builder, builder.load(idxptr)) + + count = shape[dim] + in_bounds = builder.icmp_signed('<', idx, count) + with cgutils.if_likely(builder, in_bounds): + # New index is still in bounds + builder.store(idx, idxptr) + if loop_continue is not None: + loop_continue(dim) + builder.branch(bbend) + # Index out of bounds => reset it and proceed it to outer index + builder.store(zero, idxptr) + if loop_break is not None: + loop_break(dim) + + if end_flag is not None: + builder.store(cgutils.true_byte, end_flag) + builder.branch(bbend) + + builder.position_at_end(bbend) + + +def _increment_indices_array(context, builder, arrty, arr, indices, + end_flag=None): + shape = cgutils.unpack_tuple(builder, arr.shape, arrty.ndim) + _increment_indices(context, builder, arrty.ndim, shape, indices, end_flag) + + +def make_nditer_cls(nditerty): + """ + Return the Structure representation of the given *nditerty* (an + instance of types.NumpyNdIterType). + """ + ndim = nditerty.ndim + layout = nditerty.layout + narrays = len(nditerty.arrays) + nshapes = ndim if nditerty.need_shaped_indexing else 1 + + class BaseSubIter(object): + """ + Base class for sub-iterators of a nditer() instance. + """ + + def __init__(self, nditer, member_name, start_dim, end_dim): + self.nditer = nditer + self.member_name = member_name + self.start_dim = start_dim + self.end_dim = end_dim + self.ndim = end_dim - start_dim + + def set_member_ptr(self, ptr): + setattr(self.nditer, self.member_name, ptr) + + @functools.cached_property + def member_ptr(self): + return getattr(self.nditer, self.member_name) + + def init_specific(self, context, builder): + pass + + def loop_continue(self, context, builder, logical_dim): + pass + + def loop_break(self, context, builder, logical_dim): + pass + + class FlatSubIter(BaseSubIter): + """ + Sub-iterator walking a contiguous array in physical order, with + support for broadcasting (the index is reset on the outer dimension). + """ + + def init_specific(self, context, builder): + zero = context.get_constant(types.intp, 0) + self.set_member_ptr(cgutils.alloca_once_value(builder, zero)) + + def compute_pointer(self, context, builder, indices, arrty, arr): + index = builder.load(self.member_ptr) + return builder.gep(arr.data, [index]) + + def loop_continue(self, context, builder, logical_dim): + if logical_dim == self.ndim - 1: + # Only increment index inside innermost logical dimension + index = builder.load(self.member_ptr) + index = cgutils.increment_index(builder, index) + builder.store(index, self.member_ptr) + + def loop_break(self, context, builder, logical_dim): + if logical_dim == 0: + # At the exit of outermost logical dimension, reset index + zero = context.get_constant(types.intp, 0) + builder.store(zero, self.member_ptr) + elif logical_dim == self.ndim - 1: + # Inside innermost logical dimension, increment index + index = builder.load(self.member_ptr) + index = cgutils.increment_index(builder, index) + builder.store(index, self.member_ptr) + + class TrivialFlatSubIter(BaseSubIter): + """ + Sub-iterator walking a contiguous array in physical order, + *without* support for broadcasting. + """ + + def init_specific(self, context, builder): + assert not nditerty.need_shaped_indexing + + def compute_pointer(self, context, builder, indices, arrty, arr): + assert len(indices) <= 1, len(indices) + return builder.gep(arr.data, indices) + + class IndexedSubIter(BaseSubIter): + """ + Sub-iterator walking an array in logical order. + """ + + def compute_pointer(self, context, builder, indices, arrty, arr): + assert len(indices) == self.ndim + return cgutils.get_item_pointer(context, builder, arrty, arr, + indices, wraparound=False) + + class ZeroDimSubIter(BaseSubIter): + """ + Sub-iterator "walking" a 0-d array. + """ + + def compute_pointer(self, context, builder, indices, arrty, arr): + return arr.data + + class ScalarSubIter(BaseSubIter): + """ + Sub-iterator "walking" a scalar value. + """ + + def compute_pointer(self, context, builder, indices, arrty, arr): + return arr + + class NdIter(cgutils.create_struct_proxy(nditerty)): + """ + .nditer() implementation. + + Note: 'F' layout means the shape is iterated in reverse logical order, + so indices and shapes arrays have to be reversed as well. + """ + + @functools.cached_property + def subiters(self): + l = [] + factories = {'flat': FlatSubIter if nditerty.need_shaped_indexing + else TrivialFlatSubIter, + 'indexed': IndexedSubIter, + '0d': ZeroDimSubIter, + 'scalar': ScalarSubIter, + } + for i, sub in enumerate(nditerty.indexers): + kind, start_dim, end_dim, _ = sub + member_name = 'index%d' % i + factory = factories[kind] + l.append(factory(self, member_name, start_dim, end_dim)) + return l + + def init_specific(self, context, builder, arrtys, arrays): + """ + Initialize the nditer() instance for the specific array inputs. + """ + zero = context.get_constant(types.intp, 0) + + # Store inputs + self.arrays = context.make_tuple(builder, types.Tuple(arrtys), + arrays) + # Create slots for scalars + for i, ty in enumerate(arrtys): + if not isinstance(ty, types.Array): + member_name = 'scalar%d' % i + # XXX as_data()? + slot = cgutils.alloca_once_value(builder, arrays[i]) + setattr(self, member_name, slot) + + arrays = self._arrays_or_scalars(context, builder, arrtys, arrays) + + # Extract iterator shape (the shape of the most-dimensional input) + main_shape_ty = types.UniTuple(types.intp, ndim) + main_shape = None + main_nitems = None + for i, arrty in enumerate(arrtys): + if isinstance(arrty, types.Array) and arrty.ndim == ndim: + main_shape = arrays[i].shape + main_nitems = arrays[i].nitems + break + else: + # Only scalar inputs => synthesize a dummy shape + assert ndim == 0 + main_shape = context.make_tuple(builder, main_shape_ty, ()) + main_nitems = context.get_constant(types.intp, 1) + + # Validate shapes of array inputs + def check_shape(shape, main_shape): + n = len(shape) + for i in range(n): + if shape[i] != main_shape[len(main_shape) - n + i]: + raise ValueError("nditer(): operands could not be " + "broadcast together") + + for arrty, arr in zip(arrtys, arrays): + if isinstance(arrty, types.Array) and arrty.ndim > 0: + sig = signature(types.none, + types.UniTuple(types.intp, arrty.ndim), + main_shape_ty) + context.compile_internal(builder, check_shape, + sig, (arr.shape, main_shape)) + + # Compute shape and size + shapes = cgutils.unpack_tuple(builder, main_shape) + if layout == 'F': + shapes = shapes[::-1] + + # If shape is empty, mark iterator exhausted + shape_is_empty = builder.icmp_signed('==', main_nitems, zero) + exhausted = builder.select(shape_is_empty, cgutils.true_byte, + cgutils.false_byte) + + if not nditerty.need_shaped_indexing: + # Flatten shape to make iteration faster on small innermost + # dimensions (e.g. a (100000, 3) shape) + shapes = (main_nitems,) + assert len(shapes) == nshapes + + indices = cgutils.alloca_once(builder, zero.type, size=nshapes) + for dim in range(nshapes): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + builder.store(zero, idxptr) + + self.indices = indices + self.shape = cgutils.pack_array(builder, shapes, zero.type) + self.exhausted = cgutils.alloca_once_value(builder, exhausted) + + # Initialize subiterators + for subiter in self.subiters: + subiter.init_specific(context, builder) + + def iternext_specific(self, context, builder, result): + """ + Compute next iteration of the nditer() instance. + """ + bbend = builder.append_basic_block('end') + + # Branch early if exhausted + exhausted = cgutils.as_bool_bit(builder, + builder.load(self.exhausted)) + with cgutils.if_unlikely(builder, exhausted): + result.set_valid(False) + builder.branch(bbend) + + arrtys = nditerty.arrays + arrays = cgutils.unpack_tuple(builder, self.arrays) + arrays = self._arrays_or_scalars(context, builder, arrtys, arrays) + indices = self.indices + + # Compute iterated results + result.set_valid(True) + views = self._make_views(context, builder, indices, arrtys, arrays) + views = [v._getvalue() for v in views] + if len(views) == 1: + result.yield_(views[0]) + else: + result.yield_(context.make_tuple(builder, nditerty.yield_type, + views)) + + shape = cgutils.unpack_tuple(builder, self.shape) + _increment_indices(context, builder, len(shape), shape, + indices, self.exhausted, + functools.partial(self._loop_continue, + context, + builder), + functools.partial(self._loop_break, + context, + builder), + ) + + builder.branch(bbend) + builder.position_at_end(bbend) + + def _loop_continue(self, context, builder, dim): + for sub in self.subiters: + if sub.start_dim <= dim < sub.end_dim: + sub.loop_continue(context, builder, dim - sub.start_dim) + + def _loop_break(self, context, builder, dim): + for sub in self.subiters: + if sub.start_dim <= dim < sub.end_dim: + sub.loop_break(context, builder, dim - sub.start_dim) + + def _make_views(self, context, builder, indices, arrtys, arrays): + """ + Compute the views to be yielded. + """ + views = [None] * narrays + indexers = nditerty.indexers + subiters = self.subiters + rettys = nditerty.yield_type + if isinstance(rettys, types.BaseTuple): + rettys = list(rettys) + else: + rettys = [rettys] + indices = [builder.load(cgutils.gep_inbounds(builder, indices, i)) + for i in range(nshapes)] + + for sub, subiter in zip(indexers, subiters): + _, _, _, array_indices = sub + sub_indices = indices[subiter.start_dim:subiter.end_dim] + if layout == 'F': + sub_indices = sub_indices[::-1] + for i in array_indices: + assert views[i] is None + views[i] = self._make_view(context, builder, sub_indices, + rettys[i], + arrtys[i], arrays[i], subiter) + assert all(v for v in views) + return views + + def _make_view(self, context, builder, indices, retty, arrty, arr, + subiter): + """ + Compute a 0d view for a given input array. + """ + assert isinstance(retty, types.Array) and retty.ndim == 0 + + ptr = subiter.compute_pointer(context, builder, indices, arrty, arr) + view = context.make_array(retty)(context, builder) + + itemsize = get_itemsize(context, retty) + shape = context.make_tuple(builder, types.UniTuple(types.intp, 0), + ()) + strides = context.make_tuple(builder, types.UniTuple(types.intp, 0), + ()) + # HACK: meminfo=None avoids expensive refcounting operations + # on ephemeral views + populate_array(view, ptr, shape, strides, itemsize, meminfo=None) + return view + + def _arrays_or_scalars(self, context, builder, arrtys, arrays): + # Return a list of either array structures or pointers to + # scalar slots + l = [] + for i, (arrty, arr) in enumerate(zip(arrtys, arrays)): + if isinstance(arrty, types.Array): + l.append(context.make_array(arrty)(context, + builder, + value=arr)) + else: + l.append(getattr(self, "scalar%d" % i)) + return l + + return NdIter + + +def make_ndindex_cls(nditerty): + """ + Return the Structure representation of the given *nditerty* (an + instance of types.NumpyNdIndexType). + """ + ndim = nditerty.ndim + + class NdIndexIter(cgutils.create_struct_proxy(nditerty)): + """ + .ndindex() implementation. + """ + + def init_specific(self, context, builder, shapes): + zero = context.get_constant(types.intp, 0) + indices = cgutils.alloca_once(builder, zero.type, + size=context.get_constant(types.intp, + ndim)) + exhausted = cgutils.alloca_once_value(builder, cgutils.false_byte) + + for dim in range(ndim): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + builder.store(zero, idxptr) + # 0-sized dimensions really indicate an empty array, + # but we have to catch that condition early to avoid + # a bug inside the iteration logic. + dim_size = shapes[dim] + dim_is_empty = builder.icmp_unsigned('==', dim_size, zero) + with cgutils.if_unlikely(builder, dim_is_empty): + builder.store(cgutils.true_byte, exhausted) + + self.indices = indices + self.exhausted = exhausted + self.shape = cgutils.pack_array(builder, shapes, zero.type) + + def iternext_specific(self, context, builder, result): + zero = context.get_constant(types.intp, 0) + + bbend = builder.append_basic_block('end') + + exhausted = cgutils.as_bool_bit(builder, + builder.load(self.exhausted)) + with cgutils.if_unlikely(builder, exhausted): + result.set_valid(False) + builder.branch(bbend) + + indices = [builder.load(cgutils.gep_inbounds(builder, + self.indices, + dim)) + for dim in range(ndim)] + for load in indices: + mark_positive(builder, load) + + result.yield_(cgutils.pack_array(builder, indices, zero.type)) + result.set_valid(True) + + shape = cgutils.unpack_tuple(builder, self.shape, ndim) + _increment_indices(context, builder, ndim, shape, + self.indices, self.exhausted) + + builder.branch(bbend) + builder.position_at_end(bbend) + + return NdIndexIter + + +def _make_flattening_iter_cls(flatiterty, kind): + assert kind in ('flat', 'ndenumerate') + + array_type = flatiterty.array_type + + if array_type.layout == 'C': + class CContiguousFlatIter(cgutils.create_struct_proxy(flatiterty)): + """ + .flat() / .ndenumerate() implementation for C-contiguous arrays. + """ + + def init_specific(self, context, builder, arrty, arr): + zero = context.get_constant(types.intp, 0) + self.index = cgutils.alloca_once_value(builder, zero) + # We can't trust strides[-1] to always contain the right + # step value, see + # http://docs.scipy.org/doc/numpy-dev/release.html#npy-relaxed-strides-checking # noqa: E501 + self.stride = arr.itemsize + + if kind == 'ndenumerate': + # Zero-initialize the indices array. + indices = cgutils.alloca_once( + builder, zero.type, + size=context.get_constant(types.intp, arrty.ndim)) + + for dim in range(arrty.ndim): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + builder.store(zero, idxptr) + + self.indices = indices + + # NOTE: Using gep() instead of explicit pointer addition helps + # LLVM vectorize the loop (since the stride is known and + # constant). This is not possible in the non-contiguous case, + # where the strides are unknown at compile-time. + + def iternext_specific(self, context, builder, arrty, arr, result): + ndim = arrty.ndim + nitems = arr.nitems + + index = builder.load(self.index) + is_valid = builder.icmp_signed('<', index, nitems) + result.set_valid(is_valid) + + with cgutils.if_likely(builder, is_valid): + ptr = builder.gep(arr.data, [index]) + value = load_item(context, builder, arrty, ptr) + if kind == 'flat': + result.yield_(value) + else: + # ndenumerate(): fetch and increment indices + indices = self.indices + idxvals = [builder.load(cgutils.gep_inbounds(builder, + indices, + dim)) + for dim in range(ndim)] + idxtuple = cgutils.pack_array(builder, idxvals, + ty=context.get_data_type( + types.intp)) + result.yield_( + cgutils.make_anonymous_struct(builder, + [idxtuple, value])) + _increment_indices_array(context, builder, arrty, + arr, indices) + + index = cgutils.increment_index(builder, index) + builder.store(index, self.index) + + def getitem(self, context, builder, arrty, arr, index): + ptr = builder.gep(arr.data, [index]) + return load_item(context, builder, arrty, ptr) + + def setitem(self, context, builder, arrty, arr, index, value): + ptr = builder.gep(arr.data, [index]) + store_item(context, builder, arrty, value, ptr) + + return CContiguousFlatIter + + else: + class FlatIter(cgutils.create_struct_proxy(flatiterty)): + """ + Generic .flat() / .ndenumerate() implementation for + non-contiguous arrays. + It keeps track of pointers along each dimension in order to + minimize computations. + """ + + def init_specific(self, context, builder, arrty, arr): + zero = context.get_constant(types.intp, 0) + data = arr.data + ndim = arrty.ndim + shapes = cgutils.unpack_tuple(builder, arr.shape, ndim) + + indices = cgutils.alloca_once( + builder, zero.type, size=context.get_constant(types.intp, + arrty.ndim)) + pointers = cgutils.alloca_once( + builder, data.type, size=context.get_constant(types.intp, + arrty.ndim)) + exhausted = cgutils.alloca_once_value(builder, + cgutils.false_byte) + + # Initialize indices and pointers with their start values. + for dim in range(ndim): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + ptrptr = cgutils.gep_inbounds(builder, pointers, dim) + builder.store(data, ptrptr) + builder.store(zero, idxptr) + # 0-sized dimensions really indicate an empty array, + # but we have to catch that condition early to avoid + # a bug inside the iteration logic (see issue #846). + dim_size = shapes[dim] + dim_is_empty = builder.icmp_unsigned('==', dim_size, zero) + with cgutils.if_unlikely(builder, dim_is_empty): + builder.store(cgutils.true_byte, exhausted) + + self.indices = indices + self.pointers = pointers + self.exhausted = exhausted + + def iternext_specific(self, context, builder, arrty, arr, result): + ndim = arrty.ndim + shapes = cgutils.unpack_tuple(builder, arr.shape, ndim) + strides = cgutils.unpack_tuple(builder, arr.strides, ndim) + indices = self.indices + pointers = self.pointers + + zero = context.get_constant(types.intp, 0) + + bbend = builder.append_basic_block('end') + + # Catch already computed iterator exhaustion + is_exhausted = cgutils.as_bool_bit( + builder, builder.load(self.exhausted)) + with cgutils.if_unlikely(builder, is_exhausted): + result.set_valid(False) + builder.branch(bbend) + result.set_valid(True) + + # Current pointer inside last dimension + last_ptr = cgutils.gep_inbounds(builder, pointers, ndim - 1) + ptr = builder.load(last_ptr) + value = load_item(context, builder, arrty, ptr) + if kind == 'flat': + result.yield_(value) + else: + # ndenumerate() => yield (indices, value) + idxvals = [builder.load(cgutils.gep_inbounds(builder, + indices, + dim)) + for dim in range(ndim)] + idxtuple = cgutils.pack_array(builder, idxvals) + result.yield_( + cgutils.make_anonymous_struct(builder, + [idxtuple, value])) + + # Update indices and pointers by walking from inner + # dimension to outer. + for dim in reversed(range(ndim)): + idxptr = cgutils.gep_inbounds(builder, indices, dim) + idx = cgutils.increment_index(builder, + builder.load(idxptr)) + + count = shapes[dim] + stride = strides[dim] + in_bounds = builder.icmp_signed('<', idx, count) + with cgutils.if_likely(builder, in_bounds): + # Index is valid => pointer can simply be incremented. + builder.store(idx, idxptr) + ptrptr = cgutils.gep_inbounds(builder, pointers, dim) + ptr = builder.load(ptrptr) + ptr = cgutils.pointer_add(builder, ptr, stride) + builder.store(ptr, ptrptr) + # Reset pointers in inner dimensions + for inner_dim in range(dim + 1, ndim): + ptrptr = cgutils.gep_inbounds(builder, + pointers, + inner_dim) + builder.store(ptr, ptrptr) + builder.branch(bbend) + # Reset index and continue with next dimension + builder.store(zero, idxptr) + + # End of array + builder.store(cgutils.true_byte, self.exhausted) + builder.branch(bbend) + + builder.position_at_end(bbend) + + def _ptr_for_index(self, context, builder, arrty, arr, index): + ndim = arrty.ndim + shapes = cgutils.unpack_tuple(builder, arr.shape, count=ndim) + strides = cgutils.unpack_tuple(builder, arr.strides, count=ndim) + + # First convert the flattened index into a regular n-dim index + indices = [] + for dim in reversed(range(ndim)): + indices.append(builder.urem(index, shapes[dim])) + index = builder.udiv(index, shapes[dim]) + indices.reverse() + + ptr = cgutils.get_item_pointer2(context, builder, arr.data, + shapes, strides, arrty.layout, + indices) + return ptr + + def getitem(self, context, builder, arrty, arr, index): + ptr = self._ptr_for_index(context, builder, arrty, arr, index) + return load_item(context, builder, arrty, ptr) + + def setitem(self, context, builder, arrty, arr, index, value): + ptr = self._ptr_for_index(context, builder, arrty, arr, index) + store_item(context, builder, arrty, value, ptr) + + return FlatIter + + +@lower_getattr(types.Array, "flat") +def make_array_flatiter(context, builder, arrty, arr): + flatitercls = make_array_flat_cls(types.NumpyFlatType(arrty)) + flatiter = flatitercls(context, builder) + + flatiter.array = arr + + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, ref=flatiter._get_ptr_by_name('array')) + + flatiter.init_specific(context, builder, arrty, arr) + + res = flatiter._getvalue() + return impl_ret_borrowed(context, builder, types.NumpyFlatType(arrty), res) + + +@lower_builtin('iternext', types.NumpyFlatType) +@iternext_impl(RefType.BORROWED) +def iternext_numpy_flatiter(context, builder, sig, args, result): + [flatiterty] = sig.args + [flatiter] = args + + flatitercls = make_array_flat_cls(flatiterty) + flatiter = flatitercls(context, builder, value=flatiter) + + arrty = flatiterty.array_type + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, value=flatiter.array) + + flatiter.iternext_specific(context, builder, arrty, arr, result) + + +@lower_builtin(operator.getitem, types.NumpyFlatType, types.Integer) +def iternext_numpy_getitem(context, builder, sig, args): + flatiterty = sig.args[0] + flatiter, index = args + + flatitercls = make_array_flat_cls(flatiterty) + flatiter = flatitercls(context, builder, value=flatiter) + + arrty = flatiterty.array_type + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, value=flatiter.array) + + res = flatiter.getitem(context, builder, arrty, arr, index) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(operator.setitem, types.NumpyFlatType, types.Integer, + types.Any) +def iternext_numpy_getitem_any(context, builder, sig, args): + flatiterty = sig.args[0] + flatiter, index, value = args + + flatitercls = make_array_flat_cls(flatiterty) + flatiter = flatitercls(context, builder, value=flatiter) + + arrty = flatiterty.array_type + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, value=flatiter.array) + + flatiter.setitem(context, builder, arrty, arr, index, value) + return context.get_dummy_value() + + +@lower_builtin(len, types.NumpyFlatType) +def iternext_numpy_getitem_flat(context, builder, sig, args): + flatiterty = sig.args[0] + flatitercls = make_array_flat_cls(flatiterty) + flatiter = flatitercls(context, builder, value=args[0]) + + arrcls = context.make_array(flatiterty.array_type) + arr = arrcls(context, builder, value=flatiter.array) + return arr.nitems + + +@lower_builtin(np.ndenumerate, types.Array) +def make_array_ndenumerate(context, builder, sig, args): + arrty, = sig.args + arr, = args + nditercls = make_array_ndenumerate_cls(types.NumpyNdEnumerateType(arrty)) + nditer = nditercls(context, builder) + + nditer.array = arr + + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, ref=nditer._get_ptr_by_name('array')) + + nditer.init_specific(context, builder, arrty, arr) + + res = nditer._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('iternext', types.NumpyNdEnumerateType) +@iternext_impl(RefType.BORROWED) +def iternext_numpy_nditer(context, builder, sig, args, result): + [nditerty] = sig.args + [nditer] = args + + nditercls = make_array_ndenumerate_cls(nditerty) + nditer = nditercls(context, builder, value=nditer) + + arrty = nditerty.array_type + arrcls = context.make_array(arrty) + arr = arrcls(context, builder, value=nditer.array) + + nditer.iternext_specific(context, builder, arrty, arr, result) + + +@lower_builtin(pndindex, types.VarArg(types.Integer)) +@lower_builtin(np.ndindex, types.VarArg(types.Integer)) +def make_array_ndindex(context, builder, sig, args): + """ndindex(*shape)""" + shape = [context.cast(builder, arg, argty, types.intp) + for argty, arg in zip(sig.args, args)] + + nditercls = make_ndindex_cls(types.NumpyNdIndexType(len(shape))) + nditer = nditercls(context, builder) + nditer.init_specific(context, builder, shape) + + res = nditer._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin(pndindex, types.BaseTuple) +@lower_builtin(np.ndindex, types.BaseTuple) +def make_array_ndindex_tuple(context, builder, sig, args): + """ndindex(shape)""" + ndim = sig.return_type.ndim + if ndim > 0: + idxty = sig.args[0].dtype + tup = args[0] + + shape = cgutils.unpack_tuple(builder, tup, ndim) + shape = [context.cast(builder, idx, idxty, types.intp) + for idx in shape] + else: + shape = [] + + nditercls = make_ndindex_cls(types.NumpyNdIndexType(len(shape))) + nditer = nditercls(context, builder) + nditer.init_specific(context, builder, shape) + + res = nditer._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +@lower_builtin('iternext', types.NumpyNdIndexType) +@iternext_impl(RefType.BORROWED) +def iternext_numpy_ndindex(context, builder, sig, args, result): + [nditerty] = sig.args + [nditer] = args + + nditercls = make_ndindex_cls(nditerty) + nditer = nditercls(context, builder, value=nditer) + + nditer.iternext_specific(context, builder, result) + + +@lower_builtin(np.nditer, types.Any) +def make_array_nditer(context, builder, sig, args): + """ + nditer(...) + """ + nditerty = sig.return_type + arrtys = nditerty.arrays + + if isinstance(sig.args[0], types.BaseTuple): + arrays = cgutils.unpack_tuple(builder, args[0]) + else: + arrays = [args[0]] + + nditer = make_nditer_cls(nditerty)(context, builder) + nditer.init_specific(context, builder, arrtys, arrays) + + res = nditer._getvalue() + return impl_ret_borrowed(context, builder, nditerty, res) + + +@lower_builtin('iternext', types.NumpyNdIterType) +@iternext_impl(RefType.BORROWED) +def iternext_numpy_nditer2(context, builder, sig, args, result): + [nditerty] = sig.args + [nditer] = args + + nditer = make_nditer_cls(nditerty)(context, builder, value=nditer) + nditer.iternext_specific(context, builder, result) + + +@lower_builtin(operator.eq, types.DType, types.DType) +def dtype_eq_impl(context, builder, sig, args): + arg1, arg2 = sig.args + res = ir.Constant(ir.IntType(1), int(arg1 == arg2)) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +# ------------------------------------------------------------------------------ +# Numpy array constructors + +def _empty_nd_impl(context, builder, arrtype, shapes): + """Utility function used for allocating a new array during LLVM code + generation (lowering). Given a target context, builder, array + type, and a tuple or list of lowered dimension sizes, returns a + LLVM value pointing at a Numba runtime allocated array. + """ + arycls = make_array(arrtype) + ary = arycls(context, builder) + + datatype = context.get_data_type(arrtype.dtype) + itemsize = context.get_constant(types.intp, get_itemsize(context, arrtype)) + + # compute array length + arrlen = context.get_constant(types.intp, 1) + overflow = Constant(ir.IntType(1), 0) + for s in shapes: + arrlen_mult = builder.smul_with_overflow(arrlen, s) + arrlen = builder.extract_value(arrlen_mult, 0) + overflow = builder.or_( + overflow, builder.extract_value(arrlen_mult, 1) + ) + + if arrtype.ndim == 0: + strides = () + elif arrtype.layout == 'C': + strides = [itemsize] + for dimension_size in reversed(shapes[1:]): + strides.append(builder.mul(strides[-1], dimension_size)) + strides = tuple(reversed(strides)) + elif arrtype.layout == 'F': + strides = [itemsize] + for dimension_size in shapes[:-1]: + strides.append(builder.mul(strides[-1], dimension_size)) + strides = tuple(strides) + else: + raise NotImplementedError( + "Don't know how to allocate array with layout '{0}'.".format( + arrtype.layout)) + + # Check overflow, numpy also does this after checking order + allocsize_mult = builder.smul_with_overflow(arrlen, itemsize) + allocsize = builder.extract_value(allocsize_mult, 0) + overflow = builder.or_(overflow, builder.extract_value(allocsize_mult, 1)) + + with builder.if_then(overflow, likely=False): + # Raise same error as numpy, see: + # https://github.com/numpy/numpy/blob/2a488fe76a0f732dc418d03b452caace161673da/numpy/core/src/multiarray/ctors.c#L1095-L1101 # noqa: E501 + context.call_conv.return_user_exc( + builder, ValueError, + ("array is too big; `arr.size * arr.dtype.itemsize` is larger than" + " the maximum possible size.",) + ) + + dtype = arrtype.dtype + align_val = context.get_preferred_array_alignment(dtype) + align = context.get_constant(types.uint32, align_val) + args = (context.get_dummy_value(), allocsize, align) + + mip = types.MemInfoPointer(types.voidptr) + arytypeclass = types.TypeRef(type(arrtype)) + argtypes = signature(mip, arytypeclass, types.intp, types.uint32) + + meminfo = context.compile_internal(builder, _call_allocator, argtypes, args) + data = context.nrt.meminfo_data(builder, meminfo) + + intp_t = context.get_value_type(types.intp) + shape_array = cgutils.pack_array(builder, shapes, ty=intp_t) + strides_array = cgutils.pack_array(builder, strides, ty=intp_t) + + populate_array(ary, + data=builder.bitcast(data, datatype.as_pointer()), + shape=shape_array, + strides=strides_array, + itemsize=itemsize, + meminfo=meminfo) + + return ary + + +@overload_classmethod(types.Array, "_allocate", target="CPU") +def _ol_array_allocate(cls, allocsize, align): + """Implements a Numba-only default target (cpu) classmethod on the array + type. + """ + def impl(cls, allocsize, align): + return intrin_alloc(allocsize, align) + return impl + + +def _call_allocator(arrtype, size, align): + """Trampoline to call the intrinsic used for allocation + """ + return arrtype._allocate(size, align) + + +@intrinsic +def intrin_alloc(typingctx, allocsize, align): + """Intrinsic to call into the allocator for Array + """ + def codegen(context, builder, signature, args): + [allocsize, align] = args + meminfo = context.nrt.meminfo_alloc_aligned(builder, allocsize, align) + return meminfo + + mip = types.MemInfoPointer(types.voidptr) # return untyped pointer + sig = signature(mip, allocsize, align) + return sig, codegen + + +def _parse_shape(context, builder, ty, val): + """ + Parse the shape argument to an array constructor. + """ + def safecast_intp(context, builder, src_t, src): + """Cast src to intp only if value can be maintained""" + intp_t = context.get_value_type(types.intp) + intp_width = intp_t.width + intp_ir = ir.IntType(intp_width) + maxval = Constant(intp_ir, ((1 << intp_width - 1) - 1)) + if src_t.width < intp_width: + res = builder.sext(src, intp_ir) + elif src_t.width >= intp_width: + is_larger = builder.icmp_signed(">", src, maxval) + with builder.if_then(is_larger, likely=False): + context.call_conv.return_user_exc( + builder, ValueError, + ("Cannot safely convert value to intp",) + ) + if src_t.width > intp_width: + res = builder.trunc(src, intp_ir) + else: + res = src + return res + + if isinstance(ty, types.Integer): + ndim = 1 + passed_shapes = [context.cast(builder, val, ty, types.intp)] + else: + assert isinstance(ty, types.BaseTuple) + ndim = ty.count + passed_shapes = cgutils.unpack_tuple(builder, val, count=ndim) + + shapes = [] + for s in passed_shapes: + shapes.append(safecast_intp(context, builder, s.type, s)) + + zero = context.get_constant_generic(builder, types.intp, 0) + for dim in range(ndim): + is_neg = builder.icmp_signed('<', shapes[dim], zero) + with cgutils.if_unlikely(builder, is_neg): + context.call_conv.return_user_exc( + builder, ValueError, ("negative dimensions not allowed",) + ) + + return shapes + + +def _parse_empty_args(context, builder, sig, args): + """ + Parse the arguments of a np.empty(), np.zeros() or np.ones() call. + """ + arrshapetype = sig.args[0] + arrshape = args[0] + arrtype = sig.return_type + return arrtype, _parse_shape(context, builder, arrshapetype, arrshape) + + +def _parse_empty_like_args(context, builder, sig, args): + """ + Parse the arguments of a np.empty_like(), np.zeros_like() or + np.ones_like() call. + """ + arytype = sig.args[0] + if isinstance(arytype, types.Array): + ary = make_array(arytype)(context, builder, value=args[0]) + shapes = cgutils.unpack_tuple(builder, ary.shape, count=arytype.ndim) + return sig.return_type, shapes + else: + return sig.return_type, () + + +def _check_const_str_dtype(fname, dtype): + if isinstance(dtype, types.UnicodeType): + msg = f"If np.{fname} dtype is a string it must be a string constant." + raise errors.TypingError(msg) + + +@intrinsic +def numpy_empty_nd(tyctx, ty_shape, ty_dtype, ty_retty_ref): + ty_retty = ty_retty_ref.instance_type + sig = ty_retty(ty_shape, ty_dtype, ty_retty_ref) + + def codegen(cgctx, builder, sig, llargs): + arrtype, shapes = _parse_empty_args(cgctx, builder, sig, llargs) + ary = _empty_nd_impl(cgctx, builder, arrtype, shapes) + return ary._getvalue() + return sig, codegen + + +@overload(np.empty) +def ol_np_empty(shape, dtype=float): + _check_const_str_dtype("empty", dtype) + if (dtype is float or + (isinstance(dtype, types.Function) and dtype.typing_key is float) or + is_nonelike(dtype)): #default + nb_dtype = types.double + else: + nb_dtype = ty_parse_dtype(dtype) + + ndim = ty_parse_shape(shape) + if nb_dtype is not None and ndim is not None: + retty = types.Array(dtype=nb_dtype, ndim=ndim, layout='C') + + def impl(shape, dtype=float): + return numpy_empty_nd(shape, dtype, retty) + return impl + else: + msg = f"Cannot parse input types to function np.empty({shape}, {dtype})" + raise errors.TypingError(msg) + + +@intrinsic +def numpy_empty_like_nd(tyctx, ty_prototype, ty_dtype, ty_retty_ref): + ty_retty = ty_retty_ref.instance_type + sig = ty_retty(ty_prototype, ty_dtype, ty_retty_ref) + + def codegen(cgctx, builder, sig, llargs): + arrtype, shapes = _parse_empty_like_args(cgctx, builder, sig, llargs) + ary = _empty_nd_impl(cgctx, builder, arrtype, shapes) + return ary._getvalue() + return sig, codegen + + +@overload(np.empty_like) +def ol_np_empty_like(arr, dtype=None): + _check_const_str_dtype("empty_like", dtype) + if not is_nonelike(dtype): + nb_dtype = ty_parse_dtype(dtype) + elif isinstance(arr, types.Array): + nb_dtype = arr.dtype + else: + nb_dtype = arr + if nb_dtype is not None: + if isinstance(arr, types.Array): + layout = arr.layout if arr.layout != 'A' else 'C' + retty = arr.copy(dtype=nb_dtype, layout=layout, readonly=False) + else: + retty = types.Array(nb_dtype, 0, 'C') + else: + msg = ("Cannot parse input types to function " + f"np.empty_like({arr}, {dtype})") + raise errors.TypingError(msg) + + def impl(arr, dtype=None): + return numpy_empty_like_nd(arr, dtype, retty) + return impl + + +@intrinsic +def _zero_fill_array_method(tyctx, self): + sig = types.none(self) + + def codegen(cgctx, builder, sig, llargs): + ary = make_array(sig.args[0])(cgctx, builder, llargs[0]) + cgutils.memset(builder, ary.data, builder.mul(ary.itemsize, ary.nitems), + 0) + return sig, codegen + + +@overload_method(types.Array, '_zero_fill') +def ol_array_zero_fill(self): + """Adds a `._zero_fill` method to zero fill an array using memset.""" + def impl(self): + _zero_fill_array_method(self) + return impl + + +@overload(np.zeros) +def ol_np_zeros(shape, dtype=float): + _check_const_str_dtype("zeros", dtype) + + def impl(shape, dtype=float): + arr = np.empty(shape, dtype=dtype) + arr._zero_fill() + return arr + return impl + + +@overload(np.zeros_like) +def ol_np_zeros_like(a, dtype=None): + _check_const_str_dtype("zeros_like", dtype) + + # NumPy uses 'a' as the arg name for the array-like + def impl(a, dtype=None): + arr = np.empty_like(a, dtype=dtype) + arr._zero_fill() + return arr + return impl + + +@overload(np.ones_like) +def ol_np_ones_like(a, dtype=None): + _check_const_str_dtype("ones_like", dtype) + + # NumPy uses 'a' as the arg name for the array-like + def impl(a, dtype=None): + arr = np.empty_like(a, dtype=dtype) + arr_flat = arr.flat + for idx in range(len(arr_flat)): + arr_flat[idx] = 1 + return arr + return impl + + +@overload(np.full) +def impl_np_full(shape, fill_value, dtype=None): + _check_const_str_dtype("full", dtype) + if not is_nonelike(dtype): + nb_dtype = ty_parse_dtype(dtype) + else: + nb_dtype = fill_value + + def full(shape, fill_value, dtype=None): + arr = np.empty(shape, nb_dtype) + arr_flat = arr.flat + for idx in range(len(arr_flat)): + arr_flat[idx] = fill_value + return arr + return full + + +@overload(np.full_like) +def impl_np_full_like(a, fill_value, dtype=None): + _check_const_str_dtype("full_like", dtype) + + def full_like(a, fill_value, dtype=None): + arr = np.empty_like(a, dtype) + arr_flat = arr.flat + for idx in range(len(arr_flat)): + arr_flat[idx] = fill_value + return arr + + return full_like + + +@overload(np.ones) +def ol_np_ones(shape, dtype=None): + # for some reason the NumPy default for dtype is None in the source but + # ends up as np.float64 by definition. + _check_const_str_dtype("ones", dtype) + + def impl(shape, dtype=None): + arr = np.empty(shape, dtype=dtype) + arr_flat = arr.flat + for idx in range(len(arr_flat)): + arr_flat[idx] = 1 + return arr + return impl + + +@overload(np.identity) +def impl_np_identity(n, dtype=None): + _check_const_str_dtype("identity", dtype) + if not is_nonelike(dtype): + nb_dtype = ty_parse_dtype(dtype) + else: + nb_dtype = types.double + + def identity(n, dtype=None): + arr = np.zeros((n, n), nb_dtype) + for i in range(n): + arr[i, i] = 1 + return arr + return identity + + +def _eye_none_handler(N, M): + pass + + +@extending.overload(_eye_none_handler) +def _eye_none_handler_impl(N, M): + if isinstance(M, types.NoneType): + def impl(N, M): + return N + else: + def impl(N, M): + return M + return impl + + +@extending.overload(np.eye) +def numpy_eye(N, M=None, k=0, dtype=float): + + if dtype is None or isinstance(dtype, types.NoneType): + dt = np.dtype(float) + elif isinstance(dtype, (types.DTypeSpec, types.Number)): + # dtype or instance of dtype + dt = as_dtype(getattr(dtype, 'dtype', dtype)) + else: + dt = np.dtype(dtype) + + def impl(N, M=None, k=0, dtype=float): + _M = _eye_none_handler(N, M) + arr = np.zeros((N, _M), dt) + if k >= 0: + d = min(N, _M - k) + for i in range(d): + arr[i, i + k] = 1 + else: + d = min(N + k, _M) + for i in range(d): + arr[i - k, i] = 1 + return arr + return impl + + +@overload(np.diag) +def impl_np_diag(v, k=0): + if not type_can_asarray(v): + raise errors.TypingError('The argument "v" must be array-like') + + if isinstance(v, types.Array): + if v.ndim not in (1, 2): + raise errors.NumbaTypeError("Input must be 1- or 2-d.") + + def diag_impl(v, k=0): + if v.ndim == 1: + s = v.shape + n = s[0] + abs(k) + ret = np.zeros((n, n), v.dtype) + if k >= 0: + for i in range(n - k): + ret[i, k + i] = v[i] + else: + for i in range(n + k): + ret[i - k, i] = v[i] + return ret + else: # 2-d + rows, cols = v.shape + if k < 0: + rows = rows + k + if k > 0: + cols = cols - k + n = max(min(rows, cols), 0) + ret = np.empty(n, v.dtype) + if k >= 0: + for i in range(n): + ret[i] = v[i, k + i] + else: + for i in range(n): + ret[i] = v[i - k, i] + return ret + return diag_impl + + +@overload(np.indices) +def numpy_indices(dimensions): + if not isinstance(dimensions, types.UniTuple): + msg = 'The argument "dimensions" must be a tuple of integers' + raise errors.TypingError(msg) + + if not isinstance(dimensions.dtype, types.Integer): + msg = 'The argument "dimensions" must be a tuple of integers' + raise errors.TypingError(msg) + + N = len(dimensions) + shape = (1,) * N + + def impl(dimensions): + res = np.empty((N,) + dimensions, dtype=np.int64) + i = 0 + for dim in dimensions: + idx = np.arange(dim, dtype=np.int64).reshape( + tuple_setitem(shape, i, dim) + ) + res[i] = idx + i += 1 + + return res + + return impl + + +@overload(np.diagflat) +def numpy_diagflat(v, k=0): + if not type_can_asarray(v): + msg = 'The argument "v" must be array-like' + raise errors.TypingError(msg) + + if not isinstance(k, (int, types.Integer)): + msg = 'The argument "k" must be an integer' + raise errors.TypingError(msg) + + def impl(v, k=0): + v = np.asarray(v) + v = v.ravel() + s = len(v) + abs_k = abs(k) + n = s + abs_k + res = np.zeros((n, n), v.dtype) + i = np.maximum(0, -k) + j = np.maximum(0, k) + for t in range(s): + res[i + t, j + t] = v[t] + + return res + + return impl + + +def generate_getitem_setitem_with_axis(ndim, kind): + assert kind in ('getitem', 'setitem') + + if kind == 'getitem': + fn = ''' + def _getitem(a, idx, axis): + if axis == 0: + return a[idx, ...] + ''' + for i in range(1, ndim): + lst = (':',) * i + fn += f''' + elif axis == {i}: + return a[{", ".join(lst)}, idx, ...] + ''' + else: + fn = ''' + def _setitem(a, idx, axis, vals): + if axis == 0: + a[idx, ...] = vals + ''' + + for i in range(1, ndim): + lst = (':',) * i + fn += f''' + elif axis == {i}: + a[{", ".join(lst)}, idx, ...] = vals + ''' + + fn = textwrap.dedent(fn) + exec(fn, globals()) + fn = globals()[f'_{kind}'] + return register_jitable(fn) + + +@overload(np.take) +@overload_method(types.Array, 'take') +def numpy_take(a, indices, axis=None): + + if cgutils.is_nonelike(axis): + if isinstance(a, types.Array) and isinstance(indices, types.Integer): + def take_impl(a, indices, axis=None): + if indices > (a.size - 1) or indices < -a.size: + raise IndexError("Index out of bounds") + return a.ravel()[indices] + return take_impl + + if isinstance(a, types.Array) and isinstance(indices, types.Array): + F_order = indices.layout == 'F' + + def take_impl(a, indices, axis=None): + ret = np.empty(indices.size, dtype=a.dtype) + if F_order: + walker = indices.copy() # get C order + else: + walker = indices + it = np.nditer(walker) + i = 0 + flat = a.ravel() + for x in it: + if x > (a.size - 1) or x < -a.size: + raise IndexError("Index out of bounds") + ret[i] = flat[x] + i = i + 1 + return ret.reshape(indices.shape) + return take_impl + + if isinstance(a, types.Array) and \ + isinstance(indices, (types.List, types.BaseTuple)): + def take_impl(a, indices, axis=None): + convert = np.array(indices) + return np.take(a, convert) + return take_impl + else: + if isinstance(a, types.Array) and isinstance(indices, types.Integer): + t = (0,) * (a.ndim - 1) + + # np.squeeze is too hard to implement in Numba as the tuple "t" + # needs to be allocated beforehand we don't know it's size until + # code gets executed. + @register_jitable + def _squeeze(r, axis): + tup = tuple(t) + j = 0 + assert axis < len(r.shape) and r.shape[axis] == 1, r.shape + for idx in range(len(r.shape)): + s = r.shape[idx] + if idx != axis: + tup = tuple_setitem(tup, j, s) + j += 1 + return r.reshape(tup) + + def take_impl(a, indices, axis=None): + r = np.take(a, (indices,), axis=axis) + if a.ndim == 1: + # caveats + # >>> isinstance(np.take(1d_arr, 0), int) + # True + # >>> isinstance(np.take(1d_arr, (0,)), int) + # False + # The latter returns an array + return r[0] + if axis < 0: + axis += a.ndim + return _squeeze(r, axis) + return take_impl + + if isinstance(a, types.Array) and \ + isinstance(indices, (types.Array, types.List, types.BaseTuple)): + + ndim = a.ndim + + _getitem = generate_getitem_setitem_with_axis(ndim, 'getitem') + _setitem = generate_getitem_setitem_with_axis(ndim, 'setitem') + + def take_impl(a, indices, axis=None): + ax = axis + if axis < 0: + axis += a.ndim + + if axis < 0 or axis >= a.ndim: + msg = (f"axis {ax} is out of bounds for array " + f"of dimension {a.ndim}") + raise ValueError(msg) + + shape = tuple_setitem(a.shape, axis, len(indices)) + out = np.empty(shape, dtype=a.dtype) + for i in range(len(indices)): + y = _getitem(a, indices[i], axis) + _setitem(out, i, axis, y) + return out + return take_impl + + +def _arange_dtype(*args): + bounds = [a for a in args if not isinstance(a, types.NoneType)] + + if any(isinstance(a, types.Complex) for a in bounds): + dtype = types.complex128 + elif any(isinstance(a, types.Float) for a in bounds): + dtype = types.float64 + else: + # `np.arange(10).dtype` is always `np.dtype(int)`, aka `np.int_`, which + # in all released versions of numpy corresponds to the C `long` type. + # Windows 64 is broken by default here because Numba (as of 0.47) does + # not differentiate between Python and NumPy integers, so a `typeof(1)` + # on w64 is `int64`, i.e. `intp`. This means an arange() will + # be typed as arange(int64) and the following will yield int64 opposed + # to int32. Example: without a load of analysis to work out of the args + # were wrapped in NumPy int*() calls it's not possible to detect the + # difference between `np.arange(10)` and `np.arange(np.int64(10)`. + NPY_TY = getattr(types, "int%s" % (8 * np.dtype(int).itemsize)) + + # unliteral these types such that `max` works. + unliteral_bounds = [types.unliteral(x) for x in bounds] + dtype = max(unliteral_bounds + [NPY_TY,]) + + return dtype + + +@overload(np.arange) +def np_arange(start, / ,stop=None, step=None, dtype=None): + if isinstance(stop, types.Optional): + stop = stop.type + if isinstance(step, types.Optional): + step = step.type + if isinstance(dtype, types.Optional): + dtype = dtype.type + + if stop is None: + stop = types.none + if step is None: + step = types.none + if dtype is None: + dtype = types.none + + if (not isinstance(start, types.Number) or + not isinstance(stop, (types.NoneType, types.Number)) or + not isinstance(step, (types.NoneType, types.Number)) or + not isinstance(dtype, (types.NoneType, types.DTypeSpec))): + + return + + if isinstance(dtype, types.NoneType): + true_dtype = _arange_dtype(start, stop, step) + else: + true_dtype = dtype.dtype + + use_complex = any([isinstance(x, types.Complex) + for x in (start, stop, step)]) + + start_value = getattr(start, "literal_value", None) + stop_value = getattr(stop, "literal_value", None) + step_value = getattr(step, "literal_value", None) + + def impl(start, /, stop=None, step=None, dtype=None): + # Allow for improved performance if given literal arguments. + lit_start = start_value if start_value is not None else start + lit_stop = stop_value if stop_value is not None else stop + lit_step = step_value if step_value is not None else step + + _step = lit_step if lit_step is not None else 1 + if lit_stop is None: + _start, _stop = 0, lit_start + else: + _start, _stop = lit_start, lit_stop + + if _step == 0: + raise ValueError("Maximum allowed size exceeded") + + nitems_c = (_stop - _start) / _step + nitems_r = int(math.ceil(nitems_c.real)) + + # Binary operator needed for compiler branch pruning. + if use_complex is True: + nitems_i = int(math.ceil(nitems_c.imag)) + nitems = max(min(nitems_i, nitems_r), 0) + else: + nitems = max(nitems_r, 0) + arr = np.empty(nitems, true_dtype) + val = _start + for i in range(nitems): + arr[i] = val + (i * _step) + return arr + + return impl + + +@overload(np.linspace) +def numpy_linspace(start, stop, num=50): + if not all(isinstance(arg, types.Number) for arg in [start, stop]): + return + + if not isinstance(num, (int, types.Integer)): + msg = 'The argument "num" must be an integer' + raise errors.TypingError(msg) + + if any(isinstance(arg, types.Complex) for arg in [start, stop]): + dtype = types.complex128 + else: + dtype = types.float64 + + # Implementation based on https://github.com/numpy/numpy/blob/v1.20.0/numpy/core/function_base.py#L24 # noqa: E501 + def linspace(start, stop, num=50): + arr = np.empty(num, dtype) + # The multiply by 1.0 mirrors + # https://github.com/numpy/numpy/blob/v1.20.0/numpy/core/function_base.py#L125-L128 # noqa: E501 + # the side effect of this is important... start and stop become the same + # type as `dtype` i.e. 64/128 bits wide (float/complex). This is + # important later when used in the `np.divide`. + start = start * 1.0 + stop = stop * 1.0 + if num == 0: + return arr + div = num - 1 + if div > 0: + delta = stop - start + step = np.divide(delta, div) + for i in range(0, num): + arr[i] = start + (i * step) + else: + arr[0] = start + if num > 1: + arr[-1] = stop + return arr + return linspace + + +def _array_copy(context, builder, sig, args): + """ + Array copy. + """ + arytype = sig.args[0] + ary = make_array(arytype)(context, builder, value=args[0]) + shapes = cgutils.unpack_tuple(builder, ary.shape) + + rettype = sig.return_type + ret = _empty_nd_impl(context, builder, rettype, shapes) + + src_data = ary.data + dest_data = ret.data + + assert rettype.layout in "CF" + if arytype.layout == rettype.layout: + # Fast path: memcpy + cgutils.raw_memcpy(builder, dest_data, src_data, ary.nitems, + ary.itemsize, align=1) + + else: + src_strides = cgutils.unpack_tuple(builder, ary.strides) + dest_strides = cgutils.unpack_tuple(builder, ret.strides) + intp_t = context.get_value_type(types.intp) + + with cgutils.loop_nest(builder, shapes, intp_t) as indices: + src_ptr = cgutils.get_item_pointer2(context, builder, src_data, + shapes, src_strides, + arytype.layout, indices) + dest_ptr = cgutils.get_item_pointer2(context, builder, dest_data, + shapes, dest_strides, + rettype.layout, indices) + builder.store(builder.load(src_ptr), dest_ptr) + + return impl_ret_new_ref(context, builder, sig.return_type, ret._getvalue()) + + +@intrinsic +def _array_copy_intrinsic(typingctx, a): + assert isinstance(a, types.Array) + layout = 'F' if a.layout == 'F' else 'C' + ret = a.copy(layout=layout, readonly=False) + sig = ret(a) + return sig, _array_copy + + +@lower_builtin("array.copy", types.Array) +def array_copy(context, builder, sig, args): + return _array_copy(context, builder, sig, args) + + +@overload(np.copy) +def impl_numpy_copy(a): + if not type_can_asarray(a): + raise errors.TypingError('The argument "a" must ' + 'be array-like') + + if isinstance(a, types.Array): + def numpy_copy(a): + return _array_copy_intrinsic(a) + else: + def numpy_copy(a): + # asarray automatically copies non-Array types + return np.asarray(a) + return numpy_copy + + +def _as_layout_array(context, builder, sig, args, output_layout): + """ + Common logic for layout conversion function; + e.g. ascontiguousarray and asfortranarray + """ + retty = sig.return_type + aryty = sig.args[0] + assert retty.layout == output_layout, 'return-type has incorrect layout' + + if aryty.ndim == 0: + # 0-dim input => asfortranarray() returns a 1-dim array + assert retty.ndim == 1 + ary = make_array(aryty)(context, builder, value=args[0]) + ret = make_array(retty)(context, builder) + + shape = context.get_constant_generic( + builder, types.UniTuple(types.intp, 1), (1,), + ) + strides = context.make_tuple(builder, + types.UniTuple(types.intp, 1), + (ary.itemsize,)) + populate_array(ret, ary.data, shape, strides, ary.itemsize, + ary.meminfo, ary.parent) + return impl_ret_borrowed(context, builder, retty, ret._getvalue()) + + elif (retty.layout == aryty.layout + or (aryty.ndim == 1 and aryty.layout in 'CF')): + # 1-dim contiguous input => return the same array + return impl_ret_borrowed(context, builder, retty, args[0]) + + else: + if aryty.layout == 'A': + # There's still chance the array is in contiguous layout, + # just that we don't know at compile time. + # We can do a runtime check. + + # Prepare and call is_contiguous or is_fortran + assert output_layout in 'CF' + check_func = is_contiguous if output_layout == 'C' else is_fortran + is_contig = _call_contiguous_check(check_func, + context, + builder, + aryty, + args[0]) + with builder.if_else(is_contig) as (then, orelse): + # If the array is already contiguous, just return it + with then: + out_then = impl_ret_borrowed(context, builder, retty, + args[0]) + then_blk = builder.block + # Otherwise, copy to a new contiguous region + with orelse: + out_orelse = _array_copy(context, builder, sig, args) + orelse_blk = builder.block + # Phi node for the return value + ret_phi = builder.phi(out_then.type) + ret_phi.add_incoming(out_then, then_blk) + ret_phi.add_incoming(out_orelse, orelse_blk) + return ret_phi + + else: + # Return a copy with the right layout + return _array_copy(context, builder, sig, args) + + +@intrinsic +def _as_layout_array_intrinsic(typingctx, a, output_layout): + if not isinstance(output_layout, types.StringLiteral): + raise errors.RequireLiteralValue(output_layout) + + # copies are writable + ret = a.copy( + layout=output_layout.literal_value, + ndim=max(a.ndim, 1), + readonly=False) + sig = ret(a, output_layout) + + return sig, lambda c, b, s, a: _as_layout_array( + c, b, s, a, output_layout=output_layout.literal_value) + + +@overload(np.ascontiguousarray) +def array_ascontiguousarray(a): + if not type_can_asarray(a): + raise errors.TypingError('The argument "a" must be array-like') + + if isinstance(a, (types.Number, types.Boolean,)): + def impl(a): + return np.ascontiguousarray(np.array(a)) + elif isinstance(a, types.Array): + def impl(a): + return _as_layout_array_intrinsic(a, 'C') + return impl + + +@overload(np.asfortranarray) +def array_asfortranarray(a): + if not type_can_asarray(a): + raise errors.TypingError('The argument "a" must be array-like') + + if isinstance(a, (types.Number, types.Boolean,)): + def impl(a): + return np.asfortranarray(np.array(a)) + return impl + elif isinstance(a, types.Array): + def impl(a): + return _as_layout_array_intrinsic(a, 'F') + return impl + + +@lower_builtin("array.astype", types.Array, types.DTypeSpec) +@lower_builtin("array.astype", types.Array, types.StringLiteral) +def array_astype(context, builder, sig, args): + arytype = sig.args[0] + ary = make_array(arytype)(context, builder, value=args[0]) + shapes = cgutils.unpack_tuple(builder, ary.shape) + + rettype = sig.return_type + ret = _empty_nd_impl(context, builder, rettype, shapes) + + src_data = ary.data + dest_data = ret.data + + src_strides = cgutils.unpack_tuple(builder, ary.strides) + dest_strides = cgutils.unpack_tuple(builder, ret.strides) + intp_t = context.get_value_type(types.intp) + + with cgutils.loop_nest(builder, shapes, intp_t) as indices: + src_ptr = cgutils.get_item_pointer2(context, builder, src_data, + shapes, src_strides, + arytype.layout, indices) + dest_ptr = cgutils.get_item_pointer2(context, builder, dest_data, + shapes, dest_strides, + rettype.layout, indices) + item = load_item(context, builder, arytype, src_ptr) + item = context.cast(builder, item, arytype.dtype, rettype.dtype) + store_item(context, builder, rettype, item, dest_ptr) + + return impl_ret_new_ref(context, builder, sig.return_type, ret._getvalue()) + + +@intrinsic +def _array_tobytes_intrinsic(typingctx, b): + assert isinstance(b, types.Array) + sig = bytes_type(b) + + def codegen(context, builder, sig, args): + [ty] = sig.args + arrty = make_array(ty) + arr = arrty(context, builder, args[0]) + + itemsize = arr.itemsize + nbytes = builder.mul(itemsize, arr.nitems) + + bstr = _make_constant_bytes(context, builder, nbytes) + + if (ty.is_c_contig and ty.layout == "C"): + cgutils.raw_memcpy(builder, bstr.data, arr.data, arr.nitems, + itemsize) + else: + shape = cgutils.unpack_tuple(builder, arr.shape) + strides = cgutils.unpack_tuple(builder, arr.strides) + layout = ty.layout + intp_t = context.get_value_type(types.intp) + + byteidx = cgutils.alloca_once( + builder, intp_t, name="byteptr", zfill=True + ) + with cgutils.loop_nest(builder, shape, intp_t) as indices: + ptr = cgutils.get_item_pointer2( + context, builder, arr.data, shape, strides, layout, indices + ) + srcptr = builder.bitcast(ptr, bstr.data.type) + + idx = builder.load(byteidx) + destptr = builder.gep(bstr.data, [idx]) + + cgutils.memcpy(builder, destptr, srcptr, itemsize) + builder.store(builder.add(idx, itemsize), byteidx) + + return bstr._getvalue() + return sig, codegen + + +@overload_method(types.Array, "tobytes") +def impl_array_tobytes(arr): + if isinstance(arr, types.Array): + def impl(arr): + return _array_tobytes_intrinsic(arr) + return impl + + +@intrinsic +def np_frombuffer(typingctx, buffer, dtype, count, offset, retty): + ty = retty.instance_type + sig = ty(buffer, dtype, count, offset, retty) + + def codegen(context, builder, sig, args): + bufty = sig.args[0] + arg_count = args[2] + arg_offset = args[3] + aryty = sig.return_type + + buf = make_array(bufty)(context, builder, value=args[0]) + out_ary_ty = make_array(aryty) + out_ary = out_ary_ty(context, builder) + out_datamodel = out_ary._datamodel + + itemsize = get_itemsize(context, aryty) + ll_itemsize = Constant(buf.itemsize.type, itemsize) + nbytes = builder.mul(buf.nitems, buf.itemsize) + ll_offset_size = builder.mul(arg_offset, ll_itemsize) + nbytes = builder.sub(nbytes, ll_offset_size) + + nbytes_is_negative = builder.icmp_signed( + '<', + nbytes, + ir.Constant(arg_count.type, 0), + ) + + msg = "offset must be non-negative and no greater than buffer length" + with builder.if_then(nbytes_is_negative, likely=False): + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + ll_count_is_negative = builder.icmp_signed( + '<', + arg_count, + ir.Constant(arg_count.type, 0), + ) + + # Check that the buffer size is compatible + rem = builder.srem(nbytes, ll_itemsize) + is_incompatible = cgutils.is_not_null(builder, rem) + with builder.if_then(is_incompatible, likely=False): + msg = "buffer size must be a multiple of element size" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + # Compute number of elements based on count + with builder.if_else(ll_count_is_negative) as (then_block, else_block): + with then_block: + bb_if = builder.basic_block + num_whole = builder.sdiv(nbytes, ll_itemsize) + with else_block: + bb_else = builder.basic_block + + ll_itemcount = builder.phi(arg_count.type) + ll_itemcount.add_incoming(num_whole, bb_if) + ll_itemcount.add_incoming(arg_count, bb_else) + + # Ensure we don’t exceed the buffer size + ll_required_size = builder.mul(ll_itemcount, ll_itemsize) + is_too_large = builder.icmp_unsigned('>', ll_required_size, nbytes) + + with builder.if_then(is_too_large, likely=False): + msg = "buffer is smaller than requested size" + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + # Set shape and strides + shape = cgutils.pack_array(builder, [ll_itemcount]) + strides = cgutils.pack_array(builder, [ll_itemsize]) + + data = builder.gep(buf.data, [arg_offset]) + data = builder.bitcast( + data, context.get_value_type(out_datamodel.get_type('data')) + ) + + populate_array(out_ary, + data=data, + shape=shape, + strides=strides, + itemsize=ll_itemsize, + meminfo=buf.meminfo, + parent=buf.parent) + + res = out_ary._getvalue() + return impl_ret_borrowed(context, builder, sig.return_type, res) + + return sig, codegen + + +@overload(np.frombuffer) +def impl_np_frombuffer(buffer, dtype=float, count=-1, offset=0): + _check_const_str_dtype("frombuffer", dtype) + + if not isinstance(buffer, types.Buffer) or buffer.layout != 'C': + msg = f'Argument "buffer" must be buffer-like. Got {buffer}' + raise errors.TypingError(msg) + + if (dtype is float or + (isinstance(dtype, types.Function) and dtype.typing_key is float) or + is_nonelike(dtype)): # default + nb_dtype = types.double + else: + nb_dtype = ty_parse_dtype(dtype) + + if nb_dtype is not None: + retty = types.Array(dtype=nb_dtype, ndim=1, layout='C', + readonly=not buffer.mutable) + else: + msg = ("Cannot parse input types to function " + f"np.frombuffer({buffer}, {dtype})") + raise errors.TypingError(msg) + + def impl(buffer, dtype=float, count=-1, offset=0): + return np_frombuffer(buffer, dtype, count, offset, retty) + + return impl + + +@overload(carray) +def impl_carray(ptr, shape, dtype=None): + if is_nonelike(dtype): + intrinsic_cfarray = get_cfarray_intrinsic('C', None) + + def impl(ptr, shape, dtype=None): + return intrinsic_cfarray(ptr, shape) + return impl + elif isinstance(dtype, types.DTypeSpec): + intrinsic_cfarray = get_cfarray_intrinsic('C', dtype) + + def impl(ptr, shape, dtype=None): + return intrinsic_cfarray(ptr, shape) + return impl + + +@overload(farray) +def impl_farray(ptr, shape, dtype=None): + if is_nonelike(dtype): + intrinsic_cfarray = get_cfarray_intrinsic('F', None) + + def impl(ptr, shape, dtype=None): + return intrinsic_cfarray(ptr, shape) + return impl + elif isinstance(dtype, types.DTypeSpec): + intrinsic_cfarray = get_cfarray_intrinsic('F', dtype) + + def impl(ptr, shape, dtype=None): + return intrinsic_cfarray(ptr, shape) + return impl + + +def get_cfarray_intrinsic(layout, dtype_): + @intrinsic + def intrinsic_cfarray(typingctx, ptr, shape): + if ptr is types.voidptr: + ptr_dtype = None + elif isinstance(ptr, types.CPointer): + ptr_dtype = ptr.dtype + else: + msg = f"pointer argument expected, got '{ptr}'" + raise errors.NumbaTypeError(msg) + + if dtype_ is None: + if ptr_dtype is None: + msg = "explicit dtype required for void* argument" + raise errors.NumbaTypeError(msg) + dtype = ptr_dtype + elif isinstance(dtype_, types.DTypeSpec): + dtype = dtype_.dtype + if ptr_dtype is not None and dtype != ptr_dtype: + msg = f"mismatching dtype '{dtype}' for pointer type '{ptr}'" + raise errors.NumbaTypeError(msg) + else: + msg = f"invalid dtype spec '{dtype_}'" + raise errors.NumbaTypeError(msg) + + ndim = ty_parse_shape(shape) + if ndim is None: + msg = f"invalid shape '{shape}'" + raise errors.NumbaTypeError(msg) + + retty = types.Array(dtype, ndim, layout) + sig = signature(retty, ptr, shape) + return sig, np_cfarray + return intrinsic_cfarray + + +def np_cfarray(context, builder, sig, args): + """ + numba.numpy_support.carray(...) and + numba.numpy_support.farray(...). + """ + ptrty, shapety = sig.args[:2] + ptr, shape = args[:2] + + aryty = sig.return_type + assert aryty.layout in 'CF' + + out_ary = make_array(aryty)(context, builder) + + itemsize = get_itemsize(context, aryty) + ll_itemsize = cgutils.intp_t(itemsize) + + if isinstance(shapety, types.BaseTuple): + shapes = cgutils.unpack_tuple(builder, shape) + else: + shapety = (shapety,) + shapes = (shape,) + shapes = [context.cast(builder, value, fromty, types.intp) + for fromty, value in zip(shapety, shapes)] + + off = ll_itemsize + strides = [] + if aryty.layout == 'F': + for s in shapes: + strides.append(off) + off = builder.mul(off, s) + else: + for s in reversed(shapes): + strides.append(off) + off = builder.mul(off, s) + strides.reverse() + + data = builder.bitcast(ptr, + context.get_data_type(aryty.dtype).as_pointer()) + + populate_array(out_ary, + data=data, + shape=shapes, + strides=strides, + itemsize=ll_itemsize, + # Array is not memory-managed + meminfo=None, + ) + + res = out_ary._getvalue() + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +def _get_seq_size(context, builder, seqty, seq): + if isinstance(seqty, types.BaseTuple): + return context.get_constant(types.intp, len(seqty)) + elif isinstance(seqty, types.Sequence): + len_impl = context.get_function(len, signature(types.intp, seqty,)) + return len_impl(builder, (seq,)) + else: + assert 0 + + +def _get_borrowing_getitem(context, seqty): + """ + Return a getitem() implementation that doesn't incref its result. + """ + retty = seqty.dtype + getitem_impl = context.get_function(operator.getitem, + signature(retty, seqty, types.intp)) + + def wrap(builder, args): + ret = getitem_impl(builder, args) + if context.enable_nrt: + context.nrt.decref(builder, retty, ret) + return ret + + return wrap + + +def compute_sequence_shape(context, builder, ndim, seqty, seq): + """ + Compute the likely shape of a nested sequence (possibly 0d). + """ + intp_t = context.get_value_type(types.intp) + zero = Constant(intp_t, 0) + + def get_first_item(seqty, seq): + if isinstance(seqty, types.BaseTuple): + if len(seqty) == 0: + return None, None + else: + return seqty[0], builder.extract_value(seq, 0) + else: + getitem_impl = _get_borrowing_getitem(context, seqty) + return seqty.dtype, getitem_impl(builder, (seq, zero)) + + # Compute shape by traversing the first element of each nested + # sequence + shapes = [] + innerty, inner = seqty, seq + + for i in range(ndim): + if i > 0: + innerty, inner = get_first_item(innerty, inner) + shapes.append(_get_seq_size(context, builder, innerty, inner)) + + return tuple(shapes) + + +def check_sequence_shape(context, builder, seqty, seq, shapes): + """ + Check the nested sequence matches the given *shapes*. + """ + + def _fail(): + context.call_conv.return_user_exc(builder, ValueError, + ("incompatible sequence shape",)) + + def check_seq_size(seqty, seq, shapes): + if len(shapes) == 0: + return + + size = _get_seq_size(context, builder, seqty, seq) + expected = shapes[0] + mismatch = builder.icmp_signed('!=', size, expected) + with builder.if_then(mismatch, likely=False): + _fail() + + if len(shapes) == 1: + return + + if isinstance(seqty, types.Sequence): + getitem_impl = _get_borrowing_getitem(context, seqty) + with cgutils.for_range(builder, size) as loop: + innerty = seqty.dtype + inner = getitem_impl(builder, (seq, loop.index)) + check_seq_size(innerty, inner, shapes[1:]) + + elif isinstance(seqty, types.BaseTuple): + for i in range(len(seqty)): + innerty = seqty[i] + inner = builder.extract_value(seq, i) + check_seq_size(innerty, inner, shapes[1:]) + + else: + assert 0, seqty + + check_seq_size(seqty, seq, shapes) + + +def assign_sequence_to_array(context, builder, data, shapes, strides, + arrty, seqty, seq): + """ + Assign a nested sequence contents to an array. The shape must match + the sequence's structure. + """ + + def assign_item(indices, valty, val): + ptr = cgutils.get_item_pointer2(context, builder, data, shapes, strides, + arrty.layout, indices, wraparound=False) + val = context.cast(builder, val, valty, arrty.dtype) + store_item(context, builder, arrty, val, ptr) + + def assign(seqty, seq, shapes, indices): + if len(shapes) == 0: + assert not isinstance(seqty, (types.Sequence, types.BaseTuple)) + assign_item(indices, seqty, seq) + return + + size = shapes[0] + + if isinstance(seqty, types.Sequence): + getitem_impl = _get_borrowing_getitem(context, seqty) + with cgutils.for_range(builder, size) as loop: + innerty = seqty.dtype + inner = getitem_impl(builder, (seq, loop.index)) + assign(innerty, inner, shapes[1:], indices + (loop.index,)) + + elif isinstance(seqty, types.BaseTuple): + for i in range(len(seqty)): + innerty = seqty[i] + inner = builder.extract_value(seq, i) + index = context.get_constant(types.intp, i) + assign(innerty, inner, shapes[1:], indices + (index,)) + + else: + assert 0, seqty + + assign(seqty, seq, shapes, ()) + + +def np_array_typer(typingctx, object, dtype): + ndim, seq_dtype = _parse_nested_sequence(typingctx, object) + if is_nonelike(dtype): + dtype = seq_dtype + else: + dtype = ty_parse_dtype(dtype) + if dtype is None: + return + return types.Array(dtype, ndim, 'C') + + +@intrinsic +def np_array(typingctx, obj, dtype): + _check_const_str_dtype("array", dtype) + ret = np_array_typer(typingctx, obj, dtype) + sig = ret(obj, dtype) + + def codegen(context, builder, sig, args): + arrty = sig.return_type + ndim = arrty.ndim + seqty = sig.args[0] + seq = args[0] + + shapes = compute_sequence_shape(context, builder, ndim, seqty, seq) + assert len(shapes) == ndim + + check_sequence_shape(context, builder, seqty, seq, shapes) + arr = _empty_nd_impl(context, builder, arrty, shapes) + assign_sequence_to_array(context, builder, arr.data, shapes, + arr.strides, arrty, seqty, seq) + + return impl_ret_new_ref(context, builder, sig.return_type, + arr._getvalue()) + + return sig, codegen + + +@overload(np.array) +def impl_np_array(object, dtype=None): + _check_const_str_dtype("array", dtype) + if not type_can_asarray(object): + raise errors.TypingError('The argument "object" must ' + 'be array-like') + if not is_nonelike(dtype) and ty_parse_dtype(dtype) is None: + msg = 'The argument "dtype" must be a data-type if it is provided' + raise errors.TypingError(msg) + + def impl(object, dtype=None): + return np_array(object, dtype) + return impl + + +def _normalize_axis(context, builder, func_name, ndim, axis): + zero = axis.type(0) + ll_ndim = axis.type(ndim) + + # Normalize negative axis + is_neg_axis = builder.icmp_signed('<', axis, zero) + axis = builder.select(is_neg_axis, builder.add(axis, ll_ndim), axis) + + # Check axis for bounds + axis_out_of_bounds = builder.or_( + builder.icmp_signed('<', axis, zero), + builder.icmp_signed('>=', axis, ll_ndim)) + with builder.if_then(axis_out_of_bounds, likely=False): + msg = "%s(): axis out of bounds" % func_name + context.call_conv.return_user_exc(builder, IndexError, (msg,)) + + return axis + + +def _insert_axis_in_shape(context, builder, orig_shape, ndim, axis): + """ + Compute shape with the new axis inserted + e.g. given original shape (2, 3, 4) and axis=2, + the returned new shape is (2, 3, 1, 4). + """ + assert len(orig_shape) == ndim - 1 + + ll_shty = ir.ArrayType(cgutils.intp_t, ndim) + shapes = cgutils.alloca_once(builder, ll_shty) + + one = cgutils.intp_t(1) + + # 1. copy original sizes at appropriate places + for dim in range(ndim - 1): + ll_dim = cgutils.intp_t(dim) + after_axis = builder.icmp_signed('>=', ll_dim, axis) + sh = orig_shape[dim] + idx = builder.select(after_axis, + builder.add(ll_dim, one), + ll_dim) + builder.store(sh, cgutils.gep_inbounds(builder, shapes, 0, idx)) + + # 2. insert new size (1) at axis dimension + builder.store(one, cgutils.gep_inbounds(builder, shapes, 0, axis)) + + return cgutils.unpack_tuple(builder, builder.load(shapes)) + + +def _insert_axis_in_strides(context, builder, orig_strides, ndim, axis): + """ + Same as _insert_axis_in_shape(), but with a strides array. + """ + assert len(orig_strides) == ndim - 1 + + ll_shty = ir.ArrayType(cgutils.intp_t, ndim) + strides = cgutils.alloca_once(builder, ll_shty) + + one = cgutils.intp_t(1) + zero = cgutils.intp_t(0) + + # 1. copy original strides at appropriate places + for dim in range(ndim - 1): + ll_dim = cgutils.intp_t(dim) + after_axis = builder.icmp_signed('>=', ll_dim, axis) + idx = builder.select(after_axis, + builder.add(ll_dim, one), + ll_dim) + builder.store(orig_strides[dim], + cgutils.gep_inbounds(builder, strides, 0, idx)) + + # 2. insert new stride at axis dimension + # (the value is indifferent for a 1-sized dimension, we use 0) + builder.store(zero, cgutils.gep_inbounds(builder, strides, 0, axis)) + + return cgutils.unpack_tuple(builder, builder.load(strides)) + + +def expand_dims(context, builder, sig, args, axis): + """ + np.expand_dims() with the given axis. + """ + retty = sig.return_type + ndim = retty.ndim + arrty = sig.args[0] + + arr = make_array(arrty)(context, builder, value=args[0]) + ret = make_array(retty)(context, builder) + + shapes = cgutils.unpack_tuple(builder, arr.shape) + strides = cgutils.unpack_tuple(builder, arr.strides) + + new_shapes = _insert_axis_in_shape(context, builder, shapes, ndim, axis) + new_strides = _insert_axis_in_strides(context, builder, strides, ndim, axis) + + populate_array(ret, + data=arr.data, + shape=new_shapes, + strides=new_strides, + itemsize=arr.itemsize, + meminfo=arr.meminfo, + parent=arr.parent) + + return ret._getvalue() + + +@intrinsic +def np_expand_dims(typingctx, a, axis): + layout = a.layout if a.ndim <= 1 else 'A' + ret = a.copy(ndim=a.ndim + 1, layout=layout) + sig = ret(a, axis) + + def codegen(context, builder, sig, args): + axis = context.cast(builder, args[1], sig.args[1], types.intp) + axis = _normalize_axis(context, builder, "np.expand_dims", + sig.return_type.ndim, axis) + + ret = expand_dims(context, builder, sig, args, axis) + return impl_ret_borrowed(context, builder, sig.return_type, ret) + + return sig, codegen + + +@overload(np.expand_dims) +def impl_np_expand_dims(a, axis): + if not isinstance(a, types.Array): + msg = f'First argument "a" must be an array. Got {a}' + raise errors.TypingError(msg) + + if not isinstance(axis, types.Integer): + msg = f'Argument "axis" must be an integer. Got {axis}' + raise errors.TypingError(msg) + + def impl(a, axis): + return np_expand_dims(a, axis) + return impl + + +def _atleast_nd(minimum, axes): + @intrinsic + def impl(typingcontext, *args): + arrtys = args + rettys = [arg.copy(ndim=max(arg.ndim, minimum)) for arg in args] + + def codegen(context, builder, sig, args): + transform = _atleast_nd_transform(minimum, axes) + arrs = cgutils.unpack_tuple(builder, args[0]) + + rets = [transform(context, builder, arr, arrty, retty) + for arr, arrty, retty in zip(arrs, arrtys, rettys)] + + if len(rets) > 1: + ret = context.make_tuple(builder, sig.return_type, rets) + else: + ret = rets[0] + return impl_ret_borrowed(context, builder, sig.return_type, ret) + + return signature(types.Tuple(rettys) if len(rettys) > 1 else rettys[0], + types.StarArgTuple.from_types(args)), codegen + + return lambda *args: impl(*args) + + +def _atleast_nd_transform(min_ndim, axes): + """ + Return a callback successively inserting 1-sized dimensions at the + following axes. + """ + assert min_ndim == len(axes) + + def transform(context, builder, arr, arrty, retty): + for i in range(min_ndim): + ndim = i + 1 + if arrty.ndim < ndim: + axis = cgutils.intp_t(axes[i]) + newarrty = arrty.copy(ndim=arrty.ndim + 1) + arr = expand_dims(context, builder, + typing.signature(newarrty, arrty), (arr,), + axis) + arrty = newarrty + + return arr + + return transform + + +@overload(np.atleast_1d) +def np_atleast_1d(*args): + if all(isinstance(arg, types.Array) for arg in args): + return _atleast_nd(1, [0]) + + +@overload(np.atleast_2d) +def np_atleast_2d(*args): + if all(isinstance(arg, types.Array) for arg in args): + return _atleast_nd(2, [0, 0]) + + +@overload(np.atleast_3d) +def np_atleast_3d(*args): + if all(isinstance(arg, types.Array) for arg in args): + return _atleast_nd(3, [0, 0, 2]) + + +def _do_concatenate(context, builder, axis, + arrtys, arrs, arr_shapes, arr_strides, + retty, ret_shapes): + """ + Concatenate arrays along the given axis. + """ + assert len(arrtys) == len(arrs) == len(arr_shapes) == len(arr_strides) + + zero = cgutils.intp_t(0) + + # Allocate return array + ret = _empty_nd_impl(context, builder, retty, ret_shapes) + ret_strides = cgutils.unpack_tuple(builder, ret.strides) + + # Compute the offset by which to bump the destination pointer + # after copying each input array. + # Morally, we need to copy each input array at different start indices + # into the destination array; bumping the destination pointer + # is simply easier than offsetting all destination indices. + copy_offsets = [] + + for arr_sh in arr_shapes: + # offset = ret_strides[axis] * input_shape[axis] + offset = zero + for dim, (size, stride) in enumerate(zip(arr_sh, ret_strides)): + is_axis = builder.icmp_signed('==', axis.type(dim), axis) + addend = builder.mul(size, stride) + offset = builder.select(is_axis, + builder.add(offset, addend), + offset) + copy_offsets.append(offset) + + # Copy input arrays into the return array + ret_data = ret.data + + for arrty, arr, arr_sh, arr_st, offset in zip(arrtys, arrs, arr_shapes, + arr_strides, copy_offsets): + arr_data = arr.data + + # Do the copy loop + # Note the loop nesting is optimized for the destination layout + loop_nest = cgutils.loop_nest(builder, arr_sh, cgutils.intp_t, + order=retty.layout) + + with loop_nest as indices: + src_ptr = cgutils.get_item_pointer2(context, builder, arr_data, + arr_sh, arr_st, + arrty.layout, indices) + val = load_item(context, builder, arrty, src_ptr) + val = context.cast(builder, val, arrty.dtype, retty.dtype) + dest_ptr = cgutils.get_item_pointer2(context, builder, ret_data, + ret_shapes, ret_strides, + retty.layout, indices) + store_item(context, builder, retty, val, dest_ptr) + + # Bump destination pointer + ret_data = cgutils.pointer_add(builder, ret_data, offset) + + return ret + + +def _np_concatenate(context, builder, arrtys, arrs, retty, axis): + ndim = retty.ndim + + arrs = [make_array(aty)(context, builder, value=a) + for aty, a in zip(arrtys, arrs)] + + axis = _normalize_axis(context, builder, "np.concatenate", ndim, axis) + + # Get input shapes + arr_shapes = [cgutils.unpack_tuple(builder, arr.shape) for arr in arrs] + arr_strides = [cgutils.unpack_tuple(builder, arr.strides) for arr in arrs] + + # Compute return shape: + # - the dimension for the concatenation axis is summed over all inputs + # - other dimensions must match exactly for each input + ret_shapes = [cgutils.alloca_once_value(builder, sh) + for sh in arr_shapes[0]] + + for dim in range(ndim): + is_axis = builder.icmp_signed('==', axis.type(dim), axis) + ret_shape_ptr = ret_shapes[dim] + ret_sh = builder.load(ret_shape_ptr) + other_shapes = [sh[dim] for sh in arr_shapes[1:]] + + with builder.if_else(is_axis) as (on_axis, on_other_dim): + with on_axis: + sh = functools.reduce( + builder.add, + other_shapes + [ret_sh]) + builder.store(sh, ret_shape_ptr) + + with on_other_dim: + is_ok = cgutils.true_bit + for sh in other_shapes: + is_ok = builder.and_(is_ok, + builder.icmp_signed('==', sh, ret_sh)) + with builder.if_then(builder.not_(is_ok), likely=False): + context.call_conv.return_user_exc( + builder, ValueError, + ("np.concatenate(): input sizes over " + "dimension %d do not match" % dim,)) + + ret_shapes = [builder.load(sh) for sh in ret_shapes] + + ret = _do_concatenate(context, builder, axis, + arrtys, arrs, arr_shapes, arr_strides, + retty, ret_shapes) + return impl_ret_new_ref(context, builder, retty, ret._getvalue()) + + +def _np_stack(context, builder, arrtys, arrs, retty, axis): + ndim = retty.ndim + + zero = cgutils.intp_t(0) + one = cgutils.intp_t(1) + ll_narrays = cgutils.intp_t(len(arrs)) + + arrs = [make_array(aty)(context, builder, value=a) + for aty, a in zip(arrtys, arrs)] + + axis = _normalize_axis(context, builder, "np.stack", ndim, axis) + + # Check input arrays have the same shape + orig_shape = cgutils.unpack_tuple(builder, arrs[0].shape) + + for arr in arrs[1:]: + is_ok = cgutils.true_bit + for sh, orig_sh in zip(cgutils.unpack_tuple(builder, arr.shape), + orig_shape): + is_ok = builder.and_(is_ok, builder.icmp_signed('==', sh, orig_sh)) + with builder.if_then(builder.not_(is_ok), likely=False): + context.call_conv.return_user_exc( + builder, ValueError, + ("np.stack(): all input arrays must have the same shape",)) + + orig_strides = [cgutils.unpack_tuple(builder, arr.strides) for arr in arrs] + + # Compute input shapes and return shape with the new axis inserted + # e.g. given 5 input arrays of shape (2, 3, 4) and axis=1, + # corrected input shape is (2, 1, 3, 4) and return shape is (2, 5, 3, 4). + ll_shty = ir.ArrayType(cgutils.intp_t, ndim) + + input_shapes = cgutils.alloca_once(builder, ll_shty) + ret_shapes = cgutils.alloca_once(builder, ll_shty) + + # 1. copy original sizes at appropriate places + for dim in range(ndim - 1): + ll_dim = cgutils.intp_t(dim) + after_axis = builder.icmp_signed('>=', ll_dim, axis) + sh = orig_shape[dim] + idx = builder.select(after_axis, + builder.add(ll_dim, one), + ll_dim) + builder.store(sh, cgutils.gep_inbounds(builder, input_shapes, 0, idx)) + builder.store(sh, cgutils.gep_inbounds(builder, ret_shapes, 0, idx)) + + # 2. insert new size at axis dimension + builder.store(one, cgutils.gep_inbounds(builder, input_shapes, 0, axis)) + builder.store(ll_narrays, cgutils.gep_inbounds(builder, + ret_shapes, + 0, + axis)) + + input_shapes = cgutils.unpack_tuple(builder, builder.load(input_shapes)) + input_shapes = [input_shapes] * len(arrs) + ret_shapes = cgutils.unpack_tuple(builder, builder.load(ret_shapes)) + + # Compute input strides for each array with the new axis inserted + input_strides = [cgutils.alloca_once(builder, ll_shty) + for i in range(len(arrs))] + + # 1. copy original strides at appropriate places + for dim in range(ndim - 1): + ll_dim = cgutils.intp_t(dim) + after_axis = builder.icmp_signed('>=', ll_dim, axis) + idx = builder.select(after_axis, + builder.add(ll_dim, one), + ll_dim) + for i in range(len(arrs)): + builder.store(orig_strides[i][dim], + cgutils.gep_inbounds(builder, input_strides[i], 0, + idx)) + + # 2. insert new stride at axis dimension + # (the value is indifferent for a 1-sized dimension, we put 0) + for i in range(len(arrs)): + builder.store(zero, cgutils.gep_inbounds(builder, input_strides[i], 0, + axis)) + + input_strides = [cgutils.unpack_tuple(builder, builder.load(st)) + for st in input_strides] + + # Create concatenated array + ret = _do_concatenate(context, builder, axis, + arrtys, arrs, input_shapes, input_strides, + retty, ret_shapes) + return impl_ret_new_ref(context, builder, retty, ret._getvalue()) + + +def np_concatenate_typer(typingctx, arrays, axis): + if axis is not None and not isinstance(axis, types.Integer): + # Note Numpy allows axis=None, but it isn't documented: + # https://github.com/numpy/numpy/issues/7968 + return + + # does type checking + dtype, ndim = _sequence_of_arrays(typingctx, + "np.concatenate", arrays) + if ndim == 0: + msg = "zero-dimensional arrays cannot be concatenated" + raise errors.NumbaTypeError(msg) + + layout = _choose_concatenation_layout(arrays) + + return types.Array(dtype, ndim, layout) + + +@intrinsic +def np_concatenate(typingctx, arrays, axis): + ret = np_concatenate_typer(typingctx, arrays, axis) + assert isinstance(ret, types.Array) + sig = ret(arrays, axis) + + def codegen(context, builder, sig, args): + axis = context.cast(builder, args[1], sig.args[1], types.intp) + return _np_concatenate(context, builder, + list(sig.args[0]), + cgutils.unpack_tuple(builder, args[0]), + sig.return_type, + axis) + + return sig, codegen + + +@overload(np.concatenate) +def impl_np_concatenate(arrays, axis=0): + if isinstance(arrays, types.BaseTuple): + def impl(arrays, axis=0): + return np_concatenate(arrays, axis) + return impl + + +def _column_stack_dims(context, func_name, arrays): + # column_stack() allows stacking 1-d and 2-d arrays together + for a in arrays: + if a.ndim < 1 or a.ndim > 2: + msg = "np.column_stack() is only defined on 1-d and 2-d arrays" + raise errors.NumbaTypeError(msg) + return 2 + + +@intrinsic +def np_column_stack(typingctx, tup): + dtype, ndim = _sequence_of_arrays(typingctx, + "np.column_stack", tup, + dim_chooser=_column_stack_dims) + layout = _choose_concatenation_layout(tup) + ret = types.Array(dtype, ndim, layout) + sig = ret(tup) + + def codegen(context, builder, sig, args): + orig_arrtys = list(sig.args[0]) + orig_arrs = cgutils.unpack_tuple(builder, args[0]) + + arrtys = [] + arrs = [] + + axis = context.get_constant(types.intp, 1) + + for arrty, arr in zip(orig_arrtys, orig_arrs): + if arrty.ndim == 2: + arrtys.append(arrty) + arrs.append(arr) + else: + # Convert 1d array to 2d column array: np.expand_dims(a, 1) + assert arrty.ndim == 1 + newty = arrty.copy(ndim=2) + expand_sig = typing.signature(newty, arrty) + newarr = expand_dims(context, builder, expand_sig, (arr,), axis) + + arrtys.append(newty) + arrs.append(newarr) + + return _np_concatenate(context, builder, arrtys, arrs, + sig.return_type, axis) + + return sig, codegen + + +@overload(np.column_stack) +def impl_column_stack(tup): + if isinstance(tup, types.BaseTuple): + def impl(tup): + return np_column_stack(tup) + return impl + + +def _np_stack_common(context, builder, sig, args, axis): + """ + np.stack() with the given axis value. + """ + return _np_stack(context, builder, + list(sig.args[0]), + cgutils.unpack_tuple(builder, args[0]), + sig.return_type, + axis) + + +@intrinsic +def np_stack_common(typingctx, arrays, axis): + # does type checking + dtype, ndim = _sequence_of_arrays(typingctx, + "np.stack", arrays) + layout = 'F' if all(a.layout == 'F' for a in arrays) else 'C' + ret = types.Array(dtype, ndim + 1, layout) + sig = ret(arrays, axis) + + def codegen(context, builder, sig, args): + axis = context.cast(builder, args[1], sig.args[1], types.intp) + return _np_stack_common(context, builder, sig, args, axis) + + return sig, codegen + + +@overload(np.stack) +def impl_np_stack(arrays, axis=0): + if isinstance(arrays, types.BaseTuple): + def impl(arrays, axis=0): + return np_stack_common(arrays, axis) + return impl + + +def NdStack_typer(typingctx, func_name, arrays, ndim_min): + # does type checking + dtype, ndim = _sequence_of_arrays(typingctx, func_name, arrays) + ndim = max(ndim, ndim_min) + layout = _choose_concatenation_layout(arrays) + ret = types.Array(dtype, ndim, layout) + return ret + + +@intrinsic +def _np_hstack(typingctx, tup): + ret = NdStack_typer(typingctx, "np.hstack", tup, 1) + sig = ret(tup) + + def codegen(context, builder, sig, args): + tupty = sig.args[0] + ndim = tupty[0].ndim + + if ndim == 0: + # hstack() on 0-d arrays returns a 1-d array + axis = context.get_constant(types.intp, 0) + return _np_stack_common(context, builder, sig, args, axis) + + else: + # As a special case, dimension 0 of 1-dimensional arrays + # is "horizontal" + axis = 0 if ndim == 1 else 1 + + def np_hstack_impl(arrays): + return np.concatenate(arrays, axis=axis) + + return context.compile_internal(builder, np_hstack_impl, sig, args) + + return sig, codegen + + +@overload(np.hstack) +def impl_np_hstack(tup): + if isinstance(tup, types.BaseTuple): + def impl(tup): + return _np_hstack(tup) + return impl + + +@intrinsic +def _np_vstack(typingctx, tup): + ret = NdStack_typer(typingctx, "np.vstack", tup, 2) + sig = ret(tup) + + def codegen(context, builder, sig, args): + tupty = sig.args[0] + ndim = tupty[0].ndim + + if ndim == 0: + def np_vstack_impl(arrays): + return np.expand_dims(np.hstack(arrays), 1) + + elif ndim == 1: + # np.stack(arrays, axis=0) + axis = context.get_constant(types.intp, 0) + return _np_stack_common(context, builder, sig, args, axis) + + else: + def np_vstack_impl(arrays): + return np.concatenate(arrays, axis=0) + + return context.compile_internal(builder, np_vstack_impl, sig, args) + + return sig, codegen + + +@overload(np.vstack) +def impl_np_vstack(tup): + if isinstance(tup, types.BaseTuple): + def impl(tup): + return _np_vstack(tup) + return impl + + +if numpy_version >= (2, 0): + overload(np.row_stack)(impl_np_vstack) + + +@intrinsic +def _np_dstack(typingctx, tup): + ret = NdStack_typer(typingctx, "np.dstack", tup, 3) + sig = ret(tup) + + def codegen(context, builder, sig, args): + tupty = sig.args[0] + retty = sig.return_type + ndim = tupty[0].ndim + + if ndim == 0: + def np_vstack_impl(arrays): + return np.hstack(arrays).reshape(1, 1, -1) + + return context.compile_internal(builder, np_vstack_impl, sig, args) + + elif ndim == 1: + # np.expand_dims(np.stack(arrays, axis=1), axis=0) + axis = context.get_constant(types.intp, 1) + stack_retty = retty.copy(ndim=retty.ndim - 1) + stack_sig = typing.signature(stack_retty, *sig.args) + stack_ret = _np_stack_common(context, builder, stack_sig, args, + axis) + + axis = context.get_constant(types.intp, 0) + expand_sig = typing.signature(retty, stack_retty) + return expand_dims(context, builder, expand_sig, (stack_ret,), axis) + + elif ndim == 2: + # np.stack(arrays, axis=2) + axis = context.get_constant(types.intp, 2) + return _np_stack_common(context, builder, sig, args, axis) + + else: + def np_vstack_impl(arrays): + return np.concatenate(arrays, axis=2) + + return context.compile_internal(builder, np_vstack_impl, sig, args) + + return sig, codegen + + +@overload(np.dstack) +def impl_np_dstack(tup): + if isinstance(tup, types.BaseTuple): + def impl(tup): + return _np_dstack(tup) + return impl + + +@extending.overload_method(types.Array, 'fill') +def arr_fill(arr, val): + + def fill_impl(arr, val): + arr[:] = val + return None + + return fill_impl + + +@extending.overload_method(types.Array, 'dot') +def array_dot(arr, other): + def dot_impl(arr, other): + return np.dot(arr, other) + + return dot_impl + + +@overload(np.fliplr) +def np_flip_lr(m): + + if not type_can_asarray(m): + raise errors.TypingError("Cannot np.fliplr on %s type" % m) + + def impl(m): + A = np.asarray(m) + # this handling is superfluous/dead as < 2d array cannot be indexed as + # present below and so typing fails. If the typing doesn't fail due to + # some future change, this will catch it. + if A.ndim < 2: + raise ValueError('Input must be >= 2-d.') + return A[::, ::-1, ...] + return impl + + +@overload(np.flipud) +def np_flip_ud(m): + + if not type_can_asarray(m): + raise errors.TypingError("Cannot np.flipud on %s type" % m) + + def impl(m): + A = np.asarray(m) + # this handling is superfluous/dead as a 0d array cannot be indexed as + # present below and so typing fails. If the typing doesn't fail due to + # some future change, this will catch it. + if A.ndim < 1: + raise ValueError('Input must be >= 1-d.') + return A[::-1, ...] + return impl + + +@intrinsic +def _build_flip_slice_tuple(tyctx, sz): + """ Creates a tuple of slices for np.flip indexing like + `(slice(None, None, -1),) * sz` """ + if not isinstance(sz, types.IntegerLiteral): + raise errors.RequireLiteralValue(sz) + size = int(sz.literal_value) + tuple_type = types.UniTuple(dtype=types.slice3_type, count=size) + sig = tuple_type(sz) + + def codegen(context, builder, signature, args): + def impl(length, empty_tuple): + out = empty_tuple + for i in range(length): + out = tuple_setitem(out, i, slice(None, None, -1)) + return out + + inner_argtypes = [types.intp, tuple_type] + inner_sig = typing.signature(tuple_type, *inner_argtypes) + ll_idx_type = context.get_value_type(types.intp) + # Allocate an empty tuple + empty_tuple = context.get_constant_undef(tuple_type) + inner_args = [ll_idx_type(size), empty_tuple] + + res = context.compile_internal(builder, impl, inner_sig, inner_args) + return res + + return sig, codegen + + +@overload(np.flip) +def np_flip(m): + # a constant value is needed for the tuple slice, types.Array.ndim can + # provide this and so at presnet only type.Array is support + if not isinstance(m, types.Array): + raise errors.TypingError("Cannot np.flip on %s type" % m) + + def impl(m): + sl = _build_flip_slice_tuple(m.ndim) + return m[sl] + + return impl + + +@overload(np.array_split) +def np_array_split(ary, indices_or_sections, axis=0): + if isinstance(ary, (types.UniTuple, types.ListType, types.List)): + def impl(ary, indices_or_sections, axis=0): + return np.array_split( + np.asarray(ary), + indices_or_sections, + axis=axis + ) + + return impl + + if isinstance(indices_or_sections, types.Integer): + def impl(ary, indices_or_sections, axis=0): + l, rem = divmod(ary.shape[axis], indices_or_sections) + indices = np.cumsum(np.array( + [l + 1] * rem + + [l] * (indices_or_sections - rem - 1) + )) + return np.array_split(ary, indices, axis=axis) + + return impl + + elif ( + isinstance(indices_or_sections, types.IterableType) + and isinstance( + indices_or_sections.iterator_type.yield_type, + types.Integer + ) + ): + def impl(ary, indices_or_sections, axis=0): + slice_tup = build_full_slice_tuple(ary.ndim) + axis = normalize_axis("np.split", "axis", ary.ndim, axis) + out = [] + prev = 0 + for cur in indices_or_sections: + idx = tuple_setitem(slice_tup, axis, slice(prev, cur)) + out.append(ary[idx]) + prev = cur + out.append(ary[tuple_setitem(slice_tup, axis, slice(cur, None))]) + return out + + return impl + + elif ( + isinstance(indices_or_sections, types.Tuple) + and all(isinstance(t, types.Integer) for t in indices_or_sections.types) + ): + def impl(ary, indices_or_sections, axis=0): + slice_tup = build_full_slice_tuple(ary.ndim) + axis = normalize_axis("np.split", "axis", ary.ndim, axis) + out = [] + prev = 0 + for cur in literal_unroll(indices_or_sections): + idx = tuple_setitem(slice_tup, axis, slice(prev, cur)) + out.append(ary[idx]) + prev = cur + out.append(ary[tuple_setitem(slice_tup, axis, slice(cur, None))]) + return out + + return impl + + +@overload(np.split) +def np_split(ary, indices_or_sections, axis=0): + # This is just a wrapper of array_split, but with an extra error if + # indices is an int. + if isinstance(ary, (types.UniTuple, types.ListType, types.List)): + def impl(ary, indices_or_sections, axis=0): + return np.split(np.asarray(ary), indices_or_sections, axis=axis) + + return impl + + if isinstance(indices_or_sections, types.Integer): + def impl(ary, indices_or_sections, axis=0): + _, rem = divmod(ary.shape[axis], indices_or_sections) + if rem != 0: + raise ValueError( + "array split does not result in an equal division" + ) + return np.array_split( + ary, indices_or_sections, axis=axis + ) + + return impl + + else: + return np_array_split(ary, indices_or_sections, axis=axis) + + +@overload(np.vsplit) +def numpy_vsplit(ary, indices_or_sections): + if not isinstance(ary, types.Array): + msg = 'The argument "ary" must be an array' + raise errors.TypingError(msg) + + if not isinstance(indices_or_sections, (types.Integer, types.Array, + types.List, types.UniTuple)): + msg = ('The argument "indices_or_sections" must be int or 1d-array') + raise errors.TypingError(msg) + + def impl(ary, indices_or_sections): + if ary.ndim < 2: + raise ValueError(('vsplit only works on ' + 'arrays of 2 or more dimensions')) + return np.split(ary, indices_or_sections, axis=0) + + return impl + + +@overload(np.hsplit) +def numpy_hsplit(ary, indices_or_sections): + if not isinstance(ary, types.Array): + msg = 'The argument "ary" must be an array' + raise errors.TypingError(msg) + + if not isinstance(indices_or_sections, (types.Integer, types.Array, + types.List, types.UniTuple)): + msg = ('The argument "indices_or_sections" must be int or 1d-array') + raise errors.TypingError(msg) + + def impl(ary, indices_or_sections): + if ary.ndim == 0: + raise ValueError(('hsplit only works on ' + 'arrays of 1 or more dimensions')) + if ary.ndim > 1: + return np.split(ary, indices_or_sections, axis=1) + return np.split(ary, indices_or_sections, axis=0) + + return impl + + +@overload(np.dsplit) +def numpy_dsplit(ary, indices_or_sections): + if not isinstance(ary, types.Array): + msg = 'The argument "ary" must be an array' + raise errors.TypingError(msg) + + if not isinstance(indices_or_sections, (types.Integer, types.Array, + types.List, types.UniTuple)): + msg = ('The argument "indices_or_sections" must be int or 1d-array') + raise errors.TypingError(msg) + + def impl(ary, indices_or_sections): + if ary.ndim < 3: + raise ValueError('dsplit only works on arrays of 3 or more ' + 'dimensions') + return np.split(ary, indices_or_sections, axis=2) + + return impl + + +# ----------------------------------------------------------------------------- +# Sorting + +_sorts = {} + + +def default_lt(a, b): + """ + Trivial comparison function between two keys. + """ + return a < b + + +def get_sort_func(kind, lt_impl, is_argsort=False): + """ + Get a sort implementation of the given kind. + """ + key = kind, lt_impl.__name__, is_argsort + + try: + return _sorts[key] + except KeyError: + if kind == 'quicksort': + sort = quicksort.make_jit_quicksort( + lt=lt_impl, + is_argsort=is_argsort, + is_np_array=True) + func = sort.run_quicksort + elif kind == 'mergesort': + sort = mergesort.make_jit_mergesort( + lt=lt_impl, + is_argsort=is_argsort) + func = sort.run_mergesort + _sorts[key] = func + return func + + +def lt_implementation(dtype): + if isinstance(dtype, types.Float): + return lt_floats + elif isinstance(dtype, types.Complex): + return lt_complex + else: + return default_lt + + +@lower_builtin("array.sort", types.Array) +def array_sort(context, builder, sig, args): + arytype = sig.args[0] + + sort_func = get_sort_func(kind='quicksort', + lt_impl=lt_implementation(arytype.dtype)) + + def array_sort_impl(arr): + # Note we clobber the return value + sort_func(arr) + + return context.compile_internal(builder, array_sort_impl, sig, args) + + +@overload(np.sort) +def impl_np_sort(a): + if not type_can_asarray(a): + raise errors.TypingError('Argument "a" must ' + 'be array-like') + + def np_sort_impl(a): + res = a.copy() + res.sort() + return res + return np_sort_impl + + +@lower_builtin("array.argsort", types.Array, types.StringLiteral) +@lower_builtin(np.argsort, types.Array, types.StringLiteral) +def array_argsort(context, builder, sig, args): + arytype, kind = sig.args + + sort_func = get_sort_func(kind=kind.literal_value, + lt_impl=lt_implementation(arytype.dtype), + is_argsort=True) + + def array_argsort_impl(arr): + return sort_func(arr) + + innersig = sig.replace(args=sig.args[:1]) + innerargs = args[:1] + return context.compile_internal(builder, array_argsort_impl, + innersig, innerargs) + + +# ------------------------------------------------------------------------------ +# Implicit cast + +@lower_cast(types.Array, types.Array) +def array_to_array(context, builder, fromty, toty, val): + # Type inference should have prevented illegal array casting. + assert fromty.mutable != toty.mutable or toty.layout == 'A' + return val + + +@lower_cast(types.Array, types.UnicodeCharSeq) +@lower_cast(types.Array, types.Float) +@lower_cast(types.Array, types.Integer) +@lower_cast(types.Array, types.Complex) +@lower_cast(types.Array, types.Boolean) +@lower_cast(types.Array, types.NPTimedelta) +@lower_cast(types.Array, types.NPDatetime) +def array0d_to_scalar(context, builder, fromty, toty, val): + def impl(a): + # a is an array(T, 0d, O), T is type, O is order + return a.take(0) + + sig = signature(toty, fromty) + res = context.compile_internal(builder, impl, sig, [val]) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_cast(types.Array, types.UnicodeCharSeq) +def array_to_unichrseq(context, builder, fromty, toty, val): + def impl(a): + return str(a[()]) + + sig = signature(toty, fromty) + res = context.compile_internal(builder, impl, sig, [val]) + return impl_ret_borrowed(context, builder, sig.return_type, res) + + +# ------------------------------------------------------------------------------ +# Stride tricks + +def reshape_unchecked(a, shape, strides): + """ + An intrinsic returning a derived array with the given shape and strides. + """ + raise NotImplementedError + + +@extending.type_callable(reshape_unchecked) +def type_reshape_unchecked(context): + def check_shape(shape): + return (isinstance(shape, types.BaseTuple) and + all(isinstance(v, types.Integer) for v in shape)) + + def typer(a, shape, strides): + if not isinstance(a, types.Array): + return + if not check_shape(shape) or not check_shape(strides): + return + if len(shape) != len(strides): + return + return a.copy(ndim=len(shape), layout='A') + + return typer + + +@lower_builtin(reshape_unchecked, types.Array, types.BaseTuple, types.BaseTuple) +def impl_shape_unchecked(context, builder, sig, args): + aryty = sig.args[0] + retty = sig.return_type + + ary = make_array(aryty)(context, builder, args[0]) + out = make_array(retty)(context, builder) + shape = cgutils.unpack_tuple(builder, args[1]) + strides = cgutils.unpack_tuple(builder, args[2]) + + populate_array(out, + data=ary.data, + shape=shape, + strides=strides, + itemsize=ary.itemsize, + meminfo=ary.meminfo, + ) + + res = out._getvalue() + return impl_ret_borrowed(context, builder, retty, res) + + +@extending.overload(np.lib.stride_tricks.as_strided) +def as_strided(x, shape=None, strides=None): + if shape in (None, types.none): + @register_jitable + def get_shape(x, shape): + return x.shape + else: + @register_jitable + def get_shape(x, shape): + return shape + + if strides in (None, types.none): + # When *strides* is not passed, as_strided() does a non-size-checking + # reshape(), possibly changing the original strides. This is too + # cumbersome to support right now, and a Web search shows all example + # use cases of as_strided() pass explicit *strides*. + raise errors.TypingError("as_strided() strides argument cannot be None") + else: + @register_jitable + def get_strides(x, strides): + return strides + + def as_strided_impl(x, shape=None, strides=None): + x = reshape_unchecked(x, get_shape(x, shape), get_strides(x, strides)) + return x + + return as_strided_impl + + +@extending.overload(np.lib.stride_tricks.sliding_window_view) +def sliding_window_view(x, window_shape, axis=None): + + # Window shape must be given as either an integer or tuple of integers. + # We also need to generate buffer tuples we can modify to contain the + # final shape and strides (reshape_unchecked does not accept lists). + if isinstance(window_shape, types.Integer): + shape_buffer = tuple(range(x.ndim + 1)) + stride_buffer = tuple(range(x.ndim + 1)) + + @register_jitable + def get_window_shape(window_shape): + return (window_shape,) + + elif (isinstance(window_shape, types.UniTuple) and + isinstance(window_shape.dtype, types.Integer)): + shape_buffer = tuple(range(x.ndim + len(window_shape))) + stride_buffer = tuple(range(x.ndim + len(window_shape))) + + @register_jitable + def get_window_shape(window_shape): + return window_shape + + else: + raise errors.TypingError( + "window_shape must be an integer or tuple of integers" + ) + + # Axis must be integer, tuple of integers, or None for all axes. + if is_nonelike(axis): + @register_jitable + def get_axis(window_shape, axis, ndim): + return list(range(ndim)) + + elif isinstance(axis, types.Integer): + @register_jitable + def get_axis(window_shape, axis, ndim): + return [ + normalize_axis("sliding_window_view", "axis", ndim, axis) + ] + + elif (isinstance(axis, types.UniTuple) and + isinstance(axis.dtype, types.Integer)): + @register_jitable + def get_axis(window_shape, axis, ndim): + return [normalize_axis("sliding_window_view", "axis", ndim, a) + for a in axis] + + else: + raise errors.TypingError( + "axis must be None, an integer or tuple of integers" + ) + + def sliding_window_view_impl(x, window_shape, axis=None): + window_shape = get_window_shape(window_shape) + axis = get_axis(window_shape, axis, x.ndim) + if len(window_shape) != len(axis): + raise ValueError( + "Must provide matching length window_shape and axis" + ) + + # Initialise view details with shape and strides of x. + out_shape = shape_buffer + out_strides = stride_buffer + for i in range(x.ndim): + out_shape = tuple_setitem(out_shape, i, x.shape[i]) + out_strides = tuple_setitem(out_strides, i, x.strides[i]) + + # Trim the dimensions being windowed and set the window shape and + # strides. Note: the same axis can be windowed repeatedly. + i = x.ndim + for ax, dim in zip(axis, window_shape): + if dim < 0: + raise ValueError( + "`window_shape` cannot contain negative values" + ) + if out_shape[ax] < dim: + raise ValueError( + "window_shape cannot be larger than input array shape" + ) + + trimmed = out_shape[ax] - dim + 1 + out_shape = tuple_setitem(out_shape, ax, trimmed) + out_shape = tuple_setitem(out_shape, i, dim) + out_strides = tuple_setitem(out_strides, i, x.strides[ax]) + i += 1 + + # The NumPy version calls as_strided, but our implementation of + # as_strided is effectively a wrapper for reshape_unchecked. + view = reshape_unchecked(x, out_shape, out_strides) + return view + + return sliding_window_view_impl + + +@overload(bool) +def ol_bool(arr): + if isinstance(arr, types.Array): + def impl(arr): + if arr.size == 0: + if numpy_version < (2, 2): + return False # this is deprecated + else: + raise ValueError(("The truth value of an empty array is " + "ambiguous. Use `array.size > 0` to " + "check that an array is not empty.")) + elif arr.size == 1: + return bool(arr.take(0)) + else: + raise ValueError(("The truth value of an array with more than" + " one element is ambiguous. Use a.any() or" + " a.all()")) + return impl + + +@overload(np.swapaxes) +def numpy_swapaxes(a, axis1, axis2): + if not isinstance(axis1, (int, types.Integer)): + raise errors.TypingError('The second argument "axis1" must be an ' + 'integer') + if not isinstance(axis2, (int, types.Integer)): + raise errors.TypingError('The third argument "axis2" must be an ' + 'integer') + if not isinstance(a, types.Array): + raise errors.TypingError('The first argument "a" must be an array') + + # create tuple list for transpose + ndim = a.ndim + axes_list = tuple(range(ndim)) + + def impl(a, axis1, axis2): + axis1 = normalize_axis("np.swapaxes", "axis1", ndim, axis1) + axis2 = normalize_axis("np.swapaxes", "axis2", ndim, axis2) + axes_tuple = tuple_setitem(axes_list, axis1, axis2) + axes_tuple = tuple_setitem(axes_tuple, axis2, axis1) + return np.transpose(a, axes_tuple) + + return impl + + +@overload(np.moveaxis) +def numpy_moveaxis(a, source, destination): + if not isinstance(a, types.Array): + raise errors.TypingError('The first argument "a" must be an array') + if not ( + isinstance(source, types.Integer) + or ( + isinstance(source, types.Sequence) + and isinstance(source.dtype, types.Integer) + ) + ): + raise errors.TypingError( + 'The second argument "source" must be an integer ' + 'or sequence of integers' + ) + if not ( + isinstance(destination, types.Integer) + or ( + isinstance(destination, types.Sequence) + and isinstance(destination.dtype, types.Integer) + ) + ): + raise errors.TypingError( + 'The third argument "destination" must be an integer ' + 'or sequence of integers' + ) + + ndim = a.ndim + order_init = (1,) * a.ndim + + def impl(a, source, destination): + source = normalize_axis_tuple("np.moveaxis", "source", ndim, source) + destination = normalize_axis_tuple( + "np.moveaxis", "destination", ndim, destination + ) + if len(source) != len(destination): + raise ValueError( + "`source` and `destination` arguments must have " + "the same number of parameters" + ) + + order_list = [n for n in range(a.ndim) if n not in source] + + for dest, src in sorted(zip(destination, source)): + order_list.insert(dest, src) + + order = order_init + for i, o in enumerate(order_list): + order = tuple_setitem(order, i, o) + + return a.transpose(order) + + return impl + + +@register_jitable +def _take_along_axis_impl( + arr, indices, axis, Ni_orig, Nk_orig, indices_broadcast_shape +): + # Based on example code in + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/shape_base.py#L90-L103 + # With addition of pre-broadcasting: + # https://github.com/numpy/numpy/issues/19704 + + # Wrap axis, it's used in tuple_setitem so must be (axis >= 0) to ensure + # the GEP is in bounds. + axis = normalize_axis("np.take_along_axis", "axis", arr.ndim, axis) + + # Broadcast the two arrays to matching shapes: + arr_shape = list(arr.shape) + arr_shape[axis] = 1 + for i, (d1, d2) in enumerate(zip(arr_shape, indices.shape)): + if d1 == 1: + new_val = d2 + elif d2 == 1: + new_val = d1 + else: + if d1 != d2: + raise ValueError( + "`arr` and `indices` dimensions don't match" + ) + new_val = d1 + indices_broadcast_shape = tuple_setitem( + indices_broadcast_shape, i, new_val + ) + arr_broadcast_shape = tuple_setitem( + indices_broadcast_shape, axis, arr.shape[axis] + ) + arr = np.broadcast_to(arr, arr_broadcast_shape) + indices = np.broadcast_to(indices, indices_broadcast_shape) + + Ni = Ni_orig + if len(Ni_orig) > 0: + for i in range(len(Ni)): + Ni = tuple_setitem(Ni, i, arr.shape[i]) + Nk = Nk_orig + if len(Nk_orig) > 0: + for i in range(len(Nk)): + Nk = tuple_setitem(Nk, i, arr.shape[axis + 1 + i]) + + J = indices.shape[axis] # Need not equal M + out = np.empty(Ni + (J,) + Nk, arr.dtype) + + np_s_ = (slice(None, None, None),) + + for ii in np.ndindex(Ni): + for kk in np.ndindex(Nk): + a_1d = arr[ii + np_s_ + kk] + indices_1d = indices[ii + np_s_ + kk] + out_1d = out[ii + np_s_ + kk] + for j in range(J): + out_1d[j] = a_1d[indices_1d[j]] + return out + + +@overload(np.take_along_axis) +def arr_take_along_axis(arr, indices, axis): + if not isinstance(arr, types.Array): + raise errors.TypingError('The first argument "arr" must be an array') + if not isinstance(indices, types.Array): + raise errors.TypingError( + 'The second argument "indices" must be an array') + if not isinstance(indices.dtype, types.Integer): + raise errors.TypingError('The indices array must contain integers') + if is_nonelike(axis): + arr_ndim = 1 + else: + arr_ndim = arr.ndim + if arr_ndim != indices.ndim: + # Matches NumPy error: + raise errors.TypingError( + "`indices` and `arr` must have the same number of dimensions" + ) + + indices_broadcast_shape = tuple(range(indices.ndim)) + if is_nonelike(axis): + def take_along_axis_impl(arr, indices, axis): + return _take_along_axis_impl(arr.flatten(), indices, 0, (), (), + indices_broadcast_shape) + else: + check_is_integer(axis, "axis") + if not isinstance(axis, types.IntegerLiteral): + raise errors.NumbaValueError("axis must be a literal value") + axis = axis.literal_value + if axis < 0: + axis = arr.ndim + axis + + if axis < 0 or axis >= arr.ndim: + raise errors.NumbaValueError("axis is out of bounds") + + Ni = tuple(range(axis)) + Nk = tuple(range(axis + 1, arr.ndim)) + + def take_along_axis_impl(arr, indices, axis): + return _take_along_axis_impl(arr, indices, axis, Ni, Nk, + indices_broadcast_shape) + return take_along_axis_impl + + +@overload(np.nan_to_num) +def nan_to_num_impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + if isinstance(x, types.Number): + if isinstance(x, types.Integer): + # Integers do not have nans or infs + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + return x + + elif isinstance(x, types.Float): + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + min_inf = ( + neginf + if neginf is not None + else np.finfo(type(x)).min + ) + max_inf = ( + posinf + if posinf is not None + else np.finfo(type(x)).max + ) + + if np.isnan(x): + return nan + elif np.isneginf(x): + return min_inf + elif np.isposinf(x): + return max_inf + return x + elif isinstance(x, types.Complex): + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + r = np.nan_to_num(x.real, nan=nan, posinf=posinf, neginf=neginf) + c = np.nan_to_num(x.imag, nan=nan, posinf=posinf, neginf=neginf) + return complex(r, c) + else: + raise errors.TypingError( + "Only Integer, Float, and Complex values are accepted" + ) + + elif type_can_asarray(x): + if isinstance(x.dtype, types.Integer): + # Integers do not have nans or infs + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + return x + elif isinstance(x.dtype, types.Float): + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + min_inf = ( + neginf + if neginf is not None + else np.finfo(x.dtype).min + ) + max_inf = ( + posinf + if posinf is not None + else np.finfo(x.dtype).max + ) + + x_ = np.asarray(x) + output = np.copy(x_) if copy else x_ + + output_flat = output.flat + for i in range(output.size): + if np.isnan(output_flat[i]): + output_flat[i] = nan + elif np.isneginf(output_flat[i]): + output_flat[i] = min_inf + elif np.isposinf(output_flat[i]): + output_flat[i] = max_inf + return output + elif isinstance(x.dtype, types.Complex): + def impl(x, copy=True, nan=0.0, posinf=None, neginf=None): + x_ = np.asarray(x) + output = np.copy(x_) if copy else x_ + + np.nan_to_num( + output.real, + copy=False, + nan=nan, + posinf=posinf, + neginf=neginf + ) + np.nan_to_num( + output.imag, + copy=False, + nan=nan, + posinf=posinf, + neginf=neginf + ) + return output + else: + raise errors.TypingError( + "Only Integer, Float, and Complex values are accepted" + ) + else: + raise errors.TypingError("The first argument must be a scalar or an " + "array-like") + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/extensions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..e0051a1fc18a24df57dfc337838c37d170b22521 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/extensions.py @@ -0,0 +1,10 @@ +""" +NumPy extensions. +""" + +from numba.np.arraymath import cross2d + + +__all__ = [ + 'cross2d' +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/linalg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..d26ba1e07610612065d7463e5b2dec15f45e0140 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/linalg.py @@ -0,0 +1,2839 @@ +""" +Implementation of linear algebra operations. +""" + + +import contextlib +import warnings + +from llvmlite import ir + +import numpy as np +import operator + +from numba.core.imputils import (lower_builtin, impl_ret_borrowed, + impl_ret_new_ref, impl_ret_untracked) +from numba.core.typing import signature +from numba.core.extending import intrinsic, overload, register_jitable +from numba.core import types, cgutils, config +from numba.core.errors import TypingError, NumbaTypeError, \ + NumbaPerformanceWarning +from .arrayobj import make_array, _empty_nd_impl, array_copy +from numba.np import numpy_support as np_support + +ll_char = ir.IntType(8) +ll_char_p = ll_char.as_pointer() +ll_void_p = ll_char_p +ll_intc = ir.IntType(32) +ll_intc_p = ll_intc.as_pointer() +intp_t = cgutils.intp_t +ll_intp_p = intp_t.as_pointer() + + +# fortran int type, this needs to match the F_INT C declaration in +# _lapack.c and is present to accommodate potential future 64bit int +# based LAPACK use. +F_INT_nptype = np.int32 +F_INT_nbtype = types.int32 + +# BLAS kinds as letters +_blas_kinds = { + types.float32: 's', + types.float64: 'd', + types.complex64: 'c', + types.complex128: 'z', +} + + +def get_blas_kind(dtype, func_name=""): + kind = _blas_kinds.get(dtype) + if kind is None: + raise NumbaTypeError("unsupported dtype for %s()" % (func_name,)) + return kind + + +def ensure_blas(): + try: + import scipy.linalg.cython_blas + except ImportError: + raise ImportError("scipy 0.16+ is required for linear algebra") + + +def ensure_lapack(): + try: + import scipy.linalg.cython_lapack + except ImportError: + raise ImportError("scipy 0.16+ is required for linear algebra") + + +def make_constant_slot(context, builder, ty, val): + const = context.get_constant_generic(builder, ty, val) + return cgutils.alloca_once_value(builder, const) + + +class _BLAS: + """ + Functions to return type signatures for wrapped + BLAS functions. + """ + + def __init__(self): + ensure_blas() + + @classmethod + def numba_xxnrm2(cls, dtype): + rtype = getattr(dtype, "underlying_float", dtype) + sig = types.intc(types.char, # kind + types.intp, # n + types.CPointer(dtype), # x + types.intp, # incx + types.CPointer(rtype)) # returned + + return types.ExternalFunction("numba_xxnrm2", sig) + + @classmethod + def numba_xxgemm(cls, dtype): + sig = types.intc( + types.char, # kind + types.char, # transa + types.char, # transb + types.intp, # m + types.intp, # n + types.intp, # k + types.CPointer(dtype), # alpha + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # b + types.intp, # ldb + types.CPointer(dtype), # beta + types.CPointer(dtype), # c + types.intp # ldc + ) + return types.ExternalFunction("numba_xxgemm", sig) + + +class _LAPACK: + """ + Functions to return type signatures for wrapped + LAPACK functions. + """ + + def __init__(self): + ensure_lapack() + + @classmethod + def numba_xxgetrf(cls, dtype): + sig = types.intc(types.char, # kind + types.intp, # m + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(F_INT_nbtype) # ipiv + ) + return types.ExternalFunction("numba_xxgetrf", sig) + + @classmethod + def numba_ez_xxgetri(cls, dtype): + sig = types.intc(types.char, # kind + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(F_INT_nbtype) # ipiv + ) + return types.ExternalFunction("numba_ez_xxgetri", sig) + + @classmethod + def numba_ez_rgeev(cls, dtype): + sig = types.intc(types.char, # kind + types.char, # jobvl + types.char, # jobvr + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # wr + types.CPointer(dtype), # wi + types.CPointer(dtype), # vl + types.intp, # ldvl + types.CPointer(dtype), # vr + types.intp # ldvr + ) + return types.ExternalFunction("numba_ez_rgeev", sig) + + @classmethod + def numba_ez_cgeev(cls, dtype): + sig = types.intc(types.char, # kind + types.char, # jobvl + types.char, # jobvr + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # w + types.CPointer(dtype), # vl + types.intp, # ldvl + types.CPointer(dtype), # vr + types.intp # ldvr + ) + return types.ExternalFunction("numba_ez_cgeev", sig) + + @classmethod + def numba_ez_xxxevd(cls, dtype): + wtype = getattr(dtype, "underlying_float", dtype) + sig = types.intc(types.char, # kind + types.char, # jobz + types.char, # uplo + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(wtype), # w + ) + return types.ExternalFunction("numba_ez_xxxevd", sig) + + @classmethod + def numba_xxpotrf(cls, dtype): + sig = types.intc(types.char, # kind + types.char, # uplo + types.intp, # n + types.CPointer(dtype), # a + types.intp # lda + ) + return types.ExternalFunction("numba_xxpotrf", sig) + + @classmethod + def numba_ez_gesdd(cls, dtype): + stype = getattr(dtype, "underlying_float", dtype) + sig = types.intc( + types.char, # kind + types.char, # jobz + types.intp, # m + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(stype), # s + types.CPointer(dtype), # u + types.intp, # ldu + types.CPointer(dtype), # vt + types.intp # ldvt + ) + + return types.ExternalFunction("numba_ez_gesdd", sig) + + @classmethod + def numba_ez_geqrf(cls, dtype): + sig = types.intc( + types.char, # kind + types.intp, # m + types.intp, # n + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # tau + ) + return types.ExternalFunction("numba_ez_geqrf", sig) + + @classmethod + def numba_ez_xxgqr(cls, dtype): + sig = types.intc( + types.char, # kind + types.intp, # m + types.intp, # n + types.intp, # k + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # tau + ) + return types.ExternalFunction("numba_ez_xxgqr", sig) + + @classmethod + def numba_ez_gelsd(cls, dtype): + rtype = getattr(dtype, "underlying_float", dtype) + sig = types.intc( + types.char, # kind + types.intp, # m + types.intp, # n + types.intp, # nrhs + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(dtype), # b + types.intp, # ldb + types.CPointer(rtype), # S + types.float64, # rcond + types.CPointer(types.intc) # rank + ) + return types.ExternalFunction("numba_ez_gelsd", sig) + + @classmethod + def numba_xgesv(cls, dtype): + sig = types.intc( + types.char, # kind + types.intp, # n + types.intp, # nhrs + types.CPointer(dtype), # a + types.intp, # lda + types.CPointer(F_INT_nbtype), # ipiv + types.CPointer(dtype), # b + types.intp # ldb + ) + return types.ExternalFunction("numba_xgesv", sig) + + +@contextlib.contextmanager +def make_contiguous(context, builder, sig, args): + """ + Ensure that all array arguments are contiguous, if necessary by + copying them. + A new (sig, args) tuple is yielded. + """ + newtys = [] + newargs = [] + copies = [] + for ty, val in zip(sig.args, args): + if not isinstance(ty, types.Array) or ty.layout in 'CF': + newty, newval = ty, val + else: + newty = ty.copy(layout='C') + copysig = signature(newty, ty) + newval = array_copy(context, builder, copysig, (val,)) + copies.append((newty, newval)) + newtys.append(newty) + newargs.append(newval) + yield signature(sig.return_type, *newtys), tuple(newargs) + for ty, val in copies: + context.nrt.decref(builder, ty, val) + + +def check_c_int(context, builder, n): + """ + Check whether *n* fits in a C `int`. + """ + _maxint = 2**31 - 1 + + def impl(n): + if n > _maxint: + raise OverflowError("array size too large to fit in C int") + + context.compile_internal(builder, impl, + signature(types.none, types.intp), (n,)) + + +def check_blas_return(context, builder, res): + """ + Check the integer error return from one of the BLAS wrappers in + _helperlib.c. + """ + with builder.if_then(cgutils.is_not_null(builder, res), likely=False): + # Those errors shouldn't happen, it's easier to just abort the process + pyapi = context.get_python_api(builder) + pyapi.gil_ensure() + pyapi.fatal_error("BLAS wrapper returned with an error") + + +def check_lapack_return(context, builder, res): + """ + Check the integer error return from one of the LAPACK wrappers in + _helperlib.c. + """ + with builder.if_then(cgutils.is_not_null(builder, res), likely=False): + # Those errors shouldn't happen, it's easier to just abort the process + pyapi = context.get_python_api(builder) + pyapi.gil_ensure() + pyapi.fatal_error("LAPACK wrapper returned with an error") + + +def call_xxdot(context, builder, conjugate, dtype, + n, a_data, b_data, out_data): + """ + Call the BLAS vector * vector product function for the given arguments. + """ + fnty = ir.FunctionType(ir.IntType(32), + [ll_char, ll_char, intp_t, # kind, conjugate, n + ll_void_p, ll_void_p, ll_void_p, # a, b, out + ]) + fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxdot") + + kind = get_blas_kind(dtype) + kind_val = ir.Constant(ll_char, ord(kind)) + conjugate = ir.Constant(ll_char, int(conjugate)) + + res = builder.call(fn, (kind_val, conjugate, n, + builder.bitcast(a_data, ll_void_p), + builder.bitcast(b_data, ll_void_p), + builder.bitcast(out_data, ll_void_p))) + check_blas_return(context, builder, res) + + +def call_xxgemv(context, builder, do_trans, + m_type, m_shapes, m_data, v_data, out_data): + """ + Call the BLAS matrix * vector product function for the given arguments. + """ + fnty = ir.FunctionType(ir.IntType(32), + [ll_char, ll_char, # kind, trans + intp_t, intp_t, # m, n + ll_void_p, ll_void_p, intp_t, # alpha, a, lda + ll_void_p, ll_void_p, ll_void_p, # x, beta, y + ]) + fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemv") + + dtype = m_type.dtype + alpha = make_constant_slot(context, builder, dtype, 1.0) + beta = make_constant_slot(context, builder, dtype, 0.0) + + if m_type.layout == 'F': + m, n = m_shapes + lda = m_shapes[0] + else: + n, m = m_shapes + lda = m_shapes[1] + + kind = get_blas_kind(dtype) + kind_val = ir.Constant(ll_char, ord(kind)) + trans = ir.Constant(ll_char, ord('t') if do_trans else ord('n')) + + res = builder.call(fn, (kind_val, trans, m, n, + builder.bitcast(alpha, ll_void_p), + builder.bitcast(m_data, ll_void_p), lda, + builder.bitcast(v_data, ll_void_p), + builder.bitcast(beta, ll_void_p), + builder.bitcast(out_data, ll_void_p))) + check_blas_return(context, builder, res) + + +def call_xxgemm(context, builder, + x_type, x_shapes, x_data, + y_type, y_shapes, y_data, + out_type, out_shapes, out_data): + """ + Call the BLAS matrix * matrix product function for the given arguments. + """ + fnty = ir.FunctionType(ir.IntType(32), + [ll_char, # kind + ll_char, ll_char, # transa, transb + intp_t, intp_t, intp_t, # m, n, k + ll_void_p, ll_void_p, intp_t, # alpha, a, lda + ll_void_p, intp_t, ll_void_p, # b, ldb, beta + ll_void_p, intp_t, # c, ldc + ]) + fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemm") + + m, k = x_shapes + _k, n = y_shapes + dtype = x_type.dtype + alpha = make_constant_slot(context, builder, dtype, 1.0) + beta = make_constant_slot(context, builder, dtype, 0.0) + + trans = ir.Constant(ll_char, ord('t')) + notrans = ir.Constant(ll_char, ord('n')) + + def get_array_param(ty, shapes, data): + return ( + # Transpose if layout different from result's + notrans if ty.layout == out_type.layout else trans, + # Size of the inner dimension in physical array order + shapes[1] if ty.layout == 'C' else shapes[0], + # The data pointer, unit-less + builder.bitcast(data, ll_void_p), + ) + + transa, lda, data_a = get_array_param(y_type, y_shapes, y_data) + transb, ldb, data_b = get_array_param(x_type, x_shapes, x_data) + _, ldc, data_c = get_array_param(out_type, out_shapes, out_data) + + kind = get_blas_kind(dtype) + kind_val = ir.Constant(ll_char, ord(kind)) + + res = builder.call(fn, (kind_val, transa, transb, n, m, k, + builder.bitcast(alpha, ll_void_p), data_a, lda, + data_b, ldb, builder.bitcast(beta, ll_void_p), + data_c, ldc)) + check_blas_return(context, builder, res) + + +def dot_2_mm(context, builder, sig, args): + """ + np.dot(matrix, matrix) + """ + def dot_impl(a, b): + m, k = a.shape + _k, n = b.shape + if k == 0: + return np.zeros((m, n), a.dtype) + out = np.empty((m, n), a.dtype) + return np.dot(a, b, out) + + res = context.compile_internal(builder, dot_impl, sig, args) + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +def dot_2_vm(context, builder, sig, args): + """ + np.dot(vector, matrix) + """ + def dot_impl(a, b): + m, = a.shape + _m, n = b.shape + if m == 0: + return np.zeros((n, ), a.dtype) + out = np.empty((n, ), a.dtype) + return np.dot(a, b, out) + + res = context.compile_internal(builder, dot_impl, sig, args) + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +def dot_2_mv(context, builder, sig, args): + """ + np.dot(matrix, vector) + """ + def dot_impl(a, b): + m, n = a.shape + _n, = b.shape + if n == 0: + return np.zeros((m, ), a.dtype) + out = np.empty((m, ), a.dtype) + return np.dot(a, b, out) + + res = context.compile_internal(builder, dot_impl, sig, args) + return impl_ret_new_ref(context, builder, sig.return_type, res) + + +def dot_2_vv(context, builder, sig, args, conjugate=False): + """ + np.dot(vector, vector) + np.vdot(vector, vector) + """ + aty, bty = sig.args + dtype = sig.return_type + a = make_array(aty)(context, builder, args[0]) + b = make_array(bty)(context, builder, args[1]) + n, = cgutils.unpack_tuple(builder, a.shape) + + def check_args(a, b): + m, = a.shape + n, = b.shape + if m != n: + raise ValueError("incompatible array sizes for np.dot(a, b) " + "(vector * vector)") + + context.compile_internal(builder, check_args, + signature(types.none, *sig.args), args) + check_c_int(context, builder, n) + + out = cgutils.alloca_once(builder, context.get_value_type(dtype)) + call_xxdot(context, builder, conjugate, dtype, n, a.data, b.data, out) + return builder.load(out) + + +@overload(np.dot) +def dot_2(a, b): + """ + np.dot(a, b) + """ + return dot_2_impl('np.dot()', a, b) + + +@overload(operator.matmul) +def matmul_2(a, b): + """ + a @ b + """ + return dot_2_impl("'@'", a, b) + + +def dot_2_impl(name, a, b): + if isinstance(a, types.Array) and isinstance(b, types.Array): + @intrinsic + def _impl(typingcontext, a, b): + ndims = (a.ndim, b.ndim) + + def _dot2_codegen(context, builder, sig, args): + ensure_blas() + + with make_contiguous(context, builder, sig, args) as (sig, args): + if ndims == (2, 2): + return dot_2_mm(context, builder, sig, args) + elif ndims == (2, 1): + return dot_2_mv(context, builder, sig, args) + elif ndims == (1, 2): + return dot_2_vm(context, builder, sig, args) + elif ndims == (1, 1): + return dot_2_vv(context, builder, sig, args) + else: + raise AssertionError('unreachable') + + if a.dtype != b.dtype: + raise TypingError( + "%s arguments must all have the same dtype" % name) + + if ndims == (2, 2): + return_type = types.Array(a.dtype, 2, 'C') + elif ndims == (2, 1) or ndims == (1, 2): + return_type = types.Array(a.dtype, 1, 'C') + elif ndims == (1, 1): + return_type = a.dtype + else: + raise TypingError(("%s: inputs must have compatible " + "dimensions") % name) + return signature(return_type, a, b), _dot2_codegen + + if a.layout not in 'CF' or b.layout not in 'CF': + warnings.warn( + "%s is faster on contiguous arrays, called on %s" % ( + name, (a, b),), NumbaPerformanceWarning) + + return lambda a, b: _impl(a, b) + + +@overload(np.vdot) +def vdot(left, right): + """ + np.vdot(a, b) + """ + if isinstance(left, types.Array) and isinstance(right, types.Array): + @intrinsic + def _impl(typingcontext, left, right): + def codegen(context, builder, sig, args): + ensure_blas() + + with make_contiguous(context, builder, sig, args) as\ + (sig, args): + return dot_2_vv(context, builder, sig, args, conjugate=True) + + if left.ndim != 1 or right.ndim != 1: + raise TypingError("np.vdot() only supported on 1-D arrays") + + if left.dtype != right.dtype: + raise TypingError( + "np.vdot() arguments must all have the same dtype") + return signature(left.dtype, left, right), codegen + + if left.layout not in 'CF' or right.layout not in 'CF': + warnings.warn( + "np.vdot() is faster on contiguous arrays, called on %s" + % ((left, right),), NumbaPerformanceWarning) + + return lambda left, right: _impl(left, right) + + +def dot_3_vm_check_args(a, b, out): + m, = a.shape + _m, n = b.shape + if m != _m: + raise ValueError("incompatible array sizes for " + "np.dot(a, b) (vector * matrix)") + if out.shape != (n,): + raise ValueError("incompatible output array size for " + "np.dot(a, b, out) (vector * matrix)") + + +def dot_3_mv_check_args(a, b, out): + m, _n = a.shape + n, = b.shape + if n != _n: + raise ValueError("incompatible array sizes for np.dot(a, b) " + "(matrix * vector)") + if out.shape != (m,): + raise ValueError("incompatible output array size for " + "np.dot(a, b, out) (matrix * vector)") + + +def dot_3_vm(context, builder, sig, args): + """ + np.dot(vector, matrix, out) + np.dot(matrix, vector, out) + """ + xty, yty, outty = sig.args + assert outty == sig.return_type + dtype = xty.dtype + + x = make_array(xty)(context, builder, args[0]) + y = make_array(yty)(context, builder, args[1]) + out = make_array(outty)(context, builder, args[2]) + x_shapes = cgutils.unpack_tuple(builder, x.shape) + y_shapes = cgutils.unpack_tuple(builder, y.shape) + out_shapes = cgutils.unpack_tuple(builder, out.shape) + if xty.ndim < yty.ndim: + # Vector * matrix + # Asked for x * y, we will compute y.T * x + mty = yty + m_shapes = y_shapes + v_shape = x_shapes[0] + lda = m_shapes[1] + do_trans = yty.layout == 'F' + m_data, v_data = y.data, x.data + check_args = dot_3_vm_check_args + else: + # Matrix * vector + # We will compute x * y + mty = xty + m_shapes = x_shapes + v_shape = y_shapes[0] + lda = m_shapes[0] + do_trans = xty.layout == 'C' + m_data, v_data = x.data, y.data + check_args = dot_3_mv_check_args + + context.compile_internal(builder, check_args, + signature(types.none, *sig.args), args) + for val in m_shapes: + check_c_int(context, builder, val) + + zero = context.get_constant(types.intp, 0) + both_empty = builder.icmp_signed('==', v_shape, zero) + matrix_empty = builder.icmp_signed('==', lda, zero) + is_empty = builder.or_(both_empty, matrix_empty) + with builder.if_else(is_empty, likely=False) as (empty, nonempty): + with empty: + cgutils.memset(builder, out.data, + builder.mul(out.itemsize, out.nitems), 0) + with nonempty: + call_xxgemv(context, builder, do_trans, mty, m_shapes, m_data, + v_data, out.data) + + return impl_ret_borrowed(context, builder, sig.return_type, + out._getvalue()) + + +def dot_3_mm(context, builder, sig, args): + """ + np.dot(matrix, matrix, out) + """ + xty, yty, outty = sig.args + assert outty == sig.return_type + dtype = xty.dtype + + x = make_array(xty)(context, builder, args[0]) + y = make_array(yty)(context, builder, args[1]) + out = make_array(outty)(context, builder, args[2]) + x_shapes = cgutils.unpack_tuple(builder, x.shape) + y_shapes = cgutils.unpack_tuple(builder, y.shape) + out_shapes = cgutils.unpack_tuple(builder, out.shape) + m, k = x_shapes + _k, n = y_shapes + + # The only case Numpy supports + assert outty.layout == 'C' + + def check_args(a, b, out): + m, k = a.shape + _k, n = b.shape + if k != _k: + raise ValueError("incompatible array sizes for np.dot(a, b) " + "(matrix * matrix)") + if out.shape != (m, n): + raise ValueError("incompatible output array size for " + "np.dot(a, b, out) (matrix * matrix)") + + context.compile_internal(builder, check_args, + signature(types.none, *sig.args), args) + + check_c_int(context, builder, m) + check_c_int(context, builder, k) + check_c_int(context, builder, n) + + x_data = x.data + y_data = y.data + out_data = out.data + + # If eliminated dimension is zero, set all entries to zero and return + zero = context.get_constant(types.intp, 0) + both_empty = builder.icmp_signed('==', k, zero) + x_empty = builder.icmp_signed('==', m, zero) + y_empty = builder.icmp_signed('==', n, zero) + is_empty = builder.or_(both_empty, builder.or_(x_empty, y_empty)) + with builder.if_else(is_empty, likely=False) as (empty, nonempty): + with empty: + cgutils.memset(builder, out.data, + builder.mul(out.itemsize, out.nitems), 0) + with nonempty: + # Check if any of the operands is really a 1-d vector represented + # as a (1, k) or (k, 1) 2-d array. In those cases, it is pessimal + # to call the generic matrix * matrix product BLAS function. + one = context.get_constant(types.intp, 1) + is_left_vec = builder.icmp_signed('==', m, one) + is_right_vec = builder.icmp_signed('==', n, one) + + with builder.if_else(is_right_vec) as (r_vec, r_mat): + with r_vec: + with builder.if_else(is_left_vec) as (v_v, m_v): + with v_v: + # V * V + call_xxdot(context, builder, False, dtype, + k, x_data, y_data, out_data) + with m_v: + # M * V + do_trans = xty.layout == outty.layout + call_xxgemv(context, builder, do_trans, + xty, x_shapes, x_data, y_data, out_data) + with r_mat: + with builder.if_else(is_left_vec) as (v_m, m_m): + with v_m: + # V * M + do_trans = yty.layout != outty.layout + call_xxgemv(context, builder, do_trans, + yty, y_shapes, y_data, x_data, out_data) + with m_m: + # M * M + call_xxgemm(context, builder, + xty, x_shapes, x_data, + yty, y_shapes, y_data, + outty, out_shapes, out_data) + + return impl_ret_borrowed(context, builder, sig.return_type, + out._getvalue()) + + +@overload(np.dot) +def dot_3(a, b, out): + """ + np.dot(a, b, out) + """ + if (isinstance(a, types.Array) and isinstance(b, types.Array) and + isinstance(out, types.Array)): + @intrinsic + def _impl(typingcontext, a, b, out): + def codegen(context, builder, sig, args): + ensure_blas() + + with make_contiguous(context, builder, sig, args) as (sig, + args): + ndims = set(x.ndim for x in sig.args[:2]) + if ndims == {2}: + return dot_3_mm(context, builder, sig, args) + elif ndims == {1, 2}: + return dot_3_vm(context, builder, sig, args) + else: + raise AssertionError('unreachable') + if a.dtype != b.dtype or a.dtype != out.dtype: + raise TypingError( + "np.dot() arguments must all have the same dtype") + + return signature(out, a, b, out), codegen + + if a.layout not in 'CF' or b.layout not in 'CF' or out.layout\ + not in 'CF': + warnings.warn( + "np.vdot() is faster on contiguous arrays, called on %s" + % ((a, b),), NumbaPerformanceWarning) + + return lambda a, b, out: _impl(a, b, out) + + +fatal_error_func = types.ExternalFunction("numba_fatal_error", types.intc()) + + +@register_jitable +def _check_finite_matrix(a): + for v in np.nditer(a): + if not np.isfinite(v.item()): + raise np.linalg.LinAlgError( + "Array must not contain infs or NaNs.") + + +def _check_linalg_matrix(a, func_name, la_prefix=True): + # la_prefix is present as some functions, e.g. np.trace() + # are documented under "linear algebra" but aren't in the + # module + prefix = "np.linalg" if la_prefix else "np" + interp = (prefix, func_name) + # Unpack optional type + if isinstance(a, types.Optional): + a = a.type + if not isinstance(a, types.Array): + msg = "%s.%s() only supported for array types" % interp + raise TypingError(msg, highlighting=False) + if not a.ndim == 2: + msg = "%s.%s() only supported on 2-D arrays." % interp + raise TypingError(msg, highlighting=False) + if not isinstance(a.dtype, (types.Float, types.Complex)): + msg = "%s.%s() only supported on "\ + "float and complex arrays." % interp + raise TypingError(msg, highlighting=False) + + +def _check_homogeneous_types(func_name, *types): + t0 = types[0].dtype + for t in types[1:]: + if t.dtype != t0: + msg = "np.linalg.%s() only supports inputs that have homogeneous dtypes." % func_name + raise TypingError(msg, highlighting=False) + + +def _copy_to_fortran_order(): + pass + + +@overload(_copy_to_fortran_order) +def ol_copy_to_fortran_order(a): + # This function copies the array 'a' into a new array with fortran order. + # This exists because the copy routines don't take order flags yet. + F_layout = a.layout == 'F' + A_layout = a.layout == 'A' + def impl(a): + if F_layout: + # it's F ordered at compile time, just copy + acpy = np.copy(a) + elif A_layout: + # decide based on runtime value + flag_f = a.flags.f_contiguous + if flag_f: + # it's already F ordered, so copy but in a round about way to + # ensure that the copy is also F ordered + acpy = np.copy(a.T).T + else: + # it's something else ordered, so let asfortranarray deal with + # copying and making it fortran ordered + acpy = np.asfortranarray(a) + else: + # it's C ordered at compile time, asfortranarray it. + acpy = np.asfortranarray(a) + return acpy + return impl + + +@register_jitable +def _inv_err_handler(r): + if r != 0: + if r < 0: + fatal_error_func() + assert 0 # unreachable + if r > 0: + raise np.linalg.LinAlgError( + "Matrix is singular to machine precision.") + +@register_jitable +def _dummy_liveness_func(a): + """pass a list of variables to be preserved through dead code elimination""" + return a[0] + + +@overload(np.linalg.inv) +def inv_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "inv") + + numba_xxgetrf = _LAPACK().numba_xxgetrf(a.dtype) + + numba_xxgetri = _LAPACK().numba_ez_xxgetri(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "inv")) + + def inv_impl(a): + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + if n == 0: + return acpy + + ipiv = np.empty(n, dtype=F_INT_nptype) + + r = numba_xxgetrf(kind, n, n, acpy.ctypes, n, ipiv.ctypes) + _inv_err_handler(r) + + r = numba_xxgetri(kind, n, acpy.ctypes, n, ipiv.ctypes) + _inv_err_handler(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, ipiv.size]) + return acpy + + return inv_impl + + +@register_jitable +def _handle_err_maybe_convergence_problem(r): + if r != 0: + if r < 0: + fatal_error_func() + assert 0 # unreachable + if r > 0: + raise ValueError("Internal algorithm failed to converge.") + + +def _check_linalg_1_or_2d_matrix(a, func_name, la_prefix=True): + # la_prefix is present as some functions, e.g. np.trace() + # are documented under "linear algebra" but aren't in the + # module + prefix = "np.linalg" if la_prefix else "np" + interp = (prefix, func_name) + # checks that a matrix is 1 or 2D + if not isinstance(a, types.Array): + raise TypingError("%s.%s() only supported for array types " + % interp) + if not a.ndim <= 2: + raise TypingError("%s.%s() only supported on 1 and 2-D arrays " + % interp) + if not isinstance(a.dtype, (types.Float, types.Complex)): + raise TypingError("%s.%s() only supported on " + "float and complex arrays." % interp) + + +@overload(np.linalg.cholesky) +def cho_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "cholesky") + + numba_xxpotrf = _LAPACK().numba_xxpotrf(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "cholesky")) + UP = ord('U') + LO = ord('L') + + def cho_impl(a): + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + # The output is allocated in C order + out = a.copy() + + if n == 0: + return out + + # Pass UP since xxpotrf() operates in F order + # The semantics ensure this works fine + # (out is really its Hermitian in F order, but UP instructs + # xxpotrf to compute the Hermitian of the upper triangle + # => they cancel each other) + r = numba_xxpotrf(kind, UP, n, out.ctypes, n) + if r != 0: + if r < 0: + fatal_error_func() + assert 0 # unreachable + if r > 0: + raise np.linalg.LinAlgError( + "Matrix is not positive definite.") + # Zero out upper triangle, in F order + for col in range(n): + out[:col, col] = 0 + return out + + return cho_impl + +@overload(np.linalg.eig) +def eig_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "eig") + + numba_ez_rgeev = _LAPACK().numba_ez_rgeev(a.dtype) + numba_ez_cgeev = _LAPACK().numba_ez_cgeev(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "eig")) + + JOBVL = ord('N') + JOBVR = ord('V') + + def real_eig_impl(a): + """ + eig() implementation for real arrays. + """ + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ldvl = 1 + ldvr = n + wr = np.empty(n, dtype=a.dtype) + wi = np.empty(n, dtype=a.dtype) + vl = np.empty((n, ldvl), dtype=a.dtype) + vr = np.empty((n, ldvr), dtype=a.dtype) + + if n == 0: + return (wr, vr.T) + + r = numba_ez_rgeev(kind, + JOBVL, + JOBVR, + n, + acpy.ctypes, + n, + wr.ctypes, + wi.ctypes, + vl.ctypes, + ldvl, + vr.ctypes, + ldvr) + _handle_err_maybe_convergence_problem(r) + + # By design numba does not support dynamic return types, however, + # Numpy does. Numpy uses this ability in the case of returning + # eigenvalues/vectors of a real matrix. The return type of + # np.linalg.eig(), when operating on a matrix in real space + # depends on the values present in the matrix itself (recalling + # that eigenvalues are the roots of the characteristic polynomial + # of the system matrix, which will by construction depend on the + # values present in the system matrix). As numba cannot handle + # the case of a runtime decision based domain change relative to + # the input type, if it is required numba raises as below. + if np.any(wi): + raise ValueError( + "eig() argument must not cause a domain change.") + + # put these in to help with liveness analysis, + # `.ctypes` doesn't keep the vars alive + _dummy_liveness_func([acpy.size, vl.size, vr.size, wr.size, wi.size]) + return (wr, vr.T) + + def cmplx_eig_impl(a): + """ + eig() implementation for complex arrays. + """ + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ldvl = 1 + ldvr = n + w = np.empty(n, dtype=a.dtype) + vl = np.empty((n, ldvl), dtype=a.dtype) + vr = np.empty((n, ldvr), dtype=a.dtype) + + if n == 0: + return (w, vr.T) + + r = numba_ez_cgeev(kind, + JOBVL, + JOBVR, + n, + acpy.ctypes, + n, + w.ctypes, + vl.ctypes, + ldvl, + vr.ctypes, + ldvr) + _handle_err_maybe_convergence_problem(r) + + # put these in to help with liveness analysis, + # `.ctypes` doesn't keep the vars alive + _dummy_liveness_func([acpy.size, vl.size, vr.size, w.size]) + return (w, vr.T) + + if isinstance(a.dtype, types.scalars.Complex): + return cmplx_eig_impl + else: + return real_eig_impl + +@overload(np.linalg.eigvals) +def eigvals_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "eigvals") + + numba_ez_rgeev = _LAPACK().numba_ez_rgeev(a.dtype) + numba_ez_cgeev = _LAPACK().numba_ez_cgeev(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "eigvals")) + + JOBVL = ord('N') + JOBVR = ord('N') + + def real_eigvals_impl(a): + """ + eigvals() implementation for real arrays. + """ + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ldvl = 1 + ldvr = 1 + wr = np.empty(n, dtype=a.dtype) + + if n == 0: + return wr + + wi = np.empty(n, dtype=a.dtype) + + # not referenced but need setting for MKL null check + vl = np.empty((1), dtype=a.dtype) + vr = np.empty((1), dtype=a.dtype) + + r = numba_ez_rgeev(kind, + JOBVL, + JOBVR, + n, + acpy.ctypes, + n, + wr.ctypes, + wi.ctypes, + vl.ctypes, + ldvl, + vr.ctypes, + ldvr) + _handle_err_maybe_convergence_problem(r) + + # By design numba does not support dynamic return types, however, + # Numpy does. Numpy uses this ability in the case of returning + # eigenvalues/vectors of a real matrix. The return type of + # np.linalg.eigvals(), when operating on a matrix in real space + # depends on the values present in the matrix itself (recalling + # that eigenvalues are the roots of the characteristic polynomial + # of the system matrix, which will by construction depend on the + # values present in the system matrix). As numba cannot handle + # the case of a runtime decision based domain change relative to + # the input type, if it is required numba raises as below. + if np.any(wi): + raise ValueError( + "eigvals() argument must not cause a domain change.") + + # put these in to help with liveness analysis, + # `.ctypes` doesn't keep the vars alive + _dummy_liveness_func([acpy.size, vl.size, vr.size, wr.size, wi.size]) + return wr + + def cmplx_eigvals_impl(a): + """ + eigvals() implementation for complex arrays. + """ + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ldvl = 1 + ldvr = 1 + w = np.empty(n, dtype=a.dtype) + + if n == 0: + return w + + vl = np.empty((1), dtype=a.dtype) + vr = np.empty((1), dtype=a.dtype) + + r = numba_ez_cgeev(kind, + JOBVL, + JOBVR, + n, + acpy.ctypes, + n, + w.ctypes, + vl.ctypes, + ldvl, + vr.ctypes, + ldvr) + _handle_err_maybe_convergence_problem(r) + + # put these in to help with liveness analysis, + # `.ctypes` doesn't keep the vars alive + _dummy_liveness_func([acpy.size, vl.size, vr.size, w.size]) + return w + + if isinstance(a.dtype, types.scalars.Complex): + return cmplx_eigvals_impl + else: + return real_eigvals_impl + +@overload(np.linalg.eigh) +def eigh_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "eigh") + + # convert typing floats to numpy floats for use in the impl + w_type = getattr(a.dtype, "underlying_float", a.dtype) + w_dtype = np_support.as_dtype(w_type) + + numba_ez_xxxevd = _LAPACK().numba_ez_xxxevd(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "eigh")) + + JOBZ = ord('V') + UPLO = ord('L') + + def eigh_impl(a): + n = a.shape[-1] + + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + w = np.empty(n, dtype=w_dtype) + + if n == 0: + return (w, acpy) + + r = numba_ez_xxxevd(kind, # kind + JOBZ, # jobz + UPLO, # uplo + n, # n + acpy.ctypes, # a + n, # lda + w.ctypes # w + ) + _handle_err_maybe_convergence_problem(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, w.size]) + return (w, acpy) + + return eigh_impl + +@overload(np.linalg.eigvalsh) +def eigvalsh_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "eigvalsh") + + # convert typing floats to numpy floats for use in the impl + w_type = getattr(a.dtype, "underlying_float", a.dtype) + w_dtype = np_support.as_dtype(w_type) + + numba_ez_xxxevd = _LAPACK().numba_ez_xxxevd(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "eigvalsh")) + + JOBZ = ord('N') + UPLO = ord('L') + + def eigvalsh_impl(a): + n = a.shape[-1] + + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + w = np.empty(n, dtype=w_dtype) + + if n == 0: + return w + + r = numba_ez_xxxevd(kind, # kind + JOBZ, # jobz + UPLO, # uplo + n, # n + acpy.ctypes, # a + n, # lda + w.ctypes # w + ) + _handle_err_maybe_convergence_problem(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, w.size]) + return w + + return eigvalsh_impl + +@overload(np.linalg.svd) +def svd_impl(a, full_matrices=1): + ensure_lapack() + + _check_linalg_matrix(a, "svd") + + # convert typing floats to numpy floats for use in the impl + s_type = getattr(a.dtype, "underlying_float", a.dtype) + s_dtype = np_support.as_dtype(s_type) + + numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "svd")) + + JOBZ_A = ord('A') + JOBZ_S = ord('S') + + def svd_impl(a, full_matrices=1): + n = a.shape[-1] + m = a.shape[-2] + + if n == 0 or m == 0: + raise np.linalg.LinAlgError("Arrays cannot be empty") + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ldu = m + minmn = min(m, n) + + if full_matrices: + JOBZ = JOBZ_A + ucol = m + ldvt = n + else: + JOBZ = JOBZ_S + ucol = minmn + ldvt = minmn + + u = np.empty((ucol, ldu), dtype=a.dtype) + s = np.empty(minmn, dtype=s_dtype) + vt = np.empty((n, ldvt), dtype=a.dtype) + + r = numba_ez_gesdd( + kind, # kind + JOBZ, # jobz + m, # m + n, # n + acpy.ctypes, # a + m, # lda + s.ctypes, # s + u.ctypes, # u + ldu, # ldu + vt.ctypes, # vt + ldvt # ldvt + ) + _handle_err_maybe_convergence_problem(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, vt.size, u.size, s.size]) + return (u.T, s, vt.T) + + return svd_impl + + +@overload(np.linalg.qr) +def qr_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "qr") + + # Need two functions, the first computes R, storing it in the upper + # triangle of A with the below diagonal part of A containing elementary + # reflectors needed to construct Q. The second turns the below diagonal + # entries of A into Q, storing Q in A (creates orthonormal columns from + # the elementary reflectors). + + numba_ez_geqrf = _LAPACK().numba_ez_geqrf(a.dtype) + numba_ez_xxgqr = _LAPACK().numba_ez_xxgqr(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "qr")) + + def qr_impl(a): + n = a.shape[-1] + m = a.shape[-2] + + if n == 0 or m == 0: + raise np.linalg.LinAlgError("Arrays cannot be empty") + + _check_finite_matrix(a) + + # copy A as it will be destroyed + q = _copy_to_fortran_order(a) + + lda = m + + minmn = min(m, n) + tau = np.empty((minmn), dtype=a.dtype) + + ret = numba_ez_geqrf( + kind, # kind + m, # m + n, # n + q.ctypes, # a + m, # lda + tau.ctypes # tau + ) + if ret < 0: + fatal_error_func() + assert 0 # unreachable + + # pull out R, this is transposed because of Fortran + r = np.zeros((n, minmn), dtype=a.dtype).T + + # the triangle in R + for i in range(minmn): + for j in range(i + 1): + r[j, i] = q[j, i] + + # and the possible square in R + for i in range(minmn, n): + for j in range(minmn): + r[j, i] = q[j, i] + + ret = numba_ez_xxgqr( + kind, # kind + m, # m + minmn, # n + minmn, # k + q.ctypes, # a + m, # lda + tau.ctypes # tau + ) + _handle_err_maybe_convergence_problem(ret) + + # help liveness analysis + _dummy_liveness_func([tau.size, q.size]) + return (q[:, :minmn], r) + + return qr_impl + + +# helpers and jitted specialisations required for np.linalg.lstsq +# and np.linalg.solve. These functions have "system" in their name +# as a differentiator. + +def _system_copy_in_b(bcpy, b, nrhs): + """ + Correctly copy 'b' into the 'bcpy' scratch space. + """ + raise NotImplementedError + + +@overload(_system_copy_in_b) +def _system_copy_in_b_impl(bcpy, b, nrhs): + if b.ndim == 1: + def oneD_impl(bcpy, b, nrhs): + bcpy[:b.shape[-1], 0] = b + return oneD_impl + else: + def twoD_impl(bcpy, b, nrhs): + bcpy[:b.shape[-2], :nrhs] = b + return twoD_impl + + +def _system_compute_nrhs(b): + """ + Compute the number of right hand sides in the system of equations + """ + raise NotImplementedError + + +@overload(_system_compute_nrhs) +def _system_compute_nrhs_impl(b): + if b.ndim == 1: + def oneD_impl(b): + return 1 + return oneD_impl + else: + def twoD_impl(b): + return b.shape[-1] + return twoD_impl + + +def _system_check_dimensionally_valid(a, b): + """ + Check that AX=B style system input is dimensionally valid. + """ + raise NotImplementedError + + +@overload(_system_check_dimensionally_valid) +def _system_check_dimensionally_valid_impl(a, b): + ndim = b.ndim + if ndim == 1: + def oneD_impl(a, b): + am = a.shape[-2] + bm = b.shape[-1] + if am != bm: + raise np.linalg.LinAlgError( + "Incompatible array sizes, system is not dimensionally valid.") + return oneD_impl + else: + def twoD_impl(a, b): + am = a.shape[-2] + bm = b.shape[-2] + if am != bm: + raise np.linalg.LinAlgError( + "Incompatible array sizes, system is not dimensionally valid.") + return twoD_impl + + +def _system_check_non_empty(a, b): + """ + Check that AX=B style system input is not empty. + """ + raise NotImplementedError + + +@overload(_system_check_non_empty) +def _system_check_non_empty_impl(a, b): + ndim = b.ndim + if ndim == 1: + def oneD_impl(a, b): + am = a.shape[-2] + an = a.shape[-1] + bm = b.shape[-1] + if am == 0 or bm == 0 or an == 0: + raise np.linalg.LinAlgError('Arrays cannot be empty') + return oneD_impl + else: + def twoD_impl(a, b): + am = a.shape[-2] + an = a.shape[-1] + bm = b.shape[-2] + bn = b.shape[-1] + if am == 0 or bm == 0 or an == 0 or bn == 0: + raise np.linalg.LinAlgError('Arrays cannot be empty') + return twoD_impl + + +def _lstsq_residual(b, n, nrhs): + """ + Compute the residual from the 'b' scratch space. + """ + raise NotImplementedError + + +@overload(_lstsq_residual) +def _lstsq_residual_impl(b, n, nrhs): + ndim = b.ndim + dtype = b.dtype + real_dtype = np_support.as_dtype(getattr(dtype, "underlying_float", dtype)) + + if ndim == 1: + if isinstance(dtype, (types.Complex)): + def cmplx_impl(b, n, nrhs): + res = np.empty((1,), dtype=real_dtype) + res[0] = np.sum(np.abs(b[n:, 0])**2) + return res + return cmplx_impl + else: + def real_impl(b, n, nrhs): + res = np.empty((1,), dtype=real_dtype) + res[0] = np.sum(b[n:, 0]**2) + return res + return real_impl + else: + assert ndim == 2 + if isinstance(dtype, (types.Complex)): + def cmplx_impl(b, n, nrhs): + res = np.empty((nrhs), dtype=real_dtype) + for k in range(nrhs): + res[k] = np.sum(np.abs(b[n:, k])**2) + return res + return cmplx_impl + else: + def real_impl(b, n, nrhs): + res = np.empty((nrhs), dtype=real_dtype) + for k in range(nrhs): + res[k] = np.sum(b[n:, k]**2) + return res + return real_impl + + +def _lstsq_solution(b, bcpy, n): + """ + Extract 'x' (the lstsq solution) from the 'bcpy' scratch space. + Note 'b' is only used to check the system input dimension... + """ + raise NotImplementedError + + +@overload(_lstsq_solution) +def _lstsq_solution_impl(b, bcpy, n): + if b.ndim == 1: + def oneD_impl(b, bcpy, n): + return bcpy.T.ravel()[:n] + return oneD_impl + else: + def twoD_impl(b, bcpy, n): + return bcpy[:n, :].copy() + return twoD_impl + + +@overload(np.linalg.lstsq) +def lstsq_impl(a, b, rcond=-1.0): + ensure_lapack() + + _check_linalg_matrix(a, "lstsq") + + # B can be 1D or 2D. + _check_linalg_1_or_2d_matrix(b, "lstsq") + + _check_homogeneous_types("lstsq", a, b) + + np_dt = np_support.as_dtype(a.dtype) + nb_dt = a.dtype + + # convert typing floats to np floats for use in the impl + r_type = getattr(nb_dt, "underlying_float", nb_dt) + real_dtype = np_support.as_dtype(r_type) + + # lapack solver + numba_ez_gelsd = _LAPACK().numba_ez_gelsd(a.dtype) + + kind = ord(get_blas_kind(nb_dt, "lstsq")) + + # The following functions select specialisations based on + # information around 'b', a lot of this effort is required + # as 'b' can be either 1D or 2D, and then there are + # some optimisations available depending on real or complex + # space. + + def lstsq_impl(a, b, rcond=-1.0): + n = a.shape[-1] + m = a.shape[-2] + nrhs = _system_compute_nrhs(b) + + # check the systems have no inf or NaN + _check_finite_matrix(a) + _check_finite_matrix(b) + + # check the system is not empty + _system_check_non_empty(a, b) + + # check the systems are dimensionally valid + _system_check_dimensionally_valid(a, b) + + minmn = min(m, n) + maxmn = max(m, n) + + # a is destroyed on exit, copy it + acpy = _copy_to_fortran_order(a) + + # b is overwritten on exit with the solution, copy allocate + bcpy = np.empty((nrhs, maxmn), dtype=np_dt).T + # specialised copy in due to b being 1 or 2D + _system_copy_in_b(bcpy, b, nrhs) + + # Allocate returns + s = np.empty(minmn, dtype=real_dtype) + rank_ptr = np.empty(1, dtype=np.int32) + + r = numba_ez_gelsd( + kind, # kind + m, # m + n, # n + nrhs, # nrhs + acpy.ctypes, # a + m, # lda + bcpy.ctypes, # a + maxmn, # ldb + s.ctypes, # s + rcond, # rcond + rank_ptr.ctypes # rank + ) + _handle_err_maybe_convergence_problem(r) + + # set rank to that which was computed + rank = rank_ptr[0] + + # compute residuals + if rank < n or m <= n: + res = np.empty((0), dtype=real_dtype) + else: + # this requires additional dispatch as there's a faster + # impl if the result is in the real domain (no abs() required) + res = _lstsq_residual(bcpy, n, nrhs) + + # extract 'x', the solution + x = _lstsq_solution(b, bcpy, n) + + # help liveness analysis + _dummy_liveness_func([acpy.size, bcpy.size, s.size, rank_ptr.size]) + return (x, res, rank, s[:minmn]) + + return lstsq_impl + + +def _solve_compute_return(b, bcpy): + """ + Extract 'x' (the solution) from the 'bcpy' scratch space. + Note 'b' is only used to check the system input dimension... + """ + raise NotImplementedError + + +@overload(_solve_compute_return) +def _solve_compute_return_impl(b, bcpy): + if b.ndim == 1: + def oneD_impl(b, bcpy): + return bcpy.T.ravel() + return oneD_impl + else: + def twoD_impl(b, bcpy): + return bcpy + return twoD_impl + + +@overload(np.linalg.solve) +def solve_impl(a, b): + ensure_lapack() + + _check_linalg_matrix(a, "solve") + _check_linalg_1_or_2d_matrix(b, "solve") + + _check_homogeneous_types("solve", a, b) + + np_dt = np_support.as_dtype(a.dtype) + nb_dt = a.dtype + + # the lapack solver + numba_xgesv = _LAPACK().numba_xgesv(a.dtype) + + kind = ord(get_blas_kind(nb_dt, "solve")) + + def solve_impl(a, b): + n = a.shape[-1] + nrhs = _system_compute_nrhs(b) + + # check the systems have no inf or NaN + _check_finite_matrix(a) + _check_finite_matrix(b) + + # check the systems are dimensionally valid + _system_check_dimensionally_valid(a, b) + + # a is destroyed on exit, copy it + acpy = _copy_to_fortran_order(a) + + # b is overwritten on exit with the solution, copy allocate + bcpy = np.empty((nrhs, n), dtype=np_dt).T + if n == 0: + return _solve_compute_return(b, bcpy) + + # specialised copy in due to b being 1 or 2D + _system_copy_in_b(bcpy, b, nrhs) + + # allocate pivot array (needs to be fortran int size) + ipiv = np.empty(n, dtype=F_INT_nptype) + + r = numba_xgesv( + kind, # kind + n, # n + nrhs, # nhrs + acpy.ctypes, # a + n, # lda + ipiv.ctypes, # ipiv + bcpy.ctypes, # b + n # ldb + ) + _inv_err_handler(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, bcpy.size, ipiv.size]) + return _solve_compute_return(b, bcpy) + + return solve_impl + + +@overload(np.linalg.pinv) +def pinv_impl(a, rcond=1.e-15): + ensure_lapack() + + _check_linalg_matrix(a, "pinv") + + # convert typing floats to numpy floats for use in the impl + s_type = getattr(a.dtype, "underlying_float", a.dtype) + s_dtype = np_support.as_dtype(s_type) + + numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) + + numba_xxgemm = _BLAS().numba_xxgemm(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "pinv")) + JOB = ord('S') + + # need conjugate transposes + TRANSA = ord('C') + TRANSB = ord('C') + + # scalar constants + dt = np_support.as_dtype(a.dtype) + zero = np.array([0.], dtype=dt) + one = np.array([1.], dtype=dt) + + def pinv_impl(a, rcond=1.e-15): + + # The idea is to build the pseudo-inverse via inverting the singular + # value decomposition of a matrix `A`. Mathematically, this is roughly + # A = U*S*V^H [The SV decomposition of A] + # A^+ = V*(S^+)*U^H [The inverted SV decomposition of A] + # where ^+ is pseudo inversion and ^H is Hermitian transpose. + # As V and U are unitary, their inverses are simply their Hermitian + # transpose. S has singular values on its diagonal and zero elsewhere, + # it is inverted trivially by reciprocal of the diagonal values with + # the exception that zero singular values remain as zero. + # + # The practical implementation can take advantage of a few things to + # gain a few % performance increase: + # * A is destroyed by the SVD algorithm from LAPACK so a copy is + # required, this memory is exactly the right size in which to return + # the pseudo-inverse and so can be reused for this purpose. + # * The pseudo-inverse of S can be applied to either V or U^H, this + # then leaves a GEMM operation to compute the inverse via either: + # A^+ = (V*(S^+))*U^H + # or + # A^+ = V*((S^+)*U^H) + # however application of S^+ to V^H or U is more convenient as they + # are the result of the SVD algorithm. The application of the + # diagonal system is just a matrix multiplication which results in a + # row/column scaling (direction depending). To save effort, this + # "matrix multiplication" is applied to the smallest of U or V^H and + # only up to the point of "cut-off" (see next note) just as a direct + # scaling. + # * The cut-off level for application of S^+ can be used to reduce + # total effort, this cut-off can come via rcond or may just naturally + # be present as a result of zeros in the singular values. Regardless + # there's no need to multiply by zeros in the application of S^+ to + # V^H or U as above. Further, the GEMM operation can be shrunk in + # effort by noting that the possible zero block generated by the + # presence of zeros in S^+ has no effect apart from wasting cycles as + # it is all fmadd()s where one operand is zero. The inner dimension + # of the GEMM operation can therefore be set as shrunk accordingly! + + n = a.shape[-1] + m = a.shape[-2] + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + if m == 0 or n == 0: + return acpy.T.ravel().reshape(a.shape).T + + minmn = min(m, n) + + u = np.empty((minmn, m), dtype=a.dtype) + s = np.empty(minmn, dtype=s_dtype) + vt = np.empty((n, minmn), dtype=a.dtype) + + r = numba_ez_gesdd( + kind, # kind + JOB, # job + m, # m + n, # n + acpy.ctypes, # a + m, # lda + s.ctypes, # s + u.ctypes, # u + m, # ldu + vt.ctypes, # vt + minmn # ldvt + ) + _handle_err_maybe_convergence_problem(r) + + # Invert singular values under threshold. Also find the index of + # the threshold value as this is the upper limit for the application + # of the inverted singular values. Finding this value saves + # multiplication by a block of zeros that would be created by the + # application of these values to either U or V^H ahead of multiplying + # them together. This is done by simply in BLAS parlance via + # restricting the `k` dimension to `cut_idx` in `xgemm` whilst keeping + # the leading dimensions correct. + + cut_at = s[0] * rcond + cut_idx = 0 + for k in range(minmn): + if s[k] > cut_at: + s[k] = 1. / s[k] + cut_idx = k + cut_idx += 1 + + # Use cut_idx so there's no scaling by 0. + if m >= n: + # U is largest so apply S^+ to V^H. + for i in range(n): + for j in range(cut_idx): + vt[i, j] = vt[i, j] * s[j] + else: + # V^H is largest so apply S^+ to U. + for i in range(cut_idx): + s_local = s[i] + for j in range(minmn): + u[i, j] = u[i, j] * s_local + + # Do (v^H)^H*U^H (obviously one of the matrices includes the S^+ + # scaling) and write back to acpy. Note the innner dimension of cut_idx + # taking account of the possible zero block. + # We can store the result in acpy, given we had to create it + # for use in the SVD, and it is now redundant and the right size + # but wrong shape. + + r = numba_xxgemm( + kind, + TRANSA, # TRANSA + TRANSB, # TRANSB + n, # M + m, # N + cut_idx, # K + one.ctypes, # ALPHA + vt.ctypes, # A + minmn, # LDA + u.ctypes, # B + m, # LDB + zero.ctypes, # BETA + acpy.ctypes, # C + n # LDC + ) + + # help liveness analysis + #acpy.size + #vt.size + #u.size + #s.size + #one.size + #zero.size + _dummy_liveness_func([acpy.size, vt.size, u.size, s.size, one.size, + zero.size]) + return acpy.T.ravel().reshape(a.shape).T + + return pinv_impl + + +def _get_slogdet_diag_walker(a): + """ + Walks the diag of a LUP decomposed matrix + uses that det(A) = prod(diag(lup(A))) + and also that log(a)+log(b) = log(a*b) + The return sign is adjusted based on the values found + such that the log(value) stays in the real domain. + """ + if isinstance(a.dtype, types.Complex): + @register_jitable + def cmplx_diag_walker(n, a, sgn): + # walk diagonal + csgn = sgn + 0.j + acc = 0. + for k in range(n): + absel = np.abs(a[k, k]) + csgn = csgn * (a[k, k] / absel) + acc = acc + np.log(absel) + return (csgn, acc) + return cmplx_diag_walker + else: + @register_jitable + def real_diag_walker(n, a, sgn): + # walk diagonal + acc = 0. + for k in range(n): + v = a[k, k] + if v < 0.: + sgn = -sgn + v = -v + acc = acc + np.log(v) + # sgn is a float dtype + return (sgn + 0., acc) + return real_diag_walker + + +@overload(np.linalg.slogdet) +def slogdet_impl(a): + ensure_lapack() + + _check_linalg_matrix(a, "slogdet") + + numba_xxgetrf = _LAPACK().numba_xxgetrf(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "slogdet")) + + diag_walker = _get_slogdet_diag_walker(a) + + ONE = a.dtype(1) + ZERO = getattr(a.dtype, "underlying_float", a.dtype)(0) + + def slogdet_impl(a): + n = a.shape[-1] + if a.shape[-2] != n: + msg = "Last 2 dimensions of the array must be square." + raise np.linalg.LinAlgError(msg) + + if n == 0: + return (ONE, ZERO) + + _check_finite_matrix(a) + + acpy = _copy_to_fortran_order(a) + + ipiv = np.empty(n, dtype=F_INT_nptype) + + r = numba_xxgetrf(kind, n, n, acpy.ctypes, n, ipiv.ctypes) + + if r > 0: + # factorisation failed, return same defaults as np + return (0., -np.inf) + _inv_err_handler(r) # catch input-to-lapack problem + + # The following, prior to the call to diag_walker, is present + # to account for the effect of possible permutations to the + # sign of the determinant. + # This is the same idea as in numpy: + # File name `umath_linalg.c.src` e.g. + # https://github.com/numpy/numpy/blob/master/numpy/linalg/umath_linalg.c.src + # in function `@TYPE@_slogdet_single_element`. + sgn = 1 + for k in range(n): + sgn = sgn + (ipiv[k] != (k + 1)) + + sgn = sgn & 1 + if sgn == 0: + sgn = -1 + + # help liveness analysis + _dummy_liveness_func([ipiv.size]) + return diag_walker(n, acpy, sgn) + + return slogdet_impl + + +@overload(np.linalg.det) +def det_impl(a): + + ensure_lapack() + + _check_linalg_matrix(a, "det") + + def det_impl(a): + (sgn, slogdet) = np.linalg.slogdet(a) + return sgn * np.exp(slogdet) + + return det_impl + + +def _compute_singular_values(a): + """ + Compute singular values of *a*. + """ + raise NotImplementedError + + +@overload(_compute_singular_values) +def _compute_singular_values_impl(a): + """ + Returns a function to compute singular values of `a` + """ + numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "svd")) + + # Flag for "only compute `S`" to give to xgesdd + JOBZ_N = ord('N') + + nb_ret_type = getattr(a.dtype, "underlying_float", a.dtype) + np_ret_type = np_support.as_dtype(nb_ret_type) + np_dtype = np_support.as_dtype(a.dtype) + + # These are not referenced in the computation but must be set + # for MKL. + u = np.empty((1, 1), dtype=np_dtype) + vt = np.empty((1, 1), dtype=np_dtype) + + def sv_function(a): + """ + Computes singular values. + """ + # Don't use the np.linalg.svd impl instead + # call LAPACK to shortcut doing the "reconstruct + # singular vectors from reflectors" step and just + # get back the singular values. + n = a.shape[-1] + m = a.shape[-2] + if m == 0 or n == 0: + raise np.linalg.LinAlgError('Arrays cannot be empty') + _check_finite_matrix(a) + + ldu = m + minmn = min(m, n) + + # need to be >=1 but aren't referenced + ucol = 1 + ldvt = 1 + + acpy = _copy_to_fortran_order(a) + + # u and vt are not referenced however need to be + # allocated (as done above) for MKL as it + # checks for ref is nullptr. + s = np.empty(minmn, dtype=np_ret_type) + + r = numba_ez_gesdd( + kind, # kind + JOBZ_N, # jobz + m, # m + n, # n + acpy.ctypes, # a + m, # lda + s.ctypes, # s + u.ctypes, # u + ldu, # ldu + vt.ctypes, # vt + ldvt # ldvt + ) + _handle_err_maybe_convergence_problem(r) + + # help liveness analysis + _dummy_liveness_func([acpy.size, vt.size, u.size, s.size]) + return s + + return sv_function + + +def _oneD_norm_2(a): + """ + Compute the L2-norm of 1D-array *a*. + """ + raise NotImplementedError + + +@overload(_oneD_norm_2) +def _oneD_norm_2_impl(a): + nb_ret_type = getattr(a.dtype, "underlying_float", a.dtype) + np_ret_type = np_support.as_dtype(nb_ret_type) + + xxnrm2 = _BLAS().numba_xxnrm2(a.dtype) + + kind = ord(get_blas_kind(a.dtype, "norm")) + + def impl(a): + # Just ignore order, calls are guarded to only come + # from cases where order=None or order=2. + n = len(a) + # Call L2-norm routine from BLAS + ret = np.empty((1,), dtype=np_ret_type) + jmp = int(a.strides[0] / a.itemsize) + r = xxnrm2( + kind, # kind + n, # n + a.ctypes, # x + jmp, # incx + ret.ctypes # result + ) + if r < 0: + fatal_error_func() + assert 0 # unreachable + + # help liveness analysis + #ret.size + #a.size + _dummy_liveness_func([ret.size, a.size]) + return ret[0] + + return impl + + +def _get_norm_impl(x, ord_flag): + # This function is quite involved as norm supports a large + # range of values to select different norm types via kwarg `ord`. + # The implementation below branches on dimension of the input + # (1D or 2D). The default for `ord` is `None` which requires + # special handling in numba, this is dealt with first in each of + # the dimension branches. Following this the various norms are + # computed via code that is in most cases simply a loop version + # of a ufunc based version as found in numpy. + + # The following is common to both 1D and 2D cases. + # Convert typing floats to numpy floats for use in the impl. + # The return type is always a float, numba differs from numpy in + # that it returns an input precision specific value whereas numpy + # always returns np.float64. + nb_ret_type = getattr(x.dtype, "underlying_float", x.dtype) + np_ret_type = np_support.as_dtype(nb_ret_type) + + np_dtype = np_support.as_dtype(x.dtype) + + xxnrm2 = _BLAS().numba_xxnrm2(x.dtype) + + kind = ord(get_blas_kind(x.dtype, "norm")) + + if x.ndim == 1: + # 1D cases + + # handle "ord" being "None", must be done separately + if ord_flag in (None, types.none): + def oneD_impl(x, ord=None): + return _oneD_norm_2(x) + else: + def oneD_impl(x, ord=None): + n = len(x) + + # Shortcut to handle zero length arrays + # this differs slightly to numpy in that + # numpy raises a ValueError for kwarg ord= + # +/-np.inf as the reduction operations like + # max() and min() don't accept zero length + # arrays + if n == 0: + return 0.0 + + # Note: on order == 2 + # This is the same as for ord=="None" but because + # we have to handle "None" specially this condition + # is separated + if ord == 2: + return _oneD_norm_2(x) + elif ord == np.inf: + # max(abs(x)) + ret = abs(x[0]) + for k in range(1, n): + val = abs(x[k]) + if val > ret: + ret = val + return ret + + elif ord == -np.inf: + # min(abs(x)) + ret = abs(x[0]) + for k in range(1, n): + val = abs(x[k]) + if val < ret: + ret = val + return ret + + elif ord == 0: + # sum(x != 0) + ret = 0.0 + for k in range(n): + if x[k] != 0.: + ret += 1. + return ret + + elif ord == 1: + # sum(abs(x)) + ret = 0.0 + for k in range(n): + ret += abs(x[k]) + return ret + + else: + # sum(abs(x)**ord)**(1./ord) + ret = 0.0 + for k in range(n): + ret += abs(x[k])**ord + return ret**(1. / ord) + return oneD_impl + + elif x.ndim == 2: + # 2D cases + + # handle "ord" being "None" + if ord_flag in (None, types.none): + # Force `x` to be C-order, so that we can take a contiguous + # 1D view. + if x.layout == 'C': + @register_jitable + def array_prepare(x): + return x + elif x.layout == 'F': + @register_jitable + def array_prepare(x): + # Legal since L2(x) == L2(x.T) + return x.T + else: + @register_jitable + def array_prepare(x): + return x.copy() + + # Compute the Frobenius norm, this is the L2,2 induced norm of `x` + # which is the L2-norm of x.ravel() and so can be computed via BLAS + def twoD_impl(x, ord=None): + n = x.size + if n == 0: + # reshape() currently doesn't support zero-sized arrays + return 0.0 + x_c = array_prepare(x) + return _oneD_norm_2(x_c.reshape(n)) + else: + # max value for this dtype + max_val = np.finfo(np_ret_type.type).max + + def twoD_impl(x, ord=None): + n = x.shape[-1] + m = x.shape[-2] + + # Shortcut to handle zero size arrays + # this differs slightly to numpy in that + # numpy raises errors for some ord values + # and in other cases returns zero. + if x.size == 0: + return 0.0 + + if ord == np.inf: + # max of sum of abs across rows + # max(sum(abs(x)), axis=1) + global_max = 0. + for ii in range(m): + tmp = 0. + for jj in range(n): + tmp += abs(x[ii, jj]) + if tmp > global_max: + global_max = tmp + return global_max + + elif ord == -np.inf: + # min of sum of abs across rows + # min(sum(abs(x)), axis=1) + global_min = max_val + for ii in range(m): + tmp = 0. + for jj in range(n): + tmp += abs(x[ii, jj]) + if tmp < global_min: + global_min = tmp + return global_min + elif ord == 1: + # max of sum of abs across cols + # max(sum(abs(x)), axis=0) + global_max = 0. + for ii in range(n): + tmp = 0. + for jj in range(m): + tmp += abs(x[jj, ii]) + if tmp > global_max: + global_max = tmp + return global_max + + elif ord == -1: + # min of sum of abs across cols + # min(sum(abs(x)), axis=0) + global_min = max_val + for ii in range(n): + tmp = 0. + for jj in range(m): + tmp += abs(x[jj, ii]) + if tmp < global_min: + global_min = tmp + return global_min + + # Results via SVD, singular values are sorted on return + # by definition. + elif ord == 2: + # max SV + return _compute_singular_values(x)[0] + elif ord == -2: + # min SV + return _compute_singular_values(x)[-1] + else: + # replicate numpy error + raise ValueError("Invalid norm order for matrices.") + return twoD_impl + else: + assert 0 # unreachable + + +@overload(np.linalg.norm) +def norm_impl(x, ord=None): + ensure_lapack() + + _check_linalg_1_or_2d_matrix(x, "norm") + + return _get_norm_impl(x, ord) + + +@overload(np.linalg.cond) +def cond_impl(x, p=None): + ensure_lapack() + + _check_linalg_matrix(x, "cond") + + def impl(x, p=None): + # This is extracted for performance, numpy does approximately: + # `condition = norm(x) * norm(inv(x))` + # in the cases of `p == 2` or `p ==-2` singular values are used + # for computing norms. This costs numpy an svd of `x` then an + # inversion of `x` and another svd of `x`. + # Below is a different approach, which also gives a more + # accurate answer as there is no inversion involved. + # Recall that the singular values of an inverted matrix are the + # reciprocal of singular values of the original matrix. + # Therefore calling `svd(x)` once yields all the information + # needed about both `x` and `inv(x)` without the cost or + # potential loss of accuracy incurred through inversion. + # For the case of `p == 2`, the result is just the ratio of + # `largest singular value/smallest singular value`, and for the + # case of `p==-2` the result is simply the + # `smallest singular value/largest singular value`. + # As a result of this, numba accepts non-square matrices as + # input when p==+/-2 as well as when p==None. + if p == 2 or p == -2 or p is None: + s = _compute_singular_values(x) + if p == 2 or p is None: + r = np.divide(s[0], s[-1]) + else: + r = np.divide(s[-1], s[0]) + else: # cases np.inf, -np.inf, 1, -1 + norm_x = np.linalg.norm(x, p) + norm_inv_x = np.linalg.norm(np.linalg.inv(x), p) + r = norm_x * norm_inv_x + # NumPy uses a NaN mask, if the input has a NaN, it will return NaN, + # Numba calls ban NaN through the use of _check_finite_matrix but this + # catches cases where NaN occurs through floating point use + if np.isnan(r): + return np.inf + else: + return r + return impl + + +@register_jitable +def _get_rank_from_singular_values(sv, t): + """ + Gets rank from singular values with cut-off at a given tolerance + """ + rank = 0 + for k in range(len(sv)): + if sv[k] > t: + rank = rank + 1 + else: # sv is ordered big->small so break on condition not met + break + return rank + + +@overload(np.linalg.matrix_rank) +def matrix_rank_impl(A, tol=None): + """ + Computes rank for matrices and vectors. + The only issue that may arise is that because numpy uses double + precision lapack calls whereas numba uses type specific lapack + calls, some singular values may differ and therefore counting the + number of them above a tolerance may lead to different counts, + and therefore rank, in some cases. + """ + ensure_lapack() + + _check_linalg_1_or_2d_matrix(A, "matrix_rank") + + def _2d_matrix_rank_impl(A, tol): + + # handle the tol==None case separately for type inference to work + if tol in (None, types.none): + nb_type = getattr(A.dtype, "underlying_float", A.dtype) + np_type = np_support.as_dtype(nb_type) + eps_val = np.finfo(np_type).eps + + def _2d_tol_none_impl(A, tol=None): + s = _compute_singular_values(A) + # replicate numpy default tolerance calculation + r = A.shape[0] + c = A.shape[1] + l = max(r, c) + t = s[0] * l * eps_val + return _get_rank_from_singular_values(s, t) + return _2d_tol_none_impl + else: + def _2d_tol_not_none_impl(A, tol=None): + s = _compute_singular_values(A) + return _get_rank_from_singular_values(s, tol) + return _2d_tol_not_none_impl + + def _get_matrix_rank_impl(A, tol): + ndim = A.ndim + if ndim == 1: + # NOTE: Technically, the numpy implementation could be argued as + # incorrect for the case of a vector (1D matrix). If a tolerance + # is provided and a vector with a singular value below tolerance is + # encountered this should report a rank of zero, the numpy + # implementation does not do this and instead elects to report that + # if any value in the vector is nonzero then the rank is 1. + # An example would be [0, 1e-15, 0, 2e-15] which numpy reports as + # rank 1 invariant of `tol`. The singular value for this vector is + # obviously sqrt(5)*1e-15 and so a tol of e.g. sqrt(6)*1e-15 should + # lead to a reported rank of 0 whereas a tol of 1e-15 should lead + # to a reported rank of 1, numpy reports 1 regardless. + # The code below replicates the numpy behaviour. + def _1d_matrix_rank_impl(A, tol=None): + for k in range(len(A)): + if A[k] != 0.: + return 1 + return 0 + return _1d_matrix_rank_impl + elif ndim == 2: + return _2d_matrix_rank_impl(A, tol) + else: + assert 0 # unreachable + + return _get_matrix_rank_impl(A, tol) + + +@overload(np.linalg.matrix_power) +def matrix_power_impl(a, n): + """ + Computes matrix power. Only integer powers are supported in numpy. + """ + + _check_linalg_matrix(a, "matrix_power") + np_dtype = np_support.as_dtype(a.dtype) + + nt = getattr(n, 'dtype', n) + if not isinstance(nt, types.Integer): + raise NumbaTypeError("Exponent must be an integer.") + + def matrix_power_impl(a, n): + + if n == 0: + # this should be eye() but it doesn't support + # the dtype kwarg yet so do it manually to save + # the copy required by eye(a.shape[0]).asdtype() + A = np.zeros(a.shape, dtype=np_dtype) + for k in range(a.shape[0]): + A[k, k] = 1. + return A + + am, an = a.shape[-1], a.shape[-2] + if am != an: + raise ValueError('input must be a square array') + + # empty, return a copy + if am == 0: + return a.copy() + + # note: to be consistent over contiguousness, C order is + # returned as that is what dot() produces and the most common + # paths through matrix_power will involve that. Therefore + # copies are made here to ensure the data ordering is + # correct for paths not going via dot(). + + if n < 0: + A = np.linalg.inv(a).copy() + if n == -1: # return now + return A + n = -n + else: + if n == 1: # return a copy now + return a.copy() + A = a # this is safe, `a` is only read + + if n < 4: + if n == 2: + return np.dot(A, A) + if n == 3: + return np.dot(np.dot(A, A), A) + else: + + acc = A + exp = n + + # Initialise ret, SSA cannot see the loop will execute, without this + # it appears as uninitialised. + ret = acc + # tried a loop split and branchless using identity matrix as + # input but it seems like having a "first entry" flag is quicker + flag = True + while exp != 0: + if exp & 1: + if flag: + ret = acc + flag = False + else: + ret = np.dot(ret, acc) + acc = np.dot(acc, acc) + exp = exp >> 1 + + return ret + + return matrix_power_impl + +# This is documented under linalg despite not being in the module + + +@overload(np.trace) +def matrix_trace_impl(a, offset=0): + """ + Computes the trace of an array. + """ + + _check_linalg_matrix(a, "trace", la_prefix=False) + + if not isinstance(offset, (int, types.Integer)): + raise NumbaTypeError("integer argument expected, got %s" % offset) + + def matrix_trace_impl(a, offset=0): + rows, cols = a.shape + k = offset + if k < 0: + rows = rows + k + if k > 0: + cols = cols - k + n = max(min(rows, cols), 0) + ret = 0 + if k >= 0: + for i in range(n): + ret += a[i, k + i] + else: + for i in range(n): + ret += a[i - k, i] + return ret + + return matrix_trace_impl + + +def _check_scalar_or_lt_2d_mat(a, func_name, la_prefix=True): + prefix = "np.linalg" if la_prefix else "np" + interp = (prefix, func_name) + # checks that a matrix is 1 or 2D + if isinstance(a, types.Array): + if not a.ndim <= 2: + raise TypingError("%s.%s() only supported on 1 and 2-D arrays " + % interp, highlighting=False) + + +@register_jitable +def outer_impl_none(a, b, out): + aa = np.asarray(a) + bb = np.asarray(b) + return np.multiply(aa.ravel().reshape((aa.size, 1)), + bb.ravel().reshape((1, bb.size))) + + +@register_jitable +def outer_impl_arr(a, b, out): + aa = np.asarray(a) + bb = np.asarray(b) + np.multiply(aa.ravel().reshape((aa.size, 1)), + bb.ravel().reshape((1, bb.size)), + out) + return out + + +def _get_outer_impl(a, b, out): + if out in (None, types.none): + return outer_impl_none + else: + return outer_impl_arr + + +@overload(np.outer) +def outer_impl(a, b, out=None): + + _check_scalar_or_lt_2d_mat(a, "outer", la_prefix=False) + _check_scalar_or_lt_2d_mat(b, "outer", la_prefix=False) + + impl = _get_outer_impl(a, b, out) + + def outer_impl(a, b, out=None): + return impl(a, b, out) + + return outer_impl + + +def _kron_normaliser_impl(x): + # makes x into a 2d array + if isinstance(x, types.Array): + if x.layout not in ('C', 'F'): + raise TypingError("np.linalg.kron only supports 'C' or 'F' layout " + "input arrays. Received an input of " + "layout '{}'.".format(x.layout)) + elif x.ndim == 2: + @register_jitable + def nrm_shape(x): + xn = x.shape[-1] + xm = x.shape[-2] + return x.reshape(xm, xn) + return nrm_shape + else: + @register_jitable + def nrm_shape(x): + xn = x.shape[-1] + return x.reshape(1, xn) + return nrm_shape + else: # assume its a scalar + @register_jitable + def nrm_shape(x): + a = np.empty((1, 1), type(x)) + a[0] = x + return a + return nrm_shape + + +def _kron_return(a, b): + # transforms c into something that kron would return + # based on the shapes of a and b + a_is_arr = isinstance(a, types.Array) + b_is_arr = isinstance(b, types.Array) + if a_is_arr and b_is_arr: + if a.ndim == 2 or b.ndim == 2: + @register_jitable + def ret(a, b, c): + return c + return ret + else: + @register_jitable + def ret(a, b, c): + return c.reshape(c.size) + return ret + else: # at least one of (a, b) is a scalar + if a_is_arr: + @register_jitable + def ret(a, b, c): + return c.reshape(a.shape) + return ret + elif b_is_arr: + @register_jitable + def ret(a, b, c): + return c.reshape(b.shape) + return ret + else: # both scalars + @register_jitable + def ret(a, b, c): + return c[0] + return ret + + +@overload(np.kron) +def kron_impl(a, b): + + _check_scalar_or_lt_2d_mat(a, "kron", la_prefix=False) + _check_scalar_or_lt_2d_mat(b, "kron", la_prefix=False) + + fix_a = _kron_normaliser_impl(a) + fix_b = _kron_normaliser_impl(b) + ret_c = _kron_return(a, b) + + # this is fine because the ufunc for the Hadamard product + # will reject differing dtypes in a and b. + dt = getattr(a, 'dtype', a) + + def kron_impl(a, b): + + aa = fix_a(a) + bb = fix_b(b) + + am = aa.shape[-2] + an = aa.shape[-1] + bm = bb.shape[-2] + bn = bb.shape[-1] + + cm = am * bm + cn = an * bn + + # allocate c + C = np.empty((cm, cn), dtype=dt) + + # In practice this is runs quicker than the more obvious + # `each element of A multiplied by B and assigned to + # a block in C` like alg. + + # loop over rows of A + for i in range(am): + # compute the column offset into C + rjmp = i * bm + # loop over rows of B + for k in range(bm): + # compute row the offset into C + irjmp = rjmp + k + # slice a given row of B + slc = bb[k, :] + # loop over columns of A + for j in range(an): + # vectorized assignment of an element of A + # multiplied by the current row of B into + # a slice of a row of C + cjmp = j * bn + C[irjmp, cjmp:cjmp + bn] = aa[i, j] * slc + + return ret_c(a, b, C) + + return kron_impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime.py new file mode 100644 index 0000000000000000000000000000000000000000..ba29542e92064297ca1ed8860248fa0e7ca918db --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime.py @@ -0,0 +1,840 @@ +""" +Implementation of operations on numpy timedelta64. +""" + +import numpy as np +import operator + +import llvmlite.ir +from llvmlite.ir import Constant + +from numba.core import types, cgutils +from numba.core.cgutils import create_constant_array +from numba.core.imputils import (lower_builtin, lower_constant, + impl_ret_untracked, lower_cast) +from numba.np import npdatetime_helpers, numpy_support, npyfuncs +from numba.extending import overload_method +from numba.core.config import IS_32BITS +from numba.core.errors import LoweringError + +# datetime64 and timedelta64 use the same internal representation +DATETIME64 = TIMEDELTA64 = llvmlite.ir.IntType(64) +NAT = Constant(TIMEDELTA64, npdatetime_helpers.NAT) + +TIMEDELTA_BINOP_SIG = (types.NPTimedelta,) * 2 + + +def scale_by_constant(builder, val, factor): + """ + Multiply *val* by the constant *factor*. + """ + return builder.mul(val, Constant(TIMEDELTA64, factor)) + + +def unscale_by_constant(builder, val, factor): + """ + Divide *val* by the constant *factor*. + """ + return builder.sdiv(val, Constant(TIMEDELTA64, factor)) + + +def add_constant(builder, val, const): + """ + Add constant *const* to *val*. + """ + return builder.add(val, Constant(TIMEDELTA64, const)) + + +def scale_timedelta(context, builder, val, srcty, destty): + """ + Scale the timedelta64 *val* from *srcty* to *destty* + (both numba.types.NPTimedelta instances) + """ + factor = npdatetime_helpers.get_timedelta_conversion_factor( + srcty.unit, destty.unit) + if factor is None: + # This can happen when using explicit output in a ufunc. + msg = f"cannot convert timedelta64 from {srcty.unit} to {destty.unit}" + raise LoweringError(msg) + return scale_by_constant(builder, val, factor) + + +def normalize_timedeltas(context, builder, left, right, leftty, rightty): + """ + Scale either *left* or *right* to the other's unit, in order to have + homogeneous units. + """ + factor = npdatetime_helpers.get_timedelta_conversion_factor( + leftty.unit, rightty.unit) + if factor is not None: + return scale_by_constant(builder, left, factor), right + factor = npdatetime_helpers.get_timedelta_conversion_factor( + rightty.unit, leftty.unit) + if factor is not None: + return left, scale_by_constant(builder, right, factor) + # Typing should not let this happen, except on == and != operators + raise RuntimeError("cannot normalize %r and %r" % (leftty, rightty)) + + +def alloc_timedelta_result(builder, name='ret'): + """ + Allocate a NaT-initialized datetime64 (or timedelta64) result slot. + """ + ret = cgutils.alloca_once(builder, TIMEDELTA64, name=name) + builder.store(NAT, ret) + return ret + + +def alloc_boolean_result(builder, name='ret'): + """ + Allocate an uninitialized boolean result slot. + """ + ret = cgutils.alloca_once(builder, llvmlite.ir.IntType(1), name=name) + return ret + + +def is_not_nat(builder, val): + """ + Return a predicate which is true if *val* is not NaT. + """ + return builder.icmp_unsigned('!=', val, NAT) + + +def are_not_nat(builder, vals): + """ + Return a predicate which is true if all of *vals* are not NaT. + """ + assert len(vals) >= 1 + pred = is_not_nat(builder, vals[0]) + for val in vals[1:]: + pred = builder.and_(pred, is_not_nat(builder, val)) + return pred + + +normal_year_months = create_constant_array( + TIMEDELTA64, + [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) +leap_year_months = create_constant_array( + TIMEDELTA64, + [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) +normal_year_months_acc = create_constant_array( + TIMEDELTA64, + [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]) +leap_year_months_acc = create_constant_array( + TIMEDELTA64, + [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]) + + +@lower_constant(types.NPDatetime) +@lower_constant(types.NPTimedelta) +def datetime_constant(context, builder, ty, pyval): + return DATETIME64(pyval.astype(np.int64)) + + +# Arithmetic operators on timedelta64 + +@lower_builtin(operator.pos, types.NPTimedelta) +def timedelta_pos_impl(context, builder, sig, args): + res = args[0] + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.neg, types.NPTimedelta) +def timedelta_neg_impl(context, builder, sig, args): + res = builder.neg(args[0]) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(abs, types.NPTimedelta) +def timedelta_abs_impl(context, builder, sig, args): + val, = args + ret = alloc_timedelta_result(builder) + with builder.if_else(cgutils.is_scalar_neg(builder, val)) as (then, otherwise): + with then: + builder.store(builder.neg(val), ret) + with otherwise: + builder.store(val, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def timedelta_sign_impl(context, builder, sig, args): + """ + np.sign(timedelta64) + """ + val, = args + ret = alloc_timedelta_result(builder) + zero = Constant(TIMEDELTA64, 0) + with builder.if_else(builder.icmp_signed('>', val, zero) + ) as (gt_zero, le_zero): + with gt_zero: + builder.store(Constant(TIMEDELTA64, 1), ret) + with le_zero: + with builder.if_else(builder.icmp_unsigned('==', val, zero) + ) as (eq_zero, lt_zero): + with eq_zero: + builder.store(Constant(TIMEDELTA64, 0), ret) + with lt_zero: + builder.store(Constant(TIMEDELTA64, -1), ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.add, *TIMEDELTA_BINOP_SIG) +@lower_builtin(operator.iadd, *TIMEDELTA_BINOP_SIG) +def timedelta_add_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + ret = alloc_timedelta_result(builder) + with cgutils.if_likely(builder, are_not_nat(builder, [va, vb])): + va = scale_timedelta(context, builder, va, ta, sig.return_type) + vb = scale_timedelta(context, builder, vb, tb, sig.return_type) + builder.store(builder.add(va, vb), ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.sub, *TIMEDELTA_BINOP_SIG) +@lower_builtin(operator.isub, *TIMEDELTA_BINOP_SIG) +def timedelta_sub_impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + ret = alloc_timedelta_result(builder) + with cgutils.if_likely(builder, are_not_nat(builder, [va, vb])): + va = scale_timedelta(context, builder, va, ta, sig.return_type) + vb = scale_timedelta(context, builder, vb, tb, sig.return_type) + builder.store(builder.sub(va, vb), ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +def _timedelta_times_number(context, builder, td_arg, td_type, + number_arg, number_type, return_type): + ret = alloc_timedelta_result(builder) + with cgutils.if_likely(builder, is_not_nat(builder, td_arg)): + if isinstance(number_type, types.Float): + val = builder.sitofp(td_arg, number_arg.type) + val = builder.fmul(val, number_arg) + val = _cast_to_timedelta(context, builder, val) + else: + val = builder.mul(td_arg, number_arg) + # The scaling is required for ufunc np.multiply() with an explicit + # output in a different unit. + val = scale_timedelta(context, builder, val, td_type, return_type) + builder.store(val, ret) + return builder.load(ret) + + +@lower_builtin(operator.mul, types.NPTimedelta, types.Integer) +@lower_builtin(operator.imul, types.NPTimedelta, types.Integer) +@lower_builtin(operator.mul, types.NPTimedelta, types.Float) +@lower_builtin(operator.imul, types.NPTimedelta, types.Float) +def timedelta_times_number(context, builder, sig, args): + res = _timedelta_times_number(context, builder, + args[0], sig.args[0], args[1], sig.args[1], + sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.mul, types.Integer, types.NPTimedelta) +@lower_builtin(operator.imul, types.Integer, types.NPTimedelta) +@lower_builtin(operator.mul, types.Float, types.NPTimedelta) +@lower_builtin(operator.imul, types.Float, types.NPTimedelta) +def number_times_timedelta(context, builder, sig, args): + res = _timedelta_times_number(context, builder, + args[1], sig.args[1], args[0], sig.args[0], + sig.return_type) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.truediv, types.NPTimedelta, types.Integer) +@lower_builtin(operator.itruediv, types.NPTimedelta, types.Integer) +@lower_builtin(operator.floordiv, types.NPTimedelta, types.Integer) +@lower_builtin(operator.ifloordiv, types.NPTimedelta, types.Integer) +@lower_builtin(operator.truediv, types.NPTimedelta, types.Float) +@lower_builtin(operator.itruediv, types.NPTimedelta, types.Float) +@lower_builtin(operator.floordiv, types.NPTimedelta, types.Float) +@lower_builtin(operator.ifloordiv, types.NPTimedelta, types.Float) +def timedelta_over_number(context, builder, sig, args): + td_arg, number_arg = args + number_type = sig.args[1] + ret = alloc_timedelta_result(builder) + ok = builder.and_(is_not_nat(builder, td_arg), + builder.not_(cgutils.is_scalar_zero_or_nan(builder, number_arg))) + with cgutils.if_likely(builder, ok): + # Denominator is non-zero, non-NaN + if isinstance(number_type, types.Float): + val = builder.sitofp(td_arg, number_arg.type) + val = builder.fdiv(val, number_arg) + val = _cast_to_timedelta(context, builder, val) + else: + val = builder.sdiv(td_arg, number_arg) + # The scaling is required for ufuncs np.*divide() with an explicit + # output in a different unit. + val = scale_timedelta(context, builder, val, + sig.args[0], sig.return_type) + builder.store(val, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.truediv, *TIMEDELTA_BINOP_SIG) +@lower_builtin(operator.itruediv, *TIMEDELTA_BINOP_SIG) +def timedelta_over_timedelta(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + not_nan = are_not_nat(builder, [va, vb]) + ll_ret_type = context.get_value_type(sig.return_type) + ret = cgutils.alloca_once(builder, ll_ret_type, name='ret') + builder.store(Constant(ll_ret_type, float('nan')), ret) + with cgutils.if_likely(builder, not_nan): + va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb) + va = builder.sitofp(va, ll_ret_type) + vb = builder.sitofp(vb, ll_ret_type) + builder.store(builder.fdiv(va, vb), ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.floordiv, *TIMEDELTA_BINOP_SIG) +def timedelta_floor_div_timedelta(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + ll_ret_type = context.get_value_type(sig.return_type) + not_nan = are_not_nat(builder, [va, vb]) + ret = cgutils.alloca_once(builder, ll_ret_type, name='ret') + zero = Constant(ll_ret_type, 0) + one = Constant(ll_ret_type, 1) + builder.store(zero, ret) + with cgutils.if_likely(builder, not_nan): + va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb) + # is the denominator zero or NaT? + denom_ok = builder.not_(builder.icmp_signed('==', vb, zero)) + with cgutils.if_likely(builder, denom_ok): + # is either arg negative? + vaneg = builder.icmp_signed('<', va, zero) + neg = builder.or_(vaneg, builder.icmp_signed('<', vb, zero)) + with builder.if_else(neg) as (then, otherwise): + with then: # one or more value negative + with builder.if_else(vaneg) as (negthen, negotherwise): + with negthen: + top = builder.sub(va, one) + div = builder.sdiv(top, vb) + builder.store(div, ret) + with negotherwise: + top = builder.add(va, one) + div = builder.sdiv(top, vb) + builder.store(div, ret) + with otherwise: + div = builder.sdiv(va, vb) + builder.store(div, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + +def timedelta_mod_timedelta(context, builder, sig, args): + # inspired by https://github.com/numpy/numpy/blob/fe8072a12d65e43bd2e0b0f9ad67ab0108cc54b3/numpy/core/src/umath/loops.c.src#L1424 + # alg is basically as `a % b`: + # if a or b is NaT return NaT + # elseif b is 0 return NaT + # else pretend a and b are int and do pythonic int modulus + + [va, vb] = args + [ta, tb] = sig.args + not_nan = are_not_nat(builder, [va, vb]) + ll_ret_type = context.get_value_type(sig.return_type) + ret = alloc_timedelta_result(builder) + builder.store(NAT, ret) + zero = Constant(ll_ret_type, 0) + with cgutils.if_likely(builder, not_nan): + va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb) + # is the denominator zero or NaT? + denom_ok = builder.not_(builder.icmp_signed('==', vb, zero)) + with cgutils.if_likely(builder, denom_ok): + # is either arg negative? + vapos = builder.icmp_signed('>', va, zero) + vbpos = builder.icmp_signed('>', vb, zero) + rem = builder.srem(va, vb) + cond = builder.or_(builder.and_(vapos, vbpos), + builder.icmp_signed('==', rem, zero)) + with builder.if_else(cond) as (then, otherwise): + with then: + builder.store(rem, ret) + with otherwise: + builder.store(builder.add(rem, vb), ret) + + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# Comparison operators on timedelta64 + + +def _create_timedelta_comparison_impl(ll_op, default_value): + def impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + ret = alloc_boolean_result(builder) + with builder.if_else(are_not_nat(builder, [va, vb])) as (then, otherwise): + with then: + try: + norm_a, norm_b = normalize_timedeltas( + context, builder, va, vb, ta, tb) + except RuntimeError: + # Cannot normalize units => the values are unequal (except if NaT) + builder.store(default_value, ret) + else: + builder.store(builder.icmp_unsigned(ll_op, norm_a, norm_b), ret) + with otherwise: + # NaT ==/>=/>/ is True + if ll_op == '!=': + builder.store(cgutils.true_bit, ret) + else: + builder.store(cgutils.false_bit, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + return impl + + +def _create_timedelta_ordering_impl(ll_op): + def impl(context, builder, sig, args): + [va, vb] = args + [ta, tb] = sig.args + ret = alloc_boolean_result(builder) + with builder.if_else(are_not_nat(builder, [va, vb])) as (then, otherwise): + with then: + norm_a, norm_b = normalize_timedeltas( + context, builder, va, vb, ta, tb) + builder.store(builder.icmp_signed(ll_op, norm_a, norm_b), ret) + with otherwise: + # NaT >=/>/') +timedelta_ge_timedelta_impl = _create_timedelta_ordering_impl('>=') + +for op_, func in [(operator.eq, timedelta_eq_timedelta_impl), + (operator.ne, timedelta_ne_timedelta_impl), + (operator.lt, timedelta_lt_timedelta_impl), + (operator.le, timedelta_le_timedelta_impl), + (operator.gt, timedelta_gt_timedelta_impl), + (operator.ge, timedelta_ge_timedelta_impl)]: + lower_builtin(op_, *TIMEDELTA_BINOP_SIG)(func) + + +# Arithmetic on datetime64 + +def is_leap_year(builder, year_val): + """ + Return a predicate indicating whether *year_val* (offset by 1970) is a + leap year. + """ + actual_year = builder.add(year_val, Constant(DATETIME64, 1970)) + multiple_of_4 = cgutils.is_null( + builder, builder.and_(actual_year, Constant(DATETIME64, 3))) + not_multiple_of_100 = cgutils.is_not_null( + builder, builder.srem(actual_year, Constant(DATETIME64, 100))) + multiple_of_400 = cgutils.is_null( + builder, builder.srem(actual_year, Constant(DATETIME64, 400))) + return builder.and_(multiple_of_4, + builder.or_(not_multiple_of_100, multiple_of_400)) + + +def year_to_days(builder, year_val): + """ + Given a year *year_val* (offset to 1970), return the number of days + since the 1970 epoch. + """ + # The algorithm below is copied from Numpy's get_datetimestruct_days() + # (src/multiarray/datetime.c) + ret = cgutils.alloca_once(builder, TIMEDELTA64) + # First approximation + days = scale_by_constant(builder, year_val, 365) + # Adjust for leap years + with builder.if_else(cgutils.is_neg_int(builder, year_val)) \ + as (if_neg, if_pos): + with if_pos: + # At or after 1970: + # 1968 is the closest leap year before 1970. + # Exclude the current year, so add 1. + from_1968 = add_constant(builder, year_val, 1) + # Add one day for each 4 years + p_days = builder.add(days, + unscale_by_constant(builder, from_1968, 4)) + # 1900 is the closest previous year divisible by 100 + from_1900 = add_constant(builder, from_1968, 68) + # Subtract one day for each 100 years + p_days = builder.sub(p_days, + unscale_by_constant(builder, from_1900, 100)) + # 1600 is the closest previous year divisible by 400 + from_1600 = add_constant(builder, from_1900, 300) + # Add one day for each 400 years + p_days = builder.add(p_days, + unscale_by_constant(builder, from_1600, 400)) + builder.store(p_days, ret) + with if_neg: + # Before 1970: + # NOTE `year_val` is negative, and so will be `from_1972` and `from_2000`. + # 1972 is the closest later year after 1970. + # Include the current year, so subtract 2. + from_1972 = add_constant(builder, year_val, -2) + # Subtract one day for each 4 years (`from_1972` is negative) + n_days = builder.add(days, + unscale_by_constant(builder, from_1972, 4)) + # 2000 is the closest later year divisible by 100 + from_2000 = add_constant(builder, from_1972, -28) + # Add one day for each 100 years + n_days = builder.sub(n_days, + unscale_by_constant(builder, from_2000, 100)) + # 2000 is also the closest later year divisible by 400 + # Subtract one day for each 400 years + n_days = builder.add(n_days, + unscale_by_constant(builder, from_2000, 400)) + builder.store(n_days, ret) + return builder.load(ret) + + +def reduce_datetime_for_unit(builder, dt_val, src_unit, dest_unit): + dest_unit_code = npdatetime_helpers.DATETIME_UNITS[dest_unit] + src_unit_code = npdatetime_helpers.DATETIME_UNITS[src_unit] + if dest_unit_code < 2 or src_unit_code >= 2: + return dt_val, src_unit + # Need to compute the day ordinal for *dt_val* + if src_unit_code == 0: + # Years to days + year_val = dt_val + days_val = year_to_days(builder, year_val) + + else: + # Months to days + leap_array = cgutils.global_constant(builder, "leap_year_months_acc", + leap_year_months_acc) + normal_array = cgutils.global_constant(builder, "normal_year_months_acc", + normal_year_months_acc) + + days = cgutils.alloca_once(builder, TIMEDELTA64) + + # First compute year number and month number + year, month = cgutils.divmod_by_constant(builder, dt_val, 12) + + # Then deduce the number of days + with builder.if_else(is_leap_year(builder, year)) as (then, otherwise): + with then: + addend = builder.load(cgutils.gep(builder, leap_array, + 0, month, inbounds=True)) + builder.store(addend, days) + with otherwise: + addend = builder.load(cgutils.gep(builder, normal_array, + 0, month, inbounds=True)) + builder.store(addend, days) + + days_val = year_to_days(builder, year) + days_val = builder.add(days_val, builder.load(days)) + + if dest_unit_code == 2: + # Need to scale back to weeks + weeks, _ = cgutils.divmod_by_constant(builder, days_val, 7) + return weeks, 'W' + else: + return days_val, 'D' + + +def convert_datetime_for_arith(builder, dt_val, src_unit, dest_unit): + """ + Convert datetime *dt_val* from *src_unit* to *dest_unit*. + """ + # First partial conversion to days or weeks, if necessary. + dt_val, dt_unit = reduce_datetime_for_unit( + builder, dt_val, src_unit, dest_unit) + # Then multiply by the remaining constant factor. + dt_factor = npdatetime_helpers.get_timedelta_conversion_factor(dt_unit, dest_unit) + if dt_factor is None: + # This can happen when using explicit output in a ufunc. + raise LoweringError("cannot convert datetime64 from %r to %r" + % (src_unit, dest_unit)) + return scale_by_constant(builder, dt_val, dt_factor) + + +def _datetime_timedelta_arith(ll_op_name): + def impl(context, builder, dt_arg, dt_unit, + td_arg, td_unit, ret_unit): + ret = alloc_timedelta_result(builder) + with cgutils.if_likely(builder, are_not_nat(builder, [dt_arg, td_arg])): + dt_arg = convert_datetime_for_arith(builder, dt_arg, + dt_unit, ret_unit) + td_factor = npdatetime_helpers.get_timedelta_conversion_factor( + td_unit, ret_unit) + td_arg = scale_by_constant(builder, td_arg, td_factor) + ret_val = getattr(builder, ll_op_name)(dt_arg, td_arg) + builder.store(ret_val, ret) + return builder.load(ret) + return impl + + +_datetime_plus_timedelta = _datetime_timedelta_arith('add') +_datetime_minus_timedelta = _datetime_timedelta_arith('sub') + +# datetime64 + timedelta64 + + +@lower_builtin(operator.add, types.NPDatetime, types.NPTimedelta) +@lower_builtin(operator.iadd, types.NPDatetime, types.NPTimedelta) +def datetime_plus_timedelta(context, builder, sig, args): + dt_arg, td_arg = args + dt_type, td_type = sig.args + res = _datetime_plus_timedelta(context, builder, + dt_arg, dt_type.unit, + td_arg, td_type.unit, + sig.return_type.unit) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@lower_builtin(operator.add, types.NPTimedelta, types.NPDatetime) +@lower_builtin(operator.iadd, types.NPTimedelta, types.NPDatetime) +def timedelta_plus_datetime(context, builder, sig, args): + td_arg, dt_arg = args + td_type, dt_type = sig.args + res = _datetime_plus_timedelta(context, builder, + dt_arg, dt_type.unit, + td_arg, td_type.unit, + sig.return_type.unit) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# datetime64 - timedelta64 + + +@lower_builtin(operator.sub, types.NPDatetime, types.NPTimedelta) +@lower_builtin(operator.isub, types.NPDatetime, types.NPTimedelta) +def datetime_minus_timedelta(context, builder, sig, args): + dt_arg, td_arg = args + dt_type, td_type = sig.args + res = _datetime_minus_timedelta(context, builder, + dt_arg, dt_type.unit, + td_arg, td_type.unit, + sig.return_type.unit) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# datetime64 - datetime64 + + +@lower_builtin(operator.sub, types.NPDatetime, types.NPDatetime) +def datetime_minus_datetime(context, builder, sig, args): + va, vb = args + ta, tb = sig.args + unit_a = ta.unit + unit_b = tb.unit + ret_unit = sig.return_type.unit + ret = alloc_timedelta_result(builder) + with cgutils.if_likely(builder, are_not_nat(builder, [va, vb])): + va = convert_datetime_for_arith(builder, va, unit_a, ret_unit) + vb = convert_datetime_for_arith(builder, vb, unit_b, ret_unit) + ret_val = builder.sub(va, vb) + builder.store(ret_val, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + +# datetime64 comparisons + + +def _create_datetime_comparison_impl(ll_op): + def impl(context, builder, sig, args): + va, vb = args + ta, tb = sig.args + unit_a = ta.unit + unit_b = tb.unit + ret_unit = npdatetime_helpers.get_best_unit(unit_a, unit_b) + ret = alloc_boolean_result(builder) + with builder.if_else(are_not_nat(builder, [va, vb])) as (then, otherwise): + with then: + norm_a = convert_datetime_for_arith( + builder, va, unit_a, ret_unit) + norm_b = convert_datetime_for_arith( + builder, vb, unit_b, ret_unit) + ret_val = builder.icmp_signed(ll_op, norm_a, norm_b) + builder.store(ret_val, ret) + with otherwise: + if ll_op == '!=': + ret_val = cgutils.true_bit + else: + ret_val = cgutils.false_bit + builder.store(ret_val, ret) + res = builder.load(ret) + return impl_ret_untracked(context, builder, sig.return_type, res) + + return impl + + +datetime_eq_datetime_impl = _create_datetime_comparison_impl('==') +datetime_ne_datetime_impl = _create_datetime_comparison_impl('!=') +datetime_lt_datetime_impl = _create_datetime_comparison_impl('<') +datetime_le_datetime_impl = _create_datetime_comparison_impl('<=') +datetime_gt_datetime_impl = _create_datetime_comparison_impl('>') +datetime_ge_datetime_impl = _create_datetime_comparison_impl('>=') + +for op, func in [(operator.eq, datetime_eq_datetime_impl), + (operator.ne, datetime_ne_datetime_impl), + (operator.lt, datetime_lt_datetime_impl), + (operator.le, datetime_le_datetime_impl), + (operator.gt, datetime_gt_datetime_impl), + (operator.ge, datetime_ge_datetime_impl)]: + lower_builtin(op, *[types.NPDatetime]*2)(func) + + +######################################################################## +# datetime/timedelta fmax/fmin maximum/minimum support + +def _gen_datetime_max_impl(NAT_DOMINATES): + def datetime_max_impl(context, builder, sig, args): + # note this could be optimizing relying on the actual value of NAT + # but as NumPy doesn't rely on this, this seems more resilient + in1, in2 = args + in1_not_nat = is_not_nat(builder, in1) + in2_not_nat = is_not_nat(builder, in2) + in1_ge_in2 = builder.icmp_signed('>=', in1, in2) + res = builder.select(in1_ge_in2, in1, in2) + if NAT_DOMINATES: + # NaT now dominates, like NaN + in1, in2 = in2, in1 + res = builder.select(in1_not_nat, res, in2) + res = builder.select(in2_not_nat, res, in1) + + return impl_ret_untracked(context, builder, sig.return_type, res) + return datetime_max_impl + +datetime_maximum_impl = _gen_datetime_max_impl(True) +datetime_fmax_impl = _gen_datetime_max_impl(False) + +def _gen_datetime_min_impl(NAT_DOMINATES): + def datetime_min_impl(context, builder, sig, args): + # note this could be optimizing relying on the actual value of NAT + # but as NumPy doesn't rely on this, this seems more resilient + in1, in2 = args + in1_not_nat = is_not_nat(builder, in1) + in2_not_nat = is_not_nat(builder, in2) + in1_le_in2 = builder.icmp_signed('<=', in1, in2) + res = builder.select(in1_le_in2, in1, in2) + if NAT_DOMINATES: + # NaT now dominates, like NaN + in1, in2 = in2, in1 + res = builder.select(in1_not_nat, res, in2) + res = builder.select(in2_not_nat, res, in1) + + return impl_ret_untracked(context, builder, sig.return_type, res) + return datetime_min_impl + +datetime_minimum_impl = _gen_datetime_min_impl(True) +datetime_fmin_impl = _gen_datetime_min_impl(False) + +def _gen_timedelta_max_impl(NAT_DOMINATES): + def timedelta_max_impl(context, builder, sig, args): + # note this could be optimizing relying on the actual value of NAT + # but as NumPy doesn't rely on this, this seems more resilient + in1, in2 = args + in1_not_nat = is_not_nat(builder, in1) + in2_not_nat = is_not_nat(builder, in2) + in1_ge_in2 = builder.icmp_signed('>=', in1, in2) + res = builder.select(in1_ge_in2, in1, in2) + if NAT_DOMINATES: + # NaT now dominates, like NaN + in1, in2 = in2, in1 + res = builder.select(in1_not_nat, res, in2) + res = builder.select(in2_not_nat, res, in1) + + return impl_ret_untracked(context, builder, sig.return_type, res) + return timedelta_max_impl + +timedelta_maximum_impl = _gen_timedelta_max_impl(True) +timedelta_fmax_impl = _gen_timedelta_max_impl(False) + +def _gen_timedelta_min_impl(NAT_DOMINATES): + def timedelta_min_impl(context, builder, sig, args): + # note this could be optimizing relying on the actual value of NAT + # but as NumPy doesn't rely on this, this seems more resilient + in1, in2 = args + in1_not_nat = is_not_nat(builder, in1) + in2_not_nat = is_not_nat(builder, in2) + in1_le_in2 = builder.icmp_signed('<=', in1, in2) + res = builder.select(in1_le_in2, in1, in2) + if NAT_DOMINATES: + # NaT now dominates, like NaN + in1, in2 = in2, in1 + res = builder.select(in1_not_nat, res, in2) + res = builder.select(in2_not_nat, res, in1) + + return impl_ret_untracked(context, builder, sig.return_type, res) + return timedelta_min_impl + +timedelta_minimum_impl = _gen_timedelta_min_impl(True) +timedelta_fmin_impl = _gen_timedelta_min_impl(False) + +def _cast_to_timedelta(context, builder, val): + temp = builder.alloca(TIMEDELTA64) + val_is_nan = builder.fcmp_unordered('uno', val, val) + with builder.if_else(val_is_nan) as ( + then, els): + with then: + # NaN does not guarantee to cast to NAT. + # We should store NAT explicitly. + builder.store(NAT, temp) + with els: + builder.store(builder.fptosi(val, TIMEDELTA64), temp) + return builder.load(temp) + + +@lower_builtin(np.isnat, types.NPDatetime) +@lower_builtin(np.isnat, types.NPTimedelta) +def _np_isnat_impl(context, builder, sig, args): + return npyfuncs.np_datetime_isnat_impl(context, builder, sig, args) + + +@lower_cast(types.NPDatetime, types.Integer) +@lower_cast(types.NPTimedelta, types.Integer) +def _cast_npdatetime_int64(context, builder, fromty, toty, val): + if toty.bitwidth != 64: # all date time types are 64 bit + msg = f"Cannot cast {fromty} to {toty} as {toty} is not 64 bits wide." + raise ValueError(msg) + return val + + +@overload_method(types.NPTimedelta, '__hash__') +@overload_method(types.NPDatetime, '__hash__') +def ol_hash_npdatetime(x): + if numpy_support.numpy_version >= (2, 2)\ + and isinstance(x, types.NPTimedelta) and not x.unit: + raise ValueError("Can't hash generic timedelta64") + + if IS_32BITS: + def impl(x): + x = np.int64(x) + if x < 2**31 - 1: # x < LONG_MAX + y = np.int32(x) + else: + hi = (np.int64(x) & 0xffffffff00000000) >> 32 + lo = (np.int64(x) & 0x00000000ffffffff) + y = np.int32(lo + (1000003) * hi) + if y == -1: + y = np.int32(-2) + return y + else: + def impl(x): + if np.int64(x) == -1: + return np.int64(-2) + return np.int64(x) + return impl + + +lower_builtin(npdatetime_helpers.datetime_minimum, types.NPDatetime, types.NPDatetime)(datetime_minimum_impl) +lower_builtin(npdatetime_helpers.datetime_minimum, types.NPTimedelta, types.NPTimedelta)(datetime_minimum_impl) +lower_builtin(npdatetime_helpers.datetime_maximum, types.NPDatetime, types.NPDatetime)(datetime_maximum_impl) +lower_builtin(npdatetime_helpers.datetime_maximum, types.NPTimedelta, types.NPTimedelta)(datetime_maximum_impl) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime_helpers.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4abb671b91ddea0c32fc1571dc2f9dc88a5335b5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npdatetime_helpers.py @@ -0,0 +1,212 @@ +""" +Helper functions for np.timedelta64 and np.datetime64. +For now, multiples-of-units (for example timedeltas expressed in tens +of seconds) are not supported. +""" + + +import numpy as np + + +DATETIME_UNITS = { + 'Y': 0, # Years + 'M': 1, # Months + 'W': 2, # Weeks + # Yes, there's a gap here + 'D': 4, # Days + 'h': 5, # Hours + 'm': 6, # Minutes + 's': 7, # Seconds + 'ms': 8, # Milliseconds + 'us': 9, # Microseconds + 'ns': 10, # Nanoseconds + 'ps': 11, # Picoseconds + 'fs': 12, # Femtoseconds + 'as': 13, # Attoseconds + '': 14, # "generic", i.e. unit-less +} + +NAT = np.timedelta64('nat').astype(np.int64) + +# NOTE: numpy has several inconsistent functions for timedelta casting: +# - can_cast_timedelta64_{metadata,units}() disallows "safe" casting +# to and from generic units +# - cast_timedelta_to_timedelta() allows casting from (but not to) +# generic units +# - compute_datetime_metadata_greatest_common_divisor() allows casting from +# generic units (used for promotion) + + +def same_kind(src, dest): + """ + Whether the *src* and *dest* units are of the same kind. + """ + return (DATETIME_UNITS[src] < 5) == (DATETIME_UNITS[dest] < 5) + + +def can_cast_timedelta_units(src, dest): + # Mimic NumPy's "safe" casting and promotion + # `dest` must be more precise than `src` and they must be compatible + # for conversion. + # XXX should we switch to enforcing "same-kind" for Numpy 1.10+ ? + src = DATETIME_UNITS[src] + dest = DATETIME_UNITS[dest] + if src == dest: + return True + if src == 14: + return True + if src > dest: + return False + if dest == 14: + # unit-less timedelta64 is not compatible with anything else + return False + if src <= 1 and dest > 1: + # Cannot convert between months or years and other units + return False + return True + + +# Exact conversion factors from one unit to the immediately more precise one +_factors = { + 0: (1, 12), # Years -> Months + 2: (4, 7), # Weeks -> Days + 4: (5, 24), # Days -> Hours + 5: (6, 60), # Hours -> Minutes + 6: (7, 60), # Minutes -> Seconds + 7: (8, 1000), + 8: (9, 1000), + 9: (10, 1000), + 10: (11, 1000), + 11: (12, 1000), + 12: (13, 1000), +} + + +def _get_conversion_multiplier(big_unit_code, small_unit_code): + """ + Return an integer multiplier allowing to convert from *big_unit_code* + to *small_unit_code*. + None is returned if the conversion is not possible through a + simple integer multiplication. + """ + # Mimics get_datetime_units_factor() in NumPy's datetime.c, + # with a twist to allow no-op conversion from generic units. + if big_unit_code == 14: + return 1 + c = big_unit_code + factor = 1 + while c < small_unit_code: + try: + c, mult = _factors[c] + except KeyError: + # No possible conversion + return None + factor *= mult + if c == small_unit_code: + return factor + else: + return None + + +def get_timedelta_conversion_factor(src_unit, dest_unit): + """ + Return an integer multiplier allowing to convert from timedeltas + of *src_unit* to *dest_unit*. + """ + return _get_conversion_multiplier(DATETIME_UNITS[src_unit], + DATETIME_UNITS[dest_unit]) + + +def get_datetime_timedelta_conversion(datetime_unit, timedelta_unit): + """ + Compute a possible conversion for combining *datetime_unit* and + *timedelta_unit* (presumably for adding or subtracting). + Return (result unit, integer datetime multiplier, integer timedelta + multiplier). RuntimeError is raised if the combination is impossible. + """ + # XXX now unused (I don't know where / how Numpy uses this) + dt_unit_code = DATETIME_UNITS[datetime_unit] + td_unit_code = DATETIME_UNITS[timedelta_unit] + if td_unit_code == 14 or dt_unit_code == 14: + return datetime_unit, 1, 1 + if td_unit_code < 2 and dt_unit_code >= 2: + # Cannot combine Y or M timedelta64 with a finer-grained datetime64 + raise RuntimeError("cannot combine datetime64(%r) and timedelta64(%r)" + % (datetime_unit, timedelta_unit)) + dt_factor, td_factor = 1, 1 + + # If years or months, the datetime unit is first scaled to weeks or days, + # then conversion continues below. This is the same algorithm as used + # in Numpy's get_datetime_conversion_factor() (src/multiarray/datetime.c): + # """Conversions between years/months and other units use + # the factor averaged over the 400 year leap year cycle.""" + if dt_unit_code == 0: + if td_unit_code >= 4: + dt_factor = 97 + 400 * 365 + td_factor = 400 + dt_unit_code = 4 + elif td_unit_code == 2: + dt_factor = 97 + 400 * 365 + td_factor = 400 * 7 + dt_unit_code = 2 + elif dt_unit_code == 1: + if td_unit_code >= 4: + dt_factor = 97 + 400 * 365 + td_factor = 400 * 12 + dt_unit_code = 4 + elif td_unit_code == 2: + dt_factor = 97 + 400 * 365 + td_factor = 400 * 12 * 7 + dt_unit_code = 2 + + if td_unit_code >= dt_unit_code: + factor = _get_conversion_multiplier(dt_unit_code, td_unit_code) + assert factor is not None, (dt_unit_code, td_unit_code) + return timedelta_unit, dt_factor * factor, td_factor + else: + factor = _get_conversion_multiplier(td_unit_code, dt_unit_code) + assert factor is not None, (dt_unit_code, td_unit_code) + return datetime_unit, dt_factor, td_factor * factor + + +def combine_datetime_timedelta_units(datetime_unit, timedelta_unit): + """ + Return the unit result of combining *datetime_unit* with *timedelta_unit* + (e.g. by adding or subtracting). None is returned if combining + those units is forbidden. + """ + dt_unit_code = DATETIME_UNITS[datetime_unit] + td_unit_code = DATETIME_UNITS[timedelta_unit] + if dt_unit_code == 14: + return timedelta_unit + elif td_unit_code == 14: + return datetime_unit + if td_unit_code < 2 and dt_unit_code >= 2: + return None + if dt_unit_code > td_unit_code: + return datetime_unit + else: + return timedelta_unit + + +def get_best_unit(unit_a, unit_b): + """ + Get the best (i.e. finer-grained) of two units. + """ + a = DATETIME_UNITS[unit_a] + b = DATETIME_UNITS[unit_b] + if a == 14: + return unit_b + if b == 14: + return unit_a + if b > a: + return unit_b + return unit_a + + +def datetime_minimum(a, b): + pass + + +def datetime_maximum(a, b): + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyfuncs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..230e67a1c62e442cd289a6bbcf4c52b8647635e5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyfuncs.py @@ -0,0 +1,1704 @@ +"""Codegen for functions used as kernels in NumPy functions + +Typically, the kernels of several ufuncs that can't map directly to +Python builtins +""" + + +import math + +import llvmlite.ir +import numpy as np + +from numba.core.extending import overload +from numba.core.imputils import impl_ret_untracked +from numba.core import typing, types, errors, lowering, cgutils, config +from numba.core.extending import register_jitable +from numba.np import npdatetime +from numba.np.math import cmathimpl, mathimpl, numbers +from numba.np.numpy_support import numpy_version + +# some NumPy constants. Note that we could generate some of them using +# the math library, but having the values copied from npy_math seems to +# yield more accurate results +_NPY_LOG2E = 1.442695040888963407359924681001892137 # math.log(math.e, 2) +_NPY_LOG10E = 0.434294481903251827651128918916605082 # math.log(math.e, 10) +_NPY_LOGE2 = 0.693147180559945309417232121458176568 # math.log(2) + + +def _check_arity_and_homogeneity(sig, args, arity, return_type = None): + """checks that the following are true: + - args and sig.args have arg_count elements + - all input types are homogeneous + - return type is 'return_type' if provided, otherwise it must be + homogeneous with the input types. + """ + assert len(args) == arity + assert len(sig.args) == arity + ty = sig.args[0] + if return_type is None: + return_type = ty + # must have homogeneous args + if not( all(arg==ty for arg in sig.args) and sig.return_type == return_type): + import inspect + fname = inspect.currentframe().f_back.f_code.co_name + msg = '{0} called with invalid types: {1}'.format(fname, sig) + assert False, msg + +cast_arg_ty = types.float64 + +def _call_func_by_name_with_cast(context, builder, sig, args, + func_name, ty=cast_arg_ty): + # it is quite common in NumPy to have loops implemented as a call + # to the double version of the function, wrapped in casts. This + # helper function facilitates that. + mod = builder.module + lty = context.get_argument_type(ty) + fnty = llvmlite.ir.FunctionType(lty, [lty]*len(sig.args)) + fn = cgutils.insert_pure_function(mod, fnty, name=func_name) + cast_args = [context.cast(builder, arg, argty, ty) + for arg, argty in zip(args, sig.args) ] + + result = builder.call(fn, cast_args) + return context.cast(builder, result, types.float64, sig.return_type) + + +def _dispatch_func_by_name_type(context, builder, sig, args, table, user_name): + # for most cases the functions are homogeneous on all their types. + # this code dispatches on the first argument type as it is the most useful + # for our uses (all cases but ldexp are homogeneous in all types, and + # dispatching on the first argument type works of ldexp as well) + # + # assumes that the function pointed by func_name has the type + # signature sig (but needs translation to llvm types). + + ty = sig.args[0] + try: + func_name = table[ty] + except KeyError as e: + msg = "No {0} function for real type {1}".format(user_name, str(e)) + raise errors.LoweringError(msg) + + mod = builder.module + if ty in types.complex_domain: + # In numba struct types are always passed by pointer. So the call has to + # be transformed from "result = func(ops...)" to "func(&result, ops...). + # note that the result value pointer as first argument is the convention + # used by numba. + + # First, prepare the return value + out = context.make_complex(builder, ty) + ptrargs = [cgutils.alloca_once_value(builder, arg) + for arg in args] + call_args = [out._getpointer()] + ptrargs + # get_value_as_argument for struct types like complex allocate stack space + # and initialize with the value, the return value is the pointer to that + # allocated space (ie: pointer to a copy of the value in the stack). + # get_argument_type returns a pointer to the struct type in consonance. + call_argtys = [ty] + list(sig.args) + call_argltys = [context.get_value_type(ty).as_pointer() + for ty in call_argtys] + fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), call_argltys) + # Note: the function isn't pure here (it writes to its pointer args) + fn = cgutils.get_or_insert_function(mod, fnty, func_name) + builder.call(fn, call_args) + retval = builder.load(call_args[0]) + else: + argtypes = [context.get_argument_type(aty) for aty in sig.args] + restype = context.get_argument_type(sig.return_type) + fnty = llvmlite.ir.FunctionType(restype, argtypes) + fn = cgutils.insert_pure_function(mod, fnty, name=func_name) + retval = context.call_external_function(builder, fn, sig.args, args) + return retval + + + +######################################################################## +# Division kernels inspired by NumPy loops.c.src code +# +# The builtins are not applicable as they rely on a test for zero in the +# denominator. If it is zero the appropriate exception is raised. +# In NumPy, a division by zero does not raise an exception, but instead +# generated a known value. Note that a division by zero in any of the +# operations of a vector may raise an exception or issue a warning +# depending on the np.seterr configuration. This is not supported +# right now (and in any case, it won't be handled by these functions +# either) + +def np_int_sdiv_impl(context, builder, sig, args): + # based on the actual code in NumPy loops.c.src for signed integer types + _check_arity_and_homogeneity(sig, args, 2) + + num, den = args + ty = sig.args[0] # any arg type will do, homogeneous + + ZERO = context.get_constant(ty, 0) + MINUS_ONE = context.get_constant(ty, -1) + MIN_INT = context.get_constant(ty, 1 << (den.type.width-1)) + den_is_zero = builder.icmp_unsigned('==', ZERO, den) + den_is_minus_one = builder.icmp_unsigned('==', MINUS_ONE, den) + num_is_min_int = builder.icmp_unsigned('==', MIN_INT, num) + could_cause_sigfpe = builder.and_(den_is_minus_one, num_is_min_int) + force_zero = builder.or_(den_is_zero, could_cause_sigfpe) + with builder.if_else(force_zero, likely=False) as (then, otherwise): + with then: + bb_then = builder.basic_block + with otherwise: + bb_otherwise = builder.basic_block + div = builder.sdiv(num, den) + mod = builder.srem(num, den) + num_gt_zero = builder.icmp_signed('>', num, ZERO) + den_gt_zero = builder.icmp_signed('>', den, ZERO) + not_same_sign = builder.xor(num_gt_zero, den_gt_zero) + mod_not_zero = builder.icmp_unsigned('!=', mod, ZERO) + needs_fixing = builder.and_(not_same_sign, mod_not_zero) + fix_value = builder.select(needs_fixing, MINUS_ONE, ZERO) + result_otherwise = builder.add(div, fix_value) + + result = builder.phi(ZERO.type) + result.add_incoming(ZERO, bb_then) + result.add_incoming(result_otherwise, bb_otherwise) + + return result + + +def np_int_srem_impl(context, builder, sig, args): + # based on the actual code in NumPy loops.c.src for signed integers + _check_arity_and_homogeneity(sig, args, 2) + + num, den = args + ty = sig.args[0] # any arg type will do, homogeneous + + ZERO = context.get_constant(ty, 0) + den_not_zero = builder.icmp_unsigned('!=', ZERO, den) + bb_no_if = builder.basic_block + with cgutils.if_unlikely(builder, den_not_zero): + bb_if = builder.basic_block + mod = builder.srem(num,den) + num_gt_zero = builder.icmp_signed('>', num, ZERO) + den_gt_zero = builder.icmp_signed('>', den, ZERO) + not_same_sign = builder.xor(num_gt_zero, den_gt_zero) + mod_not_zero = builder.icmp_unsigned('!=', mod, ZERO) + needs_fixing = builder.and_(not_same_sign, mod_not_zero) + fix_value = builder.select(needs_fixing, den, ZERO) + final_mod = builder.add(fix_value, mod) + + result = builder.phi(ZERO.type) + result.add_incoming(ZERO, bb_no_if) + result.add_incoming(final_mod, bb_if) + + return result + + +def np_int_sdivrem_impl(context, builder, sig, args): + div = np_int_sdiv_impl(context, builder, sig.return_type[0](*sig.args), args) + rem = np_int_srem_impl(context, builder, sig.return_type[1](*sig.args), args) + return context.make_tuple(builder, sig.return_type, [div, rem]) + + +def np_int_udiv_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + num, den = args + ty = sig.args[0] # any arg type will do, homogeneous + + ZERO = context.get_constant(ty, 0) + div_by_zero = builder.icmp_unsigned('==', ZERO, den) + with builder.if_else(div_by_zero, likely=False) as (then, otherwise): + with then: + # division by zero + bb_then = builder.basic_block + with otherwise: + # divide! + div = builder.udiv(num, den) + bb_otherwise = builder.basic_block + + result = builder.phi(ZERO.type) + result.add_incoming(ZERO, bb_then) + result.add_incoming(div, bb_otherwise) + return result + + +def np_int_urem_impl(context, builder, sig, args): + # based on the actual code in NumPy loops.c.src for signed integers + _check_arity_and_homogeneity(sig, args, 2) + + num, den = args + ty = sig.args[0] # any arg type will do, homogeneous + + ZERO = context.get_constant(ty, 0) + den_not_zero = builder.icmp_unsigned('!=', ZERO, den) + bb_no_if = builder.basic_block + with cgutils.if_unlikely(builder, den_not_zero): + bb_if = builder.basic_block + mod = builder.urem(num,den) + + result = builder.phi(ZERO.type) + result.add_incoming(ZERO, bb_no_if) + result.add_incoming(mod, bb_if) + + return result + + +def np_int_udivrem_impl(context, builder, sig, args): + div = np_int_udiv_impl(context, builder, sig.return_type[0](*sig.args), args) + rem = np_int_urem_impl(context, builder, sig.return_type[1](*sig.args), args) + return context.make_tuple(builder, sig.return_type, [div, rem]) + + +# implementation of int_fmod is in fact the same as the unsigned remainder, +# that is: srem with a special case returning 0 when the denominator is 0. +np_int_fmod_impl = np_int_urem_impl + + +def np_real_div_impl(context, builder, sig, args): + # in NumPy real div has the same semantics as an fdiv for generating + # NANs, INF and NINF + _check_arity_and_homogeneity(sig, args, 2) + return builder.fdiv(*args) + + +def np_real_mod_impl(context, builder, sig, args): + # note: this maps to NumPy remainder, which has the same semantics as Python + # based on code in loops.c.src + _check_arity_and_homogeneity(sig, args, 2) + in1, in2 = args + ty = sig.args[0] + + ZERO = context.get_constant(ty, 0.0) + res = builder.frem(in1, in2) + res_ne_zero = builder.fcmp_ordered('!=', res, ZERO) + den_lt_zero = builder.fcmp_ordered('<', in2, ZERO) + res_lt_zero = builder.fcmp_ordered('<', res, ZERO) + needs_fixing = builder.and_(res_ne_zero, + builder.xor(den_lt_zero, res_lt_zero)) + fix_value = builder.select(needs_fixing, in2, ZERO) + + return builder.fadd(res, fix_value) + + +def np_real_fmod_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + return builder.frem(*args) + + +def _fabs(context, builder, arg): + ZERO = llvmlite.ir.Constant(arg.type, 0.0) + arg_negated = builder.fsub(ZERO, arg) + arg_is_negative = builder.fcmp_ordered('<', arg, ZERO) + return builder.select(arg_is_negative, arg_negated, arg) + + +def np_complex_div_impl(context, builder, sig, args): + # Extracted from numpy/core/src/umath/loops.c.src, + # inspired by complex_div_impl + # variables named coherent with loops.c.src + # This is implemented using the approach described in + # R.L. Smith. Algorithm 116: Complex division. + # Communications of the ACM, 5(8):435, 1962 + + in1, in2 = [context.make_complex(builder, sig.args[0], value=arg) + for arg in args] + + in1r = in1.real # numerator.real + in1i = in1.imag # numerator.imag + in2r = in2.real # denominator.real + in2i = in2.imag # denominator.imag + ftype = in1r.type + assert all([i.type==ftype for i in [in1r, in1i, in2r, in2i]]), "mismatched types" + out = context.make_helper(builder, sig.return_type) + + ZERO = llvmlite.ir.Constant(ftype, 0.0) + ONE = llvmlite.ir.Constant(ftype, 1.0) + + # if abs(denominator.real) >= abs(denominator.imag) + in2r_abs = _fabs(context, builder, in2r) + in2i_abs = _fabs(context, builder, in2i) + in2r_abs_ge_in2i_abs = builder.fcmp_ordered('>=', in2r_abs, in2i_abs) + with builder.if_else(in2r_abs_ge_in2i_abs) as (then, otherwise): + with then: + # if abs(denominator.real) == 0 and abs(denominator.imag) == 0 + in2r_is_zero = builder.fcmp_ordered('==', in2r_abs, ZERO) + in2i_is_zero = builder.fcmp_ordered('==', in2i_abs, ZERO) + in2_is_zero = builder.and_(in2r_is_zero, in2i_is_zero) + with builder.if_else(in2_is_zero) as (inn_then, inn_otherwise): + with inn_then: + # division by 0. + # fdiv generates the appropriate NAN/INF/NINF + out.real = builder.fdiv(in1r, in2r_abs) + out.imag = builder.fdiv(in1i, in2i_abs) + with inn_otherwise: + # general case for: + # abs(denominator.real) > abs(denominator.imag) + rat = builder.fdiv(in2i, in2r) + # scl = 1.0/(in2r + in2i*rat) + tmp1 = builder.fmul(in2i, rat) + tmp2 = builder.fadd(in2r, tmp1) + scl = builder.fdiv(ONE, tmp2) + # out.real = (in1r + in1i*rat)*scl + # out.imag = (in1i - in1r*rat)*scl + tmp3 = builder.fmul(in1i, rat) + tmp4 = builder.fmul(in1r, rat) + tmp5 = builder.fadd(in1r, tmp3) + tmp6 = builder.fsub(in1i, tmp4) + out.real = builder.fmul(tmp5, scl) + out.imag = builder.fmul(tmp6, scl) + with otherwise: + # general case for: + # abs(denominator.imag) > abs(denominator.real) + rat = builder.fdiv(in2r, in2i) + # scl = 1.0/(in2i + in2r*rat) + tmp1 = builder.fmul(in2r, rat) + tmp2 = builder.fadd(in2i, tmp1) + scl = builder.fdiv(ONE, tmp2) + # out.real = (in1r*rat + in1i)*scl + # out.imag = (in1i*rat - in1r)*scl + tmp3 = builder.fmul(in1r, rat) + tmp4 = builder.fmul(in1i, rat) + tmp5 = builder.fadd(tmp3, in1i) + tmp6 = builder.fsub(tmp4, in1r) + out.real = builder.fmul(tmp5, scl) + out.imag = builder.fmul(tmp6, scl) + + return out._getvalue() + + +######################################################################## +# NumPy logaddexp + +def _npy_logaddexp(x1, x2): + pass + +def _generate_logaddexp(fnoverload, const, log1pfn, expfn): + # Code generation for logaddexp and logaddexp2 is based on: + # https://github.com/numpy/numpy/blob/12c2b7dd62fc0c14b81c8892ed5f4f59cc94d09c/numpy/core/src/npymath/npy_math_internal.h.src#L467-L507 + + @overload(fnoverload, target='generic') + def ol_npy_logaddexp(x1, x2): + if x1 != x2: + return + shift = x1(const) + def impl(x1, x2): + x, y = x1, x2 + if (x == y): + # Handles infinities of the same sign without warnings + return x + shift + else: + tmp = x - y + if (tmp > 0): + return x + log1pfn(expfn(-tmp)) + elif (tmp <= 0): + return y + log1pfn(expfn(tmp)) + else: + # NaN + return tmp + return impl + +def _npy_logaddexp(x1, x2): + pass + + +_generate_logaddexp(_npy_logaddexp, _NPY_LOGE2, np.log1p, np.exp) + + +def np_real_logaddexp_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + fnty = context.typing_context.resolve_value_type(_npy_logaddexp) + sig = fnty.get_call_type(context.typing_context, (*sig.args,), {}) + impl = context.get_function(fnty, sig) + return impl(builder, args) + +######################################################################## +# NumPy logaddexp2 +def _npy_logaddexp2(x1, x2): + pass + +def npy_log2_1p(x): + pass + +# The following npy_log2_1p function is a translation of: +# https://github.com/numpy/numpy/blob/12c2b7dd62fc0c14b81c8892ed5f4f59cc94d09c/numpy/core/src/npymath/npy_math_internal.h.src#L457-L460 + +@overload(npy_log2_1p, target='generic') +def ol_npy_log2_1p(x): + LOG2E = x(_NPY_LOG2E) + def impl(x): + return LOG2E * np.log1p(x) + return impl + + +_generate_logaddexp(_npy_logaddexp2, 1.0, npy_log2_1p, np.exp2) + + +def np_real_logaddexp2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + fnty = context.typing_context.resolve_value_type(_npy_logaddexp2) + sig = fnty.get_call_type(context.typing_context, (*sig.args,), {}) + impl = context.get_function(fnty, sig) + return impl(builder, args) + + +######################################################################## +# true div kernels + +def np_int_truediv_impl(context, builder, sig, args): + # in NumPy we don't check for 0 denominator... fdiv handles div by + # 0 in the way NumPy expects.. + # integer truediv always yields double + num, den = args + lltype = num.type + assert all(i.type==lltype for i in args), "must have homogeneous types" + numty, denty = sig.args + + num = context.cast(builder, num, numty, types.float64) + den = context.cast(builder, den, denty, types.float64) + + return builder.fdiv(num,den) + + +######################################################################## +# floor div kernels + +def np_real_floor_div_impl(context, builder, sig, args): + res = np_real_div_impl(context, builder, sig, args) + s = typing.signature(sig.return_type, sig.return_type) + return np_real_floor_impl(context, builder, s, (res,)) + + +def np_real_divmod_impl(context, builder, sig, args): + div = np_real_floor_div_impl(context, builder, sig.return_type[0](*sig.args), args) + rem = np_real_mod_impl(context, builder, sig.return_type[1](*sig.args), args) + return context.make_tuple(builder, sig.return_type, [div, rem]) + + +def np_complex_floor_div_impl(context, builder, sig, args): + # this is based on the complex floor divide in Numpy's loops.c.src + # This is basically a full complex division with a complex floor + # applied. + # The complex floor seems to be defined as the real floor applied + # with the real part and zero in the imaginary part. Fully developed + # so it avoids computing anything related to the imaginary result. + float_kind = sig.args[0].underlying_float + floor_sig = typing.signature(float_kind, float_kind) + + in1, in2 = [context.make_complex(builder, sig.args[0], value=arg) + for arg in args] + + in1r = in1.real + in1i = in1.imag + in2r = in2.real + in2i = in2.imag + ftype = in1r.type + assert all([i.type==ftype for i in [in1r, in1i, in2r, in2i]]), "mismatched types" + + ZERO = llvmlite.ir.Constant(ftype, 0.0) + + out = context.make_helper(builder, sig.return_type) + out.imag = ZERO + + in2r_abs = _fabs(context, builder, in2r) + in2i_abs = _fabs(context, builder, in2i) + in2r_abs_ge_in2i_abs = builder.fcmp_ordered('>=', in2r_abs, in2i_abs) + + with builder.if_else(in2r_abs_ge_in2i_abs) as (then, otherwise): + with then: + rat = builder.fdiv(in2i, in2r) + # out.real = floor((in1r+in1i*rat)/(in2r + in2i*rat)) + tmp1 = builder.fmul(in1i, rat) + tmp2 = builder.fmul(in2i, rat) + tmp3 = builder.fadd(in1r, tmp1) + tmp4 = builder.fadd(in2r, tmp2) + tmp5 = builder.fdiv(tmp3, tmp4) + out.real = np_real_floor_impl(context, builder, floor_sig, (tmp5,)) + with otherwise: + rat = builder.fdiv(in2r, in2i) + # out.real = floor((in1i + in1r*rat)/(in2i + in2r*rat)) + tmp1 = builder.fmul(in1r, rat) + tmp2 = builder.fmul(in2r, rat) + tmp3 = builder.fadd(in1i, tmp1) + tmp4 = builder.fadd(in2i, tmp2) + tmp5 = builder.fdiv(tmp3, tmp4) + out.real = np_real_floor_impl(context, builder, floor_sig, (tmp5,)) + return out._getvalue() + + +######################################################################## +# numpy power funcs + +def np_complex_power_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + return numbers.complex_power_impl(context, builder, sig, args) + + +######################################################################## +# numpy float power funcs + +def real_float_power_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + return numbers.real_power_impl(context, builder, sig, args) + + +def np_complex_float_power_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + return numbers.complex_power_impl(context, builder, sig, args) + + +######################################################################## +# numpy greatest common denominator + +def np_gcd_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + return mathimpl.gcd_impl(context, builder, sig, args) + + +######################################################################## +# numpy lowest common multiple + +def np_lcm_impl(context, builder, sig, args): + + xty, yty = sig.args + assert xty == yty == sig.return_type + x, y = args + + def lcm(a, b): + """ + Like gcd, heavily cribbed from Julia. + """ + return 0 if a == 0 else abs(a * (b // np.gcd(b, a))) + + res = context.compile_internal(builder, lcm, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +######################################################################## +# Numpy style complex sign + +def np_complex_sign_impl(context, builder, sig, args): + # equivalent to complex sign in NumPy's sign + # but implemented via selects, balancing the 4 cases. + _check_arity_and_homogeneity(sig, args, 1) + + if numpy_version >= (2, 0): + # NumPy >= 2.0.0 + def complex_sign(z): + abs = math.hypot(z.real, z.imag) + if abs == 0: + return 0 + 0j + else: + return z / abs + + res = context.compile_internal(builder, complex_sign, sig, args) + return impl_ret_untracked(context, builder, sig.return_type, res) + else: + op = args[0] + ty = sig.args[0] + result = context.make_complex(builder, ty) + float_ty = ty.underlying_float + + ZERO = context.get_constant(float_ty, 0.0) + ONE = context.get_constant(float_ty, 1.0) + MINUS_ONE = context.get_constant(float_ty, -1.0) + NAN = context.get_constant(float_ty, float('nan')) + + result.real = ZERO + result.imag = ZERO + cmp_sig = typing.signature(types.boolean, *[ty] * 2) + cmp_args = [op, result._getvalue()] + arg1_ge_arg2 = np_complex_ge_impl(context, builder, cmp_sig, cmp_args) + arg1_eq_arg2 = np_complex_eq_impl(context, builder, cmp_sig, cmp_args) + arg1_lt_arg2 = np_complex_lt_impl(context, builder, cmp_sig, cmp_args) + + real_when_ge = builder.select(arg1_eq_arg2, ZERO, ONE) + real_when_nge = builder.select(arg1_lt_arg2, MINUS_ONE, NAN) + result.real = builder.select(arg1_ge_arg2, real_when_ge, real_when_nge) + + return result._getvalue() + + +######################################################################## +# Numpy rint + +def np_real_rint_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + return mathimpl.call_fp_intrinsic(builder, 'llvm.rint', args) + + +def np_complex_rint_impl(context, builder, sig, args): + # based on code in NumPy's funcs.inc.src + # rint of a complex number defined as rint of its real and imag + # parts + _check_arity_and_homogeneity(sig, args, 1) + ty = sig.args[0] + float_ty = ty.underlying_float + in1 = context.make_complex(builder, ty, value=args[0]) + out = context.make_complex(builder, ty) + + inner_sig = typing.signature(*[float_ty]*2) + out.real = np_real_rint_impl(context, builder, inner_sig, [in1.real]) + out.imag = np_real_rint_impl(context, builder, inner_sig, [in1.imag]) + return out._getvalue() + + +######################################################################## +# NumPy exp + +def np_real_exp_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.exp_impl(context, builder, sig, args) + + +def np_complex_exp_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return cmathimpl.exp_impl(context, builder, sig, args) + +######################################################################## +# NumPy exp2 + +def np_real_exp2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + ll_ty = args[0].type + fnty = llvmlite.ir.FunctionType(ll_ty, [ll_ty,]) + fn = cgutils.insert_pure_function(builder.module, fnty, + name='llvm.exp2') + return builder.call(fn, [args[0]]) + + +def np_complex_exp2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + ty = sig.args[0] + float_ty = ty.underlying_float + in1 = context.make_complex(builder, ty, value=args[0]) + tmp = context.make_complex(builder, ty) + loge2 = context.get_constant(float_ty, _NPY_LOGE2) + tmp.real = builder.fmul(loge2, in1.real) + tmp.imag = builder.fmul(loge2, in1.imag) + return np_complex_exp_impl(context, builder, sig, [tmp._getvalue()]) + + +######################################################################## +# NumPy log + +def np_real_log_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.log_impl(context, builder, sig, args) + + +def np_complex_log_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return cmathimpl.log_impl(context, builder, sig, args) + +######################################################################## +# NumPy log2 + +def np_real_log2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + ll_ty = args[0].type + fnty = llvmlite.ir.FunctionType(ll_ty, [ll_ty,]) + fn = cgutils.insert_pure_function(builder.module, fnty, + name='llvm.log2') + return builder.call(fn, [args[0]]) + +def np_complex_log2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + float_ty = ty.underlying_float + tmp = np_complex_log_impl(context, builder, sig, args) + tmp = context.make_complex(builder, ty, value=tmp) + log2e = context.get_constant(float_ty, _NPY_LOG2E) + tmp.real = builder.fmul(log2e, tmp.real) + tmp.imag = builder.fmul(log2e, tmp.imag) + return tmp._getvalue() + + +######################################################################## +# NumPy log10 + +def np_real_log10_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.log10_impl(context, builder, sig, args) + + +def np_complex_log10_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + float_ty = ty.underlying_float + tmp = np_complex_log_impl(context, builder, sig, args) + tmp = context.make_complex(builder, ty, value=tmp) + log10e = context.get_constant(float_ty, _NPY_LOG10E) + tmp.real = builder.fmul(log10e, tmp.real) + tmp.imag = builder.fmul(log10e, tmp.imag) + return tmp._getvalue() + + +######################################################################## +# NumPy expm1 + +def np_real_expm1_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.expm1_impl(context, builder, sig, args) + +def np_complex_expm1_impl(context, builder, sig, args): + # this is based on nc_expm1 in funcs.inc.src + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + float_ty = ty.underlying_float + float_unary_sig = typing.signature(*[float_ty]*2) + + MINUS_ONE = context.get_constant(float_ty, -1.0) + in1 = context.make_complex(builder, ty, value=args[0]) + a = np_real_exp_impl(context, builder, float_unary_sig, [in1.real]) + out = context.make_complex(builder, ty) + cos_imag = np_real_cos_impl(context, builder, float_unary_sig, [in1.imag]) + sin_imag = np_real_sin_impl(context, builder, float_unary_sig, [in1.imag]) + tmp = builder.fmul(a, cos_imag) + out.imag = builder.fmul(a, sin_imag) + out.real = builder.fadd(tmp, MINUS_ONE) + + return out._getvalue() + + +######################################################################## +# NumPy log1p + +def np_real_log1p_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.log1p_impl(context, builder, sig, args) + +def np_complex_log1p_impl(context, builder, sig, args): + # base on NumPy's nc_log1p in funcs.inc.src + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + float_ty = ty.underlying_float + float_unary_sig = typing.signature(*[float_ty]*2) + float_binary_sig = typing.signature(*[float_ty]*3) + + ONE = context.get_constant(float_ty, 1.0) + in1 = context.make_complex(builder, ty, value=args[0]) + out = context.make_complex(builder, ty) + real_plus_one = builder.fadd(in1.real, ONE) + l = np_real_hypot_impl(context, builder, float_binary_sig, + [real_plus_one, in1.imag]) + out.imag = np_real_atan2_impl(context, builder, float_binary_sig, + [in1.imag, real_plus_one]) + out.real = np_real_log_impl(context, builder, float_unary_sig, [l]) + + return out._getvalue() + + +######################################################################## +# NumPy sqrt + +def np_real_sqrt_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.sqrt_impl(context, builder, sig, args) + + +def np_complex_sqrt_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return cmathimpl.sqrt_impl(context, builder, sig, args) + + +######################################################################## +# NumPy square + +def np_int_square_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return builder.mul(args[0], args[0]) + + +def np_real_square_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return builder.fmul(args[0], args[0]) + +def np_complex_square_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + binary_sig = typing.signature(*[sig.return_type]*3) + return numbers.complex_mul_impl(context, builder, binary_sig, + [args[0], args[0]]) + + +######################################################################## +# NumPy cbrt + +def np_real_cbrt_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + # We enable fastmath here to force np.power(x, 1/3) to generate a + # call to libm cbrt function + @register_jitable(fastmath=True) + def cbrt(x): + if x < 0: + return -np.power(-x, 1.0 / 3.0) + else: + return np.power(x, 1.0 / 3.0) + + def _cbrt(x): + if np.isnan(x): + return np.nan + return cbrt(x) + + return context.compile_internal(builder, _cbrt, sig, args) + + +######################################################################## +# NumPy reciprocal + +def np_int_reciprocal_impl(context, builder, sig, args): + # based on the implementation in loops.c.src + # integer versions for reciprocal are performed via promotion + # using double, and then converted back to the type + _check_arity_and_homogeneity(sig, args, 1) + ty = sig.return_type + + binary_sig = typing.signature(*[ty]*3) + in_as_float = context.cast(builder, args[0], ty, types.float64) + ONE = context.get_constant(types.float64, 1) + result_as_float = builder.fdiv(ONE, in_as_float) + return context.cast(builder, result_as_float, types.float64, ty) + + +def np_real_reciprocal_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + ONE = context.get_constant(sig.return_type, 1.0) + return builder.fdiv(ONE, args[0]) + + +def np_complex_reciprocal_impl(context, builder, sig, args): + # based on the implementation in loops.c.src + # Basically the same Smith method used for division, but with + # the numerator substituted by 1.0 + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + float_ty = ty.underlying_float + + ZERO = context.get_constant(float_ty, 0.0) + ONE = context.get_constant(float_ty, 1.0) + in1 = context.make_complex(builder, ty, value=args[0]) + out = context.make_complex(builder, ty) + in1r = in1.real + in1i = in1.imag + in1r_abs = _fabs(context, builder, in1r) + in1i_abs = _fabs(context, builder, in1i) + in1i_abs_le_in1r_abs = builder.fcmp_ordered('<=', in1i_abs, in1r_abs) + + with builder.if_else(in1i_abs_le_in1r_abs) as (then, otherwise): + with then: + r = builder.fdiv(in1i, in1r) + tmp0 = builder.fmul(in1i, r) + d = builder.fadd(in1r, tmp0) + inv_d = builder.fdiv(ONE, d) + minus_r = builder.fsub(ZERO, r) + out.real = inv_d + out.imag = builder.fmul(minus_r, inv_d) + with otherwise: + r = builder.fdiv(in1r, in1i) + tmp0 = builder.fmul(in1r, r) + d = builder.fadd(tmp0, in1i) + inv_d = builder.fdiv(ONE, d) + out.real = builder.fmul(r, inv_d) + out.imag = builder.fsub(ZERO, inv_d) + + return out._getvalue() + + +######################################################################## +# NumPy sin + +def np_real_sin_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.sin_impl(context, builder, sig, args) + + +def np_complex_sin_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return cmathimpl.sin_impl(context, builder, sig, args) + + +######################################################################## +# NumPy cos + +def np_real_cos_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.cos_impl(context, builder, sig, args) + + +def np_complex_cos_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return cmathimpl.cos_impl(context, builder, sig, args) + + +######################################################################## +# NumPy tan + +def np_real_tan_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.tan_impl(context, builder, sig, args) + + +######################################################################## +# NumPy asin + +def np_real_asin_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.asin_impl(context, builder, sig, args) + + +######################################################################## +# NumPy acos + +def np_real_acos_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.acos_impl(context, builder, sig, args) + + +######################################################################## +# NumPy atan + +def np_real_atan_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.atan_impl(context, builder, sig, args) + + +######################################################################## +# NumPy atan2 + +def np_real_atan2_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + return mathimpl.atan2_float_impl(context, builder, sig, args) + + +######################################################################## +# NumPy hypot + +def np_real_hypot_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + return mathimpl.hypot_float_impl(context, builder, sig, args) + + +######################################################################## +# NumPy sinh + +def np_real_sinh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.sinh_impl(context, builder, sig, args) + + +def np_complex_sinh_impl(context, builder, sig, args): + # npymath does not provide a complex sinh. The code in funcs.inc.src + # is translated here... + _check_arity_and_homogeneity(sig, args, 1) + + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty]*2) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + xr = x.real + xi = x.imag + + sxi = np_real_sin_impl(context, builder, fsig1, [xi]) + shxr = np_real_sinh_impl(context, builder, fsig1, [xr]) + cxi = np_real_cos_impl(context, builder, fsig1, [xi]) + chxr = np_real_cosh_impl(context, builder, fsig1, [xr]) + + out.real = builder.fmul(cxi, shxr) + out.imag = builder.fmul(sxi, chxr) + + return out._getvalue() + + +######################################################################## +# NumPy cosh + +def np_real_cosh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.cosh_impl(context, builder, sig, args) + + +def np_complex_cosh_impl(context, builder, sig, args): + # npymath does not provide a complex cosh. The code in funcs.inc.src + # is translated here... + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty]*2) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + xr = x.real + xi = x.imag + + cxi = np_real_cos_impl(context, builder, fsig1, [xi]) + chxr = np_real_cosh_impl(context, builder, fsig1, [xr]) + sxi = np_real_sin_impl(context, builder, fsig1, [xi]) + shxr = np_real_sinh_impl(context, builder, fsig1, [xr]) + + out.real = builder.fmul(cxi, chxr) + out.imag = builder.fmul(sxi, shxr) + + return out._getvalue() + + +######################################################################## +# NumPy tanh + +def np_real_tanh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.tanh_impl(context, builder, sig, args) + + +def np_complex_tanh_impl(context, builder, sig, args): + # npymath does not provide complex tan functions. The code + # in funcs.inc.src for tanh is translated here... + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + fty = ty.underlying_float + fsig1 = typing.signature(*[fty]*2) + ONE = context.get_constant(fty, 1.0) + x = context.make_complex(builder, ty, args[0]) + out = context.make_complex(builder, ty) + + xr = x.real + xi = x.imag + si = np_real_sin_impl(context, builder, fsig1, [xi]) + ci = np_real_cos_impl(context, builder, fsig1, [xi]) + shr = np_real_sinh_impl(context, builder, fsig1, [xr]) + chr_ = np_real_cosh_impl(context, builder, fsig1, [xr]) + rs = builder.fmul(ci, shr) + is_ = builder.fmul(si, chr_) + rc = builder.fmul(ci, chr_) + ic = builder.fmul(si, shr) # note: opposite sign from code in funcs.inc.src + sqr_rc = builder.fmul(rc, rc) + sqr_ic = builder.fmul(ic, ic) + d = builder.fadd(sqr_rc, sqr_ic) + inv_d = builder.fdiv(ONE, d) + rs_rc = builder.fmul(rs, rc) + is_ic = builder.fmul(is_, ic) + is_rc = builder.fmul(is_, rc) + rs_ic = builder.fmul(rs, ic) + numr = builder.fadd(rs_rc, is_ic) + numi = builder.fsub(is_rc, rs_ic) + out.real = builder.fmul(numr, inv_d) + out.imag = builder.fmul(numi, inv_d) + + return out._getvalue() + + +######################################################################## +# NumPy asinh + +def np_real_asinh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.asinh_impl(context, builder, sig, args) + + +######################################################################## +# NumPy acosh + +def np_real_acosh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.acosh_impl(context, builder, sig, args) + + +def np_complex_acosh_impl(context, builder, sig, args): + # npymath does not provide a complex acosh. The code in funcs.inc.src + # is translated here... + # log(x + sqrt(x+1) * sqrt(x-1)) + _check_arity_and_homogeneity(sig, args, 1) + + ty = sig.args[0] + csig2 = typing.signature(*[ty]*3) + + ONE = context.get_constant_generic(builder, ty, 1.0 + 0.0j) + x = args[0] + + x_plus_one = numbers.complex_add_impl(context, builder, csig2, [x, + ONE]) + x_minus_one = numbers.complex_sub_impl(context, builder, csig2, [x, + ONE]) + sqrt_x_plus_one = np_complex_sqrt_impl(context, builder, sig, [x_plus_one]) + sqrt_x_minus_one = np_complex_sqrt_impl(context, builder, sig, [x_minus_one]) + prod_sqrt = numbers.complex_mul_impl(context, builder, csig2, + [sqrt_x_plus_one, + sqrt_x_minus_one]) + log_arg = numbers.complex_add_impl(context, builder, csig2, [x, + prod_sqrt]) + + return np_complex_log_impl(context, builder, sig, [log_arg]) + + +######################################################################## +# NumPy atanh + +def np_real_atanh_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + return mathimpl.atanh_impl(context, builder, sig, args) + + +######################################################################## +# NumPy floor + +def np_real_floor_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + return mathimpl.call_fp_intrinsic(builder, 'llvm.floor', args) + + +######################################################################## +# NumPy ceil + +def np_real_ceil_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + return mathimpl.call_fp_intrinsic(builder, 'llvm.ceil', args) + + +######################################################################## +# NumPy trunc + +def np_real_trunc_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + return mathimpl.call_fp_intrinsic(builder, 'llvm.trunc', args) + + +######################################################################## +# NumPy fabs + +def np_real_fabs_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1) + + return mathimpl.call_fp_intrinsic(builder, 'llvm.fabs', args) + + +######################################################################## +# NumPy style predicates + +# For real and integer types rely on numbers... but complex ordering in +# NumPy is lexicographic (while Python does not provide ordering). +def np_complex_ge_impl(context, builder, sig, args): + # equivalent to macro CGE in NumPy's loops.c.src + # ((xr > yr && !npy_isnan(xi) && !npy_isnan(yi)) || (xr == yr && xi >= yi)) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_gt_yr = builder.fcmp_ordered('>', xr, yr) + no_nan_xi_yi = builder.fcmp_ordered('ord', xi, yi) + xr_eq_yr = builder.fcmp_ordered('==', xr, yr) + xi_ge_yi = builder.fcmp_ordered('>=', xi, yi) + first_term = builder.and_(xr_gt_yr, no_nan_xi_yi) + second_term = builder.and_(xr_eq_yr, xi_ge_yi) + return builder.or_(first_term, second_term) + + +def np_complex_le_impl(context, builder, sig, args): + # equivalent to macro CLE in NumPy's loops.c.src + # ((xr < yr && !npy_isnan(xi) && !npy_isnan(yi)) || (xr == yr && xi <= yi)) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_lt_yr = builder.fcmp_ordered('<', xr, yr) + no_nan_xi_yi = builder.fcmp_ordered('ord', xi, yi) + xr_eq_yr = builder.fcmp_ordered('==', xr, yr) + xi_le_yi = builder.fcmp_ordered('<=', xi, yi) + first_term = builder.and_(xr_lt_yr, no_nan_xi_yi) + second_term = builder.and_(xr_eq_yr, xi_le_yi) + return builder.or_(first_term, second_term) + + +def np_complex_gt_impl(context, builder, sig, args): + # equivalent to macro CGT in NumPy's loops.c.src + # ((xr > yr && !npy_isnan(xi) && !npy_isnan(yi)) || (xr == yr && xi > yi)) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_gt_yr = builder.fcmp_ordered('>', xr, yr) + no_nan_xi_yi = builder.fcmp_ordered('ord', xi, yi) + xr_eq_yr = builder.fcmp_ordered('==', xr, yr) + xi_gt_yi = builder.fcmp_ordered('>', xi, yi) + first_term = builder.and_(xr_gt_yr, no_nan_xi_yi) + second_term = builder.and_(xr_eq_yr, xi_gt_yi) + return builder.or_(first_term, second_term) + + +def np_complex_lt_impl(context, builder, sig, args): + # equivalent to macro CLT in NumPy's loops.c.src + # ((xr < yr && !npy_isnan(xi) && !npy_isnan(yi)) || (xr == yr && xi < yi)) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_lt_yr = builder.fcmp_ordered('<', xr, yr) + no_nan_xi_yi = builder.fcmp_ordered('ord', xi, yi) + xr_eq_yr = builder.fcmp_ordered('==', xr, yr) + xi_lt_yi = builder.fcmp_ordered('<', xi, yi) + first_term = builder.and_(xr_lt_yr, no_nan_xi_yi) + second_term = builder.and_(xr_eq_yr, xi_lt_yi) + return builder.or_(first_term, second_term) + + +def np_complex_eq_impl(context, builder, sig, args): + # equivalent to macro CEQ in NumPy's loops.c.src + # (xr == yr && xi == yi) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_eq_yr = builder.fcmp_ordered('==', xr, yr) + xi_eq_yi = builder.fcmp_ordered('==', xi, yi) + return builder.and_(xr_eq_yr, xi_eq_yi) + + +def np_complex_ne_impl(context, builder, sig, args): + # equivalent to macro CNE in NumPy's loops.c.src + # (xr != yr || xi != yi) + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + + ty = sig.args[0] + in1, in2 = [context.make_complex(builder, ty, value=arg) for arg in args] + xr = in1.real + xi = in1.imag + yr = in2.real + yi = in2.imag + + xr_ne_yr = builder.fcmp_unordered('!=', xr, yr) + xi_ne_yi = builder.fcmp_unordered('!=', xi, yi) + return builder.or_(xr_ne_yr, xi_ne_yi) + + +######################################################################## +# NumPy logical algebra + +# these are made generic for all types for now, assuming that +# cgutils.is_true works in the underlying types. + +def _complex_is_true(context, builder, ty, val): + complex_val = context.make_complex(builder, ty, value=val) + re_true = cgutils.is_true(builder, complex_val.real) + im_true = cgutils.is_true(builder, complex_val.imag) + return builder.or_(re_true, im_true) + + +def np_logical_and_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = cgutils.is_true(builder, args[0]) + b = cgutils.is_true(builder, args[1]) + return builder.and_(a, b) + + +def np_complex_logical_and_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = _complex_is_true(context, builder, sig.args[0], args[0]) + b = _complex_is_true(context, builder, sig.args[1], args[1]) + return builder.and_(a, b) + + +def np_logical_or_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = cgutils.is_true(builder, args[0]) + b = cgutils.is_true(builder, args[1]) + return builder.or_(a, b) + + +def np_complex_logical_or_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = _complex_is_true(context, builder, sig.args[0], args[0]) + b = _complex_is_true(context, builder, sig.args[1], args[1]) + return builder.or_(a, b) + + +def np_logical_xor_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = cgutils.is_true(builder, args[0]) + b = cgutils.is_true(builder, args[1]) + return builder.xor(a, b) + + +def np_complex_logical_xor_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2, return_type=types.boolean) + a = _complex_is_true(context, builder, sig.args[0], args[0]) + b = _complex_is_true(context, builder, sig.args[1], args[1]) + return builder.xor(a, b) + + +def np_logical_not_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return cgutils.is_false(builder, args[0]) + + +def np_complex_logical_not_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + a = _complex_is_true(context, builder, sig.args[0], args[0]) + return builder.not_(a) + +######################################################################## +# NumPy style max/min +# +# There are 2 different sets of functions to perform max and min in +# NumPy: maximum/minimum and fmax/fmin. +# Both differ in the way NaNs are handled, so the actual differences +# come in action only on float/complex numbers. The functions used for +# integers is shared. For booleans maximum is equivalent to or, and +# minimum is equivalent to and. Datetime support will go elsewhere. + +def np_int_smax_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + arg1, arg2 = args + arg1_sge_arg2 = builder.icmp_signed('>=', arg1, arg2) + return builder.select(arg1_sge_arg2, arg1, arg2) + + +def np_int_umax_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + arg1, arg2 = args + arg1_uge_arg2 = builder.icmp_unsigned('>=', arg1, arg2) + return builder.select(arg1_uge_arg2, arg1, arg2) + + +def np_real_maximum_impl(context, builder, sig, args): + # maximum prefers nan (tries to return a nan). + _check_arity_and_homogeneity(sig, args, 2) + + arg1, arg2 = args + arg1_nan = builder.fcmp_unordered('uno', arg1, arg1) + any_nan = builder.fcmp_unordered('uno', arg1, arg2) + nan_result = builder.select(arg1_nan, arg1, arg2) + + arg1_ge_arg2 = builder.fcmp_ordered('>=', arg1, arg2) + non_nan_result = builder.select(arg1_ge_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_real_fmax_impl(context, builder, sig, args): + # fmax prefers non-nan (tries to return a non-nan). + _check_arity_and_homogeneity(sig, args, 2) + + arg1, arg2 = args + arg2_nan = builder.fcmp_unordered('uno', arg2, arg2) + any_nan = builder.fcmp_unordered('uno', arg1, arg2) + nan_result = builder.select(arg2_nan, arg1, arg2) + + arg1_ge_arg2 = builder.fcmp_ordered('>=', arg1, arg2) + non_nan_result = builder.select(arg1_ge_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_complex_maximum_impl(context, builder, sig, args): + # maximum prefers nan (tries to return a nan). + # There is an extra caveat with complex numbers, as there is more + # than one type of nan. NumPy's docs state that the nan in the + # first argument is returned when both arguments are nans. + # If only one nan is found, that nan is returned. + _check_arity_and_homogeneity(sig, args, 2) + ty = sig.args[0] + bc_sig = typing.signature(types.boolean, ty) + bcc_sig = typing.signature(types.boolean, *[ty]*2) + arg1, arg2 = args + arg1_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg1]) + arg2_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg2]) + any_nan = builder.or_(arg1_nan, arg2_nan) + nan_result = builder.select(arg1_nan, arg1, arg2) + + arg1_ge_arg2 = np_complex_ge_impl(context, builder, bcc_sig, args) + non_nan_result = builder.select(arg1_ge_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_complex_fmax_impl(context, builder, sig, args): + # fmax prefers non-nan (tries to return a non-nan). + # There is an extra caveat with complex numbers, as there is more + # than one type of nan. NumPy's docs state that the nan in the + # first argument is returned when both arguments are nans. + _check_arity_and_homogeneity(sig, args, 2) + ty = sig.args[0] + bc_sig = typing.signature(types.boolean, ty) + bcc_sig = typing.signature(types.boolean, *[ty]*2) + arg1, arg2 = args + arg1_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg1]) + arg2_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg2]) + any_nan = builder.or_(arg1_nan, arg2_nan) + nan_result = builder.select(arg2_nan, arg1, arg2) + + arg1_ge_arg2 = np_complex_ge_impl(context, builder, bcc_sig, args) + non_nan_result = builder.select(arg1_ge_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_int_smin_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + arg1, arg2 = args + arg1_sle_arg2 = builder.icmp_signed('<=', arg1, arg2) + return builder.select(arg1_sle_arg2, arg1, arg2) + + +def np_int_umin_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + arg1, arg2 = args + arg1_ule_arg2 = builder.icmp_unsigned('<=', arg1, arg2) + return builder.select(arg1_ule_arg2, arg1, arg2) + + +def np_real_minimum_impl(context, builder, sig, args): + # minimum prefers nan (tries to return a nan). + _check_arity_and_homogeneity(sig, args, 2) + + arg1, arg2 = args + arg1_nan = builder.fcmp_unordered('uno', arg1, arg1) + any_nan = builder.fcmp_unordered('uno', arg1, arg2) + nan_result = builder.select(arg1_nan, arg1, arg2) + + arg1_le_arg2 = builder.fcmp_ordered('<=', arg1, arg2) + non_nan_result = builder.select(arg1_le_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_real_fmin_impl(context, builder, sig, args): + # fmin prefers non-nan (tries to return a non-nan). + _check_arity_and_homogeneity(sig, args, 2) + + arg1, arg2 = args + arg1_nan = builder.fcmp_unordered('uno', arg1, arg1) + any_nan = builder.fcmp_unordered('uno', arg1, arg2) + nan_result = builder.select(arg1_nan, arg2, arg1) + + arg1_le_arg2 = builder.fcmp_ordered('<=', arg1, arg2) + non_nan_result = builder.select(arg1_le_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_complex_minimum_impl(context, builder, sig, args): + # minimum prefers nan (tries to return a nan). + # There is an extra caveat with complex numbers, as there is more + # than one type of nan. NumPy's docs state that the nan in the + # first argument is returned when both arguments are nans. + # If only one nan is found, that nan is returned. + _check_arity_and_homogeneity(sig, args, 2) + ty = sig.args[0] + bc_sig = typing.signature(types.boolean, ty) + bcc_sig = typing.signature(types.boolean, *[ty]*2) + arg1, arg2 = args + arg1_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg1]) + arg2_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg2]) + any_nan = builder.or_(arg1_nan, arg2_nan) + nan_result = builder.select(arg1_nan, arg1, arg2) + + arg1_le_arg2 = np_complex_le_impl(context, builder, bcc_sig, args) + non_nan_result = builder.select(arg1_le_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +def np_complex_fmin_impl(context, builder, sig, args): + # fmin prefers non-nan (tries to return a non-nan). + # There is an extra caveat with complex numbers, as there is more + # than one type of nan. NumPy's docs state that the nan in the + # first argument is returned when both arguments are nans. + _check_arity_and_homogeneity(sig, args, 2) + ty = sig.args[0] + bc_sig = typing.signature(types.boolean, ty) + bcc_sig = typing.signature(types.boolean, *[ty]*2) + arg1, arg2 = args + arg1_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg1]) + arg2_nan = np_complex_isnan_impl(context, builder, bc_sig, [arg2]) + any_nan = builder.or_(arg1_nan, arg2_nan) + nan_result = builder.select(arg2_nan, arg1, arg2) + + arg1_le_arg2 = np_complex_le_impl(context, builder, bcc_sig, args) + non_nan_result = builder.select(arg1_le_arg2, arg1, arg2) + + return builder.select(any_nan, nan_result, non_nan_result) + + +######################################################################## +# NumPy floating point misc + +def np_int_isnan_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return cgutils.false_bit + + +def np_real_isnan_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return mathimpl.is_nan(builder, args[0]) + + +def np_complex_isnan_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + + x, = args + ty, = sig.args + complex_val = context.make_complex(builder, ty, value=x) + return cmathimpl.is_nan(builder, complex_val) + + +def np_int_isfinite_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return cgutils.true_bit + + +def np_datetime_isfinite_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return builder.icmp_unsigned('!=', args[0], npdatetime.NAT) + + +def np_datetime_isnat_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return builder.icmp_signed('==', args[0], npdatetime.NAT) + + +def np_real_isfinite_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return mathimpl.is_finite(builder, args[0]) + + +def np_complex_isfinite_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + x, = args + ty, = sig.args + complex_val = context.make_complex(builder, ty, value=x) + return cmathimpl.is_finite(builder, complex_val) + + +def np_int_isinf_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return cgutils.false_bit + + +def np_real_isinf_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + return mathimpl.is_inf(builder, args[0]) + + +def np_complex_isinf_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + x, = args + ty, = sig.args + complex_val = context.make_complex(builder, ty, value=x) + return cmathimpl.is_inf(builder, complex_val) + + +def np_real_signbit_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 1, return_type=types.boolean) + # there's no signbit intrinsic in LLVM, so just bitcast as int, mask the + # signbit and cmp against 0. + masks = { + types.float16: context.get_constant(types.uint16, 0x8000), + types.float32: context.get_constant(types.uint32, 0x80000000), + types.float64: context.get_constant(types.uint64, 0x8000000000000000), + } + arg_ty = sig.args[0] + arg_int_ty = getattr(types, f'uint{arg_ty.bitwidth}') + arg_ll_int_ty = context.get_value_type(arg_int_ty) + int_res = builder.and_(builder.bitcast(args[0], arg_ll_int_ty), + masks[arg_ty]) + bool_res = builder.icmp_unsigned('!=', int_res, int_res.type(0)) + return bool_res + + +def np_real_copysign_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + return mathimpl.copysign_float_impl(context, builder, sig, args) + +def np_real_nextafter_impl(context, builder, sig, args): + _check_arity_and_homogeneity(sig, args, 2) + + dispatch_table = { + types.float32: 'numba_nextafterf', + types.float64: 'numba_nextafter', + } + + return _dispatch_func_by_name_type(context, builder, sig, args, + dispatch_table, 'nextafter') + +def np_real_spacing_impl(context, builder, sig, args): + # This is different to how NumPy does it, NumPy has a specialisation of + # nextafter called _next, which is used. See: + # https://github.com/numpy/numpy/blob/12c2b7dd62fc0c14b81c8892ed5f4f59cc94d09c/numpy/core/src/npymath/ieee754.c.src#L32-L38 + # Numba elects to use `nextafter` for a similar behaviour to save + # translating this very involved function. Further, the NumPy comments note + # that there is a lot of redundancy present between the two. + _check_arity_and_homogeneity(sig, args, 1) + + dispatch_table = { + types.float32: 'numba_nextafterf', + types.float64: 'numba_nextafter', + } + + [ty] = sig.args + inner_sig = typing.signature(sig.return_type, ty, ty) + ll_ty = args[0].type + ll_inf = ll_ty(np.inf) + fnty = llvmlite.ir.FunctionType(ll_ty, [ll_ty, ll_ty]) + fn = cgutils.insert_pure_function(builder.module, fnty, + name='llvm.copysign') + ll_sinf = builder.call(fn, [ll_inf, args[0]]) + inner_args = args + [ll_sinf,] + nextafter = _dispatch_func_by_name_type(context, builder, inner_sig, + inner_args, dispatch_table, + 'nextafter') + return builder.fsub(nextafter, args[0]) + + +def np_real_ldexp_impl(context, builder, sig, args): + # this one is slightly different to other ufuncs. + # arguments are not homogeneous and second arg may come as + # an 'i' or an 'l'. + + # the function expects the second argument to be have a C int type + x1, x2 = args + ty1, ty2 = sig.args + # note that types.intc should be equivalent to int_ that is + # 'NumPy's default int') + x2 = context.cast(builder, x2, ty2, types.intc) + f_fi_sig = typing.signature(ty1, ty1, types.intc) + return mathimpl.ldexp_impl(context, builder, f_fi_sig, (x1, x2)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..43dd9b64ce0fe285e060868d4300398be7176039 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/npyimpl.py @@ -0,0 +1,876 @@ +""" +Implementation of functions in the Numpy package. +""" + + +import math +import sys +import itertools +from collections import namedtuple + +import llvmlite.ir as ir + +import numpy as np +import operator + +from numba.np import arrayobj, ufunc_db, numpy_support +from numba.np.ufunc.sigparse import parse_signature +from numba.core.imputils import (Registry, impl_ret_new_ref, force_error_model, impl_ret_borrowed) +from numba.core import typing, types, utils, cgutils, callconv, config +from numba.np.numpy_support import ( + ufunc_find_matching_loop, select_array_wrapper, from_dtype, _ufunc_loop_sig +) +from numba.np.arrayobj import _getitem_array_generic +from numba.core.typing import npydecl +from numba.core.extending import overload, intrinsic + +from numba.core import errors + +registry = Registry('npyimpl') + + +######################################################################## + +# In the way we generate code, ufuncs work with scalar as well as +# with array arguments. The following helper classes help dealing +# with scalar and array arguments in a regular way. +# +# In short, the classes provide a uniform interface. The interface +# handles the indexing of as many dimensions as the array may have. +# For scalars, all indexing is ignored and when the value is read, +# the scalar is returned. For arrays code for actual indexing is +# generated and reading performs the appropriate indirection. + +class _ScalarIndexingHelper(object): + def update_indices(self, loop_indices, name): + pass + + def as_values(self): + pass + + +class _ScalarHelper(object): + """Helper class to handle scalar arguments (and result). + Note that store_data is only used when generating code for + a scalar ufunc and to write the output value. + + For loading, the value is directly used without having any + kind of indexing nor memory backing it up. This is the use + for input arguments. + + For storing, a variable is created in the stack where the + value will be written. + + Note that it is not supported (as it is unneeded for our + current use-cases) reading back a stored value. This class + will always "load" the original value it got at its creation. + """ + def __init__(self, ctxt, bld, val, ty): + self.context = ctxt + self.builder = bld + self.val = val + self.base_type = ty + intpty = ctxt.get_value_type(types.intp) + self.shape = [ir.Constant(intpty, 1)] + + lty = ctxt.get_data_type(ty) if ty != types.boolean else ir.IntType(1) + self._ptr = cgutils.alloca_once(bld, lty) + + def create_iter_indices(self): + return _ScalarIndexingHelper() + + def load_data(self, indices): + return self.val + + def store_data(self, indices, val): + self.builder.store(val, self._ptr) + + @property + def return_val(self): + return self.builder.load(self._ptr) + + +class _ArrayIndexingHelper(namedtuple('_ArrayIndexingHelper', + ('array', 'indices'))): + def update_indices(self, loop_indices, name): + bld = self.array.builder + intpty = self.array.context.get_value_type(types.intp) + ONE = ir.Constant(ir.IntType(intpty.width), 1) + + # we are only interested in as many inner dimensions as dimensions + # the indexed array has (the outer dimensions are broadcast, so + # ignoring the outer indices produces the desired result. + indices = loop_indices[len(loop_indices) - len(self.indices):] + for src, dst, dim in zip(indices, self.indices, self.array.shape): + cond = bld.icmp_unsigned('>', dim, ONE) + with bld.if_then(cond): + bld.store(src, dst) + + def as_values(self): + """ + The indexing helper is built using alloca for each value, so it + actually contains pointers to the actual indices to load. Note + that update_indices assumes the same. This method returns the + indices as values + """ + bld = self.array.builder + return [bld.load(index) for index in self.indices] + + +class _ArrayHelper(namedtuple('_ArrayHelper', ('context', 'builder', + 'shape', 'strides', 'data', + 'layout', 'base_type', 'ndim', + 'return_val'))): + """Helper class to handle array arguments/result. + It provides methods to generate code loading/storing specific + items as well as support code for handling indices. + """ + def create_iter_indices(self): + intpty = self.context.get_value_type(types.intp) + ZERO = ir.Constant(ir.IntType(intpty.width), 0) + + indices = [] + for i in range(self.ndim): + x = cgutils.alloca_once(self.builder, ir.IntType(intpty.width)) + self.builder.store(ZERO, x) + indices.append(x) + return _ArrayIndexingHelper(self, indices) + + def _load_effective_address(self, indices): + return cgutils.get_item_pointer2(self.context, + self.builder, + data=self.data, + shape=self.shape, + strides=self.strides, + layout=self.layout, + inds=indices) + + def load_data(self, indices): + model = self.context.data_model_manager[self.base_type] + ptr = self._load_effective_address(indices) + return model.load_from_data_pointer(self.builder, ptr) + + def store_data(self, indices, value): + ctx = self.context + bld = self.builder + store_value = ctx.get_value_as_data(bld, self.base_type, value) + assert ctx.get_data_type(self.base_type) == store_value.type + bld.store(store_value, self._load_effective_address(indices)) + + +class _ArrayGUHelper(namedtuple('_ArrayHelper', ('context', 'builder', + 'shape', 'strides', 'data', + 'layout', 'base_type', 'ndim', + 'inner_arr_ty', 'is_input_arg'))): + """Helper class to handle array arguments/result. + It provides methods to generate code loading/storing specific + items as well as support code for handling indices. + + Contrary to _ArrayHelper, this class can create a view to a subarray + """ + def create_iter_indices(self): + intpty = self.context.get_value_type(types.intp) + ZERO = ir.Constant(ir.IntType(intpty.width), 0) + + indices = [] + for i in range(self.ndim - self.inner_arr_ty.ndim): + x = cgutils.alloca_once(self.builder, ir.IntType(intpty.width)) + self.builder.store(ZERO, x) + indices.append(x) + return _ArrayIndexingHelper(self, indices) + + def _load_effective_address(self, indices): + context = self.context + builder = self.builder + arr_ty = types.Array(self.base_type, self.ndim, self.layout) + arr = context.make_array(arr_ty)(context, builder, self.data) + + return cgutils.get_item_pointer2(context, + builder, + data=arr.data, + shape=self.shape, + strides=self.strides, + layout=self.layout, + inds=indices) + + def load_data(self, indices): + context, builder = self.context, self.builder + + if self.inner_arr_ty.ndim == 0 and self.is_input_arg: + # scalar case for input arguments + model = context.data_model_manager[self.base_type] + ptr = self._load_effective_address(indices) + return model.load_from_data_pointer(builder, ptr) + elif self.inner_arr_ty.ndim == 0 and not self.is_input_arg: + # Output arrays are handled as 1d with shape=(1,) when its + # signature represents a scalar. For instance: "(n),(m) -> ()" + intpty = context.get_value_type(types.intp) + one = intpty(1) + + fromty = types.Array(self.base_type, self.ndim, self.layout) + toty = types.Array(self.base_type, 1, self.layout) + itemsize = intpty(arrayobj.get_itemsize(context, fromty)) + + # create a view from the original ndarray to a 1d array + arr_from = self.context.make_array(fromty)(context, + builder, + self.data) + arr_to = self.context.make_array(toty)(context, builder) + arrayobj.populate_array( + arr_to, + data=self._load_effective_address(indices), + shape=cgutils.pack_array(builder, [one]), + strides=cgutils.pack_array(builder, [itemsize]), + itemsize=arr_from.itemsize, + meminfo=arr_from.meminfo, + parent=arr_from.parent) + return arr_to._getvalue() + else: + # generic case + # getitem n-dim array -> m-dim array, where N > M + index_types = (types.int64,) * (self.ndim - self.inner_arr_ty.ndim) + arrty = types.Array(self.base_type, self.ndim, self.layout) + arr = self.context.make_array(arrty)(context, builder, self.data) + res = _getitem_array_generic(context, builder, + self.inner_arr_ty, arrty, arr, + index_types, indices) + # NOTE: don't call impl_ret_borrowed since the caller doesn't handle + # references; but this is a borrow. + return res + + def guard_shape(self, loopshape): + inner_ndim = self.inner_arr_ty.ndim + def raise_impl(loop_shape, array_shape): + # This would in fact be a test for broadcasting. + # Broadcast would fail if, ignoring the core dimensions, the + # remaining ones are different than indices given by loop shape. + + remaining = len(array_shape) - inner_ndim + _raise = (remaining > len(loop_shape)) + if not _raise: + for i in range(remaining): + _raise |= (array_shape[i] != loop_shape[i]) + if _raise: + # Ideally we should call `np.broadcast_shapes` with loop and + # array shapes. But since broadcasting is not supported here, + # we just raise an error + # TODO: check why raising a dynamic exception here fails + raise ValueError('Loop and array shapes are incompatible') + + context, builder = self.context, self.builder + sig = types.none( + types.UniTuple(types.intp, len(loopshape)), + types.UniTuple(types.intp, len(self.shape)), + ) + tup = (context.make_tuple(builder, sig.args[0], loopshape), + context.make_tuple(builder, sig.args[1], self.shape)) + context.compile_internal(builder, raise_impl, sig, tup) + + def guard_match_core_dims(self, other: '_ArrayGUHelper', ndims: int): + # arguments with the same signature should match their core dimensions + # + # @guvectorize('(n,m), (n,m) -> (n)') + # def foo(x, y, res): + # ... + # + # x and y should have the same core (2D) dimensions + def raise_impl(self_shape, other_shape): + same = True + a, b = len(self_shape) - ndims, len(other_shape) - ndims + for i in range(ndims): + same &= self_shape[a + i] == other_shape[b + i] + if not same: + # NumPy raises the following: + # ValueError: gufunc: Input operand 1 has a mismatch in its + # core dimension 0, with gufunc signature (n),(n) -> () + # (size 3 is different from 2) + # But since we cannot raise a dynamic exception here, we just + # (try) something meaninful + msg = ('Operand has a mismatch in one of its core dimensions. ' + 'Please, check if all arguments to a @guvectorize ' + 'function have the same core dimensions.') + raise ValueError(msg) + + context, builder = self.context, self.builder + sig = types.none( + types.UniTuple(types.intp, len(self.shape)), + types.UniTuple(types.intp, len(other.shape)), + ) + tup = (context.make_tuple(builder, sig.args[0], self.shape), + context.make_tuple(builder, sig.args[1], other.shape),) + context.compile_internal(builder, raise_impl, sig, tup) + + +def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'): + """returns an instance of the appropriate Helper (either + _ScalarHelper or _ArrayHelper) class to handle the argument. + using the polymorphic interface of the Helper classes, scalar + and array cases can be handled with the same code""" + + # first un-Optional Optionals + if isinstance(tyinp, types.Optional): + oty = tyinp + tyinp = tyinp.type + inp = ctxt.cast(bld, inp, oty, tyinp) + + # then prepare the arg for a concrete instance + if isinstance(tyinp, types.ArrayCompatible): + ary = ctxt.make_array(tyinp)(ctxt, bld, inp) + shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim) + strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim) + return _ArrayHelper(ctxt, bld, shape, strides, ary.data, + tyinp.layout, tyinp.dtype, tyinp.ndim, inp) + elif (types.unliteral(tyinp) in types.number_domain | {types.boolean} + or isinstance(tyinp, types.scalars._NPDatetimeBase)): + return _ScalarHelper(ctxt, bld, inp, tyinp) + else: + raise NotImplementedError('unsupported type for {0}: {1}'.format(where, + str(tyinp))) + + +_broadcast_onto_sig = types.intp(types.intp, types.CPointer(types.intp), + types.intp, types.CPointer(types.intp)) + +def _broadcast_onto(src_ndim, src_shape, dest_ndim, dest_shape): + '''Low-level utility function used in calculating a shape for + an implicit output array. This function assumes that the + destination shape is an LLVM pointer to a C-style array that was + already initialized to a size of one along all axes. + + Returns an integer value: + >= 1 : Succeeded. Return value should equal the number of dimensions in + the destination shape. + 0 : Failed to broadcast because source shape is larger than the + destination shape (this case should be weeded out at type + checking). + < 0 : Failed to broadcast onto destination axis, at axis number == + -(return_value + 1). + ''' + if src_ndim > dest_ndim: + # This check should have been done during type checking, but + # let's be defensive anyway... + return 0 + else: + src_index = 0 + dest_index = dest_ndim - src_ndim + while src_index < src_ndim: + src_dim_size = src_shape[src_index] + dest_dim_size = dest_shape[dest_index] + # Check to see if we've already mutated the destination + # shape along this axis. + if dest_dim_size != 1: + # If we have mutated the destination shape already, + # then the source axis size must either be one, + # or the destination axis size. + if src_dim_size != dest_dim_size and src_dim_size != 1: + return -(dest_index + 1) + elif src_dim_size != 1: + # If the destination size is still its initial + dest_shape[dest_index] = src_dim_size + src_index += 1 + dest_index += 1 + return dest_index + +def _build_array(context, builder, array_ty, input_types, inputs): + """Utility function to handle allocation of an implicit output array + given the target context, builder, output array type, and a list of + _ArrayHelper instances. + """ + # First, strip optional types, ufunc loops are typed on concrete types + input_types = [x.type if isinstance(x, types.Optional) else x + for x in input_types] + + intp_ty = context.get_value_type(types.intp) + def make_intp_const(val): + return context.get_constant(types.intp, val) + + ZERO = make_intp_const(0) + ONE = make_intp_const(1) + + src_shape = cgutils.alloca_once(builder, intp_ty, array_ty.ndim, + "src_shape") + dest_ndim = make_intp_const(array_ty.ndim) + dest_shape = cgutils.alloca_once(builder, intp_ty, array_ty.ndim, + "dest_shape") + dest_shape_addrs = tuple(cgutils.gep_inbounds(builder, dest_shape, index) + for index in range(array_ty.ndim)) + + # Initialize the destination shape with all ones. + for dest_shape_addr in dest_shape_addrs: + builder.store(ONE, dest_shape_addr) + + # For each argument, try to broadcast onto the destination shape, + # mutating along any axis where the argument shape is not one and + # the destination shape is one. + for arg_number, arg in enumerate(inputs): + if not hasattr(arg, "ndim"): # Skip scalar arguments + continue + arg_ndim = make_intp_const(arg.ndim) + for index in range(arg.ndim): + builder.store(arg.shape[index], + cgutils.gep_inbounds(builder, src_shape, index)) + arg_result = context.compile_internal( + builder, _broadcast_onto, _broadcast_onto_sig, + [arg_ndim, src_shape, dest_ndim, dest_shape]) + with cgutils.if_unlikely(builder, + builder.icmp_signed('<', arg_result, ONE)): + msg = "unable to broadcast argument %d to output array" % ( + arg_number,) + + loc = errors.loc_info.get('loc', None) + if loc is not None: + msg += '\nFile "%s", line %d, ' % (loc.filename, loc.line) + + context.call_conv.return_user_exc(builder, ValueError, (msg,)) + + real_array_ty = array_ty.as_array + + dest_shape_tup = tuple(builder.load(dest_shape_addr) + for dest_shape_addr in dest_shape_addrs) + array_val = arrayobj._empty_nd_impl(context, builder, real_array_ty, + dest_shape_tup) + + # Get the best argument to call __array_wrap__ on + array_wrapper_index = select_array_wrapper(input_types) + array_wrapper_ty = input_types[array_wrapper_index] + try: + # __array_wrap__(source wrapped array, out array) -> out wrapped array + array_wrap = context.get_function('__array_wrap__', + array_ty(array_wrapper_ty, real_array_ty)) + except NotImplementedError: + # If it's the same priority as a regular array, assume we + # should use the allocated array unchanged. + if array_wrapper_ty.array_priority != types.Array.array_priority: + raise + out_val = array_val._getvalue() + else: + wrap_args = (inputs[array_wrapper_index].return_val, array_val._getvalue()) + out_val = array_wrap(builder, wrap_args) + + ndim = array_ty.ndim + shape = cgutils.unpack_tuple(builder, array_val.shape, ndim) + strides = cgutils.unpack_tuple(builder, array_val.strides, ndim) + return _ArrayHelper(context, builder, shape, strides, array_val.data, + array_ty.layout, array_ty.dtype, ndim, + out_val) + +# ufuncs either return a single result when nout == 1, else a tuple of results + +def _unpack_output_types(ufunc, sig): + if ufunc.nout == 1: + return [sig.return_type] + else: + return list(sig.return_type) + + +def _unpack_output_values(ufunc, builder, values): + if ufunc.nout == 1: + return [values] + else: + return cgutils.unpack_tuple(builder, values) + + +def _pack_output_values(ufunc, context, builder, typ, values): + if ufunc.nout == 1: + return values[0] + else: + return context.make_tuple(builder, typ, values) + + +def numpy_ufunc_kernel(context, builder, sig, args, ufunc, kernel_class): + # This is the code generator that builds all the looping needed + # to execute a numpy functions over several dimensions (including + # scalar cases). + # + # context - the code generation context + # builder - the code emitter + # sig - signature of the ufunc + # args - the args to the ufunc + # ufunc - the ufunc itself + # kernel_class - a code generating subclass of _Kernel that provides + + arguments = [_prepare_argument(context, builder, arg, tyarg) + for arg, tyarg in zip(args, sig.args)] + + if len(arguments) < ufunc.nin: + raise RuntimeError( + "Not enough inputs to {}, expected {} got {}" + .format(ufunc.__name__, ufunc.nin, len(arguments))) + + for out_i, ret_ty in enumerate(_unpack_output_types(ufunc, sig)): + if ufunc.nin + out_i >= len(arguments): + # this out argument is not provided + if isinstance(ret_ty, types.ArrayCompatible): + output = _build_array(context, builder, ret_ty, sig.args, arguments) + else: + output = _prepare_argument( + context, builder, + ir.Constant(context.get_value_type(ret_ty), None), ret_ty) + arguments.append(output) + elif context.enable_nrt: + # Incref the output + context.nrt.incref(builder, ret_ty, args[ufunc.nin + out_i]) + + inputs = arguments[:ufunc.nin] + outputs = arguments[ufunc.nin:] + assert len(outputs) == ufunc.nout + + outer_sig = _ufunc_loop_sig( + [a.base_type for a in outputs], + [a.base_type for a in inputs] + ) + kernel = kernel_class(context, builder, outer_sig) + intpty = context.get_value_type(types.intp) + + indices = [inp.create_iter_indices() for inp in inputs] + + # assume outputs are all the same size, which numpy requires + + loopshape = outputs[0].shape + + # count the number of C and F layout arrays, respectively + input_layouts = [inp.layout for inp in inputs + if isinstance(inp, _ArrayHelper)] + num_c_layout = len([x for x in input_layouts if x == 'C']) + num_f_layout = len([x for x in input_layouts if x == 'F']) + + # Only choose F iteration order if more arrays are in F layout. + # Default to C order otherwise. + # This is a best effort for performance. NumPy has more fancy logic that + # uses array iterators in non-trivial cases. + if num_f_layout > num_c_layout: + order = 'F' + else: + order = 'C' + + with cgutils.loop_nest(builder, loopshape, intp=intpty, order=order) as loop_indices: + vals_in = [] + for i, (index, arg) in enumerate(zip(indices, inputs)): + index.update_indices(loop_indices, i) + vals_in.append(arg.load_data(index.as_values())) + + vals_out = _unpack_output_values(ufunc, builder, kernel.generate(*vals_in)) + for val_out, output in zip(vals_out, outputs): + output.store_data(loop_indices, val_out) + + out = _pack_output_values(ufunc, context, builder, sig.return_type, [o.return_val for o in outputs]) + return impl_ret_new_ref(context, builder, sig.return_type, out) + + +def numpy_gufunc_kernel(context, builder, sig, args, ufunc, kernel_class): + arguments = [] + expected_ndims = kernel_class.dufunc.expected_ndims() + expected_ndims = expected_ndims[0] + expected_ndims[1] + is_input = [True] * ufunc.nin + [False] * ufunc.nout + for arg, ty, exp_ndim, is_inp in zip(args, sig.args, expected_ndims, is_input): # noqa: E501 + if isinstance(ty, types.ArrayCompatible): + # Create an array helper that iteration returns a subarray + # with ndim specified by "exp_ndim" + arr = context.make_array(ty)(context, builder, arg) + shape = cgutils.unpack_tuple(builder, arr.shape, ty.ndim) + strides = cgutils.unpack_tuple(builder, arr.strides, ty.ndim) + inner_arr_ty = ty.copy(ndim=exp_ndim) + ndim = ty.ndim + layout = ty.layout + base_type = ty.dtype + array_helper = _ArrayGUHelper(context, builder, + shape, strides, arg, + layout, base_type, ndim, + inner_arr_ty, is_inp) + arguments.append(array_helper) + else: + scalar_helper = _ScalarHelper(context, builder, arg, ty) + arguments.append(scalar_helper) + kernel = kernel_class(context, builder, sig) + + layouts = [arg.layout for arg in arguments + if isinstance(arg, _ArrayGUHelper)] + num_c_layout = len([x for x in layouts if x == 'C']) + num_f_layout = len([x for x in layouts if x == 'F']) + + # Only choose F iteration order if more arrays are in F layout. + # Default to C order otherwise. + # This is a best effort for performance. NumPy has more fancy logic that + # uses array iterators in non-trivial cases. + if num_f_layout > num_c_layout: + order = 'F' + else: + order = 'C' + + outputs = arguments[ufunc.nin:] + intpty = context.get_value_type(types.intp) + indices = [inp.create_iter_indices() for inp in arguments] + loopshape_ndim = outputs[0].ndim - outputs[0].inner_arr_ty.ndim + loopshape = outputs[0].shape[ : loopshape_ndim] + + _sig = parse_signature(ufunc.gufunc_builder.signature) + for (idx_a, sig_a), (idx_b, sig_b) in itertools.combinations( + zip(range(len(arguments)), + _sig[0] + _sig[1]), + r = 2 + ): + # For each pair of arguments, both inputs and outputs, must match their + # inner dimensions if their signatures are the same. + arg_a, arg_b = arguments[idx_a], arguments[idx_b] + if sig_a == sig_b and \ + all(isinstance(x, _ArrayGUHelper) for x in (arg_a, arg_b)): + arg_a, arg_b = arguments[idx_a], arguments[idx_b] + arg_a.guard_match_core_dims(arg_b, len(sig_a)) + + for arg in arguments[:ufunc.nin]: + if isinstance(arg, _ArrayGUHelper): + arg.guard_shape(loopshape) + + with cgutils.loop_nest(builder, + loopshape, + intp=intpty, + order=order) as loop_indices: + vals_in = [] + for i, (index, arg) in enumerate(zip(indices, arguments)): + index.update_indices(loop_indices, i) + vals_in.append(arg.load_data(index.as_values())) + + kernel.generate(*vals_in) + + +# Kernels are the code to be executed inside the multidimensional loop. +class _Kernel(object): + def __init__(self, context, builder, outer_sig): + self.context = context + self.builder = builder + self.outer_sig = outer_sig + + def cast(self, val, fromty, toty): + """Numpy uses cast semantics that are different from standard Python + (for example, it does allow casting from complex to float). + + This method acts as a patch to context.cast so that it allows + complex to real/int casts. + + """ + if (isinstance(fromty, types.Complex) and + not isinstance(toty, types.Complex)): + # attempt conversion of the real part to the specified type. + # note that NumPy issues a warning in this kind of conversions + newty = fromty.underlying_float + attr = self.context.get_getattr(fromty, 'real') + val = attr(self.context, self.builder, fromty, val, 'real') + fromty = newty + # let the regular cast do the rest... + + return self.context.cast(self.builder, val, fromty, toty) + + def generate(self, *args): + isig = self.inner_sig + osig = self.outer_sig + cast_args = [self.cast(val, inty, outty) + for val, inty, outty in + zip(args, osig.args, isig.args)] + if self.cres.objectmode: + func_type = self.context.call_conv.get_function_type( + types.pyobject, [types.pyobject] * len(isig.args)) + else: + func_type = self.context.call_conv.get_function_type( + isig.return_type, isig.args) + module = self.builder.block.function.module + entry_point = cgutils.get_or_insert_function( + module, func_type, + self.cres.fndesc.llvm_func_name) + entry_point.attributes.add("alwaysinline") + + _, res = self.context.call_conv.call_function( + self.builder, entry_point, isig.return_type, isig.args, + cast_args) + return self.cast(res, isig.return_type, osig.return_type) + + +def _ufunc_db_function(ufunc): + """Use the ufunc loop type information to select the code generation + function from the table provided by the dict_of_kernels. The dict + of kernels maps the loop identifier to a function with the + following signature: (context, builder, signature, args). + + The loop type information has the form 'AB->C'. The letters to the + left of '->' are the input types (specified as NumPy letter + types). The letters to the right of '->' are the output + types. There must be 'ufunc.nin' letters to the left of '->', and + 'ufunc.nout' letters to the right. + + For example, a binary float loop resulting in a float, will have + the following signature: 'ff->f'. + + A given ufunc implements many loops. The list of loops implemented + for a given ufunc can be accessed using the 'types' attribute in + the ufunc object. The NumPy machinery selects the first loop that + fits a given calling signature (in our case, what we call the + outer_sig). This logic is mimicked by 'ufunc_find_matching_loop'. + """ + + class _KernelImpl(_Kernel): + def __init__(self, context, builder, outer_sig): + super(_KernelImpl, self).__init__(context, builder, outer_sig) + loop = ufunc_find_matching_loop( + ufunc, outer_sig.args + tuple(_unpack_output_types(ufunc, outer_sig))) + self.fn = context.get_ufunc_info(ufunc).get(loop.ufunc_sig) + self.inner_sig = _ufunc_loop_sig(loop.outputs, loop.inputs) + + if self.fn is None: + msg = "Don't know how to lower ufunc '{0}' for loop '{1}'" + raise NotImplementedError(msg.format(ufunc.__name__, loop)) + + def generate(self, *args): + isig = self.inner_sig + osig = self.outer_sig + + cast_args = [self.cast(val, inty, outty) + for val, inty, outty in zip(args, osig.args, + isig.args)] + with force_error_model(self.context, 'numpy'): + res = self.fn(self.context, self.builder, isig, cast_args) + dmm = self.context.data_model_manager + res = dmm[isig.return_type].from_return(self.builder, res) + return self.cast(res, isig.return_type, osig.return_type) + + return _KernelImpl + + +################################################################################ +# Helper functions that register the ufuncs + +def register_ufunc_kernel(ufunc, kernel, lower): + def do_ufunc(context, builder, sig, args): + return numpy_ufunc_kernel(context, builder, sig, args, ufunc, kernel) + + _any = types.Any + in_args = (_any,) * ufunc.nin + + # Add a lowering for each out argument that is missing. + for n_explicit_out in range(ufunc.nout + 1): + out_args = (types.Array,) * n_explicit_out + lower(ufunc, *in_args, *out_args)(do_ufunc) + + return kernel + + +def register_unary_operator_kernel(operator, ufunc, kernel, lower, + inplace=False): + assert not inplace # are there any inplace unary operators? + def lower_unary_operator(context, builder, sig, args): + return numpy_ufunc_kernel(context, builder, sig, args, ufunc, kernel) + _arr_kind = types.Array + lower(operator, _arr_kind)(lower_unary_operator) + + +def register_binary_operator_kernel(op, ufunc, kernel, lower, inplace=False): + def lower_binary_operator(context, builder, sig, args): + return numpy_ufunc_kernel(context, builder, sig, args, ufunc, kernel) + + def lower_inplace_operator(context, builder, sig, args): + # The visible signature is (A, B) -> A + # The implementation's signature (with explicit output) + # is (A, B, A) -> A + args = tuple(args) + (args[0],) + sig = typing.signature(sig.return_type, *sig.args + (sig.args[0],)) + return numpy_ufunc_kernel(context, builder, sig, args, ufunc, kernel) + + _any = types.Any + _arr_kind = types.Array + formal_sigs = [(_arr_kind, _arr_kind), (_any, _arr_kind), (_arr_kind, _any)] + for sig in formal_sigs: + if not inplace: + lower(op, *sig)(lower_binary_operator) + else: + lower(op, *sig)(lower_inplace_operator) + + +################################################################################ +# Use the contents of ufunc_db to initialize the supported ufuncs + +@registry.lower(operator.pos, types.Array) +def array_positive_impl(context, builder, sig, args): + '''Lowering function for +(array) expressions. Defined here + (numba.targets.npyimpl) since the remaining array-operator + lowering functions are also registered in this module. + ''' + class _UnaryPositiveKernel(_Kernel): + def generate(self, *args): + [val] = args + return val + + return numpy_ufunc_kernel(context, builder, sig, args, np.positive, + _UnaryPositiveKernel) + + +def register_ufuncs(ufuncs, lower): + kernels = {} + for ufunc in ufuncs: + db_func = _ufunc_db_function(ufunc) + kernels[ufunc] = register_ufunc_kernel(ufunc, db_func, lower) + + for _op_map in (npydecl.NumpyRulesUnaryArrayOperator._op_map, + npydecl.NumpyRulesArrayOperator._op_map, + ): + for operator, ufunc_name in _op_map.items(): + ufunc = getattr(np, ufunc_name) + kernel = kernels[ufunc] + if ufunc.nin == 1: + register_unary_operator_kernel(operator, ufunc, kernel, lower) + elif ufunc.nin == 2: + register_binary_operator_kernel(operator, ufunc, kernel, lower) + else: + raise RuntimeError("There shouldn't be any non-unary or binary operators") + + for _op_map in (npydecl.NumpyRulesInplaceArrayOperator._op_map, + ): + for operator, ufunc_name in _op_map.items(): + ufunc = getattr(np, ufunc_name) + kernel = kernels[ufunc] + if ufunc.nin == 1: + register_unary_operator_kernel(operator, ufunc, kernel, lower, + inplace=True) + elif ufunc.nin == 2: + register_binary_operator_kernel(operator, ufunc, kernel, lower, + inplace=True) + else: + raise RuntimeError("There shouldn't be any non-unary or binary operators") + + +register_ufuncs(ufunc_db.get_ufuncs(), registry.lower) + + +@intrinsic +def _make_dtype_object(typingctx, desc): + """Given a string or NumberClass description *desc*, returns the dtype object. + """ + def from_nb_type(nb_type): + return_type = types.DType(nb_type) + sig = return_type(desc) + + def codegen(context, builder, signature, args): + # All dtype objects are dummy values in LLVM. + # They only exist in the type level. + return context.get_dummy_value() + + return sig, codegen + + if isinstance(desc, types.Literal): + # Convert the str description into np.dtype then to numba type. + nb_type = from_dtype(np.dtype(desc.literal_value)) + return from_nb_type(nb_type) + elif isinstance(desc, types.functions.NumberClass): + thestr = str(desc.dtype) + # Convert the str description into np.dtype then to numba type. + nb_type = from_dtype(np.dtype(thestr)) + return from_nb_type(nb_type) + +@overload(np.dtype) +def numpy_dtype(dtype): + """Provide an implementation so that numpy.dtype function can be lowered. + """ + if isinstance(dtype, (types.Literal, types.functions.NumberClass)): + def imp(dtype): + return _make_dtype_object(dtype) + return imp + else: + raise errors.NumbaTypeError( + 'unknown dtype descriptor: {}'.format(dtype)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/numpy_support.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/numpy_support.py new file mode 100644 index 0000000000000000000000000000000000000000..a8a9699b16bf6bb1f47b9075cbcb3a5aa5e43426 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/numpy_support.py @@ -0,0 +1,774 @@ +import collections +import ctypes +import re + +import numpy as np + +from numba.core import errors, types +from numba.core.typing.templates import signature +from numba.np import npdatetime_helpers +from numba.core.errors import TypingError + +# re-export +from numba.core.cgutils import is_nonelike # noqa: F401 + + +numpy_version = tuple(map(int, np.__version__.split('.')[:2])) + + +FROM_DTYPE = { + np.dtype('bool'): types.boolean, + np.dtype('int8'): types.int8, + np.dtype('int16'): types.int16, + np.dtype('int32'): types.int32, + np.dtype('int64'): types.int64, + + np.dtype('uint8'): types.uint8, + np.dtype('uint16'): types.uint16, + np.dtype('uint32'): types.uint32, + np.dtype('uint64'): types.uint64, + + np.dtype('float32'): types.float32, + np.dtype('float64'): types.float64, + np.dtype('float16'): types.float16, + np.dtype('complex64'): types.complex64, + np.dtype('complex128'): types.complex128, + + np.dtype(object): types.pyobject, +} + + +re_typestr = re.compile(r'[<>=\|]([a-z])(\d+)?$', re.I) +re_datetimestr = re.compile(r'[<>=\|]([mM])8?(\[([a-z]+)\])?$', re.I) + +sizeof_unicode_char = np.dtype('U1').itemsize + + +def _from_str_dtype(dtype): + m = re_typestr.match(dtype.str) + if not m: + raise errors.NumbaNotImplementedError(dtype) + groups = m.groups() + typecode = groups[0] + if typecode == 'U': + # unicode + if dtype.byteorder not in '=|': + raise errors.NumbaNotImplementedError("Does not support non-native " + "byteorder") + count = dtype.itemsize // sizeof_unicode_char + assert count == int(groups[1]), "Unicode char size mismatch" + return types.UnicodeCharSeq(count) + + elif typecode == 'S': + # char + count = dtype.itemsize + assert count == int(groups[1]), "Char size mismatch" + return types.CharSeq(count) + + else: + raise errors.NumbaNotImplementedError(dtype) + + +def _from_datetime_dtype(dtype): + m = re_datetimestr.match(dtype.str) + if not m: + raise errors.NumbaNotImplementedError(dtype) + groups = m.groups() + typecode = groups[0] + unit = groups[2] or '' + if typecode == 'm': + return types.NPTimedelta(unit) + elif typecode == 'M': + return types.NPDatetime(unit) + else: + raise errors.NumbaNotImplementedError(dtype) + + +def from_dtype(dtype): + """ + Return a Numba Type instance corresponding to the given Numpy *dtype*. + NumbaNotImplementedError is raised on unsupported Numpy dtypes. + """ + if type(dtype) is type and issubclass(dtype, np.generic): + dtype = np.dtype(dtype) + elif getattr(dtype, "fields", None) is not None: + return from_struct_dtype(dtype) + + try: + return FROM_DTYPE[dtype] + except KeyError: + pass + + try: + char = dtype.char + except AttributeError: + pass + else: + if char in 'SU': + return _from_str_dtype(dtype) + if char in 'mM': + return _from_datetime_dtype(dtype) + if char in 'V' and dtype.subdtype is not None: + subtype = from_dtype(dtype.subdtype[0]) + return types.NestedArray(subtype, dtype.shape) + + raise errors.NumbaNotImplementedError(dtype) + + +_as_dtype_letters = { + types.NPDatetime: 'M8', + types.NPTimedelta: 'm8', + types.CharSeq: 'S', + types.UnicodeCharSeq: 'U', +} + + +def as_dtype(nbtype): + """ + Return a numpy dtype instance corresponding to the given Numba type. + NumbaNotImplementedError is if no correspondence is known. + """ + nbtype = types.unliteral(nbtype) + if isinstance(nbtype, (types.Complex, types.Integer, types.Float)): + return np.dtype(str(nbtype)) + if isinstance(nbtype, (types.Boolean)): + return np.dtype('?') + if isinstance(nbtype, (types.NPDatetime, types.NPTimedelta)): + letter = _as_dtype_letters[type(nbtype)] + if nbtype.unit: + return np.dtype('%s[%s]' % (letter, nbtype.unit)) + else: + return np.dtype(letter) + if isinstance(nbtype, (types.CharSeq, types.UnicodeCharSeq)): + letter = _as_dtype_letters[type(nbtype)] + return np.dtype('%s%d' % (letter, nbtype.count)) + if isinstance(nbtype, types.Record): + return as_struct_dtype(nbtype) + if isinstance(nbtype, types.EnumMember): + return as_dtype(nbtype.dtype) + if isinstance(nbtype, types.npytypes.DType): + return as_dtype(nbtype.dtype) + if isinstance(nbtype, types.NumberClass): + return as_dtype(nbtype.dtype) + if isinstance(nbtype, types.NestedArray): + spec = (as_dtype(nbtype.dtype), tuple(nbtype.shape)) + return np.dtype(spec) + if isinstance(nbtype, types.PyObject): + return np.dtype(object) + + msg = f"{nbtype} cannot be represented as a NumPy dtype" + raise errors.NumbaNotImplementedError(msg) + + +def as_struct_dtype(rec): + """Convert Numba Record type to NumPy structured dtype + """ + assert isinstance(rec, types.Record) + names = [] + formats = [] + offsets = [] + titles = [] + # Fill the fields if they are not a title. + for k, t in rec.members: + if not rec.is_title(k): + names.append(k) + formats.append(as_dtype(t)) + offsets.append(rec.offset(k)) + titles.append(rec.fields[k].title) + + fields = { + 'names': names, + 'formats': formats, + 'offsets': offsets, + 'itemsize': rec.size, + 'titles': titles, + } + _check_struct_alignment(rec, fields) + return np.dtype(fields, align=rec.aligned) + + +def _check_struct_alignment(rec, fields): + """Check alignment compatibility with Numpy""" + if rec.aligned: + for k, dt in zip(fields['names'], fields['formats']): + llvm_align = rec.alignof(k) + npy_align = dt.alignment + if llvm_align is not None and npy_align != llvm_align: + msg = ( + 'NumPy is using a different alignment ({}) ' + 'than Numba/LLVM ({}) for {}. ' + 'This is likely a NumPy bug.' + ) + raise ValueError(msg.format(npy_align, llvm_align, dt)) + + +def map_arrayscalar_type(val): + if isinstance(val, np.generic): + # We can't blindly call np.dtype() as it loses information + # on some types, e.g. datetime64 and timedelta64. + dtype = val.dtype + else: + try: + dtype = np.dtype(type(val)) + except TypeError: + raise errors.NumbaNotImplementedError("no corresponding numpy " + "dtype for %r" % type(val)) + return from_dtype(dtype) + + +def is_array(val): + return isinstance(val, np.ndarray) + + +def map_layout(val): + if val.flags['C_CONTIGUOUS']: + layout = 'C' + elif val.flags['F_CONTIGUOUS']: + layout = 'F' + else: + layout = 'A' + return layout + + +def select_array_wrapper(inputs): + """ + Given the array-compatible input types to an operation (e.g. ufunc), + select the appropriate input for wrapping the operation output, + according to each input's __array_priority__. + + An index into *inputs* is returned. + """ + max_prio = float('-inf') + selected_index = None + for index, ty in enumerate(inputs): + # Ties are broken by choosing the first winner, as in Numpy + if (isinstance(ty, types.ArrayCompatible) and + ty.array_priority > max_prio): + selected_index = index + max_prio = ty.array_priority + + assert selected_index is not None + return selected_index + + +def resolve_output_type(context, inputs, formal_output): + """ + Given the array-compatible input types to an operation (e.g. ufunc), + and the operation's formal output type (a types.Array instance), + resolve the actual output type using the typing *context*. + + This uses a mechanism compatible with Numpy's __array_priority__ / + __array_wrap__. + """ + selected_input = inputs[select_array_wrapper(inputs)] + args = selected_input, formal_output + sig = context.resolve_function_type('__array_wrap__', args, {}) + if sig is None: + if selected_input.array_priority == types.Array.array_priority: + # If it's the same priority as a regular array, assume we + # should return the output unchanged. + # (we can't define __array_wrap__ explicitly for types.Buffer, + # as that would be inherited by most array-compatible objects) + return formal_output + raise errors.TypingError("__array_wrap__ failed for %s" % (args,)) + return sig.return_type + + +def supported_ufunc_loop(ufunc, loop): + """Return whether the *loop* for the *ufunc* is supported -in nopython-. + + *loop* should be a UFuncLoopSpec instance, and *ufunc* a numpy ufunc. + + For ufuncs implemented using the ufunc_db, it is supported if the ufunc_db + contains a lowering definition for 'loop' in the 'ufunc' entry. + + For other ufuncs, it is type based. The loop will be considered valid if it + only contains the following letter types: '?bBhHiIlLqQfd'. Note this is + legacy and when implementing new ufuncs the ufunc_db should be preferred, + as it allows for a more fine-grained incremental support. + """ + # NOTE: Assuming ufunc for the CPUContext + from numba.np import ufunc_db + loop_sig = loop.ufunc_sig + try: + # check if the loop has a codegen description in the + # ufunc_db. If so, we can proceed. + + # note that as of now not all ufuncs have an entry in the + # ufunc_db + supported_loop = loop_sig in ufunc_db.get_ufunc_info(ufunc) + except KeyError: + # for ufuncs not in ufunc_db, base the decision of whether the + # loop is supported on its types + loop_types = [x.char for x in loop.numpy_inputs + loop.numpy_outputs] + supported_types = '?bBhHiIlLqQfd' + # check if all the types involved in the ufunc loop are + # supported in this mode + supported_loop = all(t in supported_types for t in loop_types) + + return supported_loop + + +class UFuncLoopSpec(collections.namedtuple('_UFuncLoopSpec', + ('inputs', 'outputs', 'ufunc_sig'))): + """ + An object describing a ufunc loop's inner types. Properties: + - inputs: the inputs' Numba types + - outputs: the outputs' Numba types + - ufunc_sig: the string representing the ufunc's type signature, in + Numpy format (e.g. "ii->i") + """ + + __slots__ = () + + @property + def numpy_inputs(self): + return [as_dtype(x) for x in self.inputs] + + @property + def numpy_outputs(self): + return [as_dtype(x) for x in self.outputs] + + +def _ufunc_loop_sig(out_tys, in_tys): + if len(out_tys) == 1: + return signature(out_tys[0], *in_tys) + else: + return signature(types.Tuple(out_tys), *in_tys) + + +def ufunc_can_cast(from_, to, has_mixed_inputs, casting='safe'): + """ + A variant of np.can_cast() that can allow casting any integer to + any real or complex type, in case the operation has mixed-kind + inputs. + + For example we want `np.power(float32, int32)` to be computed using + SP arithmetic and return `float32`. + However, `np.sqrt(int32)` should use DP arithmetic and return `float64`. + """ + from_ = np.dtype(from_) + to = np.dtype(to) + if has_mixed_inputs and from_.kind in 'iu' and to.kind in 'cf': + # Decide that all integers can cast to any real or complex type. + return True + return np.can_cast(from_, to, casting) + + +def ufunc_find_matching_loop(ufunc, arg_types): + """Find the appropriate loop to be used for a ufunc based on the types + of the operands + + ufunc - The ufunc we want to check + arg_types - The tuple of arguments to the ufunc, including any + explicit output(s). + return value - A UFuncLoopSpec identifying the loop, or None + if no matching loop is found. + """ + + # Separate logical input from explicit output arguments + input_types = arg_types[:ufunc.nin] + output_types = arg_types[ufunc.nin:] + assert (len(input_types) == ufunc.nin) + + try: + np_input_types = [as_dtype(x) for x in input_types] + except errors.NumbaNotImplementedError: + return None + try: + np_output_types = [as_dtype(x) for x in output_types] + except errors.NumbaNotImplementedError: + return None + + # Whether the inputs are mixed integer / floating-point + has_mixed_inputs = ( + any(dt.kind in 'iu' for dt in np_input_types) and + any(dt.kind in 'cf' for dt in np_input_types)) + + def choose_types(numba_types, ufunc_letters): + """ + Return a list of Numba types representing *ufunc_letters*, + except when the letter designates a datetime64 or timedelta64, + in which case the type is taken from *numba_types*. + """ + assert len(ufunc_letters) >= len(numba_types) + types = [tp if letter in 'mM' else from_dtype(np.dtype(letter)) + for tp, letter in zip(numba_types, ufunc_letters)] + # Add missing types (presumably implicit outputs) + types += [from_dtype(np.dtype(letter)) + for letter in ufunc_letters[len(numba_types):]] + return types + + def set_output_dt_units(inputs, outputs, ufunc_inputs, ufunc_name): + """ + Sets the output unit of a datetime type based on the input units + + Timedelta is a special dtype that requires the time unit to be + specified (day, month, etc). Not every operation with timedelta inputs + leads to an output of timedelta output. However, for those that do, + the unit of output must be inferred based on the units of the inputs. + + At the moment this function takes care of two cases: + a) where all inputs are timedelta with the same unit (mm), and + therefore the output has the same unit. + This case is used for arr.sum, and for arr1+arr2 where all arrays + are timedeltas. + If in the future this needs to be extended to a case with mixed units, + the rules should be implemented in `npdatetime_helpers` and called + from this function to set the correct output unit. + b) where left operand is a timedelta, i.e. the "m?" case. This case + is used for division, eg timedelta / int. + + At the time of writing, Numba does not support addition of timedelta + and other types, so this function does not consider the case "?m", + i.e. where timedelta is the right operand to a non-timedelta left + operand. To extend it in the future, just add another elif clause. + """ + def make_specific(outputs, unit): + new_outputs = [] + for out in outputs: + if isinstance(out, types.NPTimedelta) and out.unit == "": + new_outputs.append(types.NPTimedelta(unit)) + else: + new_outputs.append(out) + return new_outputs + + def make_datetime_specific(outputs, dt_unit, td_unit): + new_outputs = [] + for out in outputs: + if isinstance(out, types.NPDatetime) and out.unit == "": + unit = npdatetime_helpers.combine_datetime_timedelta_units( + dt_unit, td_unit) + if unit is None: + raise TypingError(f"ufunc '{ufunc_name}' is not " + + "supported between " + + f"datetime64[{dt_unit}] " + + f"and timedelta64[{td_unit}]" + ) + new_outputs.append(types.NPDatetime(unit)) + else: + new_outputs.append(out) + return new_outputs + + if ufunc_inputs == 'mm': + if all(inp.unit == inputs[0].unit for inp in inputs): + # Case with operation on same units. Operations on different + # units not adjusted for now but might need to be + # added in the future + unit = inputs[0].unit + new_outputs = make_specific(outputs, unit) + else: + return outputs + return new_outputs + elif ufunc_inputs == 'mM': + # case where the left operand has timedelta type + # and the right operand has datetime + td_unit = inputs[0].unit + dt_unit = inputs[1].unit + return make_datetime_specific(outputs, dt_unit, td_unit) + + elif ufunc_inputs == 'Mm': + # case where the right operand has timedelta type + # and the left operand has datetime + dt_unit = inputs[0].unit + td_unit = inputs[1].unit + return make_datetime_specific(outputs, dt_unit, td_unit) + + elif ufunc_inputs[0] == 'm': + # case where the left operand has timedelta type + unit = inputs[0].unit + new_outputs = make_specific(outputs, unit) + return new_outputs + + # In NumPy, the loops are evaluated from first to last. The first one + # that is viable is the one used. One loop is viable if it is possible + # to cast every input operand to the one expected by the ufunc. + # Also under NumPy 1.10+ the output must be able to be cast back + # to a close enough type ("same_kind"). + + for candidate in ufunc.types: + ufunc_inputs = candidate[:ufunc.nin] + ufunc_outputs = candidate[-ufunc.nout:] if ufunc.nout else [] + + if 'e' in ufunc_inputs: + # Skip float16 arrays since we don't have implementation for them + continue + if 'O' in ufunc_inputs: + # Skip object arrays + continue + found = True + # Skip if any input or output argument is mismatching + for outer, inner in zip(np_input_types, ufunc_inputs): + # (outer is a dtype instance, inner is a type char) + if outer.char in 'mM' or inner in 'mM': + # For datetime64 and timedelta64, we want to retain + # precise typing (i.e. the units); therefore we look for + # an exact match. + if outer.char != inner: + found = False + break + elif not ufunc_can_cast(outer.char, inner, + has_mixed_inputs, 'safe'): + found = False + break + if found: + # Can we cast the inner result to the outer result type? + for outer, inner in zip(np_output_types, ufunc_outputs): + if (outer.char not in 'mM' and not + ufunc_can_cast(inner, outer.char, + has_mixed_inputs, 'same_kind')): + found = False + break + if found: + # Found: determine the Numba types for the loop's inputs and + # outputs. + try: + inputs = choose_types(input_types, ufunc_inputs) + outputs = choose_types(output_types, ufunc_outputs) + # if the left operand or both are timedeltas, or the first + # argument is datetime and the second argument is timedelta, + # then the output units need to be determined. + if ufunc_inputs[0] == 'm' or ufunc_inputs == 'Mm': + outputs = set_output_dt_units(inputs, outputs, + ufunc_inputs, ufunc.__name__) + + except errors.NumbaNotImplementedError: + # One of the selected dtypes isn't supported by Numba + # (e.g. float16), try other candidates + continue + else: + return UFuncLoopSpec(inputs, outputs, candidate) + + return None + + +def _is_aligned_struct(struct): + return struct.isalignedstruct + + +def from_struct_dtype(dtype): + """Convert a NumPy structured dtype to Numba Record type + """ + if dtype.hasobject: + msg = "dtypes that contain object are not supported." + raise errors.NumbaNotImplementedError(msg) + + fields = [] + for name, info in dtype.fields.items(): + # *info* may have 3 element + [elemdtype, offset] = info[:2] + title = info[2] if len(info) == 3 else None + + ty = from_dtype(elemdtype) + infos = { + 'type': ty, + 'offset': offset, + 'title': title, + } + fields.append((name, infos)) + + # Note: dtype.alignment is not consistent. + # It is different after passing into a recarray. + # recarray(N, dtype=mydtype).dtype.alignment != mydtype.alignment + size = dtype.itemsize + aligned = _is_aligned_struct(dtype) + + return types.Record(fields, size, aligned) + + +def _get_bytes_buffer(ptr, nbytes): + """ + Get a ctypes array of *nbytes* starting at *ptr*. + """ + if isinstance(ptr, ctypes.c_void_p): + ptr = ptr.value + arrty = ctypes.c_byte * nbytes + return arrty.from_address(ptr) + + +def _get_array_from_ptr(ptr, nbytes, dtype): + return np.frombuffer(_get_bytes_buffer(ptr, nbytes), dtype) + + +def carray(ptr, shape, dtype=None): + """ + Return a Numpy array view over the data pointed to by *ptr* with the + given *shape*, in C order. If *dtype* is given, it is used as the + array's dtype, otherwise the array's dtype is inferred from *ptr*'s type. + """ + from numba.core.typing.ctypes_utils import from_ctypes + + try: + # Use ctypes parameter protocol if available + ptr = ptr._as_parameter_ + except AttributeError: + pass + + # Normalize dtype, to accept e.g. "int64" or np.int64 + if dtype is not None: + dtype = np.dtype(dtype) + + if isinstance(ptr, ctypes.c_void_p): + if dtype is None: + raise TypeError("explicit dtype required for void* argument") + p = ptr + elif isinstance(ptr, ctypes._Pointer): + ptrty = from_ctypes(ptr.__class__) + assert isinstance(ptrty, types.CPointer) + ptr_dtype = as_dtype(ptrty.dtype) + if dtype is not None and dtype != ptr_dtype: + raise TypeError("mismatching dtype '%s' for pointer %s" + % (dtype, ptr)) + dtype = ptr_dtype + p = ctypes.cast(ptr, ctypes.c_void_p) + else: + raise TypeError("expected a ctypes pointer, got %r" % (ptr,)) + + nbytes = dtype.itemsize * np.prod(shape, dtype=np.intp) + return _get_array_from_ptr(p, nbytes, dtype).reshape(shape) + + +def farray(ptr, shape, dtype=None): + """ + Return a Numpy array view over the data pointed to by *ptr* with the + given *shape*, in Fortran order. If *dtype* is given, it is used as the + array's dtype, otherwise the array's dtype is inferred from *ptr*'s type. + """ + if not isinstance(shape, int): + shape = shape[::-1] + return carray(ptr, shape, dtype).T + + +def is_contiguous(dims, strides, itemsize): + """Is the given shape, strides, and itemsize of C layout? + + Note: The code is usable as a numba-compiled function + """ + nd = len(dims) + # Check and skip 1s or 0s in inner dims + innerax = nd - 1 + while innerax > -1 and dims[innerax] <= 1: + innerax -= 1 + + # Early exit if all axis are 1s or 0s + if innerax < 0: + return True + + # Check itemsize matches innermost stride + if itemsize != strides[innerax]: + return False + + # Check and skip 1s or 0s in outer dims + outerax = 0 + while outerax < innerax and dims[outerax] <= 1: + outerax += 1 + + # Check remaining strides to be contiguous + ax = innerax + while ax > outerax: + if strides[ax] * dims[ax] != strides[ax - 1]: + return False + ax -= 1 + return True + + +def is_fortran(dims, strides, itemsize): + """Is the given shape, strides, and itemsize of F layout? + + Note: The code is usable as a numba-compiled function + """ + nd = len(dims) + # Check and skip 1s or 0s in inner dims + firstax = 0 + while firstax < nd and dims[firstax] <= 1: + firstax += 1 + + # Early exit if all axis are 1s or 0s + if firstax >= nd: + return True + + # Check itemsize matches innermost stride + if itemsize != strides[firstax]: + return False + + # Check and skip 1s or 0s in outer dims + lastax = nd - 1 + while lastax > firstax and dims[lastax] <= 1: + lastax -= 1 + + # Check remaining strides to be contiguous + ax = firstax + while ax < lastax: + if strides[ax] * dims[ax] != strides[ax + 1]: + return False + ax += 1 + return True + + +def type_can_asarray(arr): + """ Returns True if the type of 'arr' is supported by the Numba `np.asarray` + implementation, False otherwise. + """ + + ok = (types.Array, types.Sequence, types.Tuple, types.StringLiteral, + types.Number, types.Boolean, types.containers.ListType) + + return isinstance(arr, ok) + + +def type_is_scalar(typ): + """ Returns True if the type of 'typ' is a scalar type, according to + NumPy rules. False otherwise. + https://numpy.org/doc/stable/reference/arrays.scalars.html#built-in-scalar-types + """ + + ok = (types.Boolean, types.Number, types.UnicodeType, types.StringLiteral, + types.NPTimedelta, types.NPDatetime) + return isinstance(typ, ok) + + +def check_is_integer(v, name): + """Raises TypingError if the value is not an integer.""" + if not isinstance(v, (int, types.Integer)): + raise TypingError('{} must be an integer'.format(name)) + + +def lt_floats(a, b): + # Adapted from NumPy commit 717c7acf which introduced the behavior of + # putting NaNs at the end. + # The code is later moved to numpy/core/src/npysort/npysort_common.h + # This info is gathered as of NumPy commit d8c09c50 + return a < b or (np.isnan(b) and not np.isnan(a)) + + +def lt_complex(a, b): + if np.isnan(a.real): + if np.isnan(b.real): + if np.isnan(a.imag): + return False + else: + if np.isnan(b.imag): + return True + else: + return a.imag < b.imag + else: + return False + + else: + if np.isnan(b.real): + return True + else: + if np.isnan(a.imag): + if np.isnan(b.imag): + return a.real < b.real + else: + return False + else: + if np.isnan(b.imag): + return True + else: + if a.real < b.real: + return True + elif a.real == b.real: + return a.imag < b.imag + return False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/ufunc_db.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/ufunc_db.py new file mode 100644 index 0000000000000000000000000000000000000000..a72642432ff7c041d9a8f5b6028b142548d03a2b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/np/ufunc_db.py @@ -0,0 +1,1211 @@ +"""This file contains information on how to translate different ufuncs +into numba. It is a database of different ufuncs and how each of its +loops maps to a function that implements the inner kernel of that ufunc +(the inner kernel being the per-element function). + +Use the function get_ufunc_info to get the information related to the +ufunc +""" + + +import numpy as np +import sys + +# this is lazily initialized to avoid circular imports +IS_WIN32 = sys.platform.startswith('win32') +numpy_version = tuple(map(int, np.__version__.split('.')[:2])) +_ufunc_db = None + + +def _lazy_init_db(): + global _ufunc_db + + if _ufunc_db is None: + _ufunc_db = {} + _fill_ufunc_db(_ufunc_db) + + +def get_ufuncs(): + """obtain a list of supported ufuncs in the db""" + _lazy_init_db() + return _ufunc_db.keys() + + +def get_ufunc_info(ufunc_key): + """get the lowering information for the ufunc with key ufunc_key. + + The lowering information is a dictionary that maps from a numpy + loop string (as given by the ufunc types attribute) to a function + that handles code generation for a scalar version of the ufunc + (that is, generates the "per element" operation"). + + raises a KeyError if the ufunc is not in the ufunc_db + """ + _lazy_init_db() + return _ufunc_db[ufunc_key] + + +def _fill_ufunc_db(ufunc_db): + # some of these imports would cause a problem of circular + # imports if done at global scope when importing the numba + # module. + from numba.np import npyfuncs + from numba.np.math import cmathimpl, mathimpl, numbers + from numba.np.numpy_support import numpy_version + + ufunc_db[np.isnat] = { + # datetime & timedelta + 'M->?': npyfuncs.np_datetime_isnat_impl, + 'm->?': npyfuncs.np_datetime_isnat_impl, + } + + ufunc_db[np.negative] = { + '?->?': numbers.int_invert_impl, + 'b->b': numbers.int_negate_impl, + 'B->B': numbers.int_negate_impl, + 'h->h': numbers.int_negate_impl, + 'H->H': numbers.int_negate_impl, + 'i->i': numbers.int_negate_impl, + 'I->I': numbers.int_negate_impl, + 'l->l': numbers.int_negate_impl, + 'L->L': numbers.int_negate_impl, + 'q->q': numbers.int_negate_impl, + 'Q->Q': numbers.int_negate_impl, + 'f->f': numbers.real_negate_impl, + 'd->d': numbers.real_negate_impl, + 'F->F': numbers.complex_negate_impl, + 'D->D': numbers.complex_negate_impl, + } + + ufunc_db[np.positive] = { + '?->?': numbers.int_positive_impl, + 'b->b': numbers.int_positive_impl, + 'B->B': numbers.int_positive_impl, + 'h->h': numbers.int_positive_impl, + 'H->H': numbers.int_positive_impl, + 'i->i': numbers.int_positive_impl, + 'I->I': numbers.int_positive_impl, + 'l->l': numbers.int_positive_impl, + 'L->L': numbers.int_positive_impl, + 'q->q': numbers.int_positive_impl, + 'Q->Q': numbers.int_positive_impl, + 'f->f': numbers.real_positive_impl, + 'd->d': numbers.real_positive_impl, + 'F->F': numbers.complex_positive_impl, + 'D->D': numbers.complex_positive_impl, + } + + ufunc_db[np.absolute] = { + '?->?': numbers.int_abs_impl, + 'b->b': numbers.int_abs_impl, + 'B->B': numbers.uint_abs_impl, + 'h->h': numbers.int_abs_impl, + 'H->H': numbers.uint_abs_impl, + 'i->i': numbers.int_abs_impl, + 'I->I': numbers.uint_abs_impl, + 'l->l': numbers.int_abs_impl, + 'L->L': numbers.uint_abs_impl, + 'q->q': numbers.int_abs_impl, + 'Q->Q': numbers.uint_abs_impl, + 'f->f': numbers.real_abs_impl, + 'd->d': numbers.real_abs_impl, + 'F->f': numbers.complex_abs_impl, + 'D->d': numbers.complex_abs_impl, + } + + ufunc_db[np.sign] = { + 'b->b': numbers.int_sign_impl, + 'B->B': numbers.int_sign_impl, + 'h->h': numbers.int_sign_impl, + 'H->H': numbers.int_sign_impl, + 'i->i': numbers.int_sign_impl, + 'I->I': numbers.int_sign_impl, + 'l->l': numbers.int_sign_impl, + 'L->L': numbers.int_sign_impl, + 'q->q': numbers.int_sign_impl, + 'Q->Q': numbers.int_sign_impl, + 'f->f': numbers.real_sign_impl, + 'd->d': numbers.real_sign_impl, + 'F->F': npyfuncs.np_complex_sign_impl, + 'D->D': npyfuncs.np_complex_sign_impl, + } + + ufunc_db[np.add] = { + '??->?': numbers.int_or_impl, + 'bb->b': numbers.int_add_impl, + 'BB->B': numbers.int_add_impl, + 'hh->h': numbers.int_add_impl, + 'HH->H': numbers.int_add_impl, + 'ii->i': numbers.int_add_impl, + 'II->I': numbers.int_add_impl, + 'll->l': numbers.int_add_impl, + 'LL->L': numbers.int_add_impl, + 'qq->q': numbers.int_add_impl, + 'QQ->Q': numbers.int_add_impl, + 'ff->f': numbers.real_add_impl, + 'dd->d': numbers.real_add_impl, + 'FF->F': numbers.complex_add_impl, + 'DD->D': numbers.complex_add_impl, + } + + ufunc_db[np.subtract] = { + '??->?': numbers.int_xor_impl, + 'bb->b': numbers.int_sub_impl, + 'BB->B': numbers.int_sub_impl, + 'hh->h': numbers.int_sub_impl, + 'HH->H': numbers.int_sub_impl, + 'ii->i': numbers.int_sub_impl, + 'II->I': numbers.int_sub_impl, + 'll->l': numbers.int_sub_impl, + 'LL->L': numbers.int_sub_impl, + 'qq->q': numbers.int_sub_impl, + 'QQ->Q': numbers.int_sub_impl, + 'ff->f': numbers.real_sub_impl, + 'dd->d': numbers.real_sub_impl, + 'FF->F': numbers.complex_sub_impl, + 'DD->D': numbers.complex_sub_impl, + } + + ufunc_db[np.multiply] = { + '??->?': numbers.int_and_impl, + 'bb->b': numbers.int_mul_impl, + 'BB->B': numbers.int_mul_impl, + 'hh->h': numbers.int_mul_impl, + 'HH->H': numbers.int_mul_impl, + 'ii->i': numbers.int_mul_impl, + 'II->I': numbers.int_mul_impl, + 'll->l': numbers.int_mul_impl, + 'LL->L': numbers.int_mul_impl, + 'qq->q': numbers.int_mul_impl, + 'QQ->Q': numbers.int_mul_impl, + 'ff->f': numbers.real_mul_impl, + 'dd->d': numbers.real_mul_impl, + 'FF->F': numbers.complex_mul_impl, + 'DD->D': numbers.complex_mul_impl, + } + + if np.divide != np.true_divide: + ufunc_db[np.divide] = { + 'bb->b': npyfuncs.np_int_sdiv_impl, + 'BB->B': npyfuncs.np_int_udiv_impl, + 'hh->h': npyfuncs.np_int_sdiv_impl, + 'HH->H': npyfuncs.np_int_udiv_impl, + 'ii->i': npyfuncs.np_int_sdiv_impl, + 'II->I': npyfuncs.np_int_udiv_impl, + 'll->l': npyfuncs.np_int_sdiv_impl, + 'LL->L': npyfuncs.np_int_udiv_impl, + 'qq->q': npyfuncs.np_int_sdiv_impl, + 'QQ->Q': npyfuncs.np_int_udiv_impl, + 'ff->f': npyfuncs.np_real_div_impl, + 'dd->d': npyfuncs.np_real_div_impl, + 'FF->F': npyfuncs.np_complex_div_impl, + 'DD->D': npyfuncs.np_complex_div_impl, + } + + ufunc_db[np.true_divide] = { + 'bb->d': npyfuncs.np_int_truediv_impl, + 'BB->d': npyfuncs.np_int_truediv_impl, + 'hh->d': npyfuncs.np_int_truediv_impl, + 'HH->d': npyfuncs.np_int_truediv_impl, + 'ii->d': npyfuncs.np_int_truediv_impl, + 'II->d': npyfuncs.np_int_truediv_impl, + 'll->d': npyfuncs.np_int_truediv_impl, + 'LL->d': npyfuncs.np_int_truediv_impl, + 'qq->d': npyfuncs.np_int_truediv_impl, + 'QQ->d': npyfuncs.np_int_truediv_impl, + 'ff->f': npyfuncs.np_real_div_impl, + 'dd->d': npyfuncs.np_real_div_impl, + 'FF->F': npyfuncs.np_complex_div_impl, + 'DD->D': npyfuncs.np_complex_div_impl, + } + + ufunc_db[np.floor_divide] = { + 'bb->b': npyfuncs.np_int_sdiv_impl, + 'BB->B': npyfuncs.np_int_udiv_impl, + 'hh->h': npyfuncs.np_int_sdiv_impl, + 'HH->H': npyfuncs.np_int_udiv_impl, + 'ii->i': npyfuncs.np_int_sdiv_impl, + 'II->I': npyfuncs.np_int_udiv_impl, + 'll->l': npyfuncs.np_int_sdiv_impl, + 'LL->L': npyfuncs.np_int_udiv_impl, + 'qq->q': npyfuncs.np_int_sdiv_impl, + 'QQ->Q': npyfuncs.np_int_udiv_impl, + 'ff->f': npyfuncs.np_real_floor_div_impl, + 'dd->d': npyfuncs.np_real_floor_div_impl, + } + + ufunc_db[np.remainder] = { + 'bb->b': npyfuncs.np_int_srem_impl, + 'BB->B': npyfuncs.np_int_urem_impl, + 'hh->h': npyfuncs.np_int_srem_impl, + 'HH->H': npyfuncs.np_int_urem_impl, + 'ii->i': npyfuncs.np_int_srem_impl, + 'II->I': npyfuncs.np_int_urem_impl, + 'll->l': npyfuncs.np_int_srem_impl, + 'LL->L': npyfuncs.np_int_urem_impl, + 'qq->q': npyfuncs.np_int_srem_impl, + 'QQ->Q': npyfuncs.np_int_urem_impl, + 'ff->f': npyfuncs.np_real_mod_impl, + 'dd->d': npyfuncs.np_real_mod_impl, + } + + ufunc_db[np.divmod] = { + 'bb->bb': npyfuncs.np_int_sdivrem_impl, + 'BB->BB': npyfuncs.np_int_udivrem_impl, + 'hh->hh': npyfuncs.np_int_sdivrem_impl, + 'HH->HH': npyfuncs.np_int_udivrem_impl, + 'ii->ii': npyfuncs.np_int_sdivrem_impl, + 'II->II': npyfuncs.np_int_udivrem_impl, + 'll->ll': npyfuncs.np_int_sdivrem_impl, + 'LL->LL': npyfuncs.np_int_udivrem_impl, + 'qq->qq': npyfuncs.np_int_sdivrem_impl, + 'QQ->QQ': npyfuncs.np_int_udivrem_impl, + 'ff->ff': npyfuncs.np_real_divmod_impl, + 'dd->dd': npyfuncs.np_real_divmod_impl, + } + + ufunc_db[np.fmod] = { + 'bb->b': npyfuncs.np_int_fmod_impl, + 'BB->B': npyfuncs.np_int_fmod_impl, + 'hh->h': npyfuncs.np_int_fmod_impl, + 'HH->H': npyfuncs.np_int_fmod_impl, + 'ii->i': npyfuncs.np_int_fmod_impl, + 'II->I': npyfuncs.np_int_fmod_impl, + 'll->l': npyfuncs.np_int_fmod_impl, + 'LL->L': npyfuncs.np_int_fmod_impl, + 'qq->q': npyfuncs.np_int_fmod_impl, + 'QQ->Q': npyfuncs.np_int_fmod_impl, + 'ff->f': npyfuncs.np_real_fmod_impl, + 'dd->d': npyfuncs.np_real_fmod_impl, + } + + ufunc_db[np.logaddexp] = { + 'ff->f': npyfuncs.np_real_logaddexp_impl, + 'dd->d': npyfuncs.np_real_logaddexp_impl, + } + + ufunc_db[np.logaddexp2] = { + 'ff->f': npyfuncs.np_real_logaddexp2_impl, + 'dd->d': npyfuncs.np_real_logaddexp2_impl, + } + + ufunc_db[np.power] = { + 'bb->b': numbers.int_power_impl, + 'BB->B': numbers.int_power_impl, + 'hh->h': numbers.int_power_impl, + 'HH->H': numbers.int_power_impl, + 'ii->i': numbers.int_power_impl, + 'II->I': numbers.int_power_impl, + 'll->l': numbers.int_power_impl, + 'LL->L': numbers.int_power_impl, + 'qq->q': numbers.int_power_impl, + 'QQ->Q': numbers.int_power_impl, + # XXX we would like to use `int_power_impl` for real ** integer + # as well (for better performance), but the current ufunc typing + # rules forbid that + 'ff->f': numbers.real_power_impl, + 'dd->d': numbers.real_power_impl, + 'FF->F': npyfuncs.np_complex_power_impl, + 'DD->D': npyfuncs.np_complex_power_impl, + } + + ufunc_db[np.float_power] = { + 'ff->f': npyfuncs.real_float_power_impl, + 'dd->d': npyfuncs.real_float_power_impl, + 'FF->F': npyfuncs.np_complex_float_power_impl, + 'DD->D': npyfuncs.np_complex_float_power_impl, + } + + ufunc_db[np.gcd] = { + 'bb->b': npyfuncs.np_gcd_impl, + 'BB->B': npyfuncs.np_gcd_impl, + 'hh->h': npyfuncs.np_gcd_impl, + 'HH->H': npyfuncs.np_gcd_impl, + 'ii->i': npyfuncs.np_gcd_impl, + 'II->I': npyfuncs.np_gcd_impl, + 'll->l': npyfuncs.np_gcd_impl, + 'LL->L': npyfuncs.np_gcd_impl, + 'qq->q': npyfuncs.np_gcd_impl, + 'QQ->Q': npyfuncs.np_gcd_impl, + } + + ufunc_db[np.lcm] = { + 'bb->b': npyfuncs.np_lcm_impl, + 'BB->B': npyfuncs.np_lcm_impl, + 'hh->h': npyfuncs.np_lcm_impl, + 'HH->H': npyfuncs.np_lcm_impl, + 'ii->i': npyfuncs.np_lcm_impl, + 'II->I': npyfuncs.np_lcm_impl, + 'll->l': npyfuncs.np_lcm_impl, + 'LL->L': npyfuncs.np_lcm_impl, + 'qq->q': npyfuncs.np_lcm_impl, + 'QQ->Q': npyfuncs.np_lcm_impl, + } + + ufunc_db[np.rint] = { + 'f->f': npyfuncs.np_real_rint_impl, + 'd->d': npyfuncs.np_real_rint_impl, + 'F->F': npyfuncs.np_complex_rint_impl, + 'D->D': npyfuncs.np_complex_rint_impl, + } + + ufunc_db[np.conjugate] = { + 'b->b': numbers.real_conjugate_impl, + 'B->B': numbers.real_conjugate_impl, + 'h->h': numbers.real_conjugate_impl, + 'H->H': numbers.real_conjugate_impl, + 'i->i': numbers.real_conjugate_impl, + 'I->I': numbers.real_conjugate_impl, + 'l->l': numbers.real_conjugate_impl, + 'L->L': numbers.real_conjugate_impl, + 'q->q': numbers.real_conjugate_impl, + 'Q->Q': numbers.real_conjugate_impl, + 'f->f': numbers.real_conjugate_impl, + 'd->d': numbers.real_conjugate_impl, + 'F->F': numbers.complex_conjugate_impl, + 'D->D': numbers.complex_conjugate_impl, + } + + ufunc_db[np.exp] = { + 'f->f': npyfuncs.np_real_exp_impl, + 'd->d': npyfuncs.np_real_exp_impl, + 'F->F': npyfuncs.np_complex_exp_impl, + 'D->D': npyfuncs.np_complex_exp_impl, + } + + ufunc_db[np.exp2] = { + 'f->f': npyfuncs.np_real_exp2_impl, + 'd->d': npyfuncs.np_real_exp2_impl, + 'F->F': npyfuncs.np_complex_exp2_impl, + 'D->D': npyfuncs.np_complex_exp2_impl, + } + + ufunc_db[np.log] = { + 'f->f': npyfuncs.np_real_log_impl, + 'd->d': npyfuncs.np_real_log_impl, + 'F->F': npyfuncs.np_complex_log_impl, + 'D->D': npyfuncs.np_complex_log_impl, + } + + ufunc_db[np.log2] = { + 'f->f': npyfuncs.np_real_log2_impl, + 'd->d': npyfuncs.np_real_log2_impl, + 'F->F': npyfuncs.np_complex_log2_impl, + 'D->D': npyfuncs.np_complex_log2_impl, + } + + ufunc_db[np.log10] = { + 'f->f': npyfuncs.np_real_log10_impl, + 'd->d': npyfuncs.np_real_log10_impl, + 'F->F': npyfuncs.np_complex_log10_impl, + 'D->D': npyfuncs.np_complex_log10_impl, + } + + ufunc_db[np.expm1] = { + 'f->f': npyfuncs.np_real_expm1_impl, + 'd->d': npyfuncs.np_real_expm1_impl, + 'F->F': npyfuncs.np_complex_expm1_impl, + 'D->D': npyfuncs.np_complex_expm1_impl, + } + + ufunc_db[np.log1p] = { + 'f->f': npyfuncs.np_real_log1p_impl, + 'd->d': npyfuncs.np_real_log1p_impl, + 'F->F': npyfuncs.np_complex_log1p_impl, + 'D->D': npyfuncs.np_complex_log1p_impl, + } + + ufunc_db[np.sqrt] = { + 'f->f': npyfuncs.np_real_sqrt_impl, + 'd->d': npyfuncs.np_real_sqrt_impl, + 'F->F': npyfuncs.np_complex_sqrt_impl, + 'D->D': npyfuncs.np_complex_sqrt_impl, + } + + ufunc_db[np.square] = { + 'b->b': npyfuncs.np_int_square_impl, + 'B->B': npyfuncs.np_int_square_impl, + 'h->h': npyfuncs.np_int_square_impl, + 'H->H': npyfuncs.np_int_square_impl, + 'i->i': npyfuncs.np_int_square_impl, + 'I->I': npyfuncs.np_int_square_impl, + 'l->l': npyfuncs.np_int_square_impl, + 'L->L': npyfuncs.np_int_square_impl, + 'q->q': npyfuncs.np_int_square_impl, + 'Q->Q': npyfuncs.np_int_square_impl, + 'f->f': npyfuncs.np_real_square_impl, + 'd->d': npyfuncs.np_real_square_impl, + 'F->F': npyfuncs.np_complex_square_impl, + 'D->D': npyfuncs.np_complex_square_impl, + } + + ufunc_db[np.cbrt] = { + 'f->f': npyfuncs.np_real_cbrt_impl, + 'd->d': npyfuncs.np_real_cbrt_impl, + } + + ufunc_db[np.reciprocal] = { + 'b->b': npyfuncs.np_int_reciprocal_impl, + 'B->B': npyfuncs.np_int_reciprocal_impl, + 'h->h': npyfuncs.np_int_reciprocal_impl, + 'H->H': npyfuncs.np_int_reciprocal_impl, + 'i->i': npyfuncs.np_int_reciprocal_impl, + 'I->I': npyfuncs.np_int_reciprocal_impl, + 'l->l': npyfuncs.np_int_reciprocal_impl, + 'L->L': npyfuncs.np_int_reciprocal_impl, + 'q->q': npyfuncs.np_int_reciprocal_impl, + 'Q->Q': npyfuncs.np_int_reciprocal_impl, + 'f->f': npyfuncs.np_real_reciprocal_impl, + 'd->d': npyfuncs.np_real_reciprocal_impl, + 'F->F': npyfuncs.np_complex_reciprocal_impl, + 'D->D': npyfuncs.np_complex_reciprocal_impl, + } + + ufunc_db[np.sin] = { + 'f->f': npyfuncs.np_real_sin_impl, + 'd->d': npyfuncs.np_real_sin_impl, + 'F->F': npyfuncs.np_complex_sin_impl, + 'D->D': npyfuncs.np_complex_sin_impl, + } + + ufunc_db[np.cos] = { + 'f->f': npyfuncs.np_real_cos_impl, + 'd->d': npyfuncs.np_real_cos_impl, + 'F->F': npyfuncs.np_complex_cos_impl, + 'D->D': npyfuncs.np_complex_cos_impl, + } + + tan_impl = cmathimpl.tan_impl + + ufunc_db[np.tan] = { + 'f->f': npyfuncs.np_real_tan_impl, + 'd->d': npyfuncs.np_real_tan_impl, + 'F->F': tan_impl, + 'D->D': tan_impl, + } + + arcsin_impl = cmathimpl.asin_impl + + ufunc_db[np.arcsin] = { + 'f->f': npyfuncs.np_real_asin_impl, + 'd->d': npyfuncs.np_real_asin_impl, + 'F->F': arcsin_impl, + 'D->D': arcsin_impl, + } + + ufunc_db[np.arccos] = { + 'f->f': npyfuncs.np_real_acos_impl, + 'd->d': npyfuncs.np_real_acos_impl, + 'F->F': cmathimpl.acos_impl, + 'D->D': cmathimpl.acos_impl, + } + + arctan_impl = cmathimpl.atan_impl + + ufunc_db[np.arctan] = { + 'f->f': npyfuncs.np_real_atan_impl, + 'd->d': npyfuncs.np_real_atan_impl, + 'F->F': arctan_impl, + 'D->D': arctan_impl, + } + + ufunc_db[np.arctan2] = { + 'ff->f': npyfuncs.np_real_atan2_impl, + 'dd->d': npyfuncs.np_real_atan2_impl, + } + + ufunc_db[np.hypot] = { + 'ff->f': npyfuncs.np_real_hypot_impl, + 'dd->d': npyfuncs.np_real_hypot_impl, + } + + ufunc_db[np.sinh] = { + 'f->f': npyfuncs.np_real_sinh_impl, + 'd->d': npyfuncs.np_real_sinh_impl, + 'F->F': npyfuncs.np_complex_sinh_impl, + 'D->D': npyfuncs.np_complex_sinh_impl, + } + + ufunc_db[np.cosh] = { + 'f->f': npyfuncs.np_real_cosh_impl, + 'd->d': npyfuncs.np_real_cosh_impl, + 'F->F': npyfuncs.np_complex_cosh_impl, + 'D->D': npyfuncs.np_complex_cosh_impl, + } + + ufunc_db[np.tanh] = { + 'f->f': npyfuncs.np_real_tanh_impl, + 'd->d': npyfuncs.np_real_tanh_impl, + 'F->F': npyfuncs.np_complex_tanh_impl, + 'D->D': npyfuncs.np_complex_tanh_impl, + } + + arcsinh_impl = cmathimpl.asinh_impl + + ufunc_db[np.arcsinh] = { + 'f->f': npyfuncs.np_real_asinh_impl, + 'd->d': npyfuncs.np_real_asinh_impl, + 'F->F': arcsinh_impl, + 'D->D': arcsinh_impl, + } + + ufunc_db[np.arccosh] = { + 'f->f': npyfuncs.np_real_acosh_impl, + 'd->d': npyfuncs.np_real_acosh_impl, + 'F->F': npyfuncs.np_complex_acosh_impl, + 'D->D': npyfuncs.np_complex_acosh_impl, + } + + arctanh_impl = cmathimpl.atanh_impl + + ufunc_db[np.arctanh] = { + 'f->f': npyfuncs.np_real_atanh_impl, + 'd->d': npyfuncs.np_real_atanh_impl, + 'F->F': arctanh_impl, + 'D->D': arctanh_impl, + } + + ufunc_db[np.deg2rad] = { + 'f->f': mathimpl.radians_float_impl, + 'd->d': mathimpl.radians_float_impl, + } + + ufunc_db[np.radians] = ufunc_db[np.deg2rad] + + ufunc_db[np.rad2deg] = { + 'f->f': mathimpl.degrees_float_impl, + 'd->d': mathimpl.degrees_float_impl, + } + + ufunc_db[np.degrees] = ufunc_db[np.rad2deg] + + ufunc_db[np.floor] = { + 'f->f': npyfuncs.np_real_floor_impl, + 'd->d': npyfuncs.np_real_floor_impl, + } + if numpy_version >= (2, 1): + ufunc_db[np.floor].update({ + '?->?': numbers.identity_impl, + 'b->b': numbers.identity_impl, + 'B->B': numbers.identity_impl, + 'h->h': numbers.identity_impl, + 'H->H': numbers.identity_impl, + 'i->i': numbers.identity_impl, + 'I->I': numbers.identity_impl, + 'l->l': numbers.identity_impl, + 'L->L': numbers.identity_impl, + 'q->q': numbers.identity_impl, + 'Q->Q': numbers.identity_impl, + }) + + ufunc_db[np.ceil] = { + 'f->f': npyfuncs.np_real_ceil_impl, + 'd->d': npyfuncs.np_real_ceil_impl, + } + if numpy_version >= (2, 1): + ufunc_db[np.ceil].update({ + '?->?': numbers.identity_impl, + 'b->b': numbers.identity_impl, + 'B->B': numbers.identity_impl, + 'h->h': numbers.identity_impl, + 'H->H': numbers.identity_impl, + 'i->i': numbers.identity_impl, + 'I->I': numbers.identity_impl, + 'l->l': numbers.identity_impl, + 'L->L': numbers.identity_impl, + 'q->q': numbers.identity_impl, + 'Q->Q': numbers.identity_impl, + }) + + ufunc_db[np.trunc] = { + 'f->f': npyfuncs.np_real_trunc_impl, + 'd->d': npyfuncs.np_real_trunc_impl, + } + if numpy_version >= (2, 1): + ufunc_db[np.trunc].update({ + '?->?': numbers.identity_impl, + 'b->b': numbers.identity_impl, + 'B->B': numbers.identity_impl, + 'h->h': numbers.identity_impl, + 'H->H': numbers.identity_impl, + 'i->i': numbers.identity_impl, + 'I->I': numbers.identity_impl, + 'l->l': numbers.identity_impl, + 'L->L': numbers.identity_impl, + 'q->q': numbers.identity_impl, + 'Q->Q': numbers.identity_impl, + }) + + ufunc_db[np.fabs] = { + 'f->f': npyfuncs.np_real_fabs_impl, + 'd->d': npyfuncs.np_real_fabs_impl, + } + + # logical ufuncs + ufunc_db[np.greater] = { + '??->?': numbers.int_ugt_impl, + 'bb->?': numbers.int_sgt_impl, + 'BB->?': numbers.int_ugt_impl, + 'hh->?': numbers.int_sgt_impl, + 'HH->?': numbers.int_ugt_impl, + 'ii->?': numbers.int_sgt_impl, + 'II->?': numbers.int_ugt_impl, + 'll->?': numbers.int_sgt_impl, + 'LL->?': numbers.int_ugt_impl, + 'qq->?': numbers.int_sgt_impl, + 'QQ->?': numbers.int_ugt_impl, + 'ff->?': numbers.real_gt_impl, + 'dd->?': numbers.real_gt_impl, + 'FF->?': npyfuncs.np_complex_gt_impl, + 'DD->?': npyfuncs.np_complex_gt_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.greater].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('>'), + 'Qq->?': numbers.int_unsigned_signed_cmp('>')}) + + ufunc_db[np.greater_equal] = { + '??->?': numbers.int_uge_impl, + 'bb->?': numbers.int_sge_impl, + 'BB->?': numbers.int_uge_impl, + 'hh->?': numbers.int_sge_impl, + 'HH->?': numbers.int_uge_impl, + 'ii->?': numbers.int_sge_impl, + 'II->?': numbers.int_uge_impl, + 'll->?': numbers.int_sge_impl, + 'LL->?': numbers.int_uge_impl, + 'qq->?': numbers.int_sge_impl, + 'QQ->?': numbers.int_uge_impl, + 'ff->?': numbers.real_ge_impl, + 'dd->?': numbers.real_ge_impl, + 'FF->?': npyfuncs.np_complex_ge_impl, + 'DD->?': npyfuncs.np_complex_ge_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.greater_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('>='), + 'Qq->?': numbers.int_unsigned_signed_cmp('>=')}) + + ufunc_db[np.less] = { + '??->?': numbers.int_ult_impl, + 'bb->?': numbers.int_slt_impl, + 'BB->?': numbers.int_ult_impl, + 'hh->?': numbers.int_slt_impl, + 'HH->?': numbers.int_ult_impl, + 'ii->?': numbers.int_slt_impl, + 'II->?': numbers.int_ult_impl, + 'll->?': numbers.int_slt_impl, + 'LL->?': numbers.int_ult_impl, + 'qq->?': numbers.int_slt_impl, + 'QQ->?': numbers.int_ult_impl, + 'ff->?': numbers.real_lt_impl, + 'dd->?': numbers.real_lt_impl, + 'FF->?': npyfuncs.np_complex_lt_impl, + 'DD->?': npyfuncs.np_complex_lt_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.less].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('<'), + 'Qq->?': numbers.int_unsigned_signed_cmp('<')}) + + ufunc_db[np.less_equal] = { + '??->?': numbers.int_ule_impl, + 'bb->?': numbers.int_sle_impl, + 'BB->?': numbers.int_ule_impl, + 'hh->?': numbers.int_sle_impl, + 'HH->?': numbers.int_ule_impl, + 'ii->?': numbers.int_sle_impl, + 'II->?': numbers.int_ule_impl, + 'll->?': numbers.int_sle_impl, + 'LL->?': numbers.int_ule_impl, + 'qq->?': numbers.int_sle_impl, + 'QQ->?': numbers.int_ule_impl, + 'ff->?': numbers.real_le_impl, + 'dd->?': numbers.real_le_impl, + 'FF->?': npyfuncs.np_complex_le_impl, + 'DD->?': npyfuncs.np_complex_le_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.less_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('<='), + 'Qq->?': numbers.int_unsigned_signed_cmp('<=')}) + + ufunc_db[np.not_equal] = { + '??->?': numbers.int_ne_impl, + 'bb->?': numbers.int_ne_impl, + 'BB->?': numbers.int_ne_impl, + 'hh->?': numbers.int_ne_impl, + 'HH->?': numbers.int_ne_impl, + 'ii->?': numbers.int_ne_impl, + 'II->?': numbers.int_ne_impl, + 'll->?': numbers.int_ne_impl, + 'LL->?': numbers.int_ne_impl, + 'qq->?': numbers.int_ne_impl, + 'QQ->?': numbers.int_ne_impl, + 'ff->?': numbers.real_ne_impl, + 'dd->?': numbers.real_ne_impl, + 'FF->?': npyfuncs.np_complex_ne_impl, + 'DD->?': npyfuncs.np_complex_ne_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.not_equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('!='), + 'Qq->?': numbers.int_unsigned_signed_cmp('!=')}) + + ufunc_db[np.equal] = { + '??->?': numbers.int_eq_impl, + 'bb->?': numbers.int_eq_impl, + 'BB->?': numbers.int_eq_impl, + 'hh->?': numbers.int_eq_impl, + 'HH->?': numbers.int_eq_impl, + 'ii->?': numbers.int_eq_impl, + 'II->?': numbers.int_eq_impl, + 'll->?': numbers.int_eq_impl, + 'LL->?': numbers.int_eq_impl, + 'qq->?': numbers.int_eq_impl, + 'QQ->?': numbers.int_eq_impl, + 'ff->?': numbers.real_eq_impl, + 'dd->?': numbers.real_eq_impl, + 'FF->?': npyfuncs.np_complex_eq_impl, + 'DD->?': npyfuncs.np_complex_eq_impl, + } + if numpy_version >= (1, 25): + ufunc_db[np.equal].update({ + 'qQ->?': numbers.int_signed_unsigned_cmp('=='), + 'Qq->?': numbers.int_unsigned_signed_cmp('==')}) + + ufunc_db[np.logical_and] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->?': npyfuncs.np_logical_and_impl, + 'BB->?': npyfuncs.np_logical_and_impl, + 'hh->?': npyfuncs.np_logical_and_impl, + 'HH->?': npyfuncs.np_logical_and_impl, + 'ii->?': npyfuncs.np_logical_and_impl, + 'II->?': npyfuncs.np_logical_and_impl, + 'll->?': npyfuncs.np_logical_and_impl, + 'LL->?': npyfuncs.np_logical_and_impl, + 'qq->?': npyfuncs.np_logical_and_impl, + 'QQ->?': npyfuncs.np_logical_and_impl, + 'ff->?': npyfuncs.np_logical_and_impl, + 'dd->?': npyfuncs.np_logical_and_impl, + 'FF->?': npyfuncs.np_complex_logical_and_impl, + 'DD->?': npyfuncs.np_complex_logical_and_impl, + } + + ufunc_db[np.logical_or] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->?': npyfuncs.np_logical_or_impl, + 'BB->?': npyfuncs.np_logical_or_impl, + 'hh->?': npyfuncs.np_logical_or_impl, + 'HH->?': npyfuncs.np_logical_or_impl, + 'ii->?': npyfuncs.np_logical_or_impl, + 'II->?': npyfuncs.np_logical_or_impl, + 'll->?': npyfuncs.np_logical_or_impl, + 'LL->?': npyfuncs.np_logical_or_impl, + 'qq->?': npyfuncs.np_logical_or_impl, + 'QQ->?': npyfuncs.np_logical_or_impl, + 'ff->?': npyfuncs.np_logical_or_impl, + 'dd->?': npyfuncs.np_logical_or_impl, + 'FF->?': npyfuncs.np_complex_logical_or_impl, + 'DD->?': npyfuncs.np_complex_logical_or_impl, + } + + ufunc_db[np.logical_xor] = { + '??->?': npyfuncs.np_logical_xor_impl, + 'bb->?': npyfuncs.np_logical_xor_impl, + 'BB->?': npyfuncs.np_logical_xor_impl, + 'hh->?': npyfuncs.np_logical_xor_impl, + 'HH->?': npyfuncs.np_logical_xor_impl, + 'ii->?': npyfuncs.np_logical_xor_impl, + 'II->?': npyfuncs.np_logical_xor_impl, + 'll->?': npyfuncs.np_logical_xor_impl, + 'LL->?': npyfuncs.np_logical_xor_impl, + 'qq->?': npyfuncs.np_logical_xor_impl, + 'QQ->?': npyfuncs.np_logical_xor_impl, + 'ff->?': npyfuncs.np_logical_xor_impl, + 'dd->?': npyfuncs.np_logical_xor_impl, + 'FF->?': npyfuncs.np_complex_logical_xor_impl, + 'DD->?': npyfuncs.np_complex_logical_xor_impl, + } + + ufunc_db[np.logical_not] = { + '?->?': npyfuncs.np_logical_not_impl, + 'b->?': npyfuncs.np_logical_not_impl, + 'B->?': npyfuncs.np_logical_not_impl, + 'h->?': npyfuncs.np_logical_not_impl, + 'H->?': npyfuncs.np_logical_not_impl, + 'i->?': npyfuncs.np_logical_not_impl, + 'I->?': npyfuncs.np_logical_not_impl, + 'l->?': npyfuncs.np_logical_not_impl, + 'L->?': npyfuncs.np_logical_not_impl, + 'q->?': npyfuncs.np_logical_not_impl, + 'Q->?': npyfuncs.np_logical_not_impl, + 'f->?': npyfuncs.np_logical_not_impl, + 'd->?': npyfuncs.np_logical_not_impl, + 'F->?': npyfuncs.np_complex_logical_not_impl, + 'D->?': npyfuncs.np_complex_logical_not_impl, + } + + ufunc_db[np.maximum] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->b': npyfuncs.np_int_smax_impl, + 'BB->B': npyfuncs.np_int_umax_impl, + 'hh->h': npyfuncs.np_int_smax_impl, + 'HH->H': npyfuncs.np_int_umax_impl, + 'ii->i': npyfuncs.np_int_smax_impl, + 'II->I': npyfuncs.np_int_umax_impl, + 'll->l': npyfuncs.np_int_smax_impl, + 'LL->L': npyfuncs.np_int_umax_impl, + 'qq->q': npyfuncs.np_int_smax_impl, + 'QQ->Q': npyfuncs.np_int_umax_impl, + 'ff->f': npyfuncs.np_real_maximum_impl, + 'dd->d': npyfuncs.np_real_maximum_impl, + 'FF->F': npyfuncs.np_complex_maximum_impl, + 'DD->D': npyfuncs.np_complex_maximum_impl, + } + + ufunc_db[np.minimum] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->b': npyfuncs.np_int_smin_impl, + 'BB->B': npyfuncs.np_int_umin_impl, + 'hh->h': npyfuncs.np_int_smin_impl, + 'HH->H': npyfuncs.np_int_umin_impl, + 'ii->i': npyfuncs.np_int_smin_impl, + 'II->I': npyfuncs.np_int_umin_impl, + 'll->l': npyfuncs.np_int_smin_impl, + 'LL->L': npyfuncs.np_int_umin_impl, + 'qq->q': npyfuncs.np_int_smin_impl, + 'QQ->Q': npyfuncs.np_int_umin_impl, + 'ff->f': npyfuncs.np_real_minimum_impl, + 'dd->d': npyfuncs.np_real_minimum_impl, + 'FF->F': npyfuncs.np_complex_minimum_impl, + 'DD->D': npyfuncs.np_complex_minimum_impl, + } + + ufunc_db[np.fmax] = { + '??->?': npyfuncs.np_logical_or_impl, + 'bb->b': npyfuncs.np_int_smax_impl, + 'BB->B': npyfuncs.np_int_umax_impl, + 'hh->h': npyfuncs.np_int_smax_impl, + 'HH->H': npyfuncs.np_int_umax_impl, + 'ii->i': npyfuncs.np_int_smax_impl, + 'II->I': npyfuncs.np_int_umax_impl, + 'll->l': npyfuncs.np_int_smax_impl, + 'LL->L': npyfuncs.np_int_umax_impl, + 'qq->q': npyfuncs.np_int_smax_impl, + 'QQ->Q': npyfuncs.np_int_umax_impl, + 'ff->f': npyfuncs.np_real_fmax_impl, + 'dd->d': npyfuncs.np_real_fmax_impl, + 'FF->F': npyfuncs.np_complex_fmax_impl, + 'DD->D': npyfuncs.np_complex_fmax_impl, + } + + ufunc_db[np.fmin] = { + '??->?': npyfuncs.np_logical_and_impl, + 'bb->b': npyfuncs.np_int_smin_impl, + 'BB->B': npyfuncs.np_int_umin_impl, + 'hh->h': npyfuncs.np_int_smin_impl, + 'HH->H': npyfuncs.np_int_umin_impl, + 'ii->i': npyfuncs.np_int_smin_impl, + 'II->I': npyfuncs.np_int_umin_impl, + 'll->l': npyfuncs.np_int_smin_impl, + 'LL->L': npyfuncs.np_int_umin_impl, + 'qq->q': npyfuncs.np_int_smin_impl, + 'QQ->Q': npyfuncs.np_int_umin_impl, + 'ff->f': npyfuncs.np_real_fmin_impl, + 'dd->d': npyfuncs.np_real_fmin_impl, + 'FF->F': npyfuncs.np_complex_fmin_impl, + 'DD->D': npyfuncs.np_complex_fmin_impl, + } + + # misc floating functions + ufunc_db[np.isnan] = { + 'f->?': npyfuncs.np_real_isnan_impl, + 'd->?': npyfuncs.np_real_isnan_impl, + 'F->?': npyfuncs.np_complex_isnan_impl, + 'D->?': npyfuncs.np_complex_isnan_impl, + # int8 + 'b->?': npyfuncs.np_int_isnan_impl, + 'B->?': npyfuncs.np_int_isnan_impl, + # int16 + 'h->?': npyfuncs.np_int_isnan_impl, + 'H->?': npyfuncs.np_int_isnan_impl, + # int32 + 'i->?': npyfuncs.np_int_isnan_impl, + 'I->?': npyfuncs.np_int_isnan_impl, + # int64 + 'l->?': npyfuncs.np_int_isnan_impl, + 'L->?': npyfuncs.np_int_isnan_impl, + # intp + 'q->?': npyfuncs.np_int_isnan_impl, + 'Q->?': npyfuncs.np_int_isnan_impl, + # boolean + '?->?': npyfuncs.np_int_isnan_impl, + # datetime & timedelta + 'm->?': npyfuncs.np_datetime_isnat_impl, + 'M->?': npyfuncs.np_datetime_isnat_impl, + } + + ufunc_db[np.isinf] = { + 'f->?': npyfuncs.np_real_isinf_impl, + 'd->?': npyfuncs.np_real_isinf_impl, + 'F->?': npyfuncs.np_complex_isinf_impl, + 'D->?': npyfuncs.np_complex_isinf_impl, + # int8 + 'b->?': npyfuncs.np_int_isinf_impl, + 'B->?': npyfuncs.np_int_isinf_impl, + # int16 + 'h->?': npyfuncs.np_int_isinf_impl, + 'H->?': npyfuncs.np_int_isinf_impl, + # int32 + 'i->?': npyfuncs.np_int_isinf_impl, + 'I->?': npyfuncs.np_int_isinf_impl, + # int64 + 'l->?': npyfuncs.np_int_isinf_impl, + 'L->?': npyfuncs.np_int_isinf_impl, + # intp + 'q->?': npyfuncs.np_int_isinf_impl, + 'Q->?': npyfuncs.np_int_isinf_impl, + # boolean + '?->?': npyfuncs.np_int_isinf_impl, + # datetime & timedelta + 'm->?': npyfuncs.np_int_isinf_impl, + 'M->?': npyfuncs.np_int_isinf_impl, + } + + ufunc_db[np.isfinite] = { + 'f->?': npyfuncs.np_real_isfinite_impl, + 'd->?': npyfuncs.np_real_isfinite_impl, + 'F->?': npyfuncs.np_complex_isfinite_impl, + 'D->?': npyfuncs.np_complex_isfinite_impl, + # int8 + 'b->?': npyfuncs.np_int_isfinite_impl, + 'B->?': npyfuncs.np_int_isfinite_impl, + # int16 + 'h->?': npyfuncs.np_int_isfinite_impl, + 'H->?': npyfuncs.np_int_isfinite_impl, + # int32 + 'i->?': npyfuncs.np_int_isfinite_impl, + 'I->?': npyfuncs.np_int_isfinite_impl, + # int64 + 'l->?': npyfuncs.np_int_isfinite_impl, + 'L->?': npyfuncs.np_int_isfinite_impl, + # intp + 'q->?': npyfuncs.np_int_isfinite_impl, + 'Q->?': npyfuncs.np_int_isfinite_impl, + # boolean + '?->?': npyfuncs.np_int_isfinite_impl, + # datetime & timedelta + 'M->?': npyfuncs.np_datetime_isfinite_impl, + 'm->?': npyfuncs.np_datetime_isfinite_impl, + } + + ufunc_db[np.signbit] = { + 'f->?': npyfuncs.np_real_signbit_impl, + 'd->?': npyfuncs.np_real_signbit_impl, + } + + ufunc_db[np.copysign] = { + 'ff->f': npyfuncs.np_real_copysign_impl, + 'dd->d': npyfuncs.np_real_copysign_impl, + } + + ufunc_db[np.nextafter] = { + 'ff->f': npyfuncs.np_real_nextafter_impl, + 'dd->d': npyfuncs.np_real_nextafter_impl, + } + + ufunc_db[np.spacing] = { + 'f->f': npyfuncs.np_real_spacing_impl, + 'd->d': npyfuncs.np_real_spacing_impl, + } + + ufunc_db[np.ldexp] = { + 'fi->f': npyfuncs.np_real_ldexp_impl, + 'fl->f': npyfuncs.np_real_ldexp_impl, + 'di->d': npyfuncs.np_real_ldexp_impl, + 'dl->d': npyfuncs.np_real_ldexp_impl, + } + if numpy_version >= (2, 0) and IS_WIN32: + ufunc_db[np.ldexp]['fq->f'] = ufunc_db[np.ldexp].pop('fl->f') + ufunc_db[np.ldexp]['dq->d'] = ufunc_db[np.ldexp].pop('dl->d') + + # bit twiddling functions + ufunc_db[np.bitwise_and] = { + '??->?': numbers.int_and_impl, + 'bb->b': numbers.int_and_impl, + 'BB->B': numbers.int_and_impl, + 'hh->h': numbers.int_and_impl, + 'HH->H': numbers.int_and_impl, + 'ii->i': numbers.int_and_impl, + 'II->I': numbers.int_and_impl, + 'll->l': numbers.int_and_impl, + 'LL->L': numbers.int_and_impl, + 'qq->q': numbers.int_and_impl, + 'QQ->Q': numbers.int_and_impl, + } + + ufunc_db[np.bitwise_or] = { + '??->?': numbers.int_or_impl, + 'bb->b': numbers.int_or_impl, + 'BB->B': numbers.int_or_impl, + 'hh->h': numbers.int_or_impl, + 'HH->H': numbers.int_or_impl, + 'ii->i': numbers.int_or_impl, + 'II->I': numbers.int_or_impl, + 'll->l': numbers.int_or_impl, + 'LL->L': numbers.int_or_impl, + 'qq->q': numbers.int_or_impl, + 'QQ->Q': numbers.int_or_impl, + } + + ufunc_db[np.bitwise_xor] = { + '??->?': numbers.int_xor_impl, + 'bb->b': numbers.int_xor_impl, + 'BB->B': numbers.int_xor_impl, + 'hh->h': numbers.int_xor_impl, + 'HH->H': numbers.int_xor_impl, + 'ii->i': numbers.int_xor_impl, + 'II->I': numbers.int_xor_impl, + 'll->l': numbers.int_xor_impl, + 'LL->L': numbers.int_xor_impl, + 'qq->q': numbers.int_xor_impl, + 'QQ->Q': numbers.int_xor_impl, + } + + ufunc_db[np.invert] = { # aka np.bitwise_not + '?->?': numbers.int_invert_impl, + 'b->b': numbers.int_invert_impl, + 'B->B': numbers.int_invert_impl, + 'h->h': numbers.int_invert_impl, + 'H->H': numbers.int_invert_impl, + 'i->i': numbers.int_invert_impl, + 'I->I': numbers.int_invert_impl, + 'l->l': numbers.int_invert_impl, + 'L->L': numbers.int_invert_impl, + 'q->q': numbers.int_invert_impl, + 'Q->Q': numbers.int_invert_impl, + } + + ufunc_db[np.left_shift] = { + 'bb->b': numbers.int_shl_impl, + 'BB->B': numbers.int_shl_impl, + 'hh->h': numbers.int_shl_impl, + 'HH->H': numbers.int_shl_impl, + 'ii->i': numbers.int_shl_impl, + 'II->I': numbers.int_shl_impl, + 'll->l': numbers.int_shl_impl, + 'LL->L': numbers.int_shl_impl, + 'qq->q': numbers.int_shl_impl, + 'QQ->Q': numbers.int_shl_impl, + } + + ufunc_db[np.right_shift] = { + 'bb->b': numbers.int_shr_impl, + 'BB->B': numbers.int_shr_impl, + 'hh->h': numbers.int_shr_impl, + 'HH->H': numbers.int_shr_impl, + 'ii->i': numbers.int_shr_impl, + 'II->I': numbers.int_shr_impl, + 'll->l': numbers.int_shr_impl, + 'LL->L': numbers.int_shr_impl, + 'qq->q': numbers.int_shr_impl, + 'QQ->Q': numbers.int_shr_impl, + } + + # Inject datetime64 support + from numba.np import npdatetime + ufunc_db[np.negative].update({ + 'm->m': npdatetime.timedelta_neg_impl, + }) + ufunc_db[np.positive].update({ + 'm->m': npdatetime.timedelta_pos_impl, + }) + ufunc_db[np.absolute].update({ + 'm->m': npdatetime.timedelta_abs_impl, + }) + ufunc_db[np.sign].update({ + 'm->m': npdatetime.timedelta_sign_impl, + }) + ufunc_db[np.add].update({ + 'mm->m': npdatetime.timedelta_add_impl, + 'Mm->M': npdatetime.datetime_plus_timedelta, + 'mM->M': npdatetime.timedelta_plus_datetime, + }) + ufunc_db[np.subtract].update({ + 'mm->m': npdatetime.timedelta_sub_impl, + 'Mm->M': npdatetime.datetime_minus_timedelta, + 'MM->m': npdatetime.datetime_minus_datetime, + }) + ufunc_db[np.multiply].update({ + 'mq->m': npdatetime.timedelta_times_number, + 'md->m': npdatetime.timedelta_times_number, + 'qm->m': npdatetime.number_times_timedelta, + 'dm->m': npdatetime.number_times_timedelta, + }) + if np.divide != np.true_divide: + ufunc_db[np.divide].update({ + 'mq->m': npdatetime.timedelta_over_number, + 'md->m': npdatetime.timedelta_over_number, + 'mm->d': npdatetime.timedelta_over_timedelta, + }) + ufunc_db[np.true_divide].update({ + 'mq->m': npdatetime.timedelta_over_number, + 'md->m': npdatetime.timedelta_over_number, + 'mm->d': npdatetime.timedelta_over_timedelta, + }) + ufunc_db[np.floor_divide].update({ + 'mq->m': npdatetime.timedelta_over_number, + 'md->m': npdatetime.timedelta_over_number, + }) + + ufunc_db[np.floor_divide].update({ + 'mm->q': npdatetime.timedelta_floor_div_timedelta, + }) + + ufunc_db[np.equal].update({ + 'MM->?': npdatetime.datetime_eq_datetime_impl, + 'mm->?': npdatetime.timedelta_eq_timedelta_impl, + }) + ufunc_db[np.not_equal].update({ + 'MM->?': npdatetime.datetime_ne_datetime_impl, + 'mm->?': npdatetime.timedelta_ne_timedelta_impl, + }) + ufunc_db[np.less].update({ + 'MM->?': npdatetime.datetime_lt_datetime_impl, + 'mm->?': npdatetime.timedelta_lt_timedelta_impl, + }) + ufunc_db[np.less_equal].update({ + 'MM->?': npdatetime.datetime_le_datetime_impl, + 'mm->?': npdatetime.timedelta_le_timedelta_impl, + }) + ufunc_db[np.greater].update({ + 'MM->?': npdatetime.datetime_gt_datetime_impl, + 'mm->?': npdatetime.timedelta_gt_timedelta_impl, + }) + ufunc_db[np.greater_equal].update({ + 'MM->?': npdatetime.datetime_ge_datetime_impl, + 'mm->?': npdatetime.timedelta_ge_timedelta_impl, + }) + ufunc_db[np.maximum].update({ + 'MM->M': npdatetime.datetime_maximum_impl, + 'mm->m': npdatetime.timedelta_maximum_impl, + }) + ufunc_db[np.minimum].update({ + 'MM->M': npdatetime.datetime_minimum_impl, + 'mm->m': npdatetime.timedelta_minimum_impl, + }) + # there is no difference for datetime/timedelta in maximum/fmax + # and minimum/fmin + ufunc_db[np.fmax].update({ + 'MM->M': npdatetime.datetime_fmax_impl, + 'mm->m': npdatetime.timedelta_fmax_impl, + }) + ufunc_db[np.fmin].update({ + 'MM->M': npdatetime.datetime_fmin_impl, + 'mm->m': npdatetime.timedelta_fmin_impl, + }) + + ufunc_db[np.remainder].update({ + 'mm->m': npdatetime.timedelta_mod_timedelta, + }) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2acbe3396926a249aff5bb6560735e8139cda9a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/__init__.py @@ -0,0 +1 @@ +from numba.parfors import parfor_lowering diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/array_analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/array_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c931c81861cd74fd714d7af2d18b69b5efddecbf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/array_analysis.py @@ -0,0 +1,3207 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numpy +import operator +from numba.core import types, ir, config, cgutils, errors +from numba.core.ir_utils import ( + mk_unique_var, + find_topo_order, + dprint_func_ir, + get_global_func_typ, + guard, + require, + get_definition, + find_callname, + find_build_sequence, + find_const, + is_namedtuple_class, + build_definitions, + find_potential_aliases, + get_canonical_alias, + GuardException, +) +from numba.core.analysis import compute_cfg_from_blocks +from numba.core.typing import npydecl, signature +import copy +from numba.core.extending import intrinsic +import llvmlite + +UNKNOWN_CLASS = -1 +CONST_CLASS = 0 +MAP_TYPES = [numpy.ufunc] + +array_analysis_extensions = {} + +# declaring call classes +array_creation = ["empty", "zeros", "ones", "full"] + +random_int_args = ["rand", "randn"] + +random_1arg_size = [ + "ranf", + "random_sample", + "sample", + "random", + "standard_normal", +] + +random_2arg_sizelast = [ + "chisquare", + "weibull", + "power", + "geometric", + "exponential", + "poisson", + "rayleigh", +] + +random_3arg_sizelast = [ + "normal", + "uniform", + "beta", + "binomial", + "f", + "gamma", + "lognormal", + "laplace", +] + +random_calls = ( + random_int_args + + random_1arg_size + + random_2arg_sizelast + + random_3arg_sizelast + + ["randint", "triangular"] +) + + +@intrinsic +def wrap_index(typingctx, idx, size): + """ + Calculate index value "idx" relative to a size "size" value as + (idx % size), where "size" is known to be positive. + Note that we use the mod(%) operation here instead of + (idx < 0 ? idx + size : idx) because we may have situations + where idx > size due to the way indices are calculated + during slice/range analysis. + + Both idx and size have to be Integer types. + size should be from the array size vars that array_analysis + adds and the bitwidth should match the platform maximum. + """ + require(isinstance(idx, types.scalars.Integer)) + require(isinstance(size, types.scalars.Integer)) + + # We need both idx and size to be platform size so that we can compare. + unified_ty = types.intp if size.signed else types.uintp + idx_unified = types.intp if idx.signed else types.uintp + + def codegen(context, builder, sig, args): + ll_idx_unified_ty = context.get_data_type(idx_unified) + ll_unified_ty = context.get_data_type(unified_ty) + if idx_unified.signed: + idx = builder.sext(args[0], ll_idx_unified_ty) + else: + idx = builder.zext(args[0], ll_idx_unified_ty) + if unified_ty.signed: + size = builder.sext(args[1], ll_unified_ty) + else: + size = builder.zext(args[1], ll_unified_ty) + neg_size = builder.neg(size) + zero = llvmlite.ir.Constant(ll_unified_ty, 0) + # If idx is unsigned then these signed comparisons will fail in those + # cases where the idx has the highest bit set, namely more than 2**63 + # on 64-bit platforms. + idx_negative = builder.icmp_signed("<", idx, zero) + pos_oversize = builder.icmp_signed(">=", idx, size) + neg_oversize = builder.icmp_signed("<=", idx, neg_size) + pos_res = builder.select(pos_oversize, size, idx) + neg_res = builder.select(neg_oversize, zero, builder.add(idx, size)) + mod = builder.select(idx_negative, neg_res, pos_res) + return mod + + return signature(unified_ty, idx, size), codegen + + +def wrap_index_literal(idx, size): + if idx < 0: + if idx <= -size: + return 0 + else: + return idx + size + else: + if idx >= size: + return size + else: + return idx + + +@intrinsic +def assert_equiv(typingctx, *val): + """ + A function that asserts the inputs are of equivalent size, + and throws runtime error when they are not. The input is + a vararg that contains an error message, followed by a set + of objects of either array, tuple or integer. + """ + if len(val) > 1: + # Make sure argument is a single tuple type. Note that this only + # happens when IR containing assert_equiv call is being compiled + # (and going through type inference) again. + val = (types.StarArgTuple(val),) + + assert len(val[0]) > 1 + # Arguments must be either array, tuple, or integer + assert all( + isinstance(a, ( + types.ArrayCompatible, + types.BaseTuple, + types.SliceType, + types.Integer + )) + for a in val[0][1:] + ) + if not isinstance(val[0][0], types.StringLiteral): + raise errors.TypingError('first argument must be a StringLiteral') + + def codegen(context, builder, sig, args): + assert len(args) == 1 # it is a vararg tuple + tup = cgutils.unpack_tuple(builder, args[0]) + tup_type = sig.args[0] + msg = sig.args[0][0].literal_value + + def unpack_shapes(a, aty): + if isinstance(aty, types.ArrayCompatible): + ary = context.make_array(aty)(context, builder, a) + return cgutils.unpack_tuple(builder, ary.shape) + elif isinstance(aty, types.BaseTuple): + return cgutils.unpack_tuple(builder, a) + else: # otherwise it is a single integer + return [a] + + def pairwise(a, aty, b, bty): + ashapes = unpack_shapes(a, aty) + bshapes = unpack_shapes(b, bty) + assert len(ashapes) == len(bshapes) + for (m, n) in zip(ashapes, bshapes): + m_eq_n = builder.icmp_unsigned('==', m, n) + with builder.if_else(m_eq_n) as (then, orelse): + with then: + pass + with orelse: + context.call_conv.return_user_exc( + builder, AssertionError, (msg,) + ) + + for i in range(1, len(tup_type) - 1): + pairwise(tup[i], tup_type[i], tup[i + 1], tup_type[i + 1]) + r = context.get_constant_generic(builder, types.NoneType, None) + return r + + return signature(types.none, *val), codegen + + +class EquivSet(object): + + """EquivSet keeps track of equivalence relations between + a set of objects. + """ + + def __init__(self, obj_to_ind=None, ind_to_obj=None, next_ind=0): + """Create a new EquivSet object. Optional keyword arguments are for + internal use only. + """ + # obj_to_ind maps object to equivalence index (sometimes also called + # equivalence class) is a non-negative number that uniquely identifies + # a set of objects that are equivalent. + self.obj_to_ind = obj_to_ind if obj_to_ind else {} + # ind_to_obj maps equivalence index to a list of objects. + self.ind_to_obj = ind_to_obj if ind_to_obj else {} + # next index number that is incremented each time a new equivalence + # relation is created. + self.next_ind = next_ind + + def empty(self): + """Return an empty EquivSet object. + """ + return EquivSet() + + def clone(self): + """Return a new copy. + """ + return EquivSet( + obj_to_ind=copy.deepcopy(self.obj_to_ind), + ind_to_obj=copy.deepcopy(self.ind_to_obj), + next_id=self.next_ind, + ) + + def __repr__(self): + return "EquivSet({})".format(self.ind_to_obj) + + def is_empty(self): + """Return true if the set is empty, or false otherwise. + """ + return self.obj_to_ind == {} + + def _get_ind(self, x): + """Return the internal index (greater or equal to 0) of the given + object, or -1 if not found. + """ + return self.obj_to_ind.get(x, -1) + + def _get_or_add_ind(self, x): + """Return the internal index (greater or equal to 0) of the given + object, or create a new one if not found. + """ + if x in self.obj_to_ind: + i = self.obj_to_ind[x] + else: + i = self.next_ind + self.next_ind += 1 + return i + + def _insert(self, objs): + """Base method that inserts a set of equivalent objects by modifying + self. + """ + assert len(objs) > 1 + + inds = tuple(self._get_or_add_ind(x) for x in objs) + ind = min(inds) + + if config.DEBUG_ARRAY_OPT >= 2: + print("_insert:", objs, inds) + + if not (ind in self.ind_to_obj): + self.ind_to_obj[ind] = [] + + for i, obj in zip(inds, objs): + if i == ind: + if not (obj in self.ind_to_obj[ind]): + self.ind_to_obj[ind].append(obj) + self.obj_to_ind[obj] = ind + else: + if i in self.ind_to_obj: + # those already existing are reassigned + for x in self.ind_to_obj[i]: + self.obj_to_ind[x] = ind + self.ind_to_obj[ind].append(x) + del self.ind_to_obj[i] + else: + # those that are new are assigned. + self.obj_to_ind[obj] = ind + self.ind_to_obj[ind].append(obj) + + def is_equiv(self, *objs): + """Try to derive if given objects are equivalent, return true + if so, or false otherwise. + """ + inds = [self._get_ind(x) for x in objs] + ind = max(inds) + if ind != -1: + return all(i == ind for i in inds) + else: + return all([x == objs[0] for x in objs]) + + def get_equiv_const(self, obj): + """Check if obj is equivalent to some int constant, and return + the constant if found, or None otherwise. + """ + ind = self._get_ind(obj) + if ind >= 0: + objs = self.ind_to_obj[ind] + for x in objs: + if isinstance(x, int): + return x + return None + + def get_equiv_set(self, obj): + """Return the set of equivalent objects. + """ + ind = self._get_ind(obj) + if ind >= 0: + return set(self.ind_to_obj[ind]) + return set() + + def insert_equiv(self, *objs): + """Insert a set of equivalent objects by modifying self. This + method can be overloaded to transform object type before insertion. + """ + return self._insert(objs) + + def intersect(self, equiv_set): + """ Return the intersection of self and the given equiv_set, + without modifying either of them. The result will also keep + old equivalence indices unchanged. + """ + new_set = self.empty() + new_set.next_ind = self.next_ind + + for objs in equiv_set.ind_to_obj.values(): + inds = tuple(self._get_ind(x) for x in objs) + ind_to_obj = {} + + for i, x in zip(inds, objs): + if i in ind_to_obj: + ind_to_obj[i].append(x) + elif i >= 0: + ind_to_obj[i] = [x] + + for v in ind_to_obj.values(): + if len(v) > 1: + new_set._insert(v) + + return new_set + + +class ShapeEquivSet(EquivSet): + + """Just like EquivSet, except that it accepts only numba IR variables + and constants as objects, guided by their types. Arrays are considered + equivalent as long as their shapes are equivalent. Scalars are + equivalent only when they are equal in value. Tuples are equivalent + when they are of the same size, and their elements are equivalent. + """ + + def __init__( + self, + typemap, + defs=None, + ind_to_var=None, + obj_to_ind=None, + ind_to_obj=None, + next_id=0, + ind_to_const=None, + ): + """Create a new ShapeEquivSet object, where typemap is a dictionary + that maps variable names to their types, and it will not be modified. + Optional keyword arguments are for internal use only. + """ + self.typemap = typemap + # defs maps variable name to an int, where + # 1 means the variable is defined only once, and numbers greater + # than 1 means defined more than once. + self.defs = defs if defs else {} + # ind_to_var maps index number to a list of variables (of ir.Var type). + # It is used to retrieve defined shape variables given an equivalence + # index. + self.ind_to_var = ind_to_var if ind_to_var else {} + # ind_to_const maps index number to a constant, if known. + self.ind_to_const = ind_to_const if ind_to_const else {} + + super(ShapeEquivSet, self).__init__(obj_to_ind, ind_to_obj, next_id) + + def empty(self): + """Return an empty ShapeEquivSet. + """ + return ShapeEquivSet(self.typemap, {}) + + def clone(self): + """Return a new copy. + """ + return ShapeEquivSet( + self.typemap, + defs=copy.copy(self.defs), + ind_to_var=copy.copy(self.ind_to_var), + obj_to_ind=copy.deepcopy(self.obj_to_ind), + ind_to_obj=copy.deepcopy(self.ind_to_obj), + next_id=self.next_ind, + ind_to_const=copy.deepcopy(self.ind_toconst), + ) + + def __repr__(self): + return "ShapeEquivSet({}, ind_to_var={}, ind_to_const={})".format( + self.ind_to_obj, self.ind_to_var, self.ind_to_const + ) + + def _get_names(self, obj): + """Return a set of names for the given obj, where array and tuples + are broken down to their individual shapes or elements. This is + safe because both Numba array shapes and Python tuples are immutable. + """ + if isinstance(obj, ir.Var) or isinstance(obj, str): + name = obj if isinstance(obj, str) else obj.name + if name not in self.typemap: + return (name,) + + typ = self.typemap[name] + if isinstance(typ, (types.BaseTuple, types.ArrayCompatible)): + ndim = (typ.ndim + if isinstance(typ, types.ArrayCompatible) + else len(typ)) + # Treat 0d array as if it were a scalar. + if ndim == 0: + return (name,) + else: + return tuple("{}#{}".format(name, i) for i in range(ndim)) + else: + return (name,) + elif isinstance(obj, ir.Const): + if isinstance(obj.value, tuple): + return obj.value + else: + return (obj.value,) + elif isinstance(obj, tuple): + + def get_names(x): + names = self._get_names(x) + if len(names) != 0: + return names[0] + return names + + return tuple(get_names(x) for x in obj) + elif isinstance(obj, int): + return (obj,) + if config.DEBUG_ARRAY_OPT >= 1: + print( + f"Ignoring untracked object type {type(obj)} in ShapeEquivSet") + return () + + def is_equiv(self, *objs): + """Overload EquivSet.is_equiv to handle Numba IR variables and + constants. + """ + assert len(objs) > 1 + obj_names = [self._get_names(x) for x in objs] + obj_names = [x for x in obj_names if x != ()] # rule out 0d shape + if len(obj_names) <= 1: + return False + ndims = [len(names) for names in obj_names] + ndim = ndims[0] + if not all(ndim == x for x in ndims): + if config.DEBUG_ARRAY_OPT >= 1: + print("is_equiv: Dimension mismatch for {}".format(objs)) + return False + for i in range(ndim): + names = [obj_name[i] for obj_name in obj_names] + if not super(ShapeEquivSet, self).is_equiv(*names): + return False + return True + + def get_equiv_const(self, obj): + """If the given object is equivalent to a constant scalar, + return the scalar value, or None otherwise. + """ + names = self._get_names(obj) + if len(names) != 1: + return None + return super(ShapeEquivSet, self).get_equiv_const(names[0]) + + def get_equiv_var(self, obj): + """If the given object is equivalent to some defined variable, + return the variable, or None otherwise. + """ + names = self._get_names(obj) + if len(names) != 1: + return None + ind = self._get_ind(names[0]) + vs = self.ind_to_var.get(ind, []) + return vs[0] if vs != [] else None + + def get_equiv_set(self, obj): + """Return the set of equivalent objects. + """ + names = self._get_names(obj) + if len(names) != 1: + return None + return super(ShapeEquivSet, self).get_equiv_set(names[0]) + + def _insert(self, objs): + """Overload EquivSet._insert to manage ind_to_var dictionary. + """ + inds = [] + for obj in objs: + if obj in self.obj_to_ind: + inds.append(self.obj_to_ind[obj]) + varlist = [] + constval = None + names = set() + for i in sorted(inds): + if i in self.ind_to_var: + for x in self.ind_to_var[i]: + if not (x.name in names): + varlist.append(x) + names.add(x.name) + if i in self.ind_to_const: + assert constval is None + constval = self.ind_to_const[i] + super(ShapeEquivSet, self)._insert(objs) + new_ind = self.obj_to_ind[objs[0]] + for i in set(inds): + if i in self.ind_to_var: + del self.ind_to_var[i] + self.ind_to_var[new_ind] = varlist + if constval is not None: + self.ind_to_const[new_ind] = constval + + def insert_equiv(self, *objs): + """Overload EquivSet.insert_equiv to handle Numba IR variables and + constants. Input objs are either variable or constant, and at least + one of them must be variable. + """ + assert len(objs) > 1 + obj_names = [self._get_names(x) for x in objs] + obj_names = [x for x in obj_names if x != ()] # rule out 0d shape + if len(obj_names) <= 1: + return + names = sum([list(x) for x in obj_names], []) + ndims = [len(x) for x in obj_names] + ndim = ndims[0] + assert all( + ndim == x for x in ndims + ), "Dimension mismatch for {}".format(objs) + varlist = [] + constlist = [] + for obj in objs: + if not isinstance(obj, tuple): + obj = (obj,) + for var in obj: + if isinstance(var, ir.Var) and not (var.name in varlist): + # favor those already defined, move to front of varlist + if var.name in self.defs: + varlist.insert(0, var) + else: + varlist.append(var) + if isinstance(var, ir.Const) and not (var.value in constlist): + constlist.append(var.value) + + # try to populate ind_to_var if variables are present + for obj in varlist: + name = obj.name + if name in names and not (name in self.obj_to_ind): + self.ind_to_obj[self.next_ind] = [name] + self.obj_to_ind[name] = self.next_ind + self.ind_to_var[self.next_ind] = [obj] + self.next_ind += 1 + + # create equivalence classes for previously unseen constants + for const in constlist: + if const in names and not (const in self.obj_to_ind): + self.ind_to_obj[self.next_ind] = [const] + self.obj_to_ind[const] = self.next_ind + self.ind_to_const[self.next_ind] = const + self.next_ind += 1 + + some_change = False + + for i in range(ndim): + names = [obj_name[i] for obj_name in obj_names] + ie_res = super(ShapeEquivSet, self).insert_equiv(*names) + some_change = some_change or ie_res + + return some_change + + def has_shape(self, name): + """Return true if the shape of the given variable is available. + """ + return self.get_shape(name) is not None + + def get_shape(self, name): + """Return a tuple of variables that corresponds to the shape + of the given array, or None if not found. + """ + return guard(self._get_shape, name) + + def _get_shape(self, name): + """Return a tuple of variables that corresponds to the shape + of the given array, or raise GuardException if not found. + """ + inds = self.get_shape_classes(name) + require(inds != ()) + shape = [] + for i in inds: + require(i in self.ind_to_var) + vs = self.ind_to_var[i] + if vs != []: + shape.append(vs[0]) + else: + require(i in self.ind_to_const) + vs = self.ind_to_const[i] + shape.append(vs) + return tuple(shape) + + def get_shape_classes(self, name): + """Instead of the shape tuple, return tuple of int, where + each int is the corresponding class index of the size object. + Unknown shapes are given class index -1. Return empty tuple + if the input name is a scalar variable. + """ + if isinstance(name, ir.Var): + name = name.name + typ = self.typemap[name] if name in self.typemap else None + if not ( + isinstance(typ, ( + types.BaseTuple, types.SliceType, types.ArrayCompatible + )) + ): + return [] + # Treat 0d arrays like scalars. + if isinstance(typ, types.ArrayCompatible) and typ.ndim == 0: + return [] + names = self._get_names(name) + inds = tuple(self._get_ind(name) for name in names) + return inds + + def intersect(self, equiv_set): + """Overload the intersect method to handle ind_to_var. + """ + newset = super(ShapeEquivSet, self).intersect(equiv_set) + ind_to_var = {} + for i, objs in newset.ind_to_obj.items(): + assert len(objs) > 0 + obj = objs[0] + assert obj in self.obj_to_ind + assert obj in equiv_set.obj_to_ind + j = self.obj_to_ind[obj] + k = equiv_set.obj_to_ind[obj] + assert j in self.ind_to_var + assert k in equiv_set.ind_to_var + varlist = [] + names = [x.name for x in equiv_set.ind_to_var[k]] + for x in self.ind_to_var[j]: + if x.name in names: + varlist.append(x) + ind_to_var[i] = varlist + newset.ind_to_var = ind_to_var + return newset + + def define(self, name, redefined): + """Increment the internal count of how many times a variable is being + defined. Most variables in Numba IR are SSA, i.e., defined only once, + but not all of them. When a variable is being re-defined, it must + be removed from the equivalence relation and added to the redefined + set but only if that redefinition is not known to have the same + equivalence classes. Those variables redefined are removed from all + the blocks' equivalence sets later. + + Arrays passed to define() use their whole name but these do not + appear in the equivalence sets since they are stored there per + dimension. Calling _get_names() here converts array names to + dimensional names. + + This function would previously invalidate if there were any multiple + definitions of a variable. However, we realized that this behavior + is overly restrictive. You need only invalidate on multiple + definitions if they are not known to be equivalent. So, the + equivalence insertion functions now return True if some change was + made (meaning the definition was not equivalent) and False + otherwise. If no change was made, then define() need not be + called. For no change to have been made, the variable must + already be present. If the new definition of the var has the + case where lhs and rhs are in the same equivalence class then + again, no change will be made and define() need not be called + or the variable invalidated. + """ + if isinstance(name, ir.Var): + name = name.name + if name in self.defs: + self.defs[name] += 1 + name_res = list(self._get_names(name)) + for one_name in name_res: + # NOTE: variable being redefined, must invalidate previous + # equivalences. Believe it is a rare case, and only happens to + # scalar accumuators. + if one_name in self.obj_to_ind: + redefined.add( + one_name + ) # remove this var from all equiv sets + i = self.obj_to_ind[one_name] + del self.obj_to_ind[one_name] + self.ind_to_obj[i].remove(one_name) + if self.ind_to_obj[i] == []: + del self.ind_to_obj[i] + assert i in self.ind_to_var + names = [x.name for x in self.ind_to_var[i]] + if name in names: + j = names.index(name) + del self.ind_to_var[i][j] + if self.ind_to_var[i] == []: + del self.ind_to_var[i] + # no more size variables, remove equivalence too + if i in self.ind_to_obj: + for obj in self.ind_to_obj[i]: + del self.obj_to_ind[obj] + del self.ind_to_obj[i] + else: + self.defs[name] = 1 + + def union_defs(self, defs, redefined): + """Union with the given defs dictionary. This is meant to handle + branch join-point, where a variable may have been defined in more + than one branches. + """ + for k, v in defs.items(): + if v > 0: + self.define(k, redefined) + + +class SymbolicEquivSet(ShapeEquivSet): + + """Just like ShapeEquivSet, except that it also reasons about variable + equivalence symbolically by using their arithmetic definitions. + The goal is to automatically derive the equivalence of array ranges + (slicing). For instance, a[1:m] and a[0:m-1] shall be considered + size-equivalence. + """ + + def __init__( + self, + typemap, + def_by=None, + ref_by=None, + ext_shapes=None, + defs=None, + ind_to_var=None, + obj_to_ind=None, + ind_to_obj=None, + next_id=0, + ): + """Create a new SymbolicEquivSet object, where typemap is a dictionary + that maps variable names to their types, and it will not be modified. + Optional keyword arguments are for internal use only. + """ + # A "defined-by" table that maps A to a tuple of (B, i), which + # means A is defined as: A = B + i, where A,B are variable names, + # and i is an integer constants. + self.def_by = def_by if def_by else {} + # A "referred-by" table that maps A to a list of [(B, i), (C, j) ...], + # which implies a sequence of definitions: B = A - i, C = A - j, and + # so on, where A,B,C,... are variable names, and i,j,... are + # integer constants. + self.ref_by = ref_by if ref_by else {} + # A extended shape table that can map an arbitrary object to a shape, + # currently used to remember shapes for SetItem IR node, and wrapped + # indices for Slice objects. + self.ext_shapes = ext_shapes if ext_shapes else {} + # rel_map keeps a map of relative sizes that we have seen so + # that if we compute the same relative sizes different times + # in different ways we can associate those two instances + # of the same relative size to the same equivalence class. + self.rel_map = {} + # wrap_index() computes the effectual index given a slice and a + # dimension's size. We need to be able to know that two wrap_index + # calls are equivalent. They are known to be equivalent if the slice + # and dimension sizes of the two wrap_index calls are equivalent. + # wrap_map maps from a tuple of equivalence class ids for a slice and + # a dimension size to some new equivalence class id for the output size. + self.wrap_map = {} + super(SymbolicEquivSet, self).__init__( + typemap, defs, ind_to_var, obj_to_ind, ind_to_obj, next_id + ) + + def empty(self): + """Return an empty SymbolicEquivSet. + """ + return SymbolicEquivSet(self.typemap) + + def __repr__(self): + return ( + "SymbolicEquivSet({}, ind_to_var={}, def_by={}, " + "ref_by={}, ext_shapes={})".format( + self.ind_to_obj, + self.ind_to_var, + self.def_by, + self.ref_by, + self.ext_shapes, + ) + ) + + def clone(self): + """Return a new copy. + """ + return SymbolicEquivSet( + self.typemap, + def_by=copy.copy(self.def_by), + ref_by=copy.copy(self.ref_by), + ext_shapes=copy.copy(self.ext_shapes), + defs=copy.copy(self.defs), + ind_to_var=copy.copy(self.ind_to_var), + obj_to_ind=copy.deepcopy(self.obj_to_ind), + ind_to_obj=copy.deepcopy(self.ind_to_obj), + next_id=self.next_ind, + ) + + def get_rel(self, name): + """Retrieve a definition pair for the given variable, + or return None if it is not available. + """ + return guard(self._get_or_set_rel, name) + + def _get_or_set_rel(self, name, func_ir=None): + """Retrieve a definition pair for the given variable, + and if it is not already available, try to look it up + in the given func_ir, and remember it for future use. + """ + if isinstance(name, ir.Var): + name = name.name + require(self.defs.get(name, 0) == 1) + if name in self.def_by: + return self.def_by[name] + else: + require(func_ir is not None) + + def plus(x, y): + x_is_const = isinstance(x, int) + y_is_const = isinstance(y, int) + if x_is_const: + if y_is_const: + return x + y + else: + (var, offset) = y + return (var, x + offset) + else: + (var, offset) = x + if y_is_const: + return (var, y + offset) + else: + return None + + def minus(x, y): + if isinstance(y, int): + return plus(x, -y) + elif ( + isinstance(x, tuple) + and isinstance(y, tuple) + and x[0] == y[0] + ): + return minus(x[1], y[1]) + else: + return None + + expr = get_definition(func_ir, name) + value = (name, 0) # default to its own name + if isinstance(expr, ir.Expr): + if expr.op == "call": + fname, mod_name = find_callname( + func_ir, expr, typemap=self.typemap + ) + if ( + fname == "wrap_index" + and mod_name == "numba.parfors.array_analysis" + ): + index = tuple( + self.obj_to_ind.get(x.name, -1) for x in expr.args + ) + # If wrap_index for a slice works on a variable + # that is not analyzable (e.g., multiple definitions) + # then we have to return None here since we can't know + # how that size will compare to others if we can't + # analyze some part of the slice. + if -1 in index: + return None + names = self.ext_shapes.get(index, []) + names.append(name) + if len(names) > 0: + self._insert(names) + self.ext_shapes[index] = names + elif expr.op == "binop": + lhs = self._get_or_set_rel(expr.lhs, func_ir) + rhs = self._get_or_set_rel(expr.rhs, func_ir) + # If either the lhs or rhs is not analyzable + # then don't try to record information this var. + if lhs is None or rhs is None: + return None + elif expr.fn == operator.add: + value = plus(lhs, rhs) + elif expr.fn == operator.sub: + value = minus(lhs, rhs) + elif isinstance(expr, ir.Const) and isinstance(expr.value, int): + value = expr.value + require(value is not None) + # update def_by table + self.def_by[name] = value + if isinstance(value, int) or ( + isinstance(value, tuple) + and (value[0] != name or value[1] != 0) + ): + # update ref_by table too + if isinstance(value, tuple): + (var, offset) = value + if not (var in self.ref_by): + self.ref_by[var] = [] + self.ref_by[var].append((name, -offset)) + # insert new equivalence if found + ind = self._get_ind(var) + if ind >= 0: + objs = self.ind_to_obj[ind] + names = [] + for obj in objs: + if obj in self.ref_by: + names += [ + x + for (x, i) in self.ref_by[obj] + if i == -offset + ] + if len(names) > 1: + super(SymbolicEquivSet, self)._insert(names) + return value + + def define(self, var, redefined, func_ir=None, typ=None): + """Besides incrementing the definition count of the given variable + name, it will also retrieve and simplify its definition from func_ir, + and remember the result for later equivalence comparison. Supported + operations are: + 1. arithmetic plus and minus with constants + 2. wrap_index (relative to some given size) + """ + if isinstance(var, ir.Var): + name = var.name + else: + name = var + super(SymbolicEquivSet, self).define(name, redefined) + if ( + func_ir + and self.defs.get(name, 0) == 1 + and isinstance(typ, types.Number) + ): + value = guard(self._get_or_set_rel, name, func_ir) + # turn constant definition into equivalence + if isinstance(value, int): + self._insert([name, value]) + if isinstance(var, ir.Var): + ind = self._get_or_add_ind(name) + if not (ind in self.ind_to_obj): + self.ind_to_obj[ind] = [name] + self.obj_to_ind[name] = ind + if ind in self.ind_to_var: + self.ind_to_var[ind].append(var) + else: + self.ind_to_var[ind] = [var] + return True + + def _insert(self, objs): + """Overload _insert method to handle ind changes between relative + objects. Returns True if some change is made, false otherwise. + """ + indset = set() + uniqs = set() + for obj in objs: + ind = self._get_ind(obj) + if ind == -1: + uniqs.add(obj) + elif not (ind in indset): + uniqs.add(obj) + indset.add(ind) + if len(uniqs) <= 1: + return False + uniqs = list(uniqs) + super(SymbolicEquivSet, self)._insert(uniqs) + objs = self.ind_to_obj[self._get_ind(uniqs[0])] + + # New equivalence guided by def_by and ref_by + offset_dict = {} + + def get_or_set(d, k): + if k in d: + v = d[k] + else: + v = [] + d[k] = v + return v + + for obj in objs: + if obj in self.def_by: + value = self.def_by[obj] + if isinstance(value, tuple): + (name, offset) = value + get_or_set(offset_dict, -offset).append(name) + if name in self.ref_by: # relative to name + for (v, i) in self.ref_by[name]: + get_or_set(offset_dict, -(offset + i)).append(v) + if obj in self.ref_by: + for (name, offset) in self.ref_by[obj]: + get_or_set(offset_dict, offset).append(name) + for names in offset_dict.values(): + self._insert(names) + return True + + def set_shape_setitem(self, obj, shape): + """remember shapes of SetItem IR nodes. + """ + assert isinstance(obj, (ir.StaticSetItem, ir.SetItem)) + self.ext_shapes[obj] = shape + + def _get_shape(self, obj): + """Overload _get_shape to retrieve the shape of SetItem IR nodes. + """ + if isinstance(obj, (ir.StaticSetItem, ir.SetItem)): + require(obj in self.ext_shapes) + return self.ext_shapes[obj] + else: + assert isinstance(obj, ir.Var) + typ = self.typemap[obj.name] + # for slice type, return the shape variable itself + if isinstance(typ, types.SliceType): + return (obj,) + else: + return super(SymbolicEquivSet, self)._get_shape(obj) + + +class WrapIndexMeta(object): + """ + Array analysis should be able to analyze all the function + calls that it adds to the IR. That way, array analysis can + be run as often as needed and you should get the same + equivalencies. One modification to the IR that array analysis + makes is the insertion of wrap_index calls. Thus, repeated + array analysis passes should be able to analyze these wrap_index + calls. The difficulty of these calls is that the equivalence + class of the left-hand side of the assignment is not present in + the arguments to wrap_index in the right-hand side. Instead, + the equivalence class of the wrap_index output is a combination + of the wrap_index args. The important thing to + note is that if the equivalence classes of the slice size + and the dimension's size are the same for two wrap index + calls then we can be assured of the answer being the same. + So, we maintain the wrap_map dict that maps from a tuple + of equivalence class ids for the slice and dimension size + to some new equivalence class id for the output size. + However, when we are analyzing the first such wrap_index + call we don't have a variable there to associate to the + size since we're in the process of analyzing the instruction + that creates that mapping. So, instead we return an object + of this special class and analyze_inst will establish the + connection between a tuple of the parts of this object + below and the left-hand side variable. + """ + + def __init__(self, slice_size, dim_size): + self.slice_size = slice_size + self.dim_size = dim_size + + +class ArrayAnalysis(object): + aa_count = 0 + + """Analyzes Numpy array computations for properties such as + shape/size equivalence, and keeps track of them on a per-block + basis. The analysis should only be run once because it modifies + the incoming IR by inserting assertion statements that safeguard + parfor optimizations. + """ + + def __init__(self, context, func_ir, typemap, calltypes): + self.context = context + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + + # EquivSet of variables, indexed by block number + self.equiv_sets = {} + # keep attr calls to arrays like t=A.sum() as {t:('sum',A)} + self.array_attr_calls = {} + # keep attrs of objects (value,attr)->shape_var + self.object_attrs = {} + # keep prepended instructions from conditional branch + self.prepends = {} + # keep track of pruned precessors when branch degenerates to jump + self.pruned_predecessors = {} + + def get_equiv_set(self, block_label): + """Return the equiv_set object of an block given its label. + """ + return self.equiv_sets[block_label] + + def remove_redefineds(self, redefineds): + """Take a set of variables in redefineds and go through all + the currently existing equivalence sets (created in topo order) + and remove that variable from all of them since it is multiply + defined within the function. + """ + unused = set() + for r in redefineds: + for eslabel in self.equiv_sets: + es = self.equiv_sets[eslabel] + es.define(r, unused) + + def run(self, blocks=None, equiv_set=None): + """run array shape analysis on the given IR blocks, resulting in + modified IR and finalized EquivSet for each block. + """ + if blocks is None: + blocks = self.func_ir.blocks + + self.func_ir._definitions = build_definitions(self.func_ir.blocks) + + if equiv_set is None: + init_equiv_set = SymbolicEquivSet(self.typemap) + else: + init_equiv_set = equiv_set + + self.alias_map, self.arg_aliases = find_potential_aliases( + blocks, + self.func_ir.arg_names, + self.typemap, + self.func_ir + ) + + aa_count_save = ArrayAnalysis.aa_count + ArrayAnalysis.aa_count += 1 + if config.DEBUG_ARRAY_OPT >= 1: + print("Starting ArrayAnalysis:", aa_count_save) + dprint_func_ir(self.func_ir, "before array analysis", blocks) + + if config.DEBUG_ARRAY_OPT >= 1: + print( + "ArrayAnalysis variable types: ", sorted(self.typemap.items()) + ) + print("ArrayAnalysis call types: ", self.calltypes) + + cfg = compute_cfg_from_blocks(blocks) + topo_order = find_topo_order(blocks, cfg=cfg) + # Traverse blocks in topological order + self._run_on_blocks(topo_order, blocks, cfg, init_equiv_set) + + if config.DEBUG_ARRAY_OPT >= 1: + self.dump() + print( + "ArrayAnalysis post variable types: ", + sorted(self.typemap.items()), + ) + print("ArrayAnalysis post call types: ", self.calltypes) + + dprint_func_ir(self.func_ir, "after array analysis", blocks) + if config.DEBUG_ARRAY_OPT >= 1: + print("Ending ArrayAnalysis:", aa_count_save) + + def _run_on_blocks(self, topo_order, blocks, cfg, init_equiv_set): + for label in topo_order: + if config.DEBUG_ARRAY_OPT >= 2: + print("Processing block:", label) + block = blocks[label] + scope = block.scope + pending_transforms = self._determine_transform( + cfg, block, label, scope, init_equiv_set + ) + self._combine_to_new_block(block, pending_transforms) + + def _combine_to_new_block(self, block, pending_transforms): + """Combine the new instructions from previous pass into a new block + body. + """ + new_body = [] + for inst, pre, post in pending_transforms: + for instr in pre: + new_body.append(instr) + new_body.append(inst) + for instr in post: + new_body.append(instr) + block.body = new_body + + def _determine_transform(self, cfg, block, label, scope, init_equiv_set): + """Determine the transformation for each instruction in the block + """ + equiv_set = None + # equiv_set is the intersection of predecessors + preds = cfg.predecessors(label) + # some incoming edge may be pruned due to prior analysis + if label in self.pruned_predecessors: + pruned = self.pruned_predecessors[label] + else: + pruned = [] + # Go through each incoming edge, process prepended instructions and + # calculate beginning equiv_set of current block as an intersection + # of incoming ones. + if config.DEBUG_ARRAY_OPT >= 2: + print("preds:", preds) + for (p, q) in preds: + if config.DEBUG_ARRAY_OPT >= 2: + print("p, q:", p, q) + if p in pruned: + continue + if p in self.equiv_sets: + from_set = self.equiv_sets[p].clone() + if config.DEBUG_ARRAY_OPT >= 2: + print("p in equiv_sets", from_set) + if (p, label) in self.prepends: + instrs = self.prepends[(p, label)] + for inst in instrs: + redefined = set() + self._analyze_inst( + label, scope, from_set, inst, redefined + ) + # Remove anything multiply defined in this block + # from every block equivs. + # NOTE: necessary? can't observe effect in testsuite + self.remove_redefineds(redefined) + if equiv_set is None: + equiv_set = from_set + else: + equiv_set = equiv_set.intersect(from_set) + redefined = set() + equiv_set.union_defs(from_set.defs, redefined) + # Remove anything multiply defined in this block + # from every block equivs. + # NOTE: necessary? can't observe effect in testsuite + self.remove_redefineds(redefined) + + # Start with a new equiv_set if none is computed + if equiv_set is None: + equiv_set = init_equiv_set + self.equiv_sets[label] = equiv_set + + # Go through instructions in a block, and insert pre/post + # instructions as we analyze them. + pending_transforms = [] + for inst in block.body: + redefined = set() + pre, post = self._analyze_inst( + label, scope, equiv_set, inst, redefined + ) + # Remove anything multiply defined in this block from every block + # equivs. + if len(redefined) > 0: + self.remove_redefineds(redefined) + + pending_transforms.append((inst, pre, post)) + return pending_transforms + + def dump(self): + """dump per-block equivalence sets for debugging purposes. + """ + print("Array Analysis: ", self.equiv_sets) + + def _define(self, equiv_set, var, typ, value): + self.typemap[var.name] = typ + self.func_ir._definitions[var.name] = [value] + redefineds = set() + equiv_set.define(var, redefineds, self.func_ir, typ) + + class AnalyzeResult(object): + def __init__(self, **kwargs): + self.kwargs = kwargs + + def _analyze_inst(self, label, scope, equiv_set, inst, redefined): + pre = [] + post = [] + if config.DEBUG_ARRAY_OPT >= 2: + print("analyze_inst:", inst) + if isinstance(inst, ir.Assign): + lhs = inst.target + typ = self.typemap[lhs.name] + shape = None + if isinstance(typ, types.ArrayCompatible) and typ.ndim == 0: + shape = () + elif isinstance(inst.value, ir.Expr): + result = self._analyze_expr(scope, equiv_set, inst.value, lhs) + if result: + require(isinstance(result, ArrayAnalysis.AnalyzeResult)) + if 'shape' in result.kwargs: + shape = result.kwargs['shape'] + if 'pre' in result.kwargs: + pre.extend(result.kwargs['pre']) + if 'post' in result.kwargs: + post.extend(result.kwargs['post']) + if 'rhs' in result.kwargs: + inst.value = result.kwargs['rhs'] + elif isinstance(inst.value, (ir.Var, ir.Const)): + shape = inst.value + elif isinstance(inst.value, ir.Global): + gvalue = inst.value.value + # only integer values can be part of shape + # TODO: support cases with some but not all integer values or + # nested tuples + if (isinstance(gvalue, tuple) + and all(isinstance(v, int) for v in gvalue)): + shape = gvalue + elif isinstance(gvalue, int): + shape = (gvalue,) + elif isinstance(inst.value, ir.Arg): + if ( + isinstance(typ, types.containers.UniTuple) + and isinstance(typ.dtype, types.Integer) + ): + shape = inst.value + elif ( + isinstance(typ, types.containers.Tuple) + and all([isinstance(x, + (types.Integer, types.IntegerLiteral)) + for x in typ.types] + ) + ): + shape = inst.value + + if isinstance(shape, ir.Const): + if isinstance(shape.value, tuple): + loc = shape.loc + shape = tuple(ir.Const(x, loc) for x in shape.value) + elif isinstance(shape.value, int): + shape = (shape,) + else: + shape = None + elif isinstance(shape, ir.Var) and isinstance( + self.typemap[shape.name], types.Integer + ): + shape = (shape,) + elif isinstance(shape, WrapIndexMeta): + """ Here we've got the special WrapIndexMeta object + back from analyzing a wrap_index call. We define + the lhs and then get it's equivalence class then + add the mapping from the tuple of slice size and + dimensional size equivalence ids to the lhs + equivalence id. + """ + equiv_set.define(lhs, redefined, self.func_ir, typ) + lhs_ind = equiv_set._get_ind(lhs.name) + if lhs_ind != -1: + equiv_set.wrap_map[ + (shape.slice_size, shape.dim_size) + ] = lhs_ind + return pre, post + + if isinstance(typ, types.ArrayCompatible): + if ( + shape is not None + and isinstance(shape, ir.Var) + and isinstance( + self.typemap[shape.name], types.containers.BaseTuple + ) + ): + pass + elif ( + shape is None + or isinstance(shape, tuple) + or ( + isinstance(shape, ir.Var) + and not equiv_set.has_shape(shape) + ) + ): + shape = self._gen_shape_call( + equiv_set, lhs, typ.ndim, shape, post + ) + elif isinstance(typ, types.UniTuple): + if shape and isinstance(typ.dtype, types.Integer): + shape = self._gen_shape_call( + equiv_set, lhs, len(typ), shape, post + ) + elif ( + isinstance(typ, types.containers.Tuple) + and all([isinstance(x, + (types.Integer, types.IntegerLiteral)) + for x in typ.types] + ) + ): + shape = self._gen_shape_call( + equiv_set, lhs, len(typ), shape, post + ) + + """ See the comment on the define() function. + + We need only call define(), which will invalidate a variable + from being in the equivalence sets on multiple definitions, + if the variable was not previously defined or if the new + definition would be in a conflicting equivalence class to the + original equivalence class for the variable. + + insert_equiv() returns True if either of these conditions are + True and then we call define() in those cases. + If insert_equiv() returns False then no changes were made and + all equivalence classes are consistent upon a redefinition so + no invalidation is needed and we don't call define(). + """ + needs_define = True + if shape is not None: + needs_define = equiv_set.insert_equiv(lhs, shape) + if needs_define: + equiv_set.define(lhs, redefined, self.func_ir, typ) + elif isinstance(inst, (ir.StaticSetItem, ir.SetItem)): + index = ( + inst.index if isinstance(inst, ir.SetItem) else inst.index_var + ) + result = guard( + self._index_to_shape, scope, equiv_set, inst.target, index + ) + if not result: + return [], [] + if result[0] is not None: + assert isinstance(inst, (ir.StaticSetItem, ir.SetItem)) + inst.index = result[0] + result = result[1] + target_shape = result.kwargs['shape'] + if 'pre' in result.kwargs: + pre = result.kwargs['pre'] + value_shape = equiv_set.get_shape(inst.value) + if value_shape == (): # constant + equiv_set.set_shape_setitem(inst, target_shape) + return pre, [] + elif value_shape is not None: + target_typ = self.typemap[inst.target.name] + require(isinstance(target_typ, types.ArrayCompatible)) + target_ndim = target_typ.ndim + shapes = [target_shape, value_shape] + names = [inst.target.name, inst.value.name] + broadcast_result = self._broadcast_assert_shapes( + scope, equiv_set, inst.loc, shapes, names + ) + require('shape' in broadcast_result.kwargs) + require('pre' in broadcast_result.kwargs) + shape = broadcast_result.kwargs['shape'] + asserts = broadcast_result.kwargs['pre'] + n = len(shape) + # shape dimension must be within target dimension + assert target_ndim >= n + equiv_set.set_shape_setitem(inst, shape) + return pre + asserts, [] + else: + return pre, [] + elif isinstance(inst, ir.Branch): + + def handle_call_binop(cond_def): + br = None + if cond_def.fn == operator.eq: + br = inst.truebr + otherbr = inst.falsebr + cond_val = 1 + elif cond_def.fn == operator.ne: + br = inst.falsebr + otherbr = inst.truebr + cond_val = 0 + lhs_typ = self.typemap[cond_def.lhs.name] + rhs_typ = self.typemap[cond_def.rhs.name] + if br is not None and ( + ( + isinstance(lhs_typ, types.Integer) + and isinstance(rhs_typ, types.Integer) + ) + or ( + isinstance(lhs_typ, types.BaseTuple) + and isinstance(rhs_typ, types.BaseTuple) + ) + ): + loc = inst.loc + args = (cond_def.lhs, cond_def.rhs) + asserts = self._make_assert_equiv( + scope, loc, equiv_set, args + ) + asserts.append( + ir.Assign(ir.Const(cond_val, loc), cond_var, loc) + ) + self.prepends[(label, br)] = asserts + self.prepends[(label, otherbr)] = [ + ir.Assign(ir.Const(1 - cond_val, loc), cond_var, loc) + ] + + cond_var = inst.cond + cond_def = guard(get_definition, self.func_ir, cond_var) + if not cond_def: # phi variable has no single definition + # We'll use equiv_set to try to find a cond_def instead + equivs = equiv_set.get_equiv_set(cond_var) + defs = [] + for name in equivs: + if isinstance(name, str) and name in self.typemap: + var_def = guard( + get_definition, self.func_ir, name, lhs_only=True + ) + if isinstance(var_def, ir.Var): + var_def = var_def.name + if var_def: + defs.append(var_def) + else: + defs.append(name) + defvars = set(filter(lambda x: isinstance(x, str), defs)) + defconsts = set(defs).difference(defvars) + if len(defconsts) == 1: + cond_def = list(defconsts)[0] + elif len(defvars) == 1: + cond_def = guard( + get_definition, self.func_ir, list(defvars)[0] + ) + if isinstance(cond_def, ir.Expr) and cond_def.op == 'binop': + handle_call_binop(cond_def) + elif isinstance(cond_def, ir.Expr) and cond_def.op == 'call': + # this handles bool(predicate) + glbl_bool = guard(get_definition, self.func_ir, cond_def.func) + if glbl_bool is not None and glbl_bool.value is bool: + if len(cond_def.args) == 1: + condition = guard(get_definition, self.func_ir, + cond_def.args[0]) + if (condition is not None and + isinstance(condition, ir.Expr) and + condition.op == 'binop'): + handle_call_binop(condition) + else: + if isinstance(cond_def, ir.Const): + cond_def = cond_def.value + if isinstance(cond_def, int) or isinstance(cond_def, bool): + # condition is always true/false, prune the outgoing edge + pruned_br = inst.falsebr if cond_def else inst.truebr + if pruned_br in self.pruned_predecessors: + self.pruned_predecessors[pruned_br].append(label) + else: + self.pruned_predecessors[pruned_br] = [label] + + elif type(inst) in array_analysis_extensions: + # let external calls handle stmt if type matches + f = array_analysis_extensions[type(inst)] + pre, post = f(inst, equiv_set, self.typemap, self) + + return pre, post + + def _analyze_expr(self, scope, equiv_set, expr, lhs): + fname = "_analyze_op_{}".format(expr.op) + try: + fn = getattr(self, fname) + except AttributeError: + return None + return guard(fn, scope, equiv_set, expr, lhs) + + def _analyze_op_getattr(self, scope, equiv_set, expr, lhs): + # TODO: getattr of npytypes.Record + if expr.attr == "T" and self._isarray(expr.value.name): + return self._analyze_op_call_numpy_transpose( + scope, equiv_set, expr.loc, [expr.value], {} + ) + elif expr.attr == "shape": + shape = equiv_set.get_shape(expr.value) + return ArrayAnalysis.AnalyzeResult(shape=shape) + elif expr.attr in ("real", "imag") and self._isarray(expr.value.name): + # Shape of real or imag attr is the same as the shape of the array + # itself. + return ArrayAnalysis.AnalyzeResult(shape=expr.value) + elif self._isarray(lhs.name): + canonical_value = get_canonical_alias( + expr.value.name, self.alias_map + ) + if (canonical_value, expr.attr) in self.object_attrs: + return ArrayAnalysis.AnalyzeResult( + shape=self.object_attrs[(canonical_value, expr.attr)] + ) + else: + typ = self.typemap[lhs.name] + post = [] + shape = self._gen_shape_call( + equiv_set, lhs, typ.ndim, None, post + ) + self.object_attrs[(canonical_value, expr.attr)] = shape + return ArrayAnalysis.AnalyzeResult(shape=shape, post=post) + + return None + + def _analyze_op_cast(self, scope, equiv_set, expr, lhs): + return ArrayAnalysis.AnalyzeResult(shape=expr.value) + + def _analyze_op_exhaust_iter(self, scope, equiv_set, expr, lhs): + var = expr.value + typ = self.typemap[var.name] + if isinstance(typ, types.BaseTuple): + require(len(typ) == expr.count) + require(equiv_set.has_shape(var)) + return ArrayAnalysis.AnalyzeResult(shape=var) + return None + + def gen_literal_slice_part( + self, + arg_val, + loc, + scope, + stmts, + equiv_set, + name="static_literal_slice_part", + ): + # Create var to hold the calculated slice size. + static_literal_slice_part_var = ir.Var(scope, mk_unique_var(name), loc) + static_literal_slice_part_val = ir.Const(arg_val, loc) + static_literal_slice_part_typ = types.IntegerLiteral(arg_val) + # We'll prepend this slice size calculation to the get/setitem. + stmts.append( + ir.Assign( + value=static_literal_slice_part_val, + target=static_literal_slice_part_var, + loc=loc, + ) + ) + self._define( + equiv_set, + static_literal_slice_part_var, + static_literal_slice_part_typ, + static_literal_slice_part_val, + ) + return static_literal_slice_part_var, static_literal_slice_part_typ + + def gen_static_slice_size( + self, lhs_rel, rhs_rel, loc, scope, stmts, equiv_set + ): + the_var, *_ = self.gen_literal_slice_part( + rhs_rel - lhs_rel, + loc, + scope, + stmts, + equiv_set, + name="static_slice_size", + ) + return the_var + + def gen_explicit_neg( + self, + arg, + arg_rel, + arg_typ, + size_typ, + loc, + scope, + dsize, + stmts, + equiv_set, + ): + assert not isinstance(size_typ, int) + # Create var to hold the calculated slice size. + explicit_neg_var = ir.Var(scope, mk_unique_var("explicit_neg"), loc) + explicit_neg_val = ir.Expr.binop(operator.add, dsize, arg, loc=loc) + # Determine the type of that var. Can be literal if we know the + # literal size of the dimension. + explicit_neg_typ = types.intp + self.calltypes[explicit_neg_val] = signature( + explicit_neg_typ, size_typ, arg_typ + ) + # We'll prepend this slice size calculation to the get/setitem. + stmts.append( + ir.Assign(value=explicit_neg_val, target=explicit_neg_var, loc=loc) + ) + self._define( + equiv_set, explicit_neg_var, explicit_neg_typ, explicit_neg_val + ) + return explicit_neg_var, explicit_neg_typ + + def update_replacement_slice( + self, + lhs, + lhs_typ, + lhs_rel, + dsize_rel, + replacement_slice, + slice_index, + need_replacement, + loc, + scope, + stmts, + equiv_set, + size_typ, + dsize, + ): + # Do compile-time calculation of real index value if both the given + # index value and the array length are known at compile time. + known = False + if isinstance(lhs_rel, int): + # If the index and the array size are known then the real index + # can be calculated at compile time. + if lhs_rel == 0: + # Special-case 0 as nothing needing to be done. + known = True + elif isinstance(dsize_rel, int): + known = True + # Calculate the real index. + wil = wrap_index_literal(lhs_rel, dsize_rel) + # If the given index value is between 0 and dsize then + # there's no need to rewrite anything. + if wil != lhs_rel: + if config.DEBUG_ARRAY_OPT >= 2: + print("Replacing slice to hard-code known slice size.") + # Indicate we will need to replace the slice var. + need_replacement = True + literal_var, literal_typ = self.gen_literal_slice_part( + wil, loc, scope, stmts, equiv_set + ) + assert slice_index == 0 or slice_index == 1 + if slice_index == 0: + replacement_slice.args = ( + literal_var, + replacement_slice.args[1], + ) + else: + replacement_slice.args = ( + replacement_slice.args[0], + literal_var, + ) + # Update lhs information with the negative removed. + lhs = replacement_slice.args[slice_index] + lhs_typ = literal_typ + lhs_rel = equiv_set.get_rel(lhs) + elif lhs_rel < 0: + # Indicate we will need to replace the slice var. + need_replacement = True + if config.DEBUG_ARRAY_OPT >= 2: + print("Replacing slice due to known negative index.") + explicit_neg_var, explicit_neg_typ = self.gen_explicit_neg( + lhs, + lhs_rel, + lhs_typ, + size_typ, + loc, + scope, + dsize, + stmts, + equiv_set, + ) + if slice_index == 0: + replacement_slice.args = ( + explicit_neg_var, + replacement_slice.args[1], + ) + else: + replacement_slice.args = ( + replacement_slice.args[0], + explicit_neg_var, + ) + # Update lhs information with the negative removed. + lhs = replacement_slice.args[slice_index] + lhs_typ = explicit_neg_typ + lhs_rel = equiv_set.get_rel(lhs) + return ( + lhs, + lhs_typ, + lhs_rel, + replacement_slice, + need_replacement, + known, + ) + + def slice_size(self, index, dsize, equiv_set, scope, stmts): + """Reason about the size of a slice represented by the "index" + variable, and return a variable that has this size data, or + raise GuardException if it cannot reason about it. + + The computation takes care of negative values used in the slice + with respect to the given dimensional size ("dsize"). + + Extra statements required to produce the result are appended + to parent function's stmts list. + """ + loc = index.loc + # Get the definition of the index variable. + index_def = get_definition(self.func_ir, index) + fname, mod_name = find_callname( + self.func_ir, index_def, typemap=self.typemap + ) + require(fname == 'slice' and mod_name in ('builtins')) + require(len(index_def.args) == 2) + lhs = index_def.args[0] + rhs = index_def.args[1] + size_typ = self.typemap[dsize.name] + lhs_typ = self.typemap[lhs.name] + rhs_typ = self.typemap[rhs.name] + + if config.DEBUG_ARRAY_OPT >= 2: + print(f"slice_size index={index} dsize={dsize} " + f"index_def={index_def} lhs={lhs} rhs={rhs} " + f"size_typ={size_typ} lhs_typ={lhs_typ} rhs_typ={rhs_typ}") + + # Make a deepcopy of the original slice to use as the + # replacement slice, which we will modify as necessary + # below to convert all negative constants in the slice + # to be relative to the dimension size. + replacement_slice = copy.deepcopy(index_def) + need_replacement = False + + # Fill in the left side of the slice's ":" with 0 if it wasn't + # specified. + if isinstance(lhs_typ, types.NoneType): + zero_var = ir.Var(scope, mk_unique_var("zero"), loc) + zero = ir.Const(0, loc) + stmts.append(ir.Assign(value=zero, target=zero_var, loc=loc)) + self._define(equiv_set, zero_var, types.IntegerLiteral(0), zero) + lhs = zero_var + lhs_typ = types.IntegerLiteral(0) + replacement_slice.args = (lhs, replacement_slice.args[1]) + need_replacement = True + if config.DEBUG_ARRAY_OPT >= 2: + print("Replacing slice because lhs is None.") + + # Fill in the right side of the slice's ":" with the array + # length if it wasn't specified. + if isinstance(rhs_typ, types.NoneType): + rhs = dsize + rhs_typ = size_typ + replacement_slice.args = (replacement_slice.args[0], rhs) + need_replacement = True + if config.DEBUG_ARRAY_OPT >= 2: + print("Replacing slice because lhs is None.") + + lhs_rel = equiv_set.get_rel(lhs) + rhs_rel = equiv_set.get_rel(rhs) + dsize_rel = equiv_set.get_rel(dsize) + if config.DEBUG_ARRAY_OPT >= 2: + print( + "lhs_rel", lhs_rel, "rhs_rel", rhs_rel, "dsize_rel", dsize_rel + ) + + # Update replacement slice with the real index value if we can + # compute it at compile time. + [ + lhs, + lhs_typ, + lhs_rel, + replacement_slice, + need_replacement, + lhs_known, + ] = self.update_replacement_slice( + lhs, + lhs_typ, + lhs_rel, + dsize_rel, + replacement_slice, + 0, + need_replacement, + loc, + scope, + stmts, + equiv_set, + size_typ, + dsize, + ) + [ + rhs, + rhs_typ, + rhs_rel, + replacement_slice, + need_replacement, + rhs_known, + ] = self.update_replacement_slice( + rhs, + rhs_typ, + rhs_rel, + dsize_rel, + replacement_slice, + 1, + need_replacement, + loc, + scope, + stmts, + equiv_set, + size_typ, + dsize, + ) + if config.DEBUG_ARRAY_OPT >= 2: + print("lhs_known:", lhs_known) + print("rhs_known:", rhs_known) + + # If neither of the parts of the slice were negative constants + # then we don't need to do slice replacement in the IR. + if not need_replacement: + replacement_slice_var = None + else: + # Create a new var for the replacement slice. + replacement_slice_var = ir.Var( + scope, mk_unique_var("replacement_slice"), loc + ) + # Create a deepcopy of slice calltype so that when we change it + # below the original isn't changed. Make the types of the parts of + # the slice intp. + new_arg_typs = (types.intp, types.intp) + rs_calltype = self.typemap[index_def.func.name].get_call_type( + self.context, new_arg_typs, {} + ) + self.calltypes[replacement_slice] = rs_calltype + stmts.append( + ir.Assign( + value=replacement_slice, + target=replacement_slice_var, + loc=loc, + ) + ) + # The type of the replacement slice is the same type as the + # original. + self.typemap[replacement_slice_var.name] = self.typemap[index.name] + + if config.DEBUG_ARRAY_OPT >= 2: + print( + "after rewriting negatives", + "lhs_rel", + lhs_rel, + "rhs_rel", + rhs_rel, + ) + + if lhs_known and rhs_known: + if config.DEBUG_ARRAY_OPT >= 2: + print("lhs and rhs known so return static size") + return ( + self.gen_static_slice_size( + lhs_rel, rhs_rel, loc, scope, stmts, equiv_set + ), + replacement_slice_var, + ) + + if ( + lhs_rel == 0 + and isinstance(rhs_rel, tuple) + and equiv_set.is_equiv(dsize, rhs_rel[0]) + and rhs_rel[1] == 0 + ): + return dsize, None + + slice_typ = types.intp + orig_slice_typ = slice_typ + + size_var = ir.Var(scope, mk_unique_var("slice_size"), loc) + size_val = ir.Expr.binop(operator.sub, rhs, lhs, loc=loc) + self.calltypes[size_val] = signature(slice_typ, rhs_typ, lhs_typ) + self._define(equiv_set, size_var, slice_typ, size_val) + size_rel = equiv_set.get_rel(size_var) + if config.DEBUG_ARRAY_OPT >= 2: + print("size_rel", size_rel, type(size_rel)) + + wrap_var = ir.Var(scope, mk_unique_var("wrap"), loc) + wrap_def = ir.Global("wrap_index", wrap_index, loc=loc) + fnty = get_global_func_typ(wrap_index) + sig = self.context.resolve_function_type( + fnty, (orig_slice_typ, size_typ), {} + ) + self._define(equiv_set, wrap_var, fnty, wrap_def) + + def gen_wrap_if_not_known(val, val_typ, known): + if not known: + var = ir.Var(scope, mk_unique_var("var"), loc) + var_typ = types.intp + new_value = ir.Expr.call(wrap_var, [val, dsize], {}, loc) + # def_res will be False if there is something unanalyzable + # that prevents a size association from being created. + self._define(equiv_set, var, var_typ, new_value) + self.calltypes[new_value] = sig + return (var, var_typ, new_value) + else: + return (val, val_typ, None) + + var1, var1_typ, value1 = gen_wrap_if_not_known(lhs, lhs_typ, lhs_known) + var2, var2_typ, value2 = gen_wrap_if_not_known(rhs, rhs_typ, rhs_known) + + stmts.append(ir.Assign(value=size_val, target=size_var, loc=loc)) + stmts.append(ir.Assign(value=wrap_def, target=wrap_var, loc=loc)) + if value1 is not None: + stmts.append(ir.Assign(value=value1, target=var1, loc=loc)) + if value2 is not None: + stmts.append(ir.Assign(value=value2, target=var2, loc=loc)) + + post_wrap_size_var = ir.Var( + scope, mk_unique_var("post_wrap_slice_size"), loc + ) + post_wrap_size_val = ir.Expr.binop(operator.sub, + var2, + var1, + loc=loc) + self.calltypes[post_wrap_size_val] = signature( + slice_typ, var2_typ, var1_typ + ) + self._define( + equiv_set, post_wrap_size_var, slice_typ, post_wrap_size_val + ) + + stmts.append( + ir.Assign( + value=post_wrap_size_val, target=post_wrap_size_var, loc=loc + ) + ) + + # rel_map keeps a map of relative sizes that we have seen so + # that if we compute the same relative sizes different times + # in different ways we can associate those two instances + # of the same relative size to the same equivalence class. + if isinstance(size_rel, tuple): + if config.DEBUG_ARRAY_OPT >= 2: + print("size_rel is tuple", equiv_set.rel_map) + rel_map_entry = None + for rme, rme_tuple in equiv_set.rel_map.items(): + if rme[1] == size_rel[1] and equiv_set.is_equiv( + rme[0], size_rel[0] + ): + rel_map_entry = rme_tuple + break + + if rel_map_entry is not None: + # We have seen this relative size before so establish + # equivalence to the previous variable. + if config.DEBUG_ARRAY_OPT >= 2: + print("establishing equivalence to", rel_map_entry) + equiv_set.insert_equiv(size_var, rel_map_entry[0]) + equiv_set.insert_equiv(post_wrap_size_var, rel_map_entry[1]) + else: + # The first time we've seen this relative size so + # remember the variable defining that size. + equiv_set.rel_map[size_rel] = (size_var, post_wrap_size_var) + + return post_wrap_size_var, replacement_slice_var + + def _index_to_shape(self, scope, equiv_set, var, ind_var): + """For indexing like var[index] (either write or read), see if + the index corresponds to a range/slice shape. + Returns a 2-tuple where the first item is either None or a ir.Var + to be used to replace the index variable in the outer getitem or + setitem instruction. The second item is also a tuple returning + the shape and prepending instructions. + """ + typ = self.typemap[var.name] + require(isinstance(typ, types.ArrayCompatible)) + ind_typ = self.typemap[ind_var.name] + ind_shape = equiv_set._get_shape(ind_var) + var_shape = equiv_set._get_shape(var) + if isinstance(ind_typ, types.SliceType): + seq_typs = (ind_typ,) + seq = (ind_var,) + else: + require(isinstance(ind_typ, types.BaseTuple)) + seq, op = find_build_sequence(self.func_ir, ind_var) + require(op == "build_tuple") + seq_typs = tuple(self.typemap[x.name] for x in seq) + require(len(ind_shape) == len(seq_typs) == len(var_shape)) + stmts = [] + + def to_shape(typ, index, dsize): + if isinstance(typ, types.SliceType): + return self.slice_size(index, dsize, equiv_set, scope, stmts) + elif isinstance(typ, types.Number): + return None, None + else: + # unknown dimension size for this index, + # so we'll raise GuardException + require(False) + + shape_list = [] + index_var_list = [] + replace_index = False + for (typ, size, dsize, orig_ind) in zip(seq_typs, + ind_shape, + var_shape, + seq): + # Convert the given dimension of the get/setitem index expr. + shape_part, index_var_part = to_shape(typ, size, dsize) + shape_list.append(shape_part) + + # to_shape will return index_var_part as not None if a + # replacement of the slice is required to convert from + # negative indices to positive relative indices. + if index_var_part is not None: + # Remember that we need to replace the build_tuple. + replace_index = True + index_var_list.append(index_var_part) + else: + index_var_list.append(orig_ind) + + # If at least one of the dimensions required a new slice variable + # then we'll need to replace the build_tuple for this get/setitem. + if replace_index: + # Multi-dimensional array access needs a replacement tuple built. + if len(index_var_list) > 1: + # Make a variable to hold the new build_tuple. + replacement_build_tuple_var = ir.Var( + scope, + mk_unique_var("replacement_build_tuple"), + ind_shape[0].loc, + ) + # Create the build tuple from the accumulated index vars above. + new_build_tuple = ir.Expr.build_tuple( + index_var_list, ind_shape[0].loc + ) + stmts.append( + ir.Assign( + value=new_build_tuple, + target=replacement_build_tuple_var, + loc=ind_shape[0].loc, + ) + ) + # New build_tuple has same type as the original one. + self.typemap[replacement_build_tuple_var.name] = ind_typ + else: + replacement_build_tuple_var = index_var_list[0] + else: + replacement_build_tuple_var = None + + shape = tuple(shape_list) + require(not all(x is None for x in shape)) + shape = tuple(x for x in shape if x is not None) + return (replacement_build_tuple_var, + ArrayAnalysis.AnalyzeResult(shape=shape, pre=stmts)) + + def _analyze_op_getitem(self, scope, equiv_set, expr, lhs): + result = self._index_to_shape(scope, equiv_set, expr.value, expr.index) + if result[0] is not None: + expr.index = result[0] + return result[1] + + def _analyze_op_static_getitem(self, scope, equiv_set, expr, lhs): + var = expr.value + typ = self.typemap[var.name] + if not isinstance(typ, types.BaseTuple): + result = self._index_to_shape( + scope, equiv_set, expr.value, expr.index_var + ) + if result[0] is not None: + expr.index_var = result[0] + return result[1] + shape = equiv_set._get_shape(var) + if isinstance(expr.index, int): + require(expr.index < len(shape)) + return ArrayAnalysis.AnalyzeResult(shape=shape[expr.index]) + elif isinstance(expr.index, slice): + return ArrayAnalysis.AnalyzeResult(shape=shape[expr.index]) + require(False) + + def _analyze_op_unary(self, scope, equiv_set, expr, lhs): + require(expr.fn in UNARY_MAP_OP) + # for scalars, only + operator results in equivalence + # for example, if "m = -n", m and n are not equivalent + if self._isarray(expr.value.name) or expr.fn == operator.add: + return ArrayAnalysis.AnalyzeResult(shape=expr.value) + return None + + def _analyze_op_binop(self, scope, equiv_set, expr, lhs): + require(expr.fn in BINARY_MAP_OP) + return self._analyze_broadcast( + scope, equiv_set, expr.loc, [expr.lhs, expr.rhs], expr.fn + ) + + def _analyze_op_inplace_binop(self, scope, equiv_set, expr, lhs): + require(expr.fn in INPLACE_BINARY_MAP_OP) + return self._analyze_broadcast( + scope, equiv_set, expr.loc, [expr.lhs, expr.rhs], expr.fn + ) + + def _analyze_op_arrayexpr(self, scope, equiv_set, expr, lhs): + return self._analyze_broadcast( + scope, equiv_set, expr.loc, expr.list_vars(), None + ) + + def _analyze_op_build_tuple(self, scope, equiv_set, expr, lhs): + # For the moment, we can't do anything with tuples that + # contain multi-dimensional arrays, compared to array dimensions. + # Return None to say we won't track this tuple if a part of it + # is an array. + for x in expr.items: + if ( + isinstance(x, ir.Var) + and isinstance(self.typemap[x.name], types.ArrayCompatible) + and self.typemap[x.name].ndim > 1 + ): + return None + + consts = [] + for var in expr.items: + x = guard(find_const, self.func_ir, var) + if x is not None: + consts.append(x) + else: + break + else: + out = tuple([ir.Const(x, expr.loc) for x in consts]) + return ArrayAnalysis.AnalyzeResult( + shape=out, + rhs=ir.Const(tuple(consts), expr.loc) + ) + # default return for non-const + return ArrayAnalysis.AnalyzeResult(shape=tuple(expr.items)) + + def _analyze_op_call(self, scope, equiv_set, expr, lhs): + from numba.stencils.stencil import StencilFunc + + callee = expr.func + callee_def = get_definition(self.func_ir, callee) + if isinstance( + callee_def, (ir.Global, ir.FreeVar) + ) and is_namedtuple_class(callee_def.value): + return ArrayAnalysis.AnalyzeResult(shape=tuple(expr.args)) + if isinstance(callee_def, (ir.Global, ir.FreeVar)) and isinstance( + callee_def.value, StencilFunc + ): + args = expr.args + return self._analyze_stencil( + scope, + equiv_set, + callee_def.value, + expr.loc, + args, + dict(expr.kws), + ) + + fname, mod_name = find_callname( + self.func_ir, expr, typemap=self.typemap + ) + added_mod_name = False + # call via attribute (i.e. array.func) + if isinstance(mod_name, ir.Var) and isinstance( + self.typemap[mod_name.name], types.ArrayCompatible + ): + args = [mod_name] + expr.args + mod_name = "numpy" + # Remember that args and expr.args don't alias. + added_mod_name = True + else: + args = expr.args + fname = "_analyze_op_call_{}_{}".format(mod_name, fname).replace( + ".", "_" + ) + if fname in UFUNC_MAP_OP: # known numpy ufuncs + return self._analyze_broadcast(scope, equiv_set, + expr.loc, args, None) + else: + try: + fn = getattr(self, fname) + except AttributeError: + return None + result = guard( + fn, + scope=scope, + equiv_set=equiv_set, + loc=expr.loc, + args=args, + kws=dict(expr.kws), + ) + # We want the ability for function fn to modify arguments. + # If args and expr.args don't alias then we need the extra + # step of assigning back into expr.args from the args that + # was passed to fn. + if added_mod_name: + expr.args = args[1:] + return result + + def _analyze_op_call_builtins_len(self, scope, equiv_set, loc, args, kws): + # python 3 version of len() + require(len(args) == 1) + var = args[0] + typ = self.typemap[var.name] + require(isinstance(typ, types.ArrayCompatible)) + shape = equiv_set._get_shape(var) + return ArrayAnalysis.AnalyzeResult(shape=shape[0], rhs=shape[0]) + + def _analyze_op_call_numba_parfors_array_analysis_assert_equiv( + self, scope, equiv_set, loc, args, kws + ): + equiv_set.insert_equiv(*args[1:]) + return None + + def _analyze_op_call_numba_parfors_array_analysis_wrap_index( + self, scope, equiv_set, loc, args, kws + ): + """ Analyze wrap_index calls added by a previous run of + Array Analysis + """ + require(len(args) == 2) + # Two parts to wrap index, the specified slice size... + slice_size = args[0].name + # ...and the size of the dimension. + dim_size = args[1].name + # Get the equivalence class ids for both. + slice_eq = equiv_set._get_or_add_ind(slice_size) + dim_eq = equiv_set._get_or_add_ind(dim_size) + # See if a previous wrap_index calls we've analyzed maps from + # the same pair of equivalence class ids for slice and dim size. + if (slice_eq, dim_eq) in equiv_set.wrap_map: + wrap_ind = equiv_set.wrap_map[(slice_eq, dim_eq)] + require(wrap_ind in equiv_set.ind_to_var) + vs = equiv_set.ind_to_var[wrap_ind] + require(vs != []) + # Return the shape of the variable from the previous wrap_index. + return ArrayAnalysis.AnalyzeResult(shape=(vs[0],)) + else: + # We haven't seen this combination of slice and dim + # equivalence class ids so return a WrapIndexMeta so that + # _analyze_inst can establish the connection to the lhs var. + return ArrayAnalysis.AnalyzeResult( + shape=WrapIndexMeta(slice_eq, dim_eq) + ) + + def _analyze_numpy_create_array(self, scope, equiv_set, loc, args, kws): + shape_var = None + if len(args) > 0: + shape_var = args[0] + elif "shape" in kws: + shape_var = kws["shape"] + if shape_var: + return ArrayAnalysis.AnalyzeResult(shape=shape_var) + raise errors.UnsupportedRewriteError( + "Must specify a shape for array creation", + loc=loc, + ) + + def _analyze_op_call_numpy_empty(self, scope, equiv_set, loc, args, kws): + return self._analyze_numpy_create_array( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numba_np_unsafe_ndarray_empty_inferred( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_create_array( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_zeros(self, scope, equiv_set, loc, args, kws): + return self._analyze_numpy_create_array( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_ones(self, scope, equiv_set, loc, args, kws): + return self._analyze_numpy_create_array( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_eye(self, scope, equiv_set, loc, args, kws): + if len(args) > 0: + N = args[0] + elif "N" in kws: + N = kws["N"] + else: + raise errors.UnsupportedRewriteError( + "Expect one argument (or 'N') to eye function", + loc=loc, + ) + if "M" in kws: + M = kws["M"] + else: + M = N + return ArrayAnalysis.AnalyzeResult(shape=(N, M)) + + def _analyze_op_call_numpy_identity( + self, scope, equiv_set, loc, args, kws + ): + assert len(args) > 0 + N = args[0] + return ArrayAnalysis.AnalyzeResult(shape=(N, N)) + + def _analyze_op_call_numpy_diag(self, scope, equiv_set, loc, args, kws): + # We can only reason about the output shape when the input is 1D or + # square 2D. + assert len(args) > 0 + a = args[0] + assert isinstance(a, ir.Var) + atyp = self.typemap[a.name] + if isinstance(atyp, types.ArrayCompatible): + if atyp.ndim == 2: + if "k" in kws: # will proceed only when k = 0 or absent + k = kws["k"] + if not equiv_set.is_equiv(k, 0): + return None + (m, n) = equiv_set._get_shape(a) + if equiv_set.is_equiv(m, n): + return ArrayAnalysis.AnalyzeResult(shape=(m,)) + elif atyp.ndim == 1: + (m,) = equiv_set._get_shape(a) + return ArrayAnalysis.AnalyzeResult(shape=(m, m)) + return None + + def _analyze_numpy_array_like(self, scope, equiv_set, args, kws): + assert len(args) > 0 + var = args[0] + typ = self.typemap[var.name] + if isinstance(typ, types.Integer): + return ArrayAnalysis.AnalyzeResult(shape=(1,)) + elif isinstance(typ, types.ArrayCompatible) and equiv_set.has_shape( + var + ): + return ArrayAnalysis.AnalyzeResult(shape=var) + return None + + def _analyze_op_call_numpy_ravel(self, scope, equiv_set, loc, args, kws): + assert len(args) == 1 + var = args[0] + typ = self.typemap[var.name] + assert isinstance(typ, types.ArrayCompatible) + # output array is same shape as input if input is 1D + if typ.ndim == 1 and equiv_set.has_shape(var): + if typ.layout == "C": + # output is the same as input (no copy) for 'C' layout + # optimize out the call + return ArrayAnalysis.AnalyzeResult(shape=var, rhs=var) + else: + return ArrayAnalysis.AnalyzeResult(shape=var) + # TODO: handle multi-D input arrays (calc array size) + return None + + def _analyze_op_call_numpy_copy(self, scope, equiv_set, loc, args, kws): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_empty_like( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_zeros_like( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_ones_like( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_full_like( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_asfortranarray( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_numpy_array_like(scope, equiv_set, args, kws) + + def _analyze_op_call_numpy_reshape(self, scope, equiv_set, loc, args, kws): + n = len(args) + assert n > 1 + if n == 2: + typ = self.typemap[args[1].name] + if isinstance(typ, types.BaseTuple): + return ArrayAnalysis.AnalyzeResult(shape=args[1]) + + # Reshape is allowed to take one argument that has the value <0. + # This means that the size of that dimension should be inferred from + # the size of the array being reshaped and the other dimensions + # specified. Our general approach here is to see if the reshape + # has any <0 arguments. If it has more than one then throw a + # ValueError. If exactly one <0 argument is found, remember its + # argument index. + stmts = [] + neg_one_index = -1 + for arg_index in range(1, len(args)): + reshape_arg = args[arg_index] + reshape_arg_def = guard(get_definition, self.func_ir, reshape_arg) + if isinstance(reshape_arg_def, ir.Const): + if reshape_arg_def.value < 0: + if neg_one_index == -1: + neg_one_index = arg_index + else: + msg = ("The reshape API may only include one negative" + " argument.") + raise errors.UnsupportedRewriteError( + msg, loc=reshape_arg.loc + ) + + if neg_one_index >= 0: + # If exactly one <0 argument to reshape was found, then we are + # going to insert code to calculate the missing dimension and then + # replace the negative with the calculated size. We do this + # because we can't let array equivalence analysis think that some + # array has a negative dimension size. + loc = args[0].loc + # Create a variable to hold the size of the array being reshaped. + calc_size_var = ir.Var(scope, mk_unique_var("calc_size_var"), loc) + self.typemap[calc_size_var.name] = types.intp + # Assign the size of the array calc_size_var. + init_calc_var = ir.Assign( + ir.Expr.getattr(args[0], "size", loc), calc_size_var, loc + ) + stmts.append(init_calc_var) + # For each other dimension, divide the current size by the + # specified dimension size. Once all such dimensions have been + # done then what is left is the size of the negative dimension. + for arg_index in range(1, len(args)): + # Skip the negative dimension. + if arg_index == neg_one_index: + continue + div_calc_size_var = ir.Var( + scope, mk_unique_var("calc_size_var"), loc + ) + self.typemap[div_calc_size_var.name] = types.intp + # Calculate the next size as current size // the current arg's + # dimension size. + new_binop = ir.Expr.binop( + operator.floordiv, calc_size_var, args[arg_index], loc + ) + div_calc = ir.Assign(new_binop, div_calc_size_var, loc) + self.calltypes[new_binop] = signature( + types.intp, types.intp, types.intp + ) + stmts.append(div_calc) + calc_size_var = div_calc_size_var + # Put the calculated value back into the reshape arguments, + # replacing the negative. + args[neg_one_index] = calc_size_var + + return ArrayAnalysis.AnalyzeResult(shape=tuple(args[1:]), pre=stmts) + + def _analyze_op_call_numpy_transpose( + self, scope, equiv_set, loc, args, kws + ): + in_arr = args[0] + typ = self.typemap[in_arr.name] + assert isinstance( + typ, types.ArrayCompatible + ), "Invalid np.transpose argument" + shape = equiv_set._get_shape(in_arr) + if len(args) == 1: + return ArrayAnalysis.AnalyzeResult(shape=tuple(reversed(shape))) + axes = [guard(find_const, self.func_ir, a) for a in args[1:]] + if isinstance(axes[0], tuple): + axes = list(axes[0]) + if None in axes: + return None + ret = [shape[i] for i in axes] + return ArrayAnalysis.AnalyzeResult(shape=tuple(ret)) + + def _analyze_op_call_numpy_random_rand( + self, scope, equiv_set, loc, args, kws + ): + if len(args) > 0: + return ArrayAnalysis.AnalyzeResult(shape=tuple(args)) + return None + + def _analyze_op_call_numpy_random_randn( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_call_numpy_random_rand( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_numpy_random_with_size( + self, pos, scope, equiv_set, args, kws + ): + if "size" in kws: + return ArrayAnalysis.AnalyzeResult(shape=kws["size"]) + if len(args) > pos: + return ArrayAnalysis.AnalyzeResult(shape=args[pos]) + return None + + def _analyze_op_call_numpy_random_ranf( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 0, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_random_sample( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 0, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_sample( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 0, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_random( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 0, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_standard_normal( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 0, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_chisquare( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_weibull( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_power( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_geometric( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_exponential( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_poisson( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_rayleigh( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 1, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_normal( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_uniform( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_beta( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_binomial( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_f( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_gamma( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_lognormal( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_laplace( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_randint( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 2, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_random_triangular( + self, scope, equiv_set, loc, args, kws + ): + return self._analyze_op_numpy_random_with_size( + 3, scope, equiv_set, args, kws + ) + + def _analyze_op_call_numpy_concatenate( + self, scope, equiv_set, loc, args, kws + ): + assert len(args) > 0 + loc = args[0].loc + seq, op = find_build_sequence(self.func_ir, args[0]) + n = len(seq) + require(n > 0) + axis = 0 + if "axis" in kws: + if isinstance(kws["axis"], int): # internal use only + axis = kws["axis"] + else: + axis = find_const(self.func_ir, kws["axis"]) + elif len(args) > 1: + axis = find_const(self.func_ir, args[1]) + require(isinstance(axis, int)) + require(op == "build_tuple") + shapes = [equiv_set._get_shape(x) for x in seq] + if axis < 0: + axis = len(shapes[0]) + axis + require(0 <= axis < len(shapes[0])) + asserts = [] + new_shape = [] + if n == 1: # from one array N-dimension to (N-1)-dimension + shape = shapes[0] + # first size is the count, pop it out of shapes + n = equiv_set.get_equiv_const(shapes[0]) + shape.pop(0) + for i in range(len(shape)): + if i == axis: + m = equiv_set.get_equiv_const(shape[i]) + size = m * n if (m and n) else None + else: + size = self._sum_size(equiv_set, shapes[0]) + new_shape.append(size) + else: # from n arrays N-dimension to N-dimension + for i in range(len(shapes[0])): + if i == axis: + size = self._sum_size( + equiv_set, [shape[i] for shape in shapes] + ) + else: + sizes = [shape[i] for shape in shapes] + asserts.append( + self._call_assert_equiv(scope, loc, equiv_set, sizes) + ) + size = sizes[0] + new_shape.append(size) + return ArrayAnalysis.AnalyzeResult( + shape=tuple(new_shape), + pre=sum(asserts, []) + ) + + def _analyze_op_call_numpy_stack(self, scope, equiv_set, loc, args, kws): + assert len(args) > 0 + loc = args[0].loc + seq, op = find_build_sequence(self.func_ir, args[0]) + n = len(seq) + require(n > 0) + axis = 0 + if "axis" in kws: + if isinstance(kws["axis"], int): # internal use only + axis = kws["axis"] + else: + axis = find_const(self.func_ir, kws["axis"]) + elif len(args) > 1: + axis = find_const(self.func_ir, args[1]) + require(isinstance(axis, int)) + # only build_tuple can give reliable count + require(op == "build_tuple") + shapes = [equiv_set._get_shape(x) for x in seq] + asserts = self._call_assert_equiv(scope, loc, equiv_set, seq) + shape = shapes[0] + if axis < 0: + axis = len(shape) + axis + 1 + require(0 <= axis <= len(shape)) + new_shape = list(shape[0:axis]) + [n] + list(shape[axis:]) + return ArrayAnalysis.AnalyzeResult(shape=tuple(new_shape), pre=asserts) + + def _analyze_op_call_numpy_vstack(self, scope, equiv_set, loc, args, kws): + assert len(args) == 1 + seq, op = find_build_sequence(self.func_ir, args[0]) + n = len(seq) + require(n > 0) + typ = self.typemap[seq[0].name] + require(isinstance(typ, types.ArrayCompatible)) + if typ.ndim < 2: + return self._analyze_op_call_numpy_stack( + scope, equiv_set, loc, args, kws + ) + else: + kws["axis"] = 0 + return self._analyze_op_call_numpy_concatenate( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_hstack(self, scope, equiv_set, loc, args, kws): + assert len(args) == 1 + seq, op = find_build_sequence(self.func_ir, args[0]) + n = len(seq) + require(n > 0) + typ = self.typemap[seq[0].name] + require(isinstance(typ, types.ArrayCompatible)) + if typ.ndim < 2: + kws["axis"] = 0 + else: + kws["axis"] = 1 + return self._analyze_op_call_numpy_concatenate( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_dstack(self, scope, equiv_set, loc, args, kws): + assert len(args) == 1 + seq, op = find_build_sequence(self.func_ir, args[0]) + n = len(seq) + require(n > 0) + typ = self.typemap[seq[0].name] + require(isinstance(typ, types.ArrayCompatible)) + if typ.ndim == 1: + kws["axis"] = 1 + result = self._analyze_op_call_numpy_stack( + scope, equiv_set, loc, args, kws + ) + require(result) + result.kwargs['shape'] = tuple([1] + list(result.kwargs['shape'])) + return result + elif typ.ndim == 2: + kws["axis"] = 2 + return self._analyze_op_call_numpy_stack( + scope, equiv_set, loc, args, kws + ) + else: + kws["axis"] = 2 + return self._analyze_op_call_numpy_concatenate( + scope, equiv_set, loc, args, kws + ) + + def _analyze_op_call_numpy_cumsum(self, scope, equiv_set, loc, args, kws): + # TODO + return None + + def _analyze_op_call_numpy_cumprod(self, scope, equiv_set, loc, args, kws): + # TODO + return None + + def _analyze_op_call_numpy_linspace( + self, scope, equiv_set, loc, args, kws + ): + n = len(args) + num = 50 + if n > 2: + num = args[2] + elif "num" in kws: + num = kws["num"] + return ArrayAnalysis.AnalyzeResult(shape=(num,)) + + def _analyze_op_call_numpy_dot(self, scope, equiv_set, loc, args, kws): + n = len(args) + assert n >= 2 + loc = args[0].loc + require(all([self._isarray(x.name) for x in args])) + typs = [self.typemap[x.name] for x in args] + dims = [ty.ndim for ty in typs] + require(all(x > 0 for x in dims)) + if dims[0] == 1 and dims[1] == 1: + return None + shapes = [equiv_set._get_shape(x) for x in args] + if dims[0] == 1: + asserts = self._call_assert_equiv( + scope, loc, equiv_set, [shapes[0][0], shapes[1][-2]] + ) + return ArrayAnalysis.AnalyzeResult( + shape=tuple(shapes[1][0:-2] + shapes[1][-1:]), + pre=asserts + ) + if dims[1] == 1: + asserts = self._call_assert_equiv( + scope, loc, equiv_set, [shapes[0][-1], shapes[1][0]] + ) + return ArrayAnalysis.AnalyzeResult( + shape=tuple(shapes[0][0:-1]), + pre=asserts + ) + if dims[0] == 2 and dims[1] == 2: + asserts = self._call_assert_equiv( + scope, loc, equiv_set, [shapes[0][1], shapes[1][0]] + ) + return ArrayAnalysis.AnalyzeResult( + shape=(shapes[0][0], shapes[1][1]), + pre=asserts + ) + if dims[0] > 2: # TODO: handle higher dimension cases + pass + return None + + def _analyze_stencil(self, scope, equiv_set, stencil_func, loc, args, kws): + # stencil requires that all relatively indexed array arguments are + # of same size + std_idx_arrs = stencil_func.options.get("standard_indexing", ()) + kernel_arg_names = stencil_func.kernel_ir.arg_names + if isinstance(std_idx_arrs, str): + std_idx_arrs = (std_idx_arrs,) + rel_idx_arrs = [] + assert len(args) > 0 and len(args) == len(kernel_arg_names) + for arg, var in zip(kernel_arg_names, args): + typ = self.typemap[var.name] + if isinstance(typ, types.ArrayCompatible) and not ( + arg in std_idx_arrs + ): + rel_idx_arrs.append(var) + n = len(rel_idx_arrs) + require(n > 0) + asserts = self._call_assert_equiv(scope, loc, equiv_set, rel_idx_arrs) + shape = equiv_set.get_shape(rel_idx_arrs[0]) + return ArrayAnalysis.AnalyzeResult(shape=shape, pre=asserts) + + def _analyze_op_call_numpy_linalg_inv( + self, scope, equiv_set, loc, args, kws + ): + require(len(args) >= 1) + return ArrayAnalysis.AnalyzeResult(shape=equiv_set._get_shape(args[0])) + + def _analyze_broadcast(self, scope, equiv_set, loc, args, fn): + """Infer shape equivalence of arguments based on Numpy broadcast rules + and return shape of output + https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html + """ + tups = list(filter(lambda a: self._istuple(a.name), args)) + # Here we have a tuple concatenation. + if len(tups) == 2 and fn.__name__ == 'add': + # If either of the tuples is empty then the resulting shape + # is just the other tuple. + tup0typ = self.typemap[tups[0].name] + tup1typ = self.typemap[tups[1].name] + if tup0typ.count == 0: + return ArrayAnalysis.AnalyzeResult( + shape=equiv_set.get_shape(tups[1]) + ) + if tup1typ.count == 0: + return ArrayAnalysis.AnalyzeResult( + shape=equiv_set.get_shape(tups[0]) + ) + + try: + shapes = [equiv_set.get_shape(x) for x in tups] + if None in shapes: + return None + concat_shapes = sum(shapes, ()) + return ArrayAnalysis.AnalyzeResult( + shape=concat_shapes + ) + except GuardException: + return None + + # else arrays + arrs = list(filter(lambda a: self._isarray(a.name), args)) + require(len(arrs) > 0) + names = [x.name for x in arrs] + dims = [self.typemap[x.name].ndim for x in arrs] + max_dim = max(dims) + require(max_dim > 0) + try: + shapes = [equiv_set.get_shape(x) for x in arrs] + except GuardException: + return ArrayAnalysis.AnalyzeResult( + shape=arrs[0], + pre=self._call_assert_equiv(scope, loc, equiv_set, arrs) + ) + pre = [] + if None in shapes: + # There is at least 1 shape that we don't know, + # so we need to generate that shape now. + new_shapes = [] + for i, s in enumerate(shapes): + if s is None: + var = arrs[i] + typ = self.typemap[var.name] + shape = self._gen_shape_call( + equiv_set, var, typ.ndim, None, pre + ) + new_shapes.append(shape) + else: + new_shapes.append(s) + shapes = new_shapes + + result = self._broadcast_assert_shapes( + scope, equiv_set, loc, shapes, names + ) + if pre: + # If we had to generate a shape we have to insert + # that code before the broadcast assertion. + if 'pre' in result.kwargs: + prev_pre = result.kwargs['pre'] + else: + prev_pre = [] + result.kwargs['pre'] = pre + prev_pre + return result + + def _broadcast_assert_shapes(self, scope, equiv_set, loc, shapes, names): + """Produce assert_equiv for sizes in each dimension, taking into + account of dimension coercion and constant size of 1. + """ + asserts = [] + new_shape = [] + max_dim = max([len(shape) for shape in shapes]) + const_size_one = None + for i in range(max_dim): + sizes = [] + size_names = [] + for name, shape in zip(names, shapes): + if i < len(shape): + size = shape[len(shape) - 1 - i] + const_size = equiv_set.get_equiv_const(size) + if const_size == 1: + const_size_one = size + else: + sizes.append(size) # non-1 size to front + size_names.append(name) + if sizes == []: + assert const_size_one is not None + sizes.append(const_size_one) + size_names.append("1") + asserts.append( + self._call_assert_equiv( + scope, loc, equiv_set, sizes, names=size_names + ) + ) + new_shape.append(sizes[0]) + return ArrayAnalysis.AnalyzeResult( + shape=tuple(reversed(new_shape)), + pre=sum(asserts, []) + ) + + def _call_assert_equiv(self, scope, loc, equiv_set, args, names=None): + insts = self._make_assert_equiv( + scope, loc, equiv_set, args, names=names + ) + if len(args) > 1: + equiv_set.insert_equiv(*args) + return insts + + def _make_assert_equiv(self, scope, loc, equiv_set, _args, names=None): + # filter out those that are already equivalent + if config.DEBUG_ARRAY_OPT >= 2: + print("make_assert_equiv:", _args, names) + if names is None: + names = [x.name for x in _args] + args = [] + arg_names = [] + for name, x in zip(names, _args): + if config.DEBUG_ARRAY_OPT >= 2: + print("name, x:", name, x) + seen = False + for y in args: + if config.DEBUG_ARRAY_OPT >= 2: + print("is equiv to?", y, equiv_set.is_equiv(x, y)) + if equiv_set.is_equiv(x, y): + seen = True + break + if not seen: + args.append(x) + arg_names.append(name) + + # no assertion necessary if there are less than two + if len(args) < 2: + if config.DEBUG_ARRAY_OPT >= 2: + print( + "Will not insert assert_equiv as args are known to be " + "equivalent." + ) + return [] + + msg = "Sizes of {} do not match on {}".format( + ", ".join(arg_names), loc + ) + msg_val = ir.Const(msg, loc) + msg_typ = types.StringLiteral(msg) + msg_var = ir.Var(scope, mk_unique_var("msg"), loc) + self.typemap[msg_var.name] = msg_typ + argtyps = tuple([msg_typ] + [self.typemap[x.name] for x in args]) + + # assert_equiv takes vararg, which requires a tuple as argument type + tup_typ = types.StarArgTuple.from_types(argtyps) + + # prepare function variable whose type may vary since it takes vararg + assert_var = ir.Var(scope, mk_unique_var("assert"), loc) + assert_def = ir.Global("assert_equiv", assert_equiv, loc=loc) + fnty = get_global_func_typ(assert_equiv) + sig = self.context.resolve_function_type(fnty, (tup_typ,), {}) + self._define(equiv_set, assert_var, fnty, assert_def) + + # The return value from assert_equiv is always of none type. + var = ir.Var(scope, mk_unique_var("ret"), loc) + value = ir.Expr.call(assert_var, [msg_var] + args, {}, loc=loc) + self._define(equiv_set, var, types.none, value) + self.calltypes[value] = sig + + return [ + ir.Assign(value=msg_val, target=msg_var, loc=loc), + ir.Assign(value=assert_def, target=assert_var, loc=loc), + ir.Assign(value=value, target=var, loc=loc), + ] + + def _gen_shape_call(self, equiv_set, var, ndims, shape, post): + # attr call: A_sh_attr = getattr(A, shape) + if isinstance(shape, ir.Var): + shape = equiv_set.get_shape(shape) + + # already a tuple variable that contains size + if isinstance(shape, ir.Var): + attr_var = shape + shape_attr_call = None + shape = None + elif isinstance(shape, ir.Arg): + attr_var = var + shape_attr_call = None + shape = None + else: + shape_attr_call = ir.Expr.getattr(var, "shape", var.loc) + attr_var = ir.Var( + var.scope, mk_unique_var("{}_shape".format(var.name)), var.loc + ) + shape_attr_typ = types.containers.UniTuple(types.intp, ndims) + size_vars = [] + use_attr_var = False + # trim shape tuple if it is more than ndim + if shape: + nshapes = len(shape) + if ndims < nshapes: + shape = shape[(nshapes - ndims) :] + for i in range(ndims): + skip = False + if shape and shape[i]: + if isinstance(shape[i], ir.Var): + typ = self.typemap[shape[i].name] + if isinstance(typ, (types.Number, types.SliceType)): + size_var = shape[i] + skip = True + else: + if isinstance(shape[i], int): + size_val = ir.Const(shape[i], var.loc) + else: + size_val = shape[i] + assert isinstance(size_val, ir.Const) + size_var = ir.Var( + var.scope, + mk_unique_var("{}_size{}".format(var.name, i)), + var.loc, + ) + post.append(ir.Assign(size_val, size_var, var.loc)) + self._define(equiv_set, size_var, types.intp, size_val) + skip = True + if not skip: + # get size: Asize0 = A_sh_attr[0] + size_var = ir.Var( + var.scope, + mk_unique_var("{}_size{}".format(var.name, i)), + var.loc, + ) + getitem = ir.Expr.static_getitem(attr_var, i, None, var.loc) + use_attr_var = True + self.calltypes[getitem] = None + post.append(ir.Assign(getitem, size_var, var.loc)) + self._define(equiv_set, size_var, types.intp, getitem) + size_vars.append(size_var) + if use_attr_var and shape_attr_call: + # only insert shape call if there is any getitem call + post.insert(0, ir.Assign(shape_attr_call, attr_var, var.loc)) + self._define(equiv_set, attr_var, shape_attr_typ, shape_attr_call) + return tuple(size_vars) + + def _isarray(self, varname): + typ = self.typemap[varname] + return isinstance(typ, types.npytypes.Array) and typ.ndim > 0 + + def _istuple(self, varname): + typ = self.typemap[varname] + return isinstance(typ, types.BaseTuple) + + def _sum_size(self, equiv_set, sizes): + """Return the sum of the given list of sizes if they are all equivalent + to some constant, or None otherwise. + """ + s = 0 + for size in sizes: + n = equiv_set.get_equiv_const(size) + if n is None: + return None + else: + s += n + return s + + +UNARY_MAP_OP = list(npydecl.NumpyRulesUnaryArrayOperator._op_map.keys()) + [ + operator.pos +] +BINARY_MAP_OP = npydecl.NumpyRulesArrayOperator._op_map.keys() +INPLACE_BINARY_MAP_OP = npydecl.NumpyRulesInplaceArrayOperator._op_map.keys() +UFUNC_MAP_OP = [f.__name__ for f in npydecl.supported_ufuncs] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor.py new file mode 100644 index 0000000000000000000000000000000000000000..27548a2c9504902a517810c89c4ab93bb5b94a6d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor.py @@ -0,0 +1,5253 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +""" +This module transforms data-parallel operations such as Numpy calls into +'Parfor' nodes, which are nested loops that can be parallelized. +It also implements optimizations such as loop fusion, and extends the rest of +compiler analysis and optimizations to support Parfors. +This is similar to ParallelAccelerator package in Julia: +https://github.com/IntelLabs/ParallelAccelerator.jl +'Parallelizing Julia with a Non-invasive DSL', T. Anderson et al., ECOOP'17. +""" +import types as pytypes # avoid confusion with numba.types +import sys, math +import os +import textwrap +import copy +import inspect +import linecache +from functools import reduce +from collections import defaultdict, OrderedDict, namedtuple +from contextlib import contextmanager +import operator +from dataclasses import make_dataclass +import warnings + +from llvmlite import ir as lir +from numba.core.imputils import impl_ret_untracked +import numba.core.ir +from numba.core import types, typing, utils, errors, ir, analysis, postproc, rewrites, typeinfer, config, ir_utils +from numba import prange, pndindex +from numba.np.npdatetime_helpers import datetime_minimum, datetime_maximum +from numba.np.numpy_support import as_dtype, numpy_version +from numba.core.typing.templates import infer_global, AbstractTemplate +from numba.stencils.stencilparfor import StencilPass +from numba.core.extending import register_jitable, lower_builtin + +from numba.core.ir_utils import ( + mk_unique_var, + next_label, + mk_alloc, + get_np_ufunc_typ, + mk_range_block, + mk_loop_header, + get_name_var_table, + replace_vars, + replace_vars_inner, + visit_vars, + visit_vars_inner, + remove_dead, + copy_propagate, + get_block_copies, + apply_copy_propagate, + dprint_func_ir, + find_topo_order, + get_stmt_writes, + rename_labels, + get_call_table, + simplify, + simplify_CFG, + has_no_side_effect, + canonicalize_array_math, + add_offset_to_labels, + find_callname, + find_build_sequence, + guard, + require, + GuardException, + compile_to_numba_ir, + get_definition, + build_definitions, + replace_arg_nodes, + replace_returns, + is_getitem, + is_setitem, + is_get_setitem, + index_var_of_get_setitem, + set_index_var_of_get_setitem, + find_potential_aliases, + replace_var_names, + transfer_scope, +) + +from numba.core.analysis import (compute_use_defs, compute_live_map, + compute_dead_maps, compute_cfg_from_blocks) +from numba.core.controlflow import CFGraph +from numba.core.typing import npydecl, signature +from numba.core.types.functions import Function +from numba.parfors.array_analysis import (random_int_args, random_1arg_size, + random_2arg_sizelast, random_3arg_sizelast, + random_calls, assert_equiv) +from numba.core.extending import overload +import copy +import numpy +import numpy as np +from numba.parfors import array_analysis +import numba.cpython.builtins +from numba.stencils import stencilparfor +# circular dependency: import numba.npyufunc.dufunc.DUFunc + +# wrapped pretty print +_termwidth = 80 +_txtwrapper = textwrap.TextWrapper(width=_termwidth, drop_whitespace=False) +def print_wrapped(x): + for l in x.splitlines(): + [print(y) for y in _txtwrapper.wrap(l)] + +sequential_parfor_lowering = False + +# init_prange is a sentinel call that specifies the start of the initialization +# code for the computation in the upcoming prange call +# This lets the prange pass to put the code in the generated parfor's init_block +def init_prange(): + return + +@overload(init_prange) +def init_prange_overload(): + def no_op(): + return + return no_op + +class internal_prange(object): + + def __new__(cls, *args): + return range(*args) + + +def min_parallel_impl(return_type, arg): + # XXX: use prange for 1D arrays since pndindex returns a 1-tuple instead of + # integer. This causes type and fusion issues. + if arg.ndim == 0: + def min_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + if isinstance(arg.dtype, (types.NPDatetime, types.NPTimedelta)): + # NaT is always returned if it is in the array + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_max_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = datetime_minimum(val, in_arr[i]) + return val + else: + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_max_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = min(val, in_arr[i]) + return val + else: + def min_1(in_arr): + numba.parfors.parfor.init_prange() + min_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_max_value(in_arr.dtype) + for i in numba.pndindex(in_arr.shape): + val = min(val, in_arr[i]) + return val + return min_1 + +def max_parallel_impl(return_type, arg): + if arg.ndim == 0: + def max_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + if isinstance(arg.dtype, (types.NPDatetime, types.NPTimedelta)): + # NaT is always returned if it is in the array + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_min_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = datetime_maximum(val, in_arr[i]) + return val + else: + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_min_value(in_arr.dtype) + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = max(val, in_arr[i]) + return val + else: + def max_1(in_arr): + numba.parfors.parfor.init_prange() + max_checker(len(in_arr)) + val = numba.cpython.builtins.get_type_min_value(in_arr.dtype) + for i in numba.pndindex(in_arr.shape): + val = max(val, in_arr[i]) + return val + return max_1 + +def argmin_parallel_impl(in_arr): + numba.parfors.parfor.init_prange() + argmin_checker(len(in_arr)) + A = in_arr.ravel() + init_val = numba.cpython.builtins.get_type_max_value(A.dtype) + ival = typing.builtins.IndexValue(0, init_val) + for i in numba.parfors.parfor.internal_prange(len(A)): + curr_ival = typing.builtins.IndexValue(i, A[i]) + ival = min(ival, curr_ival) + return ival.index + +def argmax_parallel_impl(in_arr): + numba.parfors.parfor.init_prange() + argmax_checker(len(in_arr)) + A = in_arr.ravel() + init_val = numba.cpython.builtins.get_type_min_value(A.dtype) + ival = typing.builtins.IndexValue(0, init_val) + for i in numba.parfors.parfor.internal_prange(len(A)): + curr_ival = typing.builtins.IndexValue(i, A[i]) + ival = max(ival, curr_ival) + return ival.index + +def dotvv_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + l = a.shape[0] + m = b.shape[0] + # TODO: investigate assert_equiv + #assert_equiv("sizes of l, m do not match", l, m) + s = 0 + for i in numba.parfors.parfor.internal_prange(l): + s += a[i] * b[i] + return s + +def dotvm_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + l = a.shape + m, n = b.shape + # TODO: investigate assert_equiv + #assert_equiv("Sizes of l, m do not match", l, m) + c = np.zeros(n, a.dtype) + # TODO: evaluate dotvm implementation options + #for i in prange(n): + # s = 0 + # for j in range(m): + # s += a[j] * b[j, i] + # c[i] = s + for i in numba.parfors.parfor.internal_prange(m): + c += a[i] * b[i, :] + return c + +def dotmv_parallel_impl(a, b): + numba.parfors.parfor.init_prange() + m, n = a.shape + l = b.shape + # TODO: investigate assert_equiv + #assert_equiv("sizes of n, l do not match", n, l) + c = np.empty(m, a.dtype) + for i in numba.parfors.parfor.internal_prange(m): + s = 0 + for j in range(n): + s += a[i, j] * b[j] + c[i] = s + return c + +def dot_parallel_impl(return_type, atyp, btyp): + # Note that matrix matrix multiply is not translated. + if (isinstance(atyp, types.npytypes.Array) and + isinstance(btyp, types.npytypes.Array)): + if atyp.ndim == btyp.ndim == 1: + return dotvv_parallel_impl + # TODO: evaluate support for dotvm and enable + #elif atyp.ndim == 1 and btyp.ndim == 2: + # return dotvm_parallel_impl + elif atyp.ndim == 2 and btyp.ndim == 1: + return dotmv_parallel_impl + +def sum_parallel_impl(return_type, arg): + zero = return_type(0) + + if arg.ndim == 0: + def sum_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def sum_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val += in_arr[i] + return val + else: + def sum_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.pndindex(in_arr.shape): + val += in_arr[i] + return val + return sum_1 + +def prod_parallel_impl(return_type, arg): + one = return_type(1) + + if arg.ndim == 0: + def prod_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def prod_1(in_arr): + numba.parfors.parfor.init_prange() + val = one + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val *= in_arr[i] + return val + else: + def prod_1(in_arr): + numba.parfors.parfor.init_prange() + val = one + for i in numba.pndindex(in_arr.shape): + val *= in_arr[i] + return val + return prod_1 + + +def mean_parallel_impl(return_type, arg): + # can't reuse sum since output type is different + zero = return_type(0) + + if arg.ndim == 0: + def mean_1(in_arr): + return in_arr[()] + elif arg.ndim == 1: + def mean_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val += in_arr[i] + return val/len(in_arr) + else: + def mean_1(in_arr): + numba.parfors.parfor.init_prange() + val = zero + for i in numba.pndindex(in_arr.shape): + val += in_arr[i] + return val/in_arr.size + return mean_1 + +def var_parallel_impl(return_type, arg): + if arg.ndim == 0: + def var_1(in_arr): + return 0 + elif arg.ndim == 1: + def var_1(in_arr): + # Compute the mean + m = in_arr.mean() + # Compute the sum of square diffs + numba.parfors.parfor.init_prange() + ssd = 0 + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + val = in_arr[i] - m + ssd += np.real(val * np.conj(val)) + return ssd / len(in_arr) + else: + def var_1(in_arr): + # Compute the mean + m = in_arr.mean() + # Compute the sum of square diffs + numba.parfors.parfor.init_prange() + ssd = 0 + for i in numba.pndindex(in_arr.shape): + val = in_arr[i] - m + ssd += np.real(val * np.conj(val)) + return ssd / in_arr.size + return var_1 + +def std_parallel_impl(return_type, arg): + def std_1(in_arr): + return in_arr.var() ** 0.5 + return std_1 + +def arange_parallel_impl(return_type, *args, dtype=None): + inferred_dtype = as_dtype(return_type.dtype) + + def arange_1(stop): + return np.arange(0, stop, 1, inferred_dtype) + + def arange_1_dtype(stop, dtype): + return np.arange(0, stop, 1, dtype) + + def arange_2(start, stop): + return np.arange(start, stop, 1, inferred_dtype) + + def arange_2_dtype(start, stop, dtype): + return np.arange(start, stop, 1, dtype) + + def arange_3(start, stop, step): + return np.arange(start, stop, step, inferred_dtype) + + def arange_3_dtype(start, stop, step, dtype): + return np.arange(start, stop, step, dtype) + + if any(isinstance(a, types.Complex) for a in args): + def arange_4(start, stop, step, dtype): + numba.parfors.parfor.init_prange() + nitems_c = (stop - start) / step + nitems_r = math.ceil(nitems_c.real) + nitems_i = math.ceil(nitems_c.imag) + nitems = int(max(min(nitems_i, nitems_r), 0)) + arr = np.empty(nitems, dtype) + for i in numba.parfors.parfor.internal_prange(nitems): + arr[i] = start + i * step + return arr + else: + def arange_4(start, stop, step, dtype): + numba.parfors.parfor.init_prange() + nitems_r = math.ceil((stop - start) / step) + nitems = int(max(nitems_r, 0)) + arr = np.empty(nitems, dtype) + val = start + for i in numba.parfors.parfor.internal_prange(nitems): + arr[i] = start + i * step + return arr + + if len(args) == 1: + return arange_1 if dtype is None else arange_1_dtype + elif len(args) == 2: + return arange_2 if dtype is None else arange_2_dtype + elif len(args) == 3: + return arange_3 if dtype is None else arange_3_dtype + elif len(args) == 4: + return arange_4 + else: + raise ValueError("parallel arange with types {}".format(args)) + +def linspace_parallel_impl(return_type, *args): + dtype = as_dtype(return_type.dtype) + + def linspace_2(start, stop): + return np.linspace(start, stop, 50) + + def linspace_3(start, stop, num): + numba.parfors.parfor.init_prange() + arr = np.empty(num, dtype) + div = num - 1 + delta = stop - start + arr[0] = start + for i in numba.parfors.parfor.internal_prange(num): + arr[i] = start + delta * (i / div) + return arr + + if len(args) == 2: + return linspace_2 + elif len(args) == 3: + return linspace_3 + else: + raise ValueError("parallel linspace with types {}".format(args)) + +swap_functions_map = { + ('argmin', 'numpy'): lambda r,a: argmin_parallel_impl, + ('argmax', 'numpy'): lambda r,a: argmax_parallel_impl, + ('min', 'numpy'): min_parallel_impl, + ('max', 'numpy'): max_parallel_impl, + ('amin', 'numpy'): min_parallel_impl, + ('amax', 'numpy'): max_parallel_impl, + ('sum', 'numpy'): sum_parallel_impl, + ('prod', 'numpy'): prod_parallel_impl, + ('mean', 'numpy'): mean_parallel_impl, + ('var', 'numpy'): var_parallel_impl, + ('std', 'numpy'): std_parallel_impl, + ('dot', 'numpy'): dot_parallel_impl, + ('arange', 'numpy'): arange_parallel_impl, + ('linspace', 'numpy'): linspace_parallel_impl, +} + +def fill_parallel_impl(return_type, arr, val): + """Parallel implementation of ndarray.fill. The array on + which to operate is retrieved from get_call_name and + is passed along with the value to fill. + """ + if arr.ndim == 1: + def fill_1(in_arr, val): + numba.parfors.parfor.init_prange() + for i in numba.parfors.parfor.internal_prange(len(in_arr)): + in_arr[i] = val + return None + else: + def fill_1(in_arr, val): + numba.parfors.parfor.init_prange() + for i in numba.pndindex(in_arr.shape): + in_arr[i] = val + return None + return fill_1 + +replace_functions_ndarray = { + 'fill': fill_parallel_impl, +} + +@register_jitable +def max_checker(arr_size): + if arr_size == 0: + raise ValueError(("zero-size array to reduction operation " + "maximum which has no identity")) + +@register_jitable +def min_checker(arr_size): + if arr_size == 0: + raise ValueError(("zero-size array to reduction operation " + "minimum which has no identity")) + +@register_jitable +def argmin_checker(arr_size): + if arr_size == 0: + raise ValueError("attempt to get argmin of an empty sequence") + +@register_jitable +def argmax_checker(arr_size): + if arr_size == 0: + raise ValueError("attempt to get argmax of an empty sequence") + +checker_impl = namedtuple('checker_impl', ['name', 'func']) + +replace_functions_checkers_map = { + ('argmin', 'numpy') : checker_impl('argmin_checker', argmin_checker), + ('argmax', 'numpy') : checker_impl('argmax_checker', argmax_checker), + ('min', 'numpy') : checker_impl('min_checker', min_checker), + ('max', 'numpy') : checker_impl('max_checker', max_checker), + ('amin', 'numpy') : checker_impl('min_checker', min_checker), + ('amax', 'numpy') : checker_impl('max_checker', max_checker), +} + + +class LoopNest(object): + + '''The LoopNest class holds information of a single loop including + the index variable (of a non-negative integer value), and the + range variable, e.g. range(r) is 0 to r-1 with step size 1. + ''' + + def __init__(self, index_variable, start, stop, step): + self.index_variable = index_variable + self.start = start + self.stop = stop + self.step = step + + + def __repr__(self): + return ("LoopNest(index_variable = {}, range = ({}, {}, {}))". + format(self.index_variable, self.start, self.stop, self.step)) + + def list_vars(self): + all_uses = [] + all_uses.append(self.index_variable) + if isinstance(self.start, ir.Var): + all_uses.append(self.start) + if isinstance(self.stop, ir.Var): + all_uses.append(self.stop) + if isinstance(self.step, ir.Var): + all_uses.append(self.step) + return all_uses + +class Parfor(ir.Expr, ir.Stmt): + + id_counter = 0 + + def __init__( + self, + loop_nests, + init_block, + loop_body, + loc, + index_var, + equiv_set, + pattern, + flags, + *, #only specify the options below by keyword + no_sequential_lowering=False, + races=None): + if races is None: + races = set() + super(Parfor, self).__init__( + op='parfor', + loc=loc + ) + + self.id = type(self).id_counter + type(self).id_counter += 1 + #self.input_info = input_info + #self.output_info = output_info + self.loop_nests = loop_nests + self.init_block = init_block + self.loop_body = loop_body + self.index_var = index_var + self.params = None # filled right before parallel lowering + self.equiv_set = equiv_set + # The parallel patterns this parfor was generated from and their options + # for example, a parfor could be from the stencil pattern with + # the neighborhood option + assert len(pattern) > 1 + self.patterns = [pattern] + self.flags = flags + # if True, this parfor shouldn't be lowered sequentially even with the + # sequential lowering option + self.no_sequential_lowering = no_sequential_lowering + self.races = races + self.redvars = [] + self.reddict = {} + # If the lowerer is None then the standard lowerer will be used. + # This can be set to a function to have that function act as the lowerer + # for this parfor. This lowerer field will also prevent parfors from + # being fused unless they have use the same lowerer. + self.lowerer = None + if config.DEBUG_ARRAY_OPT_STATS: + fmt = 'Parallel for-loop #{} is produced from pattern \'{}\' at {}' + print(fmt.format( + self.id, pattern, loc)) + + def __repr__(self): + return "id=" + str(self.id) + repr(self.loop_nests) + \ + repr(self.loop_body) + repr(self.index_var) + + def get_loop_nest_vars(self): + return [x.index_variable for x in self.loop_nests] + + def list_vars(self): + """list variables used (read/written) in this parfor by + traversing the body and combining block uses. + """ + all_uses = [] + for l, b in self.loop_body.items(): + for stmt in b.body: + all_uses += stmt.list_vars() + + for loop in self.loop_nests: + all_uses += loop.list_vars() + + for stmt in self.init_block.body: + all_uses += stmt.list_vars() + + return all_uses + + def get_shape_classes(self, var, typemap=None): + """get the shape classes for a given variable. + If a typemap is specified then use it for type resolution + """ + # We get shape classes from the equivalence set but that + # keeps its own typemap at a time prior to lowering. So + # if something is added during lowering then we can pass + # in a type map to use. We temporarily replace the + # equivalence set typemap, do the work and then restore + # the original on the way out. + if typemap is not None: + save_typemap = self.equiv_set.typemap + self.equiv_set.typemap = typemap + res = self.equiv_set.get_shape_classes(var) + if typemap is not None: + self.equiv_set.typemap = save_typemap + return res + + def dump(self, file=None): + file = file or sys.stdout + print(("begin parfor {}".format(self.id)).center(20, '-'), file=file) + print("index_var = ", self.index_var, file=file) + print("params = ", self.params, file=file) + print("races = ", self.races, file=file) + for loopnest in self.loop_nests: + print(loopnest, file=file) + print("init block:", file=file) + self.init_block.dump(file) + for offset, block in sorted(self.loop_body.items()): + print('label %s:' % (offset,), file=file) + block.dump(file) + print(("end parfor {}".format(self.id)).center(20, '-'), file=file) + + def validate_params(self, typemap): + """ + Check that Parfors params are of valid types. + """ + if self.params is None: + msg = ("Cannot run parameter validation on a Parfor with params " + "not set") + raise ValueError(msg) + for p in self.params: + ty = typemap.get(p) + if ty is None: + msg = ("Cannot validate parameter %s, there is no type " + "information available") + raise ValueError(msg) + if isinstance(ty, types.BaseTuple): + if ty.count > config.PARFOR_MAX_TUPLE_SIZE: + msg = ("Use of a tuple (%s) of length %d in a parallel region " + "exceeds the maximum supported tuple size. Since " + "Generalized Universal Functions back parallel regions " + "and those do not support tuples, tuples passed to " + "parallel regions are unpacked if their size is below " + "a certain threshold, currently configured to be %d. " + "This threshold can be modified using the Numba " + "environment variable NUMBA_PARFOR_MAX_TUPLE_SIZE.") + raise errors.UnsupportedParforsError(msg % + (p, ty.count, config.PARFOR_MAX_TUPLE_SIZE), + self.loc) + + +def _analyze_parfor(parfor, equiv_set, typemap, array_analysis): + """Recursive array analysis for parfor nodes. + """ + func_ir = array_analysis.func_ir + parfor_blocks = wrap_parfor_blocks(parfor) + # Since init_block get label 0 after wrap, we need to save + # the equivset for the real block label 0. + backup_equivset = array_analysis.equiv_sets.get(0, None) + array_analysis.run(parfor_blocks, equiv_set) + unwrap_parfor_blocks(parfor, parfor_blocks) + parfor.equiv_set = array_analysis.equiv_sets[0] + # Restore equivset for block 0 after parfor is unwrapped + if backup_equivset: + array_analysis.equiv_sets[0] = backup_equivset + return [], [] + +array_analysis.array_analysis_extensions[Parfor] = _analyze_parfor + +class ParforDiagnostics(object): + """Holds parfor diagnostic info, this is accumulated throughout the + PreParforPass and ParforPass, also in the closure inlining! + """ + def __init__(self): + # holds ref to the function for which this is providing diagnostics + self.func = None + # holds a map of the replaced functions + self.replaced_fns = dict() + # used to identify "internal" parfor functions + self.internal_name = '__numba_parfor_gufunc' + self.fusion_info = defaultdict(list) + self.nested_fusion_info = defaultdict(list) + self.fusion_reports = [] + self.hoist_info = {} + self.has_setup = False + + def setup(self, func_ir, fusion_enabled): + self.func_ir = func_ir + self.name = self.func_ir.func_id.func_qualname + self.line = self.func_ir.loc + self.fusion_enabled = fusion_enabled + if self.internal_name in self.name: + self.purpose = 'Internal parallel function' + else: + self.purpose = 'Function %s, %s' % (self.name, self.line) + # we store a reference to the parfors prior to fusion etc, the parfors + # do get mangled in the fusion process but in a predetermined manner + # and by holding a reference here the "before" state can be printed + self.initial_parfors = self.get_parfors() + self.has_setup = True + + @property + def has_setup(self): + return self._has_setup + + @has_setup.setter + def has_setup(self, state): + self._has_setup = state + + def count_parfors(self, blocks=None): + return len(self.get_parfors()) + + def _get_nested_parfors(self, parfor, parfors_list): + blocks = wrap_parfor_blocks(parfor) + self._get_parfors(blocks, parfors_list) + unwrap_parfor_blocks(parfor) + + def _get_parfors(self, blocks, parfors_list): + for label, blk in blocks.items(): + for stmt in blk.body: + if isinstance(stmt, Parfor): + parfors_list.append(stmt) + self._get_nested_parfors(stmt, parfors_list) + + def get_parfors(self): + parfors_list = [] + self._get_parfors(self.func_ir.blocks, parfors_list) + return parfors_list + + def hoisted_allocations(self): + allocs = [] + for pf_id, data in self.hoist_info.items(): + stmt = data.get('hoisted', []) + for inst in stmt: + if isinstance(inst.value, ir.Expr): + if inst.value.op == 'call': + call = guard(find_callname, self.func_ir, inst.value) + if call is not None and call == ('empty', 'numpy'): + allocs.append(inst) + return allocs + + def compute_graph_info(self, _a): + """ + compute adjacency list of the fused loops + and find the roots in of the lists + """ + a = copy.deepcopy(_a) + if a == {}: + return [], set() + + vtx = set() + for v in a.values(): + for x in v: + vtx.add(x) + + # find roots + potential_roots = set(a.keys()) + roots = potential_roots - vtx + if roots is None: + roots = set() + + # populate rest of adjacency list + not_roots = set() + for x in range(max(set(a.keys()).union(vtx)) + 1): + val = a.get(x) + if val is not None: + a[x] = val + elif val == []: + not_roots.add(x) # debug only + else: + a[x] = [] + + + # fold adjacency list into an actual list ordered + # by vtx + l = [] + for x in sorted(a.keys()): + l.append(a[x]) + + return l, roots #, not_roots + + def get_stats(self, fadj, nadj, root): + """ + Computes the number of fused and serialized loops + based on a fusion adjacency list `fadj` and a nested + parfors adjacency list `nadj` for the root, `root` + """ + def count_root(fadj, nadj, root, nfused, nserial): + for k in nadj[root]: + nserial += 1 + if nadj[k] == []: + nfused += len(fadj[k]) + else: + nf, ns = count_root(fadj, nadj, k, nfused, nserial) + nfused += nf + nserial = ns + return nfused, nserial + nfused, nserial = count_root(fadj, nadj, root, 0, 0) + return nfused, nserial + + def reachable_nodes(self, adj, root): + """ + returns a list of nodes reachable in an adjacency list from a + specified root + """ + fusers = [] + fusers.extend(adj[root]) + for k in adj[root]: + if adj[k] != []: + fusers.extend(self.reachable_nodes(adj, k)) + return fusers + + def sort_pf_by_line(self, pf_id, parfors_simple): + """ + pd_id - the parfors id + parfors_simple - the simple parfors map + """ + # this sorts parfors by source line number + pf = parfors_simple[pf_id][0] + pattern = pf.patterns[0] + line = max(0, pf.loc.line - 1) # why are these out by 1 ?! + filename = self.func_ir.loc.filename + nadj, nroots = self.compute_graph_info(self.nested_fusion_info) + fadj, froots = self.compute_graph_info(self.fusion_info) + graphs = [nadj, fadj] + + # If the parfor is internal, like internal prange, then the + # default line number is from its location in the numba source + # To get a more accurate line number, this first checks the + # adjacency graph for fused parfors that might not be internal + # and uses the minimum line number from there. If that fails + # (case where there's just a single internal parfor) the IR + # is walked backwards from the parfor location and the first non + # parfor statement line number is used. + if isinstance(pattern, tuple): + if pattern[1] == 'internal': + reported_loc = pattern[2][1] + if reported_loc.filename == filename: + return max(0, reported_loc.line - 1) + else: + # first recurse and check the adjacency list for + # something that is not an in internal parfor + tmp = [] + for adj in graphs: + if adj: # graph may be empty, e.g. no nesting + for k in adj[pf_id]: + tmp.append(self.sort_pf_by_line(k, parfors_simple)) + if tmp: + return max(0, min(tmp) - 1) + # second run through the parfor block to see if there's + # and reference to a line number in the user source + for blk in pf.loop_body.values(): + for stmt in blk.body: + if stmt.loc.filename == filename: + return max(0, stmt.loc.line - 1) + # finally run through the func_ir and look for the + # first non-parfor statement prior to this one and + # grab the line from that + for blk in self.func_ir.blocks.values(): + try: + idx = blk.body.index(pf) + for i in range(idx - 1, 0, -1): + stmt = blk.body[i] + if not isinstance(stmt, Parfor): + line = max(0, stmt.loc.line - 1) + break + except ValueError: + pass + return line + + def get_parfors_simple(self, print_loop_search): + parfors_simple = dict() + + # print in line order, parfors loop id is based on discovery order + for pf in sorted(self.initial_parfors, key=lambda x: x.loc.line): + # use 0 here, the parfors are mutated by the time this routine + # is called, however, fusion appends the patterns so we can just + # pull in the first as a "before fusion" emulation + r_pattern = pf.patterns[0] + pattern = pf.patterns[0] + loc = pf.loc + if isinstance(pattern, tuple): + if pattern[0] == 'prange': + if pattern[1] == 'internal': + replfn = '.'.join(reversed(list(pattern[2][0]))) + loc = pattern[2][1] + r_pattern = '%s %s' % (replfn, '(internal parallel version)') + elif pattern[1] == 'user': + r_pattern = "user defined prange" + elif pattern[1] == 'pndindex': + r_pattern = "internal pndindex" #FIXME: trace this! + else: + assert 0 + fmt = 'Parallel for-loop #%s: is produced from %s:\n %s\n \n' + if print_loop_search: + print_wrapped(fmt % (pf.id, loc, r_pattern)) + parfors_simple[pf.id] = (pf, loc, r_pattern) + return parfors_simple + + def get_all_lines(self, parfors_simple): + # ensure adjacency lists are the same size for both sets of info + # (nests and fusion may not traverse the same space, for + # convenience [] is used as a condition to halt recursion) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + # This computes the roots of true loop nests (i.e. loops containing + # loops opposed to just a loop that's a root). + nroots = set() + if _nroots: + for r in _nroots: + if nadj[r] != []: + nroots.add(r) + all_roots = froots ^ nroots + + # This computes all the parfors at the top level that are either: + # - roots of loop fusion + # - roots of true loop nests + # it then combines these based on source line number for ease of + # producing output ordered in a manner similar to the code structure + froots_lines = {} + for x in froots: + line = self.sort_pf_by_line(x, parfors_simple) + froots_lines[line] = 'fuse', x, fadj + + nroots_lines = {} + for x in nroots: + line = self.sort_pf_by_line(x, parfors_simple) + nroots_lines[line] = 'nest', x, nadj + + all_lines = froots_lines.copy() + all_lines.update(nroots_lines) + return all_lines + + def source_listing(self, parfors_simple, purpose_str): + filename = self.func_ir.loc.filename + count = self.count_parfors() + func_name = self.func_ir.func_id.func + try: + lines = inspect.getsource(func_name).splitlines() + except OSError: # generated function + lines = None + if lines and parfors_simple: + src_width = max([len(x) for x in lines]) + map_line_to_pf = defaultdict(list) # parfors can alias lines + for k, v in parfors_simple.items(): + # TODO: do a better job of tracking parfors that are not in + # this file but are referred to, e.g. np.arange() + if parfors_simple[k][1].filename == filename: + match_line = self.sort_pf_by_line(k, parfors_simple) + map_line_to_pf[match_line].append(str(k)) + + max_pf_per_line = max([1] + [len(x) for x in map_line_to_pf.values()]) + width = src_width + (1 + max_pf_per_line * (len(str(count)) + 2)) + newlines = [] + newlines.append('\n') + newlines.append('Parallel loop listing for %s' % purpose_str) + newlines.append(width * '-' + '|loop #ID') + fmt = '{0:{1}}| {2}' + # why are these off by 1? + lstart = max(0, self.func_ir.loc.line - 1) + for no, line in enumerate(lines, lstart): + pf_ids = map_line_to_pf.get(no, None) + if pf_ids is not None: + pfstr = '#' + ', '.join(pf_ids) + else: + pfstr = '' + stripped = line.strip('\n') + srclen = len(stripped) + if pf_ids: + l = fmt.format(width * '-', width, pfstr) + else: + l = fmt.format(width * ' ', width, pfstr) + newlines.append(stripped + l[srclen:]) + print('\n'.join(newlines)) + else: + print("No source available") + + def print_unoptimised(self, lines): + # This prints the unoptimised parfors state + sword = '+--' + fac = len(sword) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + def print_nest(fadj_, nadj_, theroot, reported, region_id): + def print_g(fadj_, nadj_, nroot, depth): + print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, nroot, '(parallel)')) + for k in nadj_[nroot]: + if nadj_[k] == []: + msg = [] + msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, k, '(parallel)')) + if fadj_[k] != [] and k not in reported: + fused = self.reachable_nodes(fadj_, k) + for i in fused: + msg.append(fac * (depth + 1) * ' ' + '%s%s %s' % (sword, i, '(parallel)')) + reported.append(k) + print_wrapped('\n'.join(msg)) + else: + print_g(fadj_, nadj_, k, depth + 1) + + if nadj_[theroot] != []: + print_wrapped("Parallel region %s:" % region_id) + print_g(fadj_, nadj_, theroot, 0) + print("\n") + region_id = region_id + 1 + return region_id + + def print_fuse(ty, pf_id, adj, depth, region_id): + msg = [] + print_wrapped("Parallel region %s:" % region_id) + msg.append(fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel)')) + if adj[pf_id] != []: + fused = sorted(self.reachable_nodes(adj, pf_id)) + for k in fused: + msg.append(fac * depth * ' ' + '%s%s %s' % (sword, k, '(parallel)')) + region_id = region_id + 1 + print_wrapped('\n'.join(msg)) + print("\n") + return region_id + + # Walk the parfors by src line and print optimised structure + region_id = 0 + reported = [] + for line, info in sorted(lines.items()): + opt_ty, pf_id, adj = info + if opt_ty == 'fuse': + if pf_id not in reported: + region_id = print_fuse('f', pf_id, adj, 0, region_id) + elif opt_ty == 'nest': + region_id = print_nest(fadj, nadj, pf_id, reported, region_id) + else: + assert 0 + + def print_optimised(self, lines): + # This prints the optimised output based on the transforms that + # occurred during loop fusion and rewriting of loop nests + sword = '+--' + fac = len(sword) + fadj, froots = self.compute_graph_info(self.fusion_info) + nadj, _nroots = self.compute_graph_info(self.nested_fusion_info) + + if len(fadj) > len(nadj): + lim = len(fadj) + tmp = nadj + else: + lim = len(nadj) + tmp = fadj + for x in range(len(tmp), lim): + tmp.append([]) + + summary = dict() + # region : {fused, serialized} + + def print_nest(fadj_, nadj_, theroot, reported, region_id): + def print_g(fadj_, nadj_, nroot, depth): + for k in nadj_[nroot]: + msg = fac * depth * ' ' + '%s%s %s' % (sword, k, '(serial') + if nadj_[k] == []: + fused = [] + if fadj_[k] != [] and k not in reported: + fused = sorted(self.reachable_nodes(fadj_, k)) + msg += ", fused with loop(s): " + msg += ', '.join([str(x) for x in fused]) + msg += ')' + reported.append(k) + print_wrapped(msg) + summary[region_id]['fused'] += len(fused) + else: + print_wrapped(msg + ')') + print_g(fadj_, nadj_, k, depth + 1) + summary[region_id]['serialized'] += 1 + + if nadj_[theroot] != []: + print_wrapped("Parallel region %s:" % region_id) + print_wrapped('%s%s %s' % (sword, theroot, '(parallel)')) + summary[region_id] = {'root': theroot, 'fused': 0, 'serialized': 0} + print_g(fadj_, nadj_, theroot, 1) + print("\n") + region_id = region_id + 1 + return region_id + + def print_fuse(ty, pf_id, adj, depth, region_id): + print_wrapped("Parallel region %s:" % region_id) + msg = fac * depth * ' ' + '%s%s %s' % (sword, pf_id, '(parallel') + fused = [] + if adj[pf_id] != []: + fused = sorted(self.reachable_nodes(adj, pf_id)) + msg += ", fused with loop(s): " + msg += ', '.join([str(x) for x in fused]) + + summary[region_id] = {'root': pf_id, 'fused': len(fused), 'serialized': 0} + msg += ')' + print_wrapped(msg) + print("\n") + region_id = region_id + 1 + return region_id + + # Walk the parfors by src line and print optimised structure + region_id = 0 + reported = [] + for line, info in sorted(lines.items()): + opt_ty, pf_id, adj = info + if opt_ty == 'fuse': + if pf_id not in reported: + region_id = print_fuse('f', pf_id, adj, 0, region_id) + elif opt_ty == 'nest': + region_id = print_nest(fadj, nadj, pf_id, reported, region_id) + else: + assert 0 + + # print the summary of the fuse/serialize rewrite + if summary: + for k, v in sorted(summary.items()): + msg = ('\n \nParallel region %s (loop #%s) had %s ' + 'loop(s) fused') + root = v['root'] + fused = v['fused'] + serialized = v['serialized'] + if serialized != 0: + msg += (' and %s loop(s) ' + 'serialized as part of the larger ' + 'parallel loop (#%s).') + print_wrapped(msg % (k, root, fused, serialized, root)) + else: + msg += '.' + print_wrapped(msg % (k, root, fused)) + else: + print_wrapped("Parallel structure is already optimal.") + + def allocation_hoist(self): + found = False + print('Allocation hoisting:') + for pf_id, data in self.hoist_info.items(): + stmt = data.get('hoisted', []) + for inst in stmt: + if isinstance(inst.value, ir.Expr): + try: + attr = inst.value.attr + if attr == 'empty': + msg = ("The memory allocation derived from the " + "instruction at %s is hoisted out of the " + "parallel loop labelled #%s (it will be " + "performed before the loop is executed and " + "reused inside the loop):") + loc = inst.loc + print_wrapped(msg % (loc, pf_id)) + try: + path = os.path.relpath(loc.filename) + except ValueError: + path = os.path.abspath(loc.filename) + lines = linecache.getlines(path) + if lines and loc.line: + print_wrapped(" Allocation:: " + lines[0 if loc.line < 2 else loc.line - 1].strip()) + print_wrapped(" - numpy.empty() is used for the allocation.\n") + found = True + except (KeyError, AttributeError): + pass + if not found: + print_wrapped('No allocation hoisting found') + + def instruction_hoist(self): + print("") + print('Instruction hoisting:') + hoist_info_printed = False + if self.hoist_info: + for pf_id, data in self.hoist_info.items(): + hoisted = data.get('hoisted', None) + not_hoisted = data.get('not_hoisted', None) + if not hoisted and not not_hoisted: + print("loop #%s has nothing to hoist." % pf_id) + continue + + print("loop #%s:" % pf_id) + if hoisted: + print(" Has the following hoisted:") + [print(" %s" % y) for y in hoisted] + hoist_info_printed = True + if not_hoisted: + print(" Failed to hoist the following:") + [print(" %s: %s" % (y, x)) for x, y in not_hoisted] + hoist_info_printed = True + if not hoist_info_printed: + print_wrapped('No instruction hoisting found') + print_wrapped(80 * '-') + + def dump(self, level=1): + if not self.has_setup: + raise RuntimeError("self.setup has not been called") + name = self.func_ir.func_id.func_qualname + line = self.func_ir.loc + if self.internal_name in name: + purpose_str = 'Internal parallel functions ' + purpose = 'internal' + else: + purpose_str = ' Function %s, %s ' % (name, line) + purpose = 'user' + + print_loop_search = False + print_source_listing = False + print_fusion_search = False + print_fusion_summary = False + print_loopnest_rewrite = False + print_pre_optimised = False + print_post_optimised = False + print_allocation_hoist = False + print_instruction_hoist = False + print_internal = False + + # each level switches on progressively more output + if level in (1, 2, 3, 4): + print_source_listing = True + print_post_optimised = True + else: + raise ValueError("Report level unknown, should be one of 1, 2, 3, 4") + + if level in (2, 3, 4): + print_pre_optimised = True + + if level in (3, 4): + print_allocation_hoist = True + + if level == 3: + print_fusion_summary = True + print_loopnest_rewrite = True + + if level == 4: + print_fusion_search = True + print_instruction_hoist = True + print_internal = True + + if purpose == 'internal' and not print_internal: + return + + print_wrapped('\n ') + print_wrapped(_termwidth * "=") + print_wrapped((" Parallel Accelerator Optimizing: %s " % purpose_str).center(_termwidth, '=')) + print_wrapped(_termwidth * "=") + print_wrapped("") + +#----------- search section + if print_loop_search: + print_wrapped('Looking for parallel loops'.center(_termwidth, '-')) + parfors_simple = self.get_parfors_simple(print_loop_search) + + count = self.count_parfors() + if print_loop_search: + print_wrapped("\nFound %s parallel loops." % count) + print_wrapped('-' * _termwidth) + +#----------- augmented source section + filename = self.func_ir.loc.filename + try: + # Try to get a relative path + # ipython/jupyter input just returns as filename + path = os.path.relpath(filename) + except ValueError: + # Fallback to absolute path if error occurred in getting the + # relative path. + # This may happen on windows if the drive is different + path = os.path.abspath(filename) + + if print_source_listing: + self.source_listing(parfors_simple, purpose_str) + +#---------- these are used a lot here on in + sword = '+--' + parfors = self.get_parfors() # this is the mutated parfors + parfor_ids = [x.id for x in parfors] + n_parfors = len(parfor_ids) + +#----------- loop fusion section + if print_fusion_search or print_fusion_summary: + if not sequential_parfor_lowering: + print_wrapped(' Fusing loops '.center(_termwidth, '-')) + msg = ("Attempting fusion of parallel loops (combines loops " + "with similar properties)...\n") + print_wrapped(msg) + else: + msg = "Performing sequential lowering of loops...\n" + print_wrapped(msg) + print_wrapped(_termwidth * '-') + # if there are some parfors, print information about them! + if n_parfors > -1: + def dump_graph_indented(a, root_msg, node_msg): + fac = len(sword) + def print_graph(adj, roots): + def print_g(adj, root, depth): + for k in adj[root]: + print_wrapped(fac * depth * ' ' + '%s%s %s' % (sword, k, node_msg)) + if adj[k] != []: + print_g(adj, k, depth + 1) + for r in roots: + print_wrapped('%s%s %s' % (sword, r, root_msg)) + print_g(l, r, 1) + print_wrapped("") + l, roots = self.compute_graph_info(a) + print_graph(l, roots) + + if print_fusion_search: + for report in self.fusion_reports: + l1, l2, msg = report + print_wrapped(" Trying to fuse loops #%s and #%s:" % (l1, l2)) + print_wrapped(" %s" % msg) + + if self.fusion_info != {}: + if print_fusion_summary: + print_wrapped("\n \nFused loop summary:\n") + + dump_graph_indented(self.fusion_info, 'has the following loops fused into it:', '(fused)') + + if print_fusion_summary: + if self.fusion_enabled: + after_fusion = "Following the attempted fusion of parallel for-loops" + else: + after_fusion = "With fusion disabled" + + print_wrapped(('\n{} there are {} parallel for-loop(s) (originating from loops labelled: {}).').format( + after_fusion, n_parfors, ', '.join(['#%s' % x for x in parfor_ids]))) + print_wrapped(_termwidth * '-') + print_wrapped("") + +#----------- loop nest section + if print_loopnest_rewrite: + if self.nested_fusion_info != {}: + print_wrapped((" Optimising loop nests ").center(_termwidth, '-')) + print_wrapped("Attempting loop nest rewrites (optimising for the largest parallel loops)...\n ") + root_msg = 'is a parallel loop' + node_msg = '--> rewritten as a serial loop' + dump_graph_indented(self.nested_fusion_info, root_msg, node_msg) + print_wrapped(_termwidth * '-') + print_wrapped("") + +#---------- compute various properties and orderings in the data for subsequent use + all_lines = self.get_all_lines(parfors_simple) + + if print_pre_optimised: + print(' Before Optimisation '.center(_termwidth,'-')) + self.print_unoptimised(all_lines) + print(_termwidth * '-') + + if print_post_optimised: + print(' After Optimisation '.center(_termwidth,'-')) + self.print_optimised(all_lines) + print(_termwidth * '-') + print_wrapped("") + print_wrapped(_termwidth * '-') + print_wrapped("\n ") + +#----------- LICM section + if print_allocation_hoist or print_instruction_hoist: + print_wrapped('Loop invariant code motion'.center(80, '-')) + + if print_allocation_hoist: + self.allocation_hoist() + + if print_instruction_hoist: + self.instruction_hoist() + + else: # there are no parfors + print_wrapped('Function %s, %s, has no parallel for-loops.'.format(name, line)) + + def __str__(self): + r = "ParforDiagnostics:\n" + r += repr(self.replaced_fns) + return r + + def __repr__(self): + r = "ParforDiagnostics" + return r + + +class PreParforPass(object): + """Preprocessing for the Parfor pass. It mostly inlines parallel + implementations of numpy functions if available. + """ + def __init__(self, func_ir, typemap, calltypes, typingctx, targetctx, + options, swapped=None, replace_functions_map=None): + if swapped is None: + swapped = {} + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.typingctx = typingctx + self.targetctx = targetctx + self.options = options + # diagnostics + self.swapped = swapped + if replace_functions_map is None: + replace_functions_map = swap_functions_map + self.replace_functions_map = replace_functions_map + self.stats = { + 'replaced_func': 0, + 'replaced_dtype': 0, + } + + def run(self): + """Run pre-parfor processing pass. + """ + # e.g. convert A.sum() to np.sum(A) for easier match and optimization + canonicalize_array_math(self.func_ir, self.typemap, + self.calltypes, self.typingctx) + if self.options.numpy: + self._replace_parallel_functions(self.func_ir.blocks) + self.func_ir.blocks = simplify_CFG(self.func_ir.blocks) + + def _replace_parallel_functions(self, blocks): + """ + Replace functions with their parallel implementation in + replace_functions_map if available. + The implementation code is inlined to enable more optimization. + """ + swapped = self.swapped + from numba.core.inline_closurecall import inline_closure_call + work_list = list(blocks.items()) + while work_list: + label, block = work_list.pop() + for i, instr in enumerate(block.body): + if isinstance(instr, ir.Assign): + lhs = instr.target + lhs_typ = self.typemap[lhs.name] + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'call': + # Try and inline known calls with their parallel implementations + def replace_func(): + func_def = get_definition(self.func_ir, expr.func) + callname = find_callname(self.func_ir, expr) + repl_func = self.replace_functions_map.get(callname, None) + # Handle method on array type + if (repl_func is None and + len(callname) == 2 and + isinstance(callname[1], ir.Var) and + isinstance(self.typemap[callname[1].name], + types.npytypes.Array)): + repl_func = replace_functions_ndarray.get(callname[0], None) + if repl_func is not None: + # Add the array that the method is on to the arg list. + expr.args.insert(0, callname[1]) + + require(repl_func is not None) + typs = tuple(self.typemap[x.name] for x in expr.args) + kws_typs = {k: self.typemap[x.name] for k, x in expr.kws} + try: + new_func = repl_func(lhs_typ, *typs, **kws_typs) + except Exception: + new_func = None + require(new_func is not None) + # bind arguments to the new_func + typs = utils.pysignature(new_func).bind(*typs, **kws_typs).args + + g = copy.copy(self.func_ir.func_id.func.__globals__) + g['numba'] = numba + g['np'] = numpy + g['math'] = math + # if the function being inlined has a function + # checking the inputs, find it and add it to globals + check = replace_functions_checkers_map.get(callname, + None) + if check is not None: + g[check.name] = check.func + # inline the parallel implementation + new_blocks, _ = inline_closure_call(self.func_ir, g, + block, i, new_func, self.typingctx, self.targetctx, + typs, self.typemap, self.calltypes, work_list) + call_table = get_call_table(new_blocks, topological_ordering=False) + + # find the prange in the new blocks and record it for use in diagnostics + for call in call_table: + for k, v in call.items(): + if v[0] == 'internal_prange': + swapped[k] = [callname, repl_func.__name__, func_def, block.body[i].loc] + break + return True + if guard(replace_func): + self.stats['replaced_func'] += 1 + break + elif (isinstance(expr, ir.Expr) and expr.op == 'getattr' and + expr.attr == 'dtype'): + # Replace getattr call "A.dtype" with numpy.dtype(). + # This helps remove superfluous dependencies from parfor. + typ = self.typemap[expr.value.name] + if isinstance(typ, types.npytypes.Array): + # Convert A.dtype to four statements. + # 1) Get numpy global. + # 2) Create var for known type of array as string + # constant. e.g. 'float64' + # 3) Get dtype function from numpy module. + # 4) Create var for numpy.dtype(var from #2). + + # Create var for numpy module. + dtype = typ.dtype + scope = block.scope + loc = instr.loc + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + self.typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + + # Create var for the inferred type of the array + # e.g., 'float64' + dtype_str = str(dtype) + if dtype_str == 'bool': + dtype_str = 'bool_' + typ_var = ir.Var( + scope, mk_unique_var("$np_typ_var"), loc) + self.typemap[typ_var.name] = types.StringLiteral( + dtype_str) + typ_var_assign = ir.Assign( + ir.Const(dtype_str, loc), typ_var, loc) + + # Get the dtype function from the numpy module. + dtype_attr_var = ir.Var(scope, mk_unique_var("$dtype_attr_var"), loc) + temp = find_template(numpy.dtype) + tfunc = numba.core.types.Function(temp) + tfunc.get_call_type(self.typingctx, (self.typemap[typ_var.name],), {}) + self.typemap[dtype_attr_var.name] = types.functions.Function(temp) + dtype_attr_getattr = ir.Expr.getattr(g_np_var, 'dtype', loc) + dtype_attr_assign = ir.Assign(dtype_attr_getattr, dtype_attr_var, loc) + + # Call numpy.dtype on the statically coded type two steps above. + dtype_var = ir.Var(scope, mk_unique_var("$dtype_var"), loc) + self.typemap[dtype_var.name] = types.npytypes.DType(dtype) + dtype_getattr = ir.Expr.call(dtype_attr_var, [typ_var], (), loc) + dtype_assign = ir.Assign(dtype_getattr, dtype_var, loc) + self.calltypes[dtype_getattr] = signature( + self.typemap[dtype_var.name], self.typemap[typ_var.name]) + + # The original A.dtype rhs is replaced with result of this call. + instr.value = dtype_var + # Add statements to body of the code. + block.body.insert(0, dtype_assign) + block.body.insert(0, dtype_attr_assign) + block.body.insert(0, typ_var_assign) + block.body.insert(0, g_np_assign) + self.stats['replaced_dtype'] += 1 + break + +def find_template(op): + for ft in numba.core.typing.templates.builtin_registry.functions: + if ft.key == op: + return ft + + +class ParforPassStates: + """This class encapsulates all internal states of the ParforPass. + """ + + def __init__(self, func_ir, typemap, calltypes, return_type, typingctx, + targetctx, options, flags, metadata, + diagnostics=ParforDiagnostics()): + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.typingctx = typingctx + self.targetctx = targetctx + self.return_type = return_type + self.options = options + self.diagnostics = diagnostics + self.swapped_fns = diagnostics.replaced_fns + self.fusion_info = diagnostics.fusion_info + self.nested_fusion_info = diagnostics.nested_fusion_info + + self.array_analysis = array_analysis.ArrayAnalysis( + self.typingctx, self.func_ir, self.typemap, self.calltypes, + ) + + ir_utils._the_max_label.update(max(func_ir.blocks.keys())) + self.flags = flags + self.metadata = metadata + if "parfors" not in metadata: + metadata["parfors"] = {} + + +class ConvertInplaceBinop: + """Parfor subpass to convert setitem on Arrays + """ + def __init__(self, pass_states): + """ + Parameters + ---------- + pass_states : ParforPassStates + """ + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + # convert expressions like A += ... where A is an array. + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, ir.Assign): + lhs = instr.target + expr = instr.value + if isinstance(expr, ir.Expr) and expr.op == 'inplace_binop': + loc = expr.loc + target = expr.lhs + value = expr.rhs + target_typ = pass_states.typemap[target.name] + value_typ = pass_states.typemap[value.name] + # Handle A op= ... + if isinstance(target_typ, types.npytypes.Array): + # RHS is an array + if isinstance(value_typ, types.npytypes.Array): + new_instr = self._inplace_binop_to_parfor(equiv_set, + loc, expr.immutable_fn, target, value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='inplace_binop'), + ) + instr = [new_instr, ir.Assign(target, lhs, loc)] + if isinstance(instr, list): + new_body.extend(instr) + else: + new_body.append(instr) + block.body = new_body + + def _inplace_binop_to_parfor(self, equiv_set, loc, op, target, value): + """generate parfor from setitem node with a boolean or slice array indices. + The value can be either a scalar or an array variable, and if a boolean index + is used for the latter case, the same index must be used for the value too. + """ + pass_states = self.pass_states + scope = target.scope + arr_typ = pass_states.typemap[target.name] + el_typ = arr_typ.dtype + init_block = ir.Block(scope, loc) + value_typ = pass_states.typemap[value.name] + + size_vars = equiv_set.get_shape(target) + + # generate loopnests and size variables from target correlations + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate body + body_label = next_label() + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + # Read value. + value_var = ir.Var(scope, mk_unique_var("$value_var"), loc) + pass_states.typemap[value_var.name] = value_typ.dtype + getitem_call = ir.Expr.getitem(value, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + value_typ.dtype, value_typ, index_var_typ) + body_block.body.append(ir.Assign(getitem_call, value_var, loc)) + + # Read target + target_var = ir.Var(scope, mk_unique_var("$target_var"), loc) + pass_states.typemap[target_var.name] = el_typ + getitem_call = ir.Expr.getitem(target, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + el_typ, arr_typ, index_var_typ) + body_block.body.append(ir.Assign(getitem_call, target_var, loc)) + + # Create temp to hold result. + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + # Create binop and assign result to temporary. + binop_expr = ir.Expr.binop(op, target_var, value_var, loc) + body_block.body.append(ir.Assign(binop_expr, expr_out_var, loc)) + unified_type = self.pass_states.typingctx.unify_pairs(el_typ, value_typ.dtype) + pass_states.calltypes[binop_expr] = signature( + unified_type, unified_type, unified_type) + + # Write to target + setitem_node = ir.SetItem(target, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, arr_typ, index_var_typ, el_typ) + body_block.body.append(setitem_node) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('inplace_binop', ''), pass_states.flags) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from inplace_binop") + parfor.dump() + return parfor + + def _type_getitem(self, args): + fnty = operator.getitem + return self.pass_states.typingctx.resolve_function_type(fnty, tuple(args), {}) + + +def get_index_var(x): + return x.index if isinstance(x, ir.SetItem) else x.index_var + + +class ConvertSetItemPass: + """Parfor subpass to convert setitem on Arrays + """ + def __init__(self, pass_states): + """ + Parameters + ---------- + pass_states : ParforPassStates + """ + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + # convert setitem expressions like A[C] = c or A[C] = B[C] to parfor, + # where C is a boolean array. + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, (ir.StaticSetItem, ir.SetItem)): + loc = instr.loc + target = instr.target + index = get_index_var(instr) + value = instr.value + target_typ = pass_states.typemap[target.name] + index_typ = pass_states.typemap[index.name] + value_typ = pass_states.typemap[value.name] + # Handle A[boolean_array] = + if isinstance(target_typ, types.npytypes.Array): + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean) and + target_typ.ndim == index_typ.ndim): + # RHS is a scalar number + if isinstance(value_typ, types.Number): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='masked_assign_broadcast_scalar'), + ) + instr = new_instr + # RHS is an array + elif isinstance(value_typ, types.npytypes.Array): + val_def = guard(get_definition, pass_states.func_ir, + value.name) + if (isinstance(val_def, ir.Expr) and + val_def.op == 'getitem' and + val_def.index.name == index.name): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, val_def.value) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='masked_assign_array'), + ) + instr = new_instr + else: + # Handle A[:] = x + shape = equiv_set.get_shape(instr) + # Don't converted broadcasted setitems into parfors. + if isinstance(index_typ, types.BaseTuple): + # The sliced dims are those in the index that + # are made of slices. Count the numbers of slices + # in the index tuple. + sliced_dims = len(list(filter( + lambda x: isinstance(x, types.misc.SliceType), + index_typ.types))) + elif isinstance(index_typ, types.misc.SliceType): + # For singular indices there can be a bare slice + # and if so there is one dimension being set. + sliced_dims = 1 + else: + sliced_dims = 0 + + # Only create a parfor for this setitem if we know the + # shape of the output and number of dimensions set is + # equal to the number of dimensions on the right side. + if (shape is not None and + (not isinstance(value_typ, types.npytypes.Array) or + sliced_dims == value_typ.ndim)): + new_instr = self._setitem_to_parfor(equiv_set, + loc, target, index, value, shape=shape) + self.rewritten.append( + dict(old=instr, new=new_instr, + reason='slice'), + ) + instr = new_instr + new_body.append(instr) + block.body = new_body + + def _setitem_to_parfor(self, equiv_set, loc, target, index, value, shape=None): + """generate parfor from setitem node with a boolean or slice array indices. + The value can be either a scalar or an array variable, and if a boolean index + is used for the latter case, the same index must be used for the value too. + """ + pass_states = self.pass_states + scope = target.scope + arr_typ = pass_states.typemap[target.name] + el_typ = arr_typ.dtype + index_typ = pass_states.typemap[index.name] + init_block = ir.Block(scope, loc) + + if shape: + # Slice index is being used on the target array, we'll have to create + # a sub-array so that the target dimension matches the given shape. + assert(isinstance(index_typ, types.BaseTuple) or + isinstance(index_typ, types.SliceType)) + # setitem has a custom target shape + size_vars = shape + # create a new target array via getitem + subarr_var = ir.Var(scope, mk_unique_var("$subarr"), loc) + getitem_call = ir.Expr.getitem(target, index, loc) + subarr_typ = typing.arraydecl.get_array_index_type( arr_typ, index_typ).result + pass_states.typemap[subarr_var.name] = subarr_typ + pass_states.calltypes[getitem_call] = self._type_getitem((arr_typ, index_typ)) + init_block.append(ir.Assign(getitem_call, subarr_var, loc)) + target = subarr_var + else: + # Otherwise it is a boolean array that is used as index. + assert(isinstance(index_typ, types.ArrayCompatible)) + size_vars = equiv_set.get_shape(target) + bool_typ = index_typ.dtype + + # generate loopnests and size variables from lhs correlations + loopnests = [] + index_vars = [] + for size_var in size_vars: + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + index_vars.append(index_var) + pass_states.typemap[index_var.name] = types.uintp + loopnests.append(LoopNest(index_var, 0, size_var, 1)) + + # generate body + body_label = next_label() + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('setitem', ''), pass_states.flags) + if shape: + # slice subarray + parfor.loop_body = {body_label: body_block} + true_block = body_block + end_label = None + else: + # boolean mask + true_label = next_label() + true_block = ir.Block(scope, loc) + end_label = next_label() + end_block = ir.Block(scope, loc) + parfor.loop_body = {body_label: body_block, + true_label: true_block, + end_label: end_block, + } + mask_var = ir.Var(scope, mk_unique_var("$mask_var"), loc) + pass_states.typemap[mask_var.name] = bool_typ + mask_val = ir.Expr.getitem(index, index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask_var, loc), + ir.Branch(mask_var, true_label, end_label, loc) + ]) + + value_typ = pass_states.typemap[value.name] + if isinstance(value_typ, types.npytypes.Array): + value_var = ir.Var(scope, mk_unique_var("$value_var"), loc) + pass_states.typemap[value_var.name] = value_typ.dtype + getitem_call = ir.Expr.getitem(value, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + value_typ.dtype, value_typ, index_var_typ) + true_block.body.append(ir.Assign(getitem_call, value_var, loc)) + else: + value_var = value + setitem_node = ir.SetItem(target, index_var, value_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[target.name], index_var_typ, el_typ) + true_block.body.append(setitem_node) + if end_label: + true_block.body.append(ir.Jump(end_label, loc)) + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from setitem") + parfor.dump() + return parfor + + def _type_getitem(self, args): + fnty = operator.getitem + return self.pass_states.typingctx.resolve_function_type(fnty, tuple(args), {}) + + +def _make_index_var(typemap, scope, index_vars, body_block, force_tuple=False): + """ When generating a SetItem call to an array in a parfor, the general + strategy is to generate a tuple if the array is more than 1 dimension. + If it is 1 dimensional then you can use a simple variable. This routine + is also used when converting pndindex to parfor but pndindex requires a + tuple even if the iteration space is 1 dimensional. The pndindex use of + this function will use force_tuple to make the output index a tuple even + if it is one dimensional. + """ + ndims = len(index_vars) + loc = body_block.loc + if ndims > 1 or force_tuple: + tuple_var = ir.Var(scope, mk_unique_var( + "$parfor_index_tuple_var"), loc) + typemap[tuple_var.name] = types.containers.UniTuple( + types.uintp, ndims) + tuple_call = ir.Expr.build_tuple(list(index_vars), loc) + tuple_assign = ir.Assign(tuple_call, tuple_var, loc) + body_block.body.append(tuple_assign) + return tuple_var, types.containers.UniTuple(types.uintp, ndims) + elif ndims == 1: + return index_vars[0], types.uintp + else: + raise errors.UnsupportedRewriteError( + "Parfor does not handle arrays of dimension 0", + loc=loc, + ) + + +def _mk_parfor_loops(typemap, size_vars, scope, loc): + """ + Create loop index variables and build LoopNest objects for a parfor. + """ + loopnests = [] + index_vars = [] + for size_var in size_vars: + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + index_vars.append(index_var) + typemap[index_var.name] = types.uintp + loopnests.append(LoopNest(index_var, 0, size_var, 1)) + return index_vars, loopnests + +class ConvertNumpyPass: + """ + Convert supported Numpy functions, as well as arrayexpr nodes, to + parfor nodes. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + topo_order = find_topo_order(blocks) + # variables available in the program so far (used for finding map + # functions in array_expr lowering) + avail_vars = [] + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + if isinstance(instr, ir.Assign): + expr = instr.value + lhs = instr.target + lhs_typ = self.pass_states.typemap[lhs.name] + if self._is_C_or_F_order(lhs_typ): + if guard(self._is_supported_npycall, expr): + new_instr = self._numpy_to_parfor(equiv_set, lhs, expr) + if new_instr is not None: + self.rewritten.append(dict( + old=instr, + new=new_instr, + reason='numpy_allocator', + )) + instr = new_instr + elif isinstance(expr, ir.Expr) and expr.op == 'arrayexpr': + new_instr = self._arrayexpr_to_parfor( + equiv_set, lhs, expr, avail_vars) + self.rewritten.append(dict( + old=instr, + new=new_instr, + reason='arrayexpr', + )) + instr = new_instr + avail_vars.append(lhs.name) + new_body.append(instr) + block.body = new_body + + def _is_C_order(self, arr_name): + if isinstance(arr_name, types.npytypes.Array): + return arr_name.layout == 'C' and arr_name.ndim > 0 + elif arr_name is str: + typ = self.pass_states.typemap[arr_name] + return (isinstance(typ, types.npytypes.Array) and + typ.layout == 'C' and + typ.ndim > 0) + else: + return False + + def _is_C_or_F_order(self, arr_name): + if isinstance(arr_name, types.npytypes.Array): + return (arr_name.layout == 'C' or arr_name.layout == 'F') and arr_name.ndim > 0 + elif arr_name is str: + typ = self.pass_states.typemap[arr_name] + return (isinstance(typ, types.npytypes.Array) and + (typ.layout == 'C' or typ.layout == 'F') and + typ.ndim > 0) + else: + return False + + def _arrayexpr_to_parfor(self, equiv_set, lhs, arrayexpr, avail_vars): + """generate parfor from arrayexpr node, which is essentially a + map with recursive tree. + """ + pass_states = self.pass_states + scope = lhs.scope + loc = lhs.loc + expr = arrayexpr.expr + arr_typ = pass_states.typemap[lhs.name] + el_typ = arr_typ.dtype + + # generate loopnests and size variables from lhs correlations + size_vars = equiv_set.get_shape(lhs) + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate init block and body + init_block = ir.Block(scope, loc) + init_block.body = mk_alloc( + pass_states.typingctx, + pass_states.typemap, pass_states.calltypes, lhs, + tuple(size_vars), el_typ, scope, loc, + pass_states.typemap[lhs.name]) + body_label = next_label() + body_block = ir.Block(scope, loc) + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + body_block.body.extend( + _arrayexpr_tree_to_ir( + pass_states.func_ir, + pass_states.typingctx, + pass_states.typemap, + pass_states.calltypes, + equiv_set, + init_block, + expr_out_var, + expr, + index_var, + index_vars, + avail_vars)) + + pat = ('array expression {}'.format(repr_arrayexpr(arrayexpr.expr)),) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, pat[0], pass_states.flags) + + setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[lhs.name], index_var_typ, el_typ) + body_block.body.append(setitem_node) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from arrayexpr") + parfor.dump() + return parfor + + def _is_supported_npycall(self, expr): + """check if we support parfor translation for + this Numpy call. + """ + call_name, mod_name = find_callname(self.pass_states.func_ir, expr) + if not (isinstance(mod_name, str) and mod_name.startswith('numpy')): + return False + if call_name in ['zeros', 'ones']: + return True + if mod_name == 'numpy.random' and call_name in random_calls: + return True + # TODO: add more calls + return False + + def _numpy_to_parfor(self, equiv_set, lhs, expr): + call_name, mod_name = find_callname(self.pass_states.func_ir, expr) + args = expr.args + kws = dict(expr.kws) + if call_name in ['zeros', 'ones'] or mod_name == 'numpy.random': + return self._numpy_map_to_parfor(equiv_set, call_name, lhs, args, kws, expr) + # return error if we couldn't handle it (avoid rewrite infinite loop) + raise errors.UnsupportedRewriteError( + f"parfor translation failed for {expr}", loc=expr.loc, + ) + + def _numpy_map_to_parfor(self, equiv_set, call_name, lhs, args, kws, expr): + """generate parfor from Numpy calls that are maps. + """ + pass_states = self.pass_states + scope = lhs.scope + loc = lhs.loc + arr_typ = pass_states.typemap[lhs.name] + el_typ = arr_typ.dtype + + # generate loopnests and size variables from lhs correlations + size_vars = equiv_set.get_shape(lhs) + if size_vars is None: + if config.DEBUG_ARRAY_OPT >= 1: + print("Could not convert numpy map to parfor, unknown size") + return None + + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + + # generate init block and body + init_block = ir.Block(scope, loc) + init_block.body = mk_alloc( + pass_states.typingctx, + pass_states.typemap, pass_states.calltypes, lhs, + tuple(size_vars), el_typ, scope, loc, + pass_states.typemap[lhs.name]) + body_label = next_label() + body_block = ir.Block(scope, loc) + expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc) + pass_states.typemap[expr_out_var.name] = el_typ + + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + if call_name == 'zeros': + value = ir.Const(el_typ(0), loc) + elif call_name == 'ones': + value = ir.Const(el_typ(1), loc) + elif call_name in random_calls: + # remove size arg to reuse the call expr for single value + _remove_size_arg(call_name, expr) + # update expr type + new_arg_typs, new_kw_types = _get_call_arg_types( + expr, pass_states.typemap) + pass_states.calltypes.pop(expr) + pass_states.calltypes[expr] = pass_states.typemap[expr.func.name].get_call_type( + typing.Context(), new_arg_typs, new_kw_types) + value = expr + else: + raise NotImplementedError( + "Map of numpy.{} to parfor is not implemented".format(call_name)) + + value_assign = ir.Assign(value, expr_out_var, loc) + body_block.body.append(value_assign) + + setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc) + pass_states.calltypes[setitem_node] = signature( + types.none, pass_states.typemap[lhs.name], index_var_typ, el_typ) + body_block.body.append(setitem_node) + + parfor = Parfor(loopnests, init_block, {}, loc, index_var, equiv_set, + ('{} function'.format(call_name,), 'NumPy mapping'), + pass_states.flags) + parfor.loop_body = {body_label: body_block} + if config.DEBUG_ARRAY_OPT >= 1: + print("generated parfor for numpy map:") + parfor.dump() + return parfor + + +class ConvertReducePass: + """ + Find reduce() calls and convert them to parfors. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + + topo_order = find_topo_order(blocks) + for label in topo_order: + block = blocks[label] + new_body = [] + equiv_set = pass_states.array_analysis.get_equiv_set(label) + for instr in block.body: + parfor = None + if isinstance(instr, ir.Assign): + loc = instr.loc + lhs = instr.target + expr = instr.value + callname = guard(find_callname, pass_states.func_ir, expr) + if (callname == ('reduce', 'builtins') + or callname == ('reduce', '_functools')): + # reduce function with generic function + parfor = guard(self._reduce_to_parfor, equiv_set, lhs, + expr.args, loc) + if parfor: + self.rewritten.append(dict( + new=parfor, + old=instr, + reason='reduce', + )) + instr = parfor + new_body.append(instr) + block.body = new_body + return + + def _reduce_to_parfor(self, equiv_set, lhs, args, loc): + """ + Convert a reduce call to a parfor. + The call arguments should be (call_name, array, init_value). + """ + pass_states = self.pass_states + + scope = lhs.scope + call_name = args[0] + in_arr = args[1] + arr_def = get_definition(pass_states.func_ir, in_arr.name) + + mask_var = None + mask_indices = None + + # Search for array[boolean_mask] + mask_query_result = guard(_find_mask, pass_states.typemap, pass_states.func_ir, arr_def) + if mask_query_result: + in_arr, mask_var, mask_typ, mask_indices = mask_query_result + + init_val = args[2] + size_vars = equiv_set.get_shape(in_arr if mask_indices is None else mask_var) + if size_vars is None: + return None + + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, scope, loc) + mask_index = index_vars + if mask_indices: + # the following is never tested + raise AssertionError("unreachable") + index_vars = tuple(x if x else index_vars[0] for x in mask_indices) + acc_var = lhs + + # init block has to init the reduction variable + init_block = ir.Block(scope, loc) + init_block.body.append(ir.Assign(init_val, acc_var, loc)) + + # produce loop body + body_label = next_label() + index_var, loop_body = self._mk_reduction_body(call_name, + scope, loc, index_vars, in_arr, acc_var) + if mask_indices: + # the following is never tested + raise AssertionError("unreachable") + index_var = mask_index[0] + + if mask_var is not None: + true_label = min(loop_body.keys()) + false_label = max(loop_body.keys()) + body_block = ir.Block(scope, loc) + loop_body[body_label] = body_block + mask = ir.Var(scope, mk_unique_var("$mask_val"), loc) + pass_states.typemap[mask.name] = mask_typ + mask_val = ir.Expr.getitem(mask_var, index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask, loc), + ir.Branch(mask, true_label, false_label, loc) + ]) + + parfor = Parfor(loopnests, init_block, loop_body, loc, index_var, + equiv_set, ('{} function'.format(call_name), + 'reduction'), pass_states.flags) + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from reduction") + parfor.dump() + return parfor + + def _mk_reduction_body(self, call_name, scope, loc, + index_vars, in_arr, acc_var): + """ + Produce the body blocks for a reduction function indicated by call_name. + """ + from numba.core.inline_closurecall import check_reduce_func + + pass_states = self.pass_states + reduce_func = get_definition(pass_states.func_ir, call_name) + fcode = check_reduce_func(pass_states.func_ir, reduce_func) + + arr_typ = pass_states.typemap[in_arr.name] + in_typ = arr_typ.dtype + body_block = ir.Block(scope, loc) + index_var, index_var_type = _make_index_var( + pass_states.typemap, scope, index_vars, body_block) + + tmp_var = ir.Var(scope, mk_unique_var("$val"), loc) + pass_states.typemap[tmp_var.name] = in_typ + getitem_call = ir.Expr.getitem(in_arr, index_var, loc) + pass_states.calltypes[getitem_call] = signature( + in_typ, arr_typ, index_var_type) + body_block.append(ir.Assign(getitem_call, tmp_var, loc)) + + reduce_f_ir = compile_to_numba_ir(fcode, + pass_states.func_ir.func_id.func.__globals__, + pass_states.typingctx, + pass_states.targetctx, + (in_typ, in_typ), + pass_states.typemap, + pass_states.calltypes) + loop_body = reduce_f_ir.blocks + end_label = next_label() + end_block = ir.Block(scope, loc) + loop_body[end_label] = end_block + first_reduce_label = min(reduce_f_ir.blocks.keys()) + first_reduce_block = reduce_f_ir.blocks[first_reduce_label] + body_block.body.extend(first_reduce_block.body) + first_reduce_block.body = body_block.body + replace_arg_nodes(first_reduce_block, [acc_var, tmp_var]) + replace_returns(loop_body, acc_var, end_label) + return index_var, loop_body + + +class ConvertLoopPass: + """Build Parfor nodes from prange loops. + """ + def __init__(self, pass_states): + self.pass_states = pass_states + self.rewritten = [] + + def run(self, blocks): + pass_states = self.pass_states + + call_table, _ = get_call_table(blocks) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + loops = cfg.loops() + sized_loops = [(loops[k], len(loops[k].body)) for k in loops.keys()] + moved_blocks = [] + # We go over all loops, smaller loops first (inner first) + for loop, s in sorted(sized_loops, key=lambda tup: tup[1]): + if len(loop.entries) != 1 or len(loop.exits) != 1: + if not config.DISABLE_PERFORMANCE_WARNINGS: + for entry in loop.entries: + for inst in blocks[entry].body: + # if prange or pndindex call + if ( + isinstance(inst, ir.Assign) + and isinstance(inst.value, ir.Expr) + and inst.value.op == "call" + and self._is_parallel_loop( + inst.value.func.name, call_table) + ): + msg = "\nprange or pndindex loop " \ + "will not be executed in " \ + "parallel due to there being more than one " \ + "entry to or exit from the loop (e.g., an " \ + "assertion)." + warnings.warn( + errors.NumbaPerformanceWarning( + msg, inst.loc)) + continue + + entry = list(loop.entries)[0] + for inst in blocks[entry].body: + # if prange or pndindex call + if (isinstance(inst, ir.Assign) + and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_parallel_loop(inst.value.func.name, call_table)): + # Here we've found a parallel loop, either prange or pndindex. + # We create a parfor from this loop and then overwrite the contents + # of the original loop header block to contain this parfor and then + # a jump to the original loop exit block. Other blocks in the + # original loop are discarded. + body_labels = [ l for l in loop.body if + l in blocks and l != loop.header ] + args = inst.value.args + loop_kind, loop_replacing = self._get_loop_kind(inst.value.func.name, + call_table) + # Get the body of the header of the loops minus the branch terminator + # The general approach is to prepend the header block to the first + # body block and then let dead code removal handle removing unneeded + # statements. Not all statements in the header block are unnecessary. + header_body = blocks[loop.header].body[:-1] + # find loop index variable (pair_first in header block) + loop_index = None + for hbi, stmt in enumerate(header_body): + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'pair_first'): + loop_index = stmt.target.name + li_index = hbi + break + assert(loop_index is not None) + # Remove pair_first from header. + # We have to remove the pair_first by hand since it causes problems + # for some code below if we don't. + header_body = header_body[:li_index] + header_body[li_index+1:] + + # loop_index may be assigned to other vars + # get header copies to find all of them + cps, _ = get_block_copies({0: blocks[loop.header]}, + pass_states.typemap) + cps = cps[0] + loop_index_vars = set(t for t, v in cps if v == loop_index) + loop_index_vars.add(loop_index) + + scope = blocks[entry].scope + loc = inst.loc + equiv_set = pass_states.array_analysis.get_equiv_set(loop.header) + init_block = ir.Block(scope, loc) + init_block.body = self._get_prange_init_block(blocks[entry], + call_table, args) + loop_body = {l: blocks[l] for l in body_labels} + # Add an empty block to the end of loop body + end_label = next_label() + loop_body[end_label] = ir.Block(scope, loc) + + # Detect races in the prange. + # Races are defs in the parfor body that are live at the exit block. + bodydefs = set() + for bl in body_labels: + bodydefs = bodydefs.union(usedefs.defmap[bl]) + exit_lives = set() + for bl in loop.exits: + exit_lives = exit_lives.union(live_map[bl]) + races = bodydefs.intersection(exit_lives) + # It is possible for the result of an ir.Global to be flagged + # as a race if it is defined in this Parfor and then used in + # a subsequent Parfor. push_call_vars() in the Parfor pass + # copies such ir.Global nodes into the Parfors in which they + # are used so no need to treat things of type Module as a race. + races = races.intersection({x for x in races + if not isinstance(pass_states.typemap[x], types.misc.Module)}) + + # replace jumps to header block with the end block + for l in body_labels: + last_inst = loop_body[l].body[-1] + if (isinstance(last_inst, ir.Jump) and + last_inst.target == loop.header): + last_inst.target = end_label + + def find_indexed_arrays(): + """find expressions that involve getitem using the + index variable. Return both the arrays and expressions. + """ + indices = copy.copy(loop_index_vars) + for block in loop_body.values(): + for inst in block.find_insts(ir.Assign): + if (isinstance(inst.value, ir.Var) and + inst.value.name in indices): + indices.add(inst.target.name) + arrs = [] + exprs = [] + for block in loop_body.values(): + for inst in block.body: + lv = set(x.name for x in inst.list_vars()) + if lv & indices: + if lv.issubset(indices): + continue + require(isinstance(inst, ir.Assign)) + expr = inst.value + require(isinstance(expr, ir.Expr) and + expr.op in ['getitem', 'static_getitem']) + arrs.append(expr.value.name) + exprs.append(expr) + return arrs, exprs + + mask_var = None + mask_indices = None + def find_mask_from_size(size_var): + """Find the case where size_var is defined by A[M].shape, + where M is a boolean array. + """ + size_def = get_definition(pass_states.func_ir, size_var) + require(size_def and isinstance(size_def, ir.Expr) and + size_def.op == 'getattr' and size_def.attr == 'shape') + arr_var = size_def.value + live_vars = set.union(*[live_map[l] for l in loop.exits]) + index_arrs, index_exprs = find_indexed_arrays() + require([arr_var.name] == list(index_arrs)) + # input array has to be dead after loop + require(arr_var.name not in live_vars) + # loop for arr's definition, where size = arr.shape + arr_def = get_definition(pass_states.func_ir, size_def.value) + result = _find_mask(pass_states.typemap, pass_states.func_ir, arr_def) + + # The following is never tested. + raise AssertionError("unreachable") + # Found the mask. + # Replace B[i] with A[i], where B = A[M] + for expr in index_exprs: + expr.value = result[0] + return result + + # pndindex and prange are provably positive except when + # user provides negative start to prange() + unsigned_index = True + # TODO: support array mask optimization for prange + # TODO: refactor and simplify array mask optimization + if loop_kind == 'pndindex': + assert(equiv_set.has_shape(args[0])) + # see if input array to pndindex is output of array + # mask like B = A[M] + result = guard(find_mask_from_size, args[0]) + if result: + in_arr, mask_var, mask_typ, mask_indices = result + else: + in_arr = args[0] + assert(isinstance(in_arr, ir.Var)) + in_arr_typ = pass_states.typemap[in_arr.name] + if isinstance(in_arr_typ, types.Integer): + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + pass_states.typemap[index_var.name] = types.uintp + loops = [LoopNest(index_var, 0, in_arr, 1)] + index_vars = [index_var] + else: + size_vars = equiv_set.get_shape(in_arr + if mask_indices is None else mask_var) + index_vars, loops = _mk_parfor_loops( + pass_states.typemap, size_vars, scope, loc, + ) + assert(len(loops) > 0) + orig_index = index_vars + if mask_indices: + # replace mask indices if required; + # integer indices of original array should be used + # instead of parfor indices + index_vars = tuple(x if x else index_vars[0] + for x in mask_indices) + first_body_block = loop_body[min(loop_body.keys())] + body_block = ir.Block(scope, loc) + index_var, index_var_typ = _make_index_var( + pass_states.typemap, scope, index_vars, body_block, + force_tuple=True + ) + body = body_block.body + first_body_block.body + first_body_block.body = body + if mask_indices: + orig_index_var = orig_index[0] + else: + orig_index_var = index_var + + # if masked array optimization is being applied, create + # the branch for array selection + if mask_var is not None: + # The following code are not tested + raise AssertionError("unreachable") + body_label = next_label() + # loop_body needs new labels greater than body_label + loop_body = add_offset_to_labels(loop_body, + body_label - min(loop_body.keys()) + 1) + labels = loop_body.keys() + true_label = min(labels) + false_label = max(labels) + body_block = ir.Block(scope, loc) + loop_body[body_label] = body_block + mask = ir.Var(scope, mk_unique_var("$mask_val"), loc) + pass_states.typemap[mask.name] = mask_typ + mask_val = ir.Expr.getitem(mask_var, orig_index_var, loc) + body_block.body.extend([ + ir.Assign(mask_val, mask, loc), + ir.Branch(mask, true_label, false_label, loc) + ]) + else: # prange + start = 0 + step = 1 + size_var = args[0] + if len(args) == 2: + start = args[0] + size_var = args[1] + if len(args) == 3: + start = args[0] + size_var = args[1] + try: + step = pass_states.func_ir.get_definition(args[2]) + except KeyError: + raise errors.UnsupportedRewriteError( + "Only known step size is supported for prange", + loc=inst.loc, + ) + if not isinstance(step, ir.Const): + raise errors.UnsupportedRewriteError( + "Only constant step size is supported for prange", + loc=inst.loc, + ) + step = step.value + if step != 1: + raise errors.UnsupportedRewriteError( + "Only constant step size of 1 is supported for prange", + loc=inst.loc, + ) + index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc) + # assume user-provided start to prange can be negative + # this is the only case parfor can have negative index + if isinstance(start, int) and start >= 0: + index_var_typ = types.uintp + else: + index_var_typ = types.intp + unsigned_index = False + loops = [LoopNest(index_var, start, size_var, step)] + pass_states.typemap[index_var.name] = index_var_typ + + # We can't just drop the header block since there can be things + # in there other than the prange looping infrastructure. + # So we just add the header to the first loop body block (minus the + # branch) and let dead code elimination remove the unnecessary parts. + first_body_label = min(loop_body.keys()) + loop_body[first_body_label].body = header_body + loop_body[first_body_label].body + + index_var_map = {v: index_var for v in loop_index_vars} + replace_vars(loop_body, index_var_map) + if unsigned_index: + # need to replace signed array access indices to enable + # optimizations (see #2846) + self._replace_loop_access_indices( + loop_body, loop_index_vars, index_var) + parfor = Parfor(loops, init_block, loop_body, loc, + orig_index_var if mask_indices else index_var, + equiv_set, + ("prange", loop_kind, loop_replacing), + pass_states.flags, races=races) + + blocks[loop.header].body = [parfor] + # We have to insert the header_body after the parfor because in + # a Numba loop this will be executed one more times before the + # branch and may contain instructions such as variable renamings + # that are relied upon later. + blocks[loop.header].body.extend(header_body) + blocks[loop.header].body.append(ir.Jump(list(loop.exits)[0], loc)) + self.rewritten.append(dict( + old_loop=loop, + new=parfor, + reason='loop', + )) + # remove loop blocks from top level dict + for l in body_labels: + if l != loop.header: + blocks.pop(l) + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor from loop") + parfor.dump() + + def _is_parallel_loop(self, func_var, call_table): + # prange can be either getattr (numba.prange) or global (prange) + if func_var not in call_table: + return False + call = call_table[func_var] + return len(call) > 0 and (call[0] == 'prange' or call[0] == prange + or call[0] == 'internal_prange' or call[0] == internal_prange + or call[0] == 'pndindex' or call[0] == pndindex) + + def _get_loop_kind(self, func_var, call_table): + """see if prange is user prange or internal""" + pass_states = self.pass_states + # prange can be either getattr (numba.prange) or global (prange) + assert func_var in call_table + call = call_table[func_var] + assert len(call) > 0 + kind = 'user', '' + if call[0] == 'internal_prange' or call[0] == internal_prange: + try: + kind = 'internal', (pass_states.swapped_fns[func_var][0], pass_states.swapped_fns[func_var][-1]) + except KeyError: + # FIXME: Fix this issue... the code didn't manage to trace the + # swapout for func_var so set the kind as internal so that the + # transform can occur, it's just not tracked + kind = 'internal', ('', '') + elif call[0] == 'pndindex' or call[0] == pndindex: + kind = 'pndindex', '' + return kind + + def _get_prange_init_block(self, entry_block, call_table, prange_args): + """ + If there is init_prange, find the code between init_prange and prange + calls. Remove the code from entry_block and return it. + """ + init_call_ind = -1 + prange_call_ind = -1 + init_body = [] + for i, inst in enumerate(entry_block.body): + # if init_prange call + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_prange_init(inst.value.func.name, call_table)): + init_call_ind = i + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and self._is_parallel_loop(inst.value.func.name, call_table)): + prange_call_ind = i + if init_call_ind != -1 and prange_call_ind != -1: + # we save instructions that are used to calculate prange call args + # in the entry block. The rest go to parfor init_block + arg_related_vars = {v.name for v in prange_args} + saved_nodes = [] + for i in reversed(range(init_call_ind+1, prange_call_ind)): + inst = entry_block.body[i] + inst_vars = {v.name for v in inst.list_vars()} + if arg_related_vars & inst_vars: + arg_related_vars |= inst_vars + saved_nodes.append(inst) + else: + init_body.append(inst) + + init_body.reverse() + saved_nodes.reverse() + entry_block.body = (entry_block.body[:init_call_ind] + + saved_nodes + entry_block.body[prange_call_ind+1:]) + + return init_body + + def _is_prange_init(self, func_var, call_table): + if func_var not in call_table: + return False + call = call_table[func_var] + return len(call) > 0 and (call[0] == 'init_prange' or call[0] == init_prange) + + def _replace_loop_access_indices(self, loop_body, index_set, new_index): + """ + Replace array access indices in a loop body with a new index. + index_set has all the variables that are equivalent to loop index. + """ + # treat new index like others since replacing it with itself is ok + index_set.add(new_index.name) + + with dummy_return_in_loop_body(loop_body): + labels = find_topo_order(loop_body) + + first_label = labels[0] + added_indices = set() + + # traverse loop body and replace indices in getitem/setitem with + # new_index if possible. + # also, find equivalent indices defined in first block. + for l in labels: + block = loop_body[l] + for stmt in block.body: + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Var)): + # the first block dominates others so we can use copies + # of indices safely + if (l == first_label and stmt.value.name in index_set + and stmt.target.name not in index_set): + index_set.add(stmt.target.name) + added_indices.add(stmt.target.name) + # make sure parallel index is not overwritten + else: + scope = block.scope + + def unver(name): + from numba.core import errors + try: + return scope.get_exact(name).unversioned_name + except errors.NotDefinedError: + return name + + if unver(stmt.target.name) in map(unver, index_set) and unver(stmt.target.name) != unver(stmt.value.name): + raise errors.UnsupportedRewriteError( + "Overwrite of parallel loop index", + loc=stmt.target.loc, + ) + + + + if is_get_setitem(stmt): + index = index_var_of_get_setitem(stmt) + # statics can have none indices + if index is None: + continue + ind_def = guard(get_definition, self.pass_states.func_ir, + index, lhs_only=True) + if (index.name in index_set + or (ind_def is not None + and ind_def.name in index_set)): + set_index_var_of_get_setitem(stmt, new_index) + # corner case where one dimension of a multi-dim access + # should be replaced + guard(self._replace_multi_dim_ind, ind_def, index_set, + new_index) + + if isinstance(stmt, Parfor): + self._replace_loop_access_indices(stmt.loop_body, index_set, new_index) + + # remove added indices for correct recursive parfor handling + index_set -= added_indices + return + + def _replace_multi_dim_ind(self, ind_var, index_set, new_index): + """ + replace individual indices in multi-dimensional access variable, which + is a build_tuple + """ + pass_states = self.pass_states + require(ind_var is not None) + # check for Tuple instead of UniTuple since some dims could be slices + require(isinstance(pass_states.typemap[ind_var.name], + (types.Tuple, types.UniTuple))) + ind_def_node = get_definition(pass_states.func_ir, ind_var) + require(isinstance(ind_def_node, ir.Expr) + and ind_def_node.op == 'build_tuple') + ind_def_node.items = [new_index if v.name in index_set else v + for v in ind_def_node.items] + + +def _find_mask(typemap, func_ir, arr_def): + """check if an array is of B[...M...], where M is a + boolean array, and other indices (if available) are ints. + If found, return B, M, M's type, and a tuple representing mask indices. + Otherwise, raise GuardException. + """ + require(isinstance(arr_def, ir.Expr) and arr_def.op == 'getitem') + value = arr_def.value + index = arr_def.index + value_typ = typemap[value.name] + index_typ = typemap[index.name] + ndim = value_typ.ndim + require(isinstance(value_typ, types.npytypes.Array)) + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean) and + ndim == index_typ.ndim): + return value, index, index_typ.dtype, None + elif isinstance(index_typ, types.BaseTuple): + # Handle multi-dimension differently by requiring + # all indices to be constant except the one for mask. + seq, op = find_build_sequence(func_ir, index) + require(op == 'build_tuple' and len(seq) == ndim) + count_consts = 0 + mask_indices = [] + mask_var = None + for ind in seq: + index_typ = typemap[ind.name] + # Handle boolean mask + if (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Boolean)): + mask_var = ind + mask_typ = index_typ.dtype + mask_indices.append(None) + # Handle integer array selector + elif (isinstance(index_typ, types.npytypes.Array) and + isinstance(index_typ.dtype, types.Integer)): + mask_var = ind + mask_typ = index_typ.dtype + mask_indices.append(None) + # Handle integer index + elif isinstance(index_typ, types.Integer): + count_consts += 1 + mask_indices.append(ind) + + require(mask_var and count_consts == ndim - 1) + return value, mask_var, mask_typ, mask_indices + raise GuardException + + +class ParforPass(ParforPassStates): + + """ParforPass class is responsible for converting NumPy + calls in Numba intermediate representation to Parfors, which + will lower into either sequential or parallel loops during lowering + stage. + """ + + def _pre_run(self): + # run array analysis, a pre-requisite for parfor translation + self.array_analysis.run(self.func_ir.blocks) + # NOTE: Prepare _the_max_label. See #6102 + ir_utils._the_max_label.update( + ir_utils.find_max_label(self.func_ir.blocks)) + + def run(self): + """run parfor conversion pass: replace Numpy calls + with Parfors when possible and optimize the IR.""" + self._pre_run() + # run stencil translation to parfor + if self.options.stencil: + stencil_pass = StencilPass(self.func_ir, self.typemap, + self.calltypes, self.array_analysis, + self.typingctx, self.targetctx, + self.flags) + stencil_pass.run() + if self.options.setitem: + ConvertSetItemPass(self).run(self.func_ir.blocks) + if self.options.numpy: + ConvertNumpyPass(self).run(self.func_ir.blocks) + if self.options.reduction: + ConvertReducePass(self).run(self.func_ir.blocks) + if self.options.prange: + ConvertLoopPass(self).run(self.func_ir.blocks) + if self.options.inplace_binop: + ConvertInplaceBinop(self).run(self.func_ir.blocks) + + # setup diagnostics now parfors are found + self.diagnostics.setup(self.func_ir, self.options.fusion) + + dprint_func_ir(self.func_ir, "after parfor pass") + + def _find_mask(self, arr_def): + """check if an array is of B[...M...], where M is a + boolean array, and other indices (if available) are ints. + If found, return B, M, M's type, and a tuple representing mask indices. + Otherwise, raise GuardException. + """ + return _find_mask(self.typemap, self.func_ir, arr_def) + + def _mk_parfor_loops(self, size_vars, scope, loc): + """ + Create loop index variables and build LoopNest objects for a parfor. + """ + return _mk_parfor_loops(self.typemap, size_vars, scope, loc) + + +class ParforFusionPass(ParforPassStates): + + """ParforFusionPass class is responsible for fusing parfors + """ + + def run(self): + """run parfor fusion pass""" + + # simplify CFG of parfor body loops since nested parfors with extra + # jumps can be created with prange conversion + n_parfors = simplify_parfor_body_CFG(self.func_ir.blocks) + # simplify before fusion + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + # need two rounds of copy propagation to enable fusion of long sequences + # of parfors like test_fuse_argmin (some PYTHONHASHSEED values since + # apply_copies_parfor depends on set order for creating dummy assigns) + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + + if self.options.fusion and n_parfors >= 2: + self.func_ir._definitions = build_definitions(self.func_ir.blocks) + self.array_analysis.equiv_sets = dict() + self.array_analysis.run(self.func_ir.blocks) + + # Get parfor params to calculate reductions below. + _, parfors = get_parfor_params(self.func_ir.blocks, + self.options.fusion, + self.nested_fusion_info) + + # Find reductions so that fusion can be disallowed if a + # subsequent parfor read a reduction variable. + for p in parfors: + p.redvars, p.reddict = get_parfor_reductions(self.func_ir, + p, + p.params, + self.calltypes) + + # reorder statements to maximize fusion + # push non-parfors down + maximize_fusion(self.func_ir, self.func_ir.blocks, self.typemap, + up_direction=False) + dprint_func_ir(self.func_ir, "after maximize fusion down") + self.fuse_parfors(self.array_analysis, + self.func_ir.blocks, + self.func_ir, + self.typemap) + dprint_func_ir(self.func_ir, "after first fuse") + # push non-parfors up + maximize_fusion(self.func_ir, self.func_ir.blocks, self.typemap) + dprint_func_ir(self.func_ir, "after maximize fusion up") + # try fuse again after maximize + self.fuse_parfors(self.array_analysis, + self.func_ir.blocks, + self.func_ir, + self.typemap) + dprint_func_ir(self.func_ir, "after fusion") + # remove dead code after fusion to remove extra arrays and variables + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + + def fuse_parfors(self, array_analysis, blocks, func_ir, typemap): + for label, block in blocks.items(): + equiv_set = array_analysis.get_equiv_set(label) + fusion_happened = True + while fusion_happened: + fusion_happened = False + new_body = [] + i = 0 + while i < len(block.body) - 1: + stmt = block.body[i] + next_stmt = block.body[i + 1] + if isinstance(stmt, Parfor) and isinstance(next_stmt, Parfor): + # we have to update equiv_set since they have changed due to + # variables being renamed before fusion. + equiv_set = array_analysis.get_equiv_set(label) + stmt.equiv_set = equiv_set + next_stmt.equiv_set = equiv_set + fused_node, fuse_report = try_fuse(equiv_set, stmt, next_stmt, + self.metadata["parfors"], func_ir, typemap) + # accumulate fusion reports + self.diagnostics.fusion_reports.append(fuse_report) + if fused_node is not None: + fusion_happened = True + self.diagnostics.fusion_info[stmt.id].extend([next_stmt.id]) + new_body.append(fused_node) + self.fuse_recursive_parfor(fused_node, equiv_set, func_ir, typemap) + i += 2 + continue + new_body.append(stmt) + if isinstance(stmt, Parfor): + self.fuse_recursive_parfor(stmt, equiv_set, func_ir, typemap) + i += 1 + new_body.append(block.body[-1]) + block.body = new_body + return + + def fuse_recursive_parfor(self, parfor, equiv_set, func_ir, typemap): + blocks = wrap_parfor_blocks(parfor) + maximize_fusion(self.func_ir, blocks, self.typemap) + dprint_func_ir(self.func_ir, "after recursive maximize fusion down", blocks) + arr_analysis = array_analysis.ArrayAnalysis(self.typingctx, self.func_ir, + self.typemap, self.calltypes) + arr_analysis.run(blocks, equiv_set) + self.fuse_parfors(arr_analysis, blocks, func_ir, typemap) + unwrap_parfor_blocks(parfor) + + +class ParforPreLoweringPass(ParforPassStates): + + """ParforPreLoweringPass class is responsible for preparing parfors for lowering. + """ + + def run(self): + """run parfor prelowering pass""" + + # push function call variables inside parfors so gufunc function + # wouldn't need function variables as argument + push_call_vars(self.func_ir.blocks, {}, {}, self.typemap) + dprint_func_ir(self.func_ir, "after push call vars") + # simplify again + simplify(self.func_ir, self.typemap, self.calltypes, self.metadata["parfors"]) + dprint_func_ir(self.func_ir, "after optimization") + if config.DEBUG_ARRAY_OPT >= 1: + print("variable types: ", sorted(self.typemap.items())) + print("call types: ", self.calltypes) + + if config.DEBUG_ARRAY_OPT >= 3: + for(block_label, block) in self.func_ir.blocks.items(): + new_block = [] + scope = block.scope + for stmt in block.body: + new_block.append(stmt) + if isinstance(stmt, ir.Assign): + loc = stmt.loc + lhs = stmt.target + rhs = stmt.value + lhs_typ = self.typemap[lhs.name] + print("Adding print for assignment to ", lhs.name, lhs_typ, type(lhs_typ)) + if lhs_typ in types.number_domain or isinstance(lhs_typ, types.Literal): + str_var = ir.Var(scope, mk_unique_var("str_var"), loc) + self.typemap[str_var.name] = types.StringLiteral(lhs.name) + lhs_const = ir.Const(lhs.name, loc) + str_assign = ir.Assign(lhs_const, str_var, loc) + new_block.append(str_assign) + str_print = ir.Print([str_var], None, loc) + self.calltypes[str_print] = signature(types.none, self.typemap[str_var.name]) + new_block.append(str_print) + ir_print = ir.Print([lhs], None, loc) + self.calltypes[ir_print] = signature(types.none, lhs_typ) + new_block.append(ir_print) + block.body = new_block + + if self.func_ir.is_generator: + fix_generator_types(self.func_ir.generator_info, self.return_type, + self.typemap) + if sequential_parfor_lowering: + lower_parfor_sequential( + self.typingctx, self.func_ir, self.typemap, self.calltypes, self.metadata) + else: + # prepare for parallel lowering + # add parfor params to parfors here since lowering is destructive + # changing the IR after this is not allowed + parfor_ids, parfors = get_parfor_params(self.func_ir.blocks, + self.options.fusion, + self.nested_fusion_info) + + # Validate reduction in parfors. + for p in parfors: + p.redvars, p.reddict = get_parfor_reductions(self.func_ir, + p, + p.params, + self.calltypes) + + # Validate parameters: + for p in parfors: + p.validate_params(self.typemap) + + if config.DEBUG_ARRAY_OPT_STATS: + name = self.func_ir.func_id.func_qualname + n_parfors = len(parfor_ids) + if n_parfors > 0: + after_fusion = ("After fusion" if self.options.fusion + else "With fusion disabled") + print(('{}, function {} has ' + '{} parallel for-loop(s) #{}.').format( + after_fusion, name, n_parfors, parfor_ids)) + else: + print('Function {} has no Parfor.'.format(name)) + + +def _remove_size_arg(call_name, expr): + "remove size argument from args or kws" + # remove size kwarg + kws = dict(expr.kws) + kws.pop('size', '') + expr.kws = tuple(kws.items()) + + # remove size arg if available + if call_name in random_1arg_size + random_int_args: + # these calls have only a "size" argument or list of ints + # so remove all args + expr.args = [] + + if call_name in random_3arg_sizelast: + # normal, uniform, ... have 3 args, last one is size + if len(expr.args) == 3: + expr.args.pop() + + if call_name in random_2arg_sizelast: + # have 2 args, last one is size + if len(expr.args) == 2: + expr.args.pop() + + if call_name == 'randint': + # has 4 args, 3rd one is size + if len(expr.args) == 3: + expr.args.pop() + if len(expr.args) == 4: + dt_arg = expr.args.pop() + expr.args.pop() # remove size + expr.args.append(dt_arg) + + if call_name == 'triangular': + # has 4 args, last one is size + if len(expr.args) == 4: + expr.args.pop() + + return + + +def _get_call_arg_types(expr, typemap): + new_arg_typs = [] + for arg in expr.args: + new_arg_typs.append(typemap[arg.name]) + + new_kw_types = {} + for name, arg in expr.kws: + new_kw_types[name] = typemap[arg.name] + + return tuple(new_arg_typs), new_kw_types + + +def _arrayexpr_tree_to_ir( + func_ir, + typingctx, + typemap, + calltypes, + equiv_set, + init_block, + expr_out_var, + expr, + parfor_index_tuple_var, + all_parfor_indices, + avail_vars): + """generate IR from array_expr's expr tree recursively. Assign output to + expr_out_var and returns the whole IR as a list of Assign nodes. + """ + el_typ = typemap[expr_out_var.name] + scope = expr_out_var.scope + loc = expr_out_var.loc + out_ir = [] + + if isinstance(expr, tuple): + op, arr_expr_args = expr + arg_vars = [] + for arg in arr_expr_args: + arg_out_var = ir.Var(scope, mk_unique_var("$arg_out_var"), loc) + typemap[arg_out_var.name] = el_typ + out_ir += _arrayexpr_tree_to_ir(func_ir, + typingctx, + typemap, + calltypes, + equiv_set, + init_block, + arg_out_var, + arg, + parfor_index_tuple_var, + all_parfor_indices, + avail_vars) + arg_vars.append(arg_out_var) + if op in npydecl.supported_array_operators: + el_typ1 = typemap[arg_vars[0].name] + if len(arg_vars) == 2: + el_typ2 = typemap[arg_vars[1].name] + func_typ = typingctx.resolve_function_type(op, (el_typ1, + el_typ2), {}) + ir_expr = ir.Expr.binop(op, arg_vars[0], arg_vars[1], loc) + if op == operator.truediv: + func_typ, ir_expr = _gen_np_divide( + arg_vars[0], arg_vars[1], out_ir, typemap, typingctx) + else: + func_typ = typingctx.resolve_function_type(op, (el_typ1,), {}) + ir_expr = ir.Expr.unary(op, arg_vars[0], loc) + calltypes[ir_expr] = func_typ + el_typ = func_typ.return_type + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + for T in array_analysis.MAP_TYPES: + if isinstance(op, T): + # elif isinstance(op, (np.ufunc, DUFunc)): + # function calls are stored in variables which are not removed + # op is typing_key to the variables type + func_var_name = _find_func_var(typemap, op, avail_vars, loc=loc) + func_var = ir.Var(scope, mk_unique_var(func_var_name), loc) + typemap[func_var.name] = typemap[func_var_name] + func_var_def = copy.deepcopy(func_ir.get_definition(func_var_name)) + if isinstance(func_var_def, ir.Expr) and func_var_def.op == 'getattr' and func_var_def.attr == 'sqrt': + g_math_var = ir.Var(scope, mk_unique_var("$math_g_var"), loc) + typemap[g_math_var.name] = types.misc.Module(math) + g_math = ir.Global('math', math, loc) + g_math_assign = ir.Assign(g_math, g_math_var, loc) + func_var_def = ir.Expr.getattr(g_math_var, 'sqrt', loc) + out_ir.append(g_math_assign) +# out_ir.append(func_var_def) + ir_expr = ir.Expr.call(func_var, arg_vars, (), loc) + call_typ = typemap[func_var.name].get_call_type( + typingctx, tuple(typemap[a.name] for a in arg_vars), {}) + calltypes[ir_expr] = call_typ + el_typ = call_typ.return_type + #signature(el_typ, el_typ) + out_ir.append(ir.Assign(func_var_def, func_var, loc)) + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + elif isinstance(expr, ir.Var): + var_typ = typemap[expr.name] + if isinstance(var_typ, types.Array): + el_typ = var_typ.dtype + ir_expr = _gen_arrayexpr_getitem( + equiv_set, + expr, + parfor_index_tuple_var, + all_parfor_indices, + el_typ, + calltypes, + typingctx, + typemap, + init_block, + out_ir) + else: + # assert typemap[expr.name]==el_typ + el_typ = var_typ + ir_expr = expr + out_ir.append(ir.Assign(ir_expr, expr_out_var, loc)) + elif isinstance(expr, ir.Const): + el_typ = typing.Context().resolve_value_type(expr.value) + out_ir.append(ir.Assign(expr, expr_out_var, loc)) + + if len(out_ir) == 0: + raise errors.UnsupportedRewriteError( + f"Don't know how to translate array expression '{expr:r}'", + loc=expr.loc, + ) + typemap.pop(expr_out_var.name, None) + typemap[expr_out_var.name] = el_typ + return out_ir + + +def _gen_np_divide(arg1, arg2, out_ir, typemap, typingctx): + """generate np.divide() instead of / for array_expr to get numpy error model + like inf for division by zero (test_division_by_zero). + """ + scope = arg1.scope + loc = arg1.loc + # g_np_var = Global(numpy) + g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + typemap[g_np_var.name] = types.misc.Module(numpy) + g_np = ir.Global('np', numpy, loc) + g_np_assign = ir.Assign(g_np, g_np_var, loc) + # attr call: div_attr = getattr(g_np_var, divide) + div_attr_call = ir.Expr.getattr(g_np_var, "divide", loc) + attr_var = ir.Var(scope, mk_unique_var("$div_attr"), loc) + func_var_typ = get_np_ufunc_typ(numpy.divide, typingctx) + typemap[attr_var.name] = func_var_typ + attr_assign = ir.Assign(div_attr_call, attr_var, loc) + # divide call: div_attr(arg1, arg2) + div_call = ir.Expr.call(attr_var, [arg1, arg2], (), loc) + func_typ = func_var_typ.get_call_type( + typingctx, [typemap[arg1.name], typemap[arg2.name]], {}) + out_ir.extend([g_np_assign, attr_assign]) + return func_typ, div_call + + +def _gen_arrayexpr_getitem( + equiv_set, + var, + parfor_index_tuple_var, + all_parfor_indices, + el_typ, + calltypes, + typingctx, + typemap, + init_block, + out_ir): + """if there is implicit dimension broadcast, generate proper access variable + for getitem. For example, if indices are (i1,i2,i3) but shape is (c1,0,c3), + generate a tuple with (i1,0,i3) for access. Another example: for (i1,i2,i3) + and (c1,c2) generate (i2,i3). + """ + loc = var.loc + index_var = parfor_index_tuple_var + var_typ = typemap[var.name] + ndims = typemap[var.name].ndim + num_indices = len(all_parfor_indices) + size_vars = equiv_set.get_shape(var) or [] + size_consts = [equiv_set.get_equiv_const(x) for x in size_vars] + # Handle array-scalar + if ndims == 0: + # call np.ravel + ravel_var = ir.Var(var.scope, mk_unique_var("$ravel"), loc) + ravel_typ = types.npytypes.Array(dtype=var_typ.dtype, ndim=1, layout='C') + typemap[ravel_var.name] = ravel_typ + stmts = ir_utils.gen_np_call('ravel', numpy.ravel, ravel_var, [var], typingctx, typemap, calltypes) + init_block.body.extend(stmts) + var = ravel_var + # Const(0) + const_node = ir.Const(0, var.loc) + const_var = ir.Var(var.scope, mk_unique_var("$const_ind_0"), loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + out_ir.append(const_assign) + index_var = const_var + # Handle 1d array + elif ndims == 1: + # Use last index for 1D arrays + index_var = all_parfor_indices[-1] + # Handle known constant size + elif any([x is not None for x in size_consts]): + # Need a tuple as index + ind_offset = num_indices - ndims + tuple_var = ir.Var(var.scope, mk_unique_var( + "$parfor_index_tuple_var_bcast"), loc) + typemap[tuple_var.name] = types.containers.UniTuple(types.uintp, ndims) + # Just in case, const var for size 1 dim access index: $const0 = + # Const(0) + const_node = ir.Const(0, var.loc) + const_var = ir.Var(var.scope, mk_unique_var("$const_ind_0"), loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + out_ir.append(const_assign) + index_vars = [] + for i in reversed(range(ndims)): + size_var = size_vars[i] + size_const = size_consts[i] + if size_const == 1: + index_vars.append(const_var) + else: + index_vars.append(all_parfor_indices[ind_offset + i]) + index_vars = list(reversed(index_vars)) + tuple_call = ir.Expr.build_tuple(index_vars, loc) + tuple_assign = ir.Assign(tuple_call, tuple_var, loc) + out_ir.append(tuple_assign) + index_var = tuple_var + + ir_expr = ir.Expr.getitem(var, index_var, loc) + calltypes[ir_expr] = signature(el_typ, typemap[var.name], + typemap[index_var.name]) + return ir_expr + + +def _find_func_var(typemap, func, avail_vars, loc): + """find variable in typemap which represents the function func. + """ + for v in avail_vars: + t = typemap[v] + # Function types store actual functions in typing_key. + if isinstance(t, Function) and t.typing_key == func: + return v + raise errors.UnsupportedRewriteError("ufunc call variable not found", loc=loc) + + +def lower_parfor_sequential(typingctx, func_ir, typemap, calltypes, metadata): + ir_utils._the_max_label.update(ir_utils.find_max_label(func_ir.blocks)) + parfor_found = False + new_blocks = {} + scope = next(iter(func_ir.blocks.values())).scope + for (block_label, block) in func_ir.blocks.items(): + block_label, parfor_found = _lower_parfor_sequential_block( + block_label, block, new_blocks, typemap, calltypes, parfor_found, + scope=scope) + # old block stays either way + new_blocks[block_label] = block + func_ir.blocks = new_blocks + # rename only if parfor found and replaced (avoid test_flow_control error) + if parfor_found: + func_ir.blocks = rename_labels(func_ir.blocks) + dprint_func_ir(func_ir, "after parfor sequential lowering") + simplify(func_ir, typemap, calltypes, metadata["parfors"]) + dprint_func_ir(func_ir, "after parfor sequential simplify") + + +def _lower_parfor_sequential_block( + block_label, + block, + new_blocks, + typemap, + calltypes, + parfor_found, + scope): + i = _find_first_parfor(block.body) + while i != -1: + parfor_found = True + inst = block.body[i] + loc = inst.init_block.loc + # split block across parfor + prev_block = ir.Block(scope, loc) + prev_block.body = block.body[:i] + block.body = block.body[i + 1:] + # previous block jump to parfor init block + init_label = next_label() + prev_block.body.append(ir.Jump(init_label, loc)) + new_blocks[init_label] = transfer_scope(inst.init_block, scope) + new_blocks[block_label] = prev_block + block_label = next_label() + + ndims = len(inst.loop_nests) + for i in range(ndims): + loopnest = inst.loop_nests[i] + # create range block for loop + range_label = next_label() + header_label = next_label() + range_block = mk_range_block( + typemap, + loopnest.start, + loopnest.stop, + loopnest.step, + calltypes, + scope, + loc) + range_block.body[-1].target = header_label # fix jump target + phi_var = range_block.body[-2].target + new_blocks[range_label] = range_block + header_block = mk_loop_header(typemap, phi_var, calltypes, + scope, loc) + header_block.body[-2].target = loopnest.index_variable + new_blocks[header_label] = header_block + # jump to this new inner loop + if i == 0: + inst.init_block.body.append(ir.Jump(range_label, loc)) + header_block.body[-1].falsebr = block_label + else: + new_blocks[prev_header_label].body[-1].truebr = range_label + header_block.body[-1].falsebr = prev_header_label + prev_header_label = header_label # to set truebr next loop + + # last body block jump to inner most header + body_last_label = max(inst.loop_body.keys()) + inst.loop_body[body_last_label].body.append( + ir.Jump(header_label, loc)) + # inner most header jumps to first body block + body_first_label = min(inst.loop_body.keys()) + header_block.body[-1].truebr = body_first_label + # add parfor body to blocks + for (l, b) in inst.loop_body.items(): + l, parfor_found = _lower_parfor_sequential_block( + l, b, new_blocks, typemap, calltypes, parfor_found, + scope=scope) + new_blocks[l] = transfer_scope(b, scope) + i = _find_first_parfor(block.body) + return block_label, parfor_found + + +def _find_first_parfor(body): + for (i, inst) in enumerate(body): + if isinstance(inst, Parfor) and not inst.no_sequential_lowering: + return i + return -1 + + +def get_parfor_params(blocks, options_fusion, fusion_info): + """find variables used in body of parfors from outside and save them. + computed as live variables at entry of first block. + """ + + # since parfor wrap creates a back-edge to first non-init basic block, + # live_map[first_non_init_block] contains variables defined in parfor body + # that could be undefined before. So we only consider variables that are + # actually defined before the parfor body in the program. + parfor_ids = set() + parfors = [] + pre_defs = set() + _, all_defs = compute_use_defs(blocks) + topo_order = find_topo_order(blocks) + for label in topo_order: + block = blocks[label] + for i, parfor in _find_parfors(block.body): + # find variable defs before the parfor in the same block + dummy_block = ir.Block(block.scope, block.loc) + dummy_block.body = block.body[:i] + before_defs = compute_use_defs({0: dummy_block}).defmap[0] + pre_defs |= before_defs + params = get_parfor_params_inner( + parfor, pre_defs, options_fusion, fusion_info, + ) + parfor.params, parfor.races = _combine_params_races_for_ssa_names( + block.scope, params, parfor.races, + ) + parfor_ids.add(parfor.id) + parfors.append(parfor) + + pre_defs |= all_defs[label] + return parfor_ids, parfors + + +def _combine_params_races_for_ssa_names(scope, params, races): + """Returns `(params|races1, races1)`, where `races1` contains all variables + in `races` are NOT referring to the same unversioned (SSA) variables in + `params`. + """ + def unversion(k): + try: + return scope.get_exact(k).unversioned_name + except ir.NotDefinedError: + # XXX: it's a bug that something references an undefined name + return k + + races1 = set(races) + unver_params = list(map(unversion, params)) + + for rv in races: + if any(unversion(rv) == pv for pv in unver_params): + races1.discard(rv) + else: + break + + return params | races1, races1 + + +def get_parfor_params_inner(parfor, pre_defs, options_fusion, fusion_info): + blocks = wrap_parfor_blocks(parfor) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + parfor_ids, _ = get_parfor_params(blocks, options_fusion, fusion_info) + n_parfors = len(parfor_ids) + if n_parfors > 0: + if config.DEBUG_ARRAY_OPT_STATS: + after_fusion = ("After fusion" if options_fusion + else "With fusion disabled") + print(('{}, parallel for-loop {} has ' + 'nested Parfor(s) #{}.').format( + after_fusion, parfor.id, n_parfors, parfor_ids)) + fusion_info[parfor.id] = list(parfor_ids) + + unwrap_parfor_blocks(parfor) + keylist = sorted(live_map.keys()) + init_block = keylist[0] + first_non_init_block = keylist[1] + + before_defs = usedefs.defmap[init_block] | pre_defs + params = live_map[first_non_init_block] & before_defs + return params + + +def _find_parfors(body): + for i, inst in enumerate(body): + if isinstance(inst, Parfor): + yield i, inst + + +def _is_indirect_index(func_ir, index, nest_indices): + index_def = guard(get_definition, func_ir, index.name) + if isinstance(index_def, ir.Expr) and index_def.op == 'build_tuple': + if [x.name for x in index_def.items] == [x.name for x in nest_indices]: + return True + + return False + + +def get_array_indexed_with_parfor_index_internal(loop_body, + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir): + for blk in loop_body: + for stmt in blk.body: + if isinstance(stmt, (ir.StaticSetItem, ir.SetItem)): + setarray_index = get_index_var(stmt) + if (isinstance(setarray_index, ir.Var) and + (setarray_index.name == index or + _is_indirect_index( + func_ir, + setarray_index, + nest_indices))): + ret_indexed.add(stmt.target.name) + else: + ret_not_indexed.add(stmt.target.name) + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Expr) and + stmt.value.op in ['getitem', 'static_getitem']): + getarray_index = stmt.value.index + getarray_name = stmt.value.value.name + if (isinstance(getarray_index, ir.Var) and + (getarray_index.name == index or + _is_indirect_index( + func_ir, + getarray_index, + nest_indices))): + ret_indexed.add(getarray_name) + else: + ret_not_indexed.add(getarray_name) + elif isinstance(stmt, Parfor): + get_array_indexed_with_parfor_index_internal( + stmt.loop_body.values(), + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir) + + +def get_array_indexed_with_parfor_index(loop_body, + index, + nest_indices, + func_ir): + ret_indexed = set() + ret_not_indexed = set() + get_array_indexed_with_parfor_index_internal( + loop_body, + index, + ret_indexed, + ret_not_indexed, + nest_indices, + func_ir) + return ret_indexed, ret_not_indexed + + +def get_parfor_outputs(parfor, parfor_params): + """get arrays that are written to inside the parfor and need to be passed + as parameters to gufunc. + """ + # FIXME: The following assumes the target of all SetItem are outputs, + # which is wrong! + last_label = max(parfor.loop_body.keys()) + outputs = [] + for blk in parfor.loop_body.values(): + for stmt in blk.body: + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == parfor.index_var.name): + outputs.append(stmt.target.name) + # make sure these written arrays are in parfor parameters (live coming in) + outputs = list(set(outputs) & set(parfor_params)) + return sorted(outputs) + + +_RedVarInfo = make_dataclass( + "_RedVarInfo", + ["init_val", "reduce_nodes", "redop"], + frozen=True, +) + + +def get_parfor_reductions(func_ir, parfor, parfor_params, calltypes, reductions=None, + reduce_varnames=None, param_uses=None, param_nodes=None, + var_to_param=None): + """find variables that are updated using their previous values and an array + item accessed with parfor index, e.g. s = s+A[i] + """ + if reductions is None: + reductions = {} + if reduce_varnames is None: + reduce_varnames = [] + + # for each param variable, find what other variables are used to update it + # also, keep the related nodes + if param_uses is None: + param_uses = defaultdict(list) + if param_nodes is None: + param_nodes = defaultdict(list) + if var_to_param is None: + var_to_param = {} + + blocks = wrap_parfor_blocks(parfor) + topo_order = find_topo_order(blocks) + topo_order = topo_order[1:] # ignore init block + unwrap_parfor_blocks(parfor) + + for label in reversed(topo_order): + for stmt in reversed(parfor.loop_body[label].body): + if (isinstance(stmt, ir.Assign) + and (stmt.target.name in parfor_params + or stmt.target.name in var_to_param)): + lhs = stmt.target + rhs = stmt.value + cur_param = lhs if lhs.name in parfor_params else var_to_param[lhs.name] + used_vars = [] + if isinstance(rhs, ir.Var): + used_vars = [rhs.name] + elif isinstance(rhs, ir.Expr): + used_vars = [v.name for v in stmt.value.list_vars()] + param_uses[cur_param].extend(used_vars) + for v in used_vars: + var_to_param[v] = cur_param + # save copy of dependent stmt + stmt_cp = copy.deepcopy(stmt) + if stmt.value in calltypes: + calltypes[stmt_cp.value] = calltypes[stmt.value] + param_nodes[cur_param].append(stmt_cp) + if isinstance(stmt, Parfor): + # recursive parfors can have reductions like test_prange8 + get_parfor_reductions(func_ir, stmt, parfor_params, calltypes, + reductions, reduce_varnames, None, param_nodes, var_to_param) + + for param, used_vars in param_uses.items(): + # a parameter is a reduction variable if its value is used to update it + # check reduce_varnames since recursive parfors might have processed + # param already + param_name = param.name + if param_name in used_vars and param_name not in reduce_varnames: + param_nodes[param].reverse() + reduce_nodes = get_reduce_nodes(param, param_nodes[param], func_ir) + # Certain kinds of ill-formed Python (like potentially undefined + # variables) in combination with SSA can make things look like + # reductions except that they don't have reduction operators. + # If we get to this point but don't find a reduction operator + # then assume it is this situation and just don't treat this + # variable as a reduction. + if reduce_nodes is not None: + reduce_varnames.append(param_name) + check_conflicting_reduction_operators(param, reduce_nodes) + gri_out = guard(get_reduction_init, reduce_nodes) + if gri_out is not None: + init_val, redop = gri_out + else: + init_val = None + redop = None + reductions[param_name] = _RedVarInfo( + init_val=init_val, + reduce_nodes=reduce_nodes, + redop=redop, + ) + + return reduce_varnames, reductions + +def check_conflicting_reduction_operators(param, nodes): + """In prange, a user could theoretically specify conflicting + reduction operators. For example, in one spot it is += and + another spot *=. Here, we raise an exception if multiple + different reduction operators are used in one prange. + """ + first_red_func = None + for node in nodes: + if (isinstance(node, ir.Assign) and + isinstance(node.value, ir.Expr) and + node.value.op=='inplace_binop'): + if first_red_func is None: + first_red_func = node.value.fn + else: + if first_red_func != node.value.fn: + msg = ("Reduction variable %s has multiple conflicting " + "reduction operators." % param.unversioned_name) + raise errors.UnsupportedRewriteError(msg, node.loc) + +def get_reduction_init(nodes): + """ + Get initial value for known reductions. + Currently, only += and *= are supported. + """ + require(len(nodes) >= 1) + # there could be multiple extra assignments after the reduce node + # See: test_reduction_var_reuse + acc_expr = list(filter(lambda x: isinstance(x.value, ir.Expr), nodes))[-1].value + require(isinstance(acc_expr, ir.Expr) and acc_expr.op in ['inplace_binop', 'binop']) + acc_expr_fn = acc_expr.fn + if acc_expr.op == 'binop': + if acc_expr_fn == operator.add: + acc_expr_fn = operator.iadd + elif acc_expr_fn == operator.sub: + acc_expr_fn = operator.isub + elif acc_expr_fn == operator.mul: + acc_expr_fn = operator.imul + elif acc_expr_fn == operator.truediv: + acc_expr_fn = operator.itruediv + if acc_expr_fn == operator.iadd or acc_expr_fn == operator.isub: + return 0, acc_expr_fn + if ( acc_expr_fn == operator.imul + or acc_expr_fn == operator.itruediv ): + return 1, acc_expr_fn + return None, None + +def supported_reduction(x, func_ir): + if x.op == 'inplace_binop' or x.op == 'binop': + if x.fn == operator.ifloordiv or x.fn == operator.floordiv: + raise errors.NumbaValueError(("Parallel floordiv reductions are not supported. " + "If all divisors are integers then a floordiv " + "reduction can in some cases be parallelized as " + "a multiply reduction followed by a floordiv of " + "the resulting product."), x.loc) + supps = [operator.iadd, + operator.isub, + operator.imul, + operator.itruediv, + operator.add, + operator.sub, + operator.mul, + operator.truediv] + return x.fn in supps + if x.op == 'call': + callname = guard(find_callname, func_ir, x) + if callname in [ + ('max', 'builtins'), + ('min', 'builtins'), + ('datetime_minimum', 'numba.np.npdatetime_helpers'), + ('datetime_maximum', 'numba.np.npdatetime_helpers'), + ]: + return True + return False + +def get_reduce_nodes(reduction_node, nodes, func_ir): + """ + Get nodes that combine the reduction variable with a sentinel variable. + Recognizes the first node that combines the reduction variable with another + variable. + """ + reduce_nodes = None + defs = {} + + def cyclic_lookup(var, varonly=True, start=None): + """Lookup definition of ``var``. + Returns ``None`` if variable definition forms a cycle. + """ + lookedup_var = defs.get(var.name, None) + if isinstance(lookedup_var, ir.Var): + if start is None: + start = lookedup_var + elif start == lookedup_var: + # cycle detected + return None + return cyclic_lookup(lookedup_var, start=start) + else: + return var if (varonly or lookedup_var is None) else lookedup_var + + def noncyclic_lookup(*args, **kwargs): + """Similar to cyclic_lookup but raise AssertionError if a cycle is + detected. + """ + res = cyclic_lookup(*args, **kwargs) + if res is None: + raise AssertionError("unexpected cycle in lookup()") + return res + + name = reduction_node.name + unversioned_name = reduction_node.unversioned_name + for i, stmt in enumerate(nodes): + lhs = stmt.target + rhs = stmt.value + defs[lhs.name] = rhs + if isinstance(rhs, ir.Var) and rhs.name in defs: + rhs = cyclic_lookup(rhs) + if isinstance(rhs, ir.Expr): + in_vars = set(noncyclic_lookup(v, True).name + for v in rhs.list_vars()) + if name in in_vars: + # reductions like sum have an assignment afterwards + # e.g. $2 = a + $1; a = $2 + # reductions that are functions calls like max() don't have an + # extra assignment afterwards + + # This code was created when Numba had an IR generation strategy + # where a binop for a reduction would be followed by an + # assignment as follows: + #$c.4.15 = inplace_binop(fn=, ...>, lhs=c.3, rhs=$const20) + #c.4 = $c.4.15 + + # With Python 3.12 changes, Numba may separate that assignment + # to a new basic block. The code below looks and sees if an + # assignment to the reduction var follows the reduction operator + # and if not it searches the rest of the reduction nodes to find + # the assignment that should follow the reduction operator + # and then reorders the reduction nodes so that assignment + # follows the reduction operator. + if (i + 1 < len(nodes) and + ((not isinstance(nodes[i + 1], ir.Assign)) or + nodes[i + 1].target.unversioned_name != unversioned_name)): + foundj = None + # Iterate through the rest of the reduction nodes. + for j, jstmt in enumerate(nodes[i + 1:]): + # If this stmt is an assignment where the right-hand + # side of the assignment is the output of the reduction + # operator. + if isinstance(jstmt, ir.Assign) and jstmt.value == lhs: + # Remember the index of this node. Because of + # nodes[i+1] above, we have to add i + 1 to j below + # to get the index in the original nodes list. + foundj = i + j + 1 + break + if foundj is not None: + # If we found the correct assignment then move it to + # after the reduction operator. + nodes = (nodes[:i + 1] + # nodes up to operator + nodes[foundj:foundj + 1] + # assignment node + nodes[i + 1:foundj] + # between op and assign + nodes[foundj + 1:]) # after assignment node + + if (not (i+1 < len(nodes) and isinstance(nodes[i+1], ir.Assign) + and nodes[i+1].target.unversioned_name == unversioned_name) + and lhs.unversioned_name != unversioned_name): + raise ValueError( + f"Use of reduction variable {unversioned_name!r} other " + "than in a supported reduction function is not " + "permitted." + ) + + if not supported_reduction(rhs, func_ir): + raise ValueError(("Use of reduction variable " + unversioned_name + + " in an unsupported reduction function.")) + args = [(x.name, noncyclic_lookup(x, True)) + for x in get_expr_args(rhs) ] + non_red_args = [ x for (x, y) in args if y.name != name ] + assert len(non_red_args) == 1 + args = [ (x, y) for (x, y) in args if x != y.name ] + replace_dict = dict(args) + replace_dict[non_red_args[0]] = ir.Var(lhs.scope, name+"#init", lhs.loc) + replace_vars_inner(rhs, replace_dict) + reduce_nodes = nodes[i:] + break + return reduce_nodes + +def get_expr_args(expr): + """ + Get arguments of an expression node + """ + if expr.op in ['binop', 'inplace_binop']: + return [expr.lhs, expr.rhs] + if expr.op == 'call': + return [v for v in expr.args] + raise NotImplementedError("get arguments for expression {}".format(expr)) + +def visit_parfor_pattern_vars(parfor, callback, cbdata): + # currently, only stencil pattern has variables + for pattern in parfor.patterns: + if pattern[0] == 'stencil': + left_lengths = pattern[1][0] + for i in range(len(left_lengths)): + if isinstance(left_lengths[i], ir.Var): + left_lengths[i] = visit_vars_inner(left_lengths[i], + callback, cbdata) + right_lengths = pattern[1][1] + for i in range(len(right_lengths)): + if isinstance(right_lengths[i], ir.Var): + right_lengths[i] = visit_vars_inner(right_lengths[i], + callback, cbdata) + +def visit_vars_parfor(parfor, callback, cbdata): + if config.DEBUG_ARRAY_OPT >= 1: + print("visiting parfor vars for:", parfor) + print("cbdata: ", sorted(cbdata.items())) + for l in parfor.loop_nests: + l.index_variable = visit_vars_inner(l.index_variable, callback, cbdata) + if isinstance(l.start, ir.Var): + l.start = visit_vars_inner(l.start, callback, cbdata) + if isinstance(l.stop, ir.Var): + l.stop = visit_vars_inner(l.stop, callback, cbdata) + if isinstance(l.step, ir.Var): + l.step = visit_vars_inner(l.step, callback, cbdata) + visit_vars({-1: parfor.init_block}, callback, cbdata) + visit_parfor_pattern_vars(parfor, callback, cbdata) + visit_vars(parfor.loop_body, callback, cbdata) + return + + +# add call to visit parfor variable +ir_utils.visit_vars_extensions[Parfor] = visit_vars_parfor + + +def parfor_defs(parfor, use_set=None, def_set=None): + """list variables written in this parfor by recursively + calling compute_use_defs() on body and combining block defs. + """ + if use_set is None: + use_set = set() + if def_set is None: + def_set = set() + blocks = wrap_parfor_blocks(parfor) + uses, defs = compute_use_defs(blocks) + cfg = compute_cfg_from_blocks(blocks) + last_label = max(blocks.keys()) + unwrap_parfor_blocks(parfor) + + # Conservatively, only add defs for blocks that are definitely executed + # Go through blocks in order, as if they are statements of the block that + # includes the parfor, and update uses/defs. + + # no need for topo order of ir_utils + topo_order = cfg.topo_order() + # blocks that dominate last block are definitely executed + definitely_executed = cfg.dominators()[last_label] + # except loop bodies that might not execute + for loop in cfg.loops().values(): + definitely_executed -= loop.body + for label in topo_order: + if label in definitely_executed: + # see compute_use_defs() in analysis.py + # variables defined in the block that includes the parfor are not + # uses of that block (are not potentially live in the beginning of + # the block) + use_set.update(uses[label] - def_set) + def_set.update(defs[label]) + else: + use_set.update(uses[label] - def_set) + + # treat loop variables and size variables as use + loop_vars = { + l.start.name for l in parfor.loop_nests if isinstance( + l.start, ir.Var)} + loop_vars |= { + l.stop.name for l in parfor.loop_nests if isinstance( + l.stop, ir.Var)} + loop_vars |= { + l.step.name for l in parfor.loop_nests if isinstance( + l.step, ir.Var)} + use_set.update(loop_vars - def_set) + use_set |= get_parfor_pattern_vars(parfor) + + return analysis._use_defs_result(usemap=use_set, defmap=def_set) + + +analysis.ir_extension_usedefs[Parfor] = parfor_defs + + +def _parfor_use_alloca(parfor, alloca_set): + """ + Reduction variables for parfors and the reduction variables within + nested parfors must be stack allocated. + """ + alloca_set |= set(parfor.redvars) + + blocks = wrap_parfor_blocks(parfor) + alloca_set |= analysis.must_use_alloca(blocks) + + unwrap_parfor_blocks(parfor) + + +analysis.ir_extension_use_alloca[Parfor] = _parfor_use_alloca + + +def parfor_insert_dels(parfor, curr_dead_set): + """insert dels in parfor. input: dead variable set right after parfor. + returns the variables for which del was inserted. + """ + blocks = wrap_parfor_blocks(parfor) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + dead_map = compute_dead_maps(cfg, blocks, live_map, usedefs.defmap) + + # treat loop variables and size variables as live + loop_vars = { + l.start.name for l in parfor.loop_nests if isinstance( + l.start, ir.Var)} + loop_vars |= { + l.stop.name for l in parfor.loop_nests if isinstance( + l.stop, ir.Var)} + loop_vars |= { + l.step.name for l in parfor.loop_nests if isinstance( + l.step, ir.Var)} + loop_vars |= {l.index_variable.name for l in parfor.loop_nests} + # for var_list in parfor.array_analysis.array_size_vars.values(): + # loop_vars |= {v.name for v in var_list if isinstance(v, ir.Var)} + + dead_set = set() + for label in blocks.keys(): + # only kill vars that are actually dead at the parfor's block + dead_map.internal[label] &= curr_dead_set + dead_map.internal[label] -= loop_vars + dead_set |= dead_map.internal[label] + dead_map.escaping[label] &= curr_dead_set + dead_map.escaping[label] -= loop_vars + dead_set |= dead_map.escaping[label] + + # dummy class to replace func_ir. _patch_var_dels only accesses blocks + class DummyFuncIR(object): + + def __init__(self, blocks): + self.blocks = blocks + post_proc = postproc.PostProcessor(DummyFuncIR(blocks)) + post_proc._patch_var_dels(dead_map.internal, dead_map.escaping) + unwrap_parfor_blocks(parfor) + + return dead_set | loop_vars + + +postproc.ir_extension_insert_dels[Parfor] = parfor_insert_dels + + +def maximize_fusion(func_ir, blocks, typemap, up_direction=True): + """ + Reorder statements to maximize parfor fusion. Push all parfors up or down + so they are adjacent. + """ + call_table, _ = get_call_table(blocks) + alias_map, arg_aliases = find_potential_aliases( + blocks, + func_ir.arg_names, + typemap, + func_ir + ) + for block in blocks.values(): + order_changed = True + while order_changed: + order_changed = maximize_fusion_inner( + func_ir, + block, + call_table, + alias_map, + arg_aliases, + up_direction + ) + +def maximize_fusion_inner(func_ir, block, call_table, alias_map, + arg_aliases, up_direction=True): + order_changed = False + i = 0 + # i goes to body[-3] (i+1 to body[-2]) since body[-1] is terminator and + # shouldn't be reordered + while i < len(block.body) - 2: + stmt = block.body[i] + next_stmt = block.body[i+1] + can_reorder = (_can_reorder_stmts(stmt, next_stmt, func_ir, + call_table, alias_map, arg_aliases) + if up_direction else _can_reorder_stmts(next_stmt, stmt, + func_ir, call_table, alias_map, arg_aliases)) + if can_reorder: + block.body[i] = next_stmt + block.body[i+1] = stmt + order_changed = True + i += 1 + return order_changed + +def expand_aliases(the_set, alias_map, arg_aliases): + ret = set() + for i in the_set: + if i in alias_map: + ret = ret.union(alias_map[i]) + if i in arg_aliases: + ret = ret.union(arg_aliases) + ret.add(i) + return ret + +def _can_reorder_stmts(stmt, next_stmt, func_ir, call_table, + alias_map, arg_aliases): + """ + Check dependencies to determine if a parfor can be reordered in the IR block + with a non-parfor statement. + """ + # swap only parfors with non-parfors + # don't reorder calls with side effects (e.g. file close) + # only read-read dependencies are OK + # make sure there is no write-write, write-read dependencies + if (isinstance(stmt, Parfor) + and not isinstance(next_stmt, Parfor) + and not isinstance(next_stmt, ir.Print) + and (not isinstance(next_stmt, ir.Assign) + or has_no_side_effect(next_stmt.value, set(), call_table) + or guard(is_assert_equiv, func_ir, next_stmt.value))): + stmt_accesses = expand_aliases({v.name for v in stmt.list_vars()}, + alias_map, arg_aliases) + stmt_writes = expand_aliases(get_parfor_writes(stmt), + alias_map, arg_aliases) + next_accesses = expand_aliases({v.name for v in next_stmt.list_vars()}, + alias_map, arg_aliases) + next_writes = expand_aliases(get_stmt_writes(next_stmt), + alias_map, arg_aliases) + if len((stmt_writes & next_accesses) + | (next_writes & stmt_accesses)) == 0: + return True + return False + +def is_assert_equiv(func_ir, expr): + func_name, mod_name = find_callname(func_ir, expr) + return func_name == 'assert_equiv' + + +def get_parfor_writes(parfor): + assert isinstance(parfor, Parfor) + writes = set() + blocks = parfor.loop_body.copy() + blocks[-1] = parfor.init_block + for block in blocks.values(): + for stmt in block.body: + writes.update(get_stmt_writes(stmt)) + if isinstance(stmt, Parfor): + writes.update(get_parfor_writes(stmt)) + return writes + +FusionReport = namedtuple('FusionReport', ['first', 'second', 'message']) + +def try_fuse(equiv_set, parfor1, parfor2, metadata, func_ir, typemap): + """try to fuse parfors and return a fused parfor, otherwise return None + """ + dprint("try_fuse: trying to fuse \n", parfor1, "\n", parfor2) + + # default report is None + report = None + + # fusion of parfors with different lowerers is not possible + if parfor1.lowerer != parfor2.lowerer: + dprint("try_fuse: parfors different lowerers") + msg = "- fusion failed: lowerer mismatch" + report = FusionReport(parfor1.id, parfor2.id, msg) + return None, report + + # fusion of parfors with different dimensions not supported yet + if len(parfor1.loop_nests) != len(parfor2.loop_nests): + dprint("try_fuse: parfors number of dimensions mismatch") + msg = "- fusion failed: number of loops mismatched, %s, %s." + fmt = "parallel loop #%s has a nest of %s loops" + l1 = fmt % (parfor1.id, len(parfor1.loop_nests)) + l2 = fmt % (parfor2.id, len(parfor2.loop_nests)) + report = FusionReport(parfor1.id, parfor2.id, msg % (l1, l2)) + return None, report + + ndims = len(parfor1.loop_nests) + # all loops should be equal length + + def is_equiv(x, y): + return x == y or equiv_set.is_equiv(x, y) + + def get_user_varname(v): + """get original variable name by user if possible""" + if not isinstance(v, ir.Var): + return v + v = v.name + if "var_rename_map" in metadata and v in metadata["var_rename_map"]: + user_varname = metadata["var_rename_map"][v] + return user_varname + return v + + for i in range(ndims): + nest1 = parfor1.loop_nests[i] + nest2 = parfor2.loop_nests[i] + if not (is_equiv(nest1.start, nest2.start) and + is_equiv(nest1.stop, nest2.stop) and + is_equiv(nest1.step, nest2.step)): + dprint("try_fuse: parfor dimension correlation mismatch", i) + msg = "- fusion failed: loop dimension mismatched in axis %s. " + msg += "slice(%s, %s, %s) != " % (get_user_varname(nest1.start), + get_user_varname(nest1.stop), get_user_varname(nest1.step)) + msg += "slice(%s, %s, %s)" % (get_user_varname(nest2.start), + get_user_varname(nest2.stop), get_user_varname(nest2.step)) + report = FusionReport(parfor1.id, parfor2.id, msg % i) + return None, report + + func_ir._definitions = build_definitions(func_ir.blocks) + p1_cross_dep, p1_ip, p1_ia, p1_non_ia = has_cross_iter_dep(parfor1, func_ir, typemap) + if not p1_cross_dep: + p2_cross_dep = has_cross_iter_dep(parfor2, func_ir, typemap, p1_ip, p1_ia, p1_non_ia)[0] + else: + p2_cross_dep = True + + if p1_cross_dep or p2_cross_dep: + dprint("try_fuse: parfor cross iteration dependency found") + msg = ("- fusion failed: cross iteration dependency found " + "between loops #%s and #%s") + report = FusionReport(parfor1.id, parfor2.id, + msg % (parfor1.id, parfor2.id)) + return None, report + + + # find parfor1's defs, only body is considered since init_block will run + # first after fusion as well + p1_body_usedefs = compute_use_defs(parfor1.loop_body) + p1_body_defs = set() + for defs in p1_body_usedefs.defmap.values(): + p1_body_defs |= defs + p1_body_defs |= get_parfor_writes(parfor1) + # Add reduction variables from parfor1 to the set of body defs + # so that if parfor2 reads the reduction variable it won't fuse. + p1_body_defs |= set(parfor1.redvars) + + p2_usedefs = compute_use_defs(parfor2.loop_body) + p2_uses = compute_use_defs({0: parfor2.init_block}).usemap[0] + for uses in p2_usedefs.usemap.values(): + p2_uses |= uses + + overlap = p1_body_defs.intersection(p2_uses) + # overlap are those variable defined in first parfor and used in the second + if len(overlap) != 0: + # Get all the arrays + _, p2arraynotindexed = get_array_indexed_with_parfor_index( + parfor2.loop_body.values(), + parfor2.index_var.name, + parfor2.get_loop_nest_vars(), + func_ir) + + unsafe_var = (not isinstance(typemap[x], types.ArrayCompatible) or x in p2arraynotindexed for x in overlap) + + if any(unsafe_var): + dprint("try_fuse: parfor2 depends on parfor1 body") + msg = ("- fusion failed: parallel loop %s has a dependency on the " + "body of parallel loop %s. ") + report = FusionReport(parfor1.id, parfor2.id, + msg % (parfor1.id, parfor2.id)) + return None, report + + return fuse_parfors_inner(parfor1, parfor2) + + +def fuse_parfors_inner(parfor1, parfor2): + # fuse parfor2 into parfor1 + # append parfor2's init block on parfor1's + parfor1.init_block.body.extend(parfor2.init_block.body) + + # append parfor2's first block to parfor1's last block + parfor2_first_label = min(parfor2.loop_body.keys()) + parfor2_first_block = parfor2.loop_body[parfor2_first_label].body + parfor1_first_label = min(parfor1.loop_body.keys()) + parfor1_last_label = max(parfor1.loop_body.keys()) + parfor1.loop_body[parfor1_last_label].body.extend(parfor2_first_block) + + # add parfor2 body blocks to parfor1's except first + parfor1.loop_body.update(parfor2.loop_body) + parfor1.loop_body.pop(parfor2_first_label) + + # replace parfor2 indices with parfor1's + ndims = len(parfor1.loop_nests) + index_dict = {parfor2.index_var.name: parfor1.index_var} + for i in range(ndims): + index_dict[parfor2.loop_nests[i].index_variable.name] = parfor1.loop_nests[ + i].index_variable + replace_vars(parfor1.loop_body, index_dict) + + # re-order labels from min to max + blocks = wrap_parfor_blocks(parfor1, entry_label=parfor1_first_label) + blocks = rename_labels(blocks) + unwrap_parfor_blocks(parfor1, blocks) + + nameset = set(x.name for x in index_dict.values()) + remove_duplicate_definitions(parfor1.loop_body, nameset) + parfor1.patterns.extend(parfor2.patterns) + if config.DEBUG_ARRAY_OPT_STATS: + print('Parallel for-loop #{} is fused into for-loop #{}.'.format( + parfor2.id, parfor1.id)) + + msg = '- fusion succeeded: parallel for-loop #{} is fused into for-loop #{}.' + msg = msg.format(parfor2.id, parfor1.id) + report = FusionReport(parfor1.id, parfor2.id, msg) + + return parfor1, report + + +def remove_duplicate_definitions(blocks, nameset): + """Remove duplicated definition for variables in the given nameset, which + is often a result of parfor fusion. + """ + for label, block in blocks.items(): + body = block.body + new_body = [] + defined = set() + for inst in body: + if isinstance(inst, ir.Assign): + name = inst.target.name + if name in nameset: + if name in defined: + continue + defined.add(name) + new_body.append(inst) + block.body = new_body + return + + +def has_cross_iter_dep( + parfor, + func_ir, + typemap, + index_positions=None, + indexed_arrays=None, + non_indexed_arrays=None): + # We should assume there is cross iteration dependency unless we can + # prove otherwise. Return True if there is a cross-iter dependency + # that should prevent fusion, False if fusion is okay. + # Also returns index_positions, indexed_arrays, and non_indexed_arrays + # who purpose is described below so that subsequent additional + # has_cross_iter_dep calls for other parfors can build on the same + # data structures to make sure that the array accesses generate no + # cross-iter dependencies both within a parfor but also across parfors. + + # TODO: make it more accurate using ud-chains + + # Get the index variable used by this parfor. + # This will hold other variables with equivalent value, e.g., a = index_var + indices = {l.index_variable.name for l in parfor.loop_nests} + # This set will store variables that are (potentially recursively) + # defined in relation to an index variable, e.g., a = index_var + 1. + # A getitem that uses an index variable from this set will be considered + # as potentially having a cross-iter dependency and so won't fuse. + derived_from_indices = set() + # For the first parfor considered for fusion, the latter 3 args will be None + # and initialized to empty. For the second parfor, the structures from the + # previous parfor are passed in so that cross-parfor violations of the + # below comments can prevent fusion. + # + # index_positions keeps track of which index positions have had an index + # variable used for them and which ones haven't for each possible array + # dimensionality. After the first array access is seen, if subsequent + # ones use a parfor index for a different dimension then we conservatively + # say that we can't fuse. For example, if a 2D array is accessed with + # a[parfor_index, 0] then index_positions[2] will be (True, False) and + # if a[0, parfor_index] happens later which is (False, True) then this + # conflicts with the previous value and will prevent fusion. + # + # indexed_arrays records arrays that are accessed with at least one + # parfor index. If such an array is later accessed with indices that + # don't include a parfor index then conservatively assume we can't fuse. + # + # non_indexed_arrays holds arrays that are indexed without a parfor index. + # If an array first accessed without a parfor index is later indexed + # with one then conservatively assume we can't fuse. + if index_positions is None: + index_positions = {} + if indexed_arrays is None: + indexed_arrays = set() + if non_indexed_arrays is None: + non_indexed_arrays = set() + + def add_check_position(new_position, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays): + """Returns True if there is a reason to prevent fusion based + on the rules described above. + new_position will be a list or tuple of booleans that + says whether the index in that spot is a parfor index + or not. array_accessed is the array on which the access + is occurring.""" + + # Convert list indices to tuple for generality. + if isinstance(new_position, list): + new_position = tuple(new_position) + + # If none of the indices are based on a parfor index. + if True not in new_position: + # See if this array has been accessed before with a + # a parfor index and if so say that we can't fuse. + if array_accessed in indexed_arrays: + return True + else: + # Either array is already in non_indexed arrays or we + # will add it. Either way, this index usage can fuse. + non_indexed_arrays.add(array_accessed) + return False + + # Fallthrough for cases where one of the indices is a parfor index. + # If this array was previously accessed without a parfor index then + # conservatively say we can't fuse. + if array_accessed in non_indexed_arrays: + return True + + indexed_arrays.add(array_accessed) + + npsize = len(new_position) + # See if we have not seen a npsize dimensioned array accessed before. + if npsize not in index_positions: + # If not then add current set of parfor/non-parfor indices and + # indicate it is safe as it is the first usage. + index_positions[npsize] = new_position + return False + + # Here we have a subsequent access to a npsize-dimensioned array. + # Make sure we see the same combination of parfor/non-parfor index + # indices that we've seen before. If not then return True saying + # that we can't fuse. + return index_positions[npsize] != new_position + + def check_index(stmt_index, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + """Looks at the indices of a getitem or setitem to see if there + is a reason that they would prevent fusion. + Returns True if fusion should be prohibited, False otherwise. + """ + if isinstance(stmt_index, ir.Var): + # If the array is 2+ dimensions then the index should be a tuple. + if isinstance(typemap[stmt_index.name], types.BaseTuple): + # Get how the index tuple is constructed. + fbs_res = guard(find_build_sequence, func_ir, stmt_index) + if fbs_res is not None: + ind_seq, _ = fbs_res + # If any indices are derived from an index is used then + # return True to say we can't fuse. + if (all([x.name in indices or + x.name not in derived_from_indices for x in ind_seq])): + # Get position in index tuple where parfor indices used. + new_index_positions = [x.name in indices for x in ind_seq] + # Make sure that we aren't accessing a given array with + # different indices in a different order. + return add_check_position(new_index_positions, + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + else: + # index derived from a parfor index used so no fusion + return True + else: + # Don't know how the index tuple is built so + # have to assume fusion can't happen. + return True + else: + # Should be for 1D arrays. + if stmt_index.name in indices: + # Array indexed by a parfor index variable. + # Make sure this 1D access is consistent with prior ones. + return add_check_position((True,), + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + elif stmt_index.name in derived_from_indices: + # If we ever index an array with something calculated + # from an index then no fusion. + return True + else: + # Some kind of index that isn't a parfor index or + # one derived from one, e.g., a constant. Make sure + # this is consistent with prior accessed of this array. + return add_check_position((False,), + array_accessed, + index_positions, + indexed_arrays, + non_indexed_arrays) + else: + # We don't know how to handle non-Var indices so no fusion. + return True + + # All branches above should cover all the cases and each should + # return so we should never get here. + raise errors.InternalError("Some code path in the parfor fusion " + "cross-iteration dependency checker " + "check_index didn't return a result.") + + # Iterate through all the statements in the parfor. + for b in parfor.loop_body.values(): + for stmt in b.body: + # Make sure SetItem accesses are fusion safe. + if isinstance(stmt, (ir.SetItem, ir.StaticSetItem)): + if isinstance(typemap[stmt.target.name], types.npytypes.Array): + # Check index safety with prior array accesses. + if check_index(stmt.index, + stmt.target.name, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + return True, index_positions, indexed_arrays, non_indexed_arrays + # Fusion safe so go to next statement. + continue + elif isinstance(stmt, ir.Assign): + # If stmt of form a = parfor_index then add "a" to set of + # parfor indices. + if isinstance(stmt.value, ir.Var): + if stmt.value.name in indices: + indices.add(stmt.target.name) + continue + elif isinstance(stmt.value, ir.Expr): + op = stmt.value.op + # Make sure getitem accesses are fusion safe. + if op in ['getitem', 'static_getitem']: + if isinstance(typemap[stmt.value.value.name], types.npytypes.Array): + # Check index safety with prior array accesses. + if check_index(stmt.value.index, + stmt.value.value.name, + index_positions, + indexed_arrays, + non_indexed_arrays, + derived_from_indices): + return True, index_positions, indexed_arrays, non_indexed_arrays + # Fusion safe so go to next statement. + continue + elif op == 'call': + # If there is a call in the parfor body that takes some + # array parameter then we have no way to analyze what + # that call is doing so presume it is unsafe for fusion. + if (any([isinstance(typemap[x.name], types.npytypes.Array) + for x in stmt.value.list_vars()])): + return True, index_positions, indexed_arrays, non_indexed_arrays + + # Get the vars used by this non-setitem/getitem statement. + rhs_vars = [x.name for x in stmt.value.list_vars()] + # If a parfor index is used as part of this statement or + # something previous determined to be derived from a parfor + # index then add the target variable to the set of + # variables that are derived from parfors and so should + # prevent fusion if used as an index. + if (not indices.isdisjoint(rhs_vars) or + not derived_from_indices.isdisjoint(rhs_vars)): + derived_from_indices.add(stmt.target.name) + + return False, index_positions, indexed_arrays, non_indexed_arrays + + +def dprint(*s): + if config.DEBUG_ARRAY_OPT >= 1: + print(*s) + +def get_parfor_pattern_vars(parfor): + """ get the variables used in parfor pattern information + """ + out = set() + # currently, only stencil pattern has variables + for pattern in parfor.patterns: + if pattern[0] == 'stencil': + left_lengths = pattern[1][0] + right_lengths = pattern[1][1] + for v in left_lengths+right_lengths: + if isinstance(v, ir.Var): + out.add(v.name) + return out + +def remove_dead_parfor(parfor, lives, lives_n_aliases, arg_aliases, alias_map, func_ir, typemap): + """ remove dead code inside parfor including get/sets + """ + + with dummy_return_in_loop_body(parfor.loop_body): + labels = find_topo_order(parfor.loop_body) + + # get/setitem replacement should ideally use dataflow to propagate setitem + # saved values, but for simplicity we handle the common case of propagating + # setitems in the first block (which is dominant) if the array is not + # potentially changed in any way + first_label = labels[0] + first_block_saved_values = {} + _update_parfor_get_setitems( + parfor.loop_body[first_label].body, + parfor.index_var, alias_map, + first_block_saved_values, + lives_n_aliases + ) + + # remove saved first block setitems if array potentially changed later + saved_arrs = set(first_block_saved_values.keys()) + for l in labels: + if l == first_label: + continue + for stmt in parfor.loop_body[l].body: + if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'getitem' + and stmt.value.index.name == parfor.index_var.name): + continue + varnames = set(v.name for v in stmt.list_vars()) + rm_arrs = varnames & saved_arrs + for a in rm_arrs: + first_block_saved_values.pop(a, None) + + + # replace getitems with available value + # e.g. A[i] = v; ... s = A[i] -> s = v + for l in labels: + if l == first_label: + continue + block = parfor.loop_body[l] + saved_values = first_block_saved_values.copy() + _update_parfor_get_setitems(block.body, parfor.index_var, alias_map, + saved_values, lives_n_aliases) + + + # after getitem replacement, remove extra setitems + blocks = parfor.loop_body.copy() # shallow copy is enough + last_label = max(blocks.keys()) + return_label, tuple_var = _add_liveness_return_block(blocks, lives_n_aliases, typemap) + # jump to return label + jump = ir.Jump(return_label, ir.Loc("parfors_dummy", -1)) + blocks[last_label].body.append(jump) + cfg = compute_cfg_from_blocks(blocks) + usedefs = compute_use_defs(blocks) + live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap) + alias_set = set(alias_map.keys()) + + for label, block in blocks.items(): + new_body = [] + in_lives = {v.name for v in block.terminator.list_vars()} + # find live variables at the end of block + for out_blk, _data in cfg.successors(label): + in_lives |= live_map[out_blk] + for stmt in reversed(block.body): + # aliases of lives are also live for setitems + alias_lives = in_lives & alias_set + for v in alias_lives: + in_lives |= alias_map[v] + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == parfor.index_var.name and + stmt.target.name not in in_lives and + stmt.target.name not in arg_aliases): + continue + in_lives |= {v.name for v in stmt.list_vars()} + new_body.append(stmt) + new_body.reverse() + block.body = new_body + + typemap.pop(tuple_var.name) # remove dummy tuple type + blocks[last_label].body.pop() # remove jump + + """ + Process parfor body recursively. + Note that this is the only place in this function that uses the + argument lives instead of lives_n_aliases. The former does not + include the aliases of live variables but only the live variable + names themselves. See a comment in this function for how that + is used. + """ + remove_dead_parfor_recursive( + parfor, lives, arg_aliases, alias_map, func_ir, typemap) + + # remove parfor if empty + is_empty = len(parfor.init_block.body) == 0 + for block in parfor.loop_body.values(): + is_empty &= len(block.body) == 0 + if is_empty: + return None + return parfor + +def _update_parfor_get_setitems(block_body, index_var, alias_map, + saved_values, lives): + """ + replace getitems of a previously set array in a block of parfor loop body + """ + for stmt in block_body: + if (isinstance(stmt, (ir.StaticSetItem, ir.SetItem)) and + get_index_var(stmt).name == index_var.name and + stmt.target.name not in lives): + # saved values of aliases of SetItem target array are invalid + for w in alias_map.get(stmt.target.name, []): + saved_values.pop(w, None) + # set saved value after invalidation since alias_map may + # contain the array itself (e.g. pi example) + saved_values[stmt.target.name] = stmt.value + continue + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Expr): + rhs = stmt.value + if rhs.op == 'getitem' and isinstance(rhs.index, ir.Var): + if rhs.index.name == index_var.name: + # replace getitem if value saved + stmt.value = saved_values.get(rhs.value.name, rhs) + continue + # conservative assumption: array is modified if referenced + # remove all referenced arrays + for v in stmt.list_vars(): + saved_values.pop(v.name, None) + # aliases are potentially modified as well + for w in alias_map.get(v.name, []): + saved_values.pop(w, None) + + return + +ir_utils.remove_dead_extensions[Parfor] = remove_dead_parfor + + +def remove_dead_parfor_recursive(parfor, lives, arg_aliases, alias_map, + func_ir, typemap): + """create a dummy function from parfor and call remove dead recursively + """ + blocks = parfor.loop_body.copy() # shallow copy is enough + first_body_block = min(blocks.keys()) + assert first_body_block > 0 # we are using 0 for init block here + last_label = max(blocks.keys()) + + """ + Previously, this statement used lives_n_aliases. That had the effect of + keeping variables in the init_block alive if they aliased an array that + was later written to. By using just lives to indicate which variables + names are live at exit of the parfor but then using alias_map for the + actual recursive dead code removal, we keep any writes to aliased arrays + alive but also allow aliasing assignments (i.e., a = b) to be eliminated + so long as 'b' is not written to through the variable 'a' later on. + This makes assignment handling of remove_dead_block work properly since + it allows distinguishing between live variables and their aliases. + """ + return_label, tuple_var = _add_liveness_return_block(blocks, lives, typemap) + + # branch back to first body label to simulate loop + scope = blocks[last_label].scope + + branchcond = ir.Var(scope, mk_unique_var("$branchcond"), ir.Loc("parfors_dummy", -1)) + typemap[branchcond.name] = types.boolean + + branch = ir.Branch(branchcond, first_body_block, return_label, ir.Loc("parfors_dummy", -1)) + blocks[last_label].body.append(branch) + + # add dummy jump in init_block for CFG to work + blocks[0] = parfor.init_block + blocks[0].body.append(ir.Jump(first_body_block, ir.Loc("parfors_dummy", -1))) + + # args var including aliases is ok + remove_dead(blocks, arg_aliases, func_ir, typemap, alias_map, arg_aliases) + typemap.pop(tuple_var.name) # remove dummy tuple type + blocks[0].body.pop() # remove dummy jump + blocks[last_label].body.pop() # remove branch + return + +def _add_liveness_return_block(blocks, lives, typemap): + last_label = max(blocks.keys()) + return_label = last_label + 1 + + loc = blocks[last_label].loc + scope = blocks[last_label].scope + blocks[return_label] = ir.Block(scope, loc) + + # add lives in a dummpy return to last block to avoid their removal + tuple_var = ir.Var(scope, mk_unique_var("$tuple_var"), loc) + # dummy type for tuple_var + typemap[tuple_var.name] = types.containers.UniTuple( + types.uintp, 2) + live_vars = [ir.Var(scope, v, loc) for v in lives] + tuple_call = ir.Expr.build_tuple(live_vars, loc) + blocks[return_label].body.append(ir.Assign(tuple_call, tuple_var, loc)) + blocks[return_label].body.append(ir.Return(tuple_var, loc)) + return return_label, tuple_var + + +def find_potential_aliases_parfor(parfor, args, typemap, func_ir, alias_map, arg_aliases): + blocks = wrap_parfor_blocks(parfor) + ir_utils.find_potential_aliases( + blocks, args, typemap, func_ir, alias_map, arg_aliases) + unwrap_parfor_blocks(parfor) + return + +ir_utils.alias_analysis_extensions[Parfor] = find_potential_aliases_parfor + +def simplify_parfor_body_CFG(blocks): + """simplify CFG of body loops in parfors""" + n_parfors = 0 + for block in blocks.values(): + for stmt in block.body: + if isinstance(stmt, Parfor): + n_parfors += 1 + parfor = stmt + # add dummy return to enable CFG creation + # can't use dummy_return_in_loop_body since body changes + last_block = parfor.loop_body[max(parfor.loop_body.keys())] + scope = last_block.scope + loc = ir.Loc("parfors_dummy", -1) + const = ir.Var(scope, mk_unique_var("$const"), loc) + last_block.body.append(ir.Assign(ir.Const(0, loc), const, loc)) + last_block.body.append(ir.Return(const, loc)) + parfor.loop_body = simplify_CFG(parfor.loop_body) + last_block = parfor.loop_body[max(parfor.loop_body.keys())] + last_block.body.pop() + # call on body recursively + simplify_parfor_body_CFG(parfor.loop_body) + return n_parfors + + +def wrap_parfor_blocks(parfor, entry_label = None): + """wrap parfor blocks for analysis/optimization like CFG""" + blocks = parfor.loop_body.copy() # shallow copy is enough + if entry_label is None: + entry_label = min(blocks.keys()) + assert entry_label > 0 # we are using 0 for init block here + + # add dummy jump in init_block for CFG to work + blocks[0] = parfor.init_block + blocks[0].body.append(ir.Jump(entry_label, blocks[0].loc)) + for block in blocks.values(): + if len(block.body) == 0 or (not block.body[-1].is_terminator): + block.body.append(ir.Jump(entry_label, block.loc)) + return blocks + + +def unwrap_parfor_blocks(parfor, blocks=None): + """ + unwrap parfor blocks after analysis/optimization. + Allows changes to the parfor loop. + """ + if blocks is not None: + # make sure init block isn't removed + init_block_label = min(blocks.keys()) + # update loop body blocks + blocks.pop(init_block_label) + parfor.loop_body = blocks + + # make sure dummy jump to loop body isn't altered + first_body_label = min(parfor.loop_body.keys()) + assert isinstance(parfor.init_block.body[-1], ir.Jump) + + # remove dummy jump to loop body + parfor.init_block.body.pop() + + # make sure dummy jump back to loop body isn't altered + for block in parfor.loop_body.values(): + if (isinstance(block.body[-1], ir.Jump) and + block.body[-1].target == first_body_label): + # remove dummy jump back to loop + block.body.pop() + return + + +def get_copies_parfor(parfor, typemap): + """find copies generated/killed by parfor""" + blocks = wrap_parfor_blocks(parfor) + in_copies_parfor, out_copies_parfor = copy_propagate(blocks, typemap) + in_gen_copies, in_extra_kill = get_block_copies(blocks, typemap) + unwrap_parfor_blocks(parfor) + + # parfor's extra kill is kills of its init block, + # and all possible gens and kills of it's body loop. + # body doesn't gen and only kills since it may or may not run + # TODO: save copies that are repeated in parfor + kill_set = in_extra_kill[0] + for label in parfor.loop_body.keys(): + kill_set |= {l for l, r in in_gen_copies[label]} + kill_set |= in_extra_kill[label] + + # gen copies is copies generated by init that are not killed by body + last_label = max(parfor.loop_body.keys()) + gens = out_copies_parfor[last_label] & in_gen_copies[0] + + if config.DEBUG_ARRAY_OPT >= 1: + print("copy propagate parfor gens:", gens, "kill_set", kill_set) + return gens, kill_set + + +ir_utils.copy_propagate_extensions[Parfor] = get_copies_parfor + + +def apply_copies_parfor(parfor, var_dict, name_var_table, + typemap, calltypes, save_copies): + """apply copy propagate recursively in parfor""" + # replace variables in pattern metadata like stencil neighborhood + for i, pattern in enumerate(parfor.patterns): + if pattern[0] == 'stencil': + parfor.patterns[i] = ('stencil', + replace_vars_inner(pattern[1], var_dict)) + + # replace loop boundary variables + for l in parfor.loop_nests: + l.start = replace_vars_inner(l.start, var_dict) + l.stop = replace_vars_inner(l.stop, var_dict) + l.step = replace_vars_inner(l.step, var_dict) + + blocks = wrap_parfor_blocks(parfor) + # add dummy assigns for each copy + assign_list = [] + for lhs_name, rhs in var_dict.items(): + assign_list.append(ir.Assign(rhs, name_var_table[lhs_name], + ir.Loc("dummy", -1))) + blocks[0].body = assign_list + blocks[0].body + in_copies_parfor, out_copies_parfor = copy_propagate(blocks, typemap) + apply_copy_propagate(blocks, in_copies_parfor, name_var_table, typemap, + calltypes, save_copies) + unwrap_parfor_blocks(parfor) + # remove dummy assignments + blocks[0].body = blocks[0].body[len(assign_list):] + return + + +ir_utils.apply_copy_propagate_extensions[Parfor] = apply_copies_parfor + + +def push_call_vars(blocks, saved_globals, saved_getattrs, typemap, nested=False): + """push call variables to right before their call site. + assuming one global/getattr is created for each call site and control flow + doesn't change it. + """ + for block in blocks.values(): + new_body = [] + # global/attr variables that are defined in this block already, + # no need to reassign them + block_defs = set() + # Some definitions are copied right before the call but then we + # need to rename that symbol in that block so that typing won't + # generate an error trying to lock the save var twice. + # In rename_dict, we collect the symbols that must be renamed in + # this block. We collect them then apply the renaming at the end. + rename_dict = {} + for stmt in block.body: + def process_assign(stmt): + if isinstance(stmt, ir.Assign): + rhs = stmt.value + lhs = stmt.target + if (isinstance(rhs, ir.Global)): + saved_globals[lhs.name] = stmt + block_defs.add(lhs.name) + elif isinstance(rhs, ir.Expr) and rhs.op == 'getattr': + if (rhs.value.name in saved_globals + or rhs.value.name in saved_getattrs): + saved_getattrs[lhs.name] = stmt + block_defs.add(lhs.name) + + if not nested and isinstance(stmt, Parfor): + for s in stmt.init_block.body: + process_assign(s) + pblocks = stmt.loop_body.copy() + push_call_vars(pblocks, saved_globals, saved_getattrs, typemap, nested=True) + new_body.append(stmt) + continue + else: + process_assign(stmt) + for v in stmt.list_vars(): + new_body += _get_saved_call_nodes(v.name, saved_globals, + saved_getattrs, block_defs, rename_dict) + new_body.append(stmt) + block.body = new_body + # If there is anything to rename then apply the renaming here. + if len(rename_dict) > 0: + # Fix-up the typing for the renamed vars. + for k, v in rename_dict.items(): + typemap[v] = typemap[k] + # This is only to call replace_var_names which takes a dict. + temp_blocks = {0: block} + replace_var_names(temp_blocks, rename_dict) + + return + + +def _get_saved_call_nodes(fname, saved_globals, saved_getattrs, block_defs, rename_dict): + """ Implement the copying of globals or getattrs for the purposes noted in + push_call_vars. We make a new var and assign to it a copy of the + global or getattr. We remember this new assignment node and add an + entry in the renaming dictionary so that for this block the original + var name is replaced by the new var name we created. + """ + nodes = [] + while (fname not in block_defs and (fname in saved_globals + or fname in saved_getattrs)): + def rename_global_or_getattr(obj, var_base, nodes, block_defs, rename_dict): + assert(isinstance(obj, ir.Assign)) + renamed_var = ir.Var(obj.target.scope, + mk_unique_var(var_base), + obj.target.loc) + renamed_assign = ir.Assign(copy.deepcopy(obj.value), + renamed_var, + obj.loc) + nodes.append(renamed_assign) + block_defs.add(obj.target.name) + rename_dict[obj.target.name] = renamed_assign.target.name + + if fname in saved_globals: + rename_global_or_getattr(saved_globals[fname], "$push_global_to_block", + nodes, block_defs, rename_dict) + fname = '_PA_DONE' + elif fname in saved_getattrs: + rename_global_or_getattr(saved_getattrs[fname], "$push_getattr_to_block", + nodes, block_defs, rename_dict) + fname = saved_getattrs[fname].value.value.name + nodes.reverse() + return nodes + +def repr_arrayexpr(arrayexpr): + """Extract operators from arrayexpr to represent it abstractly as a string. + """ + if isinstance(arrayexpr, tuple): + opr = arrayexpr[0] + # sometimes opr is not string like '+', but is a ufunc object + if not isinstance(opr, str): + if hasattr(opr, '__name__'): + opr = opr.__name__ + else: + opr = '_' # can return dummy since repr is not critical + args = arrayexpr[1] + if len(args) == 1: + return '({}({}))'.format(opr, repr_arrayexpr(args[0])) + else: + opr = ' ' + opr + ' ' + return '({})'.format(opr.join([ repr_arrayexpr(x) for x in args ])) + elif isinstance(arrayexpr, numba.core.ir.Var): + name = arrayexpr.name + if name.startswith('$'): + return '\'%s\' (temporary variable)' % name + else: + return name + elif isinstance(arrayexpr, numba.core.ir.Const): + return repr(arrayexpr.value) + else: + return '_' + +def fix_generator_types(generator_info, return_type, typemap): + """postproc updates generator_info with live variables after transformations + but generator variables have types in return_type that are updated here. + """ + new_state_types = [] + for v in generator_info.state_vars: + new_state_types.append(typemap[v]) + return_type.state_types = tuple(new_state_types) + return + + +def get_parfor_call_table(parfor, call_table=None, reverse_call_table=None): + if call_table is None: + call_table = {} + if reverse_call_table is None: + reverse_call_table = {} + blocks = wrap_parfor_blocks(parfor) + call_table, reverse_call_table = get_call_table(blocks, call_table, + reverse_call_table) + unwrap_parfor_blocks(parfor) + return call_table, reverse_call_table + + +ir_utils.call_table_extensions[Parfor] = get_parfor_call_table + + +def get_parfor_tuple_table(parfor, tuple_table=None): + if tuple_table is None: + tuple_table = {} + blocks = wrap_parfor_blocks(parfor) + tuple_table = ir_utils.get_tuple_table(blocks, tuple_table) + unwrap_parfor_blocks(parfor) + return tuple_table + + +ir_utils.tuple_table_extensions[Parfor] = get_parfor_tuple_table + + +def get_parfor_array_accesses(parfor, accesses=None): + if accesses is None: + accesses = set() + blocks = wrap_parfor_blocks(parfor) + accesses = ir_utils.get_array_accesses(blocks, accesses) + unwrap_parfor_blocks(parfor) + return accesses + + +# parfor handler is same as +ir_utils.array_accesses_extensions[Parfor] = get_parfor_array_accesses + + +def parfor_add_offset_to_labels(parfor, offset): + blocks = wrap_parfor_blocks(parfor) + blocks = add_offset_to_labels(blocks, offset) + blocks[0] = blocks[offset] + blocks.pop(offset) + unwrap_parfor_blocks(parfor, blocks) + return + + +ir_utils.add_offset_to_labels_extensions[Parfor] = parfor_add_offset_to_labels + + +def parfor_find_max_label(parfor): + blocks = wrap_parfor_blocks(parfor) + max_label = ir_utils.find_max_label(blocks) + unwrap_parfor_blocks(parfor) + return max_label + +ir_utils.find_max_label_extensions[Parfor] = parfor_find_max_label + + +def parfor_typeinfer(parfor, typeinferer): + save_blocks = typeinferer.blocks + blocks = wrap_parfor_blocks(parfor) + index_vars = [l.index_variable for l in parfor.loop_nests] + # no need to handle parfor.index_var (tuple of variables), since it will be + # assigned to a tuple from individual indices + first_block = min(blocks.keys()) + loc = blocks[first_block].loc + # XXX + index_assigns = [ir.Assign(ir.Const(1, loc=loc, use_literal_type=False), v, loc) for v in index_vars] + save_first_block_body = blocks[first_block].body + blocks[first_block].body = index_assigns + blocks[first_block].body + typeinferer.blocks = blocks + typeinferer.build_constraint() + typeinferer.blocks = save_blocks + blocks[first_block].body = save_first_block_body + unwrap_parfor_blocks(parfor) + + +typeinfer.typeinfer_extensions[Parfor] = parfor_typeinfer + +def build_parfor_definitions(parfor, definitions=None): + """get variable definition table for parfors""" + if definitions is None: + definitions = defaultdict(list) + + # avoid wrap_parfor_blocks() since build_definitions is called inside + # find_potential_aliases_parfor where the parfor is already wrapped + build_definitions(parfor.loop_body, definitions) + build_definitions({0: parfor.init_block}, definitions) + return definitions + +ir_utils.build_defs_extensions[Parfor] = build_parfor_definitions + +@contextmanager +def dummy_return_in_loop_body(loop_body): + """adds dummy return to last block of parfor loop body for CFG computation + """ + # max is last block since we add it manually for prange + last_label = max(loop_body.keys()) + scope = loop_body[last_label].scope + const = ir.Var(scope, mk_unique_var("$const"), ir.Loc("parfors_dummy", -1)) + loop_body[last_label].body.append( + ir.Return(const, ir.Loc("parfors_dummy", -1))) + yield + # remove dummy return + loop_body[last_label].body.pop() + +@infer_global(reduce) +class ReduceInfer(AbstractTemplate): + def generic(self, args, kws): + assert not kws + if len(args) != 3: + raise errors.NumbaAssertionError("len(args) != 3") + assert isinstance(args[1], types.Array) + return signature(args[1].dtype, *args) + + +def ensure_parallel_support(): + """Check if the platform supports parallel=True and raise if it does not. + """ + if config.IS_32BITS: + msg = ("The 'parallel' target is not currently supported on 32 bit " + "hardware.") + raise errors.UnsupportedParforsError(msg) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..d83ec4dac88bf88e9f1b96e2c508396b417493ec --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering.py @@ -0,0 +1,2068 @@ +import copy +import operator + +import types as pytypes +import operator +import warnings +from dataclasses import make_dataclass + +import llvmlite.ir +import numpy as np + +import numba +from numba.parfors import parfor +from numba.core import types, ir, config, compiler, sigutils, cgutils +from numba.core.ir_utils import ( + add_offset_to_labels, + replace_var_names, + remove_dels, + legalize_names, + rename_labels, + get_name_var_table, + visit_vars_inner, + get_definition, + guard, + get_call_table, + is_pure, + get_np_ufunc_typ, + get_unused_var_name, + is_const_call, + fixup_var_define_in_scope, + transfer_scope, + find_max_label, + get_global_func_typ, + find_topo_order, +) +from numba.core.typing import signature +from numba.core import lowering +from numba.parfors.parfor import ensure_parallel_support +from numba.core.errors import ( + NumbaParallelSafetyWarning, NotDefinedError, CompilerError, InternalError, +) +from numba.parfors.parfor_lowering_utils import ParforLoweringBuilder + + +class ParforLower(lowering.Lower): + """This is a custom lowering class that extends standard lowering so as + to accommodate parfor.Parfor nodes.""" + + # custom instruction lowering to handle parfor nodes + def lower_inst(self, inst): + if isinstance(inst, parfor.Parfor): + _lower_parfor_parallel(self, inst) + else: + super().lower_inst(inst) + + @property + def _disable_sroa_like_opt(self): + """ + Force disable this because Parfor use-defs is incompatible---it only + considers use-defs in blocks that must be executing. + See https://github.com/numba/numba/commit/017e2ff9db87fc34149b49dd5367ecbf0bb45268 + """ + return True + + +def _lower_parfor_parallel(lowerer, parfor): + if parfor.lowerer is None: + return _lower_parfor_parallel_std(lowerer, parfor) + else: + return parfor.lowerer(lowerer, parfor) + + +def _lower_parfor_parallel_std(lowerer, parfor): + """Lowerer that handles LLVM code generation for parfor. + This function lowers a parfor IR node to LLVM. + The general approach is as follows: + 1) The code from the parfor's init block is lowered normally + in the context of the current function. + 2) The body of the parfor is transformed into a gufunc function. + 3) Code is inserted into the main function that calls do_scheduling + to divide the iteration space for each thread, allocates + reduction arrays, calls the gufunc function, and then invokes + the reduction function across the reduction arrays to produce + the final reduction values. + """ + from numba.np.ufunc.parallel import get_thread_count + + ensure_parallel_support() + typingctx = lowerer.context.typing_context + targetctx = lowerer.context + builder = lowerer.builder + # We copy the typemap here because for race condition variable we'll + # update their type to array so they can be updated by the gufunc. + orig_typemap = lowerer.fndesc.typemap + # replace original typemap with copy and restore the original at the end. + lowerer.fndesc.typemap = copy.copy(orig_typemap) + if config.DEBUG_ARRAY_OPT: + print("lowerer.fndesc", lowerer.fndesc, type(lowerer.fndesc)) + typemap = lowerer.fndesc.typemap + varmap = lowerer.varmap + + if config.DEBUG_ARRAY_OPT: + print("_lower_parfor_parallel") + parfor.dump() + + loc = parfor.init_block.loc + scope = parfor.init_block.scope + + # produce instructions for init_block + if config.DEBUG_ARRAY_OPT: + print("init_block = ", parfor.init_block, " ", type(parfor.init_block)) + for instr in parfor.init_block.body: + if config.DEBUG_ARRAY_OPT: + print("lower init_block instr = ", instr) + lowerer.lower_inst(instr) + + for racevar in parfor.races: + if racevar not in varmap: + rvtyp = typemap[racevar] + rv = ir.Var(scope, racevar, loc) + lowerer._alloca_var(rv.name, rvtyp) + + alias_map = {} + arg_aliases = {} + numba.parfors.parfor.find_potential_aliases_parfor(parfor, parfor.params, typemap, + lowerer.func_ir, alias_map, arg_aliases) + if config.DEBUG_ARRAY_OPT: + print("alias_map", alias_map) + print("arg_aliases", arg_aliases) + + # run get_parfor_outputs() and get_parfor_reductions() before gufunc creation + # since Jumps are modified so CFG of loop_body dict will become invalid + assert parfor.params is not None + + parfor_output_arrays = numba.parfors.parfor.get_parfor_outputs( + parfor, parfor.params) + parfor_redvars, parfor_reddict = parfor.redvars, parfor.reddict + if config.DEBUG_ARRAY_OPT: + print("parfor_redvars:", parfor_redvars) + print("parfor_reddict:", parfor_reddict) + + # init reduction array allocation here. + nredvars = len(parfor_redvars) + redarrs = {} + to_cleanup = [] + if nredvars > 0: + # reduction arrays outer dimension equal to thread count + scope = parfor.init_block.scope + loc = parfor.init_block.loc + pfbdr = ParforLoweringBuilder(lowerer=lowerer, scope=scope, loc=loc) + + # Get the Numba internal function to call to get the thread count. + get_num_threads = pfbdr.bind_global_function( + fobj=numba.np.ufunc.parallel._iget_num_threads, + ftype=get_global_func_typ(numba.np.ufunc.parallel._iget_num_threads), + args=() + ) + + # Insert the call to assign the thread count to a variable. + num_threads_var = pfbdr.assign( + rhs=pfbdr.call(get_num_threads, args=[]), + typ=types.intp, + name="num_threads_var") + + # For each reduction variable... + for i in range(nredvars): + red_name = parfor_redvars[i] + # Get the type of the reduction variable. + redvar_typ = lowerer.fndesc.typemap[red_name] + # Get the ir.Var for the reduction variable. + redvar = ir.Var(scope, red_name, loc) + # Get the type of the array that holds the per-thread + # reduction variables. + redarrvar_typ = redtyp_to_redarraytype(redvar_typ) + reddtype = redarrvar_typ.dtype + if config.DEBUG_ARRAY_OPT: + print( + "reduction_info", + red_name, + redvar_typ, + redarrvar_typ, + reddtype, + types.DType(reddtype), + num_threads_var, + type(num_threads_var) + ) + + # If this is reduction over an array, + # the reduction array has just one added per-worker dimension. + if isinstance(redvar_typ, types.npytypes.Array): + redarrdim = redvar_typ.ndim + 1 + else: + redarrdim = 1 + + # Reduction array is created and initialized to the initial reduction value. + + # First create a var for the numpy empty ufunc. + glbl_np_empty = pfbdr.bind_global_function( + fobj=np.empty, + ftype=get_np_ufunc_typ(np.empty, pfbdr._typingctx), + args=( + types.UniTuple(types.intp, redarrdim), + ), + kws={'dtype': types.DType(reddtype)} + ) + + size_var_list = [num_threads_var] + + # If this is a reduction over an array... + if isinstance(redvar_typ, types.npytypes.Array): + # Add code to get the shape of the array being reduced over. + redshape_var = pfbdr.assign( + rhs=ir.Expr.getattr(redvar, "shape", loc), + typ=types.UniTuple(types.intp, redvar_typ.ndim), + name="redarr_shape", + ) + + # Add the dimension sizes of the array being reduced over to the tuple of sizes pass to empty. + for j in range(redvar_typ.ndim): + onedimvar = pfbdr.assign( + rhs=ir.Expr.static_getitem(redshape_var, j, None, loc), + typ=types.intp, + name="redshapeonedim", + ) + size_var_list.append(onedimvar) + + # Empty call takes tuple of sizes. Create here and fill in outer dimension (num threads). + size_var = pfbdr.make_tuple_variable( + size_var_list, name='tuple_size_var', + ) + + # Resolve dtype + cval = pfbdr._typingctx.resolve_value_type(reddtype) + dt = pfbdr.make_const_variable(cval=cval, typ=types.DType(reddtype)) + # Add call to empty passing the size var tuple. + empty_call = pfbdr.call(glbl_np_empty, args=[size_var, dt]) + + redarr_var = pfbdr.assign( + rhs=empty_call, typ=redarrvar_typ, name="redarr", + ) + + # Remember mapping of original reduction array to the newly created per-worker reduction array. + redarrs[redvar.name] = redarr_var + to_cleanup.append(redarr_var) + + init_val = parfor_reddict[red_name].init_val + + if init_val is not None: + if isinstance(redvar_typ, types.npytypes.Array): + # Create an array of identity values for the reduction. + # First, create a variable for np.full. + full_func_node = pfbdr.bind_global_function( + fobj=np.full, + ftype=get_np_ufunc_typ(np.full, pfbdr._typingctx), + args=( + types.UniTuple(types.intp, redvar_typ.ndim), + reddtype, + ), + kws={'dtype': types.DType(reddtype)}, + ) + + # Then create a var with the identify value. + init_val_var = pfbdr.make_const_variable( + cval=init_val, + typ=reddtype, + name="init_val", + ) + + # Then, call np.full with the shape of the reduction array and the identity value. + full_call = pfbdr.call( + full_func_node, args=[redshape_var, init_val_var, dt], + ) + + redtoset = pfbdr.assign( + rhs=full_call, + typ=redvar_typ, + name="redtoset", + ) + # rettoset is an array from np.full() and must be released + to_cleanup.append(redtoset) + else: + redtoset = pfbdr.make_const_variable( + cval=init_val, + typ=reddtype, + name="redtoset", + ) + else: + redtoset = redvar + + if config.DEBUG_ARRAY_OPT_RUNTIME: + res_print_str = "res_print1 for redvar " + str(redvar) + ":" + strconsttyp = types.StringLiteral(res_print_str) + + lhs = pfbdr.make_const_variable( + cval=res_print_str, + typ=strconsttyp, + name="str_const", + ) + + res_print = ir.Print(args=[lhs, redvar], + vararg=None, loc=loc) + lowerer.fndesc.calltypes[res_print] = signature(types.none, + typemap[lhs.name], + typemap[redvar.name]) + print("res_print_redvar", res_print) + lowerer.lower_inst(res_print) + + + # For each thread, initialize the per-worker reduction array to + # the current reduction array value. + + # Get the Numba type of the variable that holds the thread count. + num_thread_type = typemap[num_threads_var.name] + # Get the LLVM type of the thread count variable. + ntllvm_type = targetctx.get_value_type(num_thread_type) + # Create a LLVM variable to hold the loop index. + alloc_loop_var = cgutils.alloca_once(builder, ntllvm_type) + # Associate this LLVM variable to a Numba IR variable so that + # we can use setitem IR builder. + # Create a Numba IR variable. + numba_ir_loop_index_var = scope.redefine("$loop_index", loc) + # Give that variable the right type. + typemap[numba_ir_loop_index_var.name] = num_thread_type + # Associate this Numba variable to the LLVM variable in the + # lowerer's varmap. + lowerer.varmap[numba_ir_loop_index_var.name] = alloc_loop_var + # Insert a loop into the outputed LLVM that goes from 0 to + # the current thread count. + with cgutils.for_range(builder, lowerer.loadvar(num_threads_var.name), intp=ntllvm_type) as loop: + # Store the loop index into the alloca'd LLVM loop index variable. + builder.store(loop.index, alloc_loop_var) + # Initialize one element of the reduction array using the Numba + # IR variable associated with this loop's index. + pfbdr.setitem(obj=redarr_var, index=numba_ir_loop_index_var, val=redtoset) + + # compile parfor body as a separate function to be used with GUFuncWrapper + flags = parfor.flags.copy() + flags.error_model = "numpy" + # Can't get here unless flags.auto_parallel == ParallelOptions(True) + index_var_typ = typemap[parfor.loop_nests[0].index_variable.name] + # index variables should have the same type, check rest of indices + for l in parfor.loop_nests[1:]: + assert typemap[l.index_variable.name] == index_var_typ + numba.parfors.parfor.sequential_parfor_lowering = True + try: + (func, + func_args, + func_sig, + func_arg_types, + exp_name_to_tuple_var) = _create_gufunc_for_parfor_body( + lowerer, parfor, typemap, typingctx, targetctx, flags, {}, + bool(alias_map), index_var_typ, parfor.races) + finally: + numba.parfors.parfor.sequential_parfor_lowering = False + + # get the shape signature + func_args = ['sched'] + func_args + num_reductions = len(parfor_redvars) + num_inputs = len(func_args) - len(parfor_output_arrays) - num_reductions + if config.DEBUG_ARRAY_OPT: + print("func_args = ", func_args) + print("num_inputs = ", num_inputs) + print("parfor_outputs = ", parfor_output_arrays) + print("parfor_redvars = ", parfor_redvars) + print("num_reductions = ", num_reductions) + gu_signature = _create_shape_signature( + parfor.get_shape_classes, + num_inputs, + num_reductions, + func_args, + func_sig, + parfor.races, + typemap) + if config.DEBUG_ARRAY_OPT: + print("gu_signature = ", gu_signature) + + # call the func in parallel by wrapping it with ParallelGUFuncBuilder + loop_ranges = [(l.start, l.stop, l.step) for l in parfor.loop_nests] + if config.DEBUG_ARRAY_OPT: + print("loop_nests = ", parfor.loop_nests) + print("loop_ranges = ", loop_ranges) + call_parallel_gufunc( + lowerer, + func, + gu_signature, + func_sig, + func_args, + func_arg_types, + loop_ranges, + parfor_redvars, + parfor_reddict, + redarrs, + parfor.init_block, + index_var_typ, + parfor.races, + exp_name_to_tuple_var) + + if nredvars > 0: + _parfor_lowering_finalize_reduction( + parfor, redarrs, lowerer, parfor_reddict, num_threads_var, + ) + + # Cleanup reduction variable + for v in to_cleanup: + lowerer.lower_inst(ir.Del(v.name, loc=loc)) + # Restore the original typemap of the function that was replaced temporarily at the + # Beginning of this function. + lowerer.fndesc.typemap = orig_typemap + + if config.DEBUG_ARRAY_OPT: + print("_lower_parfor_parallel done") + + +_ReductionInfo = make_dataclass( + "_ReductionInfo", + [ + "redvar_info", + "redvar_name", + "redvar_typ", + "redarr_var", + "redarr_typ", + "init_val", + ], + frozen=True, +) + + +def _parfor_lowering_finalize_reduction( + parfor, + redarrs, + lowerer, + parfor_reddict, + thread_count_var, + ): + """Emit code to finalize the reduction from the intermediate values of + each thread. + """ + # For each reduction variable + for redvar_name, redarr_var in redarrs.items(): + # Pseudo-code for this loop body: + # tmp = redarr[0] + # for i in range(1, thread_count): + # tmp = reduce_op(redarr[i], tmp) + # reduction_result = tmp + redvar_typ = lowerer.fndesc.typemap[redvar_name] + redarr_typ = lowerer.fndesc.typemap[redarr_var.name] + init_val = lowerer.loadvar(redvar_name) + + reduce_info = _ReductionInfo( + redvar_info = parfor_reddict[redvar_name], + redvar_name=redvar_name, + redvar_typ=redvar_typ, + redarr_var=redarr_var, + redarr_typ=redarr_typ, + init_val=init_val, + ) + # generate code for combining reduction variable with thread output + handler = (_lower_trivial_inplace_binops + if reduce_info.redvar_info.redop is not None + else _lower_non_trivial_reduce) + handler(parfor, lowerer, thread_count_var, reduce_info) + + +class ParforsUnexpectedReduceNodeError(InternalError): + def __init__(self, inst): + super().__init__(f"Unknown reduce instruction node: {inst}") + + +def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info): + """Lower trivial inplace-binop reduction. + """ + for inst in reduce_info.redvar_info.reduce_nodes: + # Var assigns to Var? + if _lower_var_to_var_assign(lowerer, inst): + pass + # Is inplace-binop for the reduction? + elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "inplace_binop"): + fn = inst.value.fn + redvar_result = _emit_binop_reduce_call( + fn, lowerer, thread_count_var, reduce_info, + ) + lowerer.storevar(redvar_result, name=inst.target.name) + # Is binop for the reduction? + elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "binop"): + fn = inst.value.fn + redvar_result = _emit_binop_reduce_call( + fn, lowerer, thread_count_var, reduce_info, + ) + lowerer.storevar(redvar_result, name=inst.target.name) + # Otherwise? + else: + raise ParforsUnexpectedReduceNodeError(inst) + + # XXX: This seems like a hack to stop the loop with this condition. + if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, + reduce_info.redvar_name): + break + if config.DEBUG_ARRAY_OPT_RUNTIME: + varname = reduce_info.redvar_name + lowerer.print_variable( + f"{parfor.loc}: parfor {fn.__name__} reduction {varname} =", + varname, + ) + + +def _lower_non_trivial_reduce(parfor, lowerer, thread_count_var, reduce_info): + """Lower non-trivial reduction such as call to `functools.reduce()`. + """ + init_name = f"{reduce_info.redvar_name}#init" + # The init_name variable is not defined at this point. + lowerer.fndesc.typemap.setdefault(init_name, reduce_info.redvar_typ) + # Emit a sequence of the reduction operation for each intermediate result + # of each thread. + num_thread_llval = lowerer.loadvar(thread_count_var.name) + with cgutils.for_range(lowerer.builder, num_thread_llval) as loop: + tid = loop.index + for inst in reduce_info.redvar_info.reduce_nodes: + # Var assigns to Var? + if _lower_var_to_var_assign(lowerer, inst): + pass + # The reduction operation? + elif (isinstance(inst, ir.Assign) + and any(var.name == init_name for var in inst.list_vars())): + elem = _emit_getitem_call(tid, lowerer, reduce_info) + lowerer.storevar(elem, init_name) + lowerer.lower_inst(inst) + + # Otherwise? + else: + raise ParforsUnexpectedReduceNodeError(inst) + + # XXX: This seems like a hack to stop the loop with this condition. + if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, + reduce_info.redvar_name): + break + + if config.DEBUG_ARRAY_OPT_RUNTIME: + varname = reduce_info.redvar_name + lowerer.print_variable( + f"{parfor.loc}: parfor non-trivial reduction {varname} =", + varname, + ) + +def _lower_var_to_var_assign(lowerer, inst): + """Lower Var->Var assignment. + + Returns True if-and-only-if `inst` is a Var->Var assignment. + """ + if isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Var): + loaded = lowerer.loadvar(inst.value.name) + lowerer.storevar(loaded, name=inst.target.name) + return True + return False + +def _emit_getitem_call(idx, lowerer, reduce_info): + """Emit call to ``redarr_var[idx]`` + """ + def reducer_getitem(redarr, index): + return redarr[index] + + builder = lowerer.builder + ctx = lowerer.context + redarr_typ = reduce_info.redarr_typ + arg_arr = lowerer.loadvar(reduce_info.redarr_var.name) + args = (arg_arr, idx) + sig = signature(reduce_info.redvar_typ, redarr_typ, types.intp) + elem = ctx.compile_internal(builder, reducer_getitem, sig, args) + return elem + + +def _emit_binop_reduce_call(binop, lowerer, thread_count_var, reduce_info): + """Emit call to the ``binop`` for the reduction variable. + """ + + def reduction_add(thread_count, redarr, init): + c = init + for i in range(thread_count): + c += redarr[i] + return c + + def reduction_mul(thread_count, redarr, init): + c = init + for i in range(thread_count): + c *= redarr[i] + return c + + kernel = { + operator.iadd: reduction_add, + operator.isub: reduction_add, + operator.add: reduction_add, + operator.sub: reduction_add, + operator.imul: reduction_mul, + operator.ifloordiv: reduction_mul, + operator.itruediv: reduction_mul, + operator.mul: reduction_mul, + operator.floordiv: reduction_mul, + operator.truediv: reduction_mul, + }[binop] + + ctx = lowerer.context + builder = lowerer.builder + redarr_typ = reduce_info.redarr_typ + arg_arr = lowerer.loadvar(reduce_info.redarr_var.name) + + if config.DEBUG_ARRAY_OPT_RUNTIME: + init_var = reduce_info.redarr_var.scope.get(reduce_info.redvar_name) + res_print = ir.Print( + args=[reduce_info.redarr_var, init_var], vararg=None, + loc=lowerer.loc, + ) + typemap = lowerer.fndesc.typemap + lowerer.fndesc.calltypes[res_print] = signature( + types.none, typemap[reduce_info.redarr_var.name], + typemap[init_var.name], + ) + lowerer.lower_inst(res_print) + + arg_thread_count = lowerer.loadvar(thread_count_var.name) + args = (arg_thread_count, arg_arr, reduce_info.init_val) + sig = signature( + reduce_info.redvar_typ, types.uintp, redarr_typ, reduce_info.redvar_typ, + ) + + redvar_result = ctx.compile_internal(builder, kernel, sig, args) + return redvar_result + + +def _is_right_op_and_rhs_is_init(inst, redvar_name, op): + """Is ``inst`` an inplace-binop and the RHS is the reduction init? + """ + if not isinstance(inst, ir.Assign): + return False + rhs = inst.value + if not isinstance(rhs, ir.Expr): + return False + if rhs.op != op: + return False + if rhs.rhs.name != f"{redvar_name}#init": + return False + return True + + +def _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, redvar_name): + """Fix reduction variable name mismatch due to SSA. + """ + # Only process reduction statements post-gufunc execution + # until we see an assignment with a left-hand side to the + # reduction variable's name. This fixes problems with + # cases where there are multiple assignments to the + # reduction variable in the parfor. + scope = parfor.init_block.scope + if isinstance(inst, ir.Assign): + try: + reduction_var = scope.get_exact(redvar_name) + except NotDefinedError: + # Ideally, this shouldn't happen. The redvar name + # missing from scope indicates an error from + # other rewrite passes. + is_same_source_var = redvar_name == inst.target.name + else: + # Because of SSA, the redvar and target var of + # the current assignment would be different even + # though they refer to the same source-level var. + redvar_unver_name = reduction_var.unversioned_name + target_unver_name = inst.target.unversioned_name + is_same_source_var = redvar_unver_name == target_unver_name + + if is_same_source_var: + # If redvar is different from target var, add an + # assignment to put target var into redvar. + if redvar_name != inst.target.name: + val = lowerer.loadvar(inst.target.name) + lowerer.storevar(val, name=redvar_name) + return True + + return False + +def _create_shape_signature( + get_shape_classes, + num_inputs, + num_reductions, + args, + func_sig, + races, + typemap): + '''Create shape signature for GUFunc + ''' + if config.DEBUG_ARRAY_OPT: + print("_create_shape_signature", num_inputs, num_reductions, args, races) + for i in args[1:]: + print("argument", i, type(i), get_shape_classes(i, typemap=typemap)) + + num_inouts = len(args) - num_reductions + # maximum class number for array shapes + classes = [get_shape_classes(var, typemap=typemap) if var not in races else (-1,) for var in args[1:]] + class_set = set() + for _class in classes: + if _class: + for i in _class: + class_set.add(i) + max_class = max(class_set) + 1 if class_set else 0 + classes.insert(0, (max_class,)) # force set the class of 'sched' argument + class_set.add(max_class) + thread_num_class = max_class + 1 + class_set.add(thread_num_class) + class_map = {} + # TODO: use prefix + class number instead of single char + alphabet = ord('a') + for n in class_set: + if n >= 0: + class_map[n] = chr(alphabet) + alphabet += 1 + threadcount_ordinal = chr(alphabet) + + alpha_dict = {'latest_alpha' : alphabet} + + def bump_alpha(c, class_map): + if c >= 0: + return class_map[c] + else: + alpha_dict['latest_alpha'] += 1 + return chr(alpha_dict['latest_alpha']) + + gu_sin = [] + gu_sout = [] + count = 0 + syms_sin = () + if config.DEBUG_ARRAY_OPT: + print("args", args) + print("classes", classes) + print("threadcount_ordinal", threadcount_ordinal) + for cls, arg in zip(classes, args): + count = count + 1 + if cls: + dim_syms = tuple(bump_alpha(c, class_map) for c in cls) + else: + dim_syms = () + if (count > num_inouts): + # Add the threadcount_ordinal to represent the thread count + # to the start of the reduction array. + gu_sin.append(tuple([threadcount_ordinal] + list(dim_syms[1:]))) + else: + gu_sin.append(dim_syms) + syms_sin += dim_syms + return (gu_sin, gu_sout) + +def _print_block(block): + for i, inst in enumerate(block.body): + print(" ", i, " ", inst) + +def _print_body(body_dict): + '''Pretty-print a set of IR blocks. + ''' + topo_order = wrap_find_topo(body_dict) + for label in topo_order: + block = body_dict[label] + print("label: ", label) + _print_block(block) + + +def wrap_loop_body(loop_body): + blocks = loop_body.copy() # shallow copy is enough + first_label = min(blocks.keys()) + last_label = max(blocks.keys()) + loc = blocks[last_label].loc + blocks[last_label].body.append(ir.Jump(first_label, loc)) + return blocks + +def unwrap_loop_body(loop_body): + last_label = max(loop_body.keys()) + loop_body[last_label].body = loop_body[last_label].body[:-1] + +def add_to_def_once_sets(a_def, def_once, def_more): + '''If the variable is already defined more than once, do nothing. + Else if defined exactly once previously then transition this + variable to the defined more than once set (remove it from + def_once set and add to def_more set). + Else this must be the first time we've seen this variable defined + so add to def_once set. + ''' + if a_def in def_more: + pass + elif a_def in def_once: + def_more.add(a_def) + def_once.remove(a_def) + else: + def_once.add(a_def) + +def compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns): + '''Effect changes to the set of variables defined once or more than once + for a single block. + block - the block to process + def_once - set of variable names known to be defined exactly once + def_more - set of variable names known to be defined more than once + getattr_taken - dict mapping variable name to tuple of object and attribute taken + module_assigns - dict mapping variable name to the Global that they came from + ''' + # The only "defs" occur in assignments, so find such instructions. + assignments = block.find_insts(ir.Assign) + # For each assignment... + for one_assign in assignments: + # Get the LHS/target of the assignment. + a_def = one_assign.target.name + # Add variable to def sets. + add_to_def_once_sets(a_def, def_once, def_more) + + rhs = one_assign.value + if isinstance(rhs, ir.Global): + # Remember assignments of the form "a = Global(...)" + # Is this a module? + if isinstance(rhs.value, pytypes.ModuleType): + module_assigns[a_def] = rhs.value.__name__ + if isinstance(rhs, ir.Expr) and rhs.op == 'getattr' and rhs.value.name in def_once: + # Remember assignments of the form "a = b.c" + getattr_taken[a_def] = (rhs.value.name, rhs.attr) + if isinstance(rhs, ir.Expr) and rhs.op == 'call' and rhs.func.name in getattr_taken: + # If "a" is being called then lookup the getattr definition of "a" + # as above, getting the module variable "b" (base_obj) + # and the attribute "c" (base_attr). + base_obj, base_attr = getattr_taken[rhs.func.name] + if base_obj in module_assigns: + # If we know the definition of the module variable then get the module + # name from module_assigns. + base_mod_name = module_assigns[base_obj] + if not is_const_call(base_mod_name, base_attr): + # Calling a method on an object could modify the object and is thus + # like a def of that object. We call is_const_call to see if this module/attribute + # combination is known to not modify the module state. If we don't know that + # the combination is safe then we have to assume there could be a modification to + # the module and thus add the module variable as defined more than once. + add_to_def_once_sets(base_obj, def_once, def_more) + else: + # Assume the worst and say that base_obj could be modified by the call. + add_to_def_once_sets(base_obj, def_once, def_more) + if isinstance(rhs, ir.Expr) and rhs.op == 'call': + # If a mutable object is passed to a function, then it may be changed and + # therefore can't be hoisted. + # For each argument to the function... + for argvar in rhs.args: + # Get the argument's type. + if isinstance(argvar, ir.Var): + argvar = argvar.name + avtype = typemap[argvar] + # If that type doesn't have a mutable attribute or it does and it's set to + # not mutable then this usage is safe for hoisting. + if getattr(avtype, 'mutable', False): + # Here we have a mutable variable passed to a function so add this variable + # to the def lists. + add_to_def_once_sets(argvar, def_once, def_more) + +def wrap_find_topo(loop_body): + blocks = wrap_loop_body(loop_body) + topo_order = find_topo_order(blocks) + unwrap_loop_body(loop_body) + return topo_order + +def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns): + '''Compute the set of variables defined exactly once in the given set of blocks + and use the given sets for storing which variables are defined once, more than + once and which have had a getattr call on them. + ''' + # For each block in topological order... + topo_order = wrap_find_topo(loop_body) + for label in topo_order: + block = loop_body[label] + # Scan this block and effect changes to def_once, def_more, and getattr_taken + # based on the instructions in that block. + compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns) + # Have to recursively process parfors manually here. + for inst in block.body: + if isinstance(inst, parfor.Parfor): + # Recursively compute for the parfor's init block. + compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns) + # Recursively compute for the parfor's loop body. + compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns) + +def compute_def_once(loop_body, typemap): + '''Compute the set of variables defined exactly once in the given set of blocks. + ''' + def_once = set() # set to hold variables defined exactly once + def_more = set() # set to hold variables defined more than once + getattr_taken = {} + module_assigns = {} + compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns) + return def_once, def_more + +def find_vars(var, varset): + assert isinstance(var, ir.Var) + varset.add(var.name) + return var + +def _hoist_internal(inst, dep_on_param, call_table, hoisted, not_hoisted, + typemap, stored_arrays): + if inst.target.name in stored_arrays: + not_hoisted.append((inst, "stored array")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because the created array is stored.") + return False + + target_type = typemap[inst.target.name] + + uses = set() + # Get vars used by this statement. + visit_vars_inner(inst.value, find_vars, uses) + # Filter out input parameters from the set of variable usages. + unhoistable = {assgn.target.name for assgn, _ in not_hoisted} + use_unhoist = uses & unhoistable + diff = uses.difference(dep_on_param) + diff |= use_unhoist + if config.DEBUG_ARRAY_OPT >= 1: + print("_hoist_internal:", inst, "uses:", uses, "diff:", diff) + if len(diff) == 0 and is_pure(inst.value, None, call_table): + if config.DEBUG_ARRAY_OPT >= 1: + print("Will hoist instruction", inst, target_type) + hoisted.append(inst) + if not isinstance(target_type, types.npytypes.Array): + dep_on_param += [inst.target.name] + return True + else: + if len(diff) > 0: + not_hoisted.append((inst, "dependency")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because of a dependency.") + else: + not_hoisted.append((inst, "not pure")) + if config.DEBUG_ARRAY_OPT >= 1: + print("Instruction", inst, "could not be hoisted because it isn't pure.") + return False + +def find_setitems_block(setitems, itemsset, block, typemap): + for inst in block.body: + if isinstance(inst, (ir.StaticSetItem, ir.SetItem)): + setitems.add(inst.target.name) + # If we store a non-mutable object into an array then that is safe to hoist. + # If the stored object is mutable and you hoist then multiple entries in the + # outer array could reference the same object and changing one index would then + # change other indices. + if getattr(typemap[inst.value.name], "mutable", False): + itemsset.add(inst.value.name) + elif isinstance(inst, parfor.Parfor): + find_setitems_block(setitems, itemsset, inst.init_block, typemap) + find_setitems_body(setitems, itemsset, inst.loop_body, typemap) + elif isinstance(inst, ir.Assign): + # If something of mutable type is given to a build_tuple or + # used in a call then consider it unanalyzable and so + # unavailable for hoisting. + rhs = inst.value + def add_to_itemset(item): + assert isinstance(item, ir.Var), rhs + if getattr(typemap[item.name], "mutable", False): + itemsset.add(item.name) + + if isinstance(rhs, ir.Expr): + if rhs.op in ["build_tuple", "build_list", "build_set"]: + for item in rhs.items: + add_to_itemset(item) + elif rhs.op == "build_map": + for pair in rhs.items: + for item in pair: + add_to_itemset(item) + elif rhs.op == "call": + for item in list(rhs.args) + [x[1] for x in rhs.kws]: + add_to_itemset(item) + +def find_setitems_body(setitems, itemsset, loop_body, typemap): + """ + Find the arrays that are written into (goes into setitems) and the + mutable objects (mostly arrays) that are written into other arrays + (goes into itemsset). + """ + for label, block in loop_body.items(): + find_setitems_block(setitems, itemsset, block, typemap) + +def empty_container_allocator_hoist(inst, dep_on_param, call_table, hoisted, + not_hoisted, typemap, stored_arrays): + if (isinstance(inst, ir.Assign) and + isinstance(inst.value, ir.Expr) and + inst.value.op == 'call' and + inst.value.func.name in call_table): + call_list = call_table[inst.value.func.name] + if call_list == ['empty', np]: + return _hoist_internal(inst, dep_on_param, call_table, hoisted, + not_hoisted, typemap, stored_arrays) + return False + +def hoist(parfor_params, loop_body, typemap, wrapped_blocks): + dep_on_param = copy.copy(parfor_params) + hoisted = [] + not_hoisted = [] + + # Compute the set of variable defined exactly once in the loop body. + def_once, def_more = compute_def_once(loop_body, typemap) + (call_table, reverse_call_table) = get_call_table(wrapped_blocks) + + setitems = set() + itemsset = set() + find_setitems_body(setitems, itemsset, loop_body, typemap) + dep_on_param = list(set(dep_on_param).difference(setitems)) + if config.DEBUG_ARRAY_OPT >= 1: + print("hoist - def_once:", def_once, "setitems:", setitems, "itemsset:", itemsset, "dep_on_param:", dep_on_param, "parfor_params:", parfor_params) + for si in setitems: + add_to_def_once_sets(si, def_once, def_more) + + for label, block in loop_body.items(): + new_block = [] + for inst in block.body: + if empty_container_allocator_hoist(inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, itemsset): + continue + elif isinstance(inst, ir.Assign) and inst.target.name in def_once: + if _hoist_internal(inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, itemsset): + # don't add this instruction to the block since it is + # hoisted + continue + elif isinstance(inst, parfor.Parfor): + new_init_block = [] + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor") + inst.dump() + for ib_inst in inst.init_block.body: + if empty_container_allocator_hoist(ib_inst, dep_on_param, + call_table, hoisted, not_hoisted, typemap, itemsset): + continue + elif (isinstance(ib_inst, ir.Assign) and + ib_inst.target.name in def_once): + if _hoist_internal(ib_inst, dep_on_param, call_table, + hoisted, not_hoisted, typemap, + itemsset): + # don't add this instruction to the block since it is hoisted + continue + new_init_block.append(ib_inst) + inst.init_block.body = new_init_block + + new_block.append(inst) + block.body = new_block + return hoisted, not_hoisted + +def redtyp_is_scalar(redtype): + return not isinstance(redtype, types.npytypes.Array) + +def redtyp_to_redarraytype(redtyp): + """Go from a reducation variable type to a reduction array type used to hold + per-worker results. + """ + redarrdim = 1 + # If the reduction type is an array then allocate reduction array with ndim+1 dimensions. + if isinstance(redtyp, types.npytypes.Array): + redarrdim += redtyp.ndim + # We don't create array of array but multi-dimensional reduction array with same dtype. + redtyp = redtyp.dtype + return types.npytypes.Array(redtyp, redarrdim, "C") + +def redarraytype_to_sig(redarraytyp): + """Given a reduction array type, find the type of the reduction argument to the gufunc. + """ + assert isinstance(redarraytyp, types.npytypes.Array) + return types.npytypes.Array(redarraytyp.dtype, redarraytyp.ndim, redarraytyp.layout) + +def legalize_names_with_typemap(names, typemap): + """ We use ir_utils.legalize_names to replace internal IR variable names + containing illegal characters (e.g. period) with a legal character + (underscore) so as to create legal variable names. + The original variable names are in the typemap so we also + need to add the legalized name to the typemap as well. + """ + outdict = legalize_names(names) + # For each pair in the dict of legalized names... + for x, y in outdict.items(): + # If the name had some legalization change to it... + if x != y: + # Set the type of the new name the same as the type of the old name. + typemap[y] = typemap[x] + return outdict + +def to_scalar_from_0d(x): + if isinstance(x, types.ArrayCompatible): + if x.ndim == 0: + return x.dtype + return x + +def _create_gufunc_for_parfor_body( + lowerer, + parfor, + typemap, + typingctx, + targetctx, + flags, + locals, + has_aliases, + index_var_typ, + races): + ''' + Takes a parfor and creates a gufunc function for its body. + There are two parts to this function. + 1) Code to iterate across the iteration space as defined by the schedule. + 2) The parfor body that does the work for a single point in the iteration space. + Part 1 is created as Python text for simplicity with a sentinel assignment to mark the point + in the IR where the parfor body should be added. + This Python text is 'exec'ed into existence and its IR retrieved with run_frontend. + The IR is scanned for the sentinel assignment where that basic block is split and the IR + for the parfor body inserted. + ''' + if config.DEBUG_ARRAY_OPT >= 1: + print("starting _create_gufunc_for_parfor_body") + + loc = parfor.init_block.loc + + # The parfor body and the main function body share ir.Var nodes. + # We have to do some replacements of Var names in the parfor body to make them + # legal parameter names. If we don't copy then the Vars in the main function also + # would incorrectly change their name. + loop_body = copy.copy(parfor.loop_body) + remove_dels(loop_body) + + parfor_dim = len(parfor.loop_nests) + loop_indices = [l.index_variable.name for l in parfor.loop_nests] + + # Get all the parfor params. + parfor_params = parfor.params + # Get just the outputs of the parfor. + parfor_outputs = numba.parfors.parfor.get_parfor_outputs(parfor, parfor_params) + # Get all parfor reduction vars, and operators. + typemap = lowerer.fndesc.typemap + parfor_redvars, parfor_reddict = numba.parfors.parfor.get_parfor_reductions( + lowerer.func_ir, parfor, parfor_params, lowerer.fndesc.calltypes) + # Compute just the parfor inputs as a set difference. + parfor_inputs = sorted( + list( + set(parfor_params) - + set(parfor_outputs) - + set(parfor_redvars))) + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_params = ", parfor_params, " ", type(parfor_params)) + print("parfor_outputs = ", parfor_outputs, " ", type(parfor_outputs)) + print("parfor_inputs = ", parfor_inputs, " ", type(parfor_inputs)) + print("parfor_redvars = ", parfor_redvars, " ", type(parfor_redvars)) + + # ------------------------------------------------------------------------- + # Convert tuples to individual parameters. + tuple_expanded_parfor_inputs = [] + tuple_var_to_expanded_names = {} + expanded_name_to_tuple_var = {} + next_expanded_tuple_var = 0 + parfor_tuple_params = [] + # For each input to the parfor. + for pi in parfor_inputs: + # Get the type of the input. + pi_type = typemap[pi] + # If it is a UniTuple or Tuple we will do the conversion. + if isinstance(pi_type, types.UniTuple) or isinstance(pi_type, types.NamedUniTuple): + # Get the size and dtype of the tuple. + tuple_count = pi_type.count + tuple_dtype = pi_type.dtype + # Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length. + assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE) + this_var_expansion = [] + for i in range(tuple_count): + # Generate a new name for the individual part of the tuple var. + expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var) + # Add that name to the new list of inputs to the gufunc. + tuple_expanded_parfor_inputs.append(expanded_name) + this_var_expansion.append(expanded_name) + # Remember a mapping from new param name to original tuple + # var and the index within the tuple. + expanded_name_to_tuple_var[expanded_name] = (pi, i) + next_expanded_tuple_var += 1 + # Set the type of the new parameter. + typemap[expanded_name] = tuple_dtype + # Remember a mapping from the original tuple var to the + # individual parts. + tuple_var_to_expanded_names[pi] = this_var_expansion + parfor_tuple_params.append(pi) + elif isinstance(pi_type, types.Tuple) or isinstance(pi_type, types.NamedTuple): + # This is the same as above for UniTuple except that each part of + # the tuple can have a different type and we fetch that type with + # pi_type.types[offset]. + tuple_count = pi_type.count + tuple_types = pi_type.types + # Only do tuples up to config.PARFOR_MAX_TUPLE_SIZE length. + assert(tuple_count <= config.PARFOR_MAX_TUPLE_SIZE) + this_var_expansion = [] + for i in range(tuple_count): + expanded_name = "expanded_tuple_var_" + str(next_expanded_tuple_var) + tuple_expanded_parfor_inputs.append(expanded_name) + this_var_expansion.append(expanded_name) + expanded_name_to_tuple_var[expanded_name] = (pi, i) + next_expanded_tuple_var += 1 + typemap[expanded_name] = tuple_types[i] + tuple_var_to_expanded_names[pi] = this_var_expansion + parfor_tuple_params.append(pi) + else: + tuple_expanded_parfor_inputs.append(pi) + parfor_inputs = tuple_expanded_parfor_inputs + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_inputs post tuple handling = ", parfor_inputs, " ", type(parfor_inputs)) + # ------------------------------------------------------------------------- + + races = races.difference(set(parfor_redvars)) + for race in races: + msg = ("Variable %s used in parallel loop may be written " + "to simultaneously by multiple workers and may result " + "in non-deterministic or unintended results." % race) + warnings.warn(NumbaParallelSafetyWarning(msg, loc)) + replace_var_with_array(races, loop_body, typemap, lowerer.fndesc.calltypes) + + # Reduction variables are represented as arrays, so they go under + # different names. + parfor_redarrs = [] + parfor_red_arg_types = [] + for var in parfor_redvars: + arr = var + "_arr" + parfor_redarrs.append(arr) + redarraytype = redtyp_to_redarraytype(typemap[var]) + parfor_red_arg_types.append(redarraytype) + redarrsig = redarraytype_to_sig(redarraytype) + if arr in typemap: + assert(typemap[arr] == redarrsig) + else: + typemap[arr] = redarrsig + + # Reorder all the params so that inputs go first then outputs. + parfor_params = parfor_inputs + parfor_outputs + parfor_redarrs + + if config.DEBUG_ARRAY_OPT >= 1: + print("parfor_params = ", parfor_params, " ", type(parfor_params)) + print("loop_indices = ", loop_indices, " ", type(loop_indices)) + print("loop_body = ", loop_body, " ", type(loop_body)) + _print_body(loop_body) + + # Some Var are not legal parameter names so create a dict of potentially illegal + # param name to guaranteed legal name. + param_dict = legalize_names_with_typemap(parfor_params + parfor_redvars + parfor_tuple_params, typemap) + if config.DEBUG_ARRAY_OPT >= 1: + print( + "param_dict = ", + sorted( + param_dict.items()), + " ", + type(param_dict)) + + # Some loop_indices are not legal parameter names so create a dict of potentially illegal + # loop index to guaranteed legal name. + ind_dict = legalize_names_with_typemap(loop_indices, typemap) + # Compute a new list of legal loop index names. + legal_loop_indices = [ind_dict[v] for v in loop_indices] + if config.DEBUG_ARRAY_OPT >= 1: + print("ind_dict = ", sorted(ind_dict.items()), " ", type(ind_dict)) + print( + "legal_loop_indices = ", + legal_loop_indices, + " ", + type(legal_loop_indices)) + for pd in parfor_params: + print("pd = ", pd) + print("pd type = ", typemap[pd], " ", type(typemap[pd])) + + # Get the types of each parameter. + param_types = [to_scalar_from_0d(typemap[v]) for v in parfor_params] + # Calculate types of args passed to gufunc. + func_arg_types = [typemap[v] for v in (parfor_inputs + parfor_outputs)] + parfor_red_arg_types + if config.DEBUG_ARRAY_OPT >= 1: + print("new param_types:", param_types) + print("new func_arg_types:", func_arg_types) + + # Replace illegal parameter names in the loop body with legal ones. + replace_var_names(loop_body, param_dict) + # remember the name before legalizing as the actual arguments + parfor_args = parfor_params + # Change parfor_params to be legal names. + parfor_params = [param_dict[v] for v in parfor_params] + parfor_params_orig = parfor_params + + parfor_params = [] + ascontig = False + for pindex in range(len(parfor_params_orig)): + if (ascontig and + pindex < len(parfor_inputs) and + isinstance(param_types[pindex], types.npytypes.Array)): + parfor_params.append(parfor_params_orig[pindex]+"param") + else: + parfor_params.append(parfor_params_orig[pindex]) + + # Change parfor body to replace illegal loop index vars with legal ones. + replace_var_names(loop_body, ind_dict) + loop_body_var_table = get_name_var_table(loop_body) + sentinel_name = get_unused_var_name("__sentinel__", loop_body_var_table) + + if config.DEBUG_ARRAY_OPT >= 1: + print( + "legal parfor_params = ", + parfor_params, + " ", + type(parfor_params)) + + # Determine the unique names of the scheduling and gufunc functions. + # sched_func_name = "__numba_parfor_sched_%s" % (hex(hash(parfor)).replace("-", "_")) + gufunc_name = "__numba_parfor_gufunc_%s" % ( + hex(hash(parfor)).replace("-", "_")) + if config.DEBUG_ARRAY_OPT: + # print("sched_func_name ", type(sched_func_name), " ", sched_func_name) + print("gufunc_name ", type(gufunc_name), " ", gufunc_name) + + gufunc_txt = "" + + # Create the gufunc function. + gufunc_txt += "def " + gufunc_name + \ + "(sched, " + (", ".join(parfor_params)) + "):\n" + + globls = {"np": np, "numba": numba} + + # First thing in the gufunc, we reconstruct tuples from their + # individual parts, e.g., orig_tup_name = (part1, part2,). + # The rest of the code of the function will use the original tuple name. + for tup_var, exp_names in tuple_var_to_expanded_names.items(): + tup_type = typemap[tup_var] + gufunc_txt += " " + param_dict[tup_var] + # Determine if the tuple is a named tuple. + if (isinstance(tup_type, types.NamedTuple) or + isinstance(tup_type, types.NamedUniTuple)): + named_tup = True + else: + named_tup = False + + if named_tup: + # It is a named tuple so try to find the global that defines the + # named tuple. + func_def = guard(get_definition, lowerer.func_ir, tup_var) + named_tuple_def = None + if config.DEBUG_ARRAY_OPT: + print("func_def:", func_def, type(func_def)) + if func_def is not None: + if (isinstance(func_def, ir.Expr) and + func_def.op == 'call'): + named_tuple_def = guard(get_definition, lowerer.func_ir, func_def.func) + if config.DEBUG_ARRAY_OPT: + print("named_tuple_def:", named_tuple_def, type(named_tuple_def)) + elif isinstance(func_def, ir.Arg): + named_tuple_def = typemap[func_def.name] + if config.DEBUG_ARRAY_OPT: + print("named_tuple_def:", named_tuple_def, + type(named_tuple_def), named_tuple_def.name) + if named_tuple_def is not None: + if (isinstance(named_tuple_def, ir.Global) or + isinstance(named_tuple_def, ir.FreeVar)): + gval = named_tuple_def.value + if config.DEBUG_ARRAY_OPT: + print("gval:", gval, type(gval)) + globls[named_tuple_def.name] = gval + elif isinstance(named_tuple_def, types.containers.BaseNamedTuple): + named_tuple_name = named_tuple_def.name.split('(')[0] + if config.DEBUG_ARRAY_OPT: + print("name:", named_tuple_name, + named_tuple_def.instance_class, + type(named_tuple_def.instance_class)) + globls[named_tuple_name] = named_tuple_def.instance_class + else: + if config.DEBUG_ARRAY_OPT: + print("Didn't find definition of namedtuple for globls.") + raise CompilerError("Could not find definition of " + str(tup_var), + tup_var.loc) + gufunc_txt += " = " + tup_type.instance_class.__name__ + "(" + for name, field_name in zip(exp_names, tup_type.fields): + gufunc_txt += field_name + "=" + param_dict[name] + "," + else: + # Just a regular tuple so use (part0, part1, ...) + gufunc_txt += " = (" + ", ".join([param_dict[x] for x in exp_names]) + if len(exp_names) == 1: + # Add comma for tuples with singular values. We can't unilaterally + # add a comma always because (,) isn't valid. + gufunc_txt += "," + + gufunc_txt += ")\n" + + for pindex in range(len(parfor_inputs)): + if ascontig and isinstance(param_types[pindex], types.npytypes.Array): + gufunc_txt += (" " + parfor_params_orig[pindex] + + " = np.ascontiguousarray(" + parfor_params[pindex] + ")\n") + + gufunc_thread_id_var = "ParallelAcceleratorGufuncThreadId" + + if len(parfor_redarrs) > 0: + gufunc_txt += " " + gufunc_thread_id_var + " = " + gufunc_txt += "numba.np.ufunc.parallel._iget_thread_id()\n" + + # Add initialization of reduction variables + for arr, var in zip(parfor_redarrs, parfor_redvars): + gufunc_txt += " " + param_dict[var] + \ + "=" + param_dict[arr] + "[" + gufunc_thread_id_var + "]\n" + if config.DEBUG_ARRAY_OPT_RUNTIME: + gufunc_txt += " print(\"thread id =\", ParallelAcceleratorGufuncThreadId)\n" + gufunc_txt += " print(\"initial reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + "," + param_dict[var] + ".shape)\n" + gufunc_txt += " print(\"reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + "," + param_dict[arr] + ".shape)\n" + + # For each dimension of the parfor, create a for loop in the generated gufunc function. + # Iterate across the proper values extracted from the schedule. + # The form of the schedule is start_dim0, start_dim1, ..., start_dimN, end_dim0, + # end_dim1, ..., end_dimN + for eachdim in range(parfor_dim): + for indent in range(eachdim + 1): + gufunc_txt += " " + sched_dim = eachdim + gufunc_txt += ("for " + + legal_loop_indices[eachdim] + + " in range(sched[" + + str(sched_dim) + + "], sched[" + + str(sched_dim + + parfor_dim) + + "] + np.uint8(1)):\n") + + if config.DEBUG_ARRAY_OPT_RUNTIME: + for indent in range(parfor_dim + 1): + gufunc_txt += " " + gufunc_txt += "print(" + for eachdim in range(parfor_dim): + gufunc_txt += "\"" + legal_loop_indices[eachdim] + "\"," + legal_loop_indices[eachdim] + "," + gufunc_txt += ")\n" + + # Add the sentinel assignment so that we can find the loop body position + # in the IR. + for indent in range(parfor_dim + 1): + gufunc_txt += " " + gufunc_txt += sentinel_name + " = 0\n" + # Add assignments of reduction variables (for returning the value) + for arr, var in zip(parfor_redarrs, parfor_redvars): + if config.DEBUG_ARRAY_OPT_RUNTIME: + gufunc_txt += " print(\"final reduction value\",ParallelAcceleratorGufuncThreadId," + param_dict[var] + ")\n" + gufunc_txt += " print(\"final reduction array\",ParallelAcceleratorGufuncThreadId," + param_dict[arr] + ")\n" + # After the gufunc loops, copy the accumulated temp value back to reduction array. + gufunc_txt += " " + param_dict[arr] + \ + "[" + gufunc_thread_id_var + "] = " + param_dict[var] + "\n" + gufunc_txt += " return None\n" + + if config.DEBUG_ARRAY_OPT: + print("gufunc_txt = ", type(gufunc_txt), "\n", gufunc_txt) + print("globls:", globls, type(globls)) + # Force gufunc outline into existence. + locls = {} + exec(gufunc_txt, globls, locls) + gufunc_func = locls[gufunc_name] + + if config.DEBUG_ARRAY_OPT: + print("gufunc_func = ", type(gufunc_func), "\n", gufunc_func) + # Get the IR for the gufunc outline. + gufunc_ir = compiler.run_frontend(gufunc_func) + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir dump ", type(gufunc_ir)) + gufunc_ir.dump() + print("loop_body dump ", type(loop_body)) + _print_body(loop_body) + + # rename all variables in gufunc_ir afresh + var_table = get_name_var_table(gufunc_ir.blocks) + new_var_dict = {} + reserved_names = [sentinel_name] + \ + list(param_dict.values()) + legal_loop_indices + for name, var in var_table.items(): + if not (name in reserved_names): + new_var_dict[name] = parfor.init_block.scope.redefine(name, loc).name + replace_var_names(gufunc_ir.blocks, new_var_dict) + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir dump after renaming ") + gufunc_ir.dump() + gufunc_param_types = [types.npytypes.Array( + index_var_typ, 1, "C")] + param_types + if config.DEBUG_ARRAY_OPT: + print( + "gufunc_param_types = ", + type(gufunc_param_types), + "\n", + gufunc_param_types) + + gufunc_stub_last_label = find_max_label(gufunc_ir.blocks) + 1 + + # Add gufunc stub last label to each parfor.loop_body label to prevent + # label conflicts. + loop_body = add_offset_to_labels(loop_body, gufunc_stub_last_label) + # new label for splitting sentinel block + new_label = find_max_label(loop_body) + 1 + + # If enabled, add a print statement after every assignment. + if config.DEBUG_ARRAY_OPT_RUNTIME: + for label, block in loop_body.items(): + new_block = block.copy() + new_block.clear() + loc = block.loc + scope = block.scope + for inst in block.body: + new_block.append(inst) + # Append print after assignment + if isinstance(inst, ir.Assign): + # Only apply to numbers + if typemap[inst.target.name] not in types.number_domain: + continue + + # Make constant string + strval = "{} =".format(inst.target.name) + strconsttyp = types.StringLiteral(strval) + + lhs = scope.redefine("str_const", loc) + # lhs = ir.Var(scope, mk_unique_var("str_const"), loc) + assign_lhs = ir.Assign(value=ir.Const(value=strval, loc=loc), + target=lhs, loc=loc) + typemap[lhs.name] = strconsttyp + new_block.append(assign_lhs) + + # Make print node + print_node = ir.Print(args=[lhs, inst.target], vararg=None, loc=loc) + new_block.append(print_node) + sig = numba.core.typing.signature(types.none, + typemap[lhs.name], + typemap[inst.target.name]) + lowerer.fndesc.calltypes[print_node] = sig + loop_body[label] = new_block + + if config.DEBUG_ARRAY_OPT: + print("parfor loop body") + _print_body(loop_body) + + wrapped_blocks = wrap_loop_body(loop_body) + hoisted, not_hoisted = hoist(parfor_params, loop_body, typemap, wrapped_blocks) + start_block = gufunc_ir.blocks[min(gufunc_ir.blocks.keys())] + start_block.body = start_block.body[:-1] + hoisted + [start_block.body[-1]] + unwrap_loop_body(loop_body) + + # store hoisted into diagnostics + diagnostics = lowerer.metadata['parfor_diagnostics'] + diagnostics.hoist_info[parfor.id] = {'hoisted': hoisted, + 'not_hoisted': not_hoisted} + + if config.DEBUG_ARRAY_OPT: + print("After hoisting") + _print_body(loop_body) + + # Search all the block in the gufunc outline for the sentinel assignment. + for label, block in gufunc_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance( + inst, + ir.Assign) and inst.target.name == sentinel_name: + # We found the sentinel assignment. + loc = inst.loc + scope = block.scope + # split block across __sentinel__ + # A new block is allocated for the statements prior to the sentinel + # but the new block maintains the current block label. + prev_block = ir.Block(scope, loc) + prev_block.body = block.body[:i] + # The current block is used for statements after the sentinel. + block.body = block.body[i + 1:] + # But the current block gets a new label. + body_first_label = min(loop_body.keys()) + + # The previous block jumps to the minimum labelled block of the + # parfor body. + prev_block.append(ir.Jump(body_first_label, loc)) + # Add all the parfor loop body blocks to the gufunc function's + # IR. + for (l, b) in loop_body.items(): + gufunc_ir.blocks[l] = transfer_scope(b, scope) + body_last_label = max(loop_body.keys()) + gufunc_ir.blocks[new_label] = block + gufunc_ir.blocks[label] = prev_block + # Add a jump from the last parfor body block to the block containing + # statements after the sentinel. + gufunc_ir.blocks[body_last_label].append( + ir.Jump(new_label, loc)) + break + else: + continue + break + + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir last dump before renaming") + gufunc_ir.dump() + + gufunc_ir.blocks = rename_labels(gufunc_ir.blocks) + remove_dels(gufunc_ir.blocks) + + if config.DEBUG_ARRAY_OPT: + print("gufunc_ir last dump") + gufunc_ir.dump() + print("flags", flags) + print("typemap", typemap) + + old_alias = flags.noalias + if not has_aliases: + if config.DEBUG_ARRAY_OPT: + print("No aliases found so adding noalias flag.") + flags.noalias = True + + fixup_var_define_in_scope(gufunc_ir.blocks) + + class ParforGufuncCompiler(compiler.CompilerBase): + def define_pipelines(self): + from numba.core.compiler_machinery import PassManager + dpb = compiler.DefaultPassBuilder + pm = PassManager("full_parfor_gufunc") + parfor_gufunc_passes = dpb.define_parfor_gufunc_pipeline(self.state) + pm.passes.extend(parfor_gufunc_passes.passes) + lowering_passes = dpb.define_parfor_gufunc_nopython_lowering_pipeline(self.state) + pm.passes.extend(lowering_passes.passes) + + pm.finalize() + return [pm] + + kernel_func = compiler.compile_ir( + typingctx, + targetctx, + gufunc_ir, + gufunc_param_types, + types.none, + flags, + locals, + pipeline_class=ParforGufuncCompiler) + + flags.noalias = old_alias + + kernel_sig = signature(types.none, *gufunc_param_types) + if config.DEBUG_ARRAY_OPT: + print("finished create_gufunc_for_parfor_body. kernel_sig = ", kernel_sig) + + return kernel_func, parfor_args, kernel_sig, func_arg_types, expanded_name_to_tuple_var + +def replace_var_with_array_in_block(vars, block, typemap, calltypes): + new_block = [] + for inst in block.body: + if isinstance(inst, ir.Assign) and inst.target.name in vars: + loc = inst.loc + scope = inst.target.scope + + const_node = ir.Const(0, loc) + const_var = scope.redefine("$const_ind_0", loc) + typemap[const_var.name] = types.uintp + const_assign = ir.Assign(const_node, const_var, loc) + new_block.append(const_assign) + + val_var = scope.redefine("$val", loc) + typemap[val_var.name] = typemap[inst.target.name] + new_block.append(ir.Assign(inst.value, val_var, loc)) + setitem_node = ir.SetItem(inst.target, const_var, val_var, loc) + calltypes[setitem_node] = signature( + types.none, types.npytypes.Array(typemap[inst.target.name], 1, "C"), types.intp, typemap[inst.target.name]) + new_block.append(setitem_node) + continue + elif isinstance(inst, parfor.Parfor): + replace_var_with_array_internal(vars, {0: inst.init_block}, typemap, calltypes) + replace_var_with_array_internal(vars, inst.loop_body, typemap, calltypes) + + new_block.append(inst) + return new_block + +def replace_var_with_array_internal(vars, loop_body, typemap, calltypes): + for label, block in loop_body.items(): + block.body = replace_var_with_array_in_block(vars, block, typemap, calltypes) + +def replace_var_with_array(vars, loop_body, typemap, calltypes): + replace_var_with_array_internal(vars, loop_body, typemap, calltypes) + for v in vars: + el_typ = typemap[v] + typemap.pop(v, None) + typemap[v] = types.npytypes.Array(el_typ, 1, "C") + +def call_parallel_gufunc(lowerer, cres, gu_signature, outer_sig, expr_args, expr_arg_types, + loop_ranges, redvars, reddict, redarrdict, init_block, index_var_typ, races, + exp_name_to_tuple_var): + ''' + Adds the call to the gufunc function from the main function. + ''' + context = lowerer.context + builder = lowerer.builder + + from numba.np.ufunc.parallel import (build_gufunc_wrapper, + _launch_threads) + + if config.DEBUG_ARRAY_OPT: + print("make_parallel_loop") + print("outer_sig = ", outer_sig.args, outer_sig.return_type, + outer_sig.recvr, outer_sig.pysig) + print("loop_ranges = ", loop_ranges) + print("expr_args", expr_args) + print("expr_arg_types", expr_arg_types) + print("gu_signature", gu_signature) + + # Build the wrapper for GUFunc + args, return_type = sigutils.normalize_signature(outer_sig) + llvm_func = cres.library.get_function(cres.fndesc.llvm_func_name) + sin, sout = gu_signature + + # These are necessary for build_gufunc_wrapper to find external symbols + _launch_threads() + + info = build_gufunc_wrapper(llvm_func, cres, sin, sout, + cache=False, is_parfors=True) + wrapper_name = info.name + cres.library._ensure_finalized() + + if config.DEBUG_ARRAY_OPT: + print("parallel function = ", wrapper_name, cres) + + # loadvars for loop_ranges + def load_range(v): + if isinstance(v, ir.Var): + return lowerer.loadvar(v.name) + else: + return context.get_constant(types.uintp, v) + + num_dim = len(loop_ranges) + for i in range(num_dim): + start, stop, step = loop_ranges[i] + start = load_range(start) + stop = load_range(stop) + assert(step == 1) # We do not support loop steps other than 1 + step = load_range(step) + loop_ranges[i] = (start, stop, step) + + if config.DEBUG_ARRAY_OPT: + print("call_parallel_gufunc loop_ranges[{}] = ".format(i), start, + stop, step) + cgutils.printf(builder, "loop range[{}]: %d %d (%d)\n".format(i), + start, stop, step) + + # Commonly used LLVM types and constants + byte_t = llvmlite.ir.IntType(8) + byte_ptr_t = llvmlite.ir.PointerType(byte_t) + byte_ptr_ptr_t = llvmlite.ir.PointerType(byte_ptr_t) + intp_t = context.get_value_type(types.intp) + uintp_t = context.get_value_type(types.uintp) + intp_ptr_t = llvmlite.ir.PointerType(intp_t) + intp_ptr_ptr_t = llvmlite.ir.PointerType(intp_ptr_t) + uintp_ptr_t = llvmlite.ir.PointerType(uintp_t) + uintp_ptr_ptr_t = llvmlite.ir.PointerType(uintp_ptr_t) + zero = context.get_constant(types.uintp, 0) + one = context.get_constant(types.uintp, 1) + one_type = one.type + sizeof_intp = context.get_abi_sizeof(intp_t) + + # Prepare sched, first pop it out of expr_args, outer_sig, and gu_signature + expr_args.pop(0) + sched_sig = sin.pop(0) + + if config.DEBUG_ARRAY_OPT: + print("Parfor has potentially negative start", index_var_typ.signed) + + if index_var_typ.signed: + sched_type = intp_t + sched_ptr_type = intp_ptr_t + sched_ptr_ptr_type = intp_ptr_ptr_t + else: + sched_type = uintp_t + sched_ptr_type = uintp_ptr_t + sched_ptr_ptr_type = uintp_ptr_ptr_t + + # Call do_scheduling with appropriate arguments + dim_starts = cgutils.alloca_once( + builder, sched_type, size=context.get_constant( + types.uintp, num_dim), name="dim_starts") + dim_stops = cgutils.alloca_once( + builder, sched_type, size=context.get_constant( + types.uintp, num_dim), name="dim_stops") + for i in range(num_dim): + start, stop, step = loop_ranges[i] + if start.type != one_type: + start = builder.sext(start, one_type) + if stop.type != one_type: + stop = builder.sext(stop, one_type) + if step.type != one_type: + step = builder.sext(step, one_type) + # substract 1 because do-scheduling takes inclusive ranges + stop = builder.sub(stop, one) + builder.store( + start, builder.gep( + dim_starts, [ + context.get_constant( + types.uintp, i)])) + builder.store(stop, builder.gep(dim_stops, + [context.get_constant(types.uintp, i)])) + + # Prepare to call get/set parallel_chunksize and get the number of threads. + get_chunksize = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(uintp_t, []), + name="get_parallel_chunksize") + + set_chunksize = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [uintp_t]), + name="set_parallel_chunksize") + + get_num_threads = cgutils.get_or_insert_function( + builder.module, + llvmlite.ir.FunctionType(llvmlite.ir.IntType(types.intp.bitwidth), []), + "get_num_threads") + + # Get the current number of threads. + num_threads = builder.call(get_num_threads, []) + # Get the current chunksize so we can use it and restore the value later. + current_chunksize = builder.call(get_chunksize, []) + + with cgutils.if_unlikely(builder, builder.icmp_signed('<=', num_threads, + num_threads.type(0))): + cgutils.printf(builder, "num_threads: %d\n", num_threads) + context.call_conv.return_user_exc(builder, RuntimeError, + ("Invalid number of threads. " + "This likely indicates a bug in Numba.",)) + + # Call get_sched_size from gufunc_scheduler.cpp that incorporates the size of the work, + # the number of threads and the selected chunk size. This will tell us how many entries + # in the schedule we will need. + get_sched_size_fnty = llvmlite.ir.FunctionType(uintp_t, [uintp_t, uintp_t, intp_ptr_t, intp_ptr_t]) + get_sched_size = cgutils.get_or_insert_function( + builder.module, + get_sched_size_fnty, + name="get_sched_size") + num_divisions = builder.call(get_sched_size, [num_threads, + context.get_constant(types.uintp, num_dim), + dim_starts, + dim_stops]) + # Set the chunksize to zero so that any nested calls get the default chunk size behavior. + builder.call(set_chunksize, [zero]) + + # Each entry in the schedule is 2 times the number of dimensions long. + multiplier = context.get_constant(types.uintp, num_dim * 2) + # Compute the total number of entries in the schedule. + sched_size = builder.mul(num_divisions, multiplier) + + # Prepare to dynamically allocate memory to hold the schedule. + alloc_sched_fnty = llvmlite.ir.FunctionType(sched_ptr_type, [uintp_t]) + alloc_sched_func = cgutils.get_or_insert_function( + builder.module, + alloc_sched_fnty, + name="allocate_sched") + # Call gufunc_scheduler.cpp to allocate the schedule. + # This may or may not do pooling. + alloc_space = builder.call(alloc_sched_func, [sched_size]) + # Allocate a slot in the entry block to store the schedule pointer. + sched = cgutils.alloca_once(builder, sched_ptr_type) + # Store the schedule pointer into that slot. + builder.store(alloc_space, sched) + + debug_flag = 1 if config.DEBUG_ARRAY_OPT else 0 + scheduling_fnty = llvmlite.ir.FunctionType( + intp_ptr_t, [uintp_t, intp_ptr_t, intp_ptr_t, uintp_t, sched_ptr_type, intp_t]) + if index_var_typ.signed: + do_scheduling = cgutils.get_or_insert_function(builder.module, + scheduling_fnty, + name="do_scheduling_signed") + else: + do_scheduling = cgutils.get_or_insert_function(builder.module, + scheduling_fnty, + name="do_scheduling_unsigned") + + # Call the scheduling routine that decides how to break up the work. + builder.call( + do_scheduling, [ + context.get_constant( + types.uintp, num_dim), dim_starts, dim_stops, num_divisions, + builder.load(sched), context.get_constant( + types.intp, debug_flag)]) + + # Get the LLVM vars for the Numba IR reduction array vars. + redarrs = [lowerer.loadvar(redarrdict[x].name) for x in redvars] + + nredvars = len(redvars) + ninouts = len(expr_args) - nredvars + + def load_potential_tuple_var(x): + """Given a variable name, if that variable is not a new name + introduced as the extracted part of a tuple then just return + the variable loaded from its name. However, if the variable + does represent part of a tuple, as recognized by the name of + the variable being present in the exp_name_to_tuple_var dict, + then we load the original tuple var instead that we get from + the dict and then extract the corresponding element of the + tuple, also stored and returned to use in the dict (i.e., offset). + """ + if x in exp_name_to_tuple_var: + orig_tup, offset = exp_name_to_tuple_var[x] + tup_var = lowerer.loadvar(orig_tup) + res = builder.extract_value(tup_var, offset) + return res + else: + return lowerer.loadvar(x) + + # ---------------------------------------------------------------------------- + # Prepare arguments: args, shapes, steps, data + all_args = [load_potential_tuple_var(x) for x in expr_args[:ninouts]] + redarrs + num_args = len(all_args) + num_inps = len(sin) + 1 + args = cgutils.alloca_once( + builder, + byte_ptr_t, + size=context.get_constant( + types.intp, + 1 + num_args), + name="pargs") + array_strides = [] + # sched goes first + builder.store(builder.bitcast(builder.load(sched), byte_ptr_t), args) + array_strides.append(context.get_constant(types.intp, sizeof_intp)) + rv_to_arg_dict = {} + # followed by other arguments + for i in range(num_args): + arg = all_args[i] + var = expr_args[i] + aty = expr_arg_types[i] + dst = builder.gep(args, [context.get_constant(types.intp, i + 1)]) + if i >= ninouts: # reduction variables + ary = context.make_array(aty)(context, builder, arg) + strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim) + # Start from 1 because we skip the first dimension of length num_threads just like sched. + for j in range(len(strides)): + array_strides.append(strides[j]) + builder.store(builder.bitcast(ary.data, byte_ptr_t), dst) + elif isinstance(aty, types.ArrayCompatible): + if var in races: + typ = (context.get_data_type(aty.dtype) + if aty.dtype != types.boolean + else llvmlite.ir.IntType(1)) + + rv_arg = cgutils.alloca_once(builder, typ) + builder.store(arg, rv_arg) + builder.store(builder.bitcast(rv_arg, byte_ptr_t), dst) + rv_to_arg_dict[var] = (arg, rv_arg) + + array_strides.append(context.get_constant(types.intp, context.get_abi_sizeof(typ))) + else: + ary = context.make_array(aty)(context, builder, arg) + strides = cgutils.unpack_tuple(builder, ary.strides, aty.ndim) + for j in range(len(strides)): + array_strides.append(strides[j]) + builder.store(builder.bitcast(ary.data, byte_ptr_t), dst) + else: + if i < num_inps: + # Scalar input, need to store the value in an array of size 1 + if isinstance(aty, types.Optional): + # Unpack optional type + unpacked_aty = aty.type + arg = context.cast(builder, arg, aty, unpacked_aty) + else: + unpacked_aty = aty + typ = (context.get_data_type(unpacked_aty) + if not isinstance(unpacked_aty, types.Boolean) + else llvmlite.ir.IntType(1)) + ptr = cgutils.alloca_once(builder, typ) + builder.store(arg, ptr) + else: + # Scalar output, must allocate + typ = (context.get_data_type(aty) + if not isinstance(aty, types.Boolean) + else llvmlite.ir.IntType(1)) + ptr = cgutils.alloca_once(builder, typ) + builder.store(builder.bitcast(ptr, byte_ptr_t), dst) + + # ---------------------------------------------------------------------------- + # Next, we prepare the individual dimension info recorded in gu_signature + sig_dim_dict = {} + occurrences = [] + occurrences = [sched_sig[0]] + sig_dim_dict[sched_sig[0]] = context.get_constant(types.intp, 2 * num_dim) + assert len(expr_args) == len(all_args) + assert len(expr_args) == len(expr_arg_types) + assert len(expr_args) == len(sin + sout) + assert len(expr_args) == len(outer_sig.args[1:]) + for var, arg, aty, gu_sig in zip(expr_args, all_args, + expr_arg_types, sin + sout): + if isinstance(aty, types.npytypes.Array): + i = aty.ndim - len(gu_sig) + else: + i = 0 + if config.DEBUG_ARRAY_OPT: + print("var =", var, "gu_sig =", gu_sig, "type =", aty, "i =", i) + + for dim_sym in gu_sig: + if config.DEBUG_ARRAY_OPT: + print("var = ", var, " type = ", aty) + if var in races: + sig_dim_dict[dim_sym] = context.get_constant(types.intp, 1) + else: + ary = context.make_array(aty)(context, builder, arg) + shapes = cgutils.unpack_tuple(builder, ary.shape, aty.ndim) + sig_dim_dict[dim_sym] = shapes[i] + + if not (dim_sym in occurrences): + if config.DEBUG_ARRAY_OPT: + print("dim_sym = ", dim_sym, ", i = ", i) + cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym]) + occurrences.append(dim_sym) + i = i + 1 + + # ---------------------------------------------------------------------------- + # Prepare shapes, which is a single number (outer loop size), followed by + # the size of individual shape variables. + nshapes = len(sig_dim_dict) + 1 + shapes = cgutils.alloca_once(builder, intp_t, size=nshapes, name="pshape") + # For now, outer loop size is the same as number of threads + builder.store(num_divisions, shapes) + # Individual shape variables go next + i = 1 + for dim_sym in occurrences: + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, dim_sym + " = %d\n", sig_dim_dict[dim_sym]) + builder.store( + sig_dim_dict[dim_sym], builder.gep( + shapes, [ + context.get_constant( + types.intp, i)])) + i = i + 1 + + # ---------------------------------------------------------------------------- + # Prepare steps for each argument. Note that all steps are counted in + # bytes. + num_steps = num_args + 1 + len(array_strides) + steps = cgutils.alloca_once( + builder, intp_t, size=context.get_constant( + types.intp, num_steps), name="psteps") + # First goes the step size for sched, which is 2 * num_dim + builder.store(context.get_constant(types.intp, 2 * num_dim * sizeof_intp), + steps) + # The steps for all others are 0, except for reduction results. + for i in range(num_args): + # steps are strides from one thread to the next + stepsize = zero + + dst = builder.gep(steps, [context.get_constant(types.intp, 1 + i)]) + builder.store(stepsize, dst) + for j in range(len(array_strides)): + dst = builder.gep( + steps, [ + context.get_constant( + types.intp, 1 + num_args + j)]) + builder.store(array_strides[j], dst) + + # ---------------------------------------------------------------------------- + # prepare data + data = cgutils.get_null_value(byte_ptr_t) + + fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), + [byte_ptr_ptr_t, intp_ptr_t, + intp_ptr_t, byte_ptr_t]) + + fn = cgutils.get_or_insert_function(builder.module, fnty, wrapper_name) + context.active_code_library.add_linking_library(info.library) + + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, "before calling kernel %p\n", fn) + builder.call(fn, [args, shapes, steps, data]) + if config.DEBUG_ARRAY_OPT: + cgutils.printf(builder, "after calling kernel %p\n", fn) + + builder.call(set_chunksize, [current_chunksize]) + + # Deallocate the schedule's memory. + dealloc_sched_fnty = llvmlite.ir.FunctionType(llvmlite.ir.VoidType(), [sched_ptr_type]) + dealloc_sched_func = cgutils.get_or_insert_function( + builder.module, + dealloc_sched_fnty, + name="deallocate_sched") + builder.call(dealloc_sched_func, [builder.load(sched)]) + + for k, v in rv_to_arg_dict.items(): + arg, rv_arg = v + only_elem_ptr = builder.gep(rv_arg, [context.get_constant(types.intp, 0)]) + builder.store(builder.load(only_elem_ptr), lowerer.getvar(k)) + + context.active_code_library.add_linking_library(cres.library) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..66d583d8870efda8e49984bcda2e79905b1a5696 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/parfors/parfor_lowering_utils.py @@ -0,0 +1,216 @@ +from collections import namedtuple + +from numba.core import types, ir +from numba.core.typing import signature + + +_CallableNode = namedtuple("BoundFunc", ["func", "sig"]) + + +class ParforLoweringBuilder: + """Helper class for building Numba-IR and lowering for Parfor. + """ + def __init__(self, lowerer, scope, loc): + self._lowerer = lowerer + self._scope = scope + self._loc = loc + + @property + def _context(self): + return self._lowerer.context + + @property + def _typingctx(self): + return self._context.typing_context + + @property + def _typemap(self): + return self._lowerer.fndesc.typemap + + @property + def _calltypes(self): + return self._lowerer.fndesc.calltypes + + def bind_global_function(self, fobj, ftype, args, kws=None): + """Binds a global function to a variable. + + Parameters + ---------- + fobj : object + The function to be bound. + ftype : types.Type + args : Sequence[types.Type] + kws : Mapping[str, types.Type] + + Returns + ------- + callable: _CallableNode + """ + if kws is None: + kws = {} + loc = self._loc + varname = f"{fobj.__name__}_func" + gvname = f"{fobj.__name__}" + + func_sig = self._typingctx.resolve_function_type(ftype, args, kws) + func_var = self.assign( + rhs=ir.Global(gvname, fobj, loc=loc), typ=ftype, name=varname + ) + return _CallableNode(func=func_var, sig=func_sig) + + def make_const_variable(self, cval, typ, name="pf_const") -> ir.Var: + """Makes a constant variable + + Parameters + ---------- + cval : object + The constant value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + return self.assign( + rhs=ir.Const(cval, loc=self._loc), typ=typ, name=name + ) + + def make_tuple_variable(self, varlist, name="pf_tuple") -> ir.Var: + """Makes a tuple variable + + Parameters + ---------- + varlist : Sequence[ir.Var] + Variables containing the values to be stored. + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + vartys = [self._typemap[x.name] for x in varlist] + tupty = types.Tuple.from_types(vartys) + return self.assign( + rhs=ir.Expr.build_tuple(varlist, loc), typ=tupty, name=name + ) + + def assign(self, rhs, typ, name="pf_assign") -> ir.Var: + """Assign a value to a new variable + + Parameters + ---------- + rhs : object + The value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + var = self._scope.redefine(name, loc) + self._typemap[var.name] = typ + assign = ir.Assign(rhs, var, loc) + self._lowerer.lower_inst(assign) + return var + + def assign_inplace(self, rhs, typ, name) -> ir.Var: + """Assign a value to a new variable or inplace if it already exist + + Parameters + ---------- + rhs : object + The value + typ : types.Type + type of the value + name : str + variable name to store to + + Returns + ------- + res : ir.Var + """ + loc = self._loc + var = ir.Var(self._scope, name, loc) + assign = ir.Assign(rhs, var, loc) + self._typemap.setdefault(var.name, typ) + self._lowerer.lower_inst(assign) + return var + + def call(self, callable_node, args, kws=None) -> ir.Expr: + """Call a bound callable + + Parameters + ---------- + callable_node : _CallableNode + The callee + args : Sequence[ir.Var] + kws : Mapping[str, ir.Var] + + Returns + ------- + res : ir.Expr + The expression node for the return value of the call + """ + if kws is None: + kws = {} + call = ir.Expr.call(callable_node.func, args, kws, loc=self._loc) + self._calltypes[call] = callable_node.sig + return call + + def setitem(self, obj, index, val) -> ir.SetItem: + """Makes a setitem call + + Parameters + ---------- + obj : ir.Var + the object being indexed + index : ir.Var + the index + val : ir.Var + the value to be stored + + Returns + ------- + res : ir.SetItem + """ + loc = self._loc + tm = self._typemap + setitem = ir.SetItem(obj, index, val, loc=loc) + self._lowerer.fndesc.calltypes[setitem] = signature( + types.none, tm[obj.name], tm[index.name], tm[val.name] + ) + self._lowerer.lower_inst(setitem) + return setitem + + def getitem(self, obj, index, typ) -> ir.Expr: + """Makes a getitem call + + Parameters + ---------- + obj : ir.Var + the object being indexed + index : ir.Var + the index + val : ir.Var + the ty + + Returns + ------- + res : ir.Expr + the retrieved value + """ + tm = self._typemap + getitem = ir.Expr.getitem(obj, index, loc=self._loc) + self._lowerer.fndesc.calltypes[getitem] = signature( + typ, tm[obj.name], tm[index.name], + ) + return getitem diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c797fecd1c3863e7e26375aa69835dc82f297e25 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/__init__.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- + +import warnings +from numba.core.errors import NumbaPendingDeprecationWarning +# The pycc module requires setuptools. +try: + import setuptools +except ImportError: + msg = "The 'setuptools' package is required at runtime for pycc support." + raise ImportError(msg) + +# Public API +from .cc import CC +from .decorators import export, exportmany + +# If use of anything is attempted through the `pycc` import path this warning +# will be shown. +__pycc_deprecation_doc_url = ("https://numba.readthedocs.io/en/stable/" + "reference/deprecation.html" + "#deprecation-of-the-numba-pycc-module") +__pycc_pending_deprecation_message = ("The 'pycc' module is pending " + "deprecation. Replacement technology is " + "being developed.\n\n" + "Pending Deprecation in Numba 0.57.0. " + "For more information please see: " + f"{__pycc_deprecation_doc_url}") + +_pend_dep = NumbaPendingDeprecationWarning(__pycc_pending_deprecation_message) +warnings.warn(_pend_dep, stacklevel=2) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/cc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/cc.py new file mode 100644 index 0000000000000000000000000000000000000000..15a27c1bb156c415ee1b176fbe416c676bf3a243 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/cc.py @@ -0,0 +1,309 @@ +from setuptools import distutils as dutils +from setuptools.command import build_ext +from setuptools.extension import Extension + +import os +import shutil +import sys +import tempfile + +from numba.core import typing, sigutils +from numba.core.compiler_lock import global_compiler_lock +from numba.pycc.compiler import ModuleCompiler, ExportEntry +from numba.pycc.platform import Toolchain +from numba import cext + + +dir_util = dutils.dir_util +log = dutils.log +extension_libs = cext.get_extension_libs() + + +class CC(object): + """ + An ahead-of-time compiler to create extension modules that don't + depend on Numba. + """ + + # NOTE: using ccache can speed up repetitive builds + # (especially for the mixin modules) + + _mixin_sources = ['modulemixin.c',] + extension_libs + + # -flto strips all unused helper functions, which 1) makes the + # produced output much smaller and 2) can make the linking step faster. + # (the Windows linker seems to do this by default, judging by the results) + + _extra_cflags = { + # Comment out due to odd behavior with GCC 4.9+ with LTO + # 'posix': ['-flto'], + } + + _extra_ldflags = { + # Comment out due to odd behavior with GCC 4.9+ with LTO + # 'posix': ['-flto'], + } + + def __init__(self, extension_name, source_module=None): + if '.' in extension_name: + raise ValueError("basename should be a simple module name, not " + "qualified name") + + self._basename = extension_name + self._init_function = 'pycc_init_' + extension_name + self._exported_functions = {} + # Resolve source module name and directory + f = sys._getframe(1) + if source_module is None: + dct = f.f_globals + source_module = dct['__name__'] + elif hasattr(source_module, '__name__'): + dct = source_module.__dict__ + source_module = source_module.__name__ + else: + dct = sys.modules[source_module].__dict__ + + self._source_path = dct.get('__file__', '') + self._source_module = source_module + self._toolchain = Toolchain() + self._verbose = False + # By default, output in directory of caller module + self._output_dir = os.path.dirname(self._source_path) + self._output_file = self._toolchain.get_ext_filename(extension_name) + self._use_nrt = True + self._target_cpu = '' + + @property + def name(self): + """ + The name of the extension module to create. + """ + return self._basename + + @property + def output_file(self): + """ + The specific output file (a DLL) that will be generated. + """ + return self._output_file + + @output_file.setter + def output_file(self, value): + self._output_file = value + + @property + def output_dir(self): + """ + The directory the output file will be put in. + """ + return self._output_dir + + @output_dir.setter + def output_dir(self, value): + self._output_dir = value + + @property + def use_nrt(self): + return self._use_nrt + + @use_nrt.setter + def use_nrt(self, value): + self._use_nrt = value + + @property + def target_cpu(self): + """ + The target CPU model for code generation. + """ + return self._target_cpu + + @target_cpu.setter + def target_cpu(self, value): + self._target_cpu = value + + @property + def verbose(self): + """ + Whether to display detailed information when compiling. + """ + return self._verbose + + @verbose.setter + def verbose(self, value): + self._verbose = value + + def export(self, exported_name, sig): + """ + Mark a function for exporting in the extension module. + """ + fn_args, fn_retty = sigutils.normalize_signature(sig) + sig = typing.signature(fn_retty, *fn_args) + if exported_name in self._exported_functions: + raise KeyError("duplicated export symbol %s" % (exported_name)) + + def decorator(func): + entry = ExportEntry(exported_name, sig, func) + self._exported_functions[exported_name] = entry + return func + + return decorator + + @property + def _export_entries(self): + return sorted(self._exported_functions.values(), + key=lambda entry: entry.symbol) + + def _get_mixin_sources(self): + here = os.path.dirname(__file__) + mixin_sources = self._mixin_sources[:] + if self._use_nrt: + mixin_sources.append('../core/runtime/nrt.cpp') + return [os.path.join(here, f) for f in mixin_sources] + + def _get_mixin_defines(self): + # Macro definitions required by modulemixin.c + return [ + ('PYCC_MODULE_NAME', self._basename), + ('PYCC_USE_NRT', int(self._use_nrt)), + ] + + def _get_extra_cflags(self): + extra_cflags = self._extra_cflags.get(sys.platform, []) + if not extra_cflags: + extra_cflags = self._extra_cflags.get(os.name, []) + return extra_cflags + + def _get_extra_ldflags(self): + extra_ldflags = self._extra_ldflags.get(sys.platform, []) + if not extra_ldflags: + extra_ldflags = self._extra_ldflags.get(os.name, []) + # helperlib uses pthread on linux. make sure we are linking to it. + if sys.platform.startswith("linux"): + if "-pthread" not in extra_ldflags: + extra_ldflags.append('-pthread') + return extra_ldflags + + def _compile_mixins(self, build_dir): + sources = self._get_mixin_sources() + macros = self._get_mixin_defines() + include_dirs = self._toolchain.get_python_include_dirs() + + extra_cflags = self._get_extra_cflags() + # XXX distutils creates a whole subtree inside build_dir, + # e.g. /tmp/test_pycc/home/antoine/numba/numba/pycc/modulemixin.o + objects = self._toolchain.compile_objects(sources, build_dir, + include_dirs=include_dirs, + macros=macros, + extra_cflags=extra_cflags) + return objects + + @global_compiler_lock + def _compile_object_files(self, build_dir): + compiler = ModuleCompiler(self._export_entries, self._basename, + self._use_nrt, cpu_name=self._target_cpu) + compiler.external_init_function = self._init_function + temp_obj = os.path.join(build_dir, + os.path.splitext(self._output_file)[0] + '.o') + log.info("generating LLVM code for '%s' into %s", + self._basename, temp_obj) + compiler.write_native_object(temp_obj, wrap=True) + return [temp_obj], compiler.dll_exports + + @global_compiler_lock + def compile(self): + """ + Compile the extension module. + """ + self._toolchain.verbose = self.verbose + build_dir = tempfile.mkdtemp(prefix='pycc-build-%s-' % self._basename) + + # Compile object file + objects, dll_exports = self._compile_object_files(build_dir) + + # Compile mixins + objects += self._compile_mixins(build_dir) + + # Then create shared library + extra_ldflags = self._get_extra_ldflags() + output_dll = os.path.join(self._output_dir, self._output_file) + libraries = self._toolchain.get_python_libraries() + library_dirs = self._toolchain.get_python_library_dirs() + self._toolchain.link_shared(output_dll, objects, + libraries, library_dirs, + export_symbols=dll_exports, + extra_ldflags=extra_ldflags) + + shutil.rmtree(build_dir) + + def distutils_extension(self, **kwargs): + """ + Create a distutils extension object that can be used in your + setup.py. + """ + macros = kwargs.pop('macros', []) + self._get_mixin_defines() + depends = kwargs.pop('depends', []) + [self._source_path] + extra_compile_args = (kwargs.pop('extra_compile_args', []) + + self._get_extra_cflags()) + extra_link_args = (kwargs.pop('extra_link_args', []) + + self._get_extra_ldflags()) + include_dirs = (kwargs.pop('include_dirs', []) + + self._toolchain.get_python_include_dirs()) + libraries = (kwargs.pop('libraries', []) + + self._toolchain.get_python_libraries()) + library_dirs = (kwargs.pop('library_dirs', []) + + self._toolchain.get_python_library_dirs()) + python_package_path = self._source_module[:self._source_module.rfind('.')+1] + + ext = _CCExtension(name=python_package_path + self._basename, + sources=self._get_mixin_sources(), + depends=depends, + define_macros=macros, + include_dirs=include_dirs, + libraries=libraries, + library_dirs=library_dirs, + extra_compile_args=extra_compile_args, + extra_link_args=extra_link_args, + **kwargs) + ext.monkey_patch_distutils() + ext._cc = self + return ext + + +class _CCExtension(Extension): + """ + A Numba-specific Extension subclass to LLVM-compile pure Python code + to an extension module. + """ + + _cc = None + _distutils_monkey_patched = False + + def _prepare_object_files(self, build_ext): + cc = self._cc + dir_util.mkpath(os.path.join(build_ext.build_temp, *self.name.split('.')[:-1])) + objects, _ = cc._compile_object_files(build_ext.build_temp) + # Add generated object files for linking + self.extra_objects = objects + + @classmethod + def monkey_patch_distutils(cls): + """ + Monkey-patch distutils with our own build_ext class knowing + about pycc-compiled extensions modules. + """ + if cls._distutils_monkey_patched: + return + + _orig_build_ext = build_ext.build_ext + + class _CC_build_ext(_orig_build_ext): + + def build_extension(self, ext): + if isinstance(ext, _CCExtension): + ext._prepare_object_files(self) + + _orig_build_ext.build_extension(self, ext) + + build_ext.build_ext = _CC_build_ext + + cls._distutils_monkey_patched = True diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/compiler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..1b46f7a79a49fa380610fa1ec9696f5d344bbad0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/compiler.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- + +import logging +import os +import sys + +from llvmlite import ir +from llvmlite.binding import Linkage + +from numba.pycc import llvm_types as lt +from numba.core.cgutils import create_constant_array +from numba.core.compiler import compile_extra, Flags +from numba.core.compiler_lock import global_compiler_lock + +from numba.core.registry import cpu_target +from numba.core.runtime import nrtdynmod +from numba.core import cgutils +from numba.core.environment import lookup_environment + + +logger = logging.getLogger(__name__) + +__all__ = ['ModuleCompiler'] + +NULL = ir.Constant(lt._void_star, None) +ZERO = ir.Constant(lt._int32, 0) +ONE = ir.Constant(lt._int32, 1) +METH_VARARGS_AND_KEYWORDS = ir.Constant(lt._int32, 1|2) + + +def get_header(): + import numpy + import textwrap + + return textwrap.dedent("""\ + #include + + #ifndef HAVE_LONGDOUBLE + #define HAVE_LONGDOUBLE %d + #endif + + typedef struct { + float real; + float imag; + } complex64; + + typedef struct { + double real; + double imag; + } complex128; + + #if HAVE_LONGDOUBLE + typedef struct { + long double real; + long double imag; + } complex256; + #endif + + typedef float float32; + typedef double float64; + #if HAVE_LONGDOUBLE + typedef long double float128; + #endif + """ % hasattr(numpy, 'complex256')) + + +class ExportEntry(object): + """ + A simple record for exporting symbols. + """ + + def __init__(self, symbol, signature, function): + self.symbol = symbol + self.signature = signature + self.function = function + + def __repr__(self): + return "ExportEntry(%r, %r)" % (self.symbol, self.signature) + + +class _ModuleCompiler(object): + """A base class to compile Python modules to a single shared library or + extension module. + + :param export_entries: a list of ExportEntry instances. + :param module_name: the name of the exported module. + """ + + #: Structure used to describe a method of an extension type. + #: struct PyMethodDef { + #: const char *ml_name; /* The name of the built-in function/method */ + #: PyCFunction ml_meth; /* The C function that implements it */ + #: int ml_flags; /* Combination of METH_xxx flags, which mostly + #: describe the args expected by the C func */ + #: const char *ml_doc; /* The __doc__ attribute, or NULL */ + #: }; + method_def_ty = ir.LiteralStructType((lt._int8_star, + lt._void_star, + lt._int32, + lt._int8_star)) + + method_def_ptr = ir.PointerType(method_def_ty) + # The structure type constructed by PythonAPI.serialize_uncached() + # when updating this, also make sure to update `env_def_t` struct in + # numba/pycc/modulemixin.c + env_def_ty = ir.LiteralStructType((lt._void_star, + lt._int32, + lt._void_star, + lt._void_star, + lt._int32)) + env_def_ptr = ir.PointerType(env_def_ty) + + def __init__(self, export_entries, module_name, use_nrt=False, + **aot_options): + self.module_name = module_name + self.export_python_wrap = False + self.dll_exports = [] + self.export_entries = export_entries + # Used by the CC API but not the legacy API + self.external_init_function = None + self.use_nrt = use_nrt + + self.typing_context = cpu_target.typing_context + self.context = cpu_target.target_context.with_aot_codegen( + self.module_name, **aot_options) + + def _mangle_method_symbol(self, func_name): + return "._pycc_method_%s" % (func_name,) + + def _emit_python_wrapper(self, llvm_module): + """Emit generated Python wrapper and extension module code. + """ + raise NotImplementedError + + @global_compiler_lock + def _cull_exports(self): + """Read all the exported functions/modules in the translator + environment, and join them into a single LLVM module. + """ + self.exported_function_types = {} + self.function_environments = {} + self.environment_gvs = {} + self.extra_environments = {} + + codegen = self.context.codegen() + library = codegen.create_library(self.module_name) + + # Generate IR for all exported functions + flags = Flags() + flags.no_compile = True + if not self.export_python_wrap: + flags.no_cpython_wrapper = True + flags.no_cfunc_wrapper = True + if self.use_nrt: + flags.nrt = True + # Compile NRT helpers + nrt_module, _ = nrtdynmod.create_nrt_module(self.context) + library.add_ir_module(nrt_module) + + for entry in self.export_entries: + cres = compile_extra(self.typing_context, self.context, + entry.function, + entry.signature.args, + entry.signature.return_type, flags, + locals={}, library=library) + + # Fix up dynamic exc globals + module = library._final_module + for gv in module.functions: + if gv.name.startswith("__excinfo_unwrap_args"): + gv.linkage = "linkonce_odr" + + func_name = cres.fndesc.llvm_func_name + llvm_func = cres.library.get_function(func_name) + + if self.export_python_wrap: + llvm_func.linkage = 'internal' + wrappername = cres.fndesc.llvm_cpython_wrapper_name + wrapper = cres.library.get_function(wrappername) + wrapper.name = self._mangle_method_symbol(entry.symbol) + wrapper.linkage = 'external' + fnty = cres.target_context.call_conv.get_function_type( + cres.fndesc.restype, cres.fndesc.argtypes) + self.exported_function_types[entry] = fnty + self.function_environments[entry] = cres.environment + self.environment_gvs[entry] = cres.fndesc.env_name + + # Search for extra environments from linked libraries + for linkedlib in library._linking_libraries: + linkedmod = linkedlib._final_module + # Find environments + for gv in linkedmod.global_variables: + gvn = gv.name + if gvn.startswith("_ZN08NumbaEnv"): + env = lookup_environment(gvn) + if env is not None: + if env.can_cache(): + self.extra_environments[gvn] = env + else: + llvm_func.name = entry.symbol + self.dll_exports.append(entry.symbol) + + if self.export_python_wrap: + wrapper_module = library.create_ir_module("wrapper") + self._emit_python_wrapper(wrapper_module) + library.add_ir_module(wrapper_module) + + # Hide all functions in the DLL except those explicitly exported + library.finalize() + for fn in library.get_defined_functions(): + if fn.name not in self.dll_exports: + if fn.linkage in {Linkage.private, Linkage.internal}: + # Private/Internal linkage must have "default" visibility + fn.visibility = "default" + else: + fn.visibility = 'hidden' + return library + + def write_llvm_bitcode(self, output, wrap=False, **kws): + self.export_python_wrap = wrap + library = self._cull_exports() + with open(output, 'wb') as fout: + fout.write(library.emit_bitcode()) + + def write_native_object(self, output, wrap=False, **kws): + self.export_python_wrap = wrap + library = self._cull_exports() + with open(output, 'wb') as fout: + fout.write(library.emit_native_object()) + + def emit_type(self, tyobj): + ret_val = str(tyobj) + if 'int' in ret_val: + if ret_val.endswith(('8', '16', '32', '64')): + ret_val += "_t" + return ret_val + + def emit_header(self, output): + fname, ext = os.path.splitext(output) + with open(fname + '.h', 'w') as fout: + fout.write(get_header()) + fout.write("\n/* Prototypes */\n") + for export_entry in self.export_entries: + name = export_entry.symbol + restype = self.emit_type(export_entry.signature.return_type) + args = ", ".join(self.emit_type(argtype) + for argtype in export_entry.signature.args) + fout.write("extern %s %s(%s);\n" % (restype, name, args)) + + def _emit_method_array(self, llvm_module): + """ + Collect exported methods and emit a PyMethodDef array. + + :returns: a pointer to the PyMethodDef array. + """ + method_defs = [] + for entry in self.export_entries: + name = entry.symbol + llvm_func_name = self._mangle_method_symbol(name) + fnty = self.exported_function_types[entry] + lfunc = ir.Function(llvm_module, fnty, llvm_func_name) + + method_name = self.context.insert_const_string(llvm_module, name) + method_def_const = ir.Constant.literal_struct( + (method_name, + ir.Constant.bitcast(lfunc, lt._void_star), + METH_VARARGS_AND_KEYWORDS, + NULL)) + method_defs.append(method_def_const) + + sentinel = ir.Constant.literal_struct([NULL, NULL, ZERO, NULL]) + method_defs.append(sentinel) + method_array_init = create_constant_array(self.method_def_ty, method_defs) + method_array = cgutils.add_global_variable(llvm_module, + method_array_init.type, + '.module_methods') + method_array.initializer = method_array_init + method_array.linkage = 'internal' + method_array_ptr = ir.Constant.gep(method_array, [ZERO, ZERO]) + return method_array_ptr + + def _emit_environment_array(self, llvm_module, builder, pyapi): + """ + Emit an array of env_def_t structures (see modulemixin.c) + storing the pickled environment constants for each of the + exported functions. + """ + env_defs = [] + for entry in self.export_entries: + env = self.function_environments[entry] + # Constants may be unhashable so avoid trying to cache them + env_def = pyapi.serialize_uncached(env.consts) + env_defs.append(env_def) + # Append extra environments + env_defs.extend([ + pyapi.serialize_uncached(env.consts) + for env in self.extra_environments.values() + ]) + env_defs_init = create_constant_array(self.env_def_ty, env_defs) + gv = self.context.insert_unique_const(llvm_module, + '.module_environments', + env_defs_init) + return gv.gep([ZERO, ZERO]) + + def _emit_envgvs_array(self, llvm_module, builder, pyapi): + """ + Emit an array of Environment pointers that needs to be filled at + initialization. + """ + env_setters = [] + for entry in self.export_entries: + envgv_name = self.environment_gvs[entry] + gv = self.context.declare_env_global(llvm_module, envgv_name) + envgv = gv.bitcast(lt._void_star) + env_setters.append(envgv) + # Append extra environments + env_setters.extend([ + self.context.declare_env_global( + llvm_module, + envgv_name + ).bitcast(lt._void_star) + for envgv_name in self.extra_environments + ]) + # The array ends with NULL + env_setters.append(lt._void_star(None)) + + env_setters_init = create_constant_array(lt._void_star, env_setters) + gv = self.context.insert_unique_const(llvm_module, + '.module_envgvs', + env_setters_init) + return gv.gep([ZERO, ZERO]) + + def _emit_module_init_code(self, llvm_module, builder, modobj, + method_array, env_array, envgv_array): + """ + Emit call to "external" init function, if any. + """ + if self.external_init_function: + fnty = ir.FunctionType(lt._int32, + [modobj.type, self.method_def_ptr, + self.env_def_ptr, envgv_array.type]) + fn = ir.Function(llvm_module, fnty, self.external_init_function) + return builder.call(fn, [modobj, method_array, env_array, + envgv_array]) + else: + return None + + +class ModuleCompiler(_ModuleCompiler): + + _ptr_fun = lambda ret, *args: ir.PointerType(ir.FunctionType(ret, args)) + + #: typedef int (*visitproc)(PyObject *, void *); + visitproc_ty = _ptr_fun(lt._int8, + lt._pyobject_head_p) + + #: typedef int (*inquiry)(PyObject *); + inquiry_ty = _ptr_fun(lt._int8, + lt._pyobject_head_p) + + #: typedef int (*traverseproc)(PyObject *, visitproc, void *); + traverseproc_ty = _ptr_fun(lt._int8, + lt._pyobject_head_p, + visitproc_ty, + lt._void_star) + + # typedef void (*freefunc)(void *) + freefunc_ty = _ptr_fun(lt._int8, + lt._void_star) + + # PyObject* (*m_init)(void); + m_init_ty = _ptr_fun(lt._int8) + + _char_star = lt._int8_star + + #: typedef struct PyModuleDef_Base { + #: PyObject_HEAD + #: PyObject* (*m_init)(void); + #: Py_ssize_t m_index; + #: PyObject* m_copy; + #: } PyModuleDef_Base; + module_def_base_ty = ir.LiteralStructType( + ( + lt._pyobject_head, + m_init_ty, + lt._llvm_py_ssize_t, + lt._pyobject_head_p + )) + + #: This struct holds all information that is needed to create a module object. + #: typedef struct PyModuleDef{ + #: PyModuleDef_Base m_base; + #: const char* m_name; + #: const char* m_doc; + #: Py_ssize_t m_size; + #: PyMethodDef *m_methods; + #: inquiry m_reload; + #: traverseproc m_traverse; + #: inquiry m_clear; + #: freefunc m_free; + #: }PyModuleDef; + module_def_ty = ir.LiteralStructType( + ( + module_def_base_ty, + _char_star, + _char_star, + lt._llvm_py_ssize_t, + _ModuleCompiler.method_def_ptr, + inquiry_ty, + traverseproc_ty, + inquiry_ty, + freefunc_ty + )) + + @property + def module_create_definition(self): + """ + Return the signature and name of the Python C API function to + initialize the module. + """ + signature = ir.FunctionType(lt._pyobject_head_p, + (ir.PointerType(self.module_def_ty), + lt._int32)) + + name = "PyModule_Create2" + if lt._trace_refs_: + name += "TraceRefs" + + return signature, name + + @property + def module_init_definition(self): + """ + Return the name and signature of the module's initialization function. + """ + signature = ir.FunctionType(lt._pyobject_head_p, ()) + + return signature, "PyInit_" + self.module_name + + def _emit_python_wrapper(self, llvm_module): + # Figure out the Python C API module creation function, and + # get a LLVM function for it. + create_module_fn = ir.Function(llvm_module, *self.module_create_definition) + create_module_fn.linkage = 'external' + + # Define a constant string for the module name. + mod_name_const = self.context.insert_const_string(llvm_module, + self.module_name) + + mod_def_base_init = ir.Constant.literal_struct( + (lt._pyobject_head_init, # PyObject_HEAD + ir.Constant(self.m_init_ty, None), # m_init + ir.Constant(lt._llvm_py_ssize_t, None), # m_index + ir.Constant(lt._pyobject_head_p, None), # m_copy + ) + ) + mod_def_base = cgutils.add_global_variable(llvm_module, + mod_def_base_init.type, + '.module_def_base') + mod_def_base.initializer = mod_def_base_init + mod_def_base.linkage = 'internal' + + method_array = self._emit_method_array(llvm_module) + + mod_def_init = ir.Constant.literal_struct( + (mod_def_base_init, # m_base + mod_name_const, # m_name + ir.Constant(self._char_star, None), # m_doc + ir.Constant(lt._llvm_py_ssize_t, -1), # m_size + method_array, # m_methods + ir.Constant(self.inquiry_ty, None), # m_reload + ir.Constant(self.traverseproc_ty, None), # m_traverse + ir.Constant(self.inquiry_ty, None), # m_clear + ir.Constant(self.freefunc_ty, None) # m_free + ) + ) + + # Define a constant string for the module name. + mod_def = cgutils.add_global_variable(llvm_module, mod_def_init.type, + '.module_def') + mod_def.initializer = mod_def_init + mod_def.linkage = 'internal' + + # Define the module initialization function. + mod_init_fn = ir.Function(llvm_module, *self.module_init_definition) + entry = mod_init_fn.append_basic_block('Entry') + builder = ir.IRBuilder(entry) + pyapi = self.context.get_python_api(builder) + + mod = builder.call(create_module_fn, + (mod_def, + ir.Constant(lt._int32, sys.api_version))) + + # Test if module has been created correctly. + # (XXX for some reason comparing with the NULL constant fails llvm + # with an assertion in pydebug mode) + with builder.if_then(cgutils.is_null(builder, mod)): + builder.ret(NULL.bitcast(mod_init_fn.type.pointee.return_type)) + + env_array = self._emit_environment_array(llvm_module, builder, pyapi) + envgv_array = self._emit_envgvs_array(llvm_module, builder, pyapi) + ret = self._emit_module_init_code(llvm_module, builder, mod, + method_array, env_array, envgv_array) + if ret is not None: + with builder.if_then(cgutils.is_not_null(builder, ret)): + # Init function errored out + builder.ret(ir.Constant(mod.type, None)) + + builder.ret(mod) + + self.dll_exports.append(mod_init_fn.name) + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/decorators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..34278903dec5335b0aaa37063a19afc0e5f65865 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/decorators.py @@ -0,0 +1,72 @@ +import re +import warnings + +from numba.core import typing, sigutils +from numba.pycc.compiler import ExportEntry + +# Registry is okay to be a global because we are using pycc as a standalone +# commandline tool. +export_registry = [] + + +def export(prototype): + warnings.warn("export() is deprecated, use the numba.pycc.CC API instead", + DeprecationWarning, stacklevel=2) + + sym, sig = parse_prototype(prototype) + + def wrappped(func): + fn_argtys, fn_retty = sigutils.normalize_signature(sig) + signature = typing.signature(fn_retty, *fn_argtys) + entry = ExportEntry(symbol=sym, signature=signature, function=func) + export_registry.append(entry) + + return wrappped + + +def exportmany(prototypes): + warnings.warn("exportmany() is deprecated, use the numba.pycc.CC API instead", + DeprecationWarning, stacklevel=2) + + def wrapped(func): + for proto in prototypes: + export(proto)(func) + return wrapped + + +def process_input_files(inputs): + """ + Read input source files for execution of legacy @export / @exportmany + decorators. + """ + for ifile in inputs: + with open(ifile) as fin: + exec(compile(fin.read(), ifile, 'exec')) + + +def clear_export_registry(): + export_registry[:] = [] + + +# --------------------------------- Internal --------------------------------- + +re_symbol = re.compile(r'[_a-z][_a-z0-9]*', re.I) + + +def parse_prototype(text): + """Separate the symbol and function-type in a a string with + "symbol function-type" (e.g. "mult float(float, float)") + + Returns + --------- + (symbol_string, functype_string) + """ + m = re_symbol.match(text) + if not m: + raise ValueError("Invalid function name for export prototype") + s = m.start(0) + e = m.end(0) + symbol = text[s:e] + functype = text[e + 1:] + return symbol, functype + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/llvm_types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/llvm_types.py new file mode 100644 index 0000000000000000000000000000000000000000..4259ced6e6f696425530c250aba947043aa852ca --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/llvm_types.py @@ -0,0 +1,37 @@ +import sys +import ctypes +import struct as struct_ +import llvmlite.ir +from llvmlite.ir import Constant + +_trace_refs_ = hasattr(sys, 'getobjects') +_plat_bits = struct_.calcsize('@P') * 8 + +_int8 = llvmlite.ir.IntType(8) +_int32 = llvmlite.ir.IntType(32) + +_void_star = llvmlite.ir.PointerType(_int8) + +_int8_star = _void_star + +_sizeof_py_ssize_t = ctypes.sizeof(getattr(ctypes, 'c_size_t')) +_llvm_py_ssize_t = llvmlite.ir.IntType(_sizeof_py_ssize_t * 8) + +if _trace_refs_: + _pyobject_head = llvmlite.ir.LiteralStructType([_void_star, _void_star, + _llvm_py_ssize_t, _void_star]) + _pyobject_head_init = Constant.literal_struct([ + Constant(_void_star, None), # _ob_next + Constant(_void_star, None), # _ob_prev + Constant(_llvm_py_ssize_t, 1), # ob_refcnt + Constant(_void_star, None), # ob_type + ]) + +else: + _pyobject_head = llvmlite.ir.LiteralStructType([_llvm_py_ssize_t, _void_star]) + _pyobject_head_init = Constant.literal_struct([ + Constant(_llvm_py_ssize_t, 1), # ob_refcnt + Constant(_void_star, None), # ob_type + ]) + +_pyobject_head_p = llvmlite.ir.PointerType(_pyobject_head) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/modulemixin.c b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/modulemixin.c new file mode 100644 index 0000000000000000000000000000000000000000..eec3b2bd3e1a2a765af57fe2a3147295a19d842d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/modulemixin.c @@ -0,0 +1,221 @@ +/* + * This C file is compiled and linked into pycc-generated shared objects. + * It provides the Numba helper functions for runtime use in pycc-compiled + * functions. + */ + +#include "../_numba_common.h" +#include "../_pymodule.h" + +/* Define all runtime-required symbols in this C module, but do not + export them outside the shared library if possible. */ + +#define NUMBA_EXPORT_FUNC(_rettype) VISIBILITY_HIDDEN _rettype +#define NUMBA_EXPORT_DATA(_vartype) VISIBILITY_HIDDEN _vartype + +#define PYCC_COMPILING + +#include "../_helperlib.c" +#include "../_dynfunc.c" + +#if PYCC_USE_NRT +#include "../core/runtime/_nrt_python.c" +#include "../core/runtime/nrt.h" +#endif + +#if (PY_MAJOR_VERSION == 3) && (PY_MINOR_VERSION >= 12) + #define Py_BUILD_CORE 1 + #include "internal/pycore_pyhash.h" + #undef Py_BUILD_CORE +#endif + +/* Defines hashsecret variables (see issue #6386) */ +int64_t _numba_hashsecret_siphash_k0; +int64_t _numba_hashsecret_siphash_k1; +int64_t _numba_hashsecret_djbx33a_suffix; + +/* NOTE: import_array() is macro, not a function. It returns NULL on + failure */ +static void * +wrap_import_array(void) { + import_array(); + return (void *) 1; +} + + +static int +init_numpy(void) { + return wrap_import_array() != NULL; +} + + +#ifndef PYCC_MODULE_NAME +#error PYCC_MODULE_NAME must be defined +#endif + +/* Preprocessor trick: need to use two levels of macros otherwise + PYCC_MODULE_NAME would not get expanded */ +#define __PYCC(prefix, modname) prefix ## modname +#define _PYCC(prefix, modname) __PYCC(prefix, modname) +#define PYCC(prefix) _PYCC(prefix, PYCC_MODULE_NAME) + +/* Silence warnings about unused functions */ +VISIBILITY_HIDDEN void **PYCC(_unused_) = { + (void *) Numba_make_generator, +}; + +/* The structure type constructed by PythonAPI.serialize_uncached() */ +typedef struct { + const char *data; + int len; + const char *hashbuf; + const char *func_ptr; // pointer to unwrap dyn args function + int alloc_flag; +} env_def_t; + +/* Environment GlobalVariable address type */ +typedef void **env_gv_t; + +/* + * Recreate an environment object from a env_def_t structure. + */ +static EnvironmentObject * +recreate_environment(PyObject *module, env_def_t env) +{ + EnvironmentObject *envobj; + PyObject *env_consts; + + env_consts = numba_unpickle(env.data, env.len, env.hashbuf); + if (env_consts == NULL) + return NULL; + if (!PyList_Check(env_consts)) { + PyErr_Format(PyExc_TypeError, + "environment constants should be a list, got '%s'", + Py_TYPE(env_consts)->tp_name); + Py_DECREF(env_consts); + return NULL; + } + + envobj = env_new_empty(&EnvironmentType); + if (envobj == NULL) { + Py_DECREF(env_consts); + return NULL; + } + envobj->consts = env_consts; + envobj->globals = PyModule_GetDict(module); + if (envobj->globals == NULL) { + Py_DECREF(envobj); + return NULL; + } + Py_INCREF(envobj->globals); + return envobj; +} + +/* + * Subroutine to initialize all resources required for running the + * pycc-compiled functions. + */ + +int +PYCC(pycc_init_) (PyObject *module, PyMethodDef *defs, + env_def_t *envs, + env_gv_t *envgvs) +{ + /* Aligns hashsecret with values in current python process so that + * hashes computed inside the pycc module are correct if imported + * by the current process. Imports in a new process get the right + * hash secret through: + * `numba.cpython.hashing._load_hashsecret`. + */ + _numba_hashsecret_siphash_k0 = _Py_HashSecret.siphash.k0; + _numba_hashsecret_siphash_k1 = _Py_HashSecret.siphash.k1; + _numba_hashsecret_djbx33a_suffix = _Py_HashSecret.djbx33a.suffix; + + PyMethodDef *fdef; + PyObject *modname = NULL; + PyObject *docobj = NULL; + int i; + + if (!init_numpy()) { + goto error; + } + if (init_dynfunc_module(module)) { + goto error; + } + /* Initialize random generation. */ + numba_rnd_ensure_global_init(); + +#if PYCC_USE_NRT + NRT_MemSys_init(); + if (init_nrt_python_module(module)) { + goto error; + } +#endif + + modname = PyObject_GetAttrString(module, "__name__"); + if (modname == NULL) { + goto error; + } + + /* Empty docstring for all compiled functions */ + docobj = PyString_FromString(""); + if (docobj == NULL) { + goto error; + } + + /* Overwrite C method objects with our own Closure objects, in order + * to make their environments available to the compiled functions. + */ + for (i = 0, fdef = defs; fdef->ml_name != NULL; i++, fdef++) { + PyObject *func; + PyObject *nameobj; + EnvironmentObject *envobj; + + envobj = recreate_environment(module, envs[i]); + if (envobj == NULL) { + goto error; + } + nameobj = PyString_FromString(fdef->ml_name); + if (nameobj == NULL) { + Py_DECREF(envobj); + goto error; + } + // Store the environment pointer into the global + *envgvs[i] = envobj; + + func = pycfunction_new(module, nameobj, docobj, + fdef->ml_meth, envobj, NULL); + Py_DECREF(envobj); + Py_DECREF(nameobj); + + if (func == NULL) { + goto error; + } + if (PyObject_SetAttrString(module, fdef->ml_name, func)) { + Py_DECREF(func); + goto error; + } + Py_DECREF(func); + } + /* Recreate other environment objects + envgvs is expected to end with a NULL pointer. + */ + for (; envgvs[i]; ++i) { + EnvironmentObject *envobj; + envobj = recreate_environment(module, envs[i]); + if (envobj == NULL) { + goto error; + } + // Store the environment pointer into the global + *envgvs[i] = envobj; + Py_DECREF(envobj); + } + Py_DECREF(docobj); + Py_DECREF(modname); + return 0; + +error: + Py_XDECREF(docobj); + Py_XDECREF(modname); + return -1; +} diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/platform.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/platform.py new file mode 100644 index 0000000000000000000000000000000000000000..ba1f819ddda1ebaec6f269e617d82c4dff17cb00 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/pycc/platform.py @@ -0,0 +1,218 @@ +import setuptools +from setuptools.command.build_ext import build_ext +from setuptools.dist import Distribution +import numpy as np + +import functools +import os +import subprocess +import sys +from tempfile import mkdtemp +from contextlib import contextmanager +from pathlib import Path + +# Wire in distutils components from setuptools +CCompiler = setuptools.distutils.ccompiler.CCompiler +new_compiler = setuptools.distutils.ccompiler.new_compiler +customize_compiler = setuptools.distutils.sysconfig.customize_compiler +log = setuptools.distutils.log + + +_configs = { + # DLL suffix, Python C extension suffix + 'win': ('.dll', '.pyd'), + 'default': ('.so', '.so'), +} + + +def get_configs(arg): + return _configs.get(sys.platform[:3], _configs['default'])[arg] + + +find_shared_ending = functools.partial(get_configs, 0) +find_pyext_ending = functools.partial(get_configs, 1) + +@contextmanager +def _gentmpfile(suffix): + # windows locks the tempfile so use a tempdir + file, see + # https://github.com/numba/numba/issues/3304 + try: + tmpdir = mkdtemp() + ntf = open(os.path.join(tmpdir, "temp%s" % suffix), 'wt') + yield ntf + finally: + try: + ntf.close() + os.remove(ntf) + except Exception: + pass + else: + os.rmdir(tmpdir) + + +@functools.lru_cache(maxsize=1) +def external_compiler_works(): + """ + Returns True if the "external compiler" bound in numpy.distutil is present + and working, False otherwise. + """ + compiler = new_compiler() + customize_compiler(compiler) + for suffix in ['.c', '.cxx']: + try: + with _gentmpfile(suffix) as ntf: + simple_c = "int main(void) { return 0; }" + ntf.write(simple_c) + ntf.flush() + ntf.close() + # *output_dir* is set to avoid the compiler putting temp files + # in the current directory. + compiler.compile([ntf.name], output_dir=Path(ntf.name).anchor) + except Exception: # likely CompileError or file system issue + return False + return True + + +class _DummyExtension(object): + libraries = [] + + +class Toolchain(object): + + def __init__(self): + if not external_compiler_works(): + self._raise_external_compiler_error() + + self._verbose = False + self._compiler = new_compiler() + customize_compiler(self._compiler) + self._build_ext = build_ext(Distribution()) + self._build_ext.finalize_options() + self._py_lib_dirs = self._build_ext.library_dirs + self._py_include_dirs = self._build_ext.include_dirs + np_compile_args = {'include_dirs': [np.get_include(),],} + if sys.platform == 'win32': + np_compile_args['libraries'] = [] + else: + np_compile_args['libraries'] = ['m',] + self._math_info = np_compile_args + + @property + def verbose(self): + return self._verbose + + @verbose.setter + def verbose(self, value): + self._verbose = value + # DEBUG will let Numpy spew many messages, so stick to INFO + # to print commands executed by distutils + log.set_threshold(log.INFO if value else log.WARN) + + def _raise_external_compiler_error(self): + basemsg = ("Attempted to compile AOT function without the " + "compiler used by `numpy.distutils` present.") + conda_msg = "If using conda try:\n\n#> conda install %s" + plt = sys.platform + if plt.startswith('linux'): + if sys.maxsize <= 2 ** 32: + compilers = ['gcc_linux-32', 'gxx_linux-32'] + else: + compilers = ['gcc_linux-64', 'gxx_linux-64'] + msg = "%s %s" % (basemsg, conda_msg % ' '.join(compilers)) + elif plt.startswith('darwin'): + compilers = ['clang_osx-64', 'clangxx_osx-64'] + msg = "%s %s" % (basemsg, conda_msg % ' '.join(compilers)) + elif plt.startswith('win32'): + winmsg = "Cannot find suitable msvc." + msg = "%s %s" % (basemsg, winmsg) + else: + msg = "Unknown platform %s" % plt + raise RuntimeError(msg) + + def compile_objects(self, sources, output_dir, + include_dirs=(), depends=(), macros=(), + extra_cflags=None): + """ + Compile the given source files into a separate object file each, + all beneath the *output_dir*. A list of paths to object files + is returned. + + *macros* has the same format as in distutils: a list of 1- or 2-tuples. + If a 1-tuple (name,), the given name is considered undefined by + the C preprocessor. + If a 2-tuple (name, value), the given name is expanded into the + given value by the C preprocessor. + """ + objects = self._compiler.compile(sources, + output_dir=output_dir, + include_dirs=include_dirs, + depends=depends, + macros=macros or [], + extra_preargs=extra_cflags) + return objects + + def link_shared(self, output, objects, libraries=(), + library_dirs=(), export_symbols=(), + extra_ldflags=None): + """ + Create a shared library *output* linking the given *objects* + and *libraries* (all strings). + """ + output_dir, output_filename = os.path.split(output) + self._compiler.link(CCompiler.SHARED_OBJECT, objects, + output_filename, output_dir, + libraries, library_dirs, + export_symbols=export_symbols, + extra_preargs=extra_ldflags) + + def get_python_libraries(self): + """ + Get the library arguments necessary to link with Python. + """ + libs = self._build_ext.get_libraries(_DummyExtension()) + if sys.platform == 'win32': + # Under Windows, need to link explicitly against the CRT, + # as the MSVC compiler would implicitly do. + # (XXX msvcrtd in pydebug mode?) + libs = libs + ['msvcrt'] + return libs + self._math_info['libraries'] + + def get_python_library_dirs(self): + """ + Get the library directories necessary to link with Python. + """ + return list(self._py_lib_dirs) + + def get_python_include_dirs(self): + """ + Get the include directories necessary to compile against the Python + and Numpy C APIs. + """ + return list(self._py_include_dirs) + self._math_info['include_dirs'] + + def get_ext_filename(self, ext_name): + """ + Given a C extension's module name, return its intended filename. + """ + return self._build_ext.get_ext_filename(ext_name) + + +def _quote_arg(arg): + """ + Quote the argument for safe use in a shell command line. + """ + # If there is a quote in the string, assume relevants parts of the + # string are already quoted (e.g. '-I"C:\\Program Files\\..."') + if '"' not in arg and ' ' in arg: + return '"%s"' % arg + return arg + + +def _is_sequence(arg): + if isinstance(arg, (str, bytes)): + return False + try: + len(arg) + return True + except Exception: + return False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/scripts/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/scripts/generate_lower_listing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/scripts/generate_lower_listing.py new file mode 100644 index 0000000000000000000000000000000000000000..1a93e7a3d0f48007c181ba2ab44439883c749995 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/scripts/generate_lower_listing.py @@ -0,0 +1,169 @@ +""" +Generate documentation for all registered implementation for lowering +using reStructured text. +""" + + +from subprocess import check_output + +import os.path +try: + from StringIO import StringIO # py2 +except ImportError: + from io import StringIO +from collections import defaultdict +import inspect +from functools import partial + +import numba +from numba.core.registry import cpu_target + + +def git_hash(): + out = check_output(['git', 'log', "--pretty=format:'%H'", '-n', '1']) + return out.decode('ascii').strip("'\"") + + +def get_func_name(fn): + return getattr(fn, '__qualname__', fn.__name__) + + +def gather_function_info(backend): + fninfos = defaultdict(list) + basepath = os.path.dirname(os.path.dirname(numba.__file__)) + for fn, osel in backend._defns.items(): + for sig, impl in osel.versions: + info = {} + fninfos[fn].append(info) + info['fn'] = fn + info['sig'] = sig + code, firstlineno = inspect.getsourcelines(impl) + path = inspect.getsourcefile(impl) + info['impl'] = { + 'name': get_func_name(impl), + 'filename': os.path.relpath(path, start=basepath), + 'lines': (firstlineno, firstlineno + len(code) - 1), + 'docstring': impl.__doc__ + } + + return fninfos + + +def bind_file_to_print(fobj): + return partial(print, file=fobj) + + +def format_signature(sig): + def fmt(c): + try: + return c.__name__ + except AttributeError: + return repr(c).strip('\'"') + out = tuple(map(fmt, sig)) + return '`({0})`'.format(', '.join(out)) + + +github_url = ('https://github.com/numba/numba/blob/' + '{commit}/{path}#L{firstline}-L{lastline}') + +description = """ +This lists all lowering definition registered to the CPU target. +Each subsection corresponds to a Python function that is supported by numba +nopython mode. These functions have one or more lower implementation with +different signatures. The compiler chooses the most specific implementation +from all overloads. +""" + + +def format_function_infos(fninfos): + buf = StringIO() + try: + print = bind_file_to_print(buf) + + title_line = "Lowering Listing" + print(title_line) + print('=' * len(title_line)) + + print(description) + + commit = git_hash() + + def format_fname(fn): + try: + fname = "{0}.{1}".format(fn.__module__, get_func_name(fn)) + except AttributeError: + fname = repr(fn) + return fn, fname + + for fn, fname in sorted(map(format_fname, fninfos), key=lambda x: x[1]): + impinfos = fninfos[fn] + header_line = "``{0}``".format(fname) + print(header_line) + print('-' * len(header_line)) + print() + + formatted_sigs = map( + lambda x: format_signature(x['sig']), impinfos) + sorted_impinfos = sorted(zip(formatted_sigs, impinfos), + key=lambda x: x[0]) + + col_signatures = ['Signature'] + col_urls = ['Definition'] + + for fmtsig, info in sorted_impinfos: + impl = info['impl'] + + filename = impl['filename'] + lines = impl['lines'] + fname = impl['name'] + + source = '{0} lines {1}-{2}'.format(filename, *lines) + link = github_url.format(commit=commit, path=filename, + firstline=lines[0], lastline=lines[1]) + url = '``{0}`` `{1} <{2}>`_'.format(fname, source, link) + + col_signatures.append(fmtsig) + col_urls.append(url) + + # table formatting + max_width_col_sig = max(map(len, col_signatures)) + max_width_col_url = max(map(len, col_urls)) + padding = 2 + width_col_sig = padding * 2 + max_width_col_sig + width_col_url = padding * 2 + max_width_col_url + line_format = "{{0:^{0}}} {{1:^{1}}}".format(width_col_sig, + width_col_url) + print(line_format.format('=' * width_col_sig, '=' * width_col_url)) + print(line_format.format(col_signatures[0], col_urls[0])) + print(line_format.format('=' * width_col_sig, '=' * width_col_url)) + for sig, url in zip(col_signatures[1:], col_urls[1:]): + print(line_format.format(sig, url)) + print(line_format.format('=' * width_col_sig, '=' * width_col_url)) + print() + + return buf.getvalue() + finally: + buf.close() + + +# Main routine for this module: + +def gen_lower_listing(path=None): + """ + Generate lowering listing to ``path`` or (if None) to stdout. + """ + cpu_backend = cpu_target.target_context + cpu_backend.refresh() + + fninfos = gather_function_info(cpu_backend) + out = format_function_infos(fninfos) + + if path is None: + print(out) + else: + with open(path, 'w') as fobj: + print(out, file=fobj) + + +if __name__ == '__main__': + gen_lower_listing() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencil.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencil.py new file mode 100644 index 0000000000000000000000000000000000000000..61df4e0b61cc80068b3d4f729d1ad59b3da3413f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencil.py @@ -0,0 +1,836 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import copy + +import numpy as np +from llvmlite import ir as lir + +from numba.core import types, typing, utils, ir, config, ir_utils, registry +from numba.core.typing.templates import (CallableTemplate, signature, + infer_global, AbstractTemplate) +from numba.core.imputils import lower_builtin +from numba.core.extending import register_jitable +from numba.core.errors import NumbaValueError +from numba.misc.special import literal_unroll +import numba + +import operator +from numba.np import numpy_support + +class StencilFuncLowerer(object): + '''Callable class responsible for lowering calls to a specific StencilFunc. + ''' + def __init__(self, sf): + self.stencilFunc = sf + + def __call__(self, context, builder, sig, args): + cres = self.stencilFunc.compile_for_argtys(sig.args, {}, + sig.return_type, None) + res = context.call_internal(builder, cres.fndesc, sig, args) + context.add_linking_libs([cres.library]) + return res + +@register_jitable +def raise_if_incompatible_array_sizes(a, *args): + ashape = a.shape + + # We need literal_unroll here because the stencil might take + # multiple input arrays with different types that are not compatible + # (e.g. values as float[:] and flags as bool[:]) + # When more than three total arrays are given, the second and third + # are iterated over in the loop below. Without literal_unroll, their + # types have to match. + # An example failing signature without literal_unroll might be + # (float[:], float[:], bool[:]) (Just (float[:], bool[:]) wouldn't fail) + for arg in literal_unroll(args): + if a.ndim != arg.ndim: + raise ValueError("Secondary stencil array does not have same number " + " of dimensions as the first stencil input.") + argshape = arg.shape + for i in range(len(ashape)): + if ashape[i] > argshape[i]: + raise ValueError("Secondary stencil array has some dimension " + "smaller the same dimension in the first " + "stencil input.") + +def slice_addition(the_slice, addend): + """ Called by stencil in Python mode to add the loop index to a + user-specified slice. + """ + return slice(the_slice.start + addend, the_slice.stop + addend) + +class StencilFunc(object): + """ + A special type to hold stencil information for the IR. + """ + + id_counter = 0 + + def __init__(self, kernel_ir, mode, options): + self.id = type(self).id_counter + type(self).id_counter += 1 + self.kernel_ir = kernel_ir + self.mode = mode + self.options = options + self.kws = [] # remember original kws arguments + + # stencils only supported for CPU context currently + self._typingctx = registry.cpu_target.typing_context + self._targetctx = registry.cpu_target.target_context + self._install_type(self._typingctx) + self.neighborhood = self.options.get("neighborhood") + self._type_cache = {} + self._lower_me = StencilFuncLowerer(self) + + def replace_return_with_setitem(self, blocks, index_vars, out_name): + """ + Find return statements in the IR and replace them with a SetItem + call of the value "returned" by the kernel into the result array. + Returns the block labels that contained return statements. + """ + ret_blocks = [] + + for label, block in blocks.items(): + scope = block.scope + loc = block.loc + new_body = [] + for stmt in block.body: + if isinstance(stmt, ir.Return): + ret_blocks.append(label) + # If 1D array then avoid the tuple construction. + if len(index_vars) == 1: + rvar = ir.Var(scope, out_name, loc) + ivar = ir.Var(scope, index_vars[0], loc) + new_body.append(ir.SetItem(rvar, ivar, stmt.value, loc)) + else: + # Convert the string names of the index variables into + # ir.Var's. + var_index_vars = [] + for one_var in index_vars: + index_var = ir.Var(scope, one_var, loc) + var_index_vars += [index_var] + + s_index_var = scope.redefine("stencil_index", loc) + # Build a tuple from the index ir.Var's. + tuple_call = ir.Expr.build_tuple(var_index_vars, loc) + new_body.append(ir.Assign(tuple_call, s_index_var, loc)) + rvar = ir.Var(scope, out_name, loc) + # Write the return statements original value into + # the array using the tuple index. + si = ir.SetItem(rvar, s_index_var, stmt.value, loc) + new_body.append(si) + else: + new_body.append(stmt) + block.body = new_body + return ret_blocks + + def add_indices_to_kernel(self, kernel, index_names, ndim, + neighborhood, standard_indexed, typemap, calltypes): + """ + Transforms the stencil kernel as specified by the user into one + that includes each dimension's index variable as part of the getitem + calls. So, in effect array[-1] becomes array[index0-1]. + """ + const_dict = {} + kernel_consts = [] + + if config.DEBUG_ARRAY_OPT >= 1: + print("add_indices_to_kernel", ndim, neighborhood) + ir_utils.dump_blocks(kernel.blocks) + + if neighborhood is None: + need_to_calc_kernel = True + else: + need_to_calc_kernel = False + if len(neighborhood) != ndim: + raise NumbaValueError("%d dimensional neighborhood specified " + "for %d dimensional input array" % + (len(neighborhood), ndim)) + + tuple_table = ir_utils.get_tuple_table(kernel.blocks) + + relatively_indexed = set() + + for block in kernel.blocks.values(): + scope = block.scope + loc = block.loc + new_body = [] + for stmt in block.body: + if (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Const)): + if config.DEBUG_ARRAY_OPT >= 1: + print("remembering in const_dict", stmt.target.name, + stmt.value.value) + # Remember consts for use later. + const_dict[stmt.target.name] = stmt.value.value + if ((isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['setitem', 'static_setitem'] + and stmt.value.value.name in kernel.arg_names) or + (isinstance(stmt, ir.SetItem) + and stmt.target.name in kernel.arg_names)): + raise NumbaValueError("Assignments to arrays passed to " \ + "stencil kernels is not allowed.") + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['getitem', 'static_getitem'] + and stmt.value.value.name in kernel.arg_names + and stmt.value.value.name not in standard_indexed): + # We found a getitem from the input array. + if stmt.value.op == 'getitem': + stmt_index_var = stmt.value.index + else: + stmt_index_var = stmt.value.index_var + # allow static_getitem since rewrite passes are applied + #raise ValueError("Unexpected static_getitem in add_indices_to_kernel.") + + relatively_indexed.add(stmt.value.value.name) + + # Store the index used after looking up the variable in + # the const dictionary. + if need_to_calc_kernel: + assert hasattr(stmt_index_var, 'name') + + if stmt_index_var.name in tuple_table: + kernel_consts += [tuple_table[stmt_index_var.name]] + elif stmt_index_var.name in const_dict: + kernel_consts += [const_dict[stmt_index_var.name]] + else: + raise NumbaValueError("stencil kernel index is not " + "constant, 'neighborhood' option required") + + if ndim == 1: + # Single dimension always has index variable 'index0'. + # tmpvar will hold the real index and is computed by + # adding the relative offset in stmt.value.index to + # the current absolute location in index0. + index_var = ir.Var(scope, index_names[0], loc) + tmpvar = scope.redefine("stencil_index", loc) + stmt_index_var_typ = typemap[stmt_index_var.name] + # If the array is indexed with a slice then we + # have to add the index value with a call to + # slice_addition. + if isinstance(stmt_index_var_typ, types.misc.SliceType): + sa_var = scope.redefine("slice_addition", loc) + sa_func = numba.njit(slice_addition) + sa_func_typ = types.functions.Dispatcher(sa_func) + typemap[sa_var.name] = sa_func_typ + g_sa = ir.Global("slice_addition", sa_func, loc) + new_body.append(ir.Assign(g_sa, sa_var, loc)) + slice_addition_call = ir.Expr.call(sa_var, [stmt_index_var, index_var], (), loc) + calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [stmt_index_var_typ, types.intp], {}) + new_body.append(ir.Assign(slice_addition_call, tmpvar, loc)) + new_body.append(ir.Assign( + ir.Expr.getitem(stmt.value.value, tmpvar, loc), + stmt.target, loc)) + else: + acc_call = ir.Expr.binop(operator.add, stmt_index_var, + index_var, loc) + new_body.append(ir.Assign(acc_call, tmpvar, loc)) + new_body.append(ir.Assign( + ir.Expr.getitem(stmt.value.value, tmpvar, loc), + stmt.target, loc)) + else: + index_vars = [] + sum_results = [] + s_index_var = scope.redefine("stencil_index", loc) + const_index_vars = [] + ind_stencils = [] + + stmt_index_var_typ = typemap[stmt_index_var.name] + # Same idea as above but you have to extract + # individual elements out of the tuple indexing + # expression and add the corresponding index variable + # to them and then reconstitute as a tuple that can + # index the array. + for dim in range(ndim): + tmpvar = scope.redefine("const_index", loc) + new_body.append(ir.Assign(ir.Const(dim, loc), + tmpvar, loc)) + const_index_vars += [tmpvar] + index_var = ir.Var(scope, index_names[dim], loc) + index_vars += [index_var] + + tmpvar = scope.redefine("ind_stencil_index", loc) + ind_stencils += [tmpvar] + getitemvar = scope.redefine("getitem", loc) + getitemcall = ir.Expr.getitem(stmt_index_var, + const_index_vars[dim], loc) + new_body.append(ir.Assign(getitemcall, getitemvar, loc)) + # Get the type of this particular part of the index tuple. + if isinstance(stmt_index_var_typ, types.ConstSized): + one_index_typ = stmt_index_var_typ[dim] + else: + one_index_typ = stmt_index_var_typ[:] + # If the array is indexed with a slice then we + # have to add the index value with a call to + # slice_addition. + if isinstance(one_index_typ, types.misc.SliceType): + sa_var = scope.redefine("slice_addition", loc) + sa_func = numba.njit(slice_addition) + sa_func_typ = types.functions.Dispatcher(sa_func) + typemap[sa_var.name] = sa_func_typ + g_sa = ir.Global("slice_addition", sa_func, loc) + new_body.append(ir.Assign(g_sa, sa_var, loc)) + slice_addition_call = ir.Expr.call(sa_var, [getitemvar, index_vars[dim]], (), loc) + calltypes[slice_addition_call] = sa_func_typ.get_call_type(self._typingctx, [one_index_typ, types.intp], {}) + new_body.append(ir.Assign(slice_addition_call, tmpvar, loc)) + else: + acc_call = ir.Expr.binop(operator.add, getitemvar, + index_vars[dim], loc) + new_body.append(ir.Assign(acc_call, tmpvar, loc)) + + tuple_call = ir.Expr.build_tuple(ind_stencils, loc) + new_body.append(ir.Assign(tuple_call, s_index_var, loc)) + new_body.append(ir.Assign( + ir.Expr.getitem(stmt.value.value,s_index_var,loc), + stmt.target,loc)) + else: + new_body.append(stmt) + block.body = new_body + + if need_to_calc_kernel: + # Find the size of the kernel by finding the maximum absolute value + # index used in the kernel specification. + neighborhood = [[0,0] for _ in range(ndim)] + if len(kernel_consts) == 0: + raise NumbaValueError("Stencil kernel with no accesses to " + "relatively indexed arrays.") + + for index in kernel_consts: + if isinstance(index, tuple) or isinstance(index, list): + for i in range(len(index)): + te = index[i] + if isinstance(te, ir.Var) and te.name in const_dict: + te = const_dict[te.name] + if isinstance(te, int): + neighborhood[i][0] = min(neighborhood[i][0], te) + neighborhood[i][1] = max(neighborhood[i][1], te) + else: + raise NumbaValueError( + "stencil kernel index is not constant," + "'neighborhood' option required") + index_len = len(index) + elif isinstance(index, int): + neighborhood[0][0] = min(neighborhood[0][0], index) + neighborhood[0][1] = max(neighborhood[0][1], index) + index_len = 1 + else: + raise NumbaValueError( + "Non-tuple or non-integer used as stencil index.") + if index_len != ndim: + raise NumbaValueError( + "Stencil index does not match array dimensionality.") + + return (neighborhood, relatively_indexed) + + + def get_return_type(self, argtys): + if config.DEBUG_ARRAY_OPT >= 1: + print("get_return_type", argtys) + ir_utils.dump_blocks(self.kernel_ir.blocks) + + if not isinstance(argtys[0], types.npytypes.Array): + raise NumbaValueError("The first argument to a stencil kernel must " + "be the primary input array.") + + from numba.core import typed_passes + typemap, return_type, calltypes, _ = typed_passes.type_inference_stage( + self._typingctx, + self._targetctx, + self.kernel_ir, + argtys, + None, + {}) + if isinstance(return_type, types.npytypes.Array): + raise NumbaValueError( + "Stencil kernel must return a scalar and not a numpy array.") + + real_ret = types.npytypes.Array(return_type, argtys[0].ndim, + argtys[0].layout) + return (real_ret, typemap, calltypes) + + def _install_type(self, typingctx): + """Constructs and installs a typing class for a StencilFunc object in + the input typing context. + """ + _ty_cls = type('StencilFuncTyping_' + + str(self.id), + (AbstractTemplate,), + dict(key=self, generic=self._type_me)) + typingctx.insert_user_function(self, _ty_cls) + + def compile_for_argtys(self, argtys, kwtys, return_type, sigret): + # look in the type cache to find if result array is passed + (_, result, typemap, calltypes) = self._type_cache[argtys] + new_func = self._stencil_wrapper(result, sigret, return_type, + typemap, calltypes, *argtys) + return new_func + + def _type_me(self, argtys, kwtys): + """ + Implement AbstractTemplate.generic() for the typing class + built by StencilFunc._install_type(). + Return the call-site signature. + """ + if (self.neighborhood is not None and + len(self.neighborhood) != argtys[0].ndim): + raise NumbaValueError("%d dimensional neighborhood specified " + "for %d dimensional input array" % + (len(self.neighborhood), argtys[0].ndim)) + + argtys_extra = argtys + sig_extra = "" + result = None + if 'out' in kwtys: + argtys_extra += (kwtys['out'],) + sig_extra += ", out=None" + result = kwtys['out'] + + if 'neighborhood' in kwtys: + argtys_extra += (kwtys['neighborhood'],) + sig_extra += ", neighborhood=None" + + # look in the type cache first + if argtys_extra in self._type_cache: + (_sig, _, _, _) = self._type_cache[argtys_extra] + return _sig + + (real_ret, typemap, calltypes) = self.get_return_type(argtys) + sig = signature(real_ret, *argtys_extra) + dummy_text = ("def __numba_dummy_stencil({}{}):\n pass\n".format( + ",".join(self.kernel_ir.arg_names), sig_extra)) + dct = {} + exec(dummy_text, dct) + dummy_func = dct["__numba_dummy_stencil"] + sig = sig.replace(pysig=utils.pysignature(dummy_func)) + self._targetctx.insert_func_defn([(self._lower_me, self, argtys_extra)]) + self._type_cache[argtys_extra] = (sig, result, typemap, calltypes) + return sig + + def copy_ir_with_calltypes(self, ir, calltypes): + """ + Create a copy of a given IR along with its calltype information. + We need a copy of the calltypes because copy propagation applied + to the copied IR will change the calltypes and make subsequent + uses of the original IR invalid. + """ + copy_calltypes = {} + kernel_copy = ir.copy() + kernel_copy.blocks = {} + # For each block... + for (block_label, block) in ir.blocks.items(): + new_block = copy.deepcopy(ir.blocks[block_label]) + new_block.body = [] + # For each statement in each block... + for stmt in ir.blocks[block_label].body: + # Copy the statement to the new copy of the kernel + # and if the original statement is in the original + # calltypes then add the type associated with this + # statement to the calltypes copy. + scopy = copy.deepcopy(stmt) + new_block.body.append(scopy) + if stmt in calltypes: + copy_calltypes[scopy] = calltypes[stmt] + kernel_copy.blocks[block_label] = new_block + return (kernel_copy, copy_calltypes) + + def _stencil_wrapper(self, result, sigret, return_type, typemap, calltypes, *args): + # Overall approach: + # 1) Construct a string containing a function definition for the stencil function + # that will execute the stencil kernel. This function definition includes a + # unique stencil function name, the parameters to the stencil kernel, loop + # nests across the dimensions of the input array. Those loop nests use the + # computed stencil kernel size so as not to try to compute elements where + # elements outside the bounds of the input array would be needed. + # 2) The but of the loop nest in this new function is a special sentinel + # assignment. + # 3) Get the IR of this new function. + # 4) Split the block containing the sentinel assignment and remove the sentinel + # assignment. Insert the stencil kernel IR into the stencil function IR + # after label and variable renaming of the stencil kernel IR to prevent + # conflicts with the stencil function IR. + # 5) Compile the combined stencil function IR + stencil kernel IR into existence. + + # Copy the kernel so that our changes for this callsite + # won't effect other callsites. + (kernel_copy, copy_calltypes) = self.copy_ir_with_calltypes( + self.kernel_ir, calltypes) + # The stencil kernel body becomes the body of a loop, for which args aren't needed. + ir_utils.remove_args(kernel_copy.blocks) + first_arg = kernel_copy.arg_names[0] + + in_cps, out_cps = ir_utils.copy_propagate(kernel_copy.blocks, typemap) + name_var_table = ir_utils.get_name_var_table(kernel_copy.blocks) + ir_utils.apply_copy_propagate( + kernel_copy.blocks, + in_cps, + name_var_table, + typemap, + copy_calltypes) + + if "out" in name_var_table: + raise NumbaValueError("Cannot use the reserved word 'out' in stencil kernels.") + + sentinel_name = ir_utils.get_unused_var_name("__sentinel__", name_var_table) + if config.DEBUG_ARRAY_OPT >= 1: + print("name_var_table", name_var_table, sentinel_name) + + the_array = args[0] + + if config.DEBUG_ARRAY_OPT >= 1: + print("_stencil_wrapper", return_type, return_type.dtype, + type(return_type.dtype), args) + ir_utils.dump_blocks(kernel_copy.blocks) + + # We generate a Numba function to execute this stencil and here + # create the unique name of this function. + stencil_func_name = "__numba_stencil_%s_%s" % ( + hex(id(the_array)).replace("-", "_"), + self.id) + + # We will put a loop nest in the generated function for each + # dimension in the input array. Here we create the name for + # the index variable for each dimension. index0, index1, ... + index_vars = [] + for i in range(the_array.ndim): + index_var_name = ir_utils.get_unused_var_name("index" + str(i), + name_var_table) + index_vars += [index_var_name] + + # Create extra signature for out and neighborhood. + out_name = ir_utils.get_unused_var_name("out", name_var_table) + neighborhood_name = ir_utils.get_unused_var_name("neighborhood", + name_var_table) + sig_extra = "" + if result is not None: + sig_extra += ", {}=None".format(out_name) + if "neighborhood" in dict(self.kws): + sig_extra += ", {}=None".format(neighborhood_name) + + # Get a list of the standard indexed array names. + standard_indexed = self.options.get("standard_indexing", []) + + if first_arg in standard_indexed: + raise NumbaValueError("The first argument to a stencil kernel must " + "use relative indexing, not standard indexing.") + + if len(set(standard_indexed) - set(kernel_copy.arg_names)) != 0: + raise NumbaValueError("Standard indexing requested for an array name " + "not present in the stencil kernel definition.") + + # Add index variables to getitems in the IR to transition the accesses + # in the kernel from relative to regular Python indexing. Returns the + # computed size of the stencil kernel and a list of the relatively indexed + # arrays. + kernel_size, relatively_indexed = self.add_indices_to_kernel( + kernel_copy, index_vars, the_array.ndim, + self.neighborhood, standard_indexed, typemap, copy_calltypes) + if self.neighborhood is None: + self.neighborhood = kernel_size + + if config.DEBUG_ARRAY_OPT >= 1: + print("After add_indices_to_kernel") + ir_utils.dump_blocks(kernel_copy.blocks) + + # The return in the stencil kernel becomes a setitem for that + # particular point in the iteration space. + ret_blocks = self.replace_return_with_setitem(kernel_copy.blocks, + index_vars, out_name) + + if config.DEBUG_ARRAY_OPT >= 1: + print("After replace_return_with_setitem", ret_blocks) + ir_utils.dump_blocks(kernel_copy.blocks) + + # Start to form the new function to execute the stencil kernel. + func_text = "def {}({}{}):\n".format(stencil_func_name, + ",".join(kernel_copy.arg_names), sig_extra) + + # Get loop ranges for each dimension, which could be either int + # or variable. In the latter case we'll use the extra neighborhood + # argument to the function. + ranges = [] + for i in range(the_array.ndim): + if isinstance(kernel_size[i][0], int): + lo = kernel_size[i][0] + hi = kernel_size[i][1] + else: + lo = "{}[{}][0]".format(neighborhood_name, i) + hi = "{}[{}][1]".format(neighborhood_name, i) + ranges.append((lo, hi)) + + # If there are more than one relatively indexed arrays, add a call to + # a function that will raise an error if any of the relatively indexed + # arrays are of different size than the first input array. + if len(relatively_indexed) > 1: + func_text += " raise_if_incompatible_array_sizes(" + first_arg + for other_array in relatively_indexed: + if other_array != first_arg: + func_text += "," + other_array + func_text += ")\n" + + # Get the shape of the first input array. + shape_name = ir_utils.get_unused_var_name("full_shape", name_var_table) + func_text += " {} = {}.shape\n".format(shape_name, first_arg) + + # Converts cval to a string constant + def cval_as_str(cval): + if not np.isfinite(cval): + # See if this is a string-repr numerical const, issue #7286 + if np.isnan(cval): + return "np.nan" + elif np.isinf(cval): + if cval < 0: + return "-np.inf" + else: + return "np.inf" + else: + return str(cval) + + # If we have to allocate the output array (the out argument was not used) + # then us numpy.full if the user specified a cval stencil decorator option + # or np.zeros if they didn't to allocate the array. + if result is None: + return_type_name = numpy_support.as_dtype( + return_type.dtype).type.__name__ + out_init ="{} = np.empty({}, dtype=np.{})\n".format( + out_name, shape_name, return_type_name) + + if "cval" in self.options: + cval = self.options["cval"] + cval_ty = typing.typeof.typeof(cval) + if not self._typingctx.can_convert(cval_ty, return_type.dtype): + msg = "cval type does not match stencil return type." + raise NumbaValueError(msg) + else: + cval = 0 + func_text += " " + out_init + for dim in range(the_array.ndim): + start_items = [":"] * the_array.ndim + end_items = [":"] * the_array.ndim + start_items[dim] = ":-{}".format(self.neighborhood[dim][0]) + end_items[dim] = "-{}:".format(self.neighborhood[dim][1]) + func_text += " " + "{}[{}] = {}\n".format(out_name, ",".join(start_items), cval_as_str(cval)) + func_text += " " + "{}[{}] = {}\n".format(out_name, ",".join(end_items), cval_as_str(cval)) + else: # result is present, if cval is set then use it + if "cval" in self.options: + cval = self.options["cval"] + cval_ty = typing.typeof.typeof(cval) + if not self._typingctx.can_convert(cval_ty, return_type.dtype): + msg = "cval type does not match stencil return type." + raise NumbaValueError(msg) + out_init = "{}[:] = {}\n".format(out_name, cval_as_str(cval)) + func_text += " " + out_init + + offset = 1 + # Add the loop nests to the new function. + for i in range(the_array.ndim): + for j in range(offset): + func_text += " " + # ranges[i][0] is the minimum index used in the i'th dimension + # but minimum's greater than 0 don't preclude any entry in the array. + # So, take the minimum of 0 and the minimum index found in the kernel + # and this will be a negative number (potentially -0). Then, we do + # unary - on that to get the positive offset in this dimension whose + # use is precluded. + # ranges[i][1] is the maximum of 0 and the observed maximum index + # in this dimension because negative maximums would not cause us to + # preclude any entry in the array from being used. + func_text += ("for {} in range(-min(0,{})," + "{}[{}]-max(0,{})):\n").format( + index_vars[i], + ranges[i][0], + shape_name, + i, + ranges[i][1]) + offset += 1 + + for j in range(offset): + func_text += " " + # Put a sentinel in the code so we can locate it in the IR. We will + # remove this sentinel assignment and replace it with the IR for the + # stencil kernel body. + func_text += "{} = 0\n".format(sentinel_name) + func_text += " return {}\n".format(out_name) + + if config.DEBUG_ARRAY_OPT >= 1: + print("new stencil func text") + print(func_text) + + # Force the new stencil function into existence. + dct = {} + dct.update(globals()) + exec(func_text, dct) + stencil_func = dct[stencil_func_name] + if sigret is not None: + pysig = utils.pysignature(stencil_func) + sigret.pysig = pysig + # Get the IR for the newly created stencil function. + from numba.core import compiler + stencil_ir = compiler.run_frontend(stencil_func) + ir_utils.remove_dels(stencil_ir.blocks) + + # rename all variables in stencil_ir afresh + var_table = ir_utils.get_name_var_table(stencil_ir.blocks) + new_var_dict = {} + reserved_names = ([sentinel_name, out_name, neighborhood_name, + shape_name] + kernel_copy.arg_names + index_vars) + for name, var in var_table.items(): + if not name in reserved_names: + assert isinstance(var, ir.Var) + new_var = var.scope.redefine(var.name, var.loc) + new_var_dict[name] = new_var.name + ir_utils.replace_var_names(stencil_ir.blocks, new_var_dict) + + stencil_stub_last_label = max(stencil_ir.blocks.keys()) + 1 + + # Shift labels in the kernel copy so they are guaranteed unique + # and don't conflict with any labels in the stencil_ir. + kernel_copy.blocks = ir_utils.add_offset_to_labels( + kernel_copy.blocks, stencil_stub_last_label) + new_label = max(kernel_copy.blocks.keys()) + 1 + # Adjust ret_blocks to account for addition of the offset. + ret_blocks = [x + stencil_stub_last_label for x in ret_blocks] + + if config.DEBUG_ARRAY_OPT >= 1: + print("ret_blocks w/ offsets", ret_blocks, stencil_stub_last_label) + print("before replace sentinel stencil_ir") + ir_utils.dump_blocks(stencil_ir.blocks) + print("before replace sentinel kernel_copy") + ir_utils.dump_blocks(kernel_copy.blocks) + + # Search all the block in the stencil outline for the sentinel. + for label, block in stencil_ir.blocks.items(): + for i, inst in enumerate(block.body): + if (isinstance( inst, ir.Assign) and + inst.target.name == sentinel_name): + # We found the sentinel assignment. + loc = inst.loc + scope = block.scope + # split block across __sentinel__ + # A new block is allocated for the statements prior to the + # sentinel but the new block maintains the current block + # label. + prev_block = ir.Block(scope, loc) + prev_block.body = block.body[:i] + # The current block is used for statements after sentinel. + block.body = block.body[i + 1:] + # But the current block gets a new label. + body_first_label = min(kernel_copy.blocks.keys()) + + # The previous block jumps to the minimum labelled block of + # the parfor body. + prev_block.append(ir.Jump(body_first_label, loc)) + # Add all the parfor loop body blocks to the gufunc + # function's IR. + for (l, b) in kernel_copy.blocks.items(): + stencil_ir.blocks[l] = b + + stencil_ir.blocks[new_label] = block + stencil_ir.blocks[label] = prev_block + # Add a jump from all the blocks that previously contained + # a return in the stencil kernel to the block + # containing statements after the sentinel. + for ret_block in ret_blocks: + stencil_ir.blocks[ret_block].append( + ir.Jump(new_label, loc)) + break + else: + continue + break + + stencil_ir.blocks = ir_utils.rename_labels(stencil_ir.blocks) + ir_utils.remove_dels(stencil_ir.blocks) + + assert(isinstance(the_array, types.Type)) + array_types = args + + new_stencil_param_types = list(array_types) + + if config.DEBUG_ARRAY_OPT >= 1: + print("new_stencil_param_types", new_stencil_param_types) + ir_utils.dump_blocks(stencil_ir.blocks) + + # Compile the combined stencil function with the replaced loop + # body in it. + ir_utils.fixup_var_define_in_scope(stencil_ir.blocks) + new_func = compiler.compile_ir( + self._typingctx, + self._targetctx, + stencil_ir, + new_stencil_param_types, + None, + compiler.DEFAULT_FLAGS, + {}) + return new_func + + def __call__(self, *args, **kwargs): + self._typingctx.refresh() + if (self.neighborhood is not None and + len(self.neighborhood) != args[0].ndim): + raise NumbaValueError("{} dimensional neighborhood specified for " + "{} dimensional input array".format( + len(self.neighborhood), args[0].ndim)) + + if 'out' in kwargs: + result = kwargs['out'] + rdtype = result.dtype + rttype = numpy_support.from_dtype(rdtype) + result_type = types.npytypes.Array(rttype, result.ndim, + numpy_support.map_layout(result)) + array_types = tuple([typing.typeof.typeof(x) for x in args]) + array_types_full = tuple([typing.typeof.typeof(x) for x in args] + + [result_type]) + else: + result = None + array_types = tuple([typing.typeof.typeof(x) for x in args]) + array_types_full = array_types + + if config.DEBUG_ARRAY_OPT >= 1: + print("__call__", array_types, args, kwargs) + + (real_ret, typemap, calltypes) = self.get_return_type(array_types) + new_func = self._stencil_wrapper(result, None, real_ret, typemap, + calltypes, *array_types_full) + + if result is None: + return new_func.entry_point(*args) + else: + return new_func.entry_point(*(args+(result,))) + +def stencil(func_or_mode='constant', **options): + # called on function without specifying mode style + if not isinstance(func_or_mode, str): + mode = 'constant' # default style + func = func_or_mode + else: + mode = func_or_mode + func = None + + for option in options: + if option not in ["cval", "standard_indexing", "neighborhood"]: + raise NumbaValueError("Unknown stencil option " + option) + + wrapper = _stencil(mode, options) + if func is not None: + return wrapper(func) + return wrapper + +def _stencil(mode, options): + if mode != 'constant': + raise NumbaValueError("Unsupported mode style " + mode) + + def decorated(func): + from numba.core import compiler + kernel_ir = compiler.run_frontend(func) + return StencilFunc(kernel_ir, mode, options) + + return decorated + +@lower_builtin(stencil) +def stencil_dummy_lower(context, builder, sig, args): + "lowering for dummy stencil calls" + return lir.Constant(lir.IntType(types.intp.bitwidth), 0) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencilparfor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencilparfor.py new file mode 100644 index 0000000000000000000000000000000000000000..3b80635d7586135b170c080fe396581ca014f75d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/stencils/stencilparfor.py @@ -0,0 +1,957 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numbers +import copy +import types as pytypes +from operator import add +import operator + +import numpy as np + +import numba.parfors.parfor +from numba.core import types, ir, rewrites, config, ir_utils +from numba.core.typing.templates import infer_global, AbstractTemplate +from numba.core.typing import signature +from numba.core import utils, typing +from numba.core.ir_utils import (get_call_table, mk_unique_var, + compile_to_numba_ir, replace_arg_nodes, guard, + find_callname, require, find_const, GuardException) +from numba.core.errors import NumbaValueError +from numba.core.utils import OPERATORS_TO_BUILTINS +from numba.np import numpy_support + + +def _compute_last_ind(dim_size, index_const): + if index_const > 0: + return dim_size - index_const + else: + return dim_size + +class StencilPass(object): + def __init__(self, func_ir, typemap, calltypes, array_analysis, typingctx, + targetctx, flags): + self.func_ir = func_ir + self.typemap = typemap + self.calltypes = calltypes + self.array_analysis = array_analysis + self.typingctx = typingctx + self.targetctx = targetctx + self.flags = flags + + def run(self): + """ Finds all calls to StencilFuncs in the IR and converts them to parfor. + """ + from numba.stencils.stencil import StencilFunc + + # Get all the calls in the function IR. + call_table, _ = get_call_table(self.func_ir.blocks) + stencil_calls = [] + stencil_dict = {} + for call_varname, call_list in call_table.items(): + for one_call in call_list: + if isinstance(one_call, StencilFunc): + # Remember all calls to StencilFuncs. + stencil_calls.append(call_varname) + stencil_dict[call_varname] = one_call + if not stencil_calls: + return # return early if no stencil calls found + + # find and transform stencil calls + for label, block in self.func_ir.blocks.items(): + for i, stmt in reversed(list(enumerate(block.body))): + # Found a call to a StencilFunc. + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call' + and stmt.value.func.name in stencil_calls): + kws = dict(stmt.value.kws) + # Create dictionary of input argument number to + # the argument itself. + input_dict = {i: stmt.value.args[i] for i in + range(len(stmt.value.args))} + in_args = stmt.value.args + arg_typemap = tuple(self.typemap[i.name] for i in in_args) + for arg_type in arg_typemap: + if isinstance(arg_type, types.BaseTuple): + raise NumbaValueError("Tuple parameters not " \ + "supported for stencil " \ + "kernels in parallel=True " \ + "mode.") + + out_arr = kws.get('out') + + # Get the StencilFunc object corresponding to this call. + sf = stencil_dict[stmt.value.func.name] + stencil_ir, rt, arg_to_arr_dict = get_stencil_ir(sf, + self.typingctx, arg_typemap, + block.scope, block.loc, input_dict, + self.typemap, self.calltypes) + index_offsets = sf.options.get('index_offsets', None) + gen_nodes = self._mk_stencil_parfor(label, in_args, out_arr, + stencil_ir, index_offsets, stmt.target, rt, sf, + arg_to_arr_dict) + block.body = block.body[:i] + gen_nodes + block.body[i+1:] + # Found a call to a stencil via numba.stencil(). + elif (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call' + and guard(find_callname, self.func_ir, stmt.value) + == ('stencil', 'numba')): + # remove dummy stencil() call + stmt.value = ir.Const(0, stmt.loc) + + def replace_return_with_setitem(self, blocks, exit_value_var, + parfor_body_exit_label): + """ + Find return statements in the IR and replace them with a SetItem + call of the value "returned" by the kernel into the result array. + Returns the block labels that contained return statements. + """ + for label, block in blocks.items(): + scope = block.scope + loc = block.loc + new_body = [] + for stmt in block.body: + if isinstance(stmt, ir.Return): + # previous stmt should have been a cast + prev_stmt = new_body.pop() + assert (isinstance(prev_stmt, ir.Assign) + and isinstance(prev_stmt.value, ir.Expr) + and prev_stmt.value.op == 'cast') + + new_body.append(ir.Assign(prev_stmt.value.value, exit_value_var, loc)) + new_body.append(ir.Jump(parfor_body_exit_label, loc)) + else: + new_body.append(stmt) + block.body = new_body + + def _mk_stencil_parfor(self, label, in_args, out_arr, stencil_ir, + index_offsets, target, return_type, stencil_func, + arg_to_arr_dict): + """ Converts a set of stencil kernel blocks to a parfor. + """ + gen_nodes = [] + stencil_blocks = stencil_ir.blocks + + if config.DEBUG_ARRAY_OPT >= 1: + print("_mk_stencil_parfor", label, in_args, out_arr, index_offsets, + return_type, stencil_func, stencil_blocks) + ir_utils.dump_blocks(stencil_blocks) + + in_arr = in_args[0] + # run copy propagate to replace in_args copies (e.g. a = A) + in_arr_typ = self.typemap[in_arr.name] + in_cps, out_cps = ir_utils.copy_propagate(stencil_blocks, self.typemap) + name_var_table = ir_utils.get_name_var_table(stencil_blocks) + + ir_utils.apply_copy_propagate( + stencil_blocks, + in_cps, + name_var_table, + self.typemap, + self.calltypes) + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after copy_propagate") + ir_utils.dump_blocks(stencil_blocks) + ir_utils.remove_dead(stencil_blocks, self.func_ir.arg_names, stencil_ir, + self.typemap) + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after removing dead code") + ir_utils.dump_blocks(stencil_blocks) + + # create parfor vars + ndims = self.typemap[in_arr.name].ndim + scope = in_arr.scope + loc = in_arr.loc + parfor_vars = [] + for i in range(ndims): + parfor_var = ir.Var(scope, mk_unique_var( + "$parfor_index_var"), loc) + self.typemap[parfor_var.name] = types.intp + parfor_vars.append(parfor_var) + + start_lengths, end_lengths = self._replace_stencil_accesses( + stencil_ir, parfor_vars, in_args, index_offsets, stencil_func, + arg_to_arr_dict) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after replace stencil accesses") + print("start_lengths:", start_lengths) + print("end_lengths:", end_lengths) + ir_utils.dump_blocks(stencil_blocks) + + # create parfor loop nests + loopnests = [] + equiv_set = self.array_analysis.get_equiv_set(label) + in_arr_dim_sizes = equiv_set.get_shape(in_arr) + + assert ndims == len(in_arr_dim_sizes) + start_inds = [] + last_inds = [] + for i in range(ndims): + last_ind = self._get_stencil_last_ind(in_arr_dim_sizes[i], + end_lengths[i], gen_nodes, scope, loc) + start_ind = self._get_stencil_start_ind( + start_lengths[i], gen_nodes, scope, loc) + start_inds.append(start_ind) + last_inds.append(last_ind) + # start from stencil size to avoid invalid array access + loopnests.append(numba.parfors.parfor.LoopNest(parfor_vars[i], + start_ind, last_ind, 1)) + + # We have to guarantee that the exit block has maximum label and that + # there's only one exit block for the parfor body. + # So, all return statements will change to jump to the parfor exit block. + parfor_body_exit_label = max(stencil_blocks.keys()) + 1 + stencil_blocks[parfor_body_exit_label] = ir.Block(scope, loc) + exit_value_var = ir.Var(scope, mk_unique_var("$parfor_exit_value"), loc) + self.typemap[exit_value_var.name] = return_type.dtype + + # create parfor index var + for_replacing_ret = [] + if ndims == 1: + parfor_ind_var = parfor_vars[0] + else: + parfor_ind_var = ir.Var(scope, mk_unique_var( + "$parfor_index_tuple_var"), loc) + self.typemap[parfor_ind_var.name] = types.containers.UniTuple( + types.intp, ndims) + tuple_call = ir.Expr.build_tuple(parfor_vars, loc) + tuple_assign = ir.Assign(tuple_call, parfor_ind_var, loc) + for_replacing_ret.append(tuple_assign) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after creating parfor index var") + ir_utils.dump_blocks(stencil_blocks) + + # empty init block + init_block = ir.Block(scope, loc) + if out_arr is None: + in_arr_typ = self.typemap[in_arr.name] + + shape_name = ir_utils.mk_unique_var("in_arr_shape") + shape_var = ir.Var(scope, shape_name, loc) + shape_getattr = ir.Expr.getattr(in_arr, "shape", loc) + self.typemap[shape_name] = types.containers.UniTuple(types.intp, + in_arr_typ.ndim) + init_block.body.extend([ir.Assign(shape_getattr, shape_var, loc)]) + + zero_name = ir_utils.mk_unique_var("zero_val") + zero_var = ir.Var(scope, zero_name, loc) + if "cval" in stencil_func.options: + cval = stencil_func.options["cval"] + # TODO: Loosen this restriction to adhere to casting rules. + cval_ty = typing.typeof.typeof(cval) + if not self.typingctx.can_convert(cval_ty, return_type.dtype): + raise NumbaValueError("cval type does not match stencil " \ + "return type.") + + temp2 = return_type.dtype(cval) + else: + temp2 = return_type.dtype(0) + full_const = ir.Const(temp2, loc) + self.typemap[zero_name] = return_type.dtype + init_block.body.extend([ir.Assign(full_const, zero_var, loc)]) + + so_name = ir_utils.mk_unique_var("stencil_output") + out_arr = ir.Var(scope, so_name, loc) + self.typemap[out_arr.name] = numba.core.types.npytypes.Array( + return_type.dtype, + in_arr_typ.ndim, + in_arr_typ.layout) + dtype_g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc) + self.typemap[dtype_g_np_var.name] = types.misc.Module(np) + dtype_g_np = ir.Global('np', np, loc) + dtype_g_np_assign = ir.Assign(dtype_g_np, dtype_g_np_var, loc) + init_block.body.append(dtype_g_np_assign) + + return_type_name = numpy_support.as_dtype( + return_type.dtype).type.__name__ + if return_type_name == 'bool': + return_type_name = 'bool_' + dtype_np_attr_call = ir.Expr.getattr(dtype_g_np_var, return_type_name, loc) + dtype_attr_var = ir.Var(scope, mk_unique_var("$np_attr_attr"), loc) + self.typemap[dtype_attr_var.name] = types.functions.NumberClass(return_type.dtype) + dtype_attr_assign = ir.Assign(dtype_np_attr_call, dtype_attr_var, loc) + init_block.body.append(dtype_attr_assign) + + stmts = ir_utils.gen_np_call("empty", + np.empty, + out_arr, + [shape_var, dtype_attr_var], + self.typingctx, + self.typemap, + self.calltypes) + # ------------------ + # Generate the code to fill just the border with zero_var. + + # Generate a none var to use in slicing. + none_var = ir.Var(scope, mk_unique_var("$none_var"), loc) + none_assign = ir.Assign(ir.Const(None, loc), none_var, loc) + stmts.append(none_assign) + self.typemap[none_var.name] = types.none + # Generate a zero var to use in slicing. + zero_index_var = ir.Var(scope, mk_unique_var("$zero_index_var"), loc) + zero_index_assign = ir.Assign(ir.Const(0, loc), zero_index_var, loc) + stmts.append(zero_index_assign) + self.typemap[zero_index_var.name] = types.intp + # Generate generic ":" slice. + # ---- Generate var to hold slice func var. + slice_func_var = ir.Var(scope, mk_unique_var("$slice_func_var"), loc) + slice_fn_ty = self.typingctx.resolve_value_type(slice) + self.typemap[slice_func_var.name] = slice_fn_ty + slice_g = ir.Global('slice', slice, loc) + slice_assign = ir.Assign(slice_g, slice_func_var, loc) + stmts.append(slice_assign) + # ---- Generate call to slice func. + sig = self.typingctx.resolve_function_type(slice_fn_ty, + (types.none,) * 2, + {}) + slice_callexpr = ir.Expr.call(func=slice_func_var, + args=(none_var, none_var), + kws=(), + loc=loc) + self.calltypes[slice_callexpr] = sig + # ---- Generate slice var + slice_var = ir.Var(scope, mk_unique_var("$slice"), loc) + self.typemap[slice_var.name] = types.slice2_type + slice_assign = ir.Assign(slice_callexpr, slice_var, loc) + stmts.append(slice_assign) + + def handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + border_inds, + border_tuple_items, + other_arg, + other_first): + # Handle the border for start or end of the index range. + # ---- Generate call to slice func. + sig = self.typingctx.resolve_function_type( + slice_fn_ty, + (types.intp,) * 2, + {}) + si = border_inds[dim] + assert(isinstance(si, (int, ir.Var))) + si_var = ir.Var(scope, mk_unique_var("$border_ind"), loc) + self.typemap[si_var.name] = types.intp + if isinstance(si, int): + si_assign = ir.Assign(ir.Const(si, loc), si_var, loc) + else: + si_assign = ir.Assign(si, si_var, loc) + stmts.append(si_assign) + + slice_callexpr = ir.Expr.call( + func=slice_func_var, + args=(other_arg, si_var) if other_first else (si_var, other_arg), + kws=(), + loc=loc) + self.calltypes[slice_callexpr] = sig + # ---- Generate slice var + border_slice_var = ir.Var(scope, mk_unique_var("$slice"), loc) + self.typemap[border_slice_var.name] = types.slice2_type + slice_assign = ir.Assign(slice_callexpr, border_slice_var, loc) + stmts.append(slice_assign) + + border_tuple_items[dim] = border_slice_var + border_ind_var = ir.Var(scope, mk_unique_var( + "$border_index_tuple_var"), loc) + self.typemap[border_ind_var.name] = types.containers.UniTuple( + types.slice2_type, ndims) + tuple_call = ir.Expr.build_tuple(border_tuple_items, loc) + tuple_assign = ir.Assign(tuple_call, border_ind_var, loc) + stmts.append(tuple_assign) + + setitem_call = ir.SetItem(out_arr, border_ind_var, zero_var, loc) + self.calltypes[setitem_call] = signature( + types.none, self.typemap[out_arr.name], + self.typemap[border_ind_var.name], + self.typemap[out_arr.name].dtype + ) + stmts.append(setitem_call) + + # For each dimension, add setitem to set border values. + for dim in range(in_arr_typ.ndim): + # First, fill all entries with ":". + start_tuple_items = [slice_var] * in_arr_typ.ndim + last_tuple_items = [slice_var] * in_arr_typ.ndim + + handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + start_inds, + start_tuple_items, + zero_index_var, + True) + handle_border(slice_fn_ty, + dim, + scope, + loc, + slice_func_var, + stmts, + last_inds, + last_tuple_items, + in_arr_dim_sizes[dim], + False) + + # ------------------ + + equiv_set.insert_equiv(out_arr, in_arr_dim_sizes) + init_block.body.extend(stmts) + else: # out is present + if "cval" in stencil_func.options: # do out[:] = cval + cval = stencil_func.options["cval"] + # TODO: Loosen this restriction to adhere to casting rules. + cval_ty = typing.typeof.typeof(cval) + if not self.typingctx.can_convert(cval_ty, return_type.dtype): + msg = "cval type does not match stencil return type." + raise NumbaValueError(msg) + + # get slice ref + slice_var = ir.Var(scope, mk_unique_var("$py_g_var"), loc) + slice_fn_ty = self.typingctx.resolve_value_type(slice) + self.typemap[slice_var.name] = slice_fn_ty + slice_g = ir.Global('slice', slice, loc) + slice_assigned = ir.Assign(slice_g, slice_var, loc) + init_block.body.append(slice_assigned) + + sig = self.typingctx.resolve_function_type(slice_fn_ty, + (types.none,) * 2, + {}) + + callexpr = ir.Expr.call(func=slice_var, args=(), kws=(), + loc=loc) + + self.calltypes[callexpr] = sig + slice_inst_var = ir.Var(scope, mk_unique_var("$slice_inst"), + loc) + self.typemap[slice_inst_var.name] = types.slice2_type + slice_assign = ir.Assign(callexpr, slice_inst_var, loc) + init_block.body.append(slice_assign) + + # get const val for cval + cval_const_val = ir.Const(return_type.dtype(cval), loc) + cval_const_var = ir.Var(scope, mk_unique_var("$cval_const"), + loc) + self.typemap[cval_const_var.name] = return_type.dtype + cval_const_assign = ir.Assign(cval_const_val, + cval_const_var, loc) + init_block.body.append(cval_const_assign) + + # do setitem on `out` array + setitemexpr = ir.StaticSetItem(out_arr, slice(None, None), + slice_inst_var, cval_const_var, + loc) + init_block.body.append(setitemexpr) + sig = signature(types.none, self.typemap[out_arr.name], + self.typemap[slice_inst_var.name], + self.typemap[out_arr.name].dtype) + self.calltypes[setitemexpr] = sig + + + self.replace_return_with_setitem(stencil_blocks, exit_value_var, + parfor_body_exit_label) + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after replacing return") + ir_utils.dump_blocks(stencil_blocks) + + setitem_call = ir.SetItem(out_arr, parfor_ind_var, exit_value_var, loc) + self.calltypes[setitem_call] = signature( + types.none, self.typemap[out_arr.name], + self.typemap[parfor_ind_var.name], + self.typemap[out_arr.name].dtype + ) + stencil_blocks[parfor_body_exit_label].body.extend(for_replacing_ret) + stencil_blocks[parfor_body_exit_label].body.append(setitem_call) + + # simplify CFG of parfor body (exit block could be simplified often) + # add dummy return to enable CFG + dummy_loc = ir.Loc("stencilparfor_dummy", -1) + ret_const_var = ir.Var(scope, mk_unique_var("$cval_const"), dummy_loc) + cval_const_assign = ir.Assign(ir.Const(0, loc=dummy_loc), ret_const_var, dummy_loc) + stencil_blocks[parfor_body_exit_label].body.append(cval_const_assign) + + stencil_blocks[parfor_body_exit_label].body.append( + ir.Return(ret_const_var, dummy_loc), + ) + stencil_blocks = ir_utils.simplify_CFG(stencil_blocks) + stencil_blocks[max(stencil_blocks.keys())].body.pop() + + if config.DEBUG_ARRAY_OPT >= 1: + print("stencil_blocks after adding SetItem") + ir_utils.dump_blocks(stencil_blocks) + + pattern = ('stencil', [start_lengths, end_lengths]) + parfor = numba.parfors.parfor.Parfor(loopnests, init_block, stencil_blocks, + loc, parfor_ind_var, equiv_set, pattern, self.flags) + gen_nodes.append(parfor) + gen_nodes.append(ir.Assign(out_arr, target, loc)) + return gen_nodes + + def _get_stencil_last_ind(self, dim_size, end_length, gen_nodes, scope, + loc): + last_ind = dim_size + if end_length != 0: + # set last index to size minus stencil size to avoid invalid + # memory access + index_const = ir.Var(scope, mk_unique_var("stencil_const_var"), + loc) + self.typemap[index_const.name] = types.intp + if isinstance(end_length, numbers.Number): + const_assign = ir.Assign(ir.Const(end_length, loc), + index_const, loc) + else: + const_assign = ir.Assign(end_length, index_const, loc) + + gen_nodes.append(const_assign) + last_ind = ir.Var(scope, mk_unique_var("last_ind"), loc) + self.typemap[last_ind.name] = types.intp + + g_var = ir.Var(scope, mk_unique_var("compute_last_ind_var"), loc) + check_func = numba.njit(_compute_last_ind) + func_typ = types.functions.Dispatcher(check_func) + self.typemap[g_var.name] = func_typ + g_obj = ir.Global("_compute_last_ind", check_func, loc) + g_assign = ir.Assign(g_obj, g_var, loc) + gen_nodes.append(g_assign) + index_call = ir.Expr.call(g_var, [dim_size, index_const], (), loc) + self.calltypes[index_call] = func_typ.get_call_type( + self.typingctx, [types.intp, types.intp], {}) + index_assign = ir.Assign(index_call, last_ind, loc) + gen_nodes.append(index_assign) + + return last_ind + + def _get_stencil_start_ind(self, start_length, gen_nodes, scope, loc): + if isinstance(start_length, int): + return abs(min(start_length, 0)) + def get_start_ind(s_length): + return abs(min(s_length, 0)) + f_ir = compile_to_numba_ir(get_start_ind, {}, self.typingctx, + self.targetctx, (types.intp,), self.typemap, + self.calltypes) + assert len(f_ir.blocks) == 1 + block = f_ir.blocks.popitem()[1] + replace_arg_nodes(block, [start_length]) + gen_nodes += block.body[:-2] + ret_var = block.body[-2].value.value + return ret_var + + def _replace_stencil_accesses(self, stencil_ir, parfor_vars, in_args, + index_offsets, stencil_func, arg_to_arr_dict): + """ Convert relative indexing in the stencil kernel to standard indexing + by adding the loop index variables to the corresponding dimensions + of the array index tuples. + """ + stencil_blocks = stencil_ir.blocks + in_arr = in_args[0] + in_arg_names = [x.name for x in in_args] + + if "standard_indexing" in stencil_func.options: + for x in stencil_func.options["standard_indexing"]: + if x not in arg_to_arr_dict: + raise NumbaValueError("Standard indexing requested for " \ + "an array name not present in the " \ + "stencil kernel definition.") + standard_indexed = [arg_to_arr_dict[x] for x in + stencil_func.options["standard_indexing"]] + else: + standard_indexed = [] + + if in_arr.name in standard_indexed: + raise NumbaValueError("The first argument to a stencil kernel " \ + "must use relative indexing, not standard " \ + "indexing.") + + ndims = self.typemap[in_arr.name].ndim + scope = in_arr.scope + loc = in_arr.loc + # replace access indices, find access lengths in each dimension + need_to_calc_kernel = stencil_func.neighborhood is None + + # If we need to infer the kernel size then initialize the minimum and + # maximum seen indices for each dimension to 0. If we already have + # the neighborhood calculated then just convert from neighborhood format + # to the separate start and end lengths format used here. + if need_to_calc_kernel: + start_lengths = ndims*[0] + end_lengths = ndims*[0] + else: + start_lengths = [x[0] for x in stencil_func.neighborhood] + end_lengths = [x[1] for x in stencil_func.neighborhood] + + # Get all the tuples defined in the stencil blocks. + tuple_table = ir_utils.get_tuple_table(stencil_blocks) + + found_relative_index = False + + # For all blocks in the stencil kernel... + for label, block in stencil_blocks.items(): + new_body = [] + # For all statements in those blocks... + for stmt in block.body: + # Reject assignments to input arrays. + if ((isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['setitem', 'static_setitem'] + and stmt.value.value.name in in_arg_names) or + ((isinstance(stmt, ir.SetItem) or + isinstance(stmt, ir.StaticSetItem)) + and stmt.target.name in in_arg_names)): + raise NumbaValueError("Assignments to arrays passed to " \ + "stencil kernels is not allowed.") + # We found a getitem for some array. If that array is an input + # array and isn't in the list of standard indexed arrays then + # update min and max seen indices if we are inferring the + # kernel size and create a new tuple where the relative offsets + # are added to loop index vars to get standard indexing. + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op in ['static_getitem', 'getitem'] + and stmt.value.value.name in in_arg_names + and stmt.value.value.name not in standard_indexed): + index_list = stmt.value.index + # handle 1D case + if ndims == 1: + index_list = [index_list] + else: + if hasattr(index_list, 'name') and index_list.name in tuple_table: + index_list = tuple_table[index_list.name] + # indices can be inferred as constant in simple expressions + # like -c where c is constant + # handled here since this is a common stencil index pattern + stencil_ir._definitions = ir_utils.build_definitions(stencil_blocks) + index_list = [_get_const_index_expr( + stencil_ir, self.func_ir, v) for v in index_list] + if index_offsets: + index_list = self._add_index_offsets(index_list, + list(index_offsets), new_body, scope, loc) + + # update min and max indices + if need_to_calc_kernel: + # all indices should be integer to be able to calculate + # neighborhood automatically + if (isinstance(index_list, ir.Var) or + any([not isinstance(v, int) for v in index_list])): + raise NumbaValueError("Variable stencil index " \ + "only possible with known " \ + "neighborhood") + start_lengths = list(map(min, start_lengths, + index_list)) + end_lengths = list(map(max, end_lengths, index_list)) + found_relative_index = True + + # update access indices + index_vars = self._add_index_offsets(parfor_vars, + list(index_list), new_body, scope, loc) + + # new access index tuple + if ndims == 1: + ind_var = index_vars[0] + else: + ind_var = ir.Var(scope, mk_unique_var( + "$parfor_index_ind_var"), loc) + self.typemap[ind_var.name] = types.containers.UniTuple( + types.intp, ndims) + tuple_call = ir.Expr.build_tuple(index_vars, loc) + tuple_assign = ir.Assign(tuple_call, ind_var, loc) + new_body.append(tuple_assign) + + # getitem return type is scalar if all indices are integer + if all([self.typemap[v.name] == types.intp + for v in index_vars]): + getitem_return_typ = self.typemap[ + stmt.value.value.name].dtype + else: + # getitem returns an array + getitem_return_typ = self.typemap[stmt.value.value.name] + # new getitem with the new index var + getitem_call = ir.Expr.getitem(stmt.value.value, ind_var, + loc) + self.calltypes[getitem_call] = signature( + getitem_return_typ, + self.typemap[stmt.value.value.name], + self.typemap[ind_var.name]) + stmt.value = getitem_call + + new_body.append(stmt) + block.body = new_body + if need_to_calc_kernel and not found_relative_index: + raise NumbaValueError("Stencil kernel with no accesses to " \ + "relatively indexed arrays.") + + return start_lengths, end_lengths + + def _add_index_offsets(self, index_list, index_offsets, new_body, + scope, loc): + """ Does the actual work of adding loop index variables to the + relative index constants or variables. + """ + assert len(index_list) == len(index_offsets) + + # shortcut if all values are integer + if all([isinstance(v, int) for v in index_list+index_offsets]): + # add offsets in all dimensions + return list(map(add, index_list, index_offsets)) + + out_nodes = [] + index_vars = [] + for i in range(len(index_list)): + # new_index = old_index + offset + old_index_var = index_list[i] + if isinstance(old_index_var, int): + old_index_var = ir.Var(scope, + mk_unique_var("old_index_var"), loc) + self.typemap[old_index_var.name] = types.intp + const_assign = ir.Assign(ir.Const(index_list[i], loc), + old_index_var, loc) + out_nodes.append(const_assign) + + offset_var = index_offsets[i] + if isinstance(offset_var, int): + offset_var = ir.Var(scope, + mk_unique_var("offset_var"), loc) + self.typemap[offset_var.name] = types.intp + const_assign = ir.Assign(ir.Const(index_offsets[i], loc), + offset_var, loc) + out_nodes.append(const_assign) + + if (isinstance(old_index_var, slice) + or isinstance(self.typemap[old_index_var.name], + types.misc.SliceType)): + # only one arg can be slice + assert self.typemap[offset_var.name] == types.intp + index_var = self._add_offset_to_slice(old_index_var, offset_var, + out_nodes, scope, loc) + index_vars.append(index_var) + continue + + if (isinstance(offset_var, slice) + or isinstance(self.typemap[offset_var.name], + types.misc.SliceType)): + # only one arg can be slice + assert self.typemap[old_index_var.name] == types.intp + index_var = self._add_offset_to_slice(offset_var, old_index_var, + out_nodes, scope, loc) + index_vars.append(index_var) + continue + + index_var = ir.Var(scope, + mk_unique_var("offset_stencil_index"), loc) + self.typemap[index_var.name] = types.intp + index_call = ir.Expr.binop(operator.add, old_index_var, + offset_var, loc) + self.calltypes[index_call] = self.typingctx.resolve_function_type( + operator.add, (types.intp, types.intp), {}) + index_assign = ir.Assign(index_call, index_var, loc) + out_nodes.append(index_assign) + index_vars.append(index_var) + + new_body.extend(out_nodes) + return index_vars + + def _add_offset_to_slice(self, slice_var, offset_var, out_nodes, scope, + loc): + if isinstance(slice_var, slice): + f_text = """def f(offset): + return slice({} + offset, {} + offset) + """.format(slice_var.start, slice_var.stop) + loc = {} + exec(f_text, {}, loc) + f = loc['f'] + args = [offset_var] + arg_typs = (types.intp,) + else: + def f(old_slice, offset): + return slice(old_slice.start + offset, old_slice.stop + offset) + args = [slice_var, offset_var] + slice_type = self.typemap[slice_var.name] + arg_typs = (slice_type, types.intp,) + _globals = self.func_ir.func_id.func.__globals__ + f_ir = compile_to_numba_ir(f, _globals, self.typingctx, self.targetctx, + arg_typs, self.typemap, self.calltypes) + _, block = f_ir.blocks.popitem() + replace_arg_nodes(block, args) + new_index = block.body[-2].value.value + out_nodes.extend(block.body[:-2]) # ignore return nodes + return new_index + +def get_stencil_ir(sf, typingctx, args, scope, loc, input_dict, typemap, + calltypes): + """get typed IR from stencil bytecode + """ + from numba.core.cpu import CPUContext + from numba.core.registry import cpu_target + from numba.core.annotations import type_annotations + from numba.core.typed_passes import type_inference_stage + + # get untyped IR + stencil_func_ir = sf.kernel_ir.copy() + # copy the IR nodes to avoid changing IR in the StencilFunc object + stencil_blocks = copy.deepcopy(stencil_func_ir.blocks) + stencil_func_ir.blocks = stencil_blocks + + name_var_table = ir_utils.get_name_var_table(stencil_func_ir.blocks) + if "out" in name_var_table: + raise NumbaValueError("Cannot use the reserved word 'out' in stencil " \ + "kernels.") + + # get typed IR with a dummy pipeline (similar to test_parfors.py) + from numba.core.registry import cpu_target + targetctx = cpu_target.target_context + + tp = DummyPipeline(typingctx, targetctx, args, stencil_func_ir) + + rewrites.rewrite_registry.apply('before-inference', tp.state) + + tp.state.typemap, tp.state.return_type, tp.state.calltypes, _ = type_inference_stage( + tp.state.typingctx, tp.state.targetctx, tp.state.func_ir, + tp.state.args, None) + + type_annotations.TypeAnnotation( + func_ir=tp.state.func_ir, + typemap=tp.state.typemap, + calltypes=tp.state.calltypes, + lifted=(), + lifted_from=None, + args=tp.state.args, + return_type=tp.state.return_type, + html_output=config.HTML) + + # make block labels unique + stencil_blocks = ir_utils.add_offset_to_labels(stencil_blocks, + ir_utils.next_label()) + min_label = min(stencil_blocks.keys()) + max_label = max(stencil_blocks.keys()) + ir_utils._the_max_label.update(max_label) + + if config.DEBUG_ARRAY_OPT >= 1: + print("Initial stencil_blocks") + ir_utils.dump_blocks(stencil_blocks) + + # rename variables, + var_dict = {} + for v, typ in tp.state.typemap.items(): + new_var = ir.Var(scope, mk_unique_var(v), loc) + var_dict[v] = new_var + typemap[new_var.name] = typ # add new var type for overall function + ir_utils.replace_vars(stencil_blocks, var_dict) + + if config.DEBUG_ARRAY_OPT >= 1: + print("After replace_vars") + ir_utils.dump_blocks(stencil_blocks) + + # add call types to overall function + for call, call_typ in tp.state.calltypes.items(): + calltypes[call] = call_typ + + arg_to_arr_dict = {} + # replace arg with arr + for block in stencil_blocks.values(): + for stmt in block.body: + if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Arg): + if config.DEBUG_ARRAY_OPT >= 1: + print("input_dict", input_dict, stmt.value.index, + stmt.value.name, stmt.value.index in input_dict) + arg_to_arr_dict[stmt.value.name] = input_dict[stmt.value.index].name + stmt.value = input_dict[stmt.value.index] + + if config.DEBUG_ARRAY_OPT >= 1: + print("arg_to_arr_dict", arg_to_arr_dict) + print("After replace arg with arr") + ir_utils.dump_blocks(stencil_blocks) + + ir_utils.remove_dels(stencil_blocks) + stencil_func_ir.blocks = stencil_blocks + return stencil_func_ir, sf.get_return_type(args)[0], arg_to_arr_dict + +class DummyPipeline(object): + def __init__(self, typingctx, targetctx, args, f_ir): + from numba.core.compiler import StateDict + self.state = StateDict() + self.state.typingctx = typingctx + self.state.targetctx = targetctx + self.state.args = args + self.state.func_ir = f_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + + +def _get_const_index_expr(stencil_ir, func_ir, index_var): + """ + infer index_var as constant if it is of a expression form like c-1 where c + is a constant in the outer function. + index_var is assumed to be inside stencil kernel + """ + const_val = guard( + _get_const_index_expr_inner, stencil_ir, func_ir, index_var) + if const_val is not None: + return const_val + return index_var + +def _get_const_index_expr_inner(stencil_ir, func_ir, index_var): + """inner constant inference function that calls constant, unary and binary + cases. + """ + require(isinstance(index_var, ir.Var)) + # case where the index is a const itself in outer function + var_const = guard(_get_const_two_irs, stencil_ir, func_ir, index_var) + if var_const is not None: + return var_const + # get index definition + index_def = ir_utils.get_definition(stencil_ir, index_var) + # match inner_var = unary(index_var) + var_const = guard( + _get_const_unary_expr, stencil_ir, func_ir, index_def) + if var_const is not None: + return var_const + # match inner_var = arg1 + arg2 + var_const = guard( + _get_const_binary_expr, stencil_ir, func_ir, index_def) + if var_const is not None: + return var_const + raise GuardException + +def _get_const_two_irs(ir1, ir2, var): + """get constant in either of two IRs if available + otherwise, throw GuardException + """ + var_const = guard(find_const, ir1, var) + if var_const is not None: + return var_const + var_const = guard(find_const, ir2, var) + if var_const is not None: + return var_const + raise GuardException + +def _get_const_unary_expr(stencil_ir, func_ir, index_def): + """evaluate constant unary expr if possible + otherwise, raise GuardException + """ + require(isinstance(index_def, ir.Expr) and index_def.op == 'unary') + inner_var = index_def.value + # return -c as constant + const_val = _get_const_index_expr_inner(stencil_ir, func_ir, inner_var) + op = OPERATORS_TO_BUILTINS[index_def.fn] + return eval("{}{}".format(op, const_val)) + +def _get_const_binary_expr(stencil_ir, func_ir, index_def): + """evaluate constant binary expr if possible + otherwise, raise GuardException + """ + require(isinstance(index_def, ir.Expr) and index_def.op == 'binop') + arg1 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.lhs) + arg2 = _get_const_index_expr_inner(stencil_ir, func_ir, index_def.rhs) + op = OPERATORS_TO_BUILTINS[index_def.fn] + return eval("{}{}{}".format(arg1, op, arg2)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a38c69038c9ed68838f08b0a7014d2728b5855 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__init__.py @@ -0,0 +1,33 @@ +import gc +from os.path import dirname, join +import multiprocessing +import sys +import time +import unittest +import warnings + +from unittest.suite import TestSuite +from numba.testing import load_testsuite + + +try: + import faulthandler +except ImportError: + faulthandler = None +else: + try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() + except Exception as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) + +def load_tests(loader, tests, pattern): + suite = TestSuite() + suite.addTests(load_testsuite(loader, dirname(__file__))) + # Numba CUDA tests are located in a separate directory: + cuda_dir = join(dirname(dirname(__file__)), 'cuda/tests') + suite.addTests(loader.discover(cuda_dir)) + + return suite + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cache_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cache_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..372311777526d160603e862a6c1d2d58eb316b1a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cache_usecases.py @@ -0,0 +1,172 @@ +""" +This file will be copied to a temporary directory in order to +exercise caching compiled Numba functions. + +See test_dispatcher.py. +""" + +import sys + +import numpy as np + +from numba import jit, prange +from numba.core import types + +from numba.tests.ctypes_usecases import c_sin +from numba.tests.support import TestCase, captured_stderr + + +@jit(cache=True, nopython=True) +def simple_usecase(x): + return x + +def simple_usecase_caller(x): + return simple_usecase(x) + + +@jit(cache=True, nopython=True) +def add_usecase(x, y): + return x + y + Z + + +@jit(cache=True, forceobj=True) +def add_objmode_usecase(x, y): + object() + return x + y + Z + + +@jit(nopython=True) +def add_nocache_usecase(x, y): + return x + y + Z + + +@jit(cache=True, nopython=True) +def inner(x, y): + return x + y + Z + +@jit(cache=True, nopython=True) +def outer(x, y): + return inner(-y, x) + +@jit(cache=False, nopython=True) +def outer_uncached(x, y): + return inner(-y, x) + + +@jit(cache=True, forceobj=True) +def looplifted(n): + object() + res = 0 + for i in range(n): + res = res + i + return res + + +@jit(cache=True, nopython=True) +def use_c_sin(x): + return c_sin(x) + +@jit(cache=True, nopython=True) +def use_c_sin_nest1(x): + return use_c_sin(x) + +@jit(cache=True, nopython=True) +def use_c_sin_nest2(x): + return use_c_sin_nest1(x) + + +@jit(cache=True, nopython=True) +def ambiguous_function(x): + return x + 2 + +renamed_function1 = ambiguous_function + +@jit(cache=True, nopython=True) +def ambiguous_function(x): + return x + 6 + +renamed_function2 = ambiguous_function + + +def make_closure(x): + @jit(cache=True, nopython=True) + def closure(y): + return x + y + + return closure + +closure1 = make_closure(3) +closure2 = make_closure(5) +closure3 = make_closure(7) +closure4 = make_closure(9) + + +biggie = np.arange(10**6) + +@jit(cache=True, nopython=True) +def use_big_array(): + return biggie + + +Z = 1 + +# Exercise returning a record instance. This used to hardcode the dtype +# pointer's value in the bitcode. + +packed_record_type = np.dtype([('a', np.int8), ('b', np.float64)]) +aligned_record_type = np.dtype([('a', np.int8), ('b', np.float64)], align=True) + +packed_arr = np.empty(2, dtype=packed_record_type) +for i in range(packed_arr.size): + packed_arr[i]['a'] = i + 1 + packed_arr[i]['b'] = i + 42.5 + +aligned_arr = np.array(packed_arr, dtype=aligned_record_type) + +@jit(cache=True, nopython=True) +def record_return(ary, i): + return ary[i] + + +class _TestModule(TestCase): + """ + Tests for functionality of this module's functions. + Note this does not define any "test_*" method, instead check_module() + should be called by hand. + """ + + def check_module(self, mod): + self.assertPreciseEqual(mod.add_usecase(2, 3), 6) + self.assertPreciseEqual(mod.add_objmode_usecase(2, 3), 6) + self.assertPreciseEqual(mod.outer_uncached(3, 2), 2) + self.assertPreciseEqual(mod.outer(3, 2), 2) + + packed_rec = mod.record_return(mod.packed_arr, 1) + self.assertPreciseEqual(tuple(packed_rec), (2, 43.5)) + aligned_rec = mod.record_return(mod.aligned_arr, 1) + self.assertPreciseEqual(tuple(aligned_rec), (2, 43.5)) + + +@jit(cache=True) +def first_class_function_mul(x): + return x * x + + +@jit(cache=True) +def first_class_function_add(x): + return x + x + + +@jit(cache=True) +def first_class_function_usecase(f, x): + return f(x) + + +def self_test(): + mod = sys.modules[__name__] + _TestModule().check_module(mod) + + +@jit(parallel=True, cache=True, nopython=True) +def parfor_usecase(ary): + return ary * ary + ary diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cffi_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cffi_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..a101b977d8895846abba5cd96157380afe2d6926 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cffi_usecases.py @@ -0,0 +1,197 @@ +import sys + +import numpy as np + +import numba.core.typing.cffi_utils as cffi_support +from numba.tests.support import import_dynamic, temp_directory +from numba.core.types import complex128 + + +def load_inline_module(): + """ + Create an inline module, return the corresponding ffi and dll objects. + """ + from cffi import FFI + + # We can't rely on libc availability on Windows anymore, so we use our + # own compiled wrappers (see https://bugs.python.org/issue23606). + + defs = """ + double _numba_test_sin(double x); + double _numba_test_cos(double x); + double _numba_test_funcptr(double (*func)(double)); + bool _numba_test_boolean(void); + """ + + ffi = FFI() + ffi.cdef(defs) + # Load the _helperlib namespace + from numba import _helperlib + return ffi, ffi.dlopen(_helperlib.__file__) + + +def load_ool_module(): + """ + Compile an out-of-line module, return the corresponding ffi and + module objects. + """ + from cffi import FFI + + numba_complex = """ + typedef struct _numba_complex { + double real; + double imag; + } numba_complex; + """ + + bool_define = """ + #ifdef _MSC_VER + #define false 0 + #define true 1 + #define bool int + #else + #include + #endif + """ + + defs = numba_complex + """ + bool boolean(void); + double sin(double x); + double cos(double x); + int foo(int a, int b, int c); + void vsSin(int n, float* x, float* y); + void vdSin(int n, double* x, double* y); + void vector_real(numba_complex *c, double *real, int n); + void vector_imag(numba_complex *c, double *imag, int n); + """ + + source = numba_complex + bool_define + """ + static bool boolean(void) + { + return true; + } + + static int foo(int a, int b, int c) + { + return a + b * c; + } + + void vsSin(int n, float* x, float* y) { + int i; + for (i=0; i 0: + return fa(x) + else: + return fb(x) + +def use_user_defined_symbols(): + return cffi_foo(1, 2, 3) + +# The from_buffer method is member of cffi.FFI, and also of CompiledFFI objects +# (cffi_usecases_ool.ffi is a CompiledFFI object) so we use both in these +# functions. + +def vector_sin_float32(x, y): + vsSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y)) + +def vector_sin_float64(x, y): + vdSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y)) + + +# For testing pointer to structs from buffers + +def vector_extract_real(x, y): + vector_real(ffi.from_buffer(x), ffi.from_buffer(y), len(x)) + +def vector_extract_imag(x, y): + vector_imag(ffi.from_buffer(x), ffi.from_buffer(y), len(x)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/compile_with_pycc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/compile_with_pycc.py new file mode 100644 index 0000000000000000000000000000000000000000..ad2c4c456edba378932fa7511604ee5b69c85fad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/compile_with_pycc.py @@ -0,0 +1,147 @@ +import cmath + +import numpy as np + +from numba import float32 +from numba.types import unicode_type, i8 +from numba.pycc import CC, exportmany, export +from numba.tests.support import has_blas +from numba import typed + + +# +# New API +# + +cc = CC('pycc_test_simple') +cc.use_nrt = False + +# Note the first signature omits the return type +@cc.export('multf', (float32, float32)) +@cc.export('multi', 'i4(i4, i4)') +def mult(a, b): + return a * b + +# Test imported C globals such as Py_None, PyExc_ZeroDivisionError +@cc.export('get_none', 'none()') +def get_none(): + return None + +@cc.export('div', 'f8(f8, f8)') +def div(x, y): + return x / y + +_two = 2 + +# This one can't be compiled by the legacy API as it doesn't execute +# the script in a proper module. +@cc.export('square', 'i8(i8)') +def square(u): + return u ** _two + +# These ones need helperlib +cc_helperlib = CC('pycc_test_helperlib') +cc_helperlib.use_nrt = False + +@cc_helperlib.export('power', 'i8(i8, i8)') +def power(u, v): + return u ** v + +@cc_helperlib.export('sqrt', 'c16(c16)') +def sqrt(u): + return cmath.sqrt(u) + +@cc_helperlib.export('size', 'i8(f8[:])') +def size(arr): + return arr.size + +# Exercise linking to Numpy math functions +@cc_helperlib.export('np_sqrt', 'f8(f8)') +def np_sqrt(u): + return np.sqrt(u) + +@cc_helperlib.export('spacing', 'f8(f8)') +def np_spacing(u): + return np.spacing(u) + + +# This one clashes with libc random() unless pycc is careful with naming. +@cc_helperlib.export('random', 'f8(i4)') +def random_impl(seed): + if seed != -1: + np.random.seed(seed) + return np.random.random() + +# These ones need NRT +cc_nrt = CC('pycc_test_nrt') + +@cc_nrt.export('zero_scalar', 'f8(i4)') +def zero_scalar(n): + arr = np.zeros(n) + return arr[-1] + +if has_blas: + # This one also needs BLAS + @cc_nrt.export('vector_dot', 'f8(i4)') + def vector_dot(n): + a = np.linspace(1, n, n) + return np.dot(a, a) + +# This one needs an environment +@cc_nrt.export('zeros', 'f8[:](i4)') +def zeros(n): + return np.zeros(n) + +# requires list dtor, #issue3535 +@cc_nrt.export('np_argsort', 'intp[:](float64[:])') +def np_argsort(arr): + return np.argsort(arr) + +# +# Legacy API +# + +exportmany(['multf f4(f4,f4)', 'multi i4(i4,i4)'])(mult) +# Needs to link to helperlib to due with complex arguments +# export('multc c16(c16,c16)')(mult) +export('mult f8(f8, f8)')(mult) + + +@cc_nrt.export('dict_usecase', 'intp[:](intp[:])') +def dict_usecase(arr): + d = typed.Dict() + for i in range(arr.size): + d[i] = arr[i] + out = np.zeros_like(arr) + for k, v in d.items(): + out[k] = k * v + return out + +# checks for issue #6386 +@cc_nrt.export('internal_str_dict', i8(unicode_type)) +def internal_str_dict(x): + d = typed.Dict.empty(unicode_type,i8) + if(x not in d): + d[x] = len(d) + return len(d) + +@cc_nrt.export('hash_str', i8(unicode_type)) +def internal_str_dict(x): + return hash(x) + +@cc_nrt.export('hash_literal_str_A', i8()) +def internal_str_dict(): + return hash("A") + + +# For testing dynamic exception symbol collision/linkage + +cc_dynexc = CC('pycc_test_dynamic_exc') + +@cc_dynexc.export('do_setitem1', 'void(f8[:, :], f8[:, :])') +def do_setitem1(a, b): + a[:, :] = b + +@cc_dynexc.export('do_setitem2', 'void(f8[:, :], f8[:, :])') +def do_setitem2(a, b): + a[:, :] = b diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/ctypes_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/ctypes_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed8d3ab8e1a480bd1f0f82127b176eca648686f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/ctypes_usecases.py @@ -0,0 +1,114 @@ +from ctypes import * +import sys + +import numpy as np + + +is_windows = sys.platform.startswith('win32') + +# We can't rely on libc availability on Windows anymore, so we use our +# own compiled wrappers (see https://bugs.python.org/issue23606). + +from numba import _helperlib +libnumba = CDLL(_helperlib.__file__) +del _helperlib + +# A typed C function (cdecl under Windows) + +c_sin = libnumba._numba_test_sin +c_sin.argtypes = [c_double] +c_sin.restype = c_double + +def use_c_sin(x): + return c_sin(x) + +c_cos = libnumba._numba_test_cos +c_cos.argtypes = [c_double] +c_cos.restype = c_double + +def use_two_funcs(x): + return c_sin(x) - c_cos(x) + +# Typed C functions accepting an array pointer +# (either as a "void *" or as a typed pointer) + +c_vsquare = libnumba._numba_test_vsquare +c_vsquare.argtypes = [c_int, c_void_p, c_void_p] + +c_vcube = libnumba._numba_test_vsquare +c_vcube.argtypes = [c_int, POINTER(c_double), POINTER(c_double)] + +def use_c_vsquare(x): + out = np.empty_like(x) + c_vsquare(x.size, x.ctypes, out.ctypes) + return out + +def use_c_vcube(x): + out = np.empty_like(x) + c_vcube(x.size, x.ctypes, out.ctypes) + return out + +# An untyped C function + +c_untyped = libnumba._numba_test_exp + +def use_c_untyped(x): + return c_untyped(x) + +# A C function wrapped in a CFUNCTYPE + +ctype_wrapping = CFUNCTYPE(c_double, c_double)(use_c_sin) + +def use_ctype_wrapping(x): + return ctype_wrapping(x) + +# A Python API function + +savethread = pythonapi.PyEval_SaveThread +savethread.argtypes = [] +savethread.restype = c_void_p + +restorethread = pythonapi.PyEval_RestoreThread +restorethread.argtypes = [c_void_p] +restorethread.restype = None + +if is_windows: + # A function with the stdcall calling convention + c_sleep = windll.kernel32.Sleep + c_sleep.argtypes = [c_uint] + c_sleep.restype = None + + def use_c_sleep(x): + c_sleep(x) + + +def use_c_pointer(x): + """ + Running in Python will cause a segfault. + """ + threadstate = savethread() + x += 1 + restorethread(threadstate) + return x + + +def use_func_pointer(fa, fb, x): + if x > 0: + return fa(x) + else: + return fb(x) + + +mydct = {'what': 1232121} + +def call_me_maybe(arr): + return mydct[arr[0].decode('ascii')] + +# Create a callback into the python interpreter +py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe) + + +def take_array_ptr(ptr): + return ptr + +c_take_array_ptr = CFUNCTYPE(c_void_p, c_void_p)(take_array_ptr) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/dummy_module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/dummy_module.py new file mode 100644 index 0000000000000000000000000000000000000000..4152f3ff502021c9ed80bf147ca7bfe89a1f11ab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/dummy_module.py @@ -0,0 +1,4 @@ +'''Dummy module''' + +def function(): + '''Do nothing''' diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/enum_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/enum_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..995dbd917afb0abb2e48185ecb14adef692e2489 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/enum_usecases.py @@ -0,0 +1,55 @@ +from enum import Enum, IntEnum + + +class Color(Enum): + red = 1 + green = 2 + blue = 3 + + +class Shake(Enum): + vanilla = 7 + chocolate = 4 + cookies = 9 + # Same as Color.blue + mint = 3 + + +class Planet(Enum): + MERCURY = (3.303e+23, 2.4397e6) + VENUS = (4.869e+24, 6.0518e6) + EARTH = (5.976e+24, 6.37814e6) + MARS = (6.421e+23, 3.3972e6) + JUPITER = (1.9e+27, 7.1492e7) + SATURN = (5.688e+26, 6.0268e7) + URANUS = (8.686e+25, 2.5559e7) + NEPTUNE = (1.024e+26, 2.4746e7) + + +class HeterogeneousEnum(Enum): + red = 1.0 + green = 2.0 + blue = 3j + + +class Shape(IntEnum): + # Same as Color.green + circle = 2 + # Same as RequestError.internal_error + square = 500 + + +class RequestError(IntEnum): + dummy = 2 + not_found = 404 + internal_error = 500 + +class IntEnumWithNegatives(IntEnum): + # Used for testing of hash, need to make sure -1 -> -2 to comply with CPy + one = 1 + two = 2 + too = 2 + three = 3 + negone = -1 + negtwo = -2 + negthree = -3 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/matmul_usecase.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/matmul_usecase.py new file mode 100644 index 0000000000000000000000000000000000000000..84af4ef308e67c07190325e22fc1ca01b3c9d874 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/matmul_usecase.py @@ -0,0 +1,24 @@ +"""Use cases for testing matmul (@) +""" +def matmul_usecase(x, y): + return x @ y + +def imatmul_usecase(x, y): + x @= y + return x + +class DumbMatrix(object): + + def __init__(self, value): + self.value = value + + def __matmul__(self, other): + if isinstance(other, DumbMatrix): + return DumbMatrix(self.value * other.value) + return NotImplemented + + def __imatmul__(self, other): + if isinstance(other, DumbMatrix): + self.value *= other.value + return self + return NotImplemented diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/parfors_cache_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/parfors_cache_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..b650bcf5e0f2da3445e251ba972244066a323b7e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/parfors_cache_usecases.py @@ -0,0 +1,66 @@ +import sys + +import numpy as np + +from numba import njit +from numba.tests.support import TestCase + + +@njit(parallel=True, cache=True) +def arrayexprs_case(arr): + return arr / arr.sum() + + +@njit(parallel=True, cache=True) +def prange_case(arr): + out = np.zeros_like(arr) + c = 1 / arr.sum() + for i in range(arr.size): + out[i] = arr[i] * c + return out + + +@njit(cache=True) +def caller_case(arr): + return prange_case(arrayexprs_case(arr)) + + +class _TestModule(TestCase): + """ + Tests for functionality of this module's functions. + Note this does not define any "test_*" method, instead check_module() + should be called by hand. + """ + def check_module(self, mod): + total_cache_hits = 0 + for fn in [mod.arrayexprs_case, mod.prange_case, mod.caller_case]: + arr = np.ones(20) + np.testing.assert_allclose( + fn(arr), fn.py_func(arr), + ) + # Accumulate cache hits + total_cache_hits += len(fn.stats.cache_hits) + self.assertGreater( + total_cache_hits, 0, + msg="At least one dispatcher has used the cache", + ) + + def run_module(self, mod): + # This just executes the module's functionality without asserting + # anything about the cache, it's used in tests that ensure that + # properties such as thread count aren't baked in to the cached object. + for fn in [mod.arrayexprs_case, mod.prange_case, mod.caller_case]: + arr = np.ones(20) + np.testing.assert_allclose( + fn(arr), fn.py_func(arr), + ) + + +def self_test(): + mod = sys.modules[__name__] + _TestModule().check_module(mod) + + +def self_run(): + mod = sys.modules[__name__] + _TestModule().run_module(mod) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/recursion_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/recursion_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa987c425584d4f4222394a8ebe8c5c2b876831 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/recursion_usecases.py @@ -0,0 +1,228 @@ +""" +Usecases of recursive functions. + +Some functions are compiled at import time, hence a separate module. +""" + +from numba import jit + + +@jit("i8(i8)", nopython=True) +def fib1(n): + if n < 2: + return n + # Note the second call uses a named argument + return fib1(n - 1) + fib1(n=n - 2) + + +def make_fib2(): + @jit("i8(i8)", nopython=True) + def fib2(n): + if n < 2: + return n + return fib2(n - 1) + fib2(n=n - 2) + + return fib2 + +fib2 = make_fib2() + + +def make_type_change_self(jit=lambda x: x): + @jit + def type_change_self(x, y): + if x > 1 and y > 0: + return x + type_change_self(x - y, y) + else: + return y + return type_change_self + + +# Implicit signature +@jit(nopython=True) +def fib3(n): + if n < 2: + return n + return fib3(n - 1) + fib3(n - 2) + + +# Run-away self recursion +@jit(nopython=True) +def runaway_self(x): + return runaway_self(x) + + +@jit(nopython=True) +def raise_self(x): + if x == 1: + raise ValueError("raise_self") + elif x > 0: + return raise_self(x - 1) + else: + return 1 + + +# Mutual recursion +@jit(nopython=True) +def outer_fac(n): + if n < 1: + return 1 + return n * inner_fac(n - 1) + + +@jit(nopython=True) +def inner_fac(n): + if n < 1: + return 1 + return n * outer_fac(n - 1) + + +# Mutual recursion with different arg names +def make_mutual2(jit=lambda x: x): + @jit + def foo(x): + if x > 0: + return 2 * bar(z=1, y=x) + return 1 + x + + @jit + def bar(y, z): + return foo(x=y - z) + + return foo, bar + + +# Mutual runaway recursion + +@jit(nopython=True) +def runaway_mutual(x): + return runaway_mutual_inner(x) + + +@jit(nopython=True) +def runaway_mutual_inner(x): + return runaway_mutual(x) + + +# Mutual type changing recursion + +def make_type_change_mutual(jit=lambda x: x): + @jit + def foo(x, y): + if x > 1 and y > 0: + # call bar first to exercise partial type inference. + # typeinferer suspended at the call to bar() and haven't determined + # the potential return type from the else-branch + return x + bar(x - y, y) + else: + return y + + @jit + def bar(x, y): + if x > 1 and y > 0: + return x + foo(x - y, y) + else: + return y + + return foo + + +# Indirect mutual recursion +def make_four_level(jit=lambda x: x): + @jit + def first(x): + # The recursing call must have a path that is non-recursing. + if x > 0: + return second(x) * 2 + else: + return 1 + + @jit + def second(x): + return third(x) * 3 + + @jit + def third(x): + return fourth(x) * 4 + + @jit + def fourth(x): + return first(x / 2 - 1) + + return first + + +def make_inner_error(jit=lambda x: x): + @jit + def outer(x): + if x > 0: + return inner(x) + + else: + return 1 + + @jit + def inner(x): + if x > 0: + return outer(x - 1) + else: + # this branch is actually never executed + return error_fun(x) + + @jit + def error_fun(x): + # to trigger an untyped attribute error + return x.ndim + + return outer + + +def make_raise_mutual(jit=lambda x: x): + @jit + def outer(x): + if x > 0: + return inner(x) + else: + return 1 + + @jit + def inner(x): + if x == 1: + raise ValueError('raise_mutual') + elif x > 0: + return outer(x - 1) + else: + return 1 + + return outer + + +def make_optional_return_case(jit=lambda x: x): + @jit + def foo(x): + if x > 5: + return x - 1 + else: + return + + @jit + def bar(x): + out = foo(x) + if out is None: + return out + elif out < 8: + return out + else: + return x * bar(out) + + return bar + + +def make_growing_tuple_case(jit=lambda x: x): + # From issue #4387 + @jit + def make_list(n): + if n <= 0: + return None + + return (n, make_list(n - 1)) + return make_list diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_alignment.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..77eee17b26e1ee10985b99a5d192907cc890534d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_alignment.py @@ -0,0 +1,40 @@ +# See also numba.cuda.tests.test_alignment + +import numpy as np +from numba import from_dtype, njit, void +from numba.tests.support import TestCase + + +class TestAlignment(TestCase): + + def test_record_alignment(self): + rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True) + rec = from_dtype(rec_dtype) + + @njit((rec[:],)) + def foo(a): + for i in range(a.size): + a[i].a = a[i].b + + a_recarray = np.recarray(3, dtype=rec_dtype) + for i in range(a_recarray.size): + a_rec = a_recarray[i] + a_rec.a = 0 + a_rec.b = (i + 1) * 123 + + foo(a_recarray) + np.testing.assert_equal(a_recarray.a, a_recarray.b) + + def test_record_misaligned(self): + rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')]) + rec = from_dtype(rec_dtype) + + # Unlike the CUDA target, this will not generate an error + @njit((rec[:],)) + def foo(a): + for i in range(a.size): + a[i].a = a[i].b + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..321a19b6a4fe97d2dbee61a4900fe7dcfb70e26f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_analysis.py @@ -0,0 +1,1064 @@ +# Tests numba.analysis functions +import collections +import types as pytypes + +import numpy as np +from numba.core.compiler import run_frontend, Flags, StateDict +from numba import jit, njit, literal_unroll +from numba.core import types, errors, ir, rewrites, ir_utils, cpu +from numba.core import postproc +from numba.core.inline_closurecall import InlineClosureCallPass +from numba.tests.support import (TestCase, MemoryLeakMixin, SerialMixin, + IRPreservingTestPipeline) +from numba.core.analysis import dead_branch_prune, rewrite_semantic_constants +from numba.core.untyped_passes import (ReconstructSSA, TranslateByteCode, + IRProcessing, DeadBranchPrune, + PreserveIR) +from numba.core.compiler import DefaultPassBuilder, CompilerBase, PassManager +from numba.core.utils import PYVERSION + + +_GLOBAL = 123 + +enable_pyobj_flags = Flags() +enable_pyobj_flags.enable_pyobject = True + + +def compile_to_ir(func): + func_ir = run_frontend(func) + state = StateDict() + state.func_ir = func_ir + state.typemap = None + state.calltypes = None + # Transform to SSA + ReconstructSSA().run_pass(state) + # call this to get print etc rewrites + rewrites.rewrite_registry.apply('before-inference', state) + return func_ir + + +class TestBranchPruneBase(MemoryLeakMixin, TestCase): + """ + Tests branch pruning + """ + _DEBUG = False + + # find *all* branches + def find_branches(self, the_ir): + branches = [] + for blk in the_ir.blocks.values(): + tmp = [_ for _ in blk.find_insts(cls=ir.Branch)] + branches.extend(tmp) + return branches + + def assert_prune(self, func, args_tys, prune, *args, **kwargs): + # This checks that the expected pruned branches have indeed been pruned. + # func is a python function to assess + # args_tys is the numba types arguments tuple + # prune arg is a list, one entry per branch. The value in the entry is + # encoded as follows: + # True: using constant inference only, the True branch will be pruned + # False: using constant inference only, the False branch will be pruned + # None: under no circumstances should this branch be pruned + # *args: the argument instances to pass to the function to check + # execution is still valid post transform + # **kwargs: + # - flags: args to pass to `jit` default is `nopython=True`, + # e.g. permits use of e.g. object mode. + + func_ir = compile_to_ir(func) + before = func_ir.copy() + if self._DEBUG: + print("=" * 80) + print("before inline") + func_ir.dump() + + # run closure inlining to ensure that nonlocals in closures are visible + inline_pass = InlineClosureCallPass(func_ir, + cpu.ParallelOptions(False),) + inline_pass.run() + + # Remove all Dels, and re-run postproc + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + rewrite_semantic_constants(func_ir, args_tys) + if self._DEBUG: + print("=" * 80) + print("before prune") + func_ir.dump() + + dead_branch_prune(func_ir, args_tys) + + after = func_ir + if self._DEBUG: + print("after prune") + func_ir.dump() + + before_branches = self.find_branches(before) + self.assertEqual(len(before_branches), len(prune)) + + # what is expected to be pruned + expect_removed = [] + for idx, prune in enumerate(prune): + branch = before_branches[idx] + if prune is True: + expect_removed.append(branch.truebr) + elif prune is False: + expect_removed.append(branch.falsebr) + elif prune is None: + pass # nothing should be removed! + elif prune == 'both': + expect_removed.append(branch.falsebr) + expect_removed.append(branch.truebr) + else: + assert 0, "unreachable" + + # compare labels + original_labels = set([_ for _ in before.blocks.keys()]) + new_labels = set([_ for _ in after.blocks.keys()]) + # assert that the new labels are precisely the original less the + # expected pruned labels + try: + self.assertEqual(new_labels, original_labels - set(expect_removed)) + except AssertionError as e: + print("new_labels", sorted(new_labels)) + print("original_labels", sorted(original_labels)) + print("expect_removed", sorted(expect_removed)) + raise e + + supplied_flags = kwargs.pop('flags', {'nopython': True}) + # NOTE: original testing used `compile_isolated` hence use of `cres`. + cres = jit(args_tys, **supplied_flags)(func).overloads[args_tys] + if args is None: + res = cres.entry_point() + expected = func() + else: + res = cres.entry_point(*args) + expected = func(*args) + self.assertEqual(res, expected) + + +class TestBranchPrune(TestBranchPruneBase, SerialMixin): + + def test_single_if(self): + + def impl(x): + if 1 == 0: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + + def impl(x): + if 1 == 1: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + + def impl(x): + if x is None: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def impl(x): + if x == 10: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + + def impl(x): + if x == 10: + z = 3.14159 # noqa: F841 # no effect + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + + def impl(x): + z = None + y = z + if x == y: + return 100 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def test_single_if_else(self): + + def impl(x): + if x is None: + return 3.14159 + else: + return 1.61803 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def test_single_if_const_val(self): + + def impl(x): + if x == 100: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def impl(x): + # switch the condition order + if 100 == x: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def test_single_if_else_two_const_val(self): + + def impl(x, y): + if x == y: + return 3.14159 + else: + return 1.61803 + + self.assert_prune(impl, (types.IntegerLiteral(100),) * 2, [None], 100, + 100) + self.assert_prune(impl, (types.NoneType('none'),) * 2, [False], None, + None) + self.assert_prune(impl, (types.IntegerLiteral(100), + types.NoneType('none'),), [True], 100, None) + self.assert_prune(impl, (types.IntegerLiteral(100), + types.IntegerLiteral(1000)), [None], 100, 1000) + + def test_single_if_else_w_following_undetermined(self): + + def impl(x): + x_is_none_work = False + if x is None: + x_is_none_work = True + else: + dead = 7 # noqa: F841 # no effect + + if x_is_none_work: + y = 10 + else: + y = -3 + return y + + self.assert_prune(impl, (types.NoneType('none'),), [False, None], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def impl(x): + x_is_none_work = False + if x is None: + x_is_none_work = True + else: + pass + + if x_is_none_work: + y = 10 + else: + y = -3 + return y + + # Python 3.10 creates a block with a NOP in it for the `pass` which + # means it gets pruned. + self.assert_prune(impl, (types.NoneType('none'),), [False, None], + None) + + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def test_double_if_else_rt_const(self): + + def impl(x): + one_hundred = 100 + x_is_none_work = 4 + if x is None: + x_is_none_work = 100 + else: + dead = 7 # noqa: F841 # no effect + + if x_is_none_work == one_hundred: + y = 10 + else: + y = -3 + + return y, x_is_none_work + + self.assert_prune(impl, (types.NoneType('none'),), [False, None], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def test_double_if_else_non_literal_const(self): + + def impl(x): + one_hundred = 100 + if x == one_hundred: + y = 3.14159 + else: + y = 1.61803 + return y + + # no prune as compilation specialization on literal value not permitted + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def test_single_two_branches_same_cond(self): + + def impl(x): + if x is None: + y = 10 + else: + y = 40 + + if x is not None: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.NoneType('none'),), [False, True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10) + + def test_cond_is_kwarg_none(self): + + def impl(x=None): + if x is None: + y = 10 + else: + y = 40 + + if x is not None: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.Omitted(None),), + [False, True], None) + self.assert_prune(impl, (types.NoneType('none'),), [False, True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10) + + def test_cond_is_kwarg_value(self): + + def impl(x=1000): + if x == 1000: + y = 10 + else: + y = 40 + + if x != 1000: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.Omitted(1000),), [None, None], 1000) + self.assert_prune(impl, (types.IntegerLiteral(1000),), [None, None], + 1000) + self.assert_prune(impl, (types.IntegerLiteral(0),), [None, None], 0) + self.assert_prune(impl, (types.NoneType('none'),), [True, False], None) + + def test_cond_rewrite_is_correct(self): + # this checks that when a condition is replaced, it is replace by a + # true/false bit that correctly represents the evaluated condition + def fn(x): + if x is None: + return 10 + return 12 + + def check(func, arg_tys, bit_val): + func_ir = compile_to_ir(func) + + # check there is 1 branch + before_branches = self.find_branches(func_ir) + self.assertEqual(len(before_branches), 1) + + # check the condition in the branch is a binop + pred_var = before_branches[0].cond + pred_defn = ir_utils.get_definition(func_ir, pred_var) + self.assertEqual(pred_defn.op, 'call') + condition_var = pred_defn.args[0] + condition_op = ir_utils.get_definition(func_ir, condition_var) + self.assertEqual(condition_op.op, 'binop') + + # do the prune, this should kill the dead branch and rewrite the + #'condition to a true/false const bit + if self._DEBUG: + print("=" * 80) + print("before prune") + func_ir.dump() + dead_branch_prune(func_ir, arg_tys) + if self._DEBUG: + print("=" * 80) + print("after prune") + func_ir.dump() + + # after mutation, the condition should be a const value `bit_val` + new_condition_defn = ir_utils.get_definition(func_ir, condition_var) + self.assertTrue(isinstance(new_condition_defn, ir.Const)) + self.assertEqual(new_condition_defn.value, bit_val) + + check(fn, (types.NoneType('none'),), 1) + check(fn, (types.IntegerLiteral(10),), 0) + + def test_global_bake_in(self): + + def impl(x): + if _GLOBAL == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1) + + global _GLOBAL + tmp = _GLOBAL + + try: + _GLOBAL = 5 + + def impl(x): + if _GLOBAL == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1) + finally: + _GLOBAL = tmp + + def test_freevar_bake_in(self): + + _FREEVAR = 123 + + def impl(x): + if _FREEVAR == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1) + + _FREEVAR = 12 + + def impl(x): + if _FREEVAR == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1) + + def test_redefined_variables_are_not_considered_in_prune(self): + # see issue #4163, checks that if a variable that is an argument is + # redefined in the user code it is not considered const + + def impl(array, a=None): + if a is None: + a = 0 + if a < 0: + return 10 + return 30 + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'),), + [None, None], + np.zeros((2, 3)), None) + + def test_comparison_operators(self): + # see issue #4163, checks that a variable that is an argument and has + # value None survives TypeError from invalid comparison which should be + # dead + + def impl(array, a=None): + x = 0 + if a is None: + return 10 # dynamic exec would return here + # static analysis requires that this is executed with a=None, + # hence TypeError + if a < 0: + return 20 + return x + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'),), + [False, 'both'], + np.zeros((2, 3)), None) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64,), + [None, None], + np.zeros((2, 3)), 12.) + + def test_redefinition_analysis_same_block(self): + # checks that a redefinition in a block with prunable potential doesn't + # break + + def impl(array, x, a=None): + b = 2 + if x < 4: + b = 12 + if a is None: # known true + a = 7 # live + else: + b = 15 # dead + if a < 0: # valid as a result of the redefinition of 'a' + return 10 + return 30 + b + a + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none'),), + [None, False, None], + np.zeros((2, 3)), 1., None) + + def test_redefinition_analysis_different_block_can_exec(self): + # checks that a redefinition in a block that may be executed prevents + # pruning + + def impl(array, x, a=None): + b = 0 + if x > 5: + a = 11 # a redefined, cannot tell statically if this will exec + if x < 4: + b = 12 + if a is None: # cannot prune, cannot determine if re-defn occurred + b += 5 + else: + b += 7 + if a < 0: + return 10 + return 30 + b + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none'),), + [None, None, None, None], + np.zeros((2, 3)), 1., None) + + def test_redefinition_analysis_different_block_cannot_exec(self): + # checks that a redefinition in a block guarded by something that + # has prune potential + + def impl(array, x=None, a=None): + b = 0 + if x is not None: + a = 11 + if a is None: + b += 5 + else: + b += 7 + return 30 + b + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'), types.NoneType('none')), + [True, None], + np.zeros((2, 3)), None, None) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'), types.float64), + [True, None], + np.zeros((2, 3)), None, 1.2) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none')), + [None, None], + np.zeros((2, 3)), 1.2, None) + + def test_closure_and_nonlocal_can_prune(self): + # Closures must be inlined ahead of branch pruning in case nonlocal + # is used. See issue #6585. + def impl(): + x = 1000 + + def closure(): + nonlocal x + x = 0 + + closure() + + if x == 0: + return True + else: + return False + + self.assert_prune(impl, (), [False,],) + + def test_closure_and_nonlocal_cannot_prune(self): + # Closures must be inlined ahead of branch pruning in case nonlocal + # is used. See issue #6585. + def impl(n): + x = 1000 + + def closure(t): + nonlocal x + x = t + + closure(n) + + if x == 0: + return True + else: + return False + + self.assert_prune(impl, (types.int64,), [None,], 1) + + +class TestBranchPrunePredicates(TestBranchPruneBase, SerialMixin): + # Really important thing to remember... the branch on predicates end up as + # POP_JUMP_IF_ and the targets are backwards compared to normal, i.e. + # the true condition is far jump and the false the near i.e. `if x` would + # end up in Numba IR as e.g. `branch x 10, 6`. + + _TRUTHY = (1, "String", True, 7.4, 3j) + _FALSEY = (0, "", False, 0.0, 0j, None) + + def _literal_const_sample_generator(self, pyfunc, consts): + """ + This takes a python function, pyfunc, and manipulates its co_const + __code__ member to create a new function with different co_consts as + supplied in argument consts. + + consts is a dict {index: value} of co_const tuple index to constant + value used to update a pyfunc clone's co_const. + """ + pyfunc_code = pyfunc.__code__ + + # translate consts spec to update the constants + co_consts = {k: v for k, v in enumerate(pyfunc_code.co_consts)} + for k, v in consts.items(): + co_consts[k] = v + new_consts = tuple([v for _, v in sorted(co_consts.items())]) + + # create code object with mutation + new_code = pyfunc_code.replace(co_consts=new_consts) + + # get function + return pytypes.FunctionType(new_code, globals()) + + def test_literal_const_code_gen(self): + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + else: + _CONST2 = "PLACEHOLDER2" + return _CONST2 + 4 + + if PYVERSION in ((3, 14), ): + # The order of the __code__.co_consts changes with 3.14 + new = self._literal_const_sample_generator(impl, {0:0, 2:20}) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + new = self._literal_const_sample_generator(impl, {1:0, 3:20}) + else: + raise NotImplementedError(PYVERSION) + + iconst = impl.__code__.co_consts + nconst = new.__code__.co_consts + + if PYVERSION in ((3, 14), ): + self.assertEqual(iconst, ("PLACEHOLDER1", 3.14159, + "PLACEHOLDER2")) + self.assertEqual(nconst, (0, 3.14159, 20)) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + self.assertEqual(iconst, (None, "PLACEHOLDER1", 3.14159, + "PLACEHOLDER2", 4)) + self.assertEqual(nconst, (None, 0, 3.14159, 20, 4)) + else: + raise NotImplementedError(PYVERSION) + + self.assertEqual(impl(None), 3.14159) + self.assertEqual(new(None), 24) + + def test_single_if_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + if PYVERSION in ((3, 14), ): + # The order of the __code__.co_consts changes with 3.14 + func = self._literal_const_sample_generator(impl, + {0: const}) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + func = self._literal_const_sample_generator(impl, + {1: const}) + else: + raise NotImplementedError(PYVERSION) + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if not _CONST1: + return 3.14159 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + if PYVERSION in ((3, 14), ): + # The order of the __code__.co_consts changes with 3.14 + func = self._literal_const_sample_generator(impl, + {0: const}) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + func = self._literal_const_sample_generator(impl, + {1: const}) + else: + raise NotImplementedError(PYVERSION) + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + else: + return 1.61803 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + if PYVERSION in ((3, 14), ): + # The order of the __code__.co_consts changes with 3.14 + func = self._literal_const_sample_generator(impl, + {0: const}) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + func = self._literal_const_sample_generator(impl, + {1: const}) + else: + raise NotImplementedError(PYVERSION) + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if not _CONST1: + return 3.14159 + else: + return 1.61803 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + if PYVERSION in ((3, 14), ): + # The order of the __code__.co_consts changes with 3.14 + func = self._literal_const_sample_generator(impl, + {0: const}) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + func = self._literal_const_sample_generator(impl, + {1: const}) + else: + raise NotImplementedError(PYVERSION) + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if const: + return 3.14159, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if not const: + return 3.14159, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if const: + return 3.14159, const + else: + return 1.61803, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if not const: + return 3.14159, const + else: + return 1.61803, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + # globals in this section have absurd names after their test usecase names + # so as to prevent collisions and permit tests to run in parallel + def test_single_if_global(self): + global c_test_single_if_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_global = c + + def func(x): + if c_test_single_if_global: + return 3.14159, c_test_single_if_global + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_global(self): + global c_test_single_if_negate_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_negate_global = c + + def func(x): + if c_test_single_if_negate_global: + return 3.14159, c_test_single_if_negate_global + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_global(self): + global c_test_single_if_else_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_else_global = c + + def func(x): + if c_test_single_if_else_global: + return 3.14159, c_test_single_if_else_global + else: + return 1.61803, c_test_single_if_else_global + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_global(self): + global c_test_single_if_else_negate_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_else_negate_global = c + + def func(x): + if not c_test_single_if_else_negate_global: + return 3.14159, c_test_single_if_else_negate_global + else: + return 1.61803, c_test_single_if_else_negate_global + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_issue_5618(self): + + @njit + def foo(): + values = np.zeros(1) + tmp = 666 + if tmp: + values[0] = tmp + return values + + self.assertPreciseEqual(foo.py_func()[0], 666.) + self.assertPreciseEqual(foo()[0], 666.) + + +class TestBranchPruneSSA(MemoryLeakMixin, TestCase): + # Tests SSA rewiring of phi nodes after branch pruning. + + class SSAPrunerCompiler(CompilerBase): + def define_pipelines(self): + # This is a simple pipeline that does branch pruning on IR in SSA + # form, then types and lowers as per the standard nopython pipeline. + pm = PassManager("testing pm") + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(IRProcessing, "processing IR") + # SSA early + pm.add_pass(ReconstructSSA, "ssa") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + # type and then lower as usual + pm.add_pass(PreserveIR, "preserves the IR as metadata") + dpb = DefaultPassBuilder + typed_passes = dpb.define_typed_pipeline(self.state) + pm.passes.extend(typed_passes.passes) + lowering_passes = dpb.define_nopython_lowering_pipeline(self.state) + pm.passes.extend(lowering_passes.passes) + pm.finalize() + return [pm] + + def test_ssa_update_phi(self): + # This checks that dead branch pruning is rewiring phi nodes correctly + # after a block containing an incoming for a phi is removed. + + @njit(pipeline_class=self.SSAPrunerCompiler) + def impl(p=None, q=None): + z = 1 + r = False + if p is None: + r = True # live + + if r and q is not None: + z = 20 # dead + + # one of the incoming blocks for z is dead, the phi needs an update + # were this not done, it would refer to variables that do not exist + # and result in a lowering error. + return z, r + + self.assertPreciseEqual(impl(), impl.py_func()) + + def test_ssa_replace_phi(self): + # This checks that when a phi only has one incoming, because the other + # has been pruned, that a direct assignment is used instead. + + @njit(pipeline_class=self.SSAPrunerCompiler) + def impl(p=None): + z = 0 + if p is None: + z = 10 + else: + z = 20 + + return z + + self.assertPreciseEqual(impl(), impl.py_func()) + func_ir = impl.overloads[impl.signatures[0]].metadata['preserved_ir'] + + # check the func_ir, make sure there's no phi nodes + for blk in func_ir.blocks.values(): + self.assertFalse([*blk.find_exprs('phi')]) + + +class TestBranchPrunePostSemanticConstRewrites(TestBranchPruneBase): + # Tests that semantic constants rewriting works by virtue of branch pruning + + def test_array_ndim_attr(self): + + def impl(array): + if array.ndim == 2: + if array.shape[1] == 2: + return 1 + else: + return 10 + + self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False, + None], + np.zeros((2, 3))) + self.assert_prune(impl, (types.Array(types.float64, 1, 'C'),), [True, + 'both'], + np.zeros((2,))) + + def test_tuple_len(self): + + def impl(tup): + if len(tup) == 3: + if tup[2] == 2: + return 1 + else: + return 0 + + self.assert_prune(impl, (types.UniTuple(types.int64, 3),), [False, + None], + tuple([1, 2, 3])) + self.assert_prune(impl, (types.UniTuple(types.int64, 2),), [True, + 'both'], + tuple([1, 2])) + + def test_attr_not_len(self): + # The purpose of this test is to make sure that the conditions guarding + # the rewrite part do not themselves raise exceptions. + # This produces an `ir.Expr` call node for `float.as_integer_ratio`, + # which is a getattr() on `float`. + + @njit + def test(): + float.as_integer_ratio(1.23) + + # this should raise a TypingError + with self.assertRaises(errors.TypingError) as e: + test() + + self.assertIn("Unknown attribute 'as_integer_ratio'", str(e.exception)) + + def test_ndim_not_on_array(self): + + FakeArray = collections.namedtuple('FakeArray', ['ndim']) + fa = FakeArray(ndim=2) + + def impl(fa): + if fa.ndim == 2: + return fa.ndim + else: + object() + + # check prune works for array ndim + self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False], + np.zeros((2, 3))) + + # check prune fails for something with `ndim` attr that is not array + FakeArrayType = types.NamedUniTuple(types.int64, 1, FakeArray) + self.assert_prune(impl, (FakeArrayType,), [None], fa, + flags={'nopython':False, 'forceobj':True}) + + def test_semantic_const_propagates_before_static_rewrites(self): + # see issue #5015, the ndim needs writing in as a const before + # the rewrite passes run to make e.g. getitems static where possible + @njit + def impl(a, b): + return a.shape[:b.ndim] + + args = (np.zeros((5, 4, 3, 2)), np.zeros((1, 1))) + + self.assertPreciseEqual(impl(*args), impl.py_func(*args)) + + def test_tuple_const_propagation(self): + @njit(pipeline_class=IRPreservingTestPipeline) + def impl(*args): + s = 0 + for arg in literal_unroll(args): + s += len(arg) + return s + + inp = ((), (1, 2, 3), ()) + self.assertPreciseEqual(impl(*inp), impl.py_func(*inp)) + + ol = impl.overloads[impl.signatures[0]] + func_ir = ol.metadata['preserved_ir'] + # make sure one of the inplace binop args is a Const + binop_consts = set() + for blk in func_ir.blocks.values(): + for expr in blk.find_exprs('inplace_binop'): + inst = blk.find_variable_assignment(expr.rhs.name) + self.assertIsInstance(inst.value, ir.Const) + binop_consts.add(inst.value.value) + self.assertEqual(binop_consts, {len(x) for x in inp}) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_attr.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_attr.py new file mode 100644 index 0000000000000000000000000000000000000000..404ea72731b021d063b0136b25f756f40a80ff25 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_attr.py @@ -0,0 +1,410 @@ +import numpy as np + +import unittest +from numba.np.numpy_support import from_dtype +from numba import njit, typeof +from numba.core import types +from numba.tests.support import (TestCase, MemoryLeakMixin, + skip_parfors_unsupported) +from numba.core.errors import TypingError +from numba.experimental import jitclass + + +def array_dtype(a): + return a.dtype + + +def use_dtype(a, b): + return a.view(b.dtype) + + +def dtype_eq_int64(a): + return a.dtype == np.dtype('int64') + + +def array_itemsize(a): + return a.itemsize + + +def array_nbytes(a): + return a.nbytes + + +def array_shape(a, i): + return a.shape[i] + + +def array_strides(a, i): + return a.strides[i] + + +def array_ndim(a): + return a.ndim + + +def array_size(a): + return a.size + + +def array_flags_contiguous(a): + return a.flags.contiguous + +def array_flags_c_contiguous(a): + return a.flags.c_contiguous + +def array_flags_f_contiguous(a): + return a.flags.f_contiguous + + +def nested_array_itemsize(a): + return a.f.itemsize + +def nested_array_nbytes(a): + return a.f.nbytes + +def nested_array_shape(a): + return a.f.shape + + +def nested_array_strides(a): + return a.f.strides + + +def nested_array_ndim(a): + return a.f.ndim + + +def nested_array_size(a): + return a.f.size + + +def size_after_slicing_usecase(buf, i): + sliced = buf[i] + # Make sure size attribute is not lost + return sliced.size + + +def array_ctypes_data(arr): + return arr.ctypes.data + + +def array_real(arr): + return arr.real + + +def array_imag(arr): + return arr.imag + + +class TestArrayAttr(MemoryLeakMixin, TestCase): + + def setUp(self): + super(TestArrayAttr, self).setUp() + self.a = np.arange(20, dtype=np.int32).reshape(4, 5) + + def check_unary(self, pyfunc, arr): + aryty = typeof(arr) + cfunc = self.get_cfunc(pyfunc, (aryty,)) + expected = pyfunc(arr) + self.assertPreciseEqual(cfunc(arr), expected) + # Retry with forced any layout + cfunc = self.get_cfunc(pyfunc, (aryty.copy(layout='A'),)) + self.assertPreciseEqual(cfunc(arr), expected) + + def check_unary_with_arrays(self, pyfunc,): + self.check_unary(pyfunc, self.a) + self.check_unary(pyfunc, self.a.T) + self.check_unary(pyfunc, self.a[::2]) + # 0-d array + arr = np.array([42]).reshape(()) + self.check_unary(pyfunc, arr) + # array with an empty dimension + arr = np.zeros(0) + self.check_unary(pyfunc, arr) + + # check with reshape + self.check_unary(pyfunc, arr.reshape((1, 0, 2))) + + def get_cfunc(self, pyfunc, argspec): + return njit(argspec)(pyfunc) + + def test_shape(self): + pyfunc = array_shape + cfunc = self.get_cfunc(pyfunc, (types.int32[:,:], types.int32)) + + for i in range(self.a.ndim): + self.assertEqual(pyfunc(self.a, i), cfunc(self.a, i)) + + def test_strides(self): + pyfunc = array_strides + cfunc = self.get_cfunc(pyfunc, (types.int32[:,:], types.int32)) + + for i in range(self.a.ndim): + self.assertEqual(pyfunc(self.a, i), cfunc(self.a, i)) + + def test_ndim(self): + self.check_unary_with_arrays(array_ndim) + + def test_size(self): + self.check_unary_with_arrays(array_size) + + def test_itemsize(self): + self.check_unary_with_arrays(array_itemsize) + + def test_nbytes(self): + self.check_unary_with_arrays(array_nbytes) + + def test_dtype(self): + pyfunc = array_dtype + self.check_unary(pyfunc, self.a) + dtype = np.dtype([('x', np.int8), ('y', np.int8)]) + arr = np.zeros(4, dtype=dtype) + self.check_unary(pyfunc, arr) + + def test_use_dtype(self): + # Test using the dtype attribute inside the Numba function itself + b = np.empty(1, dtype=np.int16) + pyfunc = use_dtype + cfunc = self.get_cfunc(pyfunc, (typeof(self.a), typeof(b))) + expected = pyfunc(self.a, b) + self.assertPreciseEqual(cfunc(self.a, b), expected) + + def test_dtype_equal(self): + # Test checking if a dtype is equal to another dtype + pyfunc = dtype_eq_int64 + self.check_unary(pyfunc, np.empty(1, dtype=np.int16)) + self.check_unary(pyfunc, np.empty(1, dtype=np.int64)) + + def test_flags_contiguous(self): + self.check_unary_with_arrays(array_flags_contiguous) + + def test_flags_c_contiguous(self): + self.check_unary_with_arrays(array_flags_c_contiguous) + + def test_flags_f_contiguous(self): + self.check_unary_with_arrays(array_flags_f_contiguous) + + +class TestNestedArrayAttr(MemoryLeakMixin, unittest.TestCase): + def setUp(self): + super(TestNestedArrayAttr, self).setUp() + dtype = np.dtype([('a', np.int32), ('f', np.int32, (2, 5))]) + self.a = np.recarray(1, dtype)[0] + self.nbrecord = from_dtype(self.a.dtype) + + def get_cfunc(self, pyfunc): + return njit((self.nbrecord,))(pyfunc) + + def test_shape(self): + pyfunc = nested_array_shape + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + def test_strides(self): + pyfunc = nested_array_strides + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + def test_ndim(self): + pyfunc = nested_array_ndim + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + def test_nbytes(self): + pyfunc = nested_array_nbytes + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + def test_size(self): + pyfunc = nested_array_size + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + def test_itemsize(self): + pyfunc = nested_array_itemsize + cfunc = self.get_cfunc(pyfunc) + + self.assertEqual(pyfunc(self.a), cfunc(self.a)) + + +class TestSlicedArrayAttr(MemoryLeakMixin, unittest.TestCase): + def test_size_after_slicing(self): + pyfunc = size_after_slicing_usecase + cfunc = njit(pyfunc) + arr = np.arange(2 * 5).reshape(2, 5) + for i in range(arr.shape[0]): + self.assertEqual(pyfunc(arr, i), cfunc(arr, i)) + arr = np.arange(2 * 5 * 3).reshape(2, 5, 3) + for i in range(arr.shape[0]): + self.assertEqual(pyfunc(arr, i), cfunc(arr, i)) + + +class TestArrayCTypes(MemoryLeakMixin, TestCase): + + _numba_parallel_test_ = False + + def test_array_ctypes_data(self): + pyfunc = array_ctypes_data + cfunc = njit(pyfunc) + arr = np.arange(3) + self.assertEqual(pyfunc(arr), cfunc(arr)) + + @skip_parfors_unsupported + def test_array_ctypes_ref_error_in_parallel(self): + # Issue #2887 + from ctypes import CFUNCTYPE, c_void_p, c_int32, c_double, c_bool + + @CFUNCTYPE(c_bool, c_void_p, c_int32, c_void_p) + def callback(inptr, size, outptr): + # A ctypes callback that manipulate the incoming pointers. + try: + inbuf = (c_double * size).from_address(inptr) + outbuf = (c_double * 1).from_address(outptr) + a = np.ndarray(size, buffer=inbuf, dtype=np.float64) + b = np.ndarray(1, buffer=outbuf, dtype=np.float64) + b[0] = (a + a.size)[0] + return True + except Exception: + import traceback + traceback.print_exception() + return False + + + # parallel=True is required to reproduce the error. + @njit(parallel=True) + def foo(size): + arr = np.ones(size) + out = np.empty(1) + # Exercise array.ctypes + inct = arr.ctypes + outct = out.ctypes + # The reference to `arr` is dead by now + status = callback(inct.data, size, outct.data) + return status, out[0] + + size = 3 + status, got = foo(size) + self.assertTrue(status) + self.assertPreciseEqual(got, (np.ones(size) + size)[0]) + + +class TestRealImagAttr(MemoryLeakMixin, TestCase): + def check_complex(self, pyfunc): + cfunc = njit(pyfunc) + # test 1D + size = 10 + arr = np.arange(size) + np.arange(size) * 10j + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + # test 2D + arr = arr.reshape(2, 5) + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + + def test_complex_real(self): + self.check_complex(array_real) + + def test_complex_imag(self): + self.check_complex(array_imag) + + def check_number_real(self, dtype): + pyfunc = array_real + cfunc = njit(pyfunc) + # test 1D + size = 10 + arr = np.arange(size, dtype=dtype) + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + # test 2D + arr = arr.reshape(2, 5) + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + # test identity + self.assertEqual(arr.data, pyfunc(arr).data) + self.assertEqual(arr.data, cfunc(arr).data) + # test writable + real = cfunc(arr) + self.assertNotEqual(arr[0, 0], 5) + real[0, 0] = 5 + self.assertEqual(arr[0, 0], 5) + + def test_number_real(self): + """ + Testing .real of non-complex dtypes + """ + for dtype in [np.uint8, np.int32, np.float32, np.float64]: + self.check_number_real(dtype) + + def check_number_imag(self, dtype): + pyfunc = array_imag + cfunc = njit(pyfunc) + # test 1D + size = 10 + arr = np.arange(size, dtype=dtype) + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + # test 2D + arr = arr.reshape(2, 5) + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + # test are zeros + self.assertEqual(cfunc(arr).tolist(), np.zeros_like(arr).tolist()) + # test readonly + imag = cfunc(arr) + with self.assertRaises(ValueError) as raises: + imag[0] = 1 + self.assertEqual('assignment destination is read-only', + str(raises.exception)) + + def test_number_imag(self): + """ + Testing .imag of non-complex dtypes + """ + for dtype in [np.uint8, np.int32, np.float32, np.float64]: + self.check_number_imag(dtype) + + def test_record_real(self): + rectyp = np.dtype([('real', np.float32), ('imag', np.complex64)]) + arr = np.zeros(3, dtype=rectyp) + arr['real'] = np.random.random(arr.size) + arr['imag'] = np.random.random(arr.size) * 1.3j + + # check numpy behavior + # .real is identity + self.assertIs(array_real(arr), arr) + # .imag is zero_like + self.assertEqual(array_imag(arr).tolist(), np.zeros_like(arr).tolist()) + + # check numba behavior + # it's most likely a user error, anyway + jit_array_real = njit(array_real) + jit_array_imag = njit(array_imag) + + with self.assertRaises(TypingError) as raises: + jit_array_real(arr) + self.assertIn("cannot access .real of array of Record", + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + jit_array_imag(arr) + self.assertIn("cannot access .imag of array of Record", + str(raises.exception)) + +class TestJitclassFlagsSegfault(MemoryLeakMixin, TestCase): + """Regression test for: https://github.com/numba/numba/issues/4775 """ + + def test(self): + + @jitclass(dict()) + class B(object): + + def __init__(self): + pass + + def foo(self, X): + X.flags + + Z = B() + Z.foo(np.ones(4)) + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_iterators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_iterators.py new file mode 100644 index 0000000000000000000000000000000000000000..75f8c3722787b42b25c75591dd58a21b12a59b3b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_iterators.py @@ -0,0 +1,570 @@ +import itertools + +import numpy as np + +from numba import jit, njit, typeof +from numba.core import types +from numba.tests.support import TestCase, MemoryLeakMixin +import unittest + + +def array_iter(arr): + total = 0 + for i, v in enumerate(arr): + total += i * v + return total + +def array_iter_items(arr): + return list(iter(arr)) + +def array_view_iter(arr, idx): + total = 0 + for i, v in enumerate(arr[idx]): + total += i * v + return total + +def array_flat(arr, out): + for i, v in enumerate(arr.flat): + out[i] = v + +def array_flat_getitem(arr, ind): + return arr.flat[ind] + +def array_flat_setitem(arr, ind, val): + arr.flat[ind] = val + +def array_flat_sum(arr): + s = 0 + for i, v in enumerate(arr.flat): + s = s + (i + 1) * v + return s + +def array_flat_len(arr): + return len(arr.flat) + +def array_ndenumerate_zero_dim(arr): + for i, v in np.ndenumerate(arr): + return (i, v) + return None + +def array_ndenumerate_sum(arr): + s = 0 + for (i, j), v in np.ndenumerate(arr): + s = s + (i + 1) * (j + 1) * v + return s + +def np_ndindex_empty(): + s = 0 + for ind in np.ndindex(()): + s += s + len(ind) + 1 + return s + +def np_ndindex(x, y): + s = 0 + n = 0 + for i, j in np.ndindex(x, y): + s = s + (i + 1) * (j + 1) + return s + +def np_ndindex_array(arr): + s = 0 + n = 0 + for indices in np.ndindex(arr.shape): + for i, j in enumerate(indices): + s = s + (i + 1) * (j + 1) + return s + +def np_nditer1(a): + res = [] + for u in np.nditer(a): + res.append(u.item()) + return res + +def np_nditer2(a, b): + res = [] + for u, v in np.nditer((a, b)): + res.append((u.item(), v.item())) + return res + +def np_nditer3(a, b, c): + res = [] + for u, v, w in np.nditer((a, b, c)): + res.append((u.item(), v.item(), w.item())) + return res + +def iter_next(arr): + it = iter(arr) + it2 = iter(arr) + return next(it), next(it), next(it2) + + +# +# Test premature free (see issue #2112). +# The following test allocates an array ``x`` inside the body. +# The compiler will put a ``del x`` right after the last use of ``x``, +# which is right after the creation of the array iterator and +# before the loop is entered. If the iterator does not incref the array, +# the iterator will be reading garbage data of free'ed memory. +# + +def array_flat_premature_free(size): + x = np.arange(size) + res = np.zeros_like(x, dtype=np.intp) + for i, v in enumerate(x.flat): + res[i] = v + return res + +def array_ndenumerate_premature_free(size): + x = np.arange(size) + res = np.zeros_like(x, dtype=np.intp) + for i, v in np.ndenumerate(x): + res[i] = v + return res + + +class TestArrayIterators(MemoryLeakMixin, TestCase): + """ + Test array.flat, np.ndenumerate(), etc. + """ + + def setUp(self): + super(TestArrayIterators, self).setUp() + + def check_array_iter_1d(self, arr): + pyfunc = array_iter + cfunc = njit((typeof(arr),))(pyfunc) + expected = pyfunc(arr) + self.assertPreciseEqual(cfunc(arr), expected) + + def check_array_iter_items(self, arr): + pyfunc = array_iter_items + cfunc = njit((typeof(arr),))(pyfunc) + expected = pyfunc(arr) + self.assertPreciseEqual(cfunc(arr), expected) + + def check_array_view_iter(self, arr, index): + pyfunc = array_view_iter + cfunc = njit((typeof(arr), typeof(index),))(pyfunc) + expected = pyfunc(arr, index) + self.assertPreciseEqual(cfunc(arr, index), expected) + + def check_array_flat(self, arr, arrty=None): + out = np.zeros(arr.size, dtype=arr.dtype) + nb_out = out.copy() + if arrty is None: + arrty = typeof(arr) + + cfunc = njit((arrty, typeof(out),))(array_flat) + + array_flat(arr, out) + cfunc(arr, nb_out) + + self.assertPreciseEqual(out, nb_out) + + def check_array_unary(self, arr, arrty, func): + cfunc = njit((arrty,))(func) + self.assertPreciseEqual(cfunc(arr), func(arr)) + + def check_array_ndenumerate_sum(self, arr, arrty): + self.check_array_unary(arr, arrty, array_ndenumerate_sum) + + def test_array_iter(self): + # Test iterating over arrays + arr = np.arange(6) + self.check_array_iter_1d(arr) + self.check_array_iter_items(arr) + arr = arr[::2] + self.assertFalse(arr.flags.c_contiguous) + self.assertFalse(arr.flags.f_contiguous) + self.check_array_iter_1d(arr) + self.check_array_iter_items(arr) + arr = np.bool_([1, 0, 0, 1]) + self.check_array_iter_1d(arr) + self.check_array_iter_items(arr) + arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + self.check_array_iter_items(arr) + self.check_array_iter_items(arr.T) + + def test_array_iter_yielded_order(self): + # See issue #5692 + @jit(nopython=True) + def foo(arr): + t = [] + for y1 in arr: + for y2 in y1: + t.append(y2.ravel()) + return t + + # 'F' ordered + arr = np.arange(24).reshape((2, 3, 4), order='F') + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + # 'A' ordered, outer strided + arr = np.arange(64).reshape((4, 8, 2), order='F')[::2, :, :] + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + # 'A' ordered, middle strided + arr = np.arange(64).reshape((4, 8, 2), order='F')[:, ::2, :] + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + # 'A' ordered, inner strided + arr = np.arange(64).reshape((4, 8, 2), order='F')[:, :, ::2] + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + @jit(nopython=True) + def flag_check(arr): + out = [] + for sub in arr: + out.append((sub, sub.flags.c_contiguous, + sub.flags.f_contiguous)) + return out + + arr = np.arange(10).reshape((2, 5), order='F') + expected = flag_check.py_func(arr) + got = flag_check(arr) + + self.assertEqual(len(expected), len(got)) + ex_arr, e_flag_c, e_flag_f = expected[0] + go_arr, g_flag_c, g_flag_f = got[0] + np.testing.assert_allclose(ex_arr, go_arr) + self.assertEqual(e_flag_c, g_flag_c) + self.assertEqual(e_flag_f, g_flag_f) + + def test_array_view_iter(self): + # Test iterating over a 1d view over a 2d array + arr = np.arange(12).reshape((3, 4)) + self.check_array_view_iter(arr, 1) + self.check_array_view_iter(arr.T, 1) + arr = arr[::2] + self.check_array_view_iter(arr, 1) + arr = np.bool_([1, 0, 0, 1]).reshape((2, 2)) + self.check_array_view_iter(arr, 1) + + def test_array_flat_3d(self): + arr = np.arange(24).reshape(4, 2, 3) + + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 3) + self.assertEqual(arrty.layout, 'C') + self.assertTrue(arr.flags.c_contiguous) + # Test with C-contiguous array + self.check_array_flat(arr) + # Test with Fortran-contiguous array + arr = arr.transpose() + self.assertFalse(arr.flags.c_contiguous) + self.assertTrue(arr.flags.f_contiguous) + self.assertEqual(typeof(arr).layout, 'F') + self.check_array_flat(arr) + # Test with non-contiguous array + arr = arr[::2] + self.assertFalse(arr.flags.c_contiguous) + self.assertFalse(arr.flags.f_contiguous) + self.assertEqual(typeof(arr).layout, 'A') + self.check_array_flat(arr) + # Boolean array + arr = np.bool_([1, 0, 0, 1] * 2).reshape((2, 2, 2)) + self.check_array_flat(arr) + + def test_array_flat_empty(self): + # Test .flat with various shapes of empty arrays, contiguous + # and non-contiguous (see issue #846). + + # Define a local checking function, Numba's `typeof` ends up aliasing + # 0d C and F ordered arrays, so the check needs to go via the compile + # result entry point to bypass type checking. + def check(arr, arrty): + cfunc = njit((arrty,))(array_flat_sum) + cres = cfunc.overloads[(arrty,)] + got = cres.entry_point(arr) + expected = cfunc.py_func(arr) + self.assertPreciseEqual(expected, got) + + arr = np.zeros(0, dtype=np.int32) + arr = arr.reshape(0, 2) + arrty = types.Array(types.int32, 2, layout='C') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='F') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='A') + check(arr, arrty) + arr = arr.reshape(2, 0) + arrty = types.Array(types.int32, 2, layout='C') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='F') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='A') + check(arr, arrty) + + def test_array_flat_getitem(self): + # Test indexing of array.flat object + pyfunc = array_flat_getitem + cfunc = njit(pyfunc) + def check(arr, ind): + expected = pyfunc(arr, ind) + self.assertEqual(cfunc(arr, ind), expected) + + arr = np.arange(24).reshape(4, 2, 3) + for i in range(arr.size): + check(arr, i) + arr = arr.T + for i in range(arr.size): + check(arr, i) + arr = arr[::2] + for i in range(arr.size): + check(arr, i) + arr = np.array([42]).reshape(()) + for i in range(arr.size): + check(arr, i) + # Boolean array + arr = np.bool_([1, 0, 0, 1]) + for i in range(arr.size): + check(arr, i) + arr = arr[::2] + for i in range(arr.size): + check(arr, i) + + def test_array_flat_setitem(self): + # Test indexing of array.flat object + pyfunc = array_flat_setitem + cfunc = njit(pyfunc) + def check(arr, ind): + # Use np.copy() to keep the layout + expected = np.copy(arr) + got = np.copy(arr) + pyfunc(expected, ind, 123) + cfunc(got, ind, 123) + self.assertPreciseEqual(got, expected) + + arr = np.arange(24).reshape(4, 2, 3) + for i in range(arr.size): + check(arr, i) + arr = arr.T + for i in range(arr.size): + check(arr, i) + arr = arr[::2] + for i in range(arr.size): + check(arr, i) + arr = np.array([42]).reshape(()) + for i in range(arr.size): + check(arr, i) + # Boolean array + arr = np.bool_([1, 0, 0, 1]) + for i in range(arr.size): + check(arr, i) + arr = arr[::2] + for i in range(arr.size): + check(arr, i) + + def test_array_flat_len(self): + # Test len(array.flat) + pyfunc = array_flat_len + cfunc = njit(array_flat_len) + def check(arr): + expected = pyfunc(arr) + self.assertPreciseEqual(cfunc(arr), expected) + + arr = np.arange(24).reshape(4, 2, 3) + check(arr) + arr = arr.T + check(arr) + arr = arr[::2] + check(arr) + arr = np.array([42]).reshape(()) + check(arr) + + def test_array_flat_premature_free(self): + cfunc = njit((types.intp,))(array_flat_premature_free) + expect = array_flat_premature_free(6) + got = cfunc(6) + self.assertTrue(got.sum()) + self.assertPreciseEqual(expect, got) + + def test_array_ndenumerate_2d(self): + arr = np.arange(12).reshape(4, 3) + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 2) + self.assertEqual(arrty.layout, 'C') + self.assertTrue(arr.flags.c_contiguous) + # Test with C-contiguous array + self.check_array_ndenumerate_sum(arr, arrty) + # Test with Fortran-contiguous array + arr = arr.transpose() + self.assertFalse(arr.flags.c_contiguous) + self.assertTrue(arr.flags.f_contiguous) + arrty = typeof(arr) + self.assertEqual(arrty.layout, 'F') + self.check_array_ndenumerate_sum(arr, arrty) + # Test with non-contiguous array + arr = arr[::2] + self.assertFalse(arr.flags.c_contiguous) + self.assertFalse(arr.flags.f_contiguous) + arrty = typeof(arr) + self.assertEqual(arrty.layout, 'A') + self.check_array_ndenumerate_sum(arr, arrty) + # Boolean array + arr = np.bool_([1, 0, 0, 1]).reshape((2, 2)) + self.check_array_ndenumerate_sum(arr, typeof(arr)) + + def test_array_ndenumerate_empty(self): + # Define a local checking function, Numba's `typeof` ends up aliasing + # 0d C and F ordered arrays, so the check needs to go via the compile + # result entry point to bypass type checking. + def check(arr, arrty): + cfunc = njit((arrty,))(array_ndenumerate_sum) + cres = cfunc.overloads[(arrty,)] + got = cres.entry_point(arr) + expected = cfunc.py_func(arr) + np.testing.assert_allclose(expected, got) + + arr = np.zeros(0, dtype=np.int32) + arr = arr.reshape(0, 2) + arrty = types.Array(types.int32, 2, layout='C') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='F') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='A') + check(arr, arrty) + arr = arr.reshape(2, 0) + arrty = types.Array(types.int32, 2, layout='C') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='F') + check(arr, arrty) + arrty = types.Array(types.int32, 2, layout='A') + check(arr, arrty) + + def test_array_ndenumerate_premature_free(self): + cfunc = njit((types.intp,))(array_ndenumerate_premature_free) + expect = array_ndenumerate_premature_free(6) + got = cfunc(6) + self.assertTrue(got.sum()) + self.assertPreciseEqual(expect, got) + + def test_array_ndenumerate_zero_dim(self): + func = array_ndenumerate_zero_dim + cfunc = njit(func) + arr = np.array(97) + expected = func(arr) + got = cfunc(arr) + self.assertPreciseEqual(got, expected) + self.assertEqual(expected[0], ()) + self.assertEqual(expected[1], 97) + + def test_np_ndindex(self): + func = np_ndindex + cfunc = njit((types.int32, types.int32,))(func) + self.assertPreciseEqual(cfunc(3, 4), func(3, 4)) + self.assertPreciseEqual(cfunc(3, 0), func(3, 0)) + self.assertPreciseEqual(cfunc(0, 3), func(0, 3)) + self.assertPreciseEqual(cfunc(0, 0), func(0, 0)) + + def test_np_ndindex_array(self): + func = np_ndindex_array + arr = np.arange(12, dtype=np.int32) + 10 + self.check_array_unary(arr, typeof(arr), func) + arr = arr.reshape((4, 3)) + self.check_array_unary(arr, typeof(arr), func) + arr = arr.reshape((2, 2, 3)) + self.check_array_unary(arr, typeof(arr), func) + + def test_np_ndindex_empty(self): + func = np_ndindex_empty + cfunc = njit((),)(func) + self.assertPreciseEqual(cfunc(), func()) + + def test_iter_next(self): + # This also checks memory management with iter() and next() + func = iter_next + arr = np.arange(12, dtype=np.int32) + 10 + self.check_array_unary(arr, typeof(arr), func) + + +class TestNdIter(MemoryLeakMixin, TestCase): + """ + Test np.nditer() + """ + + def inputs(self): + # All those inputs are compatible with a (3, 4) main shape + + # scalars + yield np.float32(100) + + # 0-d arrays + yield np.array(102, dtype=np.int16) + + # 1-d arrays + yield np.arange(4).astype(np.complex64) + yield np.arange(8)[::2] + + # 2-d arrays + a = np.arange(12).reshape((3, 4)) + yield a + yield a.copy(order='F') + a = np.arange(24).reshape((6, 4))[::2] + yield a + + def basic_inputs(self): + yield np.arange(4).astype(np.complex64) + yield np.arange(8)[::2] + a = np.arange(12).reshape((3, 4)) + yield a + yield a.copy(order='F') + + def check_result(self, got, expected): + self.assertEqual(set(got), set(expected), (got, expected)) + + def test_nditer1(self): + pyfunc = np_nditer1 + cfunc = jit(nopython=True)(pyfunc) + for a in self.inputs(): + expected = pyfunc(a) + got = cfunc(a) + self.check_result(got, expected) + + def test_nditer2(self): + pyfunc = np_nditer2 + cfunc = jit(nopython=True)(pyfunc) + for a, b in itertools.product(self.inputs(), self.inputs()): + expected = pyfunc(a, b) + got = cfunc(a, b) + self.check_result(got, expected) + + def test_nditer3(self): + pyfunc = np_nditer3 + cfunc = jit(nopython=True)(pyfunc) + # Use a restricted set of inputs, to shorten test time + inputs = self.basic_inputs + for a, b, c in itertools.product(inputs(), inputs(), inputs()): + expected = pyfunc(a, b, c) + got = cfunc(a, b, c) + self.check_result(got, expected) + + def test_errors(self): + # Incompatible shapes + pyfunc = np_nditer2 + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + def check_incompatible(a, b): + with self.assertRaises(ValueError) as raises: + cfunc(a, b) + self.assertIn("operands could not be broadcast together", + str(raises.exception)) + + check_incompatible(np.arange(2), np.arange(3)) + a = np.arange(12).reshape((3, 4)) + b = np.arange(3) + check_incompatible(a, b) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_reductions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..e2710455a96fa3425c36b7aa695219e89dd42da4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_reductions.py @@ -0,0 +1,1409 @@ +from itertools import product, combinations_with_replacement + +import numpy as np + +from numba import jit, njit, typeof +from numba.np.numpy_support import numpy_version +from numba.tests.support import TestCase, MemoryLeakMixin, tag, skip_if_numpy_2 +import unittest + + +def array_all(arr): + return arr.all() + +def array_all_global(arr): + return np.all(arr) + +def array_any(arr): + return arr.any() + +def array_any_global(arr): + return np.any(arr) + +def array_cumprod(arr): + return arr.cumprod() + +def array_cumprod_global(arr): + return np.cumprod(arr) + +def array_nancumprod(arr): + return np.nancumprod(arr) + +def array_cumsum(arr): + return arr.cumsum() + +def array_cumsum_global(arr): + return np.cumsum(arr) + +def array_nancumsum(arr): + return np.nancumsum(arr) + +def array_sum(arr): + return arr.sum() + +def array_sum_global(arr): + return np.sum(arr) + +def array_prod(arr): + return arr.prod() + +def array_prod_global(arr): + return np.prod(arr) + +def array_mean(arr): + return arr.mean() + +def array_mean_global(arr): + return np.mean(arr) + +def array_var(arr): + return arr.var() + +def array_var_global(arr): + return np.var(arr) + +def array_std(arr): + return arr.std() + +def array_std_global(arr): + return np.std(arr) + +def array_min(arr): + return arr.min() + +def array_min_global(arr): + return np.min(arr) + +def array_amin(arr): + return np.amin(arr) + +def array_max(arr): + return arr.max() + +def array_max_global(arr): + return np.max(arr) + +def array_amax(arr): + return np.amax(arr) + +def array_argmin(arr): + return arr.argmin() + +def array_argmin_global(arr): + return np.argmin(arr) + +def array_argmax(arr): + return arr.argmax() + +def array_argmax_global(arr): + return np.argmax(arr) + +def array_median_global(arr): + return np.median(arr) + +def array_nanmin(arr): + return np.nanmin(arr) + +def array_nanmax(arr): + return np.nanmax(arr) + +def array_nanmean(arr): + return np.nanmean(arr) + +def array_nansum(arr): + return np.nansum(arr) + +def array_nanprod(arr): + return np.nanprod(arr) + +def array_nanstd(arr): + return np.nanstd(arr) + +def array_nanvar(arr): + return np.nanvar(arr) + +def array_nanmedian_global(arr): + return np.nanmedian(arr) + +def array_percentile_global(arr, q): + return np.percentile(arr, q) + +def array_nanpercentile_global(arr, q): + return np.nanpercentile(arr, q) + +def array_ptp_global(a): + return np.ptp(a) + +def array_ptp(a): + return a.ptp() + +def array_quantile_global(arr, q): + return np.quantile(arr, q) + +def array_nanquantile_global(arr, q): + return np.nanquantile(arr, q) + +def base_test_arrays(dtype): + if dtype == np.bool_: + def factory(n): + assert n % 2 == 0 + return np.bool_([0, 1] * (n // 2)) + else: + def factory(n): + return np.arange(n, dtype=dtype) + 1 + + a1 = factory(10) + a2 = factory(10).reshape(2, 5) + # The prod() of this array fits in a 32-bit int + a3 = (factory(12))[::-1].reshape((2, 3, 2), order='A') + assert not (a3.flags.c_contiguous or a3.flags.f_contiguous) + + return [a1, a2, a3] + +def full_test_arrays(dtype): + array_list = base_test_arrays(dtype) + + # Add floats with some mantissa + if dtype == np.float32: + array_list += [a / 10 for a in array_list] + + # add imaginary part + if dtype == np.complex64: + acc = [] + for a in array_list: + tmp = a / 10 + 1j * a / 11 + tmp[::2] = np.conj(tmp[::2]) + acc.append(tmp) + array_list.extend(acc) + + for a in array_list: + assert a.dtype == np.dtype(dtype) + return array_list + +def run_comparative(compare_func, test_array): + cfunc = njit(compare_func) + numpy_result = compare_func(test_array) + numba_result = cfunc(test_array) + + return numpy_result, numba_result + + +class TestArrayReductions(MemoryLeakMixin, TestCase): + """ + Test array reduction methods and functions such as .sum(), .max(), etc. + """ + + def setUp(self): + super(TestArrayReductions, self).setUp() + np.random.seed(42) + + def check_reduction_basic(self, pyfunc, **kwargs): + # Basic reduction checks on 1-d float64 arrays + cfunc = jit(nopython=True)(pyfunc) + def check(arr): + self.assertPreciseEqual(pyfunc(arr), cfunc(arr), **kwargs) + + arr = np.float64([1.0, 2.0, 0.0, -0.0, 1.0, -1.5]) + check(arr) + arr = np.float64([-0.0, -1.5]) + check(arr) + arr = np.float64([-1.5, 2.5, 'inf']) + check(arr) + arr = np.float64([-1.5, 2.5, '-inf']) + check(arr) + arr = np.float64([-1.5, 2.5, 'inf', '-inf']) + check(arr) + arr = np.float64(['nan', -1.5, 2.5, 'nan', 3.0]) + check(arr) + arr = np.float64(['nan', -1.5, 2.5, 'nan', 'inf', '-inf', 3.0]) + check(arr) + arr = np.float64([5.0, 'nan', -1.5, 'nan']) + check(arr) + # Only NaNs + arr = np.float64(['nan', 'nan']) + check(arr) + + def check_scalar_basic(self, pyfunc, **kwargs): + cfunc = jit(nopython=True)(pyfunc) + def check(arr): + self.assertPreciseEqual(pyfunc(arr), cfunc(arr), **kwargs) + #numpy values + arr = np.float64(0.0) + check(arr) + arr = np.float64(-0.0) + check(arr) + arr = np.float32(21.0) + check(arr) + arr = np.float32(-21.0) + check(arr) + arr = np.int32(21) + check(arr) + arr = np.int32(-21) + check(arr) + + #special values + arr = np.float64(np.inf) + check(arr) + arr = np.float64(-np.inf) + check(arr) + arr = np.float64('nan') + check(arr) + + #booleans + arr = np.bool_(True) + check(arr) + arr = np.bool_(False) + check(arr) + + #string negative test case + with self.assertTypingError() as e: + cfunc('string') + + def test_all_basic(self, pyfunc=array_all): + cfunc = jit(nopython=True)(pyfunc) + def check(arr): + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + + arr = np.float64([1.0, 0.0, float('inf'), float('nan')]) + check(arr) + arr[1] = -0.0 + check(arr) + arr[1] = 1.5 + check(arr) + arr = arr.reshape((2, 2)) + check(arr) + check(arr[::-1]) + + def test_array_all(self): + cfunc = jit(nopython=True)(array_all) + + def check(arg): + expected = array_all(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # Test numpy array cases + check(np.array([True, True, True])) + check(np.array([True, False, True])) + check(np.array([1.0, 2.0, 3.0])) + check(np.array([0.0, 1.0, 2.0])) + + with self.assertTypingError() as e: + cfunc('hello') + + def test_np_all(self): + cfunc = jit(nopython=True)(array_all_global) + + def check(arg): + expected = array_all_global(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # Test numpy scalar cases + check(np.float64(0.0)) + check(np.float64(0.2)) + check(np.bool_(True)) + check(np.bool_(False)) + + # Test special values + check(np.nan) + check(np.inf) + check(-np.inf) + check(-0.0) + + # Test numpy array cases + check(np.array([True, True, True])) + check(np.array([True, False, True])) + check(np.array([1.0, 2.0, 3.0])) + check(np.array([0.0, 1.0, 2.0])) + + with self.assertTypingError() as e: + cfunc([1,2,3]) + + def test_any_basic(self, pyfunc=array_any): + cfunc = jit(nopython=True)(pyfunc) + def check(arr): + self.assertPreciseEqual(pyfunc(arr), cfunc(arr)) + + arr = np.float64([0.0, -0.0, 0.0, 0.0]) + check(arr) + arr[2] = float('nan') + check(arr) + arr[2] = float('inf') + check(arr) + arr[2] = 1.5 + check(arr) + arr = arr.reshape((2, 2)) + check(arr) + check(arr[::-1]) + + def test_array_any(self): + cfunc = jit(nopython=True)(array_any) + def check(arg): + expected = array_any(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # Test numpy array cases + check(np.array([True, True, True])) + check(np.array([True, False, True])) + check(np.array([1.0, 2.0, 3.0])) + check(np.array([0.0, 1.0, 2.0])) + + with self.assertTypingError() as e: + cfunc('hello') + + def test_np_any(self): + cfunc = jit(nopython=True)(array_any_global) + + def check(arg): + expected = array_any_global(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # Test numpy scalar cases + check(np.float64(0.0)) + check(np.float64(0.2)) + check(np.bool_(True)) + check(np.bool_(False)) + + # Test special values + check(np.nan) + check(np.inf) + check(-np.inf) + check(-0.0) + + # Test numpy array cases + check(np.array([True, True, True])) + check(np.array([True, False, True])) + check(np.array([1.0, 2.0, 3.0])) + check(np.array([0.0, 1.0, 2.0])) + + with self.assertTypingError() as e: + cfunc([1,2,3]) + + def test_sum_basic(self): + self.check_reduction_basic(array_sum) + + def test_mean_basic(self): + self.check_reduction_basic(array_mean) + + def test_np_mean_scalar(self): + cfunc = jit(nopython=True)(array_mean_global) + + def check(arg): + expected = array_mean_global(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # NumPy integer and boolean scalars + check(np.int32(2)) + check(np.int64(-3)) + check(np.uint32(5)) + check(np.bool_(True)) + check(np.bool_(False)) + + # NumPy floating scalars + check(np.float32(1.25)) + check(np.float64(-2.5)) + + # Complex values + check(np.complex64(7+0j)) + check(np.complex128(61+74j)) + + # Special floating values + check(np.nan) + check(np.inf) + check(-np.inf) + check(-0.0) + check(0.0) + check(0) + check(0.0000042) + check(-0.25863) + + # Error cases + with self.assertTypingError(): + cfunc('test String') + + def test_var_basic(self): + self.check_reduction_basic(array_var, prec='double') + + def test_std_basic(self): + self.check_reduction_basic(array_std) + + def test_min_basic(self): + #scalar testing + self.check_scalar_basic(array_min_global) + #array testing + self.check_reduction_basic(array_min) + + def test_amin_basic(self): + #scalar testing + self.check_scalar_basic(array_amin) + #array testing + self.check_reduction_basic(array_amin) + + + def test_max_basic(self): + #array testing + self.check_reduction_basic(array_max) + #scalar testing + self.check_scalar_basic(array_max_global) + + def test_amax_basic(self): + #array testing + self.check_reduction_basic(array_amax) + #scalar testing + self.check_scalar_basic(array_amax) + + def test_argmin_basic(self): + self.check_reduction_basic(array_argmin) + + def test_argmax_basic(self): + self.check_reduction_basic(array_argmax) + + def test_nanmin_basic(self): + self.check_reduction_basic(array_nanmin) + + def test_nanmax_basic(self): + self.check_reduction_basic(array_nanmax) + + def test_nanmean_basic(self): + self.check_reduction_basic(array_nanmean) + + def test_nansum_basic(self): + self.check_reduction_basic(array_nansum) + + def test_nanprod_basic(self): + self.check_reduction_basic(array_nanprod) + + def test_nanstd_basic(self): + self.check_reduction_basic(array_nanstd) + + def test_nanvar_basic(self): + self.check_reduction_basic(array_nanvar, prec='double') + + def check_median_basic(self, pyfunc, array_variations): + cfunc = jit(nopython=True)(pyfunc) + def check(arr): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertPreciseEqual(got, expected) + + # Empty array case + check(np.array([])) + + # Odd sizes + def check_odd(a): + check(a) + a = a.reshape((9, 7)) + check(a) + check(a.T) + for a in array_variations(np.arange(63) + 10.5): + check_odd(a) + + # Even sizes + def check_even(a): + check(a) + a = a.reshape((4, 16)) + check(a) + check(a.T) + for a in array_variations(np.arange(64) + 10.5): + check_even(a) + + @staticmethod + def _array_variations(a): + # Sorted, reversed, random, many duplicates, many NaNs, all NaNs + yield a + a = a[::-1].copy() + yield a + np.random.shuffle(a) + yield a + a[a % 4 >= 1] = 3.5 + yield a + a[a % 4 >= 2] = np.nan + yield a + a[:] = np.nan + yield a + + def test_median_basic(self): + pyfunc = array_median_global + + def variations(a): + # Sorted, reversed, random, many duplicates + yield a + a = a[::-1].copy() + yield a + np.random.shuffle(a) + yield a + a[a % 4 >= 1] = 3.5 + yield a + + self.check_median_basic(pyfunc, variations) + + def check_percentile_and_quantile(self, pyfunc, q_upper_bound): + cfunc = jit(nopython=True)(pyfunc) + + def check(a, q, abs_tol=1e-12): + expected = pyfunc(a, q) + got = cfunc(a, q) + # NOTE: inf/nan is not checked, seems to be susceptible to upstream + # changes + finite = np.isfinite(expected) + if np.all(finite): + self.assertPreciseEqual(got, expected, abs_tol=abs_tol) + else: + self.assertPreciseEqual(got[finite], expected[finite], + abs_tol=abs_tol) + + a = self.random.randn(27).reshape(3, 3, 3) + q = np.linspace(0, q_upper_bound, 14)[::-1] + check(a, q) + check(a, 0) + check(a, q_upper_bound / 2) + check(a, q_upper_bound) + + not_finite = [np.nan, -np.inf, np.inf] + a.flat[:10] = self.random.choice(not_finite, 10) + self.random.shuffle(a) + self.random.shuffle(q) + check(a, q) + + a = a.flatten().tolist() + q = q.flatten().tolist() + check(a, q) + check(tuple(a), tuple(q)) + + a = self.random.choice([1, 2, 3, 4], 10) + q = np.linspace(0, q_upper_bound, 5) + check(a, q) + + # tests inspired by + # https://github.com/numpy/numpy/blob/345b2f6e/numpy/lib/tests/test_function_base.py + x = np.arange(8) * 0.5 + np.testing.assert_equal(cfunc(x, 0), 0.) + np.testing.assert_equal(cfunc(x, q_upper_bound), 3.5) + np.testing.assert_equal(cfunc(x, q_upper_bound / 2), 1.75) + + x = np.arange(12).reshape(3, 4) + q = np.array((0.25, 0.5, 1.0)) * q_upper_bound + np.testing.assert_equal(cfunc(x, q), [2.75, 5.5, 11.0]) + + x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) + q = np.array((0.25, 0.50)) * q_upper_bound + np.testing.assert_equal(cfunc(x, q).shape, (2,)) + + q = np.array((0.25, 0.50, 0.75)) * q_upper_bound + np.testing.assert_equal(cfunc(x, q).shape, (3,)) + + x = np.arange(12).reshape(3, 4) + np.testing.assert_equal(cfunc(x, q_upper_bound / 2), 5.5) + self.assertTrue(np.isscalar(cfunc(x, q_upper_bound / 2))) + + np.testing.assert_equal(cfunc([1, 2, 3], 0), 1) + + a = np.array([2, 3, 4, 1]) + cfunc(a, [q_upper_bound / 2]) + np.testing.assert_equal(a, np.array([2, 3, 4, 1])) + + def check_percentile_edge_cases(self, pyfunc, q_upper_bound=100): + cfunc = jit(nopython=True)(pyfunc) + + def check(a, q, abs_tol=1e-14): + expected = pyfunc(a, q) + got = cfunc(a, q) + # NOTE: inf/nan is not checked, seems to be susceptible to upstream + # changes + finite = np.isfinite(expected) + if np.all(finite): + self.assertPreciseEqual(got, expected, abs_tol=abs_tol) + else: + self.assertPreciseEqual(got[finite], expected[finite], + abs_tol=abs_tol) + + def convert_to_float_and_check(a, q, abs_tol=1e-14): + expected = pyfunc(a, q).astype(np.float64) + got = cfunc(a, q) + self.assertPreciseEqual(got, expected, abs_tol=abs_tol) + + def _array_combinations(elements): + for i in range(1, 10): + for comb in combinations_with_replacement(elements, i): + yield np.array(comb) + + # high number of combinations, many including non-finite values + q = (0, 0.1 * q_upper_bound, 0.2 * q_upper_bound, q_upper_bound) + element_pool = (1, -1, np.nan, np.inf, -np.inf) + for a in _array_combinations(element_pool): + check(a, q) + + # edge cases - numpy exhibits behavioural differences across + # platforms, see: https://github.com/numpy/numpy/issues/13272 + if q_upper_bound == 1: + _check = convert_to_float_and_check + else: + _check = check + + a = np.array(5) + q = np.array(1) + _check(a, q) + + a = 5 + q = q_upper_bound / 2 + _check(a, q) + + def check_percentile_exceptions(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + def check_err(a, q): + with self.assertRaises(ValueError) as raises: + cfunc(a, q) + self.assertEqual( + "Percentiles must be in the range [0, 100]", + str(raises.exception) + ) + + # Exceptions leak references + self.disable_leak_check() + + a = np.arange(5) + check_err(a, -5) # q less than 0 + check_err(a, (1, 10, 105)) # q contains value greater than 100 + check_err(a, (1, 10, np.nan)) # q contains nan + + with self.assertTypingError() as e: + a = np.arange(5) * 1j + q = 0.1 + cfunc(a, q) + + self.assertIn('Not supported for complex dtype', str(e.exception)) + + def check_quantile_exceptions(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + def check_err(a, q): + with self.assertRaises(ValueError) as raises: + cfunc(a, q) + self.assertEqual( + "Quantiles must be in the range [0, 1]", + str(raises.exception) + ) + + # Exceptions leak references + self.disable_leak_check() + + a = np.arange(5) + check_err(a, -0.5) # q less than 0 + check_err(a, (0.1, 0.10, 1.05)) # q contains value greater than 1 + check_err(a, (0.1, 0.10, np.nan)) # q contains nan + + with self.assertTypingError() as e: + a = np.arange(5) * 1j + q = 0.1 + cfunc(a, q) + + self.assertIn('Not supported for complex dtype', str(e.exception)) + + def test_percentile_basic(self): + pyfunc = array_percentile_global + self.check_percentile_and_quantile(pyfunc, q_upper_bound=100) + self.check_percentile_edge_cases(pyfunc, q_upper_bound=100) + self.check_percentile_exceptions(pyfunc) + + def test_nanpercentile_basic(self): + pyfunc = array_nanpercentile_global + self.check_percentile_and_quantile(pyfunc, q_upper_bound=100) + self.check_percentile_edge_cases(pyfunc, q_upper_bound=100) + self.check_percentile_exceptions(pyfunc) + + def test_quantile_basic(self): + pyfunc = array_quantile_global + self.check_percentile_and_quantile(pyfunc, q_upper_bound=1) + self.check_percentile_edge_cases(pyfunc, q_upper_bound=1) + self.check_quantile_exceptions(pyfunc) + + def test_nanquantile_basic(self): + pyfunc = array_nanquantile_global + self.check_percentile_and_quantile(pyfunc, q_upper_bound=1) + self.check_percentile_edge_cases(pyfunc, q_upper_bound=1) + self.check_quantile_exceptions(pyfunc) + + def test_nanmedian_basic(self): + pyfunc = array_nanmedian_global + self.check_median_basic(pyfunc, self._array_variations) + + def test_array_sum_global(self): + arr = np.arange(10, dtype=np.int32) + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 1) + self.assertEqual(arrty.layout, 'C') + + cfunc = njit((arrty,),)(array_sum_global) + self.assertEqual(np.sum(arr), cfunc(arr)) + + def test_array_prod_int_1d(self): + arr = np.arange(10, dtype=np.int32) + 1 + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 1) + self.assertEqual(arrty.layout, 'C') + + cfunc = njit((arrty,))(array_prod) + self.assertEqual(arr.prod(), cfunc(arr)) + + def test_array_prod_float_1d(self): + arr = np.arange(10, dtype=np.float32) + 1 / 10 + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 1) + self.assertEqual(arrty.layout, 'C') + + cfunc = njit((arrty,))(array_prod) + np.testing.assert_allclose(arr.prod(), cfunc(arr)) + + def test_array_prod_global(self): + arr = np.arange(10, dtype=np.int32) + arrty = typeof(arr) + self.assertEqual(arrty.ndim, 1) + self.assertEqual(arrty.layout, 'C') + + cfunc = njit((arrty,))(array_prod_global) + np.testing.assert_allclose(np.prod(arr), cfunc(arr)) + + def test_np_prod_scalar(self): + self.check_scalar_basic(array_prod_global) + + cfunc = jit(nopython=True)(array_prod_global) + + def check(arg): + expected = array_prod_global(arg) + got = cfunc(arg) + self.assertPreciseEqual(got, expected) + + # check less precise integer cases are converted to platform integer + check(np.int8(2)) + check(np.uint8(2)) + check(np.int16(3)) + check(np.uint16(3)) + check(np.int32(4)) + check(np.uint32(4)) + + # handle complex cases not tested in self.check_scalar_basic + check(np.complex64(1j)) + check(np.complex128(0j)) + + def check_cumulative(self, pyfunc): + arr = np.arange(2, 10, dtype=np.int16) + expected, got = run_comparative(pyfunc, arr) + self.assertPreciseEqual(got, expected) + arr = np.linspace(2, 8, 6) + expected, got = run_comparative(pyfunc, arr) + self.assertPreciseEqual(got, expected) + arr = arr.reshape((3, 2)) + expected, got = run_comparative(pyfunc, arr) + self.assertPreciseEqual(got, expected) + + def test_array_cumsum(self): + self.check_cumulative(array_cumsum) + + def test_array_cumsum_global(self): + self.check_cumulative(array_cumsum_global) + + def test_array_cumprod(self): + self.check_cumulative(array_cumprod) + + def test_array_cumprod_global(self): + self.check_cumulative(array_cumprod_global) + + def check_aggregation_magnitude(self, pyfunc, is_prod=False): + """ + Check that integer overflows are avoided (issue #931). + """ + # Overflows are avoided here (ints are cast either to intp + # or float64). + n_items = 2 if is_prod else 10 # avoid overflow on prod() + arr = (np.arange(n_items) + 40000).astype('int16') + npr, nbr = run_comparative(pyfunc, arr) + self.assertPreciseEqual(npr, nbr) + # Overflows are avoided for functions returning floats here. + # Other functions may wrap around. + arr = (np.arange(10) + 2**60).astype('int64') + npr, nbr = run_comparative(pyfunc, arr) + self.assertPreciseEqual(npr, nbr) + arr = arr.astype('uint64') + npr, nbr = run_comparative(pyfunc, arr) + self.assertPreciseEqual(npr, nbr) + + def test_sum_magnitude(self): + self.check_aggregation_magnitude(array_sum) + self.check_aggregation_magnitude(array_sum_global) + + def test_cumsum_magnitude(self): + self.check_aggregation_magnitude(array_cumsum) + self.check_aggregation_magnitude(array_cumsum_global) + + def test_nancumsum_magnitude(self): + self.check_aggregation_magnitude(array_nancumsum, is_prod=True) + + def test_prod_magnitude(self): + self.check_aggregation_magnitude(array_prod, is_prod=True) + self.check_aggregation_magnitude(array_prod_global, is_prod=True) + + def test_cumprod_magnitude(self): + self.check_aggregation_magnitude(array_cumprod, is_prod=True) + self.check_aggregation_magnitude(array_cumprod_global, is_prod=True) + + def test_nancumprod_magnitude(self): + self.check_aggregation_magnitude(array_nancumprod, is_prod=True) + + def test_mean_magnitude(self): + self.check_aggregation_magnitude(array_mean) + self.check_aggregation_magnitude(array_mean_global) + + def test_var_magnitude(self): + self.check_aggregation_magnitude(array_var) + self.check_aggregation_magnitude(array_var_global) + + def test_std_magnitude(self): + self.check_aggregation_magnitude(array_std) + self.check_aggregation_magnitude(array_std_global) + + def _do_check_nptimedelta(self, pyfunc, arr): + arrty = typeof(arr) + cfunc = jit(nopython=True)(pyfunc) + + self.assertPreciseEqual(cfunc(arr), pyfunc(arr)) + # Even vs. odd size, for np.median + self.assertPreciseEqual(cfunc(arr[:-1]), pyfunc(arr[:-1])) + # Test with different orders, for np.median + arr = arr[::-1].copy() # Keep 'C' layout + self.assertPreciseEqual(cfunc(arr), pyfunc(arr)) + np.random.shuffle(arr) + self.assertPreciseEqual(cfunc(arr), pyfunc(arr)) + # Test with a NaT + if 'median' not in pyfunc.__name__: + # Test with (val, NaT)^N (and with the random NaT from above) + # use a loop, there's some weird thing/bug with arr[1::2] = 'NaT' + + # Further Numba has bug(s) relating to NaN/NaT handling in anything + # using a partition such as np.median + for x in range(1, len(arr), 2): + arr[x] = 'NaT' + self.assertPreciseEqual(cfunc(arr), pyfunc(arr)) + # Test with all NaTs + arr.fill(arrty.dtype('NaT')) + self.assertPreciseEqual(cfunc(arr), pyfunc(arr)) + + def check_npdatetime(self, pyfunc): + arr = np.arange(10).astype(dtype='M8[Y]') + self._do_check_nptimedelta(pyfunc, arr) + + def check_nptimedelta(self, pyfunc): + arr = np.arange(10).astype(dtype='m8[s]') + self._do_check_nptimedelta(pyfunc, arr) + + def test_min_npdatetime(self): + self.check_npdatetime(array_min) + self.check_nptimedelta(array_min) + + def test_max_npdatetime(self): + self.check_npdatetime(array_max) + self.check_nptimedelta(array_max) + + def test_argmin_npdatetime(self): + self.check_npdatetime(array_argmin) + self.check_nptimedelta(array_argmin) + + def test_argmax_npdatetime(self): + self.check_npdatetime(array_argmax) + self.check_nptimedelta(array_argmax) + + def test_median_npdatetime(self): + self.check_nptimedelta(array_median_global) + + def test_sum_npdatetime(self): + self.check_nptimedelta(array_sum) + + def test_cumsum_npdatetime(self): + self.check_nptimedelta(array_cumsum) + + def test_mean_npdatetime(self): + self.check_nptimedelta(array_mean) + + def check_nan_cumulative(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def _set_some_values_to_nan(a): + p = a.size // 2 # set approx half elements to NaN + np.put(a, np.random.choice(range(a.size), p, replace=False), np.nan) + return a + + def a_variations(): + yield np.linspace(-1, 3, 60).reshape(3, 4, 5) + yield np.array([np.inf, 3, 4]) + yield np.array([True, True, True, False]) + yield np.arange(1, 10) + yield np.asfortranarray(np.arange(1, 64) - 33.3) + yield np.arange(1, 10, dtype=np.float32)[::-1] + + for a in a_variations(): + check(a) # no nans + check(_set_some_values_to_nan(a.astype(np.float64))) # about 50% nans + + # edge cases + check(np.array([])) + check(np.full(10, np.nan)) + + parts = np.array([np.nan, 2, np.nan, 4, 5, 6, 7, 8, 9]) + + a = parts + 1j * parts[::-1] + a = a.reshape(3, 3) + check(a) + + def test_nancumprod_basic(self): + self.check_cumulative(array_nancumprod) + self.check_nan_cumulative(array_nancumprod) + + def test_nancumsum_basic(self): + self.check_cumulative(array_nancumsum) + self.check_nan_cumulative(array_nancumsum) + + def test_ptp_basic(self): + pyfunc = array_ptp_global + cfunc = jit(nopython=True)(pyfunc) + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def a_variations(): + yield np.arange(10) + yield np.array([-1.1, np.nan, 2.2]) + yield np.array([-np.inf, 5]) + yield (4, 2, 5) + yield (1,) + yield np.full(5, 5) + yield [2.2, -2.3, 0.1] + a = np.linspace(-10, 10, 16).reshape(4, 2, 2) + yield a + yield np.asfortranarray(a) + yield a[::-1] + np.random.RandomState(0).shuffle(a) + yield a + yield 6 + yield 6.5 + yield -np.inf + yield 1 + 4j + yield [2.2, np.nan] + yield [2.2, np.inf] + yield ((4.1, 2.0, -7.6), (4.3, 2.7, 5.2)) + yield np.full(5, np.nan) + yield 1 + np.nan * 1j + yield np.nan + np.nan * 1j + yield np.nan + + for a in a_variations(): + check(a) + + @skip_if_numpy_2 + def test_ptp_method(self): + # checks wiring of np.ndarray.ptp() only, `np.ptp` test above checks + # the actual alg + pyfunc = array_ptp + cfunc = jit(nopython=True)(pyfunc) + + a = np.arange(10) + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_ptp_complex(self): + pyfunc = array_ptp_global + cfunc = jit(nopython=True)(pyfunc) + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def make_array(real_nan=False, imag_nan=False): + real = np.linspace(-4, 4, 25) + if real_nan: + real[4:9] = np.nan + imag = np.linspace(-5, 5, 25) + if imag_nan: + imag[7:12] = np.nan + return (real + 1j * imag).reshape(5, 5) + + for real_nan, imag_nan in product([True, False], repeat=2): + comp = make_array(real_nan, imag_nan) + check(comp) + + real = np.ones(8) + imag = np.arange(-4, 4) + comp = real + 1j * imag + check(comp) + comp = real - 1j * imag + check(comp) + + comp = np.full((4, 4), fill_value=(1 - 1j)) + check(comp) + + def test_ptp_exceptions(self): + pyfunc = array_ptp_global + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc(np.array((True, True, False))) + + msg = "Boolean dtype is unsupported (as per NumPy)" + self.assertIn(msg, str(e.exception)) + + with self.assertRaises(ValueError) as e: + cfunc(np.array([])) + + msg = "zero-size array reduction not possible" + self.assertIn(msg, str(e.exception)) + + def test_min_max_complex_basic(self): + pyfuncs = array_min_global, array_max_global + + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + real = np.linspace(-10, 10, 40) + real[:4] = real[-1] + imag = real * 2 + a = real - imag * 1j + check(a) + + for _ in range(10): + self.random.shuffle(real) + self.random.shuffle(imag) + dtype = self.random.choice([np.complex64, np.complex128]) + a = real - imag * 1j + a[:4] = a[-1] + check(a.astype(dtype)) + + def test_nanmin_nanmax_complex_basic(self): + pyfuncs = array_nanmin, array_nanmax + + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + real = np.linspace(-10, 10, 40) + real[:4] = real[-1] + real[5:9] = np.nan + imag = real * 2 + imag[7:12] = np.nan + a = real - imag * 1j + check(a) + + for _ in range(10): + self.random.shuffle(real) + self.random.shuffle(imag) + a = real - imag * 1j + a[:4] = a[-1] + check(a) + + def test_nanmin_nanmax_non_array_inputs(self): + pyfuncs = array_nanmin, array_nanmax + + def check(a): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def a_variations(): + yield [1, 6, 4, 2] + yield ((-10, 4, -12), (5, 200, -30)) + yield np.array(3) + yield (2,) + yield 3.142 + yield False + yield (np.nan, 3.142, -5.2, 3.0) + yield [np.inf, np.nan, -np.inf] + yield [(np.nan, 1.1), (-4.4, 8.7)] + + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + + for a in a_variations(): + check(a) + + def test_argmax_axis_1d_2d_4d(self): + arr1d = np.array([0, 20, 3, 4]) + arr2d = np.arange(6).reshape(2, 3) + arr2d[0,1] += 100 + + arr4d = np.arange(120).reshape(2, 3, 4, 5) + 10 + arr4d[0, 1, 1, 2] += 100 + arr4d[1, 0, 0, 0] -= 51 + + for arr in [arr1d, arr2d, arr4d]: + axes = list(range(arr.ndim)) + [ + -(i+1) for i in range(arr.ndim) + ] + py_functions = [ + lambda a, _axis=axis: np.argmax(a, axis=_axis) + for axis in axes + ] + c_functions = [ + jit(nopython=True)(pyfunc) for pyfunc in py_functions + ] + for cfunc in c_functions: + self.assertPreciseEqual(cfunc.py_func(arr), cfunc(arr)) + + def test_argmax_axis_out_of_range(self): + arr1d = np.arange(6) + arr2d = np.arange(6).reshape(2, 3) + + @jit(nopython=True) + def jitargmax(arr, axis): + return np.argmax(arr, axis) + + def assert_raises(arr, axis): + with self.assertRaisesRegex(ValueError, "axis.*out of bounds"): + jitargmax.py_func(arr, axis) + with self.assertRaisesRegex(ValueError, "axis.*out of bounds"): + jitargmax(arr, axis) + + assert_raises(arr1d, 1) + assert_raises(arr1d, -2) + assert_raises(arr2d, -3) + assert_raises(arr2d, 2) + # Exceptions leak references + self.disable_leak_check() + + def test_argmax_axis_must_be_integer(self): + arr = np.arange(6) + + @jit(nopython=True) + def jitargmax(arr, axis): + return np.argmax(arr, axis) + + with self.assertTypingError() as e: + jitargmax(arr, "foo") + self.assertIn("axis must be an integer", str(e.exception)) + + def test_argmax_method_axis(self): + arr2d = np.arange(6).reshape(2, 3) + + def argmax(arr): + return arr2d.argmax(axis=0) + + self.assertPreciseEqual(argmax(arr2d), + jit(nopython=True)(argmax)(arr2d)) + + def test_argmax_return_type(self): + # See issue #7853, return type should be intp not based on input type + arr2d = np.arange(6, dtype=np.uint8).reshape(2, 3) + + def argmax(arr): + return arr2d.argmax(axis=0) + + self.assertPreciseEqual(argmax(arr2d), + jit(nopython=True)(argmax)(arr2d)) + + def test_argmin_axis_1d_2d_4d(self): + arr1d = np.array([0, 20, 3, 4]) + arr2d = np.arange(6).reshape(2, 3) + arr2d[0,1] += 100 + + arr4d = np.arange(120).reshape(2, 3, 4, 5) + 10 + arr4d[0, 1, 1, 2] += 100 + arr4d[1, 0, 0, 0] -= 51 + + for arr in [arr1d, arr2d, arr4d]: + axes = list(range(arr.ndim)) + [ + -(i+1) for i in range(arr.ndim) + ] + py_functions = [ + lambda a, _axis=axis: np.argmin(a, axis=_axis) + for axis in axes + ] + c_functions = [ + jit(nopython=True)(pyfunc) for pyfunc in py_functions + ] + for cfunc in c_functions: + self.assertPreciseEqual(cfunc.py_func(arr), cfunc(arr)) + + def test_argmin_axis_out_of_range(self): + arr1d = np.arange(6) + arr2d = np.arange(6).reshape(2, 3) + + @jit(nopython=True) + def jitargmin(arr, axis): + return np.argmin(arr, axis) + + def assert_raises(arr, axis): + with self.assertRaisesRegex(ValueError, "axis.*out of bounds"): + jitargmin.py_func(arr, axis) + with self.assertRaisesRegex(ValueError, "axis.*out of bounds"): + jitargmin(arr, axis) + + assert_raises(arr1d, 1) + assert_raises(arr1d, -2) + assert_raises(arr2d, -3) + assert_raises(arr2d, 2) + + # Exceptions leak references + self.disable_leak_check() + + def test_argmin_axis_must_be_integer(self): + arr = np.arange(6) + + @jit(nopython=True) + def jitargmin(arr, axis): + return np.argmin(arr, axis) + + with self.assertTypingError() as e: + jitargmin(arr, "foo") + self.assertIn("axis must be an integer", str(e.exception)) + + def test_argmin_method_axis(self): + arr2d = np.arange(6).reshape(2, 3) + + def argmin(arr): + return arr2d.argmin(axis=0) + + self.assertPreciseEqual(argmin(arr2d), + jit(nopython=True)(argmin)(arr2d)) + + def test_argmin_return_type(self): + # See issue #7853, return type should be intp not based on input type + arr2d = np.arange(6, dtype=np.uint8).reshape(2, 3) + + def argmin(arr): + return arr2d.argmin(axis=0) + + self.assertPreciseEqual(argmin(arr2d), + jit(nopython=True)(argmin)(arr2d)) + + @classmethod + def install_generated_tests(cls): + # These form a testing product where each of the combinations are tested + + # these function are tested in real and complex space + reduction_funcs = [array_sum, array_sum_global, + array_prod, array_prod_global, + array_mean, array_mean_global, + array_var, array_var_global, + array_std, array_std_global, + array_all, array_all_global, + array_any, array_any_global, + array_min, array_min_global, + array_amax, array_amin, + array_max, array_max_global, + array_nanmax, array_nanmin, + array_nansum, + ] + + # these functions only work in real space as no complex comparison + # operator is implemented + reduction_funcs_rspace = [array_argmin, array_argmin_global, + array_argmax, array_argmax_global] + + reduction_funcs += [array_nanmean, array_nanstd, array_nanvar] + reduction_funcs += [array_nanprod] + + dtypes_to_test = [np.int32, np.float32, np.bool_, np.complex64] + + def install_tests(dtypes, funcs): + # Install tests on class + for dt in dtypes: + test_arrays = full_test_arrays(dt) + for red_func, test_array in product(funcs, test_arrays): + # Create the name for the test function + test_name = "test_{0}_{1}_{2}d" + test_name = test_name.format(red_func.__name__, + test_array.dtype.name, + test_array.ndim) + + def new_test_function(self, redFunc=red_func, + testArray=test_array, + testName=test_name): + ulps = 1 + if 'prod' in red_func.__name__ and \ + np.iscomplexobj(testArray): + # prod family accumulate slightly more error on + # some architectures (power, 32bit) for complex input + ulps = 3 + npr, nbr = run_comparative(redFunc, testArray) + self.assertPreciseEqual(npr, nbr, msg=testName, + prec="single", ulps=ulps) + + # Install it into the class + setattr(cls, test_name, new_test_function) + + # install tests for reduction functions that only work in real space + install_tests(dtypes_to_test[:-1], reduction_funcs_rspace) + + # install tests for reduction functions + install_tests(dtypes_to_test, reduction_funcs) + + +TestArrayReductions.install_generated_tests() + + +class TestArrayReductionsExceptions(MemoryLeakMixin, TestCase): + + # int64, size 0 + zero_size = np.arange(0) + + def check_exception(self, pyfunc, msg): + cfunc = jit(nopython=True)(pyfunc) + # make sure NumPy raises consistently/no behaviour change + with self.assertRaises(BaseException): + pyfunc(self.zero_size) + # check numba impl raises expected + with self.assertRaises(ValueError) as e: + cfunc(self.zero_size) + self.assertIn(msg, str(e.exception)) + + @classmethod + def install(cls): + + fn_to_msg = dict() + empty_seq = "attempt to get {0} of an empty sequence" + op_no_ident = ("zero-size array to reduction operation " + "{0}") + for x in [array_argmax, array_argmax_global, array_argmin, + array_argmin_global]: + fn_to_msg[x] = empty_seq + for x in [array_max, array_max, array_min, array_min]: + fn_to_msg[x] = op_no_ident + + name_template = "test_zero_size_array_{0}" + for fn, msg in fn_to_msg.items(): + test_name = name_template.format(fn.__name__) + + lmsg = msg.format(fn.__name__) + lmsg = lmsg.replace('array_','').replace('_global','') + def test_fn(self, func=fn, message=lmsg): + self.check_exception(func, message) + + setattr(cls, test_name, test_fn) + +TestArrayReductionsExceptions.install() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_return.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_return.py new file mode 100644 index 0000000000000000000000000000000000000000..bab7160404ca27a0160880268610f84f66a71a9f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_return.py @@ -0,0 +1,38 @@ +import numpy as np + +from numba import typeof, njit +from numba.tests.support import MemoryLeakMixin +import unittest + + +def array_return(a, i): + a[i] = 123 + return a + + +def array_return_start_with_loop(a): + for i in range(a.size): + a[i] += 1 + return a + + +class TestArrayReturn(MemoryLeakMixin, unittest.TestCase): + def test_array_return(self): + a = np.arange(10) + i = 2 + at, it = typeof(a), typeof(i) + cfunc = njit((at, it))(array_return) + self.assertIs(a, cfunc(a, i)) + + def test_array_return_start_with_loop(self): + """ + A bug breaks array return if the function starts with a loop + """ + a = np.arange(10) + at = typeof(a) + cfunc = njit((at,))(array_return_start_with_loop) + self.assertIs(a, cfunc(a)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_auto_constants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_auto_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e58c8a1947be711b32e6369002e992ca66d839f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_auto_constants.py @@ -0,0 +1,38 @@ +import math +import sys + +import numpy as np + +from numba import njit +import numba.tests.usecases as uc +import unittest + + +class TestAutoConstants(unittest.TestCase): + def test_numpy_nan(self): + + @njit + def f(): + return np.nan + + self.assertTrue(math.isnan(f())) + self.assertTrue(math.isnan(f.py_func())) + + def test_sys_constant(self): + + @njit + def f(): + return sys.hexversion + + self.assertEqual(f(), f.py_func()) + + def test_module_string_constant(self): + + @njit + def f(): + return uc._GLOBAL_STR + self.assertEqual(f(), f.py_func()) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_buffer_protocol.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_buffer_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..b680d819e72e48e983405c3bf969d13544eb73a7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_buffer_protocol.py @@ -0,0 +1,289 @@ +import array + +import numpy as np + +from numba import jit +from numba.tests.support import TestCase, compile_function, MemoryLeakMixin +import unittest + + +@jit(nopython=True) +def len_usecase(buf): + return len(buf) + + +@jit(nopython=True) +def getitem_usecase(buf, i): + return buf[i] + + +@jit(nopython=True) +def getslice_usecase(buf, i, j): + s = buf[i:j] + return s[0] + 2 * s[-1] + + +@jit(nopython=True) +def setitem_usecase(buf, i, v): + buf[i] = v + + +@jit(nopython=True) +def iter_usecase(buf): + res = 0.0 + for i, x in enumerate(buf): + res += x + res *= i + 1 + return res + + +def attrgetter(attr): + code = """def func(x): + return x.%(attr)s +""" % locals() + pyfunc = compile_function("func", code, globals()) + return jit(nopython=True)(pyfunc) + + +contiguous_usecase = attrgetter("contiguous") +c_contiguous_usecase = attrgetter("c_contiguous") +f_contiguous_usecase = attrgetter("f_contiguous") +itemsize_usecase = attrgetter("itemsize") +nbytes_usecase = attrgetter("nbytes") +ndim_usecase = attrgetter("ndim") +readonly_usecase = attrgetter("readonly") +shape_usecase = attrgetter("shape") +strides_usecase = attrgetter("strides") + + +class TestBufferProtocol(MemoryLeakMixin, TestCase): + """ + Test operations on buffer-providing objects. + """ + + def _arrays(self): + n = 10 + for letter, offset in [ + ('b', -3), + ('B', 0), + ('h', -5000), + ('H', 40000), + ('i', -100000), + ('I', 1000000), + ('l', -100000), + ('L', 1000000), + ('q', -2**60), + ('Q', 2**63 + 1), + ('f', 1.5), + ('d', -1.5), + ]: + yield array.array(letter, [i + offset for i in range(n)]) + + def _memoryviews(self): + n = 10 + yield memoryview(bytearray(b"abcdefghi")) + yield memoryview(b"abcdefghi") + # Different item types + for dtype, start, stop in [ + ('int8', -10, 10), + ('uint8', 0, 10), + ('int16', -5000, 1000), + ('uint16', 40000, 50000), + ('int32', -100000, 100000), + ('uint32', 0, 1000000), + ('int64', -2**60, 10), + ('uint64', 0, 2**64 - 10), + ('float32', 1.5, 3.5), + ('float64', 1.5, 3.5), + ('complex64', -8j, 12 + 5j), + ('complex128', -8j, 12 + 5j), + ]: + yield memoryview(np.linspace(start, stop, n).astype(dtype)) + # Different layouts + arr = np.arange(12).reshape((3, 4)) + assert arr.flags.c_contiguous and not arr.flags.f_contiguous + yield memoryview(arr) + arr = arr.T + assert arr.flags.f_contiguous and not arr.flags.c_contiguous + yield memoryview(arr) + arr = arr[::2] + assert not arr.flags.f_contiguous and not arr.flags.c_contiguous + yield memoryview(arr) + + def _readonlies(self): + yield b"xyz" + yield memoryview(b"abcdefghi") + arr = np.arange(5) + arr.setflags(write=False) + yield memoryview(arr) + + def _check_unary(self, jitfunc, *args): + pyfunc = jitfunc.py_func + self.assertPreciseEqual(jitfunc(*args), pyfunc(*args)) + + def check_len(self, obj): + self._check_unary(len_usecase, obj) + + def check_iter(self, obj): + self._check_unary(iter_usecase, obj) + + def check_getitem(self, obj): + # Be careful to index all dimensions, since we don't support + # partial indexing yet. + def yield_indices(obj): + try: + shape = obj.shape + except AttributeError: + shape = len(obj), + for tup in np.ndindex(shape): + # Simple 1d buffer-providing objects usually don't support + # tuple indexing. + if len(tup) == 1: + yield tup[0] + else: + yield tup + + for i in yield_indices(obj): + try: + expected = obj[i] + except (NotImplementedError, TypeError): + if isinstance(obj, memoryview): + # The memoryview object doesn't support all codes yet, + # fall back on the underlying object. + expected = obj.obj[i] + else: + raise + self.assertPreciseEqual(getitem_usecase(obj, i), expected) + + def check_setitem(self, obj): + for i in range(len(obj)): + orig = list(obj) + val = obj[i] // 2 + 1 + setitem_usecase(obj, i, val) + self.assertEqual(obj[i], val) + for j, val in enumerate(orig): + if j != i: + self.assertEqual(obj[j], val) + + def check_getslice(self, obj): + self._check_unary(getslice_usecase, obj, 1, len(obj) - 1) + + def test_len(self): + self.check_len(bytearray(5)) + self.check_len(b"xyz") + for mem in self._memoryviews(): + self.check_len(mem) + for arr in self._arrays(): + self.check_len(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_getitem(self): + self.check_getitem(bytearray(b"abc")) + self.check_getitem(b"xyz") + for mem in self._memoryviews(): + self.check_getitem(mem) + for arr in self._arrays(): + self.check_getitem(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_getslice(self): + with self.assertTypingError(): + self.check_getslice(bytearray(b"abcde")) + self.check_getslice(b"xyzuvw") + self.check_getslice(memoryview(b"xyzuvw")) + with self.assertTypingError(): + self.check_getslice(array.array('i', range(10))) + for buf in self._readonlies(): + self.check_getitem(buf) + + def test_setitem(self): + self.check_setitem(bytearray(b"abcdefghi")) + for arr in self._arrays(): + self.check_setitem(arr) + for mem in self._memoryviews(): + self.check_getitem(mem) + # Read-only buffers + for buf in self._readonlies(): + with self.assertTypingError(): + self.check_setitem(buf) + + def test_iter(self): + self.check_iter(bytearray(b"abc")) + self.check_iter(b"xyz") + self.check_iter(memoryview(b"xyz")) + for arr in self._arrays(): + self.check_iter(arr) + for buf in self._readonlies(): + self.check_getitem(buf) + + +class TestMemoryView(MemoryLeakMixin, TestCase): + """ + Test memoryview-specific attributes and operations. + """ + + def _arrays(self): + arr = np.arange(12) + yield arr + arr = arr.reshape((3, 4)) + yield arr + yield arr.T + yield arr[::2] + arr.setflags(write=False) + yield arr + arr = np.zeros(()) + assert arr.ndim == 0 + yield arr + + def test_ndim(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(ndim_usecase(m), arr.ndim) + + def test_shape(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(shape_usecase(m), arr.shape) + + def test_strides(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(strides_usecase(m), arr.strides) + + def test_itemsize(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(itemsize_usecase(m), arr.itemsize) + + def test_nbytes(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertPreciseEqual(nbytes_usecase(m), arr.size * arr.itemsize) + + def test_readonly(self): + for arr in self._arrays(): + m = memoryview(arr) + self.assertIs(readonly_usecase(m), not arr.flags.writeable) + m = memoryview(b"xyz") + self.assertIs(readonly_usecase(m), True) + m = memoryview(bytearray(b"xyz")) + self.assertIs(readonly_usecase(m), False) + + def test_contiguous(self): + m = memoryview(bytearray(b"xyz")) + self.assertIs(contiguous_usecase(m), True) + self.assertIs(c_contiguous_usecase(m), True) + self.assertIs(f_contiguous_usecase(m), True) + for arr in self._arrays(): + m = memoryview(arr) + # Note `arr.flags.contiguous` is wrong (it mimics c_contiguous) + self.assertIs(contiguous_usecase(m), + arr.flags.f_contiguous or arr.flags.c_contiguous) + self.assertIs(c_contiguous_usecase(m), arr.flags.c_contiguous) + self.assertIs(f_contiguous_usecase(m), arr.flags.f_contiguous) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_builtins.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8419e34fe78df624f68db276bf22df259e965e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_builtins.py @@ -0,0 +1,1682 @@ +import itertools +import functools +import sys +import operator +from collections import namedtuple + +import numpy as np + +import unittest +import warnings + +from numba import jit, typeof, njit, typed +from numba.core import errors, types, config +from numba.tests.support import (TestCase, tag, ignore_internal_warnings, + MemoryLeakMixin) +from numba.core.extending import overload_method, box, register_jitable + + +forceobj_flags = {'forceobj': True} + +no_pyobj_flags = {'nopython': True, '_nrt': False} + +nrt_no_pyobj_flags = {'nopython': True} + + +def abs_usecase(x): + return abs(x) + +def all_usecase(x, y): + if x == None and y == None: + return all([]) + elif x == None: + return all([y]) + elif y == None: + return all([x]) + else: + return all([x, y]) + +def any_usecase(x, y): + if x == None and y == None: + return any([]) + elif x == None: + return any([y]) + elif y == None: + return any([x]) + else: + return any([x, y]) + +def bool_usecase(x): + return bool(x) + +def complex_usecase(x, y): + return complex(x, y) + +def divmod_usecase(x, y): + return divmod(x, y) + +def enumerate_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.)): + result += i * j + return result + +def enumerate_start_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.), 42): + result += i * j + return result + +def enumerate_invalid_start_usecase(): + result = 0 + for i, j in enumerate((1., 2.5, 3.), 3.14159): + result += i * j + return result + +def filter_usecase(x, filter_func): + return filter(filter_func, x) + +def float_usecase(x): + return float(x) + +def float_inf_usecase(x): + d = { + 0: float('inf'), + 1: float('INF'), + 2: float('-inf'), + 3: float('-INF'), + 4: float('\r\nINF\r '), + 5: float(' \r\n\t-INF'), + 6: float('1234.45'), + 7: float('\n-123.4\r'), + } + return d.get(x) + +def format_usecase(x, y): + return x.format(y) + +def globals_usecase(): + return globals() + +# NOTE: hash() is tested in test_hashing + +def hex_usecase(x): + return hex(x) + +def str_usecase(x): + return str(x) + +def int_usecase(x, base): + return int(x, base=base) + +def iter_next_usecase(x): + it = iter(x) + return next(it), next(it) + +def locals_usecase(x): + y = 5 + return locals()['y'] + +def long_usecase(x, base): + return long(x, base=base) + +def map_usecase(x, map_func): + return map(map_func, x) + + +def max_usecase1(x, y): + return max(x, y) + +def max_usecase2(x, y): + return max([x, y]) + +def max_usecase3(x): + return max(x) + +def max_usecase4(): + return max(()) + + +def min_usecase1(x, y): + return min(x, y) + +def min_usecase2(x, y): + return min([x, y]) + +def min_usecase3(x): + return min(x) + +def min_usecase4(): + return min(()) + +def oct_usecase(x): + return oct(x) + +def reduce_usecase(reduce_func, x): + return functools.reduce(reduce_func, x) + +def round_usecase1(x): + return round(x) + +def round_usecase2(x, n): + return round(x, n) + +def sum_usecase(x): + return sum(x) + +def type_unary_usecase(a, b): + return type(a)(b) + +def truth_usecase(p): + return operator.truth(p) + +def unichr_usecase(x): + return unichr(x) + +def zip_usecase(): + result = 0 + for i, j in zip((1, 2, 3), (4.5, 6.7)): + result += i * j + return result + +def zip_0_usecase(): + result = 0 + for i in zip(): + result += 1 + return result + +def zip_1_usecase(): + result = 0 + for i, in zip((1, 2)): + result += i + return result + + +def zip_3_usecase(): + result = 0 + for i, j, k in zip((1, 2), (3, 4, 5), (6.7, 8.9)): + result += i * j * k + return result + + +def zip_first_exhausted(): + iterable = range(7) + n = 3 + it = iter(iterable) + # 1st iterator is shorter + front = list(zip(range(n), it)) + # Make sure that we didn't skip one in `it` + back = list(it) + return front, back + + +def pow_op_usecase(x, y): + return x ** y + + +def pow_usecase(x, y): + return pow(x, y) + + +def sum_usecase(x): + return sum(x) + + +def sum_kwarg_usecase(x, start=0): + ret = sum(x, start) + return sum(x, start=start), ret + + +def isinstance_usecase(a): + if isinstance(a, (int, float)): + if isinstance(a, int): + return a + 1, 'int' + if isinstance(a, float): + return a + 2.0, 'float' + elif isinstance(a, str): + return a + ", world!", 'str' + elif isinstance(a, complex): + return a.imag, 'complex' + elif isinstance(a, (tuple, list)): + if isinstance(a, tuple): + return 'tuple' + else: + return 'list' + elif isinstance(a, set): + return 'set' + elif isinstance(a, bytes): + return 'bytes' + return 'no match' + + +def isinstance_dict(): + a = {1: 2, 3: 4} + b = {'a': 10, 'b': np.zeros(3)} + if isinstance(a, dict) and isinstance(b, dict): + return 'dict' + else: + return 'not dict' + + +def isinstance_usecase_numba_types(a): + if isinstance(a, typed.List): + return 'typed list' + elif isinstance(a, (types.int32, types.int64)): + if isinstance(a, types.int32): + return 'int32' + else: + return 'int64' + elif isinstance(a, (types.float32, types.float64)): + if isinstance(a, types.float32): + return 'float32' + elif isinstance(a, types.float64): + return 'float64' + elif isinstance(a, typed.Dict): + return 'typed dict' + else: + return 'no match' + + +def isinstance_usecase_numba_types_2(): + # some types cannot be passed as argument to njit functions + a = b'hello' + b = range(1, 2) + c = dict() + c[2] = 3 + if isinstance(a, bytes) and \ + isinstance(b, range) and \ + isinstance(c, dict): + return True + return False + + +def invalid_isinstance_usecase(x): + if isinstance(x, ('foo',)): + return 'true branch' + else: + return 'false branch' + + +def isinstance_usecase_invalid_type(x): + # this should be a valid call when x := float + if isinstance(x, (float, 'not a type')): + return True + else: + return False + + +def invalid_isinstance_usecase_phi_nopropagate(x): + if x > 4: + z = 10 + else: + z = 'a' + if isinstance(z, int): + return True + else: + return False + + +def invalid_isinstance_usecase_phi_nopropagate2(a): + # Numba issue #9125 + x = 0 + if isinstance(a, int): + a = (a, a) + + for i in range(len(a)): + x += i + return x + + +def invalid_isinstance_optional_usecase(x): + if x > 4: + z = 10 + else: + z = None + if isinstance(z, int): + return True + else: + return False + +def invalid_isinstance_unsupported_type_usecase(): + ntpl = namedtuple('ntpl', ['a', 'b']) + inst = ntpl(1, 2) + def impl(x): + return isinstance(inst, ntpl) + return impl + +class TestBuiltins(TestCase): + + def run_nullary_func(self, pyfunc, flags): + cfunc = jit((), **flags)(pyfunc) + expected = pyfunc() + self.assertPreciseEqual(cfunc(), expected) + + def test_abs(self, flags=forceobj_flags): + pyfunc = abs_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.float32,), **flags)(pyfunc) + for x in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + + complex_values = [-1.1 + 0.5j, 0.0 + 0j, 1.1 + 3j, + float('inf') + 1j * float('nan'), + float('nan') - 1j * float('inf')] + cfunc = jit((types.complex64,), **flags)(pyfunc) + for x in complex_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + cfunc = jit((types.complex128,), **flags)(pyfunc) + for x in complex_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + for unsigned_type in types.unsigned_domain: + unsigned_values = [0, 10, 2, 2 ** unsigned_type.bitwidth - 1] + cfunc = jit((unsigned_type,), **flags)(pyfunc) + for x in unsigned_values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_abs_npm(self): + self.test_abs(flags=no_pyobj_flags) + + def test_all(self, flags=forceobj_flags): + pyfunc = all_usecase + + cfunc = jit((types.int32,types.int32), **flags)(pyfunc) + x_operands = [-1, 0, 1, None] + y_operands = [-1, 0, 1, None] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_all_npm(self): + with self.assertTypingError(): + self.test_all(flags=no_pyobj_flags) + + def test_any(self, flags=forceobj_flags): + pyfunc = any_usecase + + cfunc = jit((types.int32,types.int32), **flags)(pyfunc) + x_operands = [-1, 0, 1, None] + y_operands = [-1, 0, 1, None] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_any_npm(self): + with self.assertTypingError(): + self.test_any(flags=no_pyobj_flags) + + def test_bool(self, flags=forceobj_flags): + pyfunc = bool_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + cfunc = jit((types.float64,), **flags)(pyfunc) + for x in [0.0, -0.0, 1.5, float('inf'), float('nan')]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + cfunc = jit((types.complex128,), **flags)(pyfunc) + for x in [complex(0, float('inf')), complex(0, float('nan'))]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_bool_npm(self): + self.test_bool(flags=no_pyobj_flags) + + def test_bool_nonnumber(self, flags=forceobj_flags): + pyfunc = bool_usecase + + cfunc = jit((types.string,), **flags)(pyfunc) + for x in ['x', '']: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.Dummy('list'),), **flags)(pyfunc) + for x in [[1], []]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_bool_nonnumber_npm(self): + with self.assertTypingError(): + self.test_bool_nonnumber(flags=no_pyobj_flags) + + def test_complex(self, flags=forceobj_flags): + pyfunc = complex_usecase + + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_complex_npm(self): + self.test_complex(flags=no_pyobj_flags) + + def test_divmod_ints(self, flags=forceobj_flags): + pyfunc = divmod_usecase + + cfunc = jit((types.int64, types.int64), **flags)(pyfunc) + + def truncate_result(x, bits=64): + # Remove any extraneous bits (since Numba will return + # a 64-bit result by definition) + if x >= 0: + x &= (1 << (bits - 1)) - 1 + return x + + denominators = [1, 3, 7, 15, -1, -3, -7, -15, 2**63 - 1, -2**63] + numerators = denominators + [0] + for x, y, in itertools.product(numerators, denominators): + expected_quot, expected_rem = pyfunc(x, y) + quot, rem = cfunc(x, y) + f = truncate_result + self.assertPreciseEqual((f(quot), f(rem)), + (f(expected_quot), f(expected_rem))) + + for x in numerators: + with self.assertRaises(ZeroDivisionError): + cfunc(x, 0) + + def test_divmod_ints_npm(self): + self.test_divmod_ints(flags=no_pyobj_flags) + + def test_divmod_floats(self, flags=forceobj_flags): + pyfunc = divmod_usecase + + cfunc = jit((types.float64, types.float64), **flags)(pyfunc) + + denominators = [1., 3.5, 1e100, -2., -7.5, -1e101, + np.inf, -np.inf, np.nan] + numerators = denominators + [-0.0, 0.0] + for x, y, in itertools.product(numerators, denominators): + expected_quot, expected_rem = pyfunc(x, y) + quot, rem = cfunc(x, y) + self.assertPreciseEqual((quot, rem), (expected_quot, expected_rem)) + + for x in numerators: + with self.assertRaises(ZeroDivisionError): + cfunc(x, 0.0) + + def test_divmod_floats_npm(self): + self.test_divmod_floats(flags=no_pyobj_flags) + + def test_enumerate(self, flags=forceobj_flags): + self.run_nullary_func(enumerate_usecase, flags) + + def test_enumerate_npm(self): + self.test_enumerate(flags=no_pyobj_flags) + + def test_enumerate_start(self, flags=forceobj_flags): + self.run_nullary_func(enumerate_start_usecase, flags) + + def test_enumerate_start_npm(self): + self.test_enumerate_start(flags=no_pyobj_flags) + + def test_enumerate_start_invalid_start_type(self): + pyfunc = enumerate_invalid_start_usecase + + cfunc = jit((), **forceobj_flags)(pyfunc) + + with self.assertRaises(TypeError) as raises: + cfunc() + + msg = "'float' object cannot be interpreted as an integer" + self.assertIn(msg, str(raises.exception)) + + def test_enumerate_start_invalid_start_type_npm(self): + pyfunc = enumerate_invalid_start_usecase + with self.assertRaises(errors.TypingError) as raises: + jit((), **no_pyobj_flags)(pyfunc) + msg = "Only integers supported as start value in enumerate" + self.assertIn(msg, str(raises.exception)) + + def test_filter(self, flags=forceobj_flags): + pyfunc = filter_usecase + argtys = (types.Dummy('list'), types.Dummy('function_ptr')) + cfunc = jit(argtys, **flags)(pyfunc) + + filter_func = lambda x: x % 2 + x = [0, 1, 2, 3, 4] + self.assertSequenceEqual(list(cfunc(x, filter_func)), + list(pyfunc(x, filter_func))) + + def test_filter_npm(self): + with self.assertTypingError(): + self.test_filter(flags=no_pyobj_flags) + + def test_float(self, flags=forceobj_flags): + pyfunc = float_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + cfunc = jit((types.float32,), **flags)(pyfunc) + for x in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single') + + cfunc = jit((types.string,), **flags)(pyfunc) + for x in ['-1.1', '0.0', '1.1', 'inf', '-inf', 'INF', '-INF']: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_float_npm(self): + with self.assertTypingError(): + self.test_float(flags=no_pyobj_flags) + + def test_float_string_literal(self): + pyfunc = float_inf_usecase + cfunc = njit(pyfunc) + for x in range(8): + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_format(self, flags=forceobj_flags): + pyfunc = format_usecase + + cfunc = jit((types.string, types.int32,), **flags)(pyfunc) + x = '{0}' + for y in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + cfunc = jit((types.string, types.float32,), **flags)(pyfunc) + x = '{0}' + for y in [-1.1, 0.0, 1.1]: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + cfunc = jit((types.string, types.string,), **flags)(pyfunc) + x = '{0}' + for y in ['a', 'b', 'c']: + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_format_npm(self): + with self.assertTypingError(): + self.test_format(flags=no_pyobj_flags) + + def test_globals(self, flags=forceobj_flags): + pyfunc = globals_usecase + cfunc = jit((), **flags)(pyfunc) + g = cfunc() + self.assertIs(g, globals()) + + def test_globals_npm(self): + with self.assertTypingError(): + self.test_globals(flags=no_pyobj_flags) + + def test_globals_jit(self, flags=forceobj_flags): + # Issue #416: weird behaviour of globals() in combination with + # the @jit decorator. + pyfunc = globals_usecase + jitted = jit(**flags)(pyfunc) + self.assertIs(jitted(), globals()) + self.assertIs(jitted(), globals()) + + def test_globals_jit_npm(self): + with self.assertTypingError(): + self.test_globals_jit(nopython=True) + + def test_hex(self, flags=forceobj_flags): + pyfunc = hex_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_hex_npm(self): + with self.assertTypingError(): + self.test_hex(flags=no_pyobj_flags) + + def test_int_str(self): + pyfunc = str_usecase + + small_inputs = [ + 1234, + 1, + 0, + 10, + 1000, + ] + + large_inputs = [ + 123456789, + 2222222, + 1000000, + ~0x0 + ] + + args = [*small_inputs, *large_inputs] + + typs = [ + types.int8, + types.int16, + types.int32, + types.int64, + types.uint, + types.uint8, + types.uint16, + types.uint32, + types.uint64, + ] + + for typ in typs: + cfunc = jit((typ,), **nrt_no_pyobj_flags)(pyfunc) + for v in args: + tp_info = np.iinfo(typ.key) + if not (tp_info.min <= v <= tp_info.max): + continue + self.assertPreciseEqual(cfunc(typ(v)), pyfunc(typ(v))) + + if typ.signed: + self.assertPreciseEqual(cfunc(typ(-v)), pyfunc(typ(-v))) + + def test_int(self, flags=forceobj_flags): + pyfunc = int_usecase + + cfunc = jit((types.string, types.int32,), **flags)(pyfunc) + + x_operands = ['-1', '0', '1', '10'] + y_operands = [2, 8, 10, 16] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_int_npm(self): + with self.assertTypingError(): + self.test_int(flags=no_pyobj_flags) + + def test_iter_next(self, flags=forceobj_flags): + pyfunc = iter_next_usecase + cfunc = jit((types.UniTuple(types.int32, 3),), **flags)(pyfunc) + self.assertPreciseEqual(cfunc((1, 42, 5)), (1, 42)) + + cfunc = jit((types.UniTuple(types.int32, 1),), **flags)(pyfunc) + with self.assertRaises(StopIteration): + cfunc((1,)) + + def test_iter_next_npm(self): + self.test_iter_next(flags=no_pyobj_flags) + + def test_locals(self, flags=forceobj_flags): + pyfunc = locals_usecase + with self.assertRaises(errors.ForbiddenConstruct): + jit((types.int64,), **flags)(pyfunc) + + def test_locals_forceobj(self): + self.test_locals(flags=forceobj_flags) + + def test_locals_npm(self): + with self.assertTypingError(): + self.test_locals(flags=no_pyobj_flags) + + def test_map(self, flags=forceobj_flags): + pyfunc = map_usecase + argtys = (types.Dummy('list'), types.Dummy('function_ptr')) + cfunc = jit(argtys, **flags)(pyfunc) + + map_func = lambda x: x * 2 + x = [0, 1, 2, 3, 4] + self.assertSequenceEqual(list(cfunc(x, map_func)), + list(pyfunc(x, map_func))) + + def test_map_npm(self): + with self.assertTypingError(): + self.test_map(flags=no_pyobj_flags) + + # + # min() and max() + # + + def check_minmax_1(self, pyfunc, flags): + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_1(self, flags=forceobj_flags): + """ + max(*args) + """ + self.check_minmax_1(max_usecase1, flags) + + def test_min_1(self, flags=forceobj_flags): + """ + min(*args) + """ + self.check_minmax_1(min_usecase1, flags) + + def test_max_npm_1(self): + self.test_max_1(flags=no_pyobj_flags) + + def test_min_npm_1(self): + self.test_min_1(flags=no_pyobj_flags) + + def check_minmax_2(self, pyfunc, flags): + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + + x_operands = [-1, 0, 1] + y_operands = [-1, 0, 1] + for x, y in itertools.product(x_operands, y_operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_2(self, flags=forceobj_flags): + """ + max(list) + """ + self.check_minmax_2(max_usecase2, flags) + + def test_min_2(self, flags=forceobj_flags): + """ + min(list) + """ + self.check_minmax_2(min_usecase2, flags) + + def test_max_npm_2(self): + with self.assertTypingError(): + self.test_max_2(flags=no_pyobj_flags) + + def test_min_npm_2(self): + with self.assertTypingError(): + self.test_min_2(flags=no_pyobj_flags) + + def check_minmax_3(self, pyfunc, flags): + def check(argty): + cfunc = jit((argty,), **flags)(pyfunc) + # Check that the algorithm matches Python's with a non-total order + tup = (1.5, float('nan'), 2.5) + for val in [tup, tup[::-1]]: + self.assertPreciseEqual(cfunc(val), pyfunc(val)) + + check(types.UniTuple(types.float64, 3)) + check(types.Tuple((types.float32, types.float64, types.float32))) + + def test_max_3(self, flags=forceobj_flags): + """ + max(tuple) + """ + self.check_minmax_3(max_usecase3, flags) + + def test_min_3(self, flags=forceobj_flags): + """ + min(tuple) + """ + self.check_minmax_3(min_usecase3, flags) + + def test_max_npm_3(self): + self.test_max_3(flags=no_pyobj_flags) + + def test_min_npm_3(self): + self.test_min_3(flags=no_pyobj_flags) + + def check_min_max_invalid_types(self, pyfunc, flags=forceobj_flags): + cfunc = jit((types.int32, types.Dummy('list'),), **flags)(pyfunc) + cfunc(1, [1]) + + def test_max_1_invalid_types(self): + with self.assertRaises(TypeError): + self.check_min_max_invalid_types(max_usecase1) + + def test_max_1_invalid_types_npm(self): + with self.assertTypingError(): + self.check_min_max_invalid_types(max_usecase1, flags=no_pyobj_flags) + + def test_min_1_invalid_types(self): + with self.assertRaises(TypeError): + self.check_min_max_invalid_types(min_usecase1) + + def test_min_1_invalid_types_npm(self): + with self.assertTypingError(): + self.check_min_max_invalid_types(min_usecase1, flags=no_pyobj_flags) + + def check_minmax_bool1(self, pyfunc, flags): + cfunc = jit((types.bool_, types.bool_), **flags)(pyfunc) + + operands = (False, True) + for x, y in itertools.product(operands, operands): + self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y)) + + def test_max_bool1(self, flags=forceobj_flags): + # tests max() + self.check_minmax_bool1(max_usecase1, flags) + + def test_min_bool1(self, flags=forceobj_flags): + # tests min() + self.check_minmax_bool1(min_usecase1, flags) + + # Test that max(1) and min(1) fail + + def check_min_max_unary_non_iterable(self, pyfunc, flags=forceobj_flags): + cfunc = jit((types.int32,), **flags)(pyfunc) + cfunc(1) + + def test_max_unary_non_iterable(self): + with self.assertRaises(TypeError): + self.check_min_max_unary_non_iterable(max_usecase3) + + def test_max_unary_non_iterable_npm(self): + with self.assertTypingError(): + self.check_min_max_unary_non_iterable(max_usecase3) + + def test_min_unary_non_iterable(self): + with self.assertRaises(TypeError): + self.check_min_max_unary_non_iterable(min_usecase3) + + def test_min_unary_non_iterable_npm(self): + with self.assertTypingError(): + self.check_min_max_unary_non_iterable(min_usecase3) + + # Test that max(()) and min(()) fail + + def check_min_max_empty_tuple(self, pyfunc, func_name): + with self.assertTypingError() as raises: + jit((), **no_pyobj_flags)(pyfunc) + self.assertIn("%s() argument is an empty tuple" % func_name, + str(raises.exception)) + + def test_max_empty_tuple(self): + self.check_min_max_empty_tuple(max_usecase4, "max") + + def test_min_empty_tuple(self): + self.check_min_max_empty_tuple(min_usecase4, "min") + + + def test_oct(self, flags=forceobj_flags): + pyfunc = oct_usecase + + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-8, -1, 0, 1, 8]: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_oct_npm(self): + with self.assertTypingError(): + self.test_oct(flags=no_pyobj_flags) + + def test_reduce(self, flags=forceobj_flags): + pyfunc = reduce_usecase + argtys = (types.Dummy('function_ptr'), types.Dummy('list')) + cfunc = jit(argtys, **flags)(pyfunc) + + reduce_func = lambda x, y: x + y + + x = range(10) + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + x = [x + x/10.0 for x in range(10)] + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + x = [complex(x, x) for x in range(10)] + self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x)) + + def test_reduce_npm(self): + with self.assertTypingError(): + self.test_reduce(flags=no_pyobj_flags) + + def test_round1(self, flags=forceobj_flags): + pyfunc = round_usecase1 + + for tp in (types.float64, types.float32): + cfunc = jit((tp,), **flags)(pyfunc) + values = [-1.6, -1.5, -1.4, -0.5, 0.0, 0.1, 0.5, 0.6, 1.4, 1.5, 5.0] + values += [-0.1, -0.0] + for x in values: + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_round1_npm(self): + self.test_round1(flags=no_pyobj_flags) + + def test_round2(self, flags=forceobj_flags): + pyfunc = round_usecase2 + + for tp in (types.float64, types.float32): + prec = 'single' if tp is types.float32 else 'exact' + cfunc = jit((tp, types.int32), **flags)(pyfunc) + for x in [0.0, 0.1, 0.125, 0.25, 0.5, 0.75, 1.25, + 1.5, 1.75, 2.25, 2.5, 2.75, 12.5, 15.0, 22.5]: + for n in (-1, 0, 1, 2): + self.assertPreciseEqual(cfunc(x, n), pyfunc(x, n), + prec=prec) + expected = pyfunc(-x, n) + self.assertPreciseEqual(cfunc(-x, n), pyfunc(-x, n), + prec=prec) + + def test_round2_npm(self): + self.test_round2(flags=no_pyobj_flags) + + def test_sum_objmode(self, flags=forceobj_flags): + pyfunc = sum_usecase + + cfunc = jit((types.Dummy('list'),), **flags)(pyfunc) + + x = range(10) + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + x = [x + x/10.0 for x in range(10)] + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + x = [complex(x, x) for x in range(10)] + self.assertPreciseEqual(cfunc(x), pyfunc(x)) + + def test_sum(self): + # In Python 3.8+ "start" can be specified as a kwarg, so test that too + sum_default = njit(sum_usecase) + sum_kwarg = njit(sum_kwarg_usecase) + + @njit + def sum_range(sz, start=0): + tmp = range(sz) + ret = sum(tmp, start) + return sum(tmp, start=start), ret + + ntpl = namedtuple('ntpl', ['a', 'b']) + + # check call with default kwarg, start=0 + def args(): + yield [*range(10)] + yield [x + x/10.0 for x in range(10)] + yield [x * 1j for x in range(10)] + yield (1, 2, 3) + yield (1, 2, 3j) + # uints will likely end up as floats as `start` is signed, so just + # test mixed signed ints + yield (np.int64(32), np.int32(2), np.int8(3)) + tl = typed.List(range(5)) + yield tl + yield np.ones(5) + yield ntpl(100, 200) + yield ntpl(100, 200j) + + for x in args(): + self.assertPreciseEqual(sum_default(x), sum_default.py_func(x)) + + # Check the uint use case, as start is signed, NumPy will end up with + # a float result whereas Numba will end up with an int (see integer + # typing NBEP). + x = (np.uint64(32), np.uint32(2), np.uint8(3)) + self.assertEqual(sum_default(x), sum_default.py_func(x)) + + # check call with changing default kwarg, start + def args_kws(): + yield [*range(10)], 12 + yield [x + x/10.0 for x in range(10)], 19j + yield [x * 1j for x in range(10)], -2 + yield (1, 2, 3), 9 + yield (1, 2, 3j), -0 + # uints will likely end up as floats as `start` is signed, so just + # test mixed signed ints + yield (np.int64(32), np.int32(2), np.int8(3)), np.uint32(7) + tl = typed.List(range(5)) + yield tl, 100 + yield np.ones((5, 5)), 10 * np.ones((5,)) + yield ntpl(100, 200), -50 + yield ntpl(100, 200j), 9 + + for x, start in args_kws(): + self.assertPreciseEqual(sum_kwarg(x, start=start), + sum_kwarg.py_func(x, start=start)) + + # check call with range() + for start in range(-3, 4): + for sz in range(-3, 4): + self.assertPreciseEqual(sum_range(sz, start=start), + sum_range.py_func(sz, start=start)) + + def test_sum_exceptions(self): + sum_default = njit(sum_usecase) + sum_kwarg = njit(sum_kwarg_usecase) + + # check start as string/bytes/bytearray is error + msg = "sum() can't sum {}" + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), 'a') + + self.assertIn(msg.format('strings'), str(raises.exception)) + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), b'123') + + self.assertIn(msg.format('bytes'), str(raises.exception)) + + with self.assertRaises(errors.TypingError) as raises: + sum_kwarg((1, 2, 3), bytearray(b'123')) + + self.assertIn(msg.format('bytearray'), str(raises.exception)) + + # check invalid type has no impl + with self.assertRaises(errors.TypingError) as raises: + sum_default('abcd') + + self.assertIn('No implementation', str(raises.exception)) + + def test_truth(self): + pyfunc = truth_usecase + cfunc = jit(nopython=True)(pyfunc) + + self.assertEqual(pyfunc(True), cfunc(True)) + self.assertEqual(pyfunc(False), cfunc(False)) + + def test_type_unary(self): + # Test type(val) and type(val)(other_val) + pyfunc = type_unary_usecase + cfunc = jit(nopython=True)(pyfunc) + + def check(*args): + expected = pyfunc(*args) + self.assertPreciseEqual(cfunc(*args), expected) + + check(1.5, 2) + check(1, 2.5) + check(1.5j, 2) + check(True, 2) + check(2.5j, False) + + def test_zip(self, flags=forceobj_flags): + self.run_nullary_func(zip_usecase, flags) + + def test_zip_npm(self): + self.test_zip(flags=no_pyobj_flags) + + def test_zip_1(self, flags=forceobj_flags): + self.run_nullary_func(zip_1_usecase, flags) + + def test_zip_1_npm(self): + self.test_zip_1(flags=no_pyobj_flags) + + def test_zip_3(self, flags=forceobj_flags): + self.run_nullary_func(zip_3_usecase, flags) + + def test_zip_3_npm(self): + self.test_zip_3(flags=no_pyobj_flags) + + def test_zip_0(self, flags=forceobj_flags): + self.run_nullary_func(zip_0_usecase, flags) + + def test_zip_0_npm(self): + self.test_zip_0(flags=no_pyobj_flags) + + def test_zip_first_exhausted(self, flags=forceobj_flags): + """ + Test side effect to the input iterators when a left iterator has been + exhausted before the ones on the right. + """ + self.run_nullary_func(zip_first_exhausted, flags) + + def test_zip_first_exhausted_npm(self): + self.test_zip_first_exhausted(flags=nrt_no_pyobj_flags) + + def test_pow_op_usecase(self): + args = [ + (2, 3), + (2.0, 3), + (2, 3.0), + (2j, 3.0j), + ] + + for x, y in args: + argtys = (typeof(x), typeof(y)) + cfunc = jit(argtys, **no_pyobj_flags)(pow_op_usecase) + r = cfunc(x, y) + self.assertPreciseEqual(r, pow_op_usecase(x, y)) + + def test_pow_usecase(self): + args = [ + (2, 3), + (2.0, 3), + (2, 3.0), + (2j, 3.0j), + ] + + for x, y in args: + argtys = (typeof(x), typeof(y)) + cfunc = jit(argtys, **no_pyobj_flags)(pow_usecase) + r = cfunc(x, y) + self.assertPreciseEqual(r, pow_usecase(x, y)) + + def _check_min_max(self, pyfunc): + cfunc = njit()(pyfunc) + expected = pyfunc() + got = cfunc() + self.assertPreciseEqual(expected, got) + + def test_min_max_iterable_input(self): + + @njit + def frange(start, stop, step): + i = start + while i < stop: + yield i + i += step + + def sample_functions(op): + yield lambda: op(range(10)) + yield lambda: op(range(4, 12)) + yield lambda: op(range(-4, -15, -1)) + yield lambda: op([6.6, 5.5, 7.7]) + yield lambda: op([(3, 4), (1, 2)]) + yield lambda: op(frange(1.1, 3.3, 0.1)) + yield lambda: op([np.nan, -np.inf, np.inf, np.nan]) + yield lambda: op([(3,), (1,), (2,)]) + + for fn in sample_functions(op=min): + self._check_min_max(fn) + + for fn in sample_functions(op=max): + self._check_min_max(fn) + + +class TestOperatorMixedTypes(TestCase): + + def test_eq_ne(self): + for opstr in ('eq', 'ne'): + op = getattr(operator, opstr) + + @njit + def func(a, b): + return op(a, b) + + # all these things should evaluate to being equal or not, all should + # survive typing. + things = (1, 0, True, False, 1.0, 2.0, 1.1, 1j, None, "", "1") + for x, y in itertools.product(things, things): + self.assertPreciseEqual(func.py_func(x, y), func(x, y)) + + def test_cmp(self): + for opstr in ('gt', 'lt', 'ge', 'le', 'eq', 'ne'): + op = getattr(operator, opstr) + @njit + def func(a, b): + return op(a, b) + + # numerical things should all be comparable + things = (1, 0, True, False, 1.0, 0.0, 1.1) + for x, y in itertools.product(things, things): + expected = func.py_func(x, y) + got = func(x, y) + message = ("%s %s %s does not match between Python and Numba" + % (x, opstr, y)) + self.assertEqual(expected, got, message) + + +class TestIsinstanceBuiltin(TestCase): + def test_isinstance(self): + pyfunc = isinstance_usecase + cfunc = jit(nopython=True)(pyfunc) + + inputs = ( + 3, # int + 5.0, # float + "Hello", # string + b'world', # bytes + 1j, # complex + [1, 2, 3], # list + (1, 3, 3, 3), # UniTuple + set([1, 2]), # set + (1, 'nba', 2), # Heterogeneous Tuple + # {'hello': 2}, # dict - doesn't work as input + None, + ) + + for inpt in inputs: + expected = pyfunc(inpt) + got = cfunc(inpt) + self.assertEqual(expected, got) + + def test_isinstance_dict(self): + # Tests typed.Dict and LiteralStrKeyDict + pyfunc = isinstance_dict + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def test_isinstance_issue9125(self): + pyfunc = invalid_isinstance_usecase_phi_nopropagate2 + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(3), cfunc(3)) + + def test_isinstance_numba_types(self): + # This makes use of type aliasing between python scalars and NumPy + # scalars, see also test_numba_types() + pyfunc = isinstance_usecase_numba_types + cfunc = jit(nopython=True)(pyfunc) + + inputs = ( + (types.int32(1), 'int32'), + (types.int64(2), 'int64'), + (types.float32(3.0), 'float32'), + (types.float64(4.0), 'float64'), + (types.complex64(5j), 'no match'), + (typed.List([1, 2]), 'typed list'), + (typed.Dict.empty(types.int64, types.int64), 'typed dict') + ) + + for inpt, expected in inputs: + got = cfunc(inpt) + self.assertEqual(expected, got) + + def test_isinstance_numba_types_2(self): + pyfunc = isinstance_usecase_numba_types_2 + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def test_isinstance_invalid_type(self): + pyfunc = isinstance_usecase_invalid_type + cfunc = jit(nopython=True)(pyfunc) + + # valid type + self.assertTrue(cfunc(3.4)) + + # invalid type + msg = 'Cannot infer Numba type of Python type' + + with self.assertRaises(errors.TypingError) as raises: + cfunc(100) + + self.assertIn(msg, str(raises.exception)) + + def test_isinstance_exceptions(self): + fns = [ + (invalid_isinstance_usecase, + 'Cannot infer Numba type of Python type'), + (invalid_isinstance_usecase_phi_nopropagate, + ('isinstance() cannot determine the type of variable "z" due to a ' + 'branch.')), + (invalid_isinstance_optional_usecase, + ('isinstance() cannot determine the type of variable "z" due to a ' + 'branch.')), + (invalid_isinstance_unsupported_type_usecase(), + ('isinstance() does not support variables of type "ntpl(')), + ] + + for fn, msg in fns: + fn = njit(fn) + + with self.assertRaises(errors.TypingError) as raises: + fn(100) + + self.assertIn(msg, str(raises.exception)) + + def test_combinations(self): + # Combinatorically test common classes and instances + def gen_w_arg(clazz_type): + def impl(x): + return isinstance(x, clazz_type) + return impl + + clazz_types = (int, float, complex, str, list, tuple, bytes, set, range, + np.int8, np.float32,) + instances = (1, 2.3, 4j, '5', [6,], (7,), b'8', {9,}, None, + (10, 11, 12), (13, 'a', 14j), np.array([15, 16, 17]), + np.int8(18), np.float32(19), + typed.Dict.empty(types.unicode_type, types.float64), + typed.List.empty_list(types.complex128), np.ones(4)) + + for ct in clazz_types: + fn = njit(gen_w_arg(ct)) + for x in instances: + expected = fn.py_func(x) + got = fn(x) + self.assertEqual(got, expected) + + def test_numba_types(self): + # Check types which are Numba types, this would break without the jit + # decorator in all cases except numba.typed containers. + def gen_w_arg(clazz_type): + def impl(): + return isinstance(1, clazz_type) + return impl + + clazz_types = (types.Integer, types.Float, types.Array,) + + msg = "Numba type classes.*are not supported" + for ct in clazz_types: + fn = njit(gen_w_arg(ct)) + with self.assertRaises(errors.TypingError) as raises: + fn() + self.assertRegex(str(raises.exception), msg) + + def test_python_numpy_scalar_alias_problem(self): + # There's a problem due to Python and NumPy scalars being aliased in the + # type system. This is because e.g. int scalar values and NumPy np.intp + # type alias to types.intp. This test merely records this fact. + + @njit + def foo(): + return isinstance(np.intp(10), int) + + self.assertEqual(foo(), True) + self.assertEqual(foo.py_func(), False) + + @njit + def bar(): + return isinstance(1, np.intp) + + self.assertEqual(bar(), True) + self.assertEqual(bar.py_func(), False) + + def test_branch_prune(self): + # Check that isinstance branches are pruned allowing otherwise + # impossible type specific specialisation. + + @njit + def foo(x): + if isinstance(x, str): + return x + 'some_string' + elif isinstance(x, complex): + return np.imag(x) + elif isinstance(x, tuple): + return len(x) + else: + assert 0 + + for x in ('string', 1 + 2j, ('a', 3, 4j)): + expected = foo.py_func(x) + got = foo(x) + self.assertEqual(got, expected) + + def test_branch_prune_and_bind_to_sig(self): + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @njit + def call_f(x): + if isinstance(x, tuple): + return f(*x) + else: + return f(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a Tuple type, this will fail on the `else` + # branch as `f` takes two arguments opposed to one. + x = (1, 2) + self.assertEqual(call_f(x), call_f.py_func(x)) + + + # This should raise as partial type inference and branch pruning will + # remove the `f(*x)` branch and just leave `f(x)`, which then won't + # bind because `f` takes two arguments and only one is supplied. + with self.assertRaises(errors.TypingError) as raises: + call_f(1) + + msg = str(raises.exception) + self.assertIn("Cannot bind", msg) + self.assertIn("TypeError: missing a required argument: 'y'", msg) + + def test_branch_prune_non_tuples_as_star_arg(self): + + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @register_jitable + def g(x): + return x + + @njit + def call_f(x): + if isinstance(x, tuple): + return f(*x) + else: + return g(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a non-tuple type `*x` will not bind to the + # signature of `f`. + x = 1 + self.assertEqual(call_f(x), call_f.py_func(x)) + + def test_branch_prune_literal_as_star_arg(self): + + # see issue 9795 + @register_jitable + def f(x, y): + return x + y + + @register_jitable + def g(x): + return x + + one = 1 + @njit + def call_f(): + x = one + if isinstance(x, tuple): + return f(*x) + else: + return g(x) + + # The issue is that without isinstance and branch pruning working + # correctly, an attempt will be made to bind the function `f` with + # argument `x`. If `x` is a non-tuple const value type `*x` will not + # bind to the signature of `f`. + self.assertEqual(call_f(), call_f.py_func()) + + +class TestGetattrBuiltin(MemoryLeakMixin, TestCase): + # Tests the getattr() builtin + + def test_getattr_func_retty(self): + + @njit + def foo(x): + attr = getattr(x, '__hash__') + return attr() + + for x in (1, 2.34, (5, 6, 7)): + self.assertPreciseEqual(foo(x), foo.py_func(x)) + + def test_getattr_value_retty(self): + + @njit + def foo(x): + return getattr(x, 'ndim') + + for x in range(3): + tmp = np.empty((1, ) * x) + self.assertPreciseEqual(foo(tmp), foo.py_func(tmp)) + + def test_getattr_module_obj(self): + # Consts on modules work ok + + @njit + def foo(): + return getattr(np, 'pi') + + self.assertPreciseEqual(foo(), foo.py_func()) + + def test_getattr_module_obj_not_implemented(self): + # Functions on modules do not work at present + + @njit + def foo(): + return getattr(np, 'cos')(1) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + msg = "Returning function objects is not implemented" + self.assertIn(msg, str(raises.exception)) + + def test_getattr_raises_attribute_error(self): + + invalid_attr = '__not_a_valid_attr__' + + @njit + def foo(x): + return getattr(x, invalid_attr) + + with self.assertRaises(AttributeError) as raises: + foo(1.23) + + self.assertIn(f"'float64' has no attribute '{invalid_attr}'", + str(raises.exception)) + + def test_getattr_with_default(self): + # Checks returning a default works + + @njit + def foo(x, default): + return getattr(x, '__not_a_valid_attr__', default) + + for x, y in zip((1, 2.34, (5, 6, 7),), (None, 20, 'some_string')): + self.assertPreciseEqual(foo(x, y), foo.py_func(x, y)) + + def test_getattr_non_literal_str(self): + + @njit + def foo(x, nonliteral_str): + return getattr(x, nonliteral_str) + + with self.assertRaises(errors.TypingError) as raises: + foo(1, '__hash__') + + msg = "argument 'name' must be a literal string" + self.assertIn(msg, str(raises.exception)) + + def test_getattr_no_optional_type_generated(self): + + @njit + def default_hash(): + return 12345 + + @njit + def foo(): + hash_func = getattr(np.ones(1), "__not_a_valid_attr__", + default_hash) + return hash_func() # Optionals have no call support + + self.assertPreciseEqual(foo(), foo.py_func()) + + +class TestHasattrBuiltin(MemoryLeakMixin, TestCase): + # Tests the hasattr() builtin + + def test_hasattr(self): + + @njit + def foo(x): + return hasattr(x, '__hash__'), hasattr(x, '__not_a_valid_attr__') + + ty = types.int64 + for x in (1, 2.34, (5, 6, 7), typed.Dict.empty(ty, ty), + typed.List.empty_list(ty), np.ones(4), 'ABC'): + self.assertPreciseEqual(foo(x), foo.py_func(x)) + + def test_hasattr_non_const_attr(self): + # This tests that an error is raised in the case that a hasattr() call + # is made on an attribute that cannot be resolved as a compile time + # constant (there's a phi in the way!). + + @njit + def foo(pred): + if pred > 3: + attr = "__hash__" + else: + attr = "__str__" + + hasattr(1, attr) + + with self.assertRaises(errors.NumbaTypeError) as raises: + foo(6) + + msg = ('hasattr() cannot determine the type of variable ' + '"attr" due to a branch.') + self.assertIn(msg, str(raises.exception)) + + +class TestStrAndReprBuiltin(MemoryLeakMixin, TestCase): + + def test_str_default(self): + + @njit + def foo(): + return str() + + self.assertEqual(foo(), foo.py_func()) + + def test_str_object_kwarg(self): + + @njit + def foo(x): + return str(object=x) + + value = "a string" + self.assertEqual(foo(value), foo.py_func(value)) + + def test_str_calls_dunder_str(self): + + @njit + def foo(x): + return str(x) + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = "this is the dummy object str" + Dummy.__str__= lambda inst: string_repr + + @overload_method(DummyType, "__str__") + def ol_dummy_string(dummy): + def impl(dummy): + return string_repr + return impl + + @overload_method(DummyType, "__repr__") + def ol_dummy_repr(dummy): + def impl(dummy): + return "SHOULD NOT BE CALLED" + return impl + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + def test_str_falls_back_to_repr(self): + + @njit + def foo(x): + return str(x) + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = "this is the dummy object repr" + Dummy.__repr__= lambda inst: string_repr + + @overload_method(DummyType, "__repr__") + def ol_dummy_repr(dummy): + def impl(dummy): + return string_repr + return impl + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + def test_repr(self): + @njit + def foo(x): + return repr(x), x + + for x in ("abc", False, 123): + self.assertEqual(foo(x), foo.py_func(x)) + + def test_repr_fallback(self): + # checks str/repr fallback, there's no overloaded __str__ or __repr__ + # for the dummy type so it has to use generic '' + # string for the `repr` call. + + Dummy, DummyType = self.make_dummy_type() + dummy = Dummy() + string_repr = f"" + Dummy.__repr__= lambda inst: string_repr + + @box(DummyType) + def box_dummy(typ, obj, c): + clazobj = c.pyapi.unserialize(c.pyapi.serialize_object(Dummy)) + return c.pyapi.call_function_objargs(clazobj, ()) + + @njit + def foo(x): + return str(x) + + self.assertEqual(foo(dummy), foo.py_func(dummy)) + + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_byteflow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_byteflow.py new file mode 100644 index 0000000000000000000000000000000000000000..041e1d65b20f7fcdc49857903748727cecc29a16 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_byteflow.py @@ -0,0 +1,94 @@ +""" +Test byteflow.py specific issues +""" +import unittest + +from numba.tests.support import TestCase +from numba.core.compiler import run_frontend + + +class TestByteFlowIssues(TestCase): + def test_issue_5087(self): + # This is an odd issue. The exact number of print below is + # necessary to trigger it. Too many or too few will alter the behavior. + # Also note that the function below will not be executed. The problem + # occurs at compilation. The definition below is invalid for execution. + # The problem occurs in the bytecode analysis. + def udt(): + print + print + print + + for i in range: + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + + for j in range: + print + print + print + print + print + print + print + for k in range: + for l in range: + print + + print + print + print + print + print + print + print + print + print + if print: + for n in range: + print + else: + print + + run_frontend(udt) + + def test_issue_5097(self): + # Inspired by https://github.com/numba/numba/issues/5097 + def udt(): + for i in range(0): + if i > 0: + pass + a = None # noqa: F841 + + run_frontend(udt) + + def test_issue_5680(self): + # From https://github.com/numba/numba/issues/5680#issuecomment-625351336 + def udt(): + for k in range(0): + if 1 == 1: + ... + if 'a' == 'a': + ... + + run_frontend(udt) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_caching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..7d81e2bfe742d897f27609ee2f7ef1d5a35c925e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_caching.py @@ -0,0 +1,1325 @@ +import importlib +import inspect +import multiprocessing +import os +import shutil +import stat +import subprocess +import sys +import traceback +import unittest +import warnings +import zipfile +from pathlib import Path + +import llvmlite.binding as ll +import numpy as np +from math import floor + +from numba import njit +from numba.core import codegen +from numba.core.caching import ( + UserWideCacheLocator, + ZipCacheLocator, + FunctionCache, + InTreeCacheLocator, + InTreeCacheLocatorFsAgnostic, +) +from numba.core.errors import NumbaWarning +from numba.parfors import parfor +from numba.tests.support import ( + SerialMixin, + TestCase, + capture_cache_log, + import_dynamic, + override_config, + run_in_new_process_caching, + skip_if_typeguard, + skip_parfors_unsupported, + temp_directory, + override_env_config, +) + +from numba.core.registry import cpu_target + +try: + import ipykernel +except ImportError: + ipykernel = None + + +def check_access_is_preventable(): + # This exists to check whether it is possible to prevent access to + # a file/directory through the use of `chmod 500`. If a user has + # elevated rights (e.g. root) then writes are likely to be possible + # anyway. Tests that require functioning access prevention are + # therefore skipped based on the result of this check. + tempdir = temp_directory('test_cache') + test_dir = (os.path.join(tempdir, 'writable_test')) + os.mkdir(test_dir) + # check a write is possible + with open(os.path.join(test_dir, 'write_ok'), 'wt') as f: + f.write('check1') + # now forbid access + os.chmod(test_dir, 0o500) + try: + with open(os.path.join(test_dir, 'write_forbidden'), 'wt') as f: + f.write('check2') + # access prevention is not possible + return False + except PermissionError: + # Check that the cause of the exception is due to access/permission + # as per + # https://github.com/conda/conda/blob/4.5.0/conda/gateways/disk/permissions.py#L35-L37 # noqa: E501 + # errno reports access/perm fail so access prevention via + # `chmod 500` works for this user. + return True + finally: + os.chmod(test_dir, 0o775) + shutil.rmtree(test_dir) + + +_access_preventable = check_access_is_preventable() +_access_msg = "Cannot create a directory to which writes are preventable" +skip_bad_access = unittest.skipUnless(_access_preventable, _access_msg) + + +def constant_unicode_cache(): + c = "abcd" + return hash(c), c + + +def check_constant_unicode_cache(): + pyfunc = constant_unicode_cache + cfunc = njit(cache=True)(pyfunc) + exp_hv, exp_str = pyfunc() + got_hv, got_str = cfunc() + assert exp_hv == got_hv + assert exp_str == got_str + + +def dict_cache(): + return {'a': 1, 'b': 2} + + +def check_dict_cache(): + pyfunc = dict_cache + cfunc = njit(cache=True)(pyfunc) + exp = pyfunc() + got = cfunc() + assert exp == got + + +def generator_cache(): + for v in (1, 2, 3): + yield v + + +def check_generator_cache(): + pyfunc = generator_cache + cfunc = njit(cache=True)(pyfunc) + exp = list(pyfunc()) + got = list(cfunc()) + assert exp == got + + +class TestCaching(SerialMixin, TestCase): + def run_test(self, func): + func() + res = run_in_new_process_caching(func) + self.assertEqual(res['exitcode'], 0) + + def test_constant_unicode_cache(self): + self.run_test(check_constant_unicode_cache) + + def test_dict_cache(self): + self.run_test(check_dict_cache) + + def test_generator_cache(self): + self.run_test(check_generator_cache) + + def test_omitted(self): + + # Test in a new directory + cache_dir = temp_directory(self.__class__.__name__) + ctx = multiprocessing.get_context() + result_queue = ctx.Queue() + proc = ctx.Process( + target=omitted_child_test_wrapper, + args=(result_queue, cache_dir, False), + ) + proc.start() + proc.join() + success, output = result_queue.get() + + # Ensure the child process is completed before checking its output + if not success: + self.fail(output) + + self.assertEqual( + output, + 1000, + "Omitted function returned an incorrect output" + ) + + proc = ctx.Process( + target=omitted_child_test_wrapper, + args=(result_queue, cache_dir, True) + ) + proc.start() + proc.join() + success, output = result_queue.get() + + # Ensure the child process is completed before checking its output + if not success: + self.fail(output) + + self.assertEqual( + output, + 1000, + "Omitted function returned an incorrect output" + ) + + +def omitted_child_test_wrapper(result_queue, cache_dir, second_call): + with override_config("CACHE_DIR", cache_dir): + @njit(cache=True) + def test(num=1000): + return num + + try: + output = test() + # If we have a second call, we should have a cache hit. + # Otherwise, we expect a cache miss. + if second_call: + assert test._cache_hits[test.signatures[0]] == 1, \ + "Cache did not hit as expected" + assert test._cache_misses[test.signatures[0]] == 0, \ + "Cache has an unexpected miss" + else: + assert test._cache_misses[test.signatures[0]] == 1, \ + "Cache did not miss as expected" + assert test._cache_hits[test.signatures[0]] == 0, \ + "Cache has an unexpected hit" + success = True + # Catch anything raised so it can be propagated + except: # noqa: E722 + output = traceback.format_exc() + success = False + result_queue.put((success, output)) + + +class BaseCacheTest(TestCase): + # The source file that will be copied + usecases_file = None + # Make sure this doesn't conflict with another module + modname = None + + def setUp(self): + self.tempdir = temp_directory('test_cache') + sys.path.insert(0, self.tempdir) + self.modfile = os.path.join(self.tempdir, self.modname + ".py") + self.cache_dir = os.path.join(self.tempdir, "__pycache__") + shutil.copy(self.usecases_file, self.modfile) + os.chmod(self.modfile, stat.S_IREAD | stat.S_IWRITE) + self.maxDiff = None + + def tearDown(self): + sys.modules.pop(self.modname, None) + sys.path.remove(self.tempdir) + + def import_module(self): + # Import a fresh version of the test module. All jitted functions + # in the test module will start anew and load overloads from + # the on-disk cache if possible. + old = sys.modules.pop(self.modname, None) + if old is not None: + # Make sure cached bytecode is removed + cached = [old.__cached__] + for fn in cached: + try: + os.unlink(fn) + except FileNotFoundError: + pass + mod = import_dynamic(self.modname) + self.assertEqual(mod.__file__.rstrip('co'), self.modfile) + return mod + + def cache_contents(self): + try: + return [fn for fn in os.listdir(self.cache_dir) + if not fn.endswith(('.pyc', ".pyo"))] + except FileNotFoundError: + return [] + + def get_cache_mtimes(self): + return dict((fn, os.path.getmtime(os.path.join(self.cache_dir, fn))) + for fn in sorted(self.cache_contents())) + + def check_pycache(self, n): + c = self.cache_contents() + self.assertEqual(len(c), n, c) + + def dummy_test(self): + pass + + +class DispatcherCacheUsecasesTest(BaseCacheTest): + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "cache_usecases.py") + modname = "dispatcher_caching_test_fodder" + + def run_in_separate_process(self, *, envvars=None): + # Cached functions can be run from a distinct process. + # Also stresses issue #1603: uncached function calling cached function + # shouldn't fail compiling. + if envvars is None: + envvars = {} + code = """if 1: + import sys + + sys.path.insert(0, %(tempdir)r) + mod = __import__(%(modname)r) + mod.self_test() + """ % dict(tempdir=self.tempdir, modname=self.modname) + + subp_env = os.environ.copy() + subp_env.update(envvars) + popen = subprocess.Popen([sys.executable, "-c", code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=subp_env) + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError( + "process failed with code %s: \n" + "stdout follows\n%s\n" + "stderr follows\n%s\n" + % (popen.returncode, out.decode(), err.decode()), + ) + + def check_hits(self, func, hits, misses=None): + st = func.stats + self.assertEqual(sum(st.cache_hits.values()), hits, st.cache_hits) + if misses is not None: + self.assertEqual(sum(st.cache_misses.values()), misses, + st.cache_misses) + + +class TestCache(DispatcherCacheUsecasesTest): + + def test_caching(self): + self.check_pycache(0) + mod = self.import_module() + self.check_pycache(0) + + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 6) + self.check_pycache(2) # 1 index, 1 data + self.assertPreciseEqual(f(2.5, 3), 6.5) + self.check_pycache(3) # 1 index, 2 data + self.check_hits(f, 0, 2) + + f = mod.add_objmode_usecase + self.assertPreciseEqual(f(2, 3), 6) + self.check_pycache(5) # 2 index, 3 data + self.assertPreciseEqual(f(2.5, 3), 6.5) + self.check_pycache(6) # 2 index, 4 data + self.check_hits(f, 0, 2) + + f = mod.record_return + rec = f(mod.aligned_arr, 1) + self.assertPreciseEqual(tuple(rec), (2, 43.5)) + rec = f(mod.packed_arr, 1) + self.assertPreciseEqual(tuple(rec), (2, 43.5)) + self.check_pycache(9) # 3 index, 6 data + self.check_hits(f, 0, 2) + + # Check the code runs ok from another process + self.run_in_separate_process() + + def test_caching_nrt_pruned(self): + self.check_pycache(0) + mod = self.import_module() + self.check_pycache(0) + + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 6) + self.check_pycache(2) # 1 index, 1 data + # NRT pruning may affect cache + self.assertPreciseEqual(f(2, np.arange(3)), 2 + np.arange(3) + 1) + self.check_pycache(3) # 1 index, 2 data + self.check_hits(f, 0, 2) + + def test_inner_then_outer(self): + # Caching inner then outer function is ok + mod = self.import_module() + self.assertPreciseEqual(mod.inner(3, 2), 6) + self.check_pycache(2) # 1 index, 1 data + # Uncached outer function shouldn't fail (issue #1603) + f = mod.outer_uncached + self.assertPreciseEqual(f(3, 2), 2) + self.check_pycache(2) # 1 index, 1 data + mod = self.import_module() + f = mod.outer_uncached + self.assertPreciseEqual(f(3, 2), 2) + self.check_pycache(2) # 1 index, 1 data + # Cached outer will create new cache entries + f = mod.outer + self.assertPreciseEqual(f(3, 2), 2) + self.check_pycache(4) # 2 index, 2 data + self.assertPreciseEqual(f(3.5, 2), 2.5) + self.check_pycache(6) # 2 index, 4 data + + def test_outer_then_inner(self): + # Caching outer then inner function is ok + mod = self.import_module() + self.assertPreciseEqual(mod.outer(3, 2), 2) + self.check_pycache(4) # 2 index, 2 data + self.assertPreciseEqual(mod.outer_uncached(3, 2), 2) + self.check_pycache(4) # same + mod = self.import_module() + f = mod.inner + self.assertPreciseEqual(f(3, 2), 6) + self.check_pycache(4) # same + self.assertPreciseEqual(f(3.5, 2), 6.5) + self.check_pycache(5) # 2 index, 3 data + + def test_no_caching(self): + mod = self.import_module() + + f = mod.add_nocache_usecase + self.assertPreciseEqual(f(2, 3), 6) + self.check_pycache(0) + + def test_looplifted(self): + # Loop-lifted functions can't be cached and raise a warning + mod = self.import_module() + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaWarning) + + f = mod.looplifted + self.assertPreciseEqual(f(4), 6) + self.check_pycache(0) + + self.assertEqual(len(w), 1) + self.assertIn('Cannot cache compiled function "looplifted" ' + 'as it uses lifted code', str(w[0].message)) + + def test_big_array(self): + # Code references big array globals cannot be cached + mod = self.import_module() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaWarning) + + f = mod.use_big_array + np.testing.assert_equal(f(), mod.biggie) + self.check_pycache(0) + + self.assertEqual(len(w), 1) + self.assertIn('Cannot cache compiled function "use_big_array" ' + 'as it uses dynamic globals', str(w[0].message)) + + def test_ctypes(self): + # Functions using a ctypes pointer can't be cached and raise + # a warning. + mod = self.import_module() + + for f in [mod.use_c_sin, mod.use_c_sin_nest1, mod.use_c_sin_nest2]: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaWarning) + + self.assertPreciseEqual(f(0.0), 0.0) + self.check_pycache(0) + + self.assertEqual(len(w), 1) + self.assertIn( + 'Cannot cache compiled function "{}"'.format(f.__name__), + str(w[0].message), + ) + + def test_closure(self): + mod = self.import_module() + + with warnings.catch_warnings(): + warnings.simplefilter('error', NumbaWarning) + + f = mod.closure1 + self.assertPreciseEqual(f(3), 6) # 3 + 3 = 6 + f = mod.closure2 + self.assertPreciseEqual(f(3), 8) # 3 + 5 = 8 + f = mod.closure3 + self.assertPreciseEqual(f(3), 10) # 3 + 7 = 10 + f = mod.closure4 + self.assertPreciseEqual(f(3), 12) # 3 + 9 = 12 + self.check_pycache(5) # 1 nbi, 4 nbc + + def test_first_class_function(self): + mod = self.import_module() + f = mod.first_class_function_usecase + self.assertEqual(f(mod.first_class_function_mul, 1), 1) + self.assertEqual(f(mod.first_class_function_mul, 10), 100) + self.assertEqual(f(mod.first_class_function_add, 1), 2) + self.assertEqual(f(mod.first_class_function_add, 10), 20) + # 1 + 1 + 1 nbi, 1 + 1 + 2 nbc - a separate cache for each call to `f` + # with a different callback. + self.check_pycache(7) + + def test_cache_reuse(self): + mod = self.import_module() + mod.add_usecase(2, 3) + mod.add_usecase(2.5, 3.5) + mod.add_objmode_usecase(2, 3) + mod.outer_uncached(2, 3) + mod.outer(2, 3) + mod.record_return(mod.packed_arr, 0) + mod.record_return(mod.aligned_arr, 1) + mtimes = self.get_cache_mtimes() + # Two signatures compiled + self.check_hits(mod.add_usecase, 0, 2) + + mod2 = self.import_module() + self.assertIsNot(mod, mod2) + f = mod2.add_usecase + f(2, 3) + self.check_hits(f, 1, 0) + f(2.5, 3.5) + self.check_hits(f, 2, 0) + f = mod2.add_objmode_usecase + f(2, 3) + self.check_hits(f, 1, 0) + + # The files haven't changed + self.assertEqual(self.get_cache_mtimes(), mtimes) + + self.run_in_separate_process() + self.assertEqual(self.get_cache_mtimes(), mtimes) + + def test_cache_invalidate(self): + mod = self.import_module() + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 6) + + # This should change the functions' results + with open(self.modfile, "a") as f: + f.write("\nZ = 10\n") + + mod = self.import_module() + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 15) + f = mod.add_objmode_usecase + self.assertPreciseEqual(f(2, 3), 15) + + def test_recompile(self): + # Explicit call to recompile() should overwrite the cache + mod = self.import_module() + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 6) + + mod = self.import_module() + f = mod.add_usecase + mod.Z = 10 + self.assertPreciseEqual(f(2, 3), 6) + f.recompile() + self.assertPreciseEqual(f(2, 3), 15) + + # Freshly recompiled version is re-used from other imports + mod = self.import_module() + f = mod.add_usecase + self.assertPreciseEqual(f(2, 3), 15) + + def test_same_names(self): + # Function with the same names should still disambiguate + mod = self.import_module() + f = mod.renamed_function1 + self.assertPreciseEqual(f(2), 4) + f = mod.renamed_function2 + self.assertPreciseEqual(f(2), 8) + + def test_frozen(self): + from .dummy_module import function + old_code = function.__code__ + code_obj = compile('pass', 'tests/dummy_module.py', 'exec') + try: + function.__code__ = code_obj + + source = inspect.getfile(function) + # doesn't return anything, since it cannot find the module + # fails unless the executable is frozen + locator = UserWideCacheLocator.from_function(function, source) + self.assertIsNone(locator) + + sys.frozen = True + # returns a cache locator object, only works when the executable + # is frozen + locator = UserWideCacheLocator.from_function(function, source) + self.assertIsInstance(locator, UserWideCacheLocator) + + finally: + function.__code__ = old_code + del sys.frozen + + def _test_pycache_fallback(self): + """ + With a disabled __pycache__, test there is a working fallback + (e.g. on the user-wide cache dir) + """ + mod = self.import_module() + f = mod.add_usecase + # Remove this function's cache files at the end, to avoid accumulation + # across test calls. + self.addCleanup(shutil.rmtree, f.stats.cache_path, ignore_errors=True) + + self.assertPreciseEqual(f(2, 3), 6) + # It's a cache miss since the file was copied to a new temp location + self.check_hits(f, 0, 1) + + # Test re-use + mod2 = self.import_module() + f = mod2.add_usecase + self.assertPreciseEqual(f(2, 3), 6) + self.check_hits(f, 1, 0) + + # The __pycache__ is empty (otherwise the test's preconditions + # wouldn't be met) + self.check_pycache(0) + + @skip_bad_access + @unittest.skipIf(os.name == "nt", + "cannot easily make a directory read-only on Windows") + def test_non_creatable_pycache(self): + # Make it impossible to create the __pycache__ directory + old_perms = os.stat(self.tempdir).st_mode + os.chmod(self.tempdir, 0o500) + self.addCleanup(os.chmod, self.tempdir, old_perms) + + self._test_pycache_fallback() + + @skip_bad_access + @unittest.skipIf(os.name == "nt", + "cannot easily make a directory read-only on Windows") + def test_non_writable_pycache(self): + # Make it impossible to write to the __pycache__ directory + pycache = os.path.join(self.tempdir, '__pycache__') + os.mkdir(pycache) + old_perms = os.stat(pycache).st_mode + os.chmod(pycache, 0o500) + self.addCleanup(os.chmod, pycache, old_perms) + + self._test_pycache_fallback() + + def test_ipython(self): + # Test caching in an IPython session + base_cmd = [sys.executable, '-m', 'IPython'] + base_cmd += ['--quiet', '--quick', '--no-banner', '--colors=NoColor'] + try: + ver = subprocess.check_output(base_cmd + ['--version']) + except subprocess.CalledProcessError as e: + self.skipTest("ipython not available: return code %d" + % e.returncode) + ver = ver.strip().decode() + # Create test input + inputfn = os.path.join(self.tempdir, "ipython_cache_usecase.txt") + with open(inputfn, "w") as f: + f.write(r""" + import os + import sys + + from numba import jit + + # IPython 5 does not support multiline input if stdin isn't + # a tty (https://github.com/ipython/ipython/issues/9752) + f = jit(cache=True)(lambda: 42) + + res = f() + # IPython writes on stdout, so use stderr instead + sys.stderr.write(u"cache hits = %d\n" % f.stats.cache_hits[()]) + + # IPython hijacks sys.exit(), bypass it + sys.stdout.flush() + sys.stderr.flush() + os._exit(res) + """) + + def execute_with_input(): + # Feed the test input as stdin, to execute it in REPL context + with open(inputfn, "rb") as stdin: + p = subprocess.Popen(base_cmd, stdin=stdin, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + out, err = p.communicate() + if p.returncode != 42: + self.fail("unexpected return code %d\n" + "-- stdout:\n%s\n" + "-- stderr:\n%s\n" + % (p.returncode, out, err)) + return err + + execute_with_input() + # Run a second time and check caching + err = execute_with_input() + self.assertIn("cache hits = 1", err.strip()) + + @unittest.skipIf((ipykernel is None) or (ipykernel.version_info[0] < 6), + "requires ipykernel >= 6") + def test_ipykernel(self): + # Test caching in an IPython session using ipykernel + + base_cmd = [sys.executable, '-m', 'IPython'] + base_cmd += ['--quiet', '--quick', '--no-banner', '--colors=NoColor'] + try: + ver = subprocess.check_output(base_cmd + ['--version']) + except subprocess.CalledProcessError as e: + self.skipTest("ipython not available: return code %d" + % e.returncode) + ver = ver.strip().decode() + # Create test input + from ipykernel import compiler + inputfn = compiler.get_tmp_directory() + with open(inputfn, "w") as f: + f.write(r""" + import os + import sys + + from numba import jit + + # IPython 5 does not support multiline input if stdin isn't + # a tty (https://github.com/ipython/ipython/issues/9752) + f = jit(cache=True)(lambda: 42) + + res = f() + # IPython writes on stdout, so use stderr instead + sys.stderr.write(u"cache hits = %d\n" % f.stats.cache_hits[()]) + + # IPython hijacks sys.exit(), bypass it + sys.stdout.flush() + sys.stderr.flush() + os._exit(res) + """) + + def execute_with_input(): + # Feed the test input as stdin, to execute it in REPL context + with open(inputfn, "rb") as stdin: + p = subprocess.Popen(base_cmd, stdin=stdin, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True) + out, err = p.communicate() + if p.returncode != 42: + self.fail("unexpected return code %d\n" + "-- stdout:\n%s\n" + "-- stderr:\n%s\n" + % (p.returncode, out, err)) + return err + + execute_with_input() + # Run a second time and check caching + err = execute_with_input() + self.assertIn("cache hits = 1", err.strip()) + + +class TestCacheZip(DispatcherCacheUsecasesTest): + + def setUp(self): + super().setUp() + + # Create a simple Python module to be zipped + mod_content = """ +from numba import jit + +@jit(cache=True) +def add(x, y): + return x + y +""" + mod_filename = "test_module.py" + zip_filename = "test_archive.zip" + + # Create a zip file containing the module + zip_path = os.path.join(self.tempdir, zip_filename) + with zipfile.ZipFile(zip_path, "w") as zf: + zf.writestr(mod_filename, mod_content) + + # Add the zip file to sys.path + sys.path.insert(0, zip_path) + self.modname = "test_module" + + def tearDown(self): + # Clean up: remove the zip file from sys.path + sys.path.pop(0) + # Remove the module from sys.modules to clean up + sys.modules.pop("test_module", None) + + def test_zip_caching(self): + # (note that `self.import_module()` fails because its checks are + # incompatible + # with the zip file, so we just use normal imports here) + + # First import and call + import test_module # type: ignore + + result1 = test_module.add(2, 3) + self.assertEqual(result1, 5) + self.check_hits(test_module.add, 0, 1) + + # Record the initial cache hits + self.check_hits(test_module.add, 0) + + # Remove the module and reimport + del sys.modules["test_module"] + importlib.invalidate_caches() + import test_module # type: ignore + + # Second call: should use the cache + result2 = test_module.add(2, 3) + self.assertEqual(result2, 5) + + # Check if the cache was hit + self.check_hits(test_module.add, 1) + + +class TestCacheZipLib(DispatcherCacheUsecasesTest): + """ + ZipCache tests that don't require the setup/teardown from `TestCacheZip` + """ + def test_zip_locator_creation(self): + + def mock_func(): + pass + + zip_path = "/path/to/archive.zip/module.py" + + locator = ZipCacheLocator.from_function(mock_func, zip_path) + self.assertIsNotNone(locator) + self.assertEqual(locator._zip_path, str(Path("/path/to/archive.zip"))) + self.assertEqual(locator._internal_path, "module.py") + + def test_zip_locator_non_zip_path(self): + + def mock_func(): + pass + + non_zip_path = "/path/to/module.py" + + locator = ZipCacheLocator.from_function(mock_func, non_zip_path) + self.assertIsNone(locator) + + +@skip_parfors_unsupported +class TestSequentialParForsCache(DispatcherCacheUsecasesTest): + def setUp(self): + super(TestSequentialParForsCache, self).setUp() + # Turn on sequential parfor lowering + parfor.sequential_parfor_lowering = True + + def tearDown(self): + super(TestSequentialParForsCache, self).tearDown() + # Turn off sequential parfor lowering + parfor.sequential_parfor_lowering = False + + def test_caching(self): + mod = self.import_module() + self.check_pycache(0) + f = mod.parfor_usecase + ary = np.ones(10) + self.assertPreciseEqual(f(ary), ary * ary + ary) + dynamic_globals = [cres.library.has_dynamic_globals + for cres in f.overloads.values()] + self.assertEqual(dynamic_globals, [False]) + self.check_pycache(2) # 1 index, 1 data + + +class TestCacheWithCpuSetting(DispatcherCacheUsecasesTest): + # Disable parallel testing due to envvars modification + _numba_parallel_test_ = False + + def check_later_mtimes(self, mtimes_old): + match_count = 0 + for k, v in self.get_cache_mtimes().items(): + if k in mtimes_old: + self.assertGreaterEqual(v, mtimes_old[k]) + match_count += 1 + self.assertGreater(match_count, 0, + msg='nothing to compare') + + @unittest.skipIf(ll.get_host_cpu_name() == "generic", + "LLVM detected 'generic' CPU") + def test_user_set_cpu_name(self): + self.check_pycache(0) + + # Run initial test without NUMBA_CPU_NAME to ensure host CPU + self.run_in_separate_process( + envvars={'NUMBA_CPU_NAME': ll.get_host_cpu_name(), + 'NUMBA_CPU_FEATURES': ''} + ) + mtimes = self.get_cache_mtimes() + cache_size = len(self.cache_contents()) + + # Change CPU name to generic + self.run_in_separate_process(envvars={ + 'NUMBA_CPU_NAME': 'generic', + 'NUMBA_CPU_FEATURES': '', + }) + + self.check_later_mtimes(mtimes) + self.assertGreater(len(self.cache_contents()), cache_size) + # Check cache index + mod = self.import_module() + cache = mod.add_usecase._cache + cache_file = cache._cache_file + cache_index = cache_file._load_index() + self.assertEqual(len(cache_index), 2) + [key_a, key_b] = cache_index.keys() + if key_a[1][1] == 'generic': + key_generic, key_host = key_a, key_b + else: + key_host, key_generic = key_a, key_b + self.assertEqual(key_host[1][1], ll.get_host_cpu_name()) + self.assertEqual(key_host[1][2], '') + self.assertEqual(key_generic[1][1], 'generic') + self.assertEqual(key_generic[1][2], '') + + def test_user_set_cpu_features(self): + self.check_pycache(0) + + cpu_codegen = cpu_target.target_context.codegen() + + system_features = codegen.get_host_cpu_features() + + # Run initial testing with default CPU features + self.run_in_separate_process( + envvars={'NUMBA_CPU_FEATURES': system_features} + ) + cache_size = len(self.cache_contents()) + + mtimes = self.get_cache_mtimes() + # Change CPU feature + my_cpu_features = '-sse;-avx' + + self.assertNotEqual(system_features, my_cpu_features) + self.run_in_separate_process( + envvars={'NUMBA_CPU_FEATURES': my_cpu_features}, + ) + self.check_later_mtimes(mtimes) + self.assertGreater(len(self.cache_contents()), cache_size) + # Check cache index + mod = self.import_module() + cache = mod.add_usecase._cache + cache_file = cache._cache_file + cache_index = cache_file._load_index() + self.assertEqual(len(cache_index), 2) + [key_a, key_b] = cache_index.keys() + + if key_a[1][2] == my_cpu_features: + key_modified, key_host = key_a, key_b + else: + key_host, key_modified = key_a, key_b + + self.assertEqual(key_host[1][1], cpu_codegen._get_host_cpu_name()) + self.assertEqual(key_host[1][2], system_features) + self.assertEqual(key_modified[1][1], cpu_codegen._get_host_cpu_name()) + self.assertEqual(key_modified[1][2], my_cpu_features) + + +class TestMultiprocessCache(BaseCacheTest): + + # Nested multiprocessing.Pool raises AssertionError: + # "daemonic processes are not allowed to have children" + _numba_parallel_test_ = False + + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "cache_usecases.py") + modname = "dispatcher_caching_test_fodder" + + def test_multiprocessing(self): + # Check caching works from multiple processes at once (#2028) + mod = self.import_module() + # Calling a pure Python caller of the JIT-compiled function is + # necessary to reproduce the issue. + f = mod.simple_usecase_caller + n = 3 + try: + ctx = multiprocessing.get_context('spawn') + except AttributeError: + ctx = multiprocessing + pool = ctx.Pool(n) + try: + res = sum(pool.imap(f, range(n))) + finally: + pool.close() + self.assertEqual(res, n * (n - 1) // 2) + + +@skip_if_typeguard +class TestCacheFileCollision(unittest.TestCase): + _numba_parallel_test_ = False + + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "cache_usecases.py") + modname = "caching_file_loc_fodder" + source_text_1 = """ +from numba import njit +@njit(cache=True) +def bar(): + return 123 +""" + source_text_2 = """ +from numba import njit +@njit(cache=True) +def bar(): + return 321 +""" + + def setUp(self): + self.tempdir = temp_directory('test_cache_file_loc') + sys.path.insert(0, self.tempdir) + self.modname = 'module_name_that_is_unlikely' + self.assertNotIn(self.modname, sys.modules) + self.modname_bar1 = self.modname + self.modname_bar2 = '.'.join([self.modname, 'foo']) + foomod = os.path.join(self.tempdir, self.modname) + os.mkdir(foomod) + with open(os.path.join(foomod, '__init__.py'), 'w') as fout: + print(self.source_text_1, file=fout) + with open(os.path.join(foomod, 'foo.py'), 'w') as fout: + print(self.source_text_2, file=fout) + + def tearDown(self): + sys.modules.pop(self.modname_bar1, None) + sys.modules.pop(self.modname_bar2, None) + sys.path.remove(self.tempdir) + + def import_bar1(self): + return import_dynamic(self.modname_bar1).bar + + def import_bar2(self): + return import_dynamic(self.modname_bar2).bar + + def test_file_location(self): + bar1 = self.import_bar1() + bar2 = self.import_bar2() + # Check that the cache file is named correctly + idxname1 = bar1._cache._cache_file._index_name + idxname2 = bar2._cache._cache_file._index_name + self.assertNotEqual(idxname1, idxname2) + self.assertTrue(idxname1.startswith("__init__.bar-3.py")) + self.assertTrue(idxname2.startswith("foo.bar-3.py")) + + @unittest.skipUnless(hasattr(multiprocessing, 'get_context'), + 'Test requires multiprocessing.get_context') + def test_no_collision(self): + bar1 = self.import_bar1() + bar2 = self.import_bar2() + with capture_cache_log() as buf: + res1 = bar1() + cachelog = buf.getvalue() + # bar1 should save new index and data + self.assertEqual(cachelog.count('index saved'), 1) + self.assertEqual(cachelog.count('data saved'), 1) + self.assertEqual(cachelog.count('index loaded'), 0) + self.assertEqual(cachelog.count('data loaded'), 0) + with capture_cache_log() as buf: + res2 = bar2() + cachelog = buf.getvalue() + # bar2 should save new index and data + self.assertEqual(cachelog.count('index saved'), 1) + self.assertEqual(cachelog.count('data saved'), 1) + self.assertEqual(cachelog.count('index loaded'), 0) + self.assertEqual(cachelog.count('data loaded'), 0) + self.assertNotEqual(res1, res2) + + try: + # Make sure we can spawn new process without inheriting + # the parent context. + mp = multiprocessing.get_context('spawn') + except ValueError: + print("missing spawn context") + + q = mp.Queue() + # Start new process that calls `cache_file_collision_tester` + proc = mp.Process(target=cache_file_collision_tester, + args=(q, self.tempdir, + self.modname_bar1, + self.modname_bar2)) + proc.start() + # Get results from the process + log1 = q.get() + got1 = q.get() + log2 = q.get() + got2 = q.get() + proc.join() + + # The remote execution result of bar1() and bar2() should match + # the one executed locally. + self.assertEqual(got1, res1) + self.assertEqual(got2, res2) + + # The remote should have loaded bar1 from cache + self.assertEqual(log1.count('index saved'), 0) + self.assertEqual(log1.count('data saved'), 0) + self.assertEqual(log1.count('index loaded'), 1) + self.assertEqual(log1.count('data loaded'), 1) + + # The remote should have loaded bar2 from cache + self.assertEqual(log2.count('index saved'), 0) + self.assertEqual(log2.count('data saved'), 0) + self.assertEqual(log2.count('index loaded'), 1) + self.assertEqual(log2.count('data loaded'), 1) + + +def cache_file_collision_tester(q, tempdir, modname_bar1, modname_bar2): + sys.path.insert(0, tempdir) + bar1 = import_dynamic(modname_bar1).bar + bar2 = import_dynamic(modname_bar2).bar + with capture_cache_log() as buf: + r1 = bar1() + q.put(buf.getvalue()) + q.put(r1) + with capture_cache_log() as buf: + r2 = bar2() + q.put(buf.getvalue()) + q.put(r2) + + +class TestCacheMultipleFilesWithSignature(unittest.TestCase): + # Regression test for https://github.com/numba/numba/issues/3658 + + _numba_parallel_test_ = False + + source_text_file1 = """ +from file2 import function2 +""" + source_text_file2 = """ +from numba import njit + +@njit('float64(float64)', cache=True) +def function1(x): + return x + +@njit('float64(float64)', cache=True) +def function2(x): + return x +""" + + def setUp(self): + self.tempdir = temp_directory('test_cache_file_loc') + + self.file1 = os.path.join(self.tempdir, 'file1.py') + with open(self.file1, 'w') as fout: + print(self.source_text_file1, file=fout) + + self.file2 = os.path.join(self.tempdir, 'file2.py') + with open(self.file2, 'w') as fout: + print(self.source_text_file2, file=fout) + + def tearDown(self): + shutil.rmtree(self.tempdir) + + def test_caching_mutliple_files_with_signature(self): + # Execute file1.py + popen = subprocess.Popen([sys.executable, self.file1], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + out, err = popen.communicate() + msg = f"stdout:\n{out.decode()}\n\nstderr:\n{err.decode()}" + self.assertEqual(popen.returncode, 0, msg=msg) + + # Execute file2.py + popen = subprocess.Popen([sys.executable, self.file2], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + out, err = popen.communicate() + msg = f"stdout:\n{out.decode()}\n\nstderr:\n{err.decode()}" + self.assertEqual(popen.returncode, 0, msg) + + +class TestCFuncCache(BaseCacheTest): + + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "cfunc_cache_usecases.py") + modname = "cfunc_caching_test_fodder" + + def run_in_separate_process(self): + # Cached functions can be run from a distinct process. + code = """if 1: + import sys + + sys.path.insert(0, %(tempdir)r) + mod = __import__(%(modname)r) + mod.self_test() + + f = mod.add_usecase + assert f.cache_hits == 1 + f = mod.outer + assert f.cache_hits == 1 + f = mod.div_usecase + assert f.cache_hits == 1 + """ % dict(tempdir=self.tempdir, modname=self.modname) + + popen = subprocess.Popen([sys.executable, "-c", code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError(f"process failed with code {popen.returncode}:" + f"stderr follows\n{err.decode()}\n") + + def check_module(self, mod): + mod.self_test() + + def test_caching(self): + self.check_pycache(0) + mod = self.import_module() + self.check_pycache(6) # 3 index, 3 data + + self.assertEqual(mod.add_usecase.cache_hits, 0) + self.assertEqual(mod.outer.cache_hits, 0) + self.assertEqual(mod.add_nocache_usecase.cache_hits, 0) + self.assertEqual(mod.div_usecase.cache_hits, 0) + self.check_module(mod) + + # Reload module to hit the cache + mod = self.import_module() + self.check_pycache(6) # 3 index, 3 data + + self.assertEqual(mod.add_usecase.cache_hits, 1) + self.assertEqual(mod.outer.cache_hits, 1) + self.assertEqual(mod.add_nocache_usecase.cache_hits, 0) + self.assertEqual(mod.div_usecase.cache_hits, 1) + self.check_module(mod) + + self.run_in_separate_process() + + +class TestLocator(InTreeCacheLocator): + pass + + +class TestCacheLocatorEnvironmentIntegration(TestCase): + """Integration tests for environment variable functionality.""" + + def test_locators_env_override_unknown(self): + def mock_func(): + return 42 + + with override_env_config( + "NUMBA_CACHE_LOCATOR_CLASSES", + "foo,bar", + ): + with self.assertRaises(RuntimeError): + FunctionCache(mock_func) + + def test_locators_env_override_single(self): + def mock_func(): + return 42 + + with override_env_config( + "NUMBA_CACHE_LOCATOR_CLASSES", + "InTreeCacheLocatorFsAgnostic", + ): + cache = FunctionCache(mock_func) + expectedLocator = InTreeCacheLocatorFsAgnostic + self.assertIsInstance(cache._impl.locator, + expectedLocator) + + def test_locators_env_override_custom(self): + def mock_func(): + return 42 + + with override_env_config( + "NUMBA_CACHE_LOCATOR_CLASSES", + f"{__name__}.TestLocator", + ): + cache = FunctionCache(mock_func) + expectedLocator = TestLocator + self.assertIsInstance(cache._impl.locator, + expectedLocator) + + def test_locators_env_override_list(self): + def mock_func(): + return 42 + + locatorClasses = ("InTreeCacheLocatorFsAgnostic,InTreeCacheLocator," + "IPythonCacheLocator,UserWideCacheLocator") + expectedLocator = InTreeCacheLocatorFsAgnostic + + with override_env_config( + "NUMBA_CACHE_LOCATOR_CLASSES", + locatorClasses, + ): + cache = FunctionCache(mock_func) + self.assertIsInstance(cache._impl.locator, expectedLocator) + + def test_default_locators(self): + def mock_func(): + return 42 + + cache = FunctionCache(mock_func) + expectedLocator = InTreeCacheLocator + self.assertIsInstance(cache._impl.locator, expectedLocator) + + +class TestInTreeCacheLocatorFsAgnostic(TestCase): + """Test _InTreeCacheLocatorFsAgnostic class functionality.""" + + def test_source_stamp_precision(self): + """Test that FsAgnostic locator floors timestamp to seconds.""" + from .dummy_module import function + + source = inspect.getfile(function) + + # Create regular and FsAgnostic locators + regular_locator = InTreeCacheLocator.from_function(function, source) + fs_agnostic_locator = InTreeCacheLocatorFsAgnostic.from_function( + function, source + ) + + # Both should be valid locators + self.assertIsNotNone(regular_locator) + self.assertIsNotNone(fs_agnostic_locator) + + # Get source stamps + regular_stamp = regular_locator.get_source_stamp() + fs_agnostic_stamp = fs_agnostic_locator.get_source_stamp() + + # Verify structure: (timestamp, size) + self.assertEqual(len(regular_stamp), 2) + self.assertEqual(len(fs_agnostic_stamp), 2) + + # The second element (size) should be the same + self.assertEqual(regular_stamp[1], fs_agnostic_stamp[1]) + + # The first element (timestamp) in fs_agnostic should be floored + self.assertEqual(fs_agnostic_stamp[0], floor(regular_stamp[0])) + + # Verify that fs_agnostic timestamp is always <= regular timestamp + self.assertLessEqual(fs_agnostic_stamp[0], regular_stamp[0]) + + def test_timestamp_precision_on_fs(self): + """Test FsAgnostic timestamp handling using filesystem mtime.""" + + from .dummy_module import function + + source = inspect.getfile(function) + + # Test with a file that has a precise timestamp + fs_agnostic_locator = InTreeCacheLocatorFsAgnostic.from_function( + function, source + ) + + # Get file stat + stat_result = os.stat(source) + original_mtime = stat_result.st_mtime + + # Get stamp from locator + stamp = fs_agnostic_locator.get_source_stamp() + + # Verify that the timestamp is floored + expected_timestamp = floor(original_mtime) + self.assertEqual(stamp[0], expected_timestamp) + + # Verify size is correct + self.assertEqual(stamp[1], stat_result.st_size) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cffi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cffi.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab784bf906c2d1bb023bda30f418f2b1d35eb20 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cffi.py @@ -0,0 +1,189 @@ +import array +import numpy as np + +from numba import jit, njit +import numba.core.typing.cffi_utils as cffi_support +from numba.core import types, errors +from numba.tests.support import TestCase, skip_unless_cffi + + +import numba.tests.cffi_usecases as mod +import unittest + + +enable_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +@skip_unless_cffi +class TestCFFI(TestCase): + + # Need to run the tests serially because of race conditions in + # cffi's OOL mode. + _numba_parallel_test_ = False + + def setUp(self): + mod.init() + mod.init_ool() + + def test_type_map(self): + signature = cffi_support.map_type(mod.ffi.typeof(mod.cffi_sin)) + self.assertEqual(len(signature.args), 1) + self.assertEqual(signature.args[0], types.double) + + def _test_function(self, pyfunc, flags=enable_pyobj_flags): + cfunc = jit((types.double,), **flags)(pyfunc) + + for x in [-1.2, -1, 0, 0.1, 3.14]: + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + def test_sin_function(self): + self._test_function(mod.use_cffi_sin) + + def test_bool_function_ool(self): + pyfunc = mod.use_cffi_boolean_true + cfunc = njit((),)(pyfunc) + self.assertEqual(pyfunc(), True) + self.assertEqual(cfunc(), True) + + def test_sin_function_npm(self): + self._test_function(mod.use_cffi_sin, flags=no_pyobj_flags) + + def test_sin_function_ool(self, flags=enable_pyobj_flags): + self._test_function(mod.use_cffi_sin_ool) + + def test_sin_function_npm_ool(self): + self._test_function(mod.use_cffi_sin_ool, flags=no_pyobj_flags) + + def test_two_funcs(self): + # Check that two constant functions don't get mixed up. + self._test_function(mod.use_two_funcs) + + def test_two_funcs_ool(self): + self._test_function(mod.use_two_funcs_ool) + + def test_function_pointer(self): + pyfunc = mod.use_func_pointer + cfunc = jit(nopython=True)(pyfunc) + for (fa, fb, x) in [ + (mod.cffi_sin, mod.cffi_cos, 1.0), + (mod.cffi_sin, mod.cffi_cos, -1.0), + (mod.cffi_cos, mod.cffi_sin, 1.0), + (mod.cffi_cos, mod.cffi_sin, -1.0), + (mod.cffi_sin_ool, mod.cffi_cos_ool, 1.0), + (mod.cffi_sin_ool, mod.cffi_cos_ool, -1.0), + (mod.cffi_cos_ool, mod.cffi_sin_ool, 1.0), + (mod.cffi_cos_ool, mod.cffi_sin_ool, -1.0), + (mod.cffi_sin, mod.cffi_cos_ool, 1.0), + (mod.cffi_sin, mod.cffi_cos_ool, -1.0), + (mod.cffi_cos, mod.cffi_sin_ool, 1.0), + (mod.cffi_cos, mod.cffi_sin_ool, -1.0)]: + expected = pyfunc(fa, fb, x) + got = cfunc(fa, fb, x) + self.assertEqual(got, expected) + # A single specialization was compiled for all calls + self.assertEqual(len(cfunc.overloads), 1, cfunc.overloads) + + def test_user_defined_symbols(self): + pyfunc = mod.use_user_defined_symbols + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + + def check_vector_sin(self, cfunc, x, y): + cfunc(x, y) + np.testing.assert_allclose(y, np.sin(x)) + + def _test_from_buffer_numpy_array(self, pyfunc, dtype): + x = np.arange(10).astype(dtype) + y = np.zeros_like(x) + cfunc = jit(nopython=True)(pyfunc) + self.check_vector_sin(cfunc, x, y) + + def test_from_buffer_float32(self): + self._test_from_buffer_numpy_array(mod.vector_sin_float32, np.float32) + + def test_from_buffer_float64(self): + self._test_from_buffer_numpy_array(mod.vector_sin_float64, np.float64) + + def test_from_buffer_struct(self): + n = 10 + x = np.arange(n) + np.arange(n * 2, n * 3) * 1j + y = np.zeros(n) + real_cfunc = jit(nopython=True)(mod.vector_extract_real) + real_cfunc(x, y) + np.testing.assert_equal(x.real, y) + imag_cfunc = jit(nopython=True)(mod.vector_extract_imag) + imag_cfunc(x, y) + np.testing.assert_equal(x.imag, y) + + def test_from_buffer_pyarray(self): + pyfunc = mod.vector_sin_float32 + cfunc = jit(nopython=True)(pyfunc) + x = array.array("f", range(10)) + y = array.array("f", [0] * len(x)) + self.check_vector_sin(cfunc, x, y) + + def test_from_buffer_error(self): + pyfunc = mod.vector_sin_float32 + cfunc = jit(nopython=True)(pyfunc) + # Non-contiguous array + x = np.arange(10).astype(np.float32)[::2] + y = np.zeros_like(x) + with self.assertRaises(errors.TypingError) as raises: + cfunc(x, y) + self.assertIn("from_buffer() unsupported on non-contiguous buffers", + str(raises.exception)) + + def test_from_buffer_numpy_multi_array(self): + c1 = np.array([1, 2], order='C', dtype=np.float32) + c1_zeros = np.zeros_like(c1) + c2 = np.array([[1, 2], [3, 4]], order='C', dtype=np.float32) + c2_zeros = np.zeros_like(c2) + f1 = np.array([1, 2], order='F', dtype=np.float32) + f1_zeros = np.zeros_like(f1) + f2 = np.array([[1, 2], [3, 4]], order='F', dtype=np.float32) + f2_zeros = np.zeros_like(f2) + f2_copy = f2.copy('K') + pyfunc = mod.vector_sin_float32 + cfunc = jit(nopython=True)(pyfunc) + # No exception because of C layout and single dimension + self.check_vector_sin(cfunc, c1, c1_zeros) + # No exception because of C layout + cfunc(c2, c2_zeros) + sin_c2 = np.sin(c2) + sin_c2[1] = [0, 0] # Reset to zero, since cfunc only processes one row + np.testing.assert_allclose(c2_zeros, sin_c2) + # No exception because of single dimension + self.check_vector_sin(cfunc, f1, f1_zeros) + # Exception because multi-dimensional with F layout + with self.assertRaises(errors.TypingError) as raises: + cfunc(f2, f2_zeros) + np.testing.assert_allclose(f2, f2_copy) + self.assertIn("from_buffer() only supports multidimensional arrays with C layout", + str(raises.exception)) + + def test_indirect_multiple_use(self): + """ + Issue #2263 + + Linkage error due to multiple definition of global tracking symbol. + """ + my_sin = mod.cffi_sin + + # Use two jit functions that references `my_sin` to ensure multiple + # modules + @jit(nopython=True) + def inner(x): + return my_sin(x) + + @jit(nopython=True) + def foo(x): + return inner(x) + my_sin(x + 1) + + # Error occurs when foo is being compiled + x = 1.123 + self.assertEqual(foo(x), my_sin(x) + my_sin(x + 1)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cli.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..37b1dcefb65ebbcfbb4c197428ebdc32d14f2175 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cli.py @@ -0,0 +1,281 @@ +# Tests for the CLI + +import os +import subprocess +import sys +import threading +import json +from subprocess import CompletedProcess +from tempfile import TemporaryDirectory +from unittest import mock + +import unittest +from numba.tests.support import TestCase, linux_only +import numba.misc.numba_sysinfo as nsi +from numba.tests.gdb_support import needs_gdb +from numba.misc.numba_gdbinfo import collect_gdbinfo +# Going to mock parts of this in testing +from numba.misc.numba_gdbinfo import _GDBTestWrapper + + +def run_cmd(cmdline, env=os.environ, timeout=60): + popen = subprocess.Popen(cmdline, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env) + + timeout_timer = threading.Timer(timeout, popen.kill) + try: + timeout_timer.start() + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError( + "process failed with code %s: stderr follows\n%s\n" % + (popen.returncode, err.decode())) + return out.decode(), err.decode() + finally: + timeout_timer.cancel() + return None, None + + +class TestCLI(TestCase): + + def test_as_module_exit_code(self): + cmdline = [sys.executable, "-m", "numba"] + with self.assertRaises(AssertionError) as raises: + run_cmd(cmdline) + + self.assertIn("process failed with code 1", str(raises.exception)) + + def test_sysinfo_from_module(self): + cmdline = [sys.executable, "-m", "numba", "-s"] + o, _ = run_cmd(cmdline) + self.assertIn("System info", o) + + def test_json_sysinfo_from_module(self): + with TemporaryDirectory() as d: + path = os.path.join(d, "test_json_sysinfo.json") + cmdline = [sys.executable, "-m", "numba", "--sys-json", path] + run_cmd(cmdline) + with self.subTest(msg=f"{path} exists"): + self.assertTrue(os.path.exists(path)) + with self.subTest(msg="json load"): + with open(path, 'r') as f: + info = json.load(f) + safe_contents = { + int: ( + nsi._cpu_count, + ), + float: ( + nsi._runtime, + ), + str: ( + nsi._start, + nsi._start_utc, + nsi._machine, + nsi._cpu_name, + nsi._platform_name, + nsi._os_name, + nsi._os_version, + nsi._python_comp, + nsi._python_impl, + nsi._python_version, + nsi._llvm_version, + ), + bool: ( + nsi._cu_dev_init, + nsi._svml_state, + nsi._svml_loaded, + nsi._svml_operational, + nsi._llvm_svml_patched, + nsi._tbb_thread, + nsi._openmp_thread, + nsi._wkq_thread, + ), + list: ( + nsi._errors, + nsi._warnings, + ), + dict: ( + nsi._numba_env_vars, + ), + } + for t, keys in safe_contents.items(): + for k in keys: + with self.subTest(k=k): + self.assertIsInstance(info[k], t) + + @needs_gdb + def test_gdb_status_from_module(self): + # Check that the `python -m numba -g` works ok + cmdline = [sys.executable, "-m", "numba", "-g"] + o, _ = run_cmd(cmdline) + self.assertIn("GDB info", o) + # It's not known a priori whether the extension is supported, this just + # checks that the last logical item in the output is printed. + self.assertIn("Numba printing extension support", o) + + +class TestGDBCLIInfo(TestCase): + + def setUp(self): + # Mock the entire class, to report valid things, + # then override bits of it locally to check failures etc. + + self._patches = [] + + mock_init = lambda self: None + self._patches.append(mock.patch.object(_GDBTestWrapper, '__init__', + mock_init)) + + bpath = 'numba.misc.numba_gdbinfo._GDBTestWrapper.gdb_binary' + self._patches.append(mock.patch(bpath, 'PATH_TO_GDB')) + + def _patch(fnstr, func): + self._patches.append(mock.patch.object(_GDBTestWrapper, fnstr, + func)) + + def mock_check_launch(self): + return CompletedProcess('COMMAND STRING', 0) + + _patch('check_launch', mock_check_launch) + + # NOTE: The Python and NumPy versions are set to something unsupported! + def mock_check_python(self): + return CompletedProcess('COMMAND STRING', 0, + stdout='(3, 2)', + stderr='') + + _patch('check_python', mock_check_python) + + def mock_check_numpy(self): + return CompletedProcess('COMMAND STRING', 0, stdout='True', + stderr='') + + _patch('check_numpy', mock_check_numpy) + + def mock_check_numpy_version(self): + return CompletedProcess('COMMAND STRING', 0, stdout='1.15', + stderr='') + + _patch('check_numpy_version', mock_check_numpy_version) + + # start the patching + for p in self._patches: + p.start() + + def tearDown(self): + # stop the patching + for p in self._patches: + p.stop() + + def test_valid(self): + collected = collect_gdbinfo() + self.assertEqual(collected.binary_loc, 'PATH_TO_GDB') + extp = os.path.exists(os.path.abspath(collected.extension_loc)) + self.assertTrue(extp) + self.assertEqual(collected.py_ver, '3.2') + self.assertEqual(collected.np_ver, '1.15') + self.assertIn('Full', collected.supported) + + def test_invalid_binary(self): + + def mock_fn(self): + return CompletedProcess('INVALID_BINARY', 1) + + with mock.patch.object(_GDBTestWrapper, 'check_launch', mock_fn): + info = collect_gdbinfo() + self.assertIn("Testing gdb binary failed.", info.binary_loc) + self.assertIn("gdb at 'PATH_TO_GDB' does not appear to work", + info.binary_loc) + + def test_no_python(self): + def mock_fn(self): + return CompletedProcess('NO PYTHON', 1) + + with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn): + collected = collect_gdbinfo() + self.assertEqual(collected.py_ver, 'No Python support') + self.assertEqual(collected.supported, 'None') + + def test_unparsable_python_version(self): + def mock_fn(self): + return CompletedProcess('NO PYTHON', 0, stdout='(NOT A VERSION)') + + with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn): + collected = collect_gdbinfo() + self.assertEqual(collected.py_ver, 'No Python support') + + def test_no_numpy(self): + def mock_fn(self): + return CompletedProcess('NO NUMPY', 1) + + with mock.patch.object(_GDBTestWrapper, 'check_numpy', mock_fn): + collected = collect_gdbinfo() + self.assertEqual(collected.np_ver, 'No NumPy support') + self.assertEqual(collected.py_ver, '3.2') + self.assertIn('Partial', collected.supported) + + def test_no_numpy_version(self): + def mock_fn(self): + return CompletedProcess('NO NUMPY VERSION', 1) + + with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn): + collected = collect_gdbinfo() + self.assertEqual(collected.np_ver, 'Unknown') + + def test_traceback_in_numpy_version(self): + def mock_fn(self): + return CompletedProcess('NO NUMPY VERSION', 0, + stdout='(NOT A VERSION)', + stderr='Traceback') + + with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn): + collected = collect_gdbinfo() + self.assertEqual(collected.np_ver, 'Unknown') + + +@linux_only +class TestGDBCLIInfoBrokenGdbs(TestCase): + # In these tests, it's necessary to actually run the entry point in an env + # with the env var set as it's in part testing the processing of the + # handling of consumption of variables by numba.core.config. + + def test_cannot_find_gdb_from_name(self): + # Tests that supplying an invalid gdb binary name is handled ok + env = os.environ.copy() + env['NUMBA_GDB_BINARY'] = 'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME' + cmdline = [sys.executable, "-m", "numba", "-g"] + stdout, stderr = run_cmd(cmdline, env=env) + self.assertIn("Testing gdb binary failed", stdout) + self.assertIn("No such file or directory", stdout) + self.assertIn("'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME'", stdout) + + def test_cannot_find_gdb_from_path(self): + # Tests that an invalid path is handled ok + env = os.environ.copy() + with TemporaryDirectory() as d: + # This wont exist as a path... + path = os.path.join(d, 'CANNOT_EXIST') + env['NUMBA_GDB_BINARY'] = path + cmdline = [sys.executable, "-m", "numba", "-g"] + stdout, stderr = run_cmd(cmdline, env=env) + self.assertIn("Testing gdb binary failed", stdout) + self.assertIn("No such file or directory", stdout) + self.assertIn(path, stdout) + + def test_nonsense_gdb_binary(self): + # Tests that a nonsense binary specified as gdb it picked up ok + env = os.environ.copy() + env['NUMBA_GDB_BINARY'] = 'python' # 'python' isn't gdb! + cmdline = [sys.executable, "-m", "numba", "-g"] + stdout, stderr = run_cmd(cmdline, env=env) + self.assertIn("Testing gdb binary failed", stdout) + # NOTE: should 'python' ever add support for the same flags as the gdb + # commands used in the information gathering code in `numba_gdbinfo` + # this test will fail, it's reasonably unlikely. + self.assertIn("Unknown option", stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compile_cache.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compile_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..edeab592d3e69b190fd40515b0aaf5167c2fd4a7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compile_cache.py @@ -0,0 +1,153 @@ +import unittest +from contextlib import contextmanager + +from llvmlite import ir + +from numba.core import types, typing, callconv, cpu, cgutils +from numba.core.registry import cpu_target + + +class TestCompileCache(unittest.TestCase): + ''' + Tests that the caching in BaseContext.compile_internal() works correctly by + checking the state of the cache when it is used by the CPUContext. + ''' + + @contextmanager + def _context_builder_sig_args(self): + typing_context = cpu_target.typing_context + context = cpu_target.target_context + lib = context.codegen().create_library('testing') + with context.push_code_library(lib): + module = ir.Module("test_module") + + sig = typing.signature(types.int32, types.int32) + llvm_fnty = context.call_conv.get_function_type(sig.return_type, + sig.args) + function = cgutils.get_or_insert_function(module, llvm_fnty, + 'test_fn') + args = context.call_conv.get_arguments(function) + assert function.is_declaration + entry_block = function.append_basic_block('entry') + builder = ir.IRBuilder(entry_block) + + yield context, builder, sig, args + + def test_cache(self): + def times2(i): + return 2*i + + def times3(i): + return i*3 + + with self._context_builder_sig_args() as ( + context, builder, sig, args, + ): + initial_cache_size = len(context.cached_internal_func) + # Ensure the cache is empty to begin with + self.assertEqual(initial_cache_size + 0, + len(context.cached_internal_func)) + + # After one compile, it should contain one entry + context.compile_internal(builder, times2, sig, args) + self.assertEqual(initial_cache_size + 1, + len(context.cached_internal_func)) + + # After a second compilation of the same thing, it should still contain + # one entry + context.compile_internal(builder, times2, sig, args) + self.assertEqual(initial_cache_size + 1, + len(context.cached_internal_func)) + + # After compilation of another function, the cache should have grown by + # one more. + context.compile_internal(builder, times3, sig, args) + self.assertEqual(initial_cache_size + 2, + len(context.cached_internal_func)) + + sig2 = typing.signature(types.float64, types.float64) + llvm_fnty2 = context.call_conv.get_function_type(sig2.return_type, + sig2.args) + function2 = cgutils.get_or_insert_function(builder.module, + llvm_fnty2, 'test_fn_2') + args2 = context.call_conv.get_arguments(function2) + assert function2.is_declaration + entry_block2 = function2.append_basic_block('entry') + builder2 = ir.IRBuilder(entry_block2) + + # Ensure that the same function with a different signature does not + # reuse an entry from the cache in error + context.compile_internal(builder2, times3, sig2, args2) + self.assertEqual(initial_cache_size + 3, + len(context.cached_internal_func)) + + def test_closures(self): + """ + Caching must not mix up closures reusing the same code object. + """ + def make_closure(x, y): + def f(z): + return y + z + return f + + with self._context_builder_sig_args() as ( + context, builder, sig, args, + ): + # Closures with distinct cell contents must each be compiled. + clo11 = make_closure(1, 1) + clo12 = make_closure(1, 2) + clo22 = make_closure(2, 2) + initial_cache_size = len(context.cached_internal_func) + res1 = context.compile_internal(builder, clo11, sig, args) + self.assertEqual(initial_cache_size + 1, + len(context.cached_internal_func)) + res2 = context.compile_internal(builder, clo12, sig, args) + self.assertEqual(initial_cache_size + 2, + len(context.cached_internal_func)) + # Same cell contents as above (first parameter isn't captured) + res3 = context.compile_internal(builder, clo22, sig, args) + self.assertEqual(initial_cache_size + 2, + len(context.cached_internal_func)) + + def test_error_model(self): + """ + Caching must not mix up different error models. + """ + def inv(x): + return 1.0 / x + + inv_sig = typing.signature(types.float64, types.float64) + + def compile_inv(context): + return context.compile_subroutine(builder, inv, inv_sig) + + with self._context_builder_sig_args() as ( + context, builder, sig, args, + ): + py_error_model = callconv.create_error_model('python', context) + np_error_model = callconv.create_error_model('numpy', context) + + py_context1 = context.subtarget(error_model=py_error_model) + py_context2 = context.subtarget(error_model=py_error_model) + np_context = context.subtarget(error_model=np_error_model) + + initial_cache_size = len(context.cached_internal_func) + + # Note the parent context's cache is shared by subtargets + self.assertEqual(initial_cache_size + 0, + len(context.cached_internal_func)) + # Compiling with the same error model reuses the same cache slot + compile_inv(py_context1) + self.assertEqual(initial_cache_size + 1, + len(context.cached_internal_func)) + compile_inv(py_context2) + self.assertEqual(initial_cache_size + 1, + len(context.cached_internal_func)) + # Compiling with another error model creates a new cache slot + compile_inv(np_context) + self.assertEqual(initial_cache_size + 2, + len(context.cached_internal_func)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conditions_as_predicates.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conditions_as_predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..030b48a04ac1df7689ce3b8b9fd64cfc441a426c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conditions_as_predicates.py @@ -0,0 +1,200 @@ +from numba.tests.support import TestCase, numpy_support +from numba import njit, types +from numba.typed import List, Dict +import numpy as np + + +class TestConditionsAsPredicates(TestCase): + + def test_scalars(self): + # checks that scalar types can be used as predicates + dts = [np.int8, np.uint16, np.int64, np.float32, np.float64, + np.complex128, int, float, complex, str, bool] + for dt in dts: + for c in 1, 0: + x = dt(c) + + @njit + def foo(): + if x: + return 10 + else: + return 20 + self.assertEqual(foo(), foo.py_func()) + self.assertEqual(foo(), 10 if c == 1 or dt is str else 20) + + # empty string + @njit + def foo(x): + if x: + return 10 + else: + return 20 + s = "" + self.assertEqual(foo(s), foo.py_func(s)) + + def test_typed_list(self): + @njit + def foo(x): + if x: + return 10 + else: + return 20 + + # empty list + z = List.empty_list(types.int64) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 20) + + # non-empty list + z.append(1) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + def test_reflected_list(self): + # non-empty + @njit + def foo(x): + if x: + return 10 + else: + return 20 + + z = [1] + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + # non-empty local + @njit + def foo(): + y = [1, 2] + if y: + return 10 + else: + return 20 + + self.assertEqual(foo(), foo.py_func()) + self.assertEqual(foo.py_func(), 10) + + # empty local + @njit + def foo(): + y = [1, 2] + y.pop() + y.pop() + assert len(y) == 0 + if y: + return 10 + else: + return 20 + + self.assertEqual(foo(), foo.py_func()) + self.assertEqual(foo.py_func(), 20) + + def test_reflected_set(self): + # non-empty + @njit + def foo(x): + if x: + return 10 + else: + return 20 + + z = {1} + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + # non-empty local + @njit + def foo(): + y = {1, 2} + if y: + return 10 + else: + return 20 + + self.assertEqual(foo(), foo.py_func()) + self.assertEqual(foo.py_func(), 10) + + # empty local + @njit + def foo(): + y = {1, 2} + y.pop() + y.pop() + assert len(y) == 0 + if y: + return 10 + else: + return 20 + + self.assertEqual(foo(), foo.py_func()) + self.assertEqual(foo.py_func(), 20) + + def test_typed_dict(self): + @njit + def foo(x): + if x: + return 10 + else: + return 20 + + # empty + z = Dict.empty(types.int64, types.int64) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 20) + + # non-empty + z[2] = 3 + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + def test_arrays(self): + @njit + def foo(x): + if x: + return 10 + else: + return 20 + + # non-empty 0d, True + z = np.array(1) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + # non-empty 0d, False + z = np.array(0) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 20) + # non-empty nd True + z = np.array([[[1]]]) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 10) + + # non-empty nd False + z = np.array([[[0]]]) + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 20) + + # various problems: + + # empty, NumPy warns or raises if NumPy >= 2.2 + z = np.empty(0) + if numpy_support.numpy_version >= (2, 2): + with self.assertRaises(ValueError) as raises: + foo(z) + msg = ("The truth value of an empty array is ambiguous." + " Use `array.size > 0` to check that an array is not empty.") + self.assertIn(msg, str(raises.exception)) + else: + self.assertEqual(foo(z), foo.py_func(z)) + self.assertEqual(foo.py_func(z), 20) + + # nd, NumPy raises + z = np.array([1, 2]) + with self.assertRaises(ValueError) as raises: + foo(z) + + msg = ("The truth value of an array with more than one element " + "is ambiguous. Use a.any() or a.all()") + self.assertIn(msg, str(raises.exception)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conversion.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..54bb94ca78f66c00ebc9fe0b8f535cf2b0cd8f98 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_conversion.py @@ -0,0 +1,223 @@ +import gc +import itertools + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase +from numba.np import numpy_support + + +def identity(x): + return x + +def addition(x, y): + return x + y + +def equality(x, y): + return x == y + +def foobar(x, y, z): + return x + + +class TestConversion(TestCase): + """ + Testing Python to Native conversion + """ + + def test_complex_identity(self): + pyfunc = identity + cfunc = njit(types.complex64(types.complex64))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + self.assertEqual(cfunc(x), x) + for x in np.complex64(xs): + self.assertEqual(cfunc(x), x) + + cfunc = njit(types.complex128(types.complex128))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + self.assertEqual(cfunc(x), x) + for x in np.complex128(xs): + self.assertEqual(cfunc(x), x) + + def test_complex_addition(self): + pyfunc = addition + cfunc = njit(types.complex64(types.complex64, types.complex64))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + y = x + self.assertEqual(cfunc(x, y), x + y) + for x in np.complex64(xs): + y = x + self.assertEqual(cfunc(x, y), x + y) + + + cfunc = njit(types.complex128(types.complex128, + types.complex128))(pyfunc) + + xs = [1.0j, (1+1j), (-1-1j), (1+0j)] + for x in xs: + y = x + self.assertEqual(cfunc(x, y), x + y) + for x in np.complex128(xs): + y = x + self.assertEqual(cfunc(x, y), x + y) + + def test_boolean_as_int(self): + pyfunc = equality + cfunc = njit((types.boolean, types.intp))(pyfunc) + + xs = True, False + ys = -1, 0, 1 + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + def test_boolean_as_float(self): + pyfunc = equality + cfunc = njit((types.boolean, types.float64))(pyfunc) + + xs = True, False + ys = -1, 0, 1 + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + def test_boolean_eq_boolean(self): + pyfunc = equality + cfunc = njit((types.boolean, types.boolean))(pyfunc) + + xs = True, False + ys = True, False + + for xs, ys in itertools.product(xs, ys): + self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys)) + + # test when a function parameters are jitted as unsigned types + # the function is called with negative parameters the Python error + # that it generates is correctly handled -- a Python error is returned to the user + # For more info, see the comment in Include/longobject.h for _PyArray_AsByteArray + # which PyLong_AsUnsignedLongLong calls + def test_negative_to_unsigned(self): + def f(x): + return x + with self.assertRaises(OverflowError): + jit('uintp(uintp)', nopython=True)(f)(-5) + + # test the switch logic in callwraper.py:build_wrapper() works for more than one argument + # and where the error occurs + def test_multiple_args_negative_to_unsigned(self): + pyfunc = foobar + cfunc = njit(types.uint64(types.uint64, types.uint64, + types.uint64),)(pyfunc) + + test_fail_args = ((-1, 0, 1), (0, -1, 1), (0, 1, -1)) + with self.assertRaises(OverflowError): + for a, b, c in test_fail_args: + cfunc(a, b, c) + + # test switch logic of callwraper.py:build_wrapper() with records as function parameters + def test_multiple_args_records(self): + pyfunc = foobar + + mystruct_dt = np.dtype([('p', np.float64), + ('row', np.float64), + ('col', np.float64)]) + mystruct = numpy_support.from_dtype(mystruct_dt) + + cfunc = njit(mystruct[:](mystruct[:], types.uint64, + types.uint64),)(pyfunc) + + st1 = np.recarray(3, dtype=mystruct_dt) + + st1.p = np.arange(st1.size) + 1 + st1.row = np.arange(st1.size) + 1 + st1.col = np.arange(st1.size) + 1 + + with self.assertRefCount(st1): + test_fail_args = ((st1, -1, 1), (st1, 1, -1)) + + for a, b, c in test_fail_args: + with self.assertRaises(OverflowError): + cfunc(a, b, c) + + del test_fail_args, a, b, c + gc.collect() + + # test switch logic of callwraper.py:build_wrapper() with no function parameters + def test_with_no_parameters(self): + def f(): + pass + self.assertEqual(f(), jit('()', nopython=True)(f)()) + + def check_argument_cleanup(self, typ, obj): + """ + Check that argument cleanup doesn't leak references. + """ + def f(x, y): + pass + + def _objects(obj): + objs = [obj] + if isinstance(obj, tuple): + for v in obj: + objs += _objects(v) + return objs + + objects = _objects(obj) + + cfunc = njit((typ, types.uint32))(f) + with self.assertRefCount(*objects): + cfunc(obj, 1) + with self.assertRefCount(*objects): + with self.assertRaises(OverflowError): + cfunc(obj, -1) + + cfunc = njit((types.uint32, typ))(f) + with self.assertRefCount(*objects): + cfunc(1, obj) + with self.assertRefCount(*objects): + with self.assertRaises(OverflowError): + cfunc(-1, obj) + + def test_cleanup_buffer(self): + mem = memoryview(bytearray(b"xyz")) + self.check_argument_cleanup(types.MemoryView(types.byte, 1, 'C'), mem) + + def test_cleanup_record(self): + dtype = np.dtype([('x', np.float64), ('y', np.float64)]) + recarr = np.zeros(1, dtype=dtype) + self.check_argument_cleanup(numpy_support.from_dtype(dtype), recarr[0]) + + def test_cleanup_tuple(self): + mem = memoryview(bytearray(b"xyz")) + tp = types.UniTuple(types.MemoryView(types.byte, 1, 'C'), 2) + self.check_argument_cleanup(tp, (mem, mem)) + + def test_cleanup_optional(self): + mem = memoryview(bytearray(b"xyz")) + tp = types.Optional(types.MemoryView(types.byte, 1, 'C')) + self.check_argument_cleanup(tp, mem) + + def test_stringliteral_to_unicode(self): + # See issue #6907, explicit signature on bar() takes a unicode_type but + # the call to bar() in foo() is with a StringLiteral + + @jit(types.void(types.unicode_type), nopython=True) + def bar(string): + pass + + @jit(types.void(), nopython=True) + def foo2(): + bar("literal string") + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ctypes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..c1a7edf5099f6415576dda54faa52f8d18f150e5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ctypes.py @@ -0,0 +1,255 @@ +from ctypes import * +import sys +import threading + +import numpy as np + + +from numba import jit, njit +from numba.core import types, errors +from numba.core.typing import ctypes_utils +from numba.tests.support import MemoryLeakMixin, tag, TestCase +from numba.tests.ctypes_usecases import * +import unittest + + +class TestCTypesTypes(TestCase): + + def _conversion_tests(self, check): + check(c_double, types.float64) + check(c_int, types.intc) + check(c_uint16, types.uint16) + check(c_size_t, types.size_t) + check(c_ssize_t, types.ssize_t) + + check(c_void_p, types.voidptr) + check(POINTER(c_float), types.CPointer(types.float32)) + check(POINTER(POINTER(c_float)), + types.CPointer(types.CPointer(types.float32))) + + check(None, types.void) + + def test_from_ctypes(self): + """ + Test converting a ctypes type to a Numba type. + """ + def check(cty, ty): + got = ctypes_utils.from_ctypes(cty) + self.assertEqual(got, ty) + + self._conversion_tests(check) + + # An unsupported type + with self.assertRaises(TypeError) as raises: + ctypes_utils.from_ctypes(c_wchar_p) + self.assertIn("Unsupported ctypes type", str(raises.exception)) + + def test_to_ctypes(self): + """ + Test converting a Numba type to a ctypes type. + """ + def check(cty, ty): + got = ctypes_utils.to_ctypes(ty) + self.assertEqual(got, cty) + + self._conversion_tests(check) + + # An unsupported type + with self.assertRaises(TypeError) as raises: + ctypes_utils.to_ctypes(types.ellipsis) + self.assertIn("Cannot convert Numba type '...' to ctypes type", + str(raises.exception)) + + +class TestCTypesUseCases(MemoryLeakMixin, TestCase): + + def test_c_sin(self): + pyfunc = use_c_sin + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + def test_two_funcs(self): + # Check that two constant functions don't get mixed up. + pyfunc = use_two_funcs + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + @unittest.skipUnless(is_windows, "Windows-specific test") + def test_stdcall(self): + # Just check that it doesn't crash + cfunc = njit((types.uintc,))(use_c_sleep) + + cfunc(1) + + def test_ctype_wrapping(self): + pyfunc = use_ctype_wrapping + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + def test_ctype_voidptr(self): + pyfunc = use_c_pointer + # pyfunc will segfault if called + cfunc = njit((types.int32,))(pyfunc) + x = 123 + self.assertEqual(cfunc(x), x + 1) + + def test_function_pointer(self): + pyfunc = use_func_pointer + cfunc = jit(nopython=True)(pyfunc) + for (fa, fb, x) in [ + (c_sin, c_cos, 1.0), + (c_sin, c_cos, -1.0), + (c_cos, c_sin, 1.0), + (c_cos, c_sin, -1.0)]: + expected = pyfunc(fa, fb, x) + got = cfunc(fa, fb, x) + self.assertEqual(got, expected) + # A single specialization was compiled for all calls + self.assertEqual(len(cfunc.overloads), 1, cfunc.overloads) + + def test_untyped_function(self): + with self.assertRaises(TypeError) as raises: + njit((types.double,))(use_c_untyped) + self.assertIn("ctypes function '_numba_test_exp' doesn't define its argument types", + str(raises.exception)) + + def test_python_call_back(self): + mydct = {'what': 1232121} + + def call_me_maybe(arr): + return mydct[arr[0].decode('ascii')] + + # Create a callback into the python interpreter + py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe) + + def pyfunc(a): + what = py_call_back(a) + return what + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + arr = np.array(["what"], dtype='S10') + self.assertEqual(pyfunc(arr), cfunc(arr)) + + def test_python_call_back_threaded(self): + def pyfunc(a, repeat): + out = 0 + for _ in range(repeat): + out += py_call_back(a) + return out + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + + arr = np.array(["what"], dtype='S10') + repeat = 1000 + + expected = pyfunc(arr, repeat) + outputs = [] + + # Warm up + cfunc(arr, repeat) + + # Test the function in multiple threads to exercise the + # GIL ensure/release code + + def run(func, arr, repeat): + outputs.append(func(arr, repeat)) + + threads = [threading.Thread(target=run, args=(cfunc, arr, repeat)) + for _ in range(10)] + + # Start threads + for th in threads: + th.start() + + # End threads + for th in threads: + th.join() + + # Check results + for got in outputs: + self.assertEqual(expected, got) + + def test_passing_array_ctypes_data(self): + """ + Test the ".ctypes.data" attribute of an array can be passed + as a "void *" parameter. + """ + def pyfunc(arr): + return c_take_array_ptr(arr.ctypes.data) + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + + arr = np.arange(5) + + expected = pyfunc(arr) + got = cfunc(arr) + + self.assertEqual(expected, got) + + def check_array_ctypes(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + arr = np.linspace(0, 10, 5) + expected = arr ** 2.0 + got = cfunc(arr) + self.assertPreciseEqual(expected, got) + return cfunc + + def test_passing_array_ctypes_voidptr(self): + """ + Test the ".ctypes" attribute of an array can be passed + as a "void *" parameter. + """ + self.check_array_ctypes(use_c_vsquare) + + def test_passing_array_ctypes_voidptr_pass_ptr(self): + """ + Test the ".ctypes" attribute of an array can be passed + as a pointer parameter of the right type. + """ + cfunc = self.check_array_ctypes(use_c_vcube) + + # Non-compatible pointers are not accepted (here float32* vs. float64*) + with self.assertRaises(errors.TypingError) as raises: + cfunc(np.float32([0.0])) + + self.assertIn("No implementation of function ExternalFunctionPointer", + str(raises.exception)) + + def test_storing_voidptr_to_int_array(self): + # Make C callback that returns a void* + cproto = CFUNCTYPE(c_void_p) + + @cproto + def get_voidstar(): + return 0xdeadbeef + + # Make python functions that use the C callback + def pyfunc(a): + ptr = get_voidstar() + a[0] = ptr + return ptr + + # Compile it + cfunc = njit((types.uintp[::1],))(pyfunc) + + # Setup inputs + arr_got = np.zeros(1, dtype=np.uintp) + arr_expect = arr_got.copy() + + # Run functions + ret_got = cfunc(arr_got) + ret_expect = pyfunc(arr_expect) + + # Check + self.assertEqual(ret_expect, 0xdeadbeef) + self.assertPreciseEqual(ret_got, ret_expect) + self.assertPreciseEqual(arr_got, arr_expect) + + +if __name__ == '__main__': + unittest.main() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dataflow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dataflow.py new file mode 100644 index 0000000000000000000000000000000000000000..1659ad2bda25df82a2d1704b26837b38a34ea359 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dataflow.py @@ -0,0 +1,170 @@ +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase + + +force_pyobj_jit_opt = {'forceobj': True} +no_pyobj_jit_opt = {'nopython': True} + + +def assignments(a): + b = c = str(a) + return b + c + + +def assignments2(a): + b = c = d = str(a) + return b + c + d + + +# Use cases for issue #503 + +def var_propagate1(a, b): + c = (a if a > b else b) + 5 + return c + + +def var_propagate2(a, b): + c = 5 + (a if a > b else b + 12) / 2.0 + return c + + +def var_propagate3(a, b): + c = 5 + (a > b and a or b) + return c + + +def var_propagate4(a, b): + c = 5 + (a - 1 and b + 1) or (a + 1 and b - 1) + return c + + +# Issue #480 +def chained_compare(a): + return 1 < a < 3 + + +# Issue #591 +def stack_effect_error(x): + i = 2 + c = 1 + if i == x: + for i in range(3): + c = i + return i + c + +# Some more issues with stack effect and blocks +def for_break(n, x): + for i in range(n): + n = 0 + if i == x: + break + else: + n = i + return i, n + +# Issue #571 +def var_swapping(a, b, c, d, e): + a, b = b, a + c, d, e = e, c, d + a, b, c, d = b, c, d, a + return a + b + c + d +e + +class TestDataFlow(TestCase): + + def test_assignments(self, flags=force_pyobj_jit_opt): + pyfunc = assignments + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + def test_assignments2(self, flags=force_pyobj_jit_opt): + pyfunc = assignments2 + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [-1, 0, 1]: + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + if flags is force_pyobj_jit_opt: + cfunc("a") + + # The dataflow analysis must be good enough for native mode + # compilation to succeed, hence the use of njit in the following tests. + + def run_propagate_func(self, func, args): + self.assertPreciseEqual(func(*args), func.py_func(*args)) + + def test_var_propagate1(self): + cfunc = njit((types.intp, types.intp))(var_propagate1) + self.run_propagate_func(cfunc, (2, 3)) + self.run_propagate_func(cfunc, (3, 2)) + + def test_var_propagate2(self): + cfunc = njit((types.intp, types.intp))(var_propagate2) + self.run_propagate_func(cfunc, (2, 3)) + self.run_propagate_func(cfunc, (3, 2)) + + def test_var_propagate3(self): + cfunc = njit((types.intp, types.intp))(var_propagate3) + self.run_propagate_func(cfunc, (2, 3)) + self.run_propagate_func(cfunc, (3, 2)) + self.run_propagate_func(cfunc, (2, 0)) + self.run_propagate_func(cfunc, (-1, 0)) + self.run_propagate_func(cfunc, (0, 2)) + self.run_propagate_func(cfunc, (0, -1)) + + def test_var_propagate4(self): + cfunc = njit((types.intp, types.intp))(var_propagate4) + self.run_propagate_func(cfunc, (1, 1)) + self.run_propagate_func(cfunc, (1, 0)) + self.run_propagate_func(cfunc, (1, -1)) + self.run_propagate_func(cfunc, (0, 1)) + self.run_propagate_func(cfunc, (0, 0)) + self.run_propagate_func(cfunc, (0, -1)) + self.run_propagate_func(cfunc, (-1, 1)) + self.run_propagate_func(cfunc, (-1, 0)) + self.run_propagate_func(cfunc, (-1, -1)) + + def test_chained_compare(self, flags=force_pyobj_jit_opt): + pyfunc = chained_compare + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in [0, 1, 2, 3, 4]: + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + def test_chained_compare_npm(self): + self.test_chained_compare(no_pyobj_jit_opt) + + def test_stack_effect_error(self, flags=force_pyobj_jit_opt): + # Issue #591: POP_BLOCK must undo all stack pushes done inside + # the block. + pyfunc = stack_effect_error + cfunc = jit((types.int32,), **flags)(pyfunc) + for x in (0, 1, 2, 3): + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + def test_stack_effect_error_npm(self): + self.test_stack_effect_error(no_pyobj_jit_opt) + + def test_var_swapping(self, flags=force_pyobj_jit_opt): + pyfunc = var_swapping + cfunc = jit((types.int32,) * 5, **flags)(pyfunc) + args = tuple(range(0, 10, 2)) + self.assertPreciseEqual(pyfunc(*args), cfunc(*args)) + + def test_var_swapping_npm(self): + self.test_var_swapping(no_pyobj_jit_opt) + + def test_for_break(self, flags=force_pyobj_jit_opt): + # BREAK_LOOP must unwind the current inner syntax block. + pyfunc = for_break + cfunc = jit((types.intp, types.intp), **flags)(pyfunc) + for (n, x) in [(4, 2), (4, 6)]: + self.assertPreciseEqual(pyfunc(n, x), cfunc(n, x)) + + def test_for_break_npm(self): + self.test_for_break(no_pyobj_jit_opt) + + +if __name__ == '__main__': + unittest.main() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_doctest.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_doctest.py new file mode 100644 index 0000000000000000000000000000000000000000..53771dc4d6c1cf542f62314dadbf6a670e9a99da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_doctest.py @@ -0,0 +1,28 @@ +import doctest +import unittest +from numba.tests.support import TestCase + + +class TestDocTest(TestCase): + def test_basic_decorators(self): + from . import doctest_usecase + + # Make sure the finder see all the doctest + finder = doctest.DocTestFinder() + tests = finder.find(doctest_usecase) + testnames = {x.name for x in tests} + expected = { + 'numba.tests.doctest_usecase', + 'numba.tests.doctest_usecase.a', + 'numba.tests.doctest_usecase.b', + 'numba.tests.doctest_usecase.c', + 'numba.tests.doctest_usecase.d', + } + self.assertEqual(testnames, expected) + + # Execute the doctest in the module + doctest.testmod(doctest_usecase) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dyn_array.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dyn_array.py new file mode 100644 index 0000000000000000000000000000000000000000..99328052cac21076bba947475b72fdd1ebc110ab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dyn_array.py @@ -0,0 +1,1864 @@ +import contextlib +import sys +import numpy as np +import random +import re +import threading +import gc + +from numba.core.errors import TypingError +from numba import njit +from numba.core import types, utils, config +from numba.tests.support import MemoryLeakMixin, TestCase, tag, skip_if_32bit +from numba.core.utils import PYVERSION +import unittest + + +nrtjit = njit(_nrt=True, nogil=True) + + +def np_concatenate1(a, b, c): + return np.concatenate((a, b, c)) + +def np_concatenate2(a, b, c, axis): + return np.concatenate((a, b, c), axis=axis) + +def np_stack1(a, b, c): + return np.stack((a, b, c)) + +def np_stack2(a, b, c, axis): + return np.stack((a, b, c), axis=axis) + +def np_hstack(a, b, c): + return np.hstack((a, b, c)) + +def np_vstack(a, b, c): + return np.vstack((a, b, c)) + +def np_row_stack(a, b, c): + return np.row_stack((a, b, c)) + +def np_dstack(a, b, c): + return np.dstack((a, b, c)) + +def np_column_stack(a, b, c): + return np.column_stack((a, b, c)) + + +class BaseTest(TestCase): + + def check_outputs(self, pyfunc, argslist, exact=True): + cfunc = nrtjit(pyfunc) + for args in argslist: + expected = pyfunc(*args) + ret = cfunc(*args) + self.assertEqual(ret.size, expected.size) + self.assertEqual(ret.dtype, expected.dtype) + self.assertStridesEqual(ret, expected) + if exact: + np.testing.assert_equal(expected, ret) + else: + np.testing.assert_allclose(expected, ret) + + +class NrtRefCtTest(MemoryLeakMixin): + def assert_array_nrt_refct(self, arr, expect): + self.assertEqual(arr.base.refcount, expect) + + +class TestDynArray(NrtRefCtTest, TestCase): + + def test_empty_0d(self): + @nrtjit + def foo(): + arr = np.empty(()) + arr[()] = 42 + return arr + + arr = foo() + self.assert_array_nrt_refct(arr, 1) + np.testing.assert_equal(42, arr) + self.assertEqual(arr.size, 1) + self.assertEqual(arr.shape, ()) + self.assertEqual(arr.dtype, np.dtype(np.float64)) + self.assertEqual(arr.strides, ()) + arr.fill(123) # test writability + np.testing.assert_equal(123, arr) + del arr + + def test_empty_1d(self): + @nrtjit + def foo(n): + arr = np.empty(n) + for i in range(n): + arr[i] = i + + return arr + + n = 3 + arr = foo(n) + self.assert_array_nrt_refct(arr, 1) + np.testing.assert_equal(np.arange(n), arr) + self.assertEqual(arr.size, n) + self.assertEqual(arr.shape, (n,)) + self.assertEqual(arr.dtype, np.dtype(np.float64)) + self.assertEqual(arr.strides, (np.dtype(np.float64).itemsize,)) + arr.fill(123) # test writability + np.testing.assert_equal(123, arr) + del arr + + def test_empty_2d(self): + def pyfunc(m, n): + arr = np.empty((m, n), np.int32) + for i in range(m): + for j in range(n): + arr[i, j] = i + j + + return arr + + cfunc = nrtjit(pyfunc) + m = 4 + n = 3 + expected_arr = pyfunc(m, n) + got_arr = cfunc(m, n) + self.assert_array_nrt_refct(got_arr, 1) + np.testing.assert_equal(expected_arr, got_arr) + + self.assertEqual(expected_arr.size, got_arr.size) + self.assertEqual(expected_arr.shape, got_arr.shape) + self.assertEqual(expected_arr.strides, got_arr.strides) + + del got_arr + + def test_empty_3d(self): + def pyfunc(m, n, p): + arr = np.empty((m, n, p), np.int32) + for i in range(m): + for j in range(n): + for k in range(p): + arr[i, j, k] = i + j + k + + return arr + + cfunc = nrtjit(pyfunc) + m = 4 + n = 3 + p = 2 + expected_arr = pyfunc(m, n, p) + got_arr = cfunc(m, n, p) + self.assert_array_nrt_refct(got_arr, 1) + np.testing.assert_equal(expected_arr, got_arr) + + self.assertEqual(expected_arr.size, got_arr.size) + self.assertEqual(expected_arr.shape, got_arr.shape) + self.assertEqual(expected_arr.strides, got_arr.strides) + + del got_arr + + def test_empty_2d_sliced(self): + def pyfunc(m, n, p): + arr = np.empty((m, n), np.int32) + for i in range(m): + for j in range(n): + arr[i, j] = i + j + + return arr[p] + + cfunc = nrtjit(pyfunc) + m = 4 + n = 3 + p = 2 + expected_arr = pyfunc(m, n, p) + got_arr = cfunc(m, n, p) + self.assert_array_nrt_refct(got_arr, 1) + np.testing.assert_equal(expected_arr, got_arr) + + self.assertEqual(expected_arr.size, got_arr.size) + self.assertEqual(expected_arr.shape, got_arr.shape) + self.assertEqual(expected_arr.strides, got_arr.strides) + + del got_arr + + def test_return_global_array(self): + y = np.ones(4, dtype=np.float32) + initrefct = sys.getrefcount(y) + + def return_external_array(): + return y + + cfunc = nrtjit(return_external_array) + out = cfunc() + + # out reference by cfunc + self.assertEqual(initrefct + 1, sys.getrefcount(y)) + + np.testing.assert_equal(y, out) + np.testing.assert_equal(y, np.ones(4, dtype=np.float32)) + np.testing.assert_equal(out, np.ones(4, dtype=np.float32)) + + del out + gc.collect() + # out is only referenced by cfunc + self.assertEqual(initrefct + 1, sys.getrefcount(y)) + + del cfunc + gc.collect() + # y is no longer referenced by cfunc + self.assertEqual(initrefct, sys.getrefcount(y)) + + def test_return_global_array_sliced(self): + y = np.ones(4, dtype=np.float32) + + def return_external_array(): + return y[2:] + + cfunc = nrtjit(return_external_array) + out = cfunc() + self.assertIsNone(out.base) + + yy = y[2:] + np.testing.assert_equal(yy, out) + np.testing.assert_equal(yy, np.ones(2, dtype=np.float32)) + np.testing.assert_equal(out, np.ones(2, dtype=np.float32)) + + def test_array_pass_through(self): + def pyfunc(y): + return y + + arr = np.ones(4, dtype=np.float32) + + cfunc = nrtjit(pyfunc) + expected = cfunc(arr) + got = pyfunc(arr) + + np.testing.assert_equal(expected, arr) + np.testing.assert_equal(expected, got) + self.assertIs(expected, arr) + self.assertIs(expected, got) + + def test_array_pass_through_sliced(self): + def pyfunc(y): + return y[y.size // 2:] + + arr = np.ones(4, dtype=np.float32) + + initrefct = sys.getrefcount(arr) + + cfunc = nrtjit(pyfunc) + got = cfunc(arr) + self.assertEqual(initrefct + 1, sys.getrefcount(arr)) + expected = pyfunc(arr) + self.assertEqual(initrefct + 2, sys.getrefcount(arr)) + + np.testing.assert_equal(expected, arr[arr.size // 2]) + np.testing.assert_equal(expected, got) + + del expected + self.assertEqual(initrefct + 1, sys.getrefcount(arr)) + del got + self.assertEqual(initrefct, sys.getrefcount(arr)) + + def test_ufunc_with_allocated_output(self): + + def pyfunc(a, b): + out = np.empty(a.shape) + np.add(a, b, out) + return out + + cfunc = nrtjit(pyfunc) + + # 1D case + arr_a = np.random.random(10) + arr_b = np.random.random(10) + + np.testing.assert_equal(pyfunc(arr_a, arr_b), + cfunc(arr_a, arr_b)) + + self.assert_array_nrt_refct(cfunc(arr_a, arr_b), 1) + + # 2D case + arr_a = np.random.random(10).reshape(2, 5) + arr_b = np.random.random(10).reshape(2, 5) + + np.testing.assert_equal(pyfunc(arr_a, arr_b), + cfunc(arr_a, arr_b)) + + self.assert_array_nrt_refct(cfunc(arr_a, arr_b), 1) + + # 3D case + arr_a = np.random.random(70).reshape(2, 5, 7) + arr_b = np.random.random(70).reshape(2, 5, 7) + + np.testing.assert_equal(pyfunc(arr_a, arr_b), + cfunc(arr_a, arr_b)) + + self.assert_array_nrt_refct(cfunc(arr_a, arr_b), 1) + + def test_allocation_mt(self): + """ + This test exercises the array allocation in multithreaded usecase. + This stress the freelist inside NRT. + """ + + def pyfunc(inp): + out = np.empty(inp.size) + + # Zero fill + for i in range(out.size): + out[i] = 0 + + for i in range(inp[0]): + # Allocate inside a loop + tmp = np.empty(inp.size) + # Write to tmp + for j in range(tmp.size): + tmp[j] = inp[j] + # out = tmp + i + for j in range(tmp.size): + out[j] += tmp[j] + i + + return out + + cfunc = nrtjit(pyfunc) + size = 10 # small array size so that the computation is short + arr = np.random.randint(1, 10, size) + frozen_arr = arr.copy() + + np.testing.assert_equal(pyfunc(arr), cfunc(arr)) + # Ensure we did not modify the input + np.testing.assert_equal(frozen_arr, arr) + + workers = [] + inputs = [] + outputs = [] + + # Make wrapper to store the output + def wrapped(inp, out): + out[:] = cfunc(inp) + + # Create a lot of worker threads to create contention + for i in range(100): + arr = np.random.randint(1, 10, size) + out = np.empty_like(arr) + thread = threading.Thread(target=wrapped, + args=(arr, out), + name="worker{0}".format(i)) + workers.append(thread) + inputs.append(arr) + outputs.append(out) + + # Launch worker threads + for thread in workers: + thread.start() + + # Join worker threads + for thread in workers: + thread.join() + + # Check result + for inp, out in zip(inputs, outputs): + np.testing.assert_equal(pyfunc(inp), out) + + def test_refct_mt(self): + """ + This test exercises the refct in multithreaded code + """ + + def pyfunc(n, inp): + out = np.empty(inp.size) + for i in range(out.size): + out[i] = inp[i] + 1 + # Use swap to trigger many refct ops + for i in range(n): + out, inp = inp, out + return out + + cfunc = nrtjit(pyfunc) + size = 10 + input = np.arange(size, dtype=float) + expected_refct = sys.getrefcount(input) + swapct = random.randrange(1000) + expected = pyfunc(swapct, input) + np.testing.assert_equal(expected, cfunc(swapct, input)) + # The following checks can discover a reference count error + del expected + self.assertEqual(expected_refct, sys.getrefcount(input)) + + workers = [] + outputs = [] + swapcts = [] + + # Make wrapper to store the output + def wrapped(n, input, out): + out[:] = cfunc(n, input) + + # Create worker threads + for i in range(100): + out = np.empty(size) + # All thread shares the same input + swapct = random.randrange(1000) + thread = threading.Thread(target=wrapped, + args=(swapct, input, out), + name="worker{0}".format(i)) + workers.append(thread) + outputs.append(out) + swapcts.append(swapct) + + # Launch worker threads + for thread in workers: + thread.start() + + # Join worker threads + for thread in workers: + thread.join() + + # Check result + for swapct, out in zip(swapcts, outputs): + np.testing.assert_equal(pyfunc(swapct, input), out) + + del outputs, workers + # The following checks can discover a reference count error + self.assertEqual(expected_refct, sys.getrefcount(input)) + + @skip_if_32bit + def test_invalid_size_array(self): + + @njit + def foo(x): + np.empty(x) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(MemoryError) as raises: + foo(types.size_t.maxval // 8 // 2) + + self.assertIn("Allocation failed", str(raises.exception)) + + def test_swap(self): + + def pyfunc(x, y, t): + """Swap array x and y for t number of times + """ + for i in range(t): + x, y = y, x + + return x, y + + + cfunc = nrtjit(pyfunc) + + x = np.random.random(100) + y = np.random.random(100) + + t = 100 + + initrefct = sys.getrefcount(x), sys.getrefcount(y) + expect, got = pyfunc(x, y, t), cfunc(x, y, t) + self.assertIsNone(got[0].base) + self.assertIsNone(got[1].base) + np.testing.assert_equal(expect, got) + del expect, got + self.assertEqual(initrefct, (sys.getrefcount(x), sys.getrefcount(y))) + + def test_return_tuple_of_array(self): + + def pyfunc(x): + y = np.empty(x.size) + for i in range(y.size): + y[i] = x[i] + 1 + return x, y + + cfunc = nrtjit(pyfunc) + + x = np.random.random(5) + initrefct = sys.getrefcount(x) + expected_x, expected_y = pyfunc(x) + got_x, got_y = cfunc(x) + self.assertIs(x, expected_x) + self.assertIs(x, got_x) + np.testing.assert_equal(expected_x, got_x) + np.testing.assert_equal(expected_y, got_y) + del expected_x, got_x + self.assertEqual(initrefct, sys.getrefcount(x)) + + self.assertEqual(sys.getrefcount(expected_y), sys.getrefcount(got_y)) + + def test_return_tuple_of_array_created(self): + + def pyfunc(x): + y = np.empty(x.size) + for i in range(y.size): + y[i] = x[i] + 1 + out = y, y + return out + + cfunc = nrtjit(pyfunc) + + x = np.random.random(5) + expected_x, expected_y = pyfunc(x) + got_x, got_y = cfunc(x) + np.testing.assert_equal(expected_x, got_x) + np.testing.assert_equal(expected_y, got_y) + + if PYVERSION in ((3, 14), ): + expected_refcount = 1 + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + expected_refcount = 2 + else: + raise NotImplementedError(PYVERSION) + + self.assertEqual(expected_refcount, sys.getrefcount(got_y)) + self.assertEqual(expected_refcount, sys.getrefcount(got_x)) + + def test_issue_with_return_leak(self): + """ + Dispatcher returns a new reference. + It need to workaround it for now. + """ + @nrtjit + def inner(out): + return out + + def pyfunc(x): + return inner(x) + + cfunc = nrtjit(pyfunc) + + arr = np.arange(10) + old_refct = sys.getrefcount(arr) + + if PYVERSION in ((3, 14), ): + self.assertEqual(2, sys.getrefcount(pyfunc(arr))) + self.assertEqual(2, sys.getrefcount(cfunc(arr))) + elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + self.assertEqual(old_refct, sys.getrefcount(pyfunc(arr))) + self.assertEqual(old_refct, sys.getrefcount(cfunc(arr))) + else: + raise NotImplementedError(PYVERSION) + + self.assertEqual(old_refct, sys.getrefcount(arr)) + + +class ConstructorBaseTest(NrtRefCtTest): + + def check_0d(self, pyfunc): + cfunc = nrtjit(pyfunc) + expected = pyfunc() + ret = cfunc() + self.assert_array_nrt_refct(ret, 1) + self.assertEqual(ret.size, expected.size) + self.assertEqual(ret.shape, expected.shape) + self.assertEqual(ret.dtype, expected.dtype) + self.assertEqual(ret.strides, expected.strides) + self.check_result_value(ret, expected) + # test writability + expected = np.empty_like(ret) # np.full_like was not added until Numpy 1.8 + expected.fill(123) + ret.fill(123) + np.testing.assert_equal(ret, expected) + + def check_1d(self, pyfunc): + cfunc = nrtjit(pyfunc) + n = 3 + expected = pyfunc(n) + ret = cfunc(n) + self.assert_array_nrt_refct(ret, 1) + self.assertEqual(ret.size, expected.size) + self.assertEqual(ret.shape, expected.shape) + self.assertEqual(ret.dtype, expected.dtype) + self.assertEqual(ret.strides, expected.strides) + self.check_result_value(ret, expected) + # test writability + expected = np.empty_like(ret) # np.full_like was not added until Numpy 1.8 + expected.fill(123) + ret.fill(123) + np.testing.assert_equal(ret, expected) + # errors + with self.assertRaises(ValueError) as cm: + cfunc(-1) + self.assertEqual(str(cm.exception), "negative dimensions not allowed") + + def check_2d(self, pyfunc): + cfunc = nrtjit(pyfunc) + m, n = 2, 3 + expected = pyfunc(m, n) + ret = cfunc(m, n) + self.assert_array_nrt_refct(ret, 1) + self.assertEqual(ret.size, expected.size) + self.assertEqual(ret.shape, expected.shape) + self.assertEqual(ret.dtype, expected.dtype) + self.assertEqual(ret.strides, expected.strides) + self.check_result_value(ret, expected) + # test writability + expected = np.empty_like(ret) # np.full_like was not added until Numpy 1.8 + expected.fill(123) + ret.fill(123) + np.testing.assert_equal(ret, expected) + # errors + with self.assertRaises(ValueError) as cm: + cfunc(2, -1) + self.assertEqual(str(cm.exception), "negative dimensions not allowed") + + def check_alloc_size(self, pyfunc): + """Checks that pyfunc will error, not segfaulting due to array size.""" + cfunc = nrtjit(pyfunc) + with self.assertRaises(ValueError) as e: + cfunc() + self.assertIn( + "array is too big", + str(e.exception) + ) + + +class TestNdZeros(ConstructorBaseTest, TestCase): + + def setUp(self): + super(TestNdZeros, self).setUp() + self.pyfunc = np.zeros + + def check_result_value(self, ret, expected): + np.testing.assert_equal(ret, expected) + + def test_0d(self): + pyfunc = self.pyfunc + def func(): + return pyfunc(()) + self.check_0d(func) + + def test_1d(self): + pyfunc = self.pyfunc + def func(n): + return pyfunc(n) + self.check_1d(func) + + def test_1d_dtype(self): + pyfunc = self.pyfunc + def func(n): + return pyfunc(n, np.int32) + self.check_1d(func) + + def test_1d_dtype_instance(self): + # dtype as numpy dtype, not as scalar class + pyfunc = self.pyfunc + _dtype = np.dtype('int32') + def func(n): + return pyfunc(n, _dtype) + self.check_1d(func) + + def test_1d_dtype_str(self): + pyfunc = self.pyfunc + _dtype = 'int32' + def func(n): + return pyfunc(n, _dtype) + self.check_1d(func) + + def func(n): + return pyfunc(n, 'complex128') + self.check_1d(func) + + def test_1d_dtype_str_alternative_spelling(self): + # like test_1d_dtype_str but using the shorthand type spellings + pyfunc = self.pyfunc + _dtype = 'i4' + def func(n): + return pyfunc(n, _dtype) + self.check_1d(func) + + def func(n): + return pyfunc(n, 'c8') + self.check_1d(func) + + def test_1d_dtype_str_structured_dtype(self): + # test_1d_dtype_str but using a structured dtype + pyfunc = self.pyfunc + _dtype = "i4, (2,3)f8" + def func(n): + return pyfunc(n, _dtype) + self.check_1d(func) + + def test_1d_dtype_non_const_str(self): + pyfunc = self.pyfunc + + @njit + def func(n, dt): + return pyfunc(n, dt) + + with self.assertRaises(TypingError) as raises: + func(5, 'int32') + + excstr = str(raises.exception) + msg = (f"If np.{self.pyfunc.__name__} dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + + def test_1d_dtype_invalid_str(self): + pyfunc = self.pyfunc + + @njit + def func(n): + return pyfunc(n, 'ABCDEF') + + with self.assertRaises(TypingError) as raises: + func(5) + + excstr = str(raises.exception) + self.assertIn("Invalid NumPy dtype specified: 'ABCDEF'", excstr) + + def test_2d(self): + pyfunc = self.pyfunc + def func(m, n): + return pyfunc((m, n)) + self.check_2d(func) + + def test_2d_shape_dtypes(self): + # Test for issue #4575 + pyfunc = self.pyfunc + def func1(m, n): + return pyfunc((np.int16(m), np.int32(n))) + self.check_2d(func1) + # Using a 64-bit value checks that 32 bit systems will downcast to intp + def func2(m, n): + return pyfunc((np.int64(m), np.int8(n))) + self.check_2d(func2) + # Make sure an error is thrown if we can't downcast safely + if config.IS_32BITS: + cfunc = nrtjit(lambda m, n: pyfunc((m, n))) + with self.assertRaises(ValueError): + cfunc(np.int64(1 << (32 - 1)), 1) + + def test_2d_dtype_kwarg(self): + pyfunc = self.pyfunc + def func(m, n): + return pyfunc((m, n), dtype=np.complex64) + self.check_2d(func) + + def test_2d_dtype_str_kwarg(self): + pyfunc = self.pyfunc + def func(m, n): + return pyfunc((m, n), dtype='complex64') + self.check_2d(func) + + def test_2d_dtype_str_kwarg_alternative_spelling(self): + # as test_2d_dtype_str_kwarg but with the numpy shorthand type spelling + pyfunc = self.pyfunc + def func(m, n): + return pyfunc((m, n), dtype='c8') + self.check_2d(func) + + def test_alloc_size(self): + pyfunc = self.pyfunc + width = types.intp.bitwidth + def gen_func(shape, dtype): + return lambda : pyfunc(shape, dtype) + # Under these values numba will segfault, but that's another issue + self.check_alloc_size(gen_func(1 << width - 2, np.intp)) + self.check_alloc_size(gen_func((1 << width - 8, 64), np.intp)) + + +class TestNdOnes(TestNdZeros): + + def setUp(self): + super(TestNdOnes, self).setUp() + self.pyfunc = np.ones + + @unittest.expectedFailure + def test_1d_dtype_str_structured_dtype(self): + super().test_1d_dtype_str_structured_dtype() + + +class TestNdFull(ConstructorBaseTest, TestCase): + + def check_result_value(self, ret, expected): + np.testing.assert_equal(ret, expected) + + def test_0d(self): + def func(): + return np.full((), 4.5) + self.check_0d(func) + + def test_1d(self): + def func(n): + return np.full(n, 4.5) + self.check_1d(func) + + def test_1d_dtype(self): + def func(n): + return np.full(n, 4.5, np.bool_) + self.check_1d(func) + + def test_1d_dtype_instance(self): + dtype = np.dtype('bool') + def func(n): + return np.full(n, 4.5, dtype) + self.check_1d(func) + + def test_1d_dtype_str(self): + def func(n): + return np.full(n, 4.5, 'bool_') + self.check_1d(func) + + def test_1d_dtype_str_alternative_spelling(self): + # like test_1d_dtype_str but using the shorthand type spelling + def func(n): + return np.full(n, 4.5, '?') + self.check_1d(func) + + def test_1d_dtype_non_const_str(self): + + @njit + def func(n, fv, dt): + return np.full(n, fv, dt) + + with self.assertRaises(TypingError) as raises: + func((5,), 4.5, 'int32') + + excstr = str(raises.exception) + msg = ("If np.full dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + + def test_1d_dtype_invalid_str(self): + + @njit + def func(n, fv): + return np.full(n, fv, 'ABCDEF') + + with self.assertRaises(TypingError) as raises: + func((5,), 4.5) + + excstr = str(raises.exception) + self.assertIn("Invalid NumPy dtype specified: 'ABCDEF'", excstr) + + def test_2d(self): + def func(m, n): + return np.full((m, n), 4.5) + self.check_2d(func) + + def test_2d_dtype_kwarg(self): + def func(m, n): + return np.full((m, n), 1 + 4.5j, dtype=np.complex64) + self.check_2d(func) + + def test_2d_dtype_from_type(self): + # tests issue #2862 + def func(m, n): + return np.full((m, n), np.int32(1)) + self.check_2d(func) + + # Complex uses `.real`, imaginary part dropped + def func(m, n): + return np.full((m, n), np.complex128(1)) + self.check_2d(func) + + # and that if a dtype is specified, this influences the return type + def func(m, n): + return np.full((m, n), 1, dtype=np.int8) + self.check_2d(func) + + def test_2d_shape_dtypes(self): + # Test for issue #4575 + def func1(m, n): + return np.full((np.int16(m), np.int32(n)), 4.5) + self.check_2d(func1) + # Using a 64-bit value checks that 32 bit systems will downcast to intp + def func2(m, n): + return np.full((np.int64(m), np.int8(n)), 4.5) + self.check_2d(func2) + # Make sure an error is thrown if we can't downcast safely + if config.IS_32BITS: + cfunc = nrtjit(lambda m, n: np.full((m, n), 4.5)) + with self.assertRaises(ValueError): + cfunc(np.int64(1 << (32 - 1)), 1) + + def test_alloc_size(self): + width = types.intp.bitwidth + def gen_func(shape, value): + return lambda : np.full(shape, value) + # Under these values numba will segfault, but that's another issue + self.check_alloc_size(gen_func(1 << width - 2, 1)) + self.check_alloc_size(gen_func((1 << width - 8, 64), 1)) + + +class ConstructorLikeBaseTest(object): + + def mutate_array(self, arr): + try: + arr.fill(42) + except (TypeError, ValueError): + # Try something else (e.g. Numpy 1.6 with structured dtypes) + fill_value = b'x' * arr.dtype.itemsize + arr.fill(fill_value) + + def check_like(self, pyfunc, dtype): + def check_arr(arr): + expected = pyfunc(arr) + ret = cfunc(arr) + self.assertEqual(ret.size, expected.size) + self.assertEqual(ret.dtype, expected.dtype) + self.assertStridesEqual(ret, expected) + self.check_result_value(ret, expected) + # test writability + self.mutate_array(ret) + self.mutate_array(expected) + np.testing.assert_equal(ret, expected) + + orig = np.linspace(0, 5, 6).astype(dtype) + cfunc = nrtjit(pyfunc) + + for shape in (6, (2, 3), (1, 2, 3), (3, 1, 2), ()): + if shape == (): + arr = orig[-1:].reshape(()) + else: + arr = orig.reshape(shape) + check_arr(arr) + # Non-contiguous array + if arr.ndim > 0: + check_arr(arr[::2]) + # Check new array doesn't inherit readonly flag + arr.flags['WRITEABLE'] = False + # verify read-only + with self.assertRaises(ValueError): + arr[0] = 1 + check_arr(arr) + + # Scalar argument => should produce a 0-d array + check_arr(orig[0]) + + +class TestNdEmptyLike(ConstructorLikeBaseTest, TestCase): + + def setUp(self): + super(TestNdEmptyLike, self).setUp() + self.pyfunc = np.empty_like + + def check_result_value(self, ret, expected): + pass + + def test_like(self): + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr) + self.check_like(func, np.float64) + + def test_like_structured(self): + dtype = np.dtype([('a', np.int16), ('b', np.float32)]) + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr) + self.check_like(func, dtype) + + def test_like_dtype(self): + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, np.int32) + self.check_like(func, np.float64) + + def test_like_dtype_instance(self): + dtype = np.dtype('int32') + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, dtype) + self.check_like(func, np.float64) + + def test_like_dtype_structured(self): + dtype = np.dtype([('a', np.int16), ('b', np.float32)]) + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, dtype) + self.check_like(func, np.float64) + + def test_like_dtype_kwarg(self): + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, dtype=np.int32) + self.check_like(func, np.float64) + + def test_like_dtype_str_kwarg(self): + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, dtype='int32') + self.check_like(func, np.float64) + + def test_like_dtype_str_kwarg_alternative_spelling(self): + pyfunc = self.pyfunc + def func(arr): + return pyfunc(arr, dtype='i4') + self.check_like(func, np.float64) + + def test_like_dtype_non_const_str(self): + pyfunc = self.pyfunc + + @njit + def func(n, dt): + return pyfunc(n, dt) + + with self.assertRaises(TypingError) as raises: + func(np.ones(4), 'int32') + + excstr = str(raises.exception) + msg = (f"If np.{self.pyfunc.__name__} dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + self.assertIn( + '{}(array(float64, 1d, C), unicode_type)'.format(pyfunc.__name__), + excstr) + + def test_like_dtype_invalid_str(self): + pyfunc = self.pyfunc + + @njit + def func(n): + return pyfunc(n, 'ABCDEF') + + with self.assertRaises(TypingError) as raises: + func(np.ones(4)) + + excstr = str(raises.exception) + self.assertIn("Invalid NumPy dtype specified: 'ABCDEF'", excstr) + + +class TestNdZerosLike(TestNdEmptyLike): + + def setUp(self): + super(TestNdZerosLike, self).setUp() + self.pyfunc = np.zeros_like + + def check_result_value(self, ret, expected): + np.testing.assert_equal(ret, expected) + + def test_like_structured(self): + super(TestNdZerosLike, self).test_like_structured() + + def test_like_dtype_structured(self): + super(TestNdZerosLike, self).test_like_dtype_structured() + + +class TestNdOnesLike(TestNdZerosLike): + + def setUp(self): + super(TestNdOnesLike, self).setUp() + self.pyfunc = np.ones_like + self.expected_value = 1 + + # Not supported yet. + + @unittest.expectedFailure + def test_like_structured(self): + super(TestNdOnesLike, self).test_like_structured() + + @unittest.expectedFailure + def test_like_dtype_structured(self): + super(TestNdOnesLike, self).test_like_dtype_structured() + + +class TestNdFullLike(ConstructorLikeBaseTest, TestCase): + + def check_result_value(self, ret, expected): + np.testing.assert_equal(ret, expected) + + def test_like(self): + def func(arr): + return np.full_like(arr, 3.5) + self.check_like(func, np.float64) + + # Not supported yet. + @unittest.expectedFailure + def test_like_structured(self): + dtype = np.dtype([('a', np.int16), ('b', np.float32)]) + def func(arr): + return np.full_like(arr, 4.5) + self.check_like(func, dtype) + + def test_like_dtype(self): + def func(arr): + return np.full_like(arr, 4.5, np.bool_) + self.check_like(func, np.float64) + + def test_like_dtype_instance(self): + dtype = np.dtype('bool') + def func(arr): + return np.full_like(arr, 4.5, dtype) + self.check_like(func, np.float64) + + def test_like_dtype_kwarg(self): + def func(arr): + return np.full_like(arr, 4.5, dtype=np.bool_) + self.check_like(func, np.float64) + + def test_like_dtype_str_kwarg(self): + def func(arr): + return np.full_like(arr, 4.5, 'bool_') + self.check_like(func, np.float64) + + def test_like_dtype_str_kwarg_alternative_spelling(self): + def func(arr): + return np.full_like(arr, 4.5, dtype='?') + self.check_like(func, np.float64) + + def test_like_dtype_non_const_str_kwarg(self): + + @njit + def func(arr, fv, dt): + return np.full_like(arr, fv, dt) + + with self.assertRaises(TypingError) as raises: + func(np.ones(3,), 4.5, 'int32') + + excstr = str(raises.exception) + msg = ("If np.full_like dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + + def test_like_dtype_invalid_str(self): + + @njit + def func(arr, fv): + return np.full_like(arr, fv, "ABCDEF") + + with self.assertRaises(TypingError) as raises: + func(np.ones(4), 3.4) + + excstr = str(raises.exception) + self.assertIn("Invalid NumPy dtype specified: 'ABCDEF'", excstr) + + +class TestNdIdentity(BaseTest): + + def check_identity(self, pyfunc): + self.check_outputs(pyfunc, [(3,)]) + + def test_identity(self): + def func(n): + return np.identity(n) + self.check_identity(func) + + def test_identity_dtype(self): + for dtype in (np.complex64, np.int16, np.bool_, np.dtype('bool'), + 'bool_'): + def func(n): + return np.identity(n, dtype) + self.check_identity(func) + + def test_like_dtype_non_const_str_kwarg(self): + + @njit + def func(n, dt): + return np.identity(n, dt) + + with self.assertRaises(TypingError) as raises: + func(4, 'int32') + + excstr = str(raises.exception) + msg = ("If np.identity dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + + + +class TestNdEye(BaseTest): + + def test_eye_n(self): + def func(n): + return np.eye(n) + self.check_outputs(func, [(1,), (3,)]) + + def test_eye_n_dtype(self): + # check None option, dtype class, instance of dtype class + for dt in (None, np.complex128, np.complex64(1)): + def func(n, dtype=dt): + return np.eye(n, dtype=dtype) + self.check_outputs(func, [(1,), (3,)]) + + def test_eye_n_m(self): + def func(n, m): + return np.eye(n, m) + self.check_outputs(func, [(1, 2), (3, 2), (0, 3)]) + + def check_eye_n_m_k(self, func): + self.check_outputs(func, [(1, 2, 0), + (3, 4, 1), + (3, 4, -1), + (4, 3, -2), + (4, 3, -5), + (4, 3, 5)]) + + def test_eye_n_m_k(self): + def func(n, m, k): + return np.eye(n, m, k) + self.check_eye_n_m_k(func) + + def test_eye_n_m_k_dtype(self): + def func(n, m, k): + return np.eye(N=n, M=m, k=k, dtype=np.int16) + self.check_eye_n_m_k(func) + + def test_eye_n_m_k_dtype_instance(self): + dtype = np.dtype('int16') + def func(n, m, k): + return np.eye(N=n, M=m, k=k, dtype=dtype) + self.check_eye_n_m_k(func) + + +class TestNdDiag(TestCase): + + def setUp(self): + v = np.array([1, 2, 3]) + hv = np.array([[1, 2, 3]]) + vv = np.transpose(hv) + self.vectors = [v, hv, vv] + a3x4 = np.arange(12).reshape(3, 4) + a4x3 = np.arange(12).reshape(4, 3) + self.matricies = [a3x4, a4x3] + def func(q): + return np.diag(q) + self.py = func + self.jit = nrtjit(func) + + def func_kwarg(q, k=0): + return np.diag(q, k=k) + self.py_kw = func_kwarg + self.jit_kw = nrtjit(func_kwarg) + + def check_diag(self, pyfunc, nrtfunc, *args, **kwargs): + expected = pyfunc(*args, **kwargs) + computed = nrtfunc(*args, **kwargs) + self.assertEqual(computed.size, expected.size) + self.assertEqual(computed.dtype, expected.dtype) + # NOTE: stride not tested as np returns a RO view, nb returns new data + np.testing.assert_equal(expected, computed) + + # create a diag matrix from a vector + def test_diag_vect_create(self): + for d in self.vectors: + self.check_diag(self.py, self.jit, d) + + # create a diag matrix from a vector at a given offset + def test_diag_vect_create_kwarg(self): + for k in range(-10, 10): + for d in self.vectors: + self.check_diag(self.py_kw, self.jit_kw, d, k=k) + + # extract the diagonal + def test_diag_extract(self): + for d in self.matricies: + self.check_diag(self.py, self.jit, d) + + # extract a diagonal at a given offset + def test_diag_extract_kwarg(self): + for k in range(-4, 4): + for d in self.matricies: + self.check_diag(self.py_kw, self.jit_kw, d, k=k) + + # check error handling + def test_error_handling(self): + d = np.array([[[1.]]]) + cfunc = nrtjit(self.py) + + # missing arg + with self.assertRaises(TypeError): + cfunc() + + # > 2d + with self.assertRaises(TypingError): + cfunc(d) + with self.assertRaises(TypingError): + dfunc = nrtjit(self.py_kw) + dfunc(d, k=3) + + def test_bad_shape(self): + cfunc = nrtjit(self.py) + msg = '.*The argument "v" must be array-like.*' + with self.assertRaisesRegex(TypingError, msg) as raises: + cfunc(None) + +class TestLinspace(BaseTest): + + def test_linspace_2(self): + def pyfunc(n, m): + return np.linspace(n, m) + self.check_outputs(pyfunc, + [(0, 4), (1, 100), (-3.5, 2.5), (-3j, 2+3j), + (2, 1), (1+0.5j, 1.5j)]) + + def test_linspace_3(self): + def pyfunc(n, m, p): + return np.linspace(n, m, p) + self.check_outputs(pyfunc, + [(0, 4, 9), (1, 4, 3), (-3.5, 2.5, 8), + (-3j, 2+3j, 7), (2, 1, 0), + (1+0.5j, 1.5j, 5), (1, 1e100, 1)]) + + def test_linspace_accuracy(self): + # Checking linspace reasonably replicates NumPy's algorithm + # see https://github.com/numba/numba/issues/6768 + @nrtjit + def foo(n, m, p): + return np.linspace(n, m, p) + + n, m, p = 0.0, 1.0, 100 + self.assertPreciseEqual(foo(n, m, p), foo.py_func(n, m, p)) + + +class TestNpyEmptyKeyword(TestCase): + def _test_with_dtype_kw(self, dtype): + def pyfunc(shape): + return np.empty(shape, dtype=dtype) + + shapes = [1, 5, 9] + + cfunc = nrtjit(pyfunc) + for s in shapes: + expected = pyfunc(s) + got = cfunc(s) + self.assertEqual(expected.dtype, got.dtype) + self.assertEqual(expected.shape, got.shape) + + def test_with_dtype_kws(self): + for dtype in [np.int32, np.float32, np.complex64, np.dtype('complex64')]: + self._test_with_dtype_kw(dtype) + + def _test_with_shape_and_dtype_kw(self, dtype): + def pyfunc(shape): + return np.empty(shape=shape, dtype=dtype) + + shapes = [1, 5, 9] + + cfunc = nrtjit(pyfunc) + for s in shapes: + expected = pyfunc(s) + got = cfunc(s) + self.assertEqual(expected.dtype, got.dtype) + self.assertEqual(expected.shape, got.shape) + + def test_with_shape_and_dtype_kws(self): + for dtype in [np.int32, np.float32, np.complex64, np.dtype('complex64')]: + self._test_with_shape_and_dtype_kw(dtype) + + def test_empty_no_args(self): + + def pyfunc(): + return np.empty() + + cfunc = nrtjit(pyfunc) + + # Trigger the compilation + # That will cause a TypingError due to missing shape argument + with self.assertRaises(TypingError): + cfunc() + + +class TestNpArray(MemoryLeakMixin, BaseTest): + + def test_0d(self): + def pyfunc(arg): + return np.array(arg) + + cfunc = nrtjit(pyfunc) + got = cfunc(42) + self.assertPreciseEqual(got, np.array(42, dtype=np.intp)) + got = cfunc(2.5) + self.assertPreciseEqual(got, np.array(2.5)) + + def test_0d_with_dtype(self): + def pyfunc(arg): + return np.array(arg, dtype=np.int16) + + self.check_outputs(pyfunc, [(42,), (3.5,)]) + + def test_1d(self): + def pyfunc(arg): + return np.array(arg) + + cfunc = nrtjit(pyfunc) + # A list + got = cfunc([2, 3, 42]) + self.assertPreciseEqual(got, np.intp([2, 3, 42])) + # A heterogeneous tuple + got = cfunc((1.0, 2.5j, 42)) + self.assertPreciseEqual(got, np.array([1.0, 2.5j, 42])) + # An empty tuple + got = cfunc(()) + self.assertPreciseEqual(got, np.float64(())) + + def test_1d_with_dtype(self): + def pyfunc(arg): + return np.array(arg, dtype=np.float32) + + self.check_outputs(pyfunc, + [([2, 42],), + ([3.5, 1.0],), + ((1, 3.5, 42),), + ((),), + ]) + + def test_1d_with_str_dtype(self): + def pyfunc(arg): + return np.array(arg, dtype='float32') + + self.check_outputs(pyfunc, + [([2, 42],), + ([3.5, 1.0],), + ((1, 3.5, 42),), + ((),), + ]) + + def test_1d_with_non_const_str_dtype(self): + + @njit + def func(arg, dt): + return np.array(arg, dtype=dt) + + with self.assertRaises(TypingError) as raises: + func((5, 3), 'int32') + + excstr = str(raises.exception) + msg = (f"If np.array dtype is a string it must be a " + "string constant.") + self.assertIn(msg, excstr) + + def test_2d(self): + def pyfunc(arg): + return np.array(arg) + + cfunc = nrtjit(pyfunc) + # A list of tuples + got = cfunc([(1, 2), (3, 4)]) + self.assertPreciseEqual(got, np.intp([[1, 2], [3, 4]])) + got = cfunc([(1, 2.5), (3, 4.5)]) + self.assertPreciseEqual(got, np.float64([[1, 2.5], [3, 4.5]])) + # A tuple of lists + got = cfunc(([1, 2], [3, 4])) + self.assertPreciseEqual(got, np.intp([[1, 2], [3, 4]])) + got = cfunc(([1, 2], [3.5, 4.5])) + self.assertPreciseEqual(got, np.float64([[1, 2], [3.5, 4.5]])) + # A tuple of tuples + got = cfunc(((1.5, 2), (3.5, 4.5))) + self.assertPreciseEqual(got, np.float64([[1.5, 2], [3.5, 4.5]])) + got = cfunc(((), ())) + self.assertPreciseEqual(got, np.float64(((), ()))) + + def test_2d_with_dtype(self): + def pyfunc(arg): + return np.array(arg, dtype=np.int32) + + cfunc = nrtjit(pyfunc) + got = cfunc([(1, 2.5), (3, 4.5)]) + self.assertPreciseEqual(got, np.int32([[1, 2], [3, 4]])) + + def test_raises(self): + + def pyfunc(arg): + return np.array(arg) + + cfunc = nrtjit(pyfunc) + + @contextlib.contextmanager + def check_raises(msg): + with self.assertRaises(TypingError) as raises: + yield + self.assertIn(msg, str(raises.exception)) + + with check_raises(('array(float64, 1d, C) not allowed in a ' + 'homogeneous sequence')): + cfunc(np.array([1.])) + + with check_raises(('type Tuple(int64, reflected list(int64)) ' + 'does not have a regular shape')): + cfunc((np.int64(1), [np.int64(2)])) + + with check_raises( + "cannot convert Tuple(int64, Record(a[type=int32;offset=0]," + "b[type=float32;offset=4];8;False)) to a homogeneous type", + ): + st = np.dtype([('a', 'i4'), ('b', 'f4')]) + val = np.zeros(1, dtype=st)[0] + cfunc(((1, 2), (np.int64(1), val))) + + def test_bad_array(self): + @njit + def func(obj): + return np.array(obj) + + msg = '.*The argument "object" must be array-like.*' + with self.assertRaisesRegex(TypingError, msg) as raises: + func(None) + + def test_bad_dtype(self): + @njit + def func(obj, dt): + return np.array(obj, dt) + + msg = '.*The argument "dtype" must be a data-type if it is provided.*' + with self.assertRaisesRegex(TypingError, msg) as raises: + func(5, 4) + + +class TestNpConcatenate(MemoryLeakMixin, TestCase): + """ + Tests for np.concatenate(). + """ + + def _3d_arrays(self): + a = np.arange(24).reshape((4, 3, 2)) + b = a + 10 + c = (b + 10).copy(order='F') + d = (c + 10)[::-1] + e = (d + 10)[...,::-1] + return a, b, c, d, e + + @contextlib.contextmanager + def assert_invalid_sizes_over_dim(self, axis): + with self.assertRaises(ValueError) as raises: + yield + self.assertIn("input sizes over dimension %d do not match" % axis, + str(raises.exception)) + + def test_3d(self): + pyfunc = np_concatenate2 + cfunc = nrtjit(pyfunc) + + def check(a, b, c, axis): + for ax in (axis, -3 + axis): + expected = pyfunc(a, b, c, axis=ax) + got = cfunc(a, b, c, axis=ax) + self.assertPreciseEqual(got, expected) + + def check_all_axes(a, b, c): + for axis in range(3): + check(a, b, c, axis) + + a, b, c, d, e = self._3d_arrays() + + # Inputs with equal sizes + # C, C, C + check_all_axes(a, b, b) + # C, C, F + check_all_axes(a, b, c) + # F, F, F + check_all_axes(a.T, b.T, a.T) + # F, F, C + check_all_axes(a.T, b.T, c.T) + # F, F, A + check_all_axes(a.T, b.T, d.T) + # A, A, A + # (note Numpy may select the layout differently for other inputs) + check_all_axes(d.T, e.T, d.T) + + # Inputs with compatible sizes + check(a[1:], b, c[::-1], axis=0) + check(a, b[:,1:], c, axis=1) + check(a, b, c[:,:,1:], axis=2) + + # Different but compatible dtypes + check_all_axes(a, b.astype(np.float64), b) + + # Exceptions leak references + self.disable_leak_check() + + # Incompatible sizes + for axis in (1, 2, -2, -1): + with self.assert_invalid_sizes_over_dim(0): + cfunc(a[1:], b, b, axis) + for axis in (0, 2, -3, -1): + with self.assert_invalid_sizes_over_dim(1): + cfunc(a, b[:,1:], b, axis) + + def test_3d_no_axis(self): + pyfunc = np_concatenate1 + cfunc = nrtjit(pyfunc) + + def check(a, b, c): + expected = pyfunc(a, b, c) + got = cfunc(a, b, c) + self.assertPreciseEqual(got, expected) + + a, b, c, d, e = self._3d_arrays() + + # Inputs with equal sizes + # C, C, C + check(a, b, b) + # C, C, F + check(a, b, c) + # F, F, F + check(a.T, b.T, a.T) + # F, F, C + check(a.T, b.T, c.T) + # F, F, A + check(a.T, b.T, d.T) + # A, A, A + # (note Numpy may select the layout differently for other inputs) + check(d.T, e.T, d.T) + + # Inputs with compatible sizes + check(a[1:], b, c[::-1]) + + # Exceptions leak references + self.disable_leak_check() + + # Incompatible sizes + with self.assert_invalid_sizes_over_dim(1): + cfunc(a, b[:,1:], b) + + def test_typing_errors(self): + pyfunc = np_concatenate1 + cfunc = nrtjit(pyfunc) + + a = np.arange(15) + b = a.reshape((3, 5)) + c = a.astype(np.dtype([('x', np.int8)])) + d = np.array(42) + + # Different dimensionalities + with self.assertTypingError() as raises: + cfunc(a, b, b) + self.assertIn("all the input arrays must have same number of dimensions", + str(raises.exception)) + + # Incompatible dtypes + with self.assertTypingError() as raises: + cfunc(a, c, c) + self.assertIn("input arrays must have compatible dtypes", + str(raises.exception)) + + # 0-d arrays + with self.assertTypingError() as raises: + cfunc(d, d, d) + self.assertIn("zero-dimensional arrays cannot be concatenated", + str(raises.exception)) + + # non-tuple input + with self.assertTypingError() as raises: + cfunc(c, 1, c) + self.assertIn('expecting a non-empty tuple of arrays', str(raises.exception)) + + +@unittest.skipUnless(hasattr(np, "stack"), "this Numpy doesn't have np.stack()") +class TestNpStack(MemoryLeakMixin, TestCase): + """ + Tests for np.stack(). + """ + + def _3d_arrays(self): + a = np.arange(24).reshape((4, 3, 2)) + b = a + 10 + c = (b + 10).copy(order='F') + d = (c + 10)[::-1] + e = (d + 10)[...,::-1] + return a, b, c, d, e + + @contextlib.contextmanager + def assert_invalid_sizes(self): + with self.assertRaises(ValueError) as raises: + yield + self.assertIn("all input arrays must have the same shape", + str(raises.exception)) + + def check_stack(self, pyfunc, cfunc, args): + expected = pyfunc(*args) + got = cfunc(*args) + # Numba doesn't choose the same layout as Numpy. + # We would like to check the result is contiguous, but we can't + # rely on the "flags" attribute when there are 1-sized + # dimensions. + self.assertEqual(got.shape, expected.shape) + self.assertPreciseEqual(got.flatten(), expected.flatten()) + + def check_3d(self, pyfunc, cfunc, generate_starargs): + def check(a, b, c, args): + self.check_stack(pyfunc, cfunc, (a, b, c) + args) + + def check_all_axes(a, b, c): + for args in generate_starargs(): + check(a, b, c, args) + + a, b, c, d, e = self._3d_arrays() + + # C, C, C + check_all_axes(a, b, b) + # C, C, F + check_all_axes(a, b, c) + # F, F, F + check_all_axes(a.T, b.T, a.T) + # F, F, C + check_all_axes(a.T, b.T, c.T) + # F, F, A + check_all_axes(a.T, b.T, d.T) + # A, A, A + check_all_axes(d.T, e.T, d.T) + + # Different but compatible dtypes + check_all_axes(a, b.astype(np.float64), b) + + def check_runtime_errors(self, cfunc, generate_starargs): + # Exceptions leak references + self.assert_no_memory_leak() + self.disable_leak_check() + + # Inputs have different shapes + a, b, c, d, e = self._3d_arrays() + with self.assert_invalid_sizes(): + args = next(generate_starargs()) + cfunc(a[:-1], b, c, *args) + + def test_3d(self): + """ + stack(3d arrays, axis) + """ + pyfunc = np_stack2 + cfunc = nrtjit(pyfunc) + + def generate_starargs(): + for axis in range(3): + yield (axis,) + yield (-3 + axis,) + + self.check_3d(pyfunc, cfunc, generate_starargs) + self.check_runtime_errors(cfunc, generate_starargs) + + def test_3d_no_axis(self): + """ + stack(3d arrays) + """ + pyfunc = np_stack1 + cfunc = nrtjit(pyfunc) + + def generate_starargs(): + yield() + + self.check_3d(pyfunc, cfunc, generate_starargs) + self.check_runtime_errors(cfunc, generate_starargs) + + def test_0d(self): + """ + stack(0d arrays) + """ + pyfunc = np_stack1 + cfunc = nrtjit(pyfunc) + + a = np.array(42) + b = np.array(-5j) + c = np.array(True) + + self.check_stack(pyfunc, cfunc, (a, b, c)) + + def check_xxstack(self, pyfunc, cfunc): + """ + 3d and 0d tests for hstack(), vstack(), dstack(). + """ + def generate_starargs(): + yield() + + self.check_3d(pyfunc, cfunc, generate_starargs) + # 0d + a = np.array(42) + b = np.array(-5j) + c = np.array(True) + self.check_stack(pyfunc, cfunc, (a, b, a)) + + def test_hstack(self): + pyfunc = np_hstack + cfunc = nrtjit(pyfunc) + + self.check_xxstack(pyfunc, cfunc) + # 1d + a = np.arange(5) + b = np.arange(6) + 10 + self.check_stack(pyfunc, cfunc, (a, b, b)) + # 2d + a = np.arange(6).reshape((2, 3)) + b = np.arange(8).reshape((2, 4)) + 100 + self.check_stack(pyfunc, cfunc, (a, b, a)) + + def test_vstack(self): + # Since np.row_stack is an alias for np.vstack, it does not need a + # separate Numba implementation. For every test for np.vstack, the same + # test for np.row_stack has been added. + functions = [np_vstack, np_row_stack] + for pyfunc in functions: + cfunc = nrtjit(pyfunc) + + self.check_xxstack(pyfunc, cfunc) + # 1d + a = np.arange(5) + b = a + 10 + self.check_stack(pyfunc, cfunc, (a, b, b)) + # 2d + a = np.arange(6).reshape((3, 2)) + b = np.arange(8).reshape((4, 2)) + 100 + self.check_stack(pyfunc, cfunc, (a, b, b)) + + def test_dstack(self): + pyfunc = np_dstack + cfunc = nrtjit(pyfunc) + + self.check_xxstack(pyfunc, cfunc) + # 1d + a = np.arange(5) + b = a + 10 + self.check_stack(pyfunc, cfunc, (a, b, b)) + # 2d + a = np.arange(12).reshape((3, 4)) + b = a + 100 + self.check_stack(pyfunc, cfunc, (a, b, b)) + + def test_column_stack(self): + pyfunc = np_column_stack + cfunc = nrtjit(pyfunc) + + a = np.arange(4) + b = a + 10 + c = np.arange(12).reshape((4, 3)) + self.check_stack(pyfunc, cfunc, (a, b, c)) + + # Exceptions leak references + self.assert_no_memory_leak() + self.disable_leak_check() + + # Invalid dims + a = np.array(42) + with self.assertTypingError(): + cfunc((a, a, a)) + a = a.reshape((1, 1, 1)) + with self.assertTypingError(): + cfunc((a, a, a)) + + def test_bad_arrays(self): + for pyfunc in (np_stack1, np_hstack, np_vstack, np_dstack, np_column_stack): + cfunc = nrtjit(pyfunc) + c = np.arange(12).reshape((4, 3)) + + # non-tuple input + with self.assertTypingError() as raises: + cfunc(c, 1, c) + self.assertIn('expecting a non-empty tuple of arrays', str(raises.exception)) + + +def benchmark_refct_speed(): + def pyfunc(x, y, t): + """Swap array x and y for t number of times + """ + for i in range(t): + x, y = y, x + return x, y + + cfunc = nrtjit(pyfunc) + + x = np.random.random(100) + y = np.random.random(100) + t = 10000 + + def bench_pyfunc(): + pyfunc(x, y, t) + + def bench_cfunc(): + cfunc(x, y, t) + + python_time = utils.benchmark(bench_pyfunc) + numba_time = utils.benchmark(bench_cfunc) + print(python_time) + print(numba_time) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_event.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_event.py new file mode 100644 index 0000000000000000000000000000000000000000..dce8b01226fe7f0fb4e48a442e91bbfc0098a0a4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_event.py @@ -0,0 +1,218 @@ +import unittest +import string + +import numpy as np + +from numba import njit, jit, literal_unroll +from numba.core import event as ev +from numba.tests.support import TestCase, override_config +from numba.core.utils import _lazy_pformat + + +class TestEvent(TestCase): + + def setUp(self): + # Trigger compilation to ensure all listeners are initialized + njit(lambda: None)() + self.__registered_listeners = len(ev._registered) + + def tearDown(self): + # Check there is no lingering listeners + self.assertEqual(len(ev._registered), self.__registered_listeners) + + def test_recording_listener(self): + @njit + def foo(x): + return x + x + + with ev.install_recorder("numba:compile") as rec: + foo(1) + + self.assertIsInstance(rec, ev.RecordingListener) + # Check there must be at least two events. + # Because there must be a START and END for the compilation of foo() + self.assertGreaterEqual(len(rec.buffer), 2) + + def test_compiler_lock_event(self): + @njit + def foo(x): + return x + x + + foo(1) + md = foo.get_metadata(foo.signatures[0]) + lock_duration = md['timers']['compiler_lock'] + self.assertIsInstance(lock_duration, float) + self.assertGreater(lock_duration, 0) + + def test_llvm_lock_event(self): + @njit + def foo(x): + return x + x + + foo(1) + md = foo.get_metadata(foo.signatures[0]) + lock_duration = md['timers']['llvm_lock'] + self.assertIsInstance(lock_duration, float) + self.assertGreater(lock_duration, 0) + + def test_run_pass_event(self): + @njit + def foo(x): + return x + x + + with ev.install_recorder("numba:run_pass") as recorder: + foo(2) + + self.assertGreater(len(recorder.buffer), 0) + for _, event in recorder.buffer: + # Check that all fields are there + data = event.data + self.assertIsInstance(data['name'], str) + self.assertIsInstance(data['qualname'], str) + self.assertIsInstance(data['module'], str) + self.assertIsInstance(data['flags'], _lazy_pformat) + self.assertIsInstance(data['args'], str) + self.assertIsInstance(data['return_type'], str) + + def test_install_listener(self): + ut = self + + class MyListener(ev.Listener): + def on_start(self, event): + ut.assertEqual(event.status, ev.EventStatus.START) + ut.assertEqual(event.kind, "numba:compile") + ut.assertIs(event.data["dispatcher"], foo) + dispatcher = event.data["dispatcher"] + ut.assertIs(dispatcher, foo) + # Check that the compiling signature is NOT in the overloads + ut.assertNotIn(event.data["args"], dispatcher.overloads) + + def on_end(self, event): + ut.assertEqual(event.status, ev.EventStatus.END) + ut.assertEqual(event.kind, "numba:compile") + dispatcher = event.data["dispatcher"] + ut.assertIs(dispatcher, foo) + # Check that the compiling signature is in the overloads + ut.assertIn(event.data["args"], dispatcher.overloads) + + @njit + def foo(x): + return x + + listener = MyListener() + with ev.install_listener("numba:compile", listener) as yielded: + foo(1) + + # Check that the yielded value is the same listener + self.assertIs(listener, yielded) + + def test_global_register(self): + ut = self + + class MyListener(ev.Listener): + def on_start(self, event): + ut.assertEqual(event.status, ev.EventStatus.START) + ut.assertEqual(event.kind, "numba:compile") + # Check it is the same dispatcher + dispatcher = event.data["dispatcher"] + ut.assertIs(dispatcher, foo) + # Check that the compiling signature is NOT in the overloads + ut.assertNotIn(event.data["args"], dispatcher.overloads) + + def on_end(self, event): + ut.assertEqual(event.status, ev.EventStatus.END) + ut.assertEqual(event.kind, "numba:compile") + # Check it is the same dispatcher + dispatcher = event.data["dispatcher"] + ut.assertIs(dispatcher, foo) + # Check that the compiling signature is in the overloads + ut.assertIn(event.data["args"], dispatcher.overloads) + + @njit + def foo(x): + return x + + listener = MyListener() + ev.register("numba:compile", listener) + foo(1) + ev.unregister("numba:compile", listener) + + def test_lifted_dispatcher(self): + @jit(forceobj=True) + def foo(): + object() # to trigger loop-lifting + c = 0 + for i in range(10): + c += i + return c + + with ev.install_recorder("numba:compile") as rec: + foo() + + # Check that there are 4 events. + # Two for `foo()` and two for the lifted loop. + self.assertGreaterEqual(len(rec.buffer), 4) + + cres = foo.overloads[foo.signatures[0]] + [ldisp] = cres.lifted + + lifted_cres = ldisp.overloads[ldisp.signatures[0]] + self.assertIsInstance( + lifted_cres.metadata["timers"]["compiler_lock"], + float, + ) + self.assertIsInstance( + lifted_cres.metadata["timers"]["llvm_lock"], + float, + ) + + def test_timing_properties(self): + a = tuple(string.ascii_lowercase) + + @njit + def bar(x): + acc = 0 + for i in literal_unroll(a): + if i in {'1': x}: + acc += 1 + else: + acc += np.sqrt(x[0, 0]) + return np.sin(x), acc + + @njit + def foo(x): + return bar(np.zeros((x, x))) + + with override_config('LLVM_PASS_TIMINGS', True): + foo(1) + + def get_timers(fn, prop): + md = fn.get_metadata(fn.signatures[0]) + return md[prop] + + foo_timers = get_timers(foo, 'timers') + bar_timers = get_timers(bar, 'timers') + foo_llvm_timer = get_timers(foo, 'llvm_pass_timings') + bar_llvm_timer = get_timers(bar, 'llvm_pass_timings') + + # Check: time spent in bar() must be longer than in foo() + self.assertLess(bar_timers['llvm_lock'], + foo_timers['llvm_lock']) + self.assertLess(bar_timers['compiler_lock'], + foo_timers['compiler_lock']) + + # Check: time spent in LLVM itself must be less than in the LLVM lock + self.assertLess(foo_llvm_timer.get_total_time(), + foo_timers['llvm_lock']) + self.assertLess(bar_llvm_timer.get_total_time(), + bar_timers['llvm_lock']) + + # Check: time spent in LLVM lock must be less than in compiler + self.assertLess(foo_timers['llvm_lock'], + foo_timers['compiler_lock']) + self.assertLess(bar_timers['llvm_lock'], + bar_timers['compiler_lock']) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_firstlinefinder.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_firstlinefinder.py new file mode 100644 index 0000000000000000000000000000000000000000..cda4c0a33553fa095969db6e3f5aaaaa2ef36382 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_firstlinefinder.py @@ -0,0 +1,221 @@ +import unittest +import linecache +import inspect +import textwrap + +from numba import njit +from numba.tests.support import TestCase +from numba.misc.firstlinefinder import get_func_body_first_lineno + + +class TestFirstLineFinder(TestCase): + """ + The following methods contains tests that are sensitive to the source + locations w.r.t. the beginning of each method. + """ + + def _get_grandparent_caller_code(self): + frame = inspect.currentframe() + caller_frame = inspect.getouterframes(frame) + return caller_frame[2].frame.f_code + + def assert_line_location(self, expected, offset_from_caller): + grandparent_co = self._get_grandparent_caller_code() + lno = grandparent_co.co_firstlineno + self.assertEqual(expected, lno + offset_from_caller) + + def test_decorated_odd_comment_indent(self): + @njit + def foo(): +# NOTE: THIS COMMENT MUST START AT COLUMN 0 FOR THIS SAMPLE CODE TO BE VALID # noqa: E115, E501 + return 1 + + first_def_line = get_func_body_first_lineno(foo) + self.assert_line_location(first_def_line, 4) + + def test_undecorated_odd_comment_indent(self): + def foo(): +# NOTE: THIS COMMENT MUST START AT COLUMN 0 FOR THIS SAMPLE CODE TO BE VALID # noqa: E115, E501 + return 1 + + first_def_line = get_func_body_first_lineno(njit(foo)) + self.assert_line_location(first_def_line, 3) + + def test_unnamed_lambda(self): + foo = lambda: 1 + first_def_line = get_func_body_first_lineno(njit(foo)) + # Cannot determine first line of lambda function + self.assertIsNone(first_def_line) + + def test_nested_function(self): + def foo(): + @njit + def foo(): + # This function is intentionally named the same as the parent + return 1 + + return foo + + inner = foo() + first_def_line = get_func_body_first_lineno(inner) + self.assert_line_location(first_def_line, 5) + + def test_pass_statement(self): + @njit + def foo(): + pass + + first_def_line = get_func_body_first_lineno(foo) + self.assert_line_location(first_def_line, 3) + + def test_string_eval(self): + source = """def foo(): + pass + """ + + globalns = {} + exec(source, globalns) + foo = globalns['foo'] + + first_def_line = get_func_body_first_lineno(foo) + # Cannot determine first line of string evaled functions + self.assertIsNone(first_def_line) + + def _test_with_patched_linecache(self, filename, source, + function_name, expected_first_line): + # Modify the line cache in a similar manner to Jupyter, so that + # get_func_body_first_lineno can find the code using the fallback to + # inspect.getsourcelines() + timestamp = None + entry = (len(source), timestamp, source.splitlines(True), filename) + linecache.cache[filename] = entry + + # We need to compile the code so we can give it the fake filename used + # in the linecache + code = compile(source, filename, "exec") + + globalns = {} + exec(code, globalns) + function = globalns[function_name] + + # We should be able to determine the first line number even though the + # source does not exist on disk + first_def_line = get_func_body_first_lineno(function) + self.assertEqual(first_def_line, expected_first_line) + + def test_string_eval_linecache_basic(self): + source = """def foo(): + pass + """ + + filename = "" + function_name = "foo" + expected_first_line = 2 + self._test_with_patched_linecache(filename, source, function_name, + expected_first_line) + + def test_string_eval_linecache_indent(self): + source = """if True: + # indent designed to test against potential indent error in ast.parse + + def foo(): + pass + """ + + filename = "" + function_name = "foo" + expected_first_line = 5 + self._test_with_patched_linecache(filename, source, function_name, + expected_first_line) + + def test_string_eval_linecache_closure(self): + source = textwrap.dedent(""" + def foo_gen(): + def foo(): + pass + return foo + + generated_foo = foo_gen() + """) + + filename = "" + function_name = "generated_foo" + expected_first_line = 4 + self._test_with_patched_linecache(filename, source, function_name, + expected_first_line) + + def test_string_eval_linecache_stacked_decorators(self): + source = textwrap.dedent(""" + def decorator(function): + return function + + @decorator + @decorator + @decorator + def decorated(): + pass + """) + + filename = "" + function_name = "decorated" + expected_first_line = 9 + self._test_with_patched_linecache(filename, source, function_name, + expected_first_line) + + def test_string_eval_linecache_all(self): + # A test combining indented code, a closure, and stacked decorators + source = """if 1: + def decorator(function): + return function + + def gen_decorated_foo(): + @decorator + @decorator + @decorator + def _foo(): + pass + + return _foo + + foo_all = gen_decorated_foo() + """ + + filename = "" + function_name = "foo_all" + expected_first_line = 10 + self._test_with_patched_linecache(filename, source, function_name, + expected_first_line) + + def test_single_line_function(self): + @njit + def foo(): pass # noqa: E704 + + first_def_line = get_func_body_first_lineno(foo) + self.assert_line_location(first_def_line, 2) + + def test_docstring(self): + @njit + def foo(): + """Docstring + """ + pass + + first_def_line = get_func_body_first_lineno(foo) + self.assert_line_location(first_def_line, 5) + + def test_docstring_2(self): + @njit + def foo(): + """Docstring + """ + """Not Docstring, but a bare string literal + """ + pass + # Variation on test_docstring but with a "fake" docstring following + # the true docstring. + first_def_line = get_func_body_first_lineno(foo) + self.assert_line_location(first_def_line, 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_func_lifetime.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_func_lifetime.py new file mode 100644 index 0000000000000000000000000000000000000000..5624b57047bda17d17f21db4335d7691f2f0c0ad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_func_lifetime.py @@ -0,0 +1,164 @@ +import gc +import weakref + +from numba import jit +from numba.core import types +from numba.tests.support import TestCase +import unittest + + +class Dummy(object): + + def __add__(self, other): + return other + 5 + + +def global_usecase1(x): + return x + 1 + +def global_usecase2(): + return global_obj + 1 + + +class TestFuncLifetime(TestCase): + """ + Test the lifetime of compiled function objects and their dependencies. + """ + + def get_impl(self, dispatcher): + """ + Get the single implementation (a C function object) of a dispatcher. + """ + self.assertEqual(len(dispatcher.overloads), 1) + cres = list(dispatcher.overloads.values())[0] + return cres.entry_point + + def check_local_func_lifetime(self, **jitargs): + def f(x): + return x + 1 + + c_f = jit('int32(int32)', **jitargs)(f) + self.assertPreciseEqual(c_f(1), 2) + + cfunc = self.get_impl(c_f) + + # Since we can't take a weakref to a C function object + # (see http://bugs.python.org/issue22116), ensure it's + # collected by taking a weakref to its __self__ instead + # (a _dynfunc._Closure object). + refs = [weakref.ref(obj) for obj in (f, c_f, cfunc.__self__)] + obj = f = c_f = cfunc = None + gc.collect() + self.assertEqual([wr() for wr in refs], [None] * len(refs)) + + def test_local_func_lifetime(self): + self.check_local_func_lifetime(forceobj=True) + + def test_local_func_lifetime_npm(self): + self.check_local_func_lifetime(nopython=True) + + def check_global_func_lifetime(self, **jitargs): + c_f = jit(**jitargs)(global_usecase1) + self.assertPreciseEqual(c_f(1), 2) + + cfunc = self.get_impl(c_f) + + wr = weakref.ref(c_f) + refs = [weakref.ref(obj) for obj in (c_f, cfunc.__self__)] + obj = c_f = cfunc = None + gc.collect() + self.assertEqual([wr() for wr in refs], [None] * len(refs)) + + def test_global_func_lifetime(self): + self.check_global_func_lifetime(forceobj=True) + + def test_global_func_lifetime_npm(self): + self.check_global_func_lifetime(nopython=True) + + def check_global_obj_lifetime(self, **jitargs): + # Since global objects can be recorded for typing purposes, + # check that they are not kept around after they are removed + # from the globals. + global global_obj + global_obj = Dummy() + + c_f = jit(**jitargs)(global_usecase2) + self.assertPreciseEqual(c_f(), 6) + + refs = [weakref.ref(obj) for obj in (c_f, global_obj)] + obj = c_f = global_obj = None + gc.collect() + self.assertEqual([wr() for wr in refs], [None] * len(refs)) + + def test_global_obj_lifetime(self): + self.check_global_obj_lifetime(forceobj=True) + + def check_inner_function_lifetime(self, **jitargs): + """ + When a jitted function calls into another jitted function, check + that everything is collected as desired. + """ + def mult_10(a): + return a * 10 + + c_mult_10 = jit('intp(intp)', **jitargs)(mult_10) + c_mult_10.disable_compile() + + def do_math(x): + return c_mult_10(x + 4) + + c_do_math = jit('intp(intp)', **jitargs)(do_math) + c_do_math.disable_compile() + + self.assertEqual(c_do_math(1), 50) + + wrs = [weakref.ref(obj) for obj in + (mult_10, c_mult_10, do_math, c_do_math, + self.get_impl(c_mult_10).__self__, + self.get_impl(c_do_math).__self__, + )] + obj = mult_10 = c_mult_10 = do_math = c_do_math = None + gc.collect() + self.assertEqual([w() for w in wrs], [None] * len(wrs)) + + def test_inner_function_lifetime(self): + self.check_inner_function_lifetime(forceobj=True) + + def test_inner_function_lifetime_npm(self): + self.check_inner_function_lifetime(nopython=True) + + +class TestLifeTimeIssue(TestCase): + def test_double_free(self): + from numba import njit + import numpy as np + + # This is the function that causes the crash + + @njit + def is_point_in_polygons(point, polygons): + num_polygons = polygons.shape[0] + if num_polygons != 0: + # An extra decref is inserted in this block + intentionally_unused_variable = polygons[0] + return 0 + + # This function creates some NRT objects for the previous function + # to corrupt. + + @njit + def dummy(): + return np.empty(10, dtype=np.int64) + + polygons = np.array([[[0, 1]]]) + points = np.array([[-1.5, 0.5]]) + a = dummy() + is_point_in_polygons(points[0], polygons) + b = dummy() + # Crash happens at second call + is_point_in_polygons(points[0], polygons) + c = dummy() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_generators.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_generators.py new file mode 100644 index 0000000000000000000000000000000000000000..9258a22c723476fc58ffe08c45e974be93232509 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_generators.py @@ -0,0 +1,661 @@ +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.core.datamodel.testing import test_factory + +forceobj_flags = {'nopython': False, 'forceobj': True} +nopython_flags = {'nopython': True} + + +def make_consumer(gen_func): + def consumer(x): + res = 0.0 + for y in gen_func(x): + res += y + return res + + return consumer + + +def gen1(x): + for i in range(x): + yield i + + +def gen2(x): + for i in range(x): + yield i + for j in range(1, 3): + yield i + j + + +def gen3(x): + # Polymorphic yield types must be unified + yield x + yield x + 1.5 + yield x + 1j + + +def gen4(x, y, z): + for i in range(3): + yield z + yield y + z + return + yield x + + +def gen5(): + # The bytecode for this generator doesn't contain any YIELD_VALUE + # (it's optimized away). We fail typing it, since the yield type + # is entirely undefined. + if 0: + yield 1 + + +def gen6(a, b): + # Infinite loop: exercise computation of state variables + x = a + 1 + while True: + y = b + 2 + yield x + y + + +def gen7(arr): + # Array variable in generator state + for i in range(arr.size): + yield arr[i] + + +# Optional arguments and boolean state members +def gen8(x=1, y=2, b=False): + bb = not b + yield x + if bb: + yield y + if b: + yield x + y + + +def genobj(x): + object() + yield x + + +def return_generator_expr(x): + return (i * 2 for i in x) + + +def gen_ndindex(shape): + for ind in np.ndindex(shape): + yield ind + + +def gen_flat(arr): + for val in arr.flat: + yield val + + +def gen_ndenumerate(arr): + for tup in np.ndenumerate(arr): + yield tup + + +def gen_bool(): + yield True + + +def gen_unification_error(): + yield None + yield 1j + + +def gen_optional_and_type_unification_error(): + # yields complex and optional(literalint) + i = 0 + yield 1j + while True: + i = yield i + + +def gen_changing_tuple_type(): + # https://github.com/numba/numba/issues/7295 + yield 1, 2 + yield 3, 4 + + +def gen_changing_number_type(): + # additional test for https://github.com/numba/numba/issues/7295 + yield 1 + yield 3.5 + yield 67.8j + + +class TestGenerators(MemoryLeakMixin, TestCase): + def check_generator(self, pygen, cgen): + self.assertEqual(next(cgen), next(pygen)) + # Use list comprehensions to make sure we trash the generator's + # former C stack. + expected = [x for x in pygen] + got = [x for x in cgen] + self.assertEqual(expected, got) + with self.assertRaises(StopIteration): + next(cgen) + + def check_gen1(self, **kwargs): + pyfunc = gen1 + cr = jit((types.int32,), **kwargs)(pyfunc) + pygen = pyfunc(8) + cgen = cr(8) + self.check_generator(pygen, cgen) + + def test_gen1(self): + self.check_gen1(**nopython_flags) + + def test_gen1_objmode(self): + self.check_gen1(**forceobj_flags) + + def check_gen2(self, **kwargs): + pyfunc = gen2 + cr = jit((types.int32,), **kwargs)(pyfunc) + pygen = pyfunc(8) + cgen = cr(8) + self.check_generator(pygen, cgen) + + def test_gen2(self): + self.check_gen2(**nopython_flags) + + def test_gen2_objmode(self): + self.check_gen2(**forceobj_flags) + + def check_gen3(self, **kwargs): + pyfunc = gen3 + cr = jit((types.int32,), **kwargs)(pyfunc) + pygen = pyfunc(8) + cgen = cr(8) + self.check_generator(pygen, cgen) + + def test_gen3(self): + self.check_gen3(**nopython_flags) + + def test_gen3_objmode(self): + self.check_gen3(**forceobj_flags) + + def check_gen4(self, **kwargs): + pyfunc = gen4 + cr = jit((types.int32,) * 3, **kwargs)(pyfunc) + pygen = pyfunc(5, 6, 7) + cgen = cr(5, 6, 7) + self.check_generator(pygen, cgen) + + def test_gen4(self): + self.check_gen4(**nopython_flags) + + def test_gen4_objmode(self): + self.check_gen4(**forceobj_flags) + + def test_gen5(self): + with self.assertTypingError() as raises: + jit((), **nopython_flags)(gen5) + self.assertIn("Cannot type generator: it does not yield any value", + str(raises.exception)) + + def test_gen5_objmode(self): + cgen = jit((), **forceobj_flags)(gen5)() + self.assertEqual(list(cgen), []) + with self.assertRaises(StopIteration): + next(cgen) + + def check_gen6(self, **kwargs): + cr = jit((types.int32,) * 2, **kwargs)(gen6) + cgen = cr(5, 6) + l = [] + for i in range(3): + l.append(next(cgen)) + self.assertEqual(l, [14] * 3) + + def test_gen6(self): + self.check_gen6(**nopython_flags) + + def test_gen6_objmode(self): + self.check_gen6(**forceobj_flags) + + def check_gen7(self, **kwargs): + pyfunc = gen7 + cr = jit((types.Array(types.float64, 1, 'C'),), **kwargs)(pyfunc) + arr = np.linspace(1, 10, 7) + pygen = pyfunc(arr.copy()) + cgen = cr(arr) + self.check_generator(pygen, cgen) + + def test_gen7(self): + self.check_gen7(**nopython_flags) + + def test_gen7_objmode(self): + self.check_gen7(**forceobj_flags) + + def check_gen8(self, **jit_args): + pyfunc = gen8 + cfunc = jit(**jit_args)(pyfunc) + + def check(*args, **kwargs): + self.check_generator(pyfunc(*args, **kwargs), + cfunc(*args, **kwargs)) + + check(2, 3) + check(4) + check(y=5) + check(x=6, b=True) + + def test_gen8(self): + self.check_gen8(nopython=True) + + def test_gen8_objmode(self): + self.check_gen8(forceobj=True) + + def check_gen9(self, **kwargs): + pyfunc = gen_bool + cr = jit((), **kwargs)(pyfunc) + pygen = pyfunc() + cgen = cr() + self.check_generator(pygen, cgen) + + def test_gen9(self): + self.check_gen9(**nopython_flags) + + def test_gen9_objmode(self): + self.check_gen9(**forceobj_flags) + + def check_consume_generator(self, gen_func): + cgen = jit(nopython=True)(gen_func) + cfunc = jit(nopython=True)(make_consumer(cgen)) + pyfunc = make_consumer(gen_func) + expected = pyfunc(5) + got = cfunc(5) + self.assertPreciseEqual(got, expected) + + def test_consume_gen1(self): + self.check_consume_generator(gen1) + + def test_consume_gen2(self): + self.check_consume_generator(gen2) + + def test_consume_gen3(self): + self.check_consume_generator(gen3) + + # Check generator storage of some types + + def check_ndindex(self, **kwargs): + pyfunc = gen_ndindex + cr = jit((types.UniTuple(types.intp, 2),), **kwargs)(pyfunc) + shape = (2, 3) + pygen = pyfunc(shape) + cgen = cr(shape) + self.check_generator(pygen, cgen) + + def test_ndindex(self): + self.check_ndindex(**nopython_flags) + + def test_ndindex_objmode(self): + self.check_ndindex(**forceobj_flags) + + def check_np_flat(self, pyfunc, **kwargs): + cr = jit((types.Array(types.int32, 2, "C"),), **kwargs)(pyfunc) + arr = np.arange(6, dtype=np.int32).reshape((2, 3)) + self.check_generator(pyfunc(arr), cr(arr)) + crA = jit((types.Array(types.int32, 2, "A"),), **kwargs)(pyfunc) + arr = arr.T + self.check_generator(pyfunc(arr), crA(arr)) + + def test_np_flat(self): + self.check_np_flat(gen_flat, **nopython_flags) + + def test_np_flat_objmode(self): + self.check_np_flat(gen_flat, **forceobj_flags) + + def test_ndenumerate(self): + self.check_np_flat(gen_ndenumerate, **nopython_flags) + + def test_ndenumerate_objmode(self): + self.check_np_flat(gen_ndenumerate, **forceobj_flags) + + def test_type_unification_error(self): + pyfunc = gen_unification_error + with self.assertTypingError() as raises: + jit((), **nopython_flags)(pyfunc) + + msg = ("Can't unify yield type from the following types: complex128, " + "none") + self.assertIn(msg, str(raises.exception)) + + def test_optional_expansion_type_unification_error(self): + pyfunc = gen_optional_and_type_unification_error + with self.assertTypingError() as raises: + jit((), **nopython_flags)(pyfunc) + + msg = ("Can't unify yield type from the following types: complex128, " + "int%s, none") + self.assertIn(msg % types.intp.bitwidth, str(raises.exception)) + + def test_changing_tuple_type(self): + # test https://github.com/numba/numba/issues/7295 + pyfunc = gen_changing_tuple_type + expected = list(pyfunc()) + got = list(njit(pyfunc)()) + self.assertEqual(expected, got) + + def test_changing_number_type(self): + # additional test for https://github.com/numba/numba/issues/7295 + pyfunc = gen_changing_number_type + expected = list(pyfunc()) + got = list(njit(pyfunc)()) + self.assertEqual(expected, got) + + +def nrt_gen0(ary): + for elem in ary: + yield elem + + +def nrt_gen1(ary1, ary2): + for e1, e2 in zip(ary1, ary2): + yield e1 + yield e2 + + +class TestNrtArrayGen(MemoryLeakMixin, TestCase): + def test_nrt_gen0(self): + pygen = nrt_gen0 + cgen = jit(nopython=True)(pygen) + + py_ary = np.arange(10) + c_ary = py_ary.copy() + + py_res = list(pygen(py_ary)) + c_res = list(cgen(c_ary)) + + np.testing.assert_equal(py_ary, c_ary) + self.assertEqual(py_res, c_res) + # Check reference count + self.assertRefCountEqual(py_ary, c_ary) + + def test_nrt_gen1(self): + pygen = nrt_gen1 + cgen = jit(nopython=True)(pygen) + + py_ary1 = np.arange(10) + py_ary2 = py_ary1 + 100 + + c_ary1 = py_ary1.copy() + c_ary2 = py_ary2.copy() + + py_res = list(pygen(py_ary1, py_ary2)) + c_res = list(cgen(c_ary1, c_ary2)) + + np.testing.assert_equal(py_ary1, c_ary1) + np.testing.assert_equal(py_ary2, c_ary2) + self.assertEqual(py_res, c_res) + # Check reference count + self.assertRefCountEqual(py_ary1, c_ary1) + self.assertRefCountEqual(py_ary2, c_ary2) + + def test_combine_gen0_gen1(self): + """ + Issue #1163 is observed when two generator with NRT object arguments + is ran in sequence. The first one does a invalid free and corrupts + the NRT memory subsystem. The second generator is likely to segfault + due to corrupted NRT data structure (an invalid MemInfo). + """ + self.test_nrt_gen0() + self.test_nrt_gen1() + + def test_nrt_gen0_stop_iteration(self): + """ + Test cleanup on StopIteration + """ + pygen = nrt_gen0 + cgen = jit(nopython=True)(pygen) + + py_ary = np.arange(1) + c_ary = py_ary.copy() + + py_iter = pygen(py_ary) + c_iter = cgen(c_ary) + + py_res = next(py_iter) + c_res = next(c_iter) + + with self.assertRaises(StopIteration): + py_res = next(py_iter) + + with self.assertRaises(StopIteration): + c_res = next(c_iter) + + del py_iter + del c_iter + + np.testing.assert_equal(py_ary, c_ary) + self.assertEqual(py_res, c_res) + # Check reference count + self.assertRefCountEqual(py_ary, c_ary) + + def test_nrt_gen0_no_iter(self): + """ + Test cleanup for a initialized but never iterated (never call next()) + generator. + """ + pygen = nrt_gen0 + cgen = jit(nopython=True)(pygen) + + py_ary = np.arange(1) + c_ary = py_ary.copy() + + py_iter = pygen(py_ary) + c_iter = cgen(c_ary) + + del py_iter + del c_iter + + np.testing.assert_equal(py_ary, c_ary) + + # Check reference count + self.assertRefCountEqual(py_ary, c_ary) + + +# TODO: fix nested generator and MemoryLeakMixin +class TestNrtNestedGen(TestCase): + def test_nrt_nested_gen(self): + + def gen0(arr): + for i in range(arr.size): + yield arr + + def factory(gen0): + def gen1(arr): + out = np.zeros_like(arr) + for x in gen0(arr): + out = out + x + return out, arr + + return gen1 + + py_arr = np.arange(10) + c_arr = py_arr.copy() + py_res, py_old = factory(gen0)(py_arr) + c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0))) + c_res, c_old = c_gen(c_arr) + + self.assertIsNot(py_arr, c_arr) + self.assertIs(py_old, py_arr) + self.assertIs(c_old, c_arr) + + np.testing.assert_equal(py_res, c_res) + + self.assertRefCountEqual(py_res, c_res) + + # The below test will fail due to generator finalizer not invoked. + # This kept a reference of the c_old. + # + # self.assertEqual(sys.getrefcount(py_old), + # sys.getrefcount(c_old)) + + @unittest.expectedFailure + def test_nrt_nested_gen_refct(self): + def gen0(arr): + yield arr + + def factory(gen0): + def gen1(arr): + for out in gen0(arr): + return out + + return gen1 + + py_arr = np.arange(10) + c_arr = py_arr.copy() + py_old = factory(gen0)(py_arr) + c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0))) + c_old = c_gen(c_arr) + + self.assertIsNot(py_arr, c_arr) + self.assertIs(py_old, py_arr) + self.assertIs(c_old, c_arr) + + self.assertRefCountEqual(py_old, c_old) + + def test_nrt_nested_nopython_gen(self): + """ + Test nesting three generators + """ + + def factory(decor=lambda x: x): + @decor + def foo(a, n): + for i in range(n): + yield a[i] + a[i] += i + + @decor + def bar(n): + a = np.arange(n) + for i in foo(a, n): + yield i * 2 + for i in range(a.size): + yield a[i] + + @decor + def cat(n): + for i in bar(n): + yield i + i + + return cat + + py_gen = factory() + c_gen = factory(jit(nopython=True)) + + py_res = list(py_gen(10)) + c_res = list(c_gen(10)) + + self.assertEqual(py_res, c_res) + + +class TestGeneratorWithNRT(MemoryLeakMixin, TestCase): + def test_issue_1254(self): + """ + Missing environment for returning array + """ + + @jit(nopython=True) + def random_directions(n): + for i in range(n): + vec = np.empty(3) + vec[:] = 12 + yield vec + + outputs = list(random_directions(5)) + self.assertEqual(len(outputs), 5) + + expect = np.empty(3) + expect[:] = 12 + for got in outputs: + np.testing.assert_equal(expect, got) + + def test_issue_1265(self): + """ + Double-free for locally allocated, non escaping NRT objects + """ + + def py_gen(rmin, rmax, nr): + a = np.linspace(rmin, rmax, nr) + yield a[0] + yield a[1] + + c_gen = jit(nopython=True)(py_gen) + + py_res = list(py_gen(-2, 2, 100)) + c_res = list(c_gen(-2, 2, 100)) + + self.assertEqual(py_res, c_res) + + def py_driver(args): + rmin, rmax, nr = args + points = np.empty(nr, dtype=np.complex128) + for i, c in enumerate(py_gen(rmin, rmax, nr)): + points[i] = c + + return points + + @jit(nopython=True) + def c_driver(args): + rmin, rmax, nr = args + points = np.empty(nr, dtype=np.complex128) + for i, c in enumerate(c_gen(rmin, rmax, nr)): + points[i] = c + + return points + + n = 2 + patches = (-2, -1, n) + + py_res = py_driver(patches) + # The error will cause a segfault here + c_res = c_driver(patches) + + np.testing.assert_equal(py_res, c_res) + + def test_issue_1808(self): + """ + Incorrect return data model + """ + magic = 0xdeadbeef + + @njit + def generator(): + yield magic + + @njit + def get_generator(): + return generator() + + @njit + def main(): + out = 0 + for x in get_generator(): + out += x + + return out + + self.assertEqual(main(), magic) + + +class TestGeneratorModel(test_factory()): + fe_type = types.Generator(gen_func=None, yield_type=types.int32, + arg_types=[types.int64, types.float32], + state_types=[types.intp, types.intp[::1]], + has_finalizer=False) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_globals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_globals.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdcb8605aef1c55cea37ea8c8dd0f25f493ff45 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_globals.py @@ -0,0 +1,266 @@ +import numpy as np +from numba import jit, njit, errors +from numba.extending import register_jitable +from numba.tests import usecases +import unittest + +X = np.arange(10) + + +def global_ndarray_func(x): + y = x + X.shape[0] + return y + + +# Create complex array with real and imaginary parts of distinct value +cplx_X = np.arange(10, dtype=np.complex128) +tmp = np.arange(10, dtype=np.complex128) +cplx_X += (tmp+10)*1j + + +def global_cplx_arr_copy(a): + for i in range(len(a)): + a[i] = cplx_X[i] + + +# Create a recarray with fields of distinct value +x_dt = np.dtype([('a', np.int32), ('b', np.float32)]) +rec_X = np.recarray(10, dtype=x_dt) +for i in range(len(rec_X)): + rec_X[i].a = i + rec_X[i].b = i + 0.5 + + +def global_rec_arr_copy(a): + for i in range(len(a)): + a[i] = rec_X[i] + + +def global_rec_arr_extract_fields(a, b): + for i in range(len(a)): + a[i] = rec_X[i].a + b[i] = rec_X[i].b + + +# Create additional global recarray +y_dt = np.dtype([('c', np.int16), ('d', np.float64)]) +rec_Y = np.recarray(10, dtype=y_dt) +for i in range(len(rec_Y)): + rec_Y[i].c = i + 10 + rec_Y[i].d = i + 10.5 + + +def global_two_rec_arrs(a, b, c, d): + for i in range(len(a)): + a[i] = rec_X[i].a + b[i] = rec_X[i].b + c[i] = rec_Y[i].c + d[i] = rec_Y[i].d + + +# Test a global record +record_only_X = np.recarray(1, dtype=x_dt)[0] +record_only_X.a = 1 +record_only_X.b = 1.5 + +@jit(nopython=True) +def global_record_func(x): + return x.a == record_only_X.a + + +@jit(nopython=True) +def global_module_func(x, y): + return usecases.andornopython(x, y) + +# Test a global tuple +tup_int = (1, 2) +tup_str = ('a', 'b') +tup_mixed = (1, 'a') +tup_float = (1.2, 3.5) +tup_npy_ints = (np.uint64(12), np.int8(3)) +tup_tup_array = ((np.ones(5),),) +mixed_tup_tup_array = (('Z', np.ones(5),), 2j, 'A') + +def global_int_tuple(): + return tup_int[0] + tup_int[1] + + +def global_str_tuple(): + return tup_str[0] + tup_str[1] + + +def global_mixed_tuple(): + idx = tup_mixed[0] + field = tup_mixed[1] + return rec_X[idx][field] + + +def global_float_tuple(): + return tup_float[0] + tup_float[1] + + +def global_npy_int_tuple(): + return tup_npy_ints[0] + tup_npy_ints[1] + + +def global_write_to_arr_in_tuple(): + tup_tup_array[0][0][0] = 10. + + +def global_write_to_arr_in_mixed_tuple(): + mixed_tup_tup_array[0][1][0] = 10. + + +_glbl_np_bool_T = np.bool_(True) +_glbl_np_bool_F = np.bool_(False) + + +@register_jitable # consumer function +def _sink(*args): + pass + +def global_npy_bool(): + _sink(_glbl_np_bool_T, _glbl_np_bool_F) + return _glbl_np_bool_T, _glbl_np_bool_F + + +class TestGlobals(unittest.TestCase): + + def check_global_ndarray(self, **jitargs): + # (see github issue #448) + ctestfunc = jit(**jitargs)(global_ndarray_func) + self.assertEqual(ctestfunc(1), 11) + + def test_global_ndarray(self): + # This also checks we can access an unhashable global value + # (see issue #697) + self.check_global_ndarray(forceobj=True) + + def test_global_ndarray_npm(self): + self.check_global_ndarray(nopython=True) + + + def check_global_complex_arr(self, **jitargs): + # (see github issue #897) + ctestfunc = jit(**jitargs)(global_cplx_arr_copy) + arr = np.zeros(len(cplx_X), dtype=np.complex128) + ctestfunc(arr) + np.testing.assert_equal(arr, cplx_X) + + def test_global_complex_arr(self): + self.check_global_complex_arr(forceobj=True) + + def test_global_complex_arr_npm(self): + self.check_global_complex_arr(nopython=True) + + + def check_global_rec_arr(self, **jitargs): + # (see github issue #897) + ctestfunc = jit(**jitargs)(global_rec_arr_copy) + arr = np.zeros(rec_X.shape, dtype=x_dt) + ctestfunc(arr) + np.testing.assert_equal(arr, rec_X) + + def test_global_rec_arr(self): + self.check_global_rec_arr(forceobj=True) + + def test_global_rec_arr_npm(self): + self.check_global_rec_arr(nopython=True) + + + def check_global_rec_arr_extract(self, **jitargs): + # (see github issue #897) + ctestfunc = jit(**jitargs)(global_rec_arr_extract_fields) + arr1 = np.zeros(rec_X.shape, dtype=np.int32) + arr2 = np.zeros(rec_X.shape, dtype=np.float32) + ctestfunc(arr1, arr2) + np.testing.assert_equal(arr1, rec_X.a) + np.testing.assert_equal(arr2, rec_X.b) + + def test_global_rec_arr_extract(self): + self.check_global_rec_arr_extract(forceobj=True) + + def test_global_rec_arr_extract_npm(self): + self.check_global_rec_arr_extract(nopython=True) + + + def check_two_global_rec_arrs(self, **jitargs): + # (see github issue #897) + ctestfunc = jit(**jitargs)(global_two_rec_arrs) + arr1 = np.zeros(rec_X.shape, dtype=np.int32) + arr2 = np.zeros(rec_X.shape, dtype=np.float32) + arr3 = np.zeros(rec_Y.shape, dtype=np.int16) + arr4 = np.zeros(rec_Y.shape, dtype=np.float64) + ctestfunc(arr1, arr2, arr3, arr4) + np.testing.assert_equal(arr1, rec_X.a) + np.testing.assert_equal(arr2, rec_X.b) + np.testing.assert_equal(arr3, rec_Y.c) + np.testing.assert_equal(arr4, rec_Y.d) + + def test_two_global_rec_arrs(self): + self.check_two_global_rec_arrs(forceobj=True) + + def test_two_global_rec_arrs_npm(self): + self.check_two_global_rec_arrs(nopython=True) + + def test_global_module(self): + # (see github issue #1059) + res = global_module_func(5, 6) + self.assertEqual(True, res) + + def test_global_record(self): + # (see github issue #1081) + x = np.recarray(1, dtype=x_dt)[0] + x.a = 1 + res = global_record_func(x) + self.assertEqual(True, res) + x.a = 2 + res = global_record_func(x) + self.assertEqual(False, res) + + def test_global_int_tuple(self): + pyfunc = global_int_tuple + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + def test_global_str_tuple(self): + pyfunc = global_str_tuple + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + def test_global_mixed_tuple(self): + pyfunc = global_mixed_tuple + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + def test_global_float_tuple(self): + pyfunc = global_float_tuple + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + def test_global_npy_int_tuple(self): + pyfunc = global_npy_int_tuple + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + def test_global_write_to_arr_in_tuple(self): + # Test writing to an array in a global tuple + # See issue https://github.com/numba/numba/issues/7120 + for func in (global_write_to_arr_in_tuple, + global_write_to_arr_in_mixed_tuple): + jitfunc = njit(func) + with self.assertRaises(errors.TypingError) as e: + jitfunc() + msg = "Cannot modify readonly array of type:" + self.assertIn(msg, str(e.exception)) + + def test_global_npy_bool(self): + # Test global NumPy bool + # See issue https://github.com/numba/numba/issues/6979 + pyfunc = global_npy_bool + jitfunc = njit(pyfunc) + self.assertEqual(pyfunc(), jitfunc()) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_hashing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2cd1a945b5f16a20f7911d7d1385644afd8d8f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_hashing.py @@ -0,0 +1,532 @@ +# -*- coding: utf-8 -*- +""" +Test hashing of various supported types. +""" + +import unittest + +import os +import sys +import subprocess +from collections import defaultdict +from textwrap import dedent + +import numpy as np + +from numba import jit, config, typed, typeof +from numba.core import types, utils +import unittest +from numba.tests.support import (TestCase, skip_unless_py10_or_later, + run_in_subprocess) + +from numba.cpython.unicode import compile_time_get_string_data +from numba.cpython import hashing +from numba.np.numpy_support import numpy_version + + +def hash_usecase(x): + return hash(x) + + +class TestHashingSetup(TestCase): + + def test_warn_on_fnv(self): + # FNV hash alg variant is not supported, check Numba warns + work = """ + import sys + import warnings + from collections import namedtuple + + # hash_info is a StructSequence, mock as a named tuple + fields = ["width", "modulus", "inf", "nan", "imag", "algorithm", + "hash_bits", "seed_bits", "cutoff"] + + hinfo = sys.hash_info + FAKE_HASHINFO = namedtuple('FAKE_HASHINFO', fields) + + fd = dict() + for f in fields: + fd[f] = getattr(hinfo, f) + + fd['algorithm'] = 'fnv' + + fake_hashinfo = FAKE_HASHINFO(**fd) + + # replace the hashinfo with the fnv version + sys.hash_info = fake_hashinfo + with warnings.catch_warnings(record=True) as warns: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + from numba import njit + @njit + def foo(): + hash(1) + foo() + assert len(warns) > 0 + expect = "FNV hashing is not implemented in Numba. See PEP 456" + for w in warns: + if expect in str(w.message): + break + else: + raise RuntimeError("Expected warning not found") + """ + subprocess.check_call([sys.executable, '-c', dedent(work)]) + + +class TestHashAlgs(TestCase): + # This tests Numba hashing replication against cPython "gold", i.e. the + # actual hash values for given inputs, algs and PYTHONHASHSEEDs + # Test adapted from: + # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L197-L264 + # and + # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L174-L189 + + # 32bit little, 64bit little, 32bit big, 64bit big + known_hashes = { + 'djba33x': [ # only used for small strings + # seed 0, 'abc' + [193485960, 193485960, 193485960, 193485960], + # seed 42, 'abc' + [-678966196, 573763426263223372, -820489388, -4282905804826039665], + ], + 'siphash13': [ + # NOTE: PyUCS2 layout depends on endianness + # seed 0, 'abc' + [69611762, -4594863902769663758, 69611762, -4594863902769663758], + # seed 42, 'abc' + [-975800855, 3869580338025362921, -975800855, 3869580338025362921], + # seed 42, 'abcdefghijk' + [-595844228, 7764564197781545852, -595844228, 7764564197781545852], + # seed 0, 'Ă€Ăș∑ℇ' + [-1093288643, -2810468059467891395, -1041341092, 4925090034378237276], + # seed 42, 'Ă€Ăș∑ℇ' + [-585999602, -2845126246016066802, -817336969, -2219421378907968137], + ], + 'siphash24': [ + # NOTE: PyUCS2 layout depends on endianness + # seed 0, 'abc' + [1198583518, 4596069200710135518, 1198583518, 4596069200710135518], + # seed 42, 'abc' + [273876886, -4501618152524544106, 273876886, -4501618152524544106], + # seed 42, 'abcdefghijk' + [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975], + # seed 0, 'Ă€Ăș∑ℇ' + [493570806, 5749986484189612790, -1006381564, -5915111450199468540], + # seed 42, 'Ă€Ăș∑ℇ' + [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017], + ], + } + + def get_expected_hash(self, position, length): + if length < sys.hash_info.cutoff: + algorithm = "djba33x" + else: + algorithm = sys.hash_info.algorithm + IS_64BIT = not config.IS_32BITS + if sys.byteorder == 'little': + platform = 1 if IS_64BIT else 0 + else: + assert(sys.byteorder == 'big') + platform = 3 if IS_64BIT else 2 + return self.known_hashes[algorithm][position][platform] + + def get_hash_command(self, repr_): + return 'print(hash(eval(%a)))' % repr_ + + def get_hash(self, repr_, seed=None): + env = os.environ.copy() + if seed is not None: + env['PYTHONHASHSEED'] = str(seed) + else: + env.pop('PYTHONHASHSEED', None) + out, _ = run_in_subprocess(code=self.get_hash_command(repr_), + env=env) + stdout = out.decode().strip() + return int(stdout) + + def test_against_cpython_gold(self): + + args = (('abc', 0, 0), ('abc', 42, 1), ('abcdefghijk', 42, 2), + ('Ă€Ăș∑ℇ', 0, 3), ('Ă€Ăș∑ℇ', 42, 4),) + + for input_str, seed, position in args: + with self.subTest(input_str=input_str, seed=seed): + got = self.get_hash(repr(input_str), seed=seed) + expected = self.get_expected_hash(position, len(input_str)) + self.assertEqual(got, expected) + + +class BaseTest(TestCase): + + def setUp(self): + self.cfunc = jit(nopython=True)(hash_usecase) + + def check_hash_values(self, values): + cfunc = self.cfunc + for val in list(values): + nb_hash = cfunc(val) + self.assertIsInstance(nb_hash, int) + try: + self.assertEqual(nb_hash, hash(val)) + except AssertionError as e: + print("val, nb_hash, hash(val)") + print(val, nb_hash, hash(val)) + print("abs(val), hashing._PyHASH_MODULUS - 1") + print(abs(val), hashing._PyHASH_MODULUS - 1) + raise e + + def int_samples(self, typ=np.int64): + for start in (0, -50, 60000, 1 << 32): + info = np.iinfo(typ) + if not info.min <= start <= info.max: + continue + n = 100 + yield range(start, start + n) + yield range(start, start + 100 * n, 100) + yield range(start, start + 128 * n, 128) + yield [-1] + + def safe_construct(self, typ, value): + return getattr(np, 'int' + str(np.iinfo(typ).bits))(value).view(typ) + + def float_samples(self, typ): + info = np.finfo(typ) + + for start in (0, 10, info.max ** 0.5, info.max / 1000.0): + n = 100 + min_step = max(info.tiny, start * info.resolution) + for step in (1.2, min_step ** 0.5, min_step): + if step < min_step: + continue + a = np.linspace(start, start + n * step, n) + a = a.astype(typ) + yield a + yield -a + yield a + a.mean() + + # Infs, nans, zeros, magic -1 + a = [0.0, 0.5, -0.0, -1.0, float('inf'), -float('inf'),] + + # Python 3.10 has a hash for nan based on the pointer to the PyObject + # containing the nan, skip this input and use explicit test instead. + + yield typ(a) + + def complex_samples(self, typ, float_ty): + for real in self.float_samples(float_ty): + for imag in self.float_samples(float_ty): + # Ensure equal sizes + real = real[:len(imag)] + imag = imag[:len(real)] + a = real + typ(1j) * imag + # Python 3.10 has a hash for nan based on the pointer to the + # PyObject containing the nan, skip input that ends up as nan + if not np.any(np.isnan(a)): + yield a + + +class TestNumberHashing(BaseTest): + """ + Test hashing of number types. + """ + + def setUp(self): + if numpy_version >= (2, 0) and numpy_version <= (2, 1): + # Temporarily set promotions state to legacy, + # to ensure overflow logic works + self.initial_state = np._get_promotion_state() + np._set_promotion_state("legacy") + + return super().setUp() + + def tearDown(self) -> None: + if numpy_version >= (2, 0) and numpy_version <= (2, 1): + # Reset numpy promotion state to initial state + # since the setting is global + np._set_promotion_state(self.initial_state) + + return super().tearDown() + + def check_floats(self, typ): + for a in self.float_samples(typ): + self.assertEqual(a.dtype, np.dtype(typ)) + self.check_hash_values(a) + + def check_complex(self, typ, float_ty): + for a in self.complex_samples(typ, float_ty): + self.assertEqual(a.dtype, np.dtype(typ)) + self.check_hash_values(a) + + def test_floats(self): + self.check_floats(np.float32) + self.check_floats(np.float64) + + def test_complex(self): + self.check_complex(np.complex64, np.float32) + self.check_complex(np.complex128, np.float64) + + def test_bool(self): + self.check_hash_values([False, True]) + + def test_ints(self): + minmax = [] + + for ty in [np.int8, np.uint8, np.int16, np.uint16, + np.int32, np.uint32, np.int64, np.uint64]: + for a in self.int_samples(ty): + self.check_hash_values(a) + info = np.iinfo(ty) + # check hash(-1) = -2 + # check hash(0) = 0 + self.check_hash_values([self.safe_construct(ty, -1)]) + self.check_hash_values([ty(0)]) + signed = 'uint' not in str(ty) + # check bit shifting patterns from min through to max + sz = ty().itemsize + for x in [info.min, info.max]: + shifts = 8 * sz + # x is a python int, do shifts etc as a python int and init + # numpy type from that to avoid numpy type rules + y = x + for i in range(shifts): + twiddle1 = 0xaaaaaaaaaaaaaaaa + twiddle2 = 0x5555555555555555 + vals = [y] + for tw in [twiddle1, twiddle2]: + val = y & twiddle1 + if val < sys.maxsize: + vals.append(val) + for v in vals: + self.check_hash_values([ty(v)]) + if signed: # try the same with flipped signs + # negated signed INT_MIN will overflow + for v in vals: + if v != info.min: + self.check_hash_values([ty(-v)]) + if x == 0: # unsigned min is 0, shift up + y = (y | 1) << 1 + else: # everything else shift down + y = y >> 1 + + # these straddle the branch between returning the int as the hash and + # doing the PyLong hash alg + self.check_hash_values([np.int64(0x1ffffffffffffffe)]) + self.check_hash_values([np.int64(0x1fffffffffffffff)]) + self.check_hash_values([np.uint64(0x1ffffffffffffffe)]) + self.check_hash_values([np.uint64(0x1fffffffffffffff)]) + + # check some values near sys int mins + self.check_hash_values([np.int64(-0x7fffffffffffffff)]) + self.check_hash_values([np.int64(-0x7ffffffffffffff6)]) + self.check_hash_values([np.int64(-0x7fffffffffffff9c)]) + self.check_hash_values([np.int32(-0x7fffffff)]) + self.check_hash_values([np.int32(-0x7ffffff6)]) + self.check_hash_values([np.int32(-0x7fffff9c)]) + + @skip_unless_py10_or_later + def test_py310_nan_hash(self): + # On Python 3.10+ nan's hash to a value which is based on the pointer to + # the PyObject containing the nan. Numba cannot replicate as there's no + # object, it instead produces equivalent behaviour, i.e. hashes to + # something "unique". + + # Run 10 hashes, make sure that the "uniqueness" is sufficient that + # there's more than one hash value. Not much more can be done! + x = [float('nan') for i in range(10)] + out = set([self.cfunc(z) for z in x]) + self.assertGreater(len(out), 1) + + +class TestTupleHashing(BaseTest): + """ + Test hashing of tuples. + """ + + def setUp(self): + if numpy_version >= (2, 0) and numpy_version <= (2, 1): + # Temporarily set promotions state to legacy, + # to ensure overflow logic works + self.initial_state = np._get_promotion_state() + np._set_promotion_state("legacy") + + return super().setUp() + + def tearDown(self) -> None: + if numpy_version >= (2, 0) and numpy_version <= (2, 1): + # Reset numpy promotion state to initial state + # since the setting is global + np._set_promotion_state(self.initial_state) + + return super().tearDown() + + def check_tuples(self, value_generator, split): + for values in value_generator: + tuples = [split(a) for a in values] + self.check_hash_values(tuples) + + def test_homogeneous_tuples(self): + typ = np.uint64 + + def split2(i): + """ + Split i's bits into 2 integers. + """ + i = self.safe_construct(typ, i) + return (i & typ(0x5555555555555555), + i & typ(0xaaaaaaaaaaaaaaaa), + ) + + def split3(i): + """ + Split i's bits into 3 integers. + """ + i = self.safe_construct(typ, i) + return (i & typ(0x2492492492492492), + i & typ(0x4924924924924924), + i & typ(0x9249249249249249), + ) + + self.check_tuples(self.int_samples(), split2) + self.check_tuples(self.int_samples(), split3) + + # Check exact. Sample values from: + # https://github.com/python/cpython/blob/b738237d6792acba85b1f6e6c8993a812c7fd815/Lib/test/test_tuple.py#L80-L93 + # Untypable empty tuples are replaced with (7,). + self.check_hash_values([(7,), (0,), (0, 0), (0.5,), + (0.5, (7,), (-2, 3, (4, 6)))]) + + def test_heterogeneous_tuples(self): + modulo = 2**63 + + def split(i): + a = i & 0x5555555555555555 + b = (i & 0xaaaaaaaa) ^ ((i >> 32) & 0xaaaaaaaa) + return np.int64(a), np.float64(b * 0.0001) + + self.check_tuples(self.int_samples(), split) + + +class TestUnicodeHashing(BaseTest): + + def test_basic_unicode(self): + kind1_string = "abcdefghijklmnopqrstuvwxyz" + for i in range(len(kind1_string)): + self.check_hash_values([kind1_string[:i]]) + + sep = "県" + kind2_string = sep.join(list(kind1_string)) + for i in range(len(kind2_string)): + self.check_hash_values([kind2_string[:i]]) + + sep = "🐍⚡" + kind4_string = sep.join(list(kind1_string)) + for i in range(len(kind4_string)): + self.check_hash_values([kind4_string[:i]]) + + empty_string = "" + self.check_hash_values(empty_string) + + def test_hash_passthrough(self): + # no `hash` call made, this just checks that `._hash` is correctly + # passed through from an already existing string + kind1_string = "abcdefghijklmnopqrstuvwxyz" + + @jit(nopython=True) + def fn(x): + return x._hash + + hash_value = compile_time_get_string_data(kind1_string)[-1] + self.assertTrue(hash_value != -1) + self.assertEqual(fn(kind1_string), hash_value) + + def test_hash_passthrough_call(self): + # check `x._hash` and hash(x) are the same + kind1_string = "abcdefghijklmnopqrstuvwxyz" + + @jit(nopython=True) + def fn(x): + return x._hash, hash(x) + + hash_value = compile_time_get_string_data(kind1_string)[-1] + self.assertTrue(hash_value != -1) + self.assertEqual(fn(kind1_string), (hash_value, hash_value)) + + @unittest.skip("Needs hash computation at const unpickling time") + def test_hash_literal(self): + # a strconst always seem to have an associated hash value so the hash + # member of the returned value should contain the correct hash + @jit(nopython=True) + def fn(): + x = "abcdefghijklmnopqrstuvwxyz" + return x + val = fn() + tmp = hash("abcdefghijklmnopqrstuvwxyz") + self.assertEqual(tmp, (compile_time_get_string_data(val)[-1])) + + def test_hash_on_str_creation(self): + # In cPython some? new strings do not have a cached hash until hash() is + # called + def impl(do_hash): + const1 = "aaaa" + const2 = "県県県県" + new = const1 + const2 + if do_hash: + hash(new) + return new + + jitted = jit(nopython=True)(impl) + + # do not compute the hash, cPython will have no cached hash, but Numba + # will + compute_hash = False + expected = impl(compute_hash) + got = jitted(compute_hash) + a = (compile_time_get_string_data(expected)) + b = (compile_time_get_string_data(got)) + self.assertEqual(a[:-1], b[:-1]) + self.assertTrue(a[-1] != b[-1]) + + # now with compute hash enabled, cPython will have a cached hash as will + # Numba + compute_hash = True + expected = impl(compute_hash) + got = jitted(compute_hash) + a = (compile_time_get_string_data(expected)) + b = (compile_time_get_string_data(got)) + self.assertEqual(a, b) + + +class TestUnhashable(TestCase): + # Tests that unhashable types behave correctly and raise a TypeError at + # runtime. + + def test_hash_unhashable(self): + unhashables = (typed.Dict().empty(types.int64, types.int64), + typed.List().empty_list(types.int64), + np.ones(4)) + cfunc = jit(nopython=True)(hash_usecase) + for ty in unhashables: + with self.assertRaises(TypeError) as raises: + cfunc(ty) + expected = f"unhashable type: '{str(typeof(ty))}'" + self.assertIn(expected, str(raises.exception)) + + def test_no_generic_hash(self): + # In CPython, if there's no attr `__hash__` on an object, a hash of the + # object's pointer is returned (see: _Py_HashPointer in the CPython + # source). Numba has no access to such objects and can't create them + # either, so it catches this case and raises an exception. + + @jit(nopython=True) + def foo(): + hash(np.cos) + + with self.assertRaises(TypeError) as raises: + foo() + + expected = ("No __hash__ is defined for object ") + self.assertIn(expected, str(raises.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_help.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_help.py new file mode 100644 index 0000000000000000000000000000000000000000..8199d4c93c4b6969f9437e8b28cc05a4948d9c5e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_help.py @@ -0,0 +1,92 @@ +import sys +import subprocess +import types as pytypes +import os.path + +import numpy as np + +import builtins +from numba.core import types +from numba.tests.support import TestCase, temp_directory +from numba.misc.help.inspector import inspect_function, inspect_module + + +class TestInspector(TestCase): + def check_function_descriptor(self, info, must_be_defined=False): + self.assertIsInstance(info, dict) + self.assertIn('numba_type', info) + numba_type = info['numba_type'] + if numba_type is None: + self.assertFalse(must_be_defined) + else: + self.assertIsInstance(numba_type, types.Type) + self.assertIn('explained', info) + self.assertIsInstance(info['explained'], str) + self.assertIn('source_infos', info) + self.assertIsInstance(info['source_infos'], dict) + + def test_inspect_function_on_range(self): + info = inspect_function(range) + self.check_function_descriptor(info, must_be_defined=True) + + def test_inspect_function_on_np_all(self): + info = inspect_function(np.all) + self.check_function_descriptor(info, must_be_defined=True) + source_infos = info['source_infos'] + self.assertGreater(len(source_infos), 0) + c = 0 + for srcinfo in source_infos.values(): + self.assertIsInstance(srcinfo['kind'], str) + self.assertIsInstance(srcinfo['name'], str) + self.assertIsInstance(srcinfo['sig'], str) + self.assertIsInstance(srcinfo['filename'], str) + self.assertIsInstance(srcinfo['lines'], tuple) + self.assertIn('docstring', srcinfo) + c += 1 + self.assertEqual(c, len(source_infos)) + + def test_inspect_module(self): + c = 0 + for it in inspect_module(builtins): + self.assertIsInstance(it['module'], pytypes.ModuleType) + self.assertIsInstance(it['name'], str) + self.assertTrue(callable(it['obj'])) + self.check_function_descriptor(it) + c += 1 + self.assertGreater(c, 0) + + def test_inspect_cli(self): + # Try CLI on math module + cmdbase = [sys.executable, '-m', 'numba.misc.help.inspector'] + + dirpath = temp_directory('{}.{}'.format(__name__, + self.__class__.__name__)) + filename = os.path.join(dirpath, 'out') + + # Try default format "html" + expected_file = filename + '.html' + cmds = cmdbase + ['--file', filename, 'math'] + # File shouldn't exist yet + self.assertFalse(os.path.isfile(expected_file)) + # Run CLI + subprocess.check_output(cmds) + # File should exist now + self.assertTrue(os.path.isfile(expected_file)) + + # Try changing the format to "rst" + cmds = cmdbase + ['--file', filename, '--format', 'rst', 'math'] + expected_file = filename + '.rst' + # File shouldn't exist yet + self.assertFalse(os.path.isfile(expected_file)) + # Run CLI + subprocess.check_output(cmds) + # File should exist now + self.assertTrue(os.path.isfile(expected_file)) + + # Try unsupported format + cmds = cmdbase + ['--file', filename, '--format', 'foo', 'math'] + # Run CLI + with self.assertRaises(subprocess.CalledProcessError) as raises: + subprocess.check_output(cmds, stderr=subprocess.STDOUT) + self.assertIn("\'foo\' is not supported", + raises.exception.stdout.decode()) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_inlining.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_inlining.py new file mode 100644 index 0000000000000000000000000000000000000000..45376a483d515974481212c6454ff5ec1f193136 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_inlining.py @@ -0,0 +1,279 @@ +import re +import numpy as np + +from numba.tests.support import (TestCase, override_config, captured_stdout, + skip_parfors_unsupported) +from numba import jit, njit +from numba.core import types, ir, postproc, compiler +from numba.core.ir_utils import (guard, find_callname, find_const, + get_definition, simplify_CFG) +from numba.core.registry import CPUDispatcher +from numba.core.inline_closurecall import inline_closure_call + +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs, + IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, GenericRewrites, + WithLifting, PreserveIR, InlineClosureLikes) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, PreParforPass, ParforPass, + DumpParforDiagnostics, NativeLowering, + NativeParforLowering, IRLegalization, + NoPythonBackend, NativeLowering, + ParforFusionPass, ParforPreLoweringPass) + +from numba.core.compiler_machinery import FunctionPass, PassManager, register_pass +import unittest + +@register_pass(analysis_only=False, mutates_CFG=True) +class InlineTestPass(FunctionPass): + _name = "inline_test_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # assuming the function has one block with one call inside + assert len(state.func_ir.blocks) == 1 + block = list(state.func_ir.blocks.values())[0] + for i, stmt in enumerate(block.body): + if guard(find_callname,state.func_ir, stmt.value) is not None: + inline_closure_call(state.func_ir, {}, block, i, lambda: None, + state.typingctx, state.targetctx, (), + state.typemap, state.calltypes) + break + # also fix up the IR + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run() + post_proc.remove_dels() + return True + + +def gen_pipeline(state, test_pass): + name = 'inline_test' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(WithLifting, "Handle with contexts") + # pre typing + if not state.flags.no_rewrites: + pm.add_pass(GenericRewrites, "nopython rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + if state.flags.auto_parallel.enabled: + pm.add_pass(PreParforPass, "Preprocessing for parfors") + if not state.flags.no_rewrites: + pm.add_pass(NopythonRewrites, "nopython rewrites") + if state.flags.auto_parallel.enabled: + pm.add_pass(ParforPass, "convert to parfors") + pm.add_pass(ParforFusionPass, "fuse parfors") + pm.add_pass(ParforPreLoweringPass, "parfor prelowering") + + pm.add_pass(test_pass, "inline test") + + # legalise + pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering") + pm.add_pass(AnnotateTypes, "annotate types") + pm.add_pass(PreserveIR, "preserve IR") + + # lower + if state.flags.auto_parallel.enabled: + pm.add_pass(NativeParforLowering, "native parfor lowering") + else: + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.add_pass(DumpParforDiagnostics, "dump parfor diagnostics") + return pm + +class InlineTestPipeline(compiler.CompilerBase): + """compiler pipeline for testing inlining after optimization + """ + def define_pipelines(self): + pm = gen_pipeline(self.state, InlineTestPass) + pm.finalize() + return [pm] + +class TestInlining(TestCase): + """ + Check that jitted inner functions are inlined into outer functions, + in nopython mode. + Note that not all inner functions are guaranteed to be inlined. + We just trust LLVM's inlining heuristics. + """ + + def make_pattern(self, fullname): + """ + Make regexpr to match mangled name + """ + parts = fullname.split('.') + return r'_ZN?' + r''.join([r'\d+{}'.format(p) for p in parts]) + + def assert_has_pattern(self, fullname, text): + pat = self.make_pattern(fullname) + self.assertIsNotNone(re.search(pat, text), + msg='expected {}'.format(pat)) + + def assert_not_has_pattern(self, fullname, text): + pat = self.make_pattern(fullname) + self.assertIsNone(re.search(pat, text), + msg='unexpected {}'.format(pat)) + + def test_inner_function(self): + from numba.tests.inlining_usecases import outer_simple, \ + __name__ as prefix + + with override_config('DUMP_ASSEMBLY', True): + with captured_stdout() as out: + cfunc = jit((types.int32,), nopython=True)(outer_simple) + self.assertPreciseEqual(cfunc(1), 4) + # Check the inner function was elided from the output (which also + # guarantees it was inlined into the outer function). + asm = out.getvalue() + self.assert_has_pattern('%s.outer_simple' % prefix, asm) + self.assert_not_has_pattern('%s.inner' % prefix, asm) + + def test_multiple_inner_functions(self): + from numba.tests.inlining_usecases import outer_multiple, \ + __name__ as prefix + # Same with multiple inner functions, and multiple calls to + # the same inner function (inner()). This checks that linking in + # the same library/module twice doesn't produce linker errors. + with override_config('DUMP_ASSEMBLY', True): + with captured_stdout() as out: + cfunc = jit((types.int32,), nopython=True)(outer_multiple) + self.assertPreciseEqual(cfunc(1), 6) + asm = out.getvalue() + self.assert_has_pattern('%s.outer_multiple' % prefix, asm) + self.assert_not_has_pattern('%s.more' % prefix, asm) + self.assert_not_has_pattern('%s.inner' % prefix, asm) + + @skip_parfors_unsupported + def test_inline_call_after_parfor(self): + from numba.tests.inlining_usecases import __dummy__ + # replace the call to make sure inlining doesn't cause label conflict + # with parfor body + def test_impl(A): + __dummy__() + return A.sum() + j_func = njit(parallel=True, pipeline_class=InlineTestPipeline)( + test_impl) + A = np.arange(10) + self.assertEqual(test_impl(A), j_func(A)) + + @skip_parfors_unsupported + def test_inline_update_target_def(self): + + def test_impl(a): + if a == 1: + b = 2 + else: + b = 3 + return b + + func_ir = compiler.run_frontend(test_impl) + blocks = list(func_ir.blocks.values()) + for block in blocks: + for i, stmt in enumerate(block.body): + # match b = 2 and replace with lambda: 2 + if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Var) + and guard(find_const, func_ir, stmt.value) == 2): + # replace expr with a dummy call + func_ir._definitions[stmt.target.name].remove(stmt.value) + stmt.value = ir.Expr.call(ir.Var(block.scope, "myvar", loc=stmt.loc), (), (), stmt.loc) + func_ir._definitions[stmt.target.name].append(stmt.value) + #func = g.py_func# + inline_closure_call(func_ir, {}, block, i, lambda: 2) + break + + self.assertEqual(len(func_ir._definitions['b']), 2) + + @skip_parfors_unsupported + def test_inline_var_dict_ret(self): + # make sure inline_closure_call returns the variable replacement dict + # and it contains the original variable name used in locals + @njit(locals={'b': types.float64}) + def g(a): + b = a + 1 + return b + + def test_impl(): + return g(1) + + func_ir = compiler.run_frontend(test_impl) + blocks = list(func_ir.blocks.values()) + for block in blocks: + for i, stmt in enumerate(block.body): + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call'): + func_def = guard(get_definition, func_ir, stmt.value.func) + if (isinstance(func_def, (ir.Global, ir.FreeVar)) + and isinstance(func_def.value, CPUDispatcher)): + py_func = func_def.value.py_func + _, var_map = inline_closure_call( + func_ir, py_func.__globals__, block, i, py_func) + break + + self.assertTrue('b' in var_map) + + @skip_parfors_unsupported + def test_inline_call_branch_pruning(self): + # branch pruning pass should run properly in inlining to enable + # functions with type checks + @njit + def foo(A=None): + if A is None: + return 2 + else: + return A + + def test_impl(A=None): + return foo(A) + + @register_pass(analysis_only=False, mutates_CFG=True) + class PruningInlineTestPass(FunctionPass): + _name = "pruning_inline_test_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # assuming the function has one block with one call inside + assert len(state.func_ir.blocks) == 1 + block = list(state.func_ir.blocks.values())[0] + for i, stmt in enumerate(block.body): + if (guard(find_callname, state.func_ir, stmt.value) + is not None): + inline_closure_call(state.func_ir, {}, block, i, + foo.py_func, state.typingctx, state.targetctx, + (state.typemap[stmt.value.args[0].name],), + state.typemap, state.calltypes) + break + return True + + class InlineTestPipelinePrune(compiler.CompilerBase): + + def define_pipelines(self): + pm = gen_pipeline(self.state, PruningInlineTestPass) + pm.finalize() + return [pm] + + # make sure inline_closure_call runs in full pipeline + j_func = njit(pipeline_class=InlineTestPipelinePrune)(test_impl) + A = 3 + self.assertEqual(test_impl(A), j_func(A)) + self.assertEqual(test_impl(), j_func()) + + # make sure IR doesn't have branches + fir = j_func.overloads[(types.Omitted(None),)].metadata['preserved_ir'] + fir.blocks = simplify_CFG(fir.blocks) + self.assertEqual(len(fir.blocks), 1) + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_interpreter.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..fef9ddaa91b2e7a40162475e627afd89244b8c0b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_interpreter.py @@ -0,0 +1,1154 @@ +""" +Test bytecode fixes provided in interpreter.py +""" +import unittest +from numba import jit, njit, objmode, typeof, literally +from numba.extending import overload +from numba.core import types +from numba.core.errors import UnsupportedBytecodeError +from numba.tests.support import ( + TestCase, + MemoryLeakMixin, + skip_unless_py10_or_later, +) + + +@njit +def sum_jit_func( + arg0=0, + arg1=0, + arg2=0, + arg3=0, + arg4=0, + arg5=0, + arg6=0, + arg7=0, + arg8=0, + arg9=0, + arg10=0, + arg11=0, + arg12=0, + arg13=0, + arg14=0, + arg15=0, + arg16=0, + arg17=0, + arg18=0, + arg19=0, + arg20=0, + arg21=0, + arg22=0, + arg23=0, + arg24=0, + arg25=0, + arg26=0, + arg27=0, + arg28=0, + arg29=0, + arg30=0, + arg31=0, + arg32=0, + arg33=0, + arg34=0, + arg35=0, + arg36=0, + arg37=0, + arg38=0, + arg39=0, + arg40=0, + arg41=0, + arg42=0, + arg43=0, + arg44=0, + arg45=0, + arg46=0, +): + return ( + arg0 + + arg1 + + arg2 + + arg3 + + arg4 + + arg5 + + arg6 + + arg7 + + arg8 + + arg9 + + arg10 + + arg11 + + arg12 + + arg13 + + arg14 + + arg15 + + arg16 + + arg17 + + arg18 + + arg19 + + arg20 + + arg21 + + arg22 + + arg23 + + arg24 + + arg25 + + arg26 + + arg27 + + arg28 + + arg29 + + arg30 + + arg31 + + arg32 + + arg33 + + arg34 + + arg35 + + arg36 + + arg37 + + arg38 + + arg39 + + arg40 + + arg41 + + arg42 + + arg43 + + arg44 + + arg45 + + arg46 + ) + + +class TestCallFunctionExPeepHole(MemoryLeakMixin, TestCase): + """ + gh #7812 + + Tests that check a peephole optimization for Function calls + in Python 3.10. The bytecode changes when + (n_args / 2) + n_kws > 15, which moves the arguments from + the stack into a tuple and dictionary. + + This peephole optimization updates the IR to use the original format. + There are different paths when n_args > 30 and n_args <= 30 and when + n_kws > 15 and n_kws <= 15. + """ + THRESHOLD_ARGS = 31 + THRESHOLD_KWS = 16 + + def gen_func(self, n_args, n_kws): + """ + Generates a function that calls sum_jit_func + with the desired number of args and kws. + """ + param_list = [f"arg{i}" for i in range(n_args + n_kws)] + args_list = [] + for i in range(n_args + n_kws): + # Call a function on every 5th argument to ensure + # we test function calls. + if i % 5 == 0: + arg_val = f"pow(arg{i}, 2)" + else: + arg_val = f"arg{i}" + args_list.append(arg_val) + total_params = ", ".join(param_list) + func_text = f"def impl({total_params}):\n" + func_text += " return sum_jit_func(\n" + for i in range(n_args): + func_text += f" {args_list[i]},\n" + for i in range(n_args, n_args + n_kws): + func_text += f" {param_list[i]}={args_list[i]},\n" + func_text += " )\n" + local_vars = {} + exec(func_text, {"sum_jit_func": sum_jit_func}, local_vars) + return local_vars["impl"] + + @skip_unless_py10_or_later + def test_all_args(self): + """ + Tests calling a function when n_args > 30 and + n_kws = 0. This shouldn't use the peephole, but + it should still succeed. + """ + total_args = [i for i in range(self.THRESHOLD_ARGS)] + f = self.gen_func(self.THRESHOLD_ARGS, 0) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_all_kws(self): + """ + Tests calling a function when n_kws > 15 and + n_args = 0. + """ + total_args = [i for i in range(self.THRESHOLD_KWS)] + f = self.gen_func(0, self.THRESHOLD_KWS) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_small_args_small_kws(self): + """ + Tests calling a function when (n_args / 2) + n_kws > 15, + but n_args <= 30 and n_kws <= 15 + """ + used_args = self.THRESHOLD_ARGS - 1 + used_kws = self.THRESHOLD_KWS - 1 + total_args = [i for i in range((used_args) + (used_kws))] + f = self.gen_func(used_args, used_kws) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_small_args_large_kws(self): + """ + Tests calling a function when (n_args / 2) + n_kws > 15, + but n_args <= 30 and n_kws > 15 + """ + used_args = self.THRESHOLD_ARGS - 1 + used_kws = self.THRESHOLD_KWS + total_args = [i for i in range((used_args) + (used_kws))] + f = self.gen_func(used_args, used_kws) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_args_small_kws(self): + """ + Tests calling a function when (n_args / 2) + n_kws > 15, + but n_args > 30 and n_kws <= 15 + """ + used_args = self.THRESHOLD_ARGS + used_kws = self.THRESHOLD_KWS - 1 + total_args = [i for i in range((used_args) + (used_kws))] + f = self.gen_func(used_args, used_kws) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_args_large_kws(self): + """ + Tests calling a function when (n_args / 2) + n_kws > 15, + but n_args > 30 and n_kws > 15 + """ + used_args = self.THRESHOLD_ARGS + used_kws = self.THRESHOLD_KWS + total_args = [i for i in range((used_args) + (used_kws))] + f = self.gen_func(used_args, used_kws) + py_func = f + cfunc = njit()(f) + a = py_func(*total_args) + b = cfunc(*total_args) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_kws_objmode(self): + """ + Tests calling an objectmode function with > 15 return values. + """ + def py_func(): + return ( + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + ) + + @njit + def objmode_func(): + """ + Wrapper to call py_func from objmode. This tests + large kws with objmode. If the definition for the + call is not properly updated this test will fail. + """ + with objmode( + a='int64', + b='int64', + c='int64', + d='int64', + e='int64', + f='int64', + g='int64', + h='int64', + i='int64', + j='int64', + k='int64', + l='int64', + m='int64', + n='int64', + o='int64', + p='int64', + ): + ( + a, + b, + c, + d, + e, + f, + g, + h, + i, + j, + k, + l, + m, + n, + o, + p + ) = py_func() + return ( + a + + b + + c + + d + + e + + f + + g + + h + + i + + j + + k + + l + + m + + n + + o + + p + ) + + a = sum(list(py_func())) + b = objmode_func() + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_args_inline_controlflow(self): + """ + Tests generating large args when one of the inputs + has inlined controlflow. + """ + def inline_func(flag): + return sum_jit_func( + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 if flag else 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + arg41=1, + ) + + with self.assertRaises(UnsupportedBytecodeError) as raises: + njit()(inline_func)(False) + self.assertIn( + 'You can resolve this issue by moving the control flow out', + str(raises.exception) + ) + + @skip_unless_py10_or_later + def test_large_args_noninlined_controlflow(self): + """ + Tests generating large args when one of the inputs + has the change suggested in the error message + for inlined control flow. + """ + def inline_func(flag): + a_val = 1 if flag else 2 + return sum_jit_func( + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + a_val, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + arg41=1, + ) + + py_func = inline_func + cfunc = njit()(inline_func) + a = py_func(False) + b = cfunc(False) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_all_args_inline_controlflow(self): + """ + Tests generating only large args when one of the inputs + has inlined controlflow. This requires a special check + inside peep_hole_call_function_ex_to_call_function_kw + because it usually only handles varkwargs. + """ + def inline_func(flag): + return sum_jit_func( + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 if flag else 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ) + + with self.assertRaises(UnsupportedBytecodeError) as raises: + njit()(inline_func)(False) + self.assertIn( + 'You can resolve this issue by moving the control flow out', + str(raises.exception) + ) + + @skip_unless_py10_or_later + def test_all_args_noninlined_controlflow(self): + """ + Tests generating large args when one of the inputs + has the change suggested in the error message + for inlined control flow. + """ + def inline_func(flag): + a_val = 1 if flag else 2 + return sum_jit_func( + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + a_val, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ) + + py_func = inline_func + cfunc = njit()(inline_func) + a = py_func(False) + b = cfunc(False) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_kws_inline_controlflow(self): + """ + Tests generating large kws when one of the inputs + has inlined controlflow. + """ + def inline_func(flag): + return sum_jit_func( + arg0=1, + arg1=1, + arg2=1, + arg3=1, + arg4=1, + arg5=1, + arg6=1, + arg7=1, + arg8=1, + arg9=1, + arg10=1, + arg11=1, + arg12=1, + arg13=1, + arg14=1, + arg15=1 if flag else 2, + ) + + with self.assertRaises(UnsupportedBytecodeError) as raises: + njit()(inline_func)(False) + self.assertIn( + 'You can resolve this issue by moving the control flow out', + str(raises.exception) + ) + + @skip_unless_py10_or_later + def test_large_kws_noninlined_controlflow(self): + """ + Tests generating large kws when one of the inputs + has the change suggested in the error message + for inlined control flow. + """ + def inline_func(flag): + a_val = 1 if flag else 2 + return sum_jit_func( + arg0=1, + arg1=1, + arg2=1, + arg3=1, + arg4=1, + arg5=1, + arg6=1, + arg7=1, + arg8=1, + arg9=1, + arg10=1, + arg11=1, + arg12=1, + arg13=1, + arg14=1, + arg15=a_val, + ) + + py_func = inline_func + cfunc = njit()(inline_func) + a = py_func(False) + b = cfunc(False) + self.assertEqual(a, b) + + +class TestLargeConstDict(TestCase, MemoryLeakMixin): + """ + gh #7894 + + Tests that check a peephole optimization for constant + dictionaries in Python 3.10. The bytecode changes when + number of elements > 15, which splits the constant dictionary + into multiple dictionaries that are joined by a DICT_UPDATE + bytecode instruction. + + This optimization modifies the IR to rejoin dictionaries + and remove the DICT_UPDATE generated code. This then allows + code that depends on literal dictionaries or literal keys + to succeed. + """ + + @skip_unless_py10_or_later + def test_large_heterogeneous_const_dict(self): + """ + Tests that a function with a large heterogeneous constant + dictionary remains a constant. + """ + def const_func(): + # D is a heterogeneous dictionary + # so this code can only compile if + # d is constant. + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": 'a', + } + return d["S"] + + py_func = const_func + cfunc = njit()(const_func) + a = py_func() + b = cfunc() + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_heterogeneous_LiteralStrKeyDict_literal_values(self): + """Check the literal values for a LiteralStrKeyDict requiring + optimizations because it is heterogeneous. + """ + + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + a = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": 'a', + } + + def specific_ty(z): + return types.literal(z) if types.maybe_literal(z) else typeof(z) + expected = {types.literal(x): specific_ty(y) for x, y in a.items()} + self.assertTrue(isinstance(d, types.LiteralStrKeyDict)) + self.assertEqual(d.literal_value, expected) + self.assertEqual(hasattr(d, 'initial_value'), False) + return lambda d: d + + @njit + def foo(): + # D is a heterogeneous dictionary + # so this code can only compile if + # d has the correct literal values. + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": 'a', + } + bar(d) + + foo() + + @skip_unless_py10_or_later + def test_large_heterogeneous_const_keys_dict(self): + """ + Tests that a function with a large heterogeneous constant + dictionary remains a constant. + """ + def const_keys_func(a): + # D is a heterogeneous dictionary + # so this code can only compile if + # d has constant keys. + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": a, + } + return d["S"] + + py_func = const_keys_func + cfunc = njit()(const_keys_func) + # str to make the dictionary heterogeneous. + value = "a_string" + a = py_func(value) + b = cfunc(value) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_dict_mutation_not_carried(self): + """Checks that the optimization for large dictionaries + do not incorrectly update initial values due to other + mutations. + """ + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + a = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": 7, + } + if d.initial_value is None: + return lambda d: literally(d) + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, a) + return lambda d: d + + @njit + def foo(): + # This dictionary is mutated, check the initial_value carries + # correctly and is not mutated + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": 7, + } + d['X'] = 4 + bar(d) + + foo() + + @skip_unless_py10_or_later + def test_usercode_update_use_d2(self): + """ + Tests an example using a regular update is + not modified by the optimization. + """ + + def check_before(x): + pass + + def check_after(x): + pass + + checked_before = False + checked_after = False + + @overload(check_before, prefer_literal=True) + def ol_check_before(d): + nonlocal checked_before + # Typing iteration from d1.update(d2) + # may reset the initial values to None, + # so we only check on the first iteration. + if not checked_before: + checked_before = True + a = { + "a": 1, + "b": 2, + "c": 3, + } + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, a) + + return lambda d: None + + @overload(check_after, prefer_literal=True) + def ol_check_after(d): + nonlocal checked_after + # Typing iteration from d1.update(d2) + # may reset the initial values to None, + # so we only check on the first iteration. + if not checked_after: + checked_after = True + self.assertTrue(isinstance(d, types.DictType)) + self.assertTrue(d.initial_value is None) + + return lambda d: None + + def const_dict_func(): + """ + Dictionary update between two constant + dictionaries. This verifies d2 doesn't + get incorrectly removed. + """ + d1 = { + "a": 1, + "b": 2, + "c": 3, + } + d2 = { + "d": 4, + "e": 4 + } + check_before(d1) + d1.update(d2) + check_after(d1) + # Create a use of d2 in a new block. + if len(d1) > 4: + return d2 + return d1 + + py_func = const_dict_func + cfunc = njit()(const_dict_func) + a = py_func() + b = cfunc() + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_large_const_dict_inline_controlflow(self): + """ + Tests generating a large dictionary when one of + the inputs requires inline control flow + has the change suggested in the error message + for inlined control flow. + """ + def inline_func(a, flag): + # D is a heterogeneous dictionary + # so this code can only compile if + # d has constant keys. + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": 1 if flag else 2, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": a, + } + return d["S"] + + with self.assertRaises(UnsupportedBytecodeError) as raises: + njit()(inline_func)("a_string", False) + self.assertIn( + 'You can resolve this issue by moving the control flow out', + str(raises.exception) + ) + + @skip_unless_py10_or_later + def test_large_const_dict_noninline_controlflow(self): + """ + Tests generating large constant dict when one of the + inputs has the change suggested in the error message + for inlined control flow. + """ + def non_inline_func(a, flag): + # D is a heterogeneous dictionary + # so this code can only compile if + # d has constant keys. + val = 1 if flag else 2 + d = { + "A": 1, + "B": 1, + "C": 1, + "D": 1, + "E": 1, + "F": 1, + "G": 1, + "H": val, + "I": 1, + "J": 1, + "K": 1, + "L": 1, + "M": 1, + "N": 1, + "O": 1, + "P": 1, + "Q": 1, + "R": 1, + "S": a, + } + return d["S"] + + py_func = non_inline_func + cfunc = njit()(non_inline_func) + value = "a_string" + a = py_func(value, False) + b = cfunc(value, False) + self.assertEqual(a, b) + + @skip_unless_py10_or_later + def test_fuse_twice_literal_values(self): + """ + Tests that the correct literal values are generated + for a dictionary that produces two DICT_UPDATE + bytecode entries for the same dictionary. + """ + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + a = { + "a1" : 1, + "a2" : 2, + "a3" : 3, + "a4" : 4, + "a5" : 5, + "a6" : 6, + "a7" : 7, + "a8" : 8, + "a9" : 9, + "a10" : 10, + "a11" : 11, + "a12" : 12, + "a13" : 13, + "a14" : 14, + "a15" : 15, + "a16" : 16, + "a17" : 17, + "a18" : 18, + "a19" : 19, + "a20" : 20, + "a21" : 21, + "a22" : 22, + "a23" : 23, + "a24" : 24, + "a25" : 25, + "a26" : 26, + "a27" : 27, + "a28" : 28, + "a29" : 29, + "a30" : 30, + "a31" : 31, + "a32" : 32, + "a33" : 33, + "a34" : 34, # 34 items is the limit of + # (LOAD_CONST + MAP_ADD)^n + DICT_UPDATE + "a35" : 35, # 35 Generates an additional BUILD_MAP + DICT_UPDATE + } + if d.initial_value is None: + return lambda d: literally(d) + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, a) + return lambda d: d + + @njit + def foo(): + # This dictionary is mutated, check the initial_value carries + # correctly and is not mutated + d = { + "a1" : 1, + "a2" : 2, + "a3" : 3, + "a4" : 4, + "a5" : 5, + "a6" : 6, + "a7" : 7, + "a8" : 8, + "a9" : 9, + "a10" : 10, + "a11" : 11, + "a12" : 12, + "a13" : 13, + "a14" : 14, + "a15" : 15, + "a16" : 16, + "a17" : 17, + "a18" : 18, + "a19" : 19, + "a20" : 20, + "a21" : 21, + "a22" : 22, + "a23" : 23, + "a24" : 24, + "a25" : 25, + "a26" : 26, + "a27" : 27, + "a28" : 28, + "a29" : 29, + "a30" : 30, + "a31" : 31, + "a32" : 32, + "a33" : 33, + "a34" : 34, # 34 items is the limit of + # (LOAD_CONST + MAP_ADD)^n + DICT_UPDATE + "a35" : 35, # 35 Generates an additional BUILD_MAP + DICT_UPDATE + } + bar(d) + + foo() + + +class TestListExtendInStarArgNonTupleIterable(MemoryLeakMixin, TestCase): + """Test `fn(pos_arg0, pos_arg1, *args)` where args is a non-tuple iterable. + + Python 3.9+ will generate LIST_EXTEND bytecode to combine the positional + arguments with the `*args`. + + See #8059 + + NOTE: At the moment, there are no meaningful tests for NoPython because the + lack of support for `tuple(iterable)` for most iterable types. + """ + def test_list_extend_forceobj(self): + def consumer(*x): + return x + + @jit(forceobj=True) + def foo(x): + return consumer(1, 2, *x) + + got = foo("ijo") + expect = foo.py_func("ijo") + self.assertEqual(got, (1, 2, "i", "j", "o")) + self.assertEqual(got, expect) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_intwidth.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_intwidth.py new file mode 100644 index 0000000000000000000000000000000000000000..76c0effebf14364f0001db6736da2b68766f0dfe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_intwidth.py @@ -0,0 +1,90 @@ +import unittest + +import math +import sys + +from numba import jit +from numba.core import utils +from numba.tests.support import TestCase, tag + + +max_uint64 = 18446744073709551615 + +def usecase_uint64_global(): + return max_uint64 + +def usecase_uint64_constant(): + return 18446744073709551615 + +def usecase_uint64_func(): + return max(18446744073709551614, 18446744073709551615) + +def usecase_int64_pos(): + return 9223372036854775807 + +def usecase_int64_neg(): + return -9223372036854775808 + +def usecase_int64_func(): + return (max(9223372036854775807, -9223372036854775808) + + min(9223372036854775807, -9223372036854775808)) + + +class IntWidthTest(TestCase): + + def check_nullary_func(self, pyfunc, **kwargs): + cfunc = jit(**kwargs)(pyfunc) + self.assertPreciseEqual(cfunc(), pyfunc()) + + def test_global_uint64(self, nopython=False): + pyfunc = usecase_uint64_global + self.check_nullary_func(pyfunc, nopython=nopython) + + def test_global_uint64_npm(self): + self.test_global_uint64(nopython=True) + + def test_constant_uint64(self, nopython=False): + pyfunc = usecase_uint64_constant + self.check_nullary_func(pyfunc, nopython=nopython) + + def test_constant_uint64_npm(self): + self.test_constant_uint64(nopython=True) + + def test_constant_uint64_function_call(self, nopython=False): + pyfunc = usecase_uint64_func + self.check_nullary_func(pyfunc, nopython=nopython) + + def test_constant_uint64_function_call_npm(self): + self.test_constant_uint64_function_call(nopython=True) + + def test_bit_length(self): + f = utils.bit_length + self.assertEqual(f(0x7f), 7) + self.assertEqual(f(-0x7f), 7) + self.assertEqual(f(0x80), 8) + self.assertEqual(f(-0x80), 7) + self.assertEqual(f(0xff), 8) + self.assertEqual(f(-0xff), 8) + self.assertEqual(f(0x100), 9) + self.assertEqual(f(-0x100), 8) + self.assertEqual(f(-0x101), 9) + self.assertEqual(f(0x7fffffff), 31) + self.assertEqual(f(-0x7fffffff), 31) + self.assertEqual(f(-0x80000000), 31) + self.assertEqual(f(0x80000000), 32) + self.assertEqual(f(0xffffffff), 32) + self.assertEqual(f(0xffffffffffffffff), 64) + self.assertEqual(f(0x10000000000000000), 65) + + def test_constant_int64(self, nopython=False): + self.check_nullary_func(usecase_int64_pos, nopython=nopython) + self.check_nullary_func(usecase_int64_neg, nopython=nopython) + self.check_nullary_func(usecase_int64_func, nopython=nopython) + + def test_constant_int64_npm(self): + self.test_constant_int64(nopython=True) + + +if __name__ == '__main__': + unittest.main() + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_iteration.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..aea9869e9cc3d55a1e763f6870cb2873b4823680 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_iteration.py @@ -0,0 +1,241 @@ +import unittest +import numpy as np + +from numba import jit, njit +from numba.core import types, errors +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.np import numpy_support + + +force_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def int_tuple_iter_usecase(): + res = 0 + for i in (1, 2, 99, 3): + res += i + return res + +def float_tuple_iter_usecase(): + res = 0.0 + for i in (1.5, 2.0, 99.3, 3.4): + res += i + return res + +def tuple_tuple_iter_usecase(): + # Recursively homogeneous tuple type + res = 0.0 + for i in ((1.5, 2.0), (99.3, 3.4), (1.8, 2.5)): + for j in i: + res += j + res = res * 2 + return res + +def enumerate_nested_tuple_usecase(): + res = 0.0 + for i, j in enumerate(((1.5, 2.0), (99.3, 3.4), (1.8, 2.5))): + for l in j: + res += i * l + res = res * 2 + return res + +def nested_enumerate_usecase(): + res = 0.0 + for i, (j, k) in enumerate(enumerate(((1.5, 2.0), (99.3, 3.4), (1.8, 2.5)))): + for l in k: + res += i * j * l + res = res * 2 + return res + + +def enumerate_array_usecase(): + res = 0 + arrays = (np.ones(4), np.ones(5)) + for i, v in enumerate(arrays): + res += v.sum() + return res + + +def scalar_iter_usecase(iterable): + res = 0.0 + for x in iterable: + res += x + return res + +def record_iter_usecase(iterable): + res = 0.0 + for x in iterable: + res += x.a * x.b + return res + +def record_iter_mutate_usecase(iterable): + for x in iterable: + x.a = x.a + x.b + + +record_dtype = np.dtype([('a', np.float64), + ('b', np.int32), + ]) + + +class IterationTest(MemoryLeakMixin, TestCase): + + def run_nullary_func(self, pyfunc, flags): + cfunc = jit((), **flags)(pyfunc) + expected = pyfunc() + self.assertPreciseEqual(cfunc(), expected) + + def test_int_tuple_iter(self, flags=force_pyobj_flags): + self.run_nullary_func(int_tuple_iter_usecase, flags) + + def test_int_tuple_iter_npm(self): + self.test_int_tuple_iter(flags=no_pyobj_flags) + + # Type inference on tuples used to be hardcoded for ints, check + # that it works for other types. + + def test_float_tuple_iter(self, flags=force_pyobj_flags): + self.run_nullary_func(float_tuple_iter_usecase, flags) + + def test_float_tuple_iter_npm(self): + self.test_float_tuple_iter(flags=no_pyobj_flags) + + def test_tuple_tuple_iter(self, flags=force_pyobj_flags): + self.run_nullary_func(tuple_tuple_iter_usecase, flags) + + def test_tuple_tuple_iter_npm(self): + self.test_tuple_tuple_iter(flags=no_pyobj_flags) + + def test_enumerate_nested_tuple(self, flags=force_pyobj_flags): + self.run_nullary_func(enumerate_nested_tuple_usecase, flags) + + def test_enumerate_nested_tuple_npm(self): + self.test_enumerate_nested_tuple(flags=no_pyobj_flags) + + def test_nested_enumerate(self, flags=force_pyobj_flags): + self.run_nullary_func(nested_enumerate_usecase, flags) + + def test_nested_enumerate_npm(self): + self.test_nested_enumerate(flags=no_pyobj_flags) + + def test_enumerate_refct(self): + # Test issue 3473 + pyfunc = enumerate_array_usecase + cfunc = njit((),)(pyfunc) + expected = pyfunc() + self.assertPreciseEqual(cfunc(), expected) + + def run_array_1d(self, item_type, arg, flags): + # Iteration over a 1d numpy array + pyfunc = scalar_iter_usecase + cfunc = jit(item_type(types.Array(item_type, 1, 'A'),), **flags)(pyfunc) + self.assertPreciseEqual(cfunc(arg), pyfunc(arg)) + + def test_array_1d_float(self, flags=force_pyobj_flags): + self.run_array_1d(types.float64, np.arange(5.0), flags) + + def test_array_1d_float_npm(self): + self.test_array_1d_float(no_pyobj_flags) + + def test_array_1d_complex(self, flags=force_pyobj_flags): + self.run_array_1d(types.complex128, np.arange(5.0) * 1.0j, flags) + + def test_array_1d_complex_npm(self): + self.test_array_1d_complex(no_pyobj_flags) + + def test_array_1d_record(self, flags=force_pyobj_flags): + pyfunc = record_iter_usecase + item_type = numpy_support.from_dtype(record_dtype) + cfunc = jit((types.Array(item_type, 1, 'A'),), **flags)(pyfunc) + arr = np.recarray(3, dtype=record_dtype) + for i in range(3): + arr[i].a = float(i * 2) + arr[i].b = i + 2 + got = pyfunc(arr) + self.assertPreciseEqual(cfunc(arr), got) + + def test_array_1d_record_npm(self): + self.test_array_1d_record(no_pyobj_flags) + + def test_array_1d_record_mutate_npm(self, flags=no_pyobj_flags): + pyfunc = record_iter_mutate_usecase + item_type = numpy_support.from_dtype(record_dtype) + cfunc = jit((types.Array(item_type, 1, 'A'),), **flags)(pyfunc) + arr = np.recarray(3, dtype=record_dtype) + for i in range(3): + arr[i].a = float(i * 2) + arr[i].b = i + 2 + expected = arr.copy() + pyfunc(expected) + got = arr.copy() + cfunc(got) + self.assertPreciseEqual(expected, got) + + def test_array_1d_record_mutate(self): + self.test_array_1d_record_mutate_npm(flags=force_pyobj_flags) + + def test_array_0d_raises(self): + + def foo(x): + for i in x: + pass + + # 0d is typing error + with self.assertRaises(errors.TypingError) as raises: + aryty = types.Array(types.int32, 0, 'C') + njit((aryty,))(foo) + + self.assertIn("0-d array", str(raises.exception)) + + def test_tuple_iter_issue1504(self): + # The issue is due to `row` being typed as heterogeneous tuple. + def bar(x, y): + total = 0 + for row in zip(x, y): + total += row[0] + row[1] + + return total + + x = y = np.arange(3, dtype=np.int32) + aryty = types.Array(types.int32, 1, 'C') + cfunc = njit((aryty, aryty))(bar) + + expect = bar(x, y) + got = cfunc(x, y) + self.assertEqual(expect, got) + + def test_tuple_of_arrays_iter(self): + # We used to leak a reference to each element of the tuple + def bar(arrs): + total = 0 + for arr in arrs: + total += arr[0] + + return total + + x = y = np.arange(3, dtype=np.int32) + aryty = types.Array(types.int32, 1, 'C') + cfunc = njit((types.containers.UniTuple(aryty, 2),))(bar) + + expect = bar((x, y)) + got = cfunc((x, y)) + self.assertEqual(expect, got) + + + +class TestIterationRefct(MemoryLeakMixin, TestCase): + def test_zip_with_arrays(self): + @njit + def foo(sequence): + c = 0 + for a, b in zip(range(len(sequence)), sequence): + c += (a + 1) * b.sum() + return + + sequence = [np.arange(1 + i) for i in range(10)] + self.assertEqual(foo(sequence), foo.py_func(sequence)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jit_module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jit_module.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9697aecd49ce4e15494a484f46c41d8d82e9f8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jit_module.py @@ -0,0 +1,146 @@ +import os +import sys +import inspect +import contextlib +import numpy as np +import logging +from io import StringIO + +import unittest +from numba.tests.support import SerialMixin, create_temp_module +from numba.core import dispatcher + + +@contextlib.contextmanager +def captured_logs(l): + try: + buffer = StringIO() + handler = logging.StreamHandler(buffer) + l.addHandler(handler) + yield buffer + finally: + l.removeHandler(handler) + + +class TestJitModule(SerialMixin, unittest.TestCase): + + source_lines = """ +from numba import jit_module + +def inc(x): + return x + 1 + +def add(x, y): + return x + y + +def inc_add(x): + y = inc(x) + return add(x, y) + +import numpy as np +mean = np.mean + +class Foo(object): + pass + +jit_module({jit_options}) +""" + + def test_create_temp_jitted_module(self): + sys_path_original = list(sys.path) + sys_modules_original = dict(sys.modules) + with create_temp_module(self.source_lines) as test_module: + temp_module_dir = os.path.dirname(test_module.__file__) + self.assertEqual(temp_module_dir, sys.path[0]) + self.assertEqual(sys.path[1:], sys_path_original) + self.assertTrue(test_module.__name__ in sys.modules) + # Test that modifications to sys.path / sys.modules are reverted + self.assertEqual(sys.path, sys_path_original) + self.assertEqual(sys.modules, sys_modules_original) + + def test_create_temp_jitted_module_with_exception(self): + try: + sys_path_original = list(sys.path) + sys_modules_original = dict(sys.modules) + with create_temp_module(self.source_lines): + raise ValueError("Something went wrong!") + except ValueError: + # Test that modifications to sys.path / sys.modules are reverted + self.assertEqual(sys.path, sys_path_original) + self.assertEqual(sys.modules, sys_modules_original) + + def test_jit_module(self): + with create_temp_module(self.source_lines) as test_module: + self.assertIsInstance(test_module.inc, dispatcher.Dispatcher) + self.assertIsInstance(test_module.add, dispatcher.Dispatcher) + self.assertIsInstance(test_module.inc_add, dispatcher.Dispatcher) + self.assertTrue(test_module.mean is np.mean) + self.assertTrue(inspect.isclass(test_module.Foo)) + + # Test output of jitted functions is as expected + x, y = 1.7, 2.3 + self.assertEqual(test_module.inc(x), + test_module.inc.py_func(x)) + self.assertEqual(test_module.add(x, y), + test_module.add.py_func(x, y)) + self.assertEqual(test_module.inc_add(x), + test_module.inc_add.py_func(x)) + + def test_jit_module_jit_options(self): + jit_options = {"nopython": True, + "nogil": False, + "error_model": "numpy", + "boundscheck": False, + } + with create_temp_module(self.source_lines, + **jit_options) as test_module: + self.assertEqual(test_module.inc.targetoptions, jit_options) + + def test_jit_module_jit_options_override(self): + source_lines = """ +from numba import jit, jit_module + +@jit(nogil=True, forceobj=True) +def inc(x): + return x + 1 + +def add(x, y): + return x + y + +jit_module({jit_options}) +""" + jit_options = {"nopython": True, + "error_model": "numpy", + "boundscheck": False, + } + with create_temp_module(source_lines=source_lines, + **jit_options) as test_module: + self.assertEqual(test_module.add.targetoptions, jit_options) + # Test that manual jit-wrapping overrides jit_module options, + # `forceobj` will automatically apply `nopython=False`. + self.assertEqual(test_module.inc.targetoptions, + {'nogil': True, 'forceobj': True, + 'boundscheck': None, 'nopython': False}) + + def test_jit_module_logging_output(self): + logger = logging.getLogger('numba.core.decorators') + logger.setLevel(logging.DEBUG) + jit_options = {"nopython": True, + "error_model": "numpy", + } + with captured_logs(logger) as logs: + with create_temp_module(self.source_lines, + **jit_options) as test_module: + logs = logs.getvalue() + expected = ["Auto decorating function", + "from module {}".format(test_module.__name__), + "with jit and options: {}".format(jit_options)] + self.assertTrue(all(i in logs for i in expected)) + + def test_jit_module_logging_level(self): + logger = logging.getLogger('numba.core.decorators') + # Test there's no logging for INFO level + logger.setLevel(logging.INFO) + with captured_logs(logger) as logs: + with create_temp_module(self.source_lines): + self.assertEqual(logs.getvalue(), '') diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitclasses.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..293ef72c840124d5dd61b8f76f909e2276ea8647 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitclasses.py @@ -0,0 +1,2044 @@ +import ctypes +import itertools +import pickle +import random +import typing as pt +import unittest + +from collections import OrderedDict + +import numpy as np +from numba import (boolean, deferred_type, float32, float64, int16, int32, + njit, optional, typeof) +from numba.core import errors, types +from numba.core.dispatcher import Dispatcher +from numba.core.errors import LoweringError, TypingError +from numba.core.runtime.nrt import MemInfo +from numba.experimental import jitclass +from numba.experimental.jitclass import _box +from numba.experimental.jitclass.base import JitClassType +from numba.tests.support import MemoryLeakMixin, TestCase, skip_if_typeguard +from numba.tests.support import skip_unless_scipy + + +class TestClass1(object): + def __init__(self, x, y, z=1, *, a=5): + self.x = x + self.y = y + self.z = z + self.a = a + + +class TestClass2(object): + def __init__(self, x, y, z=1, *args, a=5): + self.x = x + self.y = y + self.z = z + self.args = args + self.a = a + + +def _get_meminfo(box): + ptr = _box.box_get_meminfoptr(box) + mi = MemInfo(ptr) + mi.acquire() + return mi + + +class TestJitClass(TestCase, MemoryLeakMixin): + + def _check_spec(self, spec=None, test_cls=None, all_expected=None): + if test_cls is None: + @jitclass(spec) + class Test(object): + + def __init__(self): + pass + test_cls = Test + + clsty = test_cls.class_type.instance_type + names = list(clsty.struct.keys()) + values = list(clsty.struct.values()) + + if all_expected is None: + if isinstance(spec, OrderedDict): + all_expected = spec.items() + else: + all_expected = spec + + assert all_expected is not None + + self.assertEqual(len(names), len(all_expected)) + for got, expected in zip(zip(names, values), all_expected): + self.assertEqual(got[0], expected[0]) + self.assertEqual(got[1], expected[1]) + + def test_ordereddict_spec(self): + spec = OrderedDict() + spec["x"] = int32 + spec["y"] = float32 + self._check_spec(spec) + + def test_list_spec(self): + spec = [("x", int32), + ("y", float32)] + self._check_spec(spec) + + def test_type_annotations(self): + spec = [("x", int32)] + + @jitclass(spec) + class Test1(object): + x: int + y: pt.List[float] + + def __init__(self): + pass + + self._check_spec(spec, Test1, spec + [("y", types.ListType(float64))]) + + def test_type_annotation_inheritance(self): + + class Foo: + x: int + + @jitclass + class Bar(Foo): + y: float + + def __init__(self, value: float) -> None: + self.x = int(value) + self.y = value + + self._check_spec( + test_cls=Bar, all_expected=[("x", typeof(0)), ("y", typeof(0.0))] + ) + + def test_spec_errors(self): + spec1 = [("x", int), ("y", float32[:])] + spec2 = [(1, int32), ("y", float32[:])] + + class Test(object): + + def __init__(self): + pass + + with self.assertRaises(TypeError) as raises: + jitclass(Test, spec1) + self.assertIn("spec values should be Numba type instances", + str(raises.exception)) + with self.assertRaises(TypeError) as raises: + jitclass(Test, spec2) + self.assertEqual(str(raises.exception), + "spec keys should be strings, got 1") + + def test_init_errors(self): + + @jitclass([]) + class Test: + def __init__(self): + return 7 + + with self.assertRaises(errors.TypingError) as raises: + Test() + + self.assertIn("__init__() should return None, not", + str(raises.exception)) + + def _make_Float2AndArray(self): + spec = OrderedDict() + spec["x"] = float32 + spec["y"] = float32 + spec["arr"] = float32[:] + + @jitclass(spec) + class Float2AndArray(object): + + def __init__(self, x, y, arr): + self.x = x + self.y = y + self.arr = arr + + def add(self, val): + self.x += val + self.y += val + return val + + return Float2AndArray + + def _make_Vector2(self): + spec = OrderedDict() + spec["x"] = int32 + spec["y"] = int32 + + @jitclass(spec) + class Vector2(object): + + def __init__(self, x, y): + self.x = x + self.y = y + + return Vector2 + + def test_jit_class_1(self): + Float2AndArray = self._make_Float2AndArray() + Vector2 = self._make_Vector2() + + @njit + def bar(obj): + return obj.x + obj.y + + @njit + def foo(a): + obj = Float2AndArray(1, 2, a) + obj.add(123) + + vec = Vector2(3, 4) + return bar(obj), bar(vec), obj.arr + + inp = np.ones(10, dtype=np.float32) + a, b, c = foo(inp) + self.assertEqual(a, 123 + 1 + 123 + 2) + self.assertEqual(b, 3 + 4) + self.assertPreciseEqual(c, inp) + + def test_jitclass_usage_from_python(self): + Float2AndArray = self._make_Float2AndArray() + + @njit + def identity(obj): + return obj + + @njit + def retrieve_attributes(obj): + return obj.x, obj.y, obj.arr + + arr = np.arange(10, dtype=np.float32) + obj = Float2AndArray(1, 2, arr) + obj_meminfo = _get_meminfo(obj) + self.assertEqual(obj_meminfo.refcount, 2) + self.assertEqual(obj_meminfo.data, _box.box_get_dataptr(obj)) + self.assertEqual(obj._numba_type_.class_type, + Float2AndArray.class_type) + # Use jit class instance in numba + other = identity(obj) + other_meminfo = _get_meminfo(other) # duplicates MemInfo object to obj + self.assertEqual(obj_meminfo.refcount, 4) + self.assertEqual(other_meminfo.refcount, 4) + self.assertEqual(other_meminfo.data, _box.box_get_dataptr(other)) + self.assertEqual(other_meminfo.data, obj_meminfo.data) + + # Check dtor + del other, other_meminfo + self.assertEqual(obj_meminfo.refcount, 2) + + # Check attributes + out_x, out_y, out_arr = retrieve_attributes(obj) + self.assertEqual(out_x, 1) + self.assertEqual(out_y, 2) + self.assertIs(out_arr, arr) + + # Access attributes from python + self.assertEqual(obj.x, 1) + self.assertEqual(obj.y, 2) + self.assertIs(obj.arr, arr) + + # Access methods from python + self.assertEqual(obj.add(123), 123) + self.assertEqual(obj.x, 1 + 123) + self.assertEqual(obj.y, 2 + 123) + + # Setter from python + obj.x = 333 + obj.y = 444 + obj.arr = newarr = np.arange(5, dtype=np.float32) + self.assertEqual(obj.x, 333) + self.assertEqual(obj.y, 444) + self.assertIs(obj.arr, newarr) + + def test_jitclass_datalayout(self): + spec = OrderedDict() + # Boolean has different layout as value vs data + spec["val"] = boolean + + @jitclass(spec) + class Foo(object): + + def __init__(self, val): + self.val = val + + self.assertTrue(Foo(True).val) + self.assertFalse(Foo(False).val) + + def test_deferred_type(self): + node_type = deferred_type() + + spec = OrderedDict() + spec["data"] = float32 + spec["next"] = optional(node_type) + + @njit + def get_data(node): + return node.data + + @jitclass(spec) + class LinkedNode(object): + + def __init__(self, data, next): + self.data = data + self.next = next + + def get_next_data(self): + # use deferred type as argument + return get_data(self.next) + + def append_to_tail(self, other): + cur = self + while cur.next is not None: + cur = cur.next + cur.next = other + + node_type.define(LinkedNode.class_type.instance_type) + + first = LinkedNode(123, None) + self.assertEqual(first.data, 123) + self.assertIsNone(first.next) + + second = LinkedNode(321, first) + + first_meminfo = _get_meminfo(first) + second_meminfo = _get_meminfo(second) + self.assertEqual(first_meminfo.refcount, 3) + self.assertEqual(second.next.data, first.data) + self.assertEqual(first_meminfo.refcount, 3) + self.assertEqual(second_meminfo.refcount, 2) + + # Test using deferred type as argument + first_val = second.get_next_data() + self.assertEqual(first_val, first.data) + + # Check setattr (issue #2606) + self.assertIsNone(first.next) + second.append_to_tail(LinkedNode(567, None)) + self.assertIsNotNone(first.next) + self.assertEqual(first.next.data, 567) + self.assertIsNone(first.next.next) + second.append_to_tail(LinkedNode(678, None)) + self.assertIsNotNone(first.next.next) + self.assertEqual(first.next.next.data, 678) + + # Check ownership + self.assertEqual(first_meminfo.refcount, 3) + del second, second_meminfo + self.assertEqual(first_meminfo.refcount, 2) + + def test_c_structure(self): + spec = OrderedDict() + spec["a"] = int32 + spec["b"] = int16 + spec["c"] = float64 + + @jitclass(spec) + class Struct(object): + + def __init__(self, a, b, c): + self.a = a + self.b = b + self.c = c + + st = Struct(0xabcd, 0xef, 3.1415) + + class CStruct(ctypes.Structure): + _fields_ = [ + ("a", ctypes.c_int32), + ("b", ctypes.c_int16), + ("c", ctypes.c_double), + ] + + ptr = ctypes.c_void_p(_box.box_get_dataptr(st)) + cstruct = ctypes.cast(ptr, ctypes.POINTER(CStruct))[0] + self.assertEqual(cstruct.a, st.a) + self.assertEqual(cstruct.b, st.b) + self.assertEqual(cstruct.c, st.c) + + def test_is(self): + Vector = self._make_Vector2() + vec_a = Vector(1, 2) + + @njit + def do_is(a, b): + return a is b + + with self.assertRaises(LoweringError) as raises: + # trigger compilation + do_is(vec_a, vec_a) + self.assertIn("no default `is` implementation", str(raises.exception)) + + def test_isinstance(self): + Vector2 = self._make_Vector2() + vec = Vector2(1, 2) + self.assertIsInstance(vec, Vector2) + + def test_subclassing(self): + Vector2 = self._make_Vector2() + with self.assertRaises(TypeError) as raises: + class SubV(Vector2): + pass + self.assertEqual(str(raises.exception), + "cannot subclass from a jitclass") + + def test_base_class(self): + class Base(object): + + def what(self): + return self.attr + + @jitclass([("attr", int32)]) + class Test(Base): + + def __init__(self, attr): + self.attr = attr + + obj = Test(123) + self.assertEqual(obj.what(), 123) + + def test_globals(self): + + class Mine(object): + constant = 123 + + def __init__(self): + pass + + with self.assertRaises(TypeError) as raises: + jitclass(Mine) + + self.assertEqual(str(raises.exception), + "class members are not yet supported: constant") + + def test_user_getter_setter(self): + @jitclass([("attr", int32)]) + class Foo(object): + + def __init__(self, attr): + self.attr = attr + + @property + def value(self): + return self.attr + 1 + + @value.setter + def value(self, val): + self.attr = val - 1 + + foo = Foo(123) + self.assertEqual(foo.attr, 123) + # Getter + self.assertEqual(foo.value, 123 + 1) + # Setter + foo.value = 789 + self.assertEqual(foo.attr, 789 - 1) + self.assertEqual(foo.value, 789) + + # Test nopython mode usage of getter and setter + @njit + def bar(foo, val): + a = foo.value + foo.value = val + b = foo.value + c = foo.attr + return a, b, c + + a, b, c = bar(foo, 567) + self.assertEqual(a, 789) + self.assertEqual(b, 567) + self.assertEqual(c, 567 - 1) + + def test_user_deleter_error(self): + class Foo(object): + + def __init__(self): + pass + + @property + def value(self): + return 1 + + @value.deleter + def value(self): + pass + + with self.assertRaises(TypeError) as raises: + jitclass(Foo) + self.assertEqual(str(raises.exception), + "deleter is not supported: value") + + def test_name_shadowing_error(self): + class Foo(object): + + def __init__(self): + pass + + @property + def my_property(self): + pass + + def my_method(self): + pass + + with self.assertRaises(NameError) as raises: + jitclass(Foo, [("my_property", int32)]) + self.assertEqual(str(raises.exception), "name shadowing: my_property") + + with self.assertRaises(NameError) as raises: + jitclass(Foo, [("my_method", int32)]) + self.assertEqual(str(raises.exception), "name shadowing: my_method") + + def test_distinct_classes(self): + # Different classes with the same names shouldn't confuse the compiler + @jitclass([("x", int32)]) + class Foo(object): + + def __init__(self, x): + self.x = x + 2 + + def run(self): + return self.x + 1 + + FirstFoo = Foo + + @jitclass([("x", int32)]) + class Foo(object): + + def __init__(self, x): + self.x = x - 2 + + def run(self): + return self.x - 1 + + SecondFoo = Foo + foo = FirstFoo(5) + self.assertEqual(foo.x, 7) + self.assertEqual(foo.run(), 8) + foo = SecondFoo(5) + self.assertEqual(foo.x, 3) + self.assertEqual(foo.run(), 2) + + def test_parameterized(self): + class MyClass(object): + + def __init__(self, value): + self.value = value + + def create_my_class(value): + cls = jitclass(MyClass, [("value", typeof(value))]) + return cls(value) + + a = create_my_class(123) + self.assertEqual(a.value, 123) + + b = create_my_class(12.3) + self.assertEqual(b.value, 12.3) + + c = create_my_class(np.array([123])) + np.testing.assert_equal(c.value, [123]) + + d = create_my_class(np.array([12.3])) + np.testing.assert_equal(d.value, [12.3]) + + def test_protected_attrs(self): + spec = { + "value": int32, + "_value": float32, + "__value": int32, + "__value__": int32, + } + + @jitclass(spec) + class MyClass(object): + + def __init__(self, value): + self.value = value + self._value = value / 2 + self.__value = value * 2 + self.__value__ = value - 1 + + @property + def private_value(self): + return self.__value + + @property + def _inner_value(self): + return self._value + + @_inner_value.setter + def _inner_value(self, v): + self._value = v + + @property + def __private_value(self): + return self.__value + + @__private_value.setter + def __private_value(self, v): + self.__value = v + + def swap_private_value(self, new): + old = self.__private_value + self.__private_value = new + return old + + def _protected_method(self, factor): + return self._value * factor + + def __private_method(self, factor): + return self.__value * factor + + def check_private_method(self, factor): + return self.__private_method(factor) + + value = 123 + inst = MyClass(value) + # test attributes + self.assertEqual(inst.value, value) + self.assertEqual(inst._value, value / 2) + self.assertEqual(inst.private_value, value * 2) + # test properties + self.assertEqual(inst._inner_value, inst._value) + freeze_inst_value = inst._value + inst._inner_value -= 1 + self.assertEqual(inst._inner_value, freeze_inst_value - 1) + + self.assertEqual(inst.swap_private_value(321), value * 2) + self.assertEqual(inst.swap_private_value(value * 2), 321) + # test methods + self.assertEqual(inst._protected_method(3), inst._value * 3) + self.assertEqual(inst.check_private_method(3), inst.private_value * 3) + # test special + self.assertEqual(inst.__value__, value - 1) + inst.__value__ -= 100 + self.assertEqual(inst.__value__, value - 101) + + # test errors + @njit + def access_dunder(inst): + return inst.__value + + with self.assertRaises(errors.TypingError) as raises: + access_dunder(inst) + # It will appear as "_TestJitClass__value" because the `access_dunder` + # is under the scope of "TestJitClass". + self.assertIn("_TestJitClass__value", str(raises.exception)) + + with self.assertRaises(AttributeError) as raises: + access_dunder.py_func(inst) + self.assertIn("_TestJitClass__value", str(raises.exception)) + + @skip_if_typeguard + def test_annotations(self): + """ + Methods with annotations should compile fine (issue #1911). + """ + from .annotation_usecases import AnnotatedClass + + spec = {"x": int32} + cls = jitclass(AnnotatedClass, spec) + + obj = cls(5) + self.assertEqual(obj.x, 5) + self.assertEqual(obj.add(2), 7) + + def test_docstring(self): + + @jitclass + class Apple(object): + "Class docstring" + + def __init__(self): + "init docstring" + + def foo(self): + "foo method docstring" + + @property + def aval(self): + "aval property docstring" + + self.assertEqual(Apple.__doc__, "Class docstring") + self.assertEqual(Apple.__init__.__doc__, "init docstring") + self.assertEqual(Apple.foo.__doc__, "foo method docstring") + self.assertEqual(Apple.aval.__doc__, "aval property docstring") + + def test_kwargs(self): + spec = [("a", int32), + ("b", float64)] + + @jitclass(spec) + class TestClass(object): + def __init__(self, x, y, z): + self.a = x * y + self.b = z + + x = 2 + y = 2 + z = 1.1 + kwargs = {"y": y, "z": z} + tc = TestClass(x=2, **kwargs) + self.assertEqual(tc.a, x * y) + self.assertEqual(tc.b, z) + + def test_default_args(self): + spec = [("x", int32), + ("y", int32), + ("z", int32)] + + @jitclass(spec) + class TestClass(object): + def __init__(self, x, y, z=1): + self.x = x + self.y = y + self.z = z + + tc = TestClass(1, 2, 3) + self.assertEqual(tc.x, 1) + self.assertEqual(tc.y, 2) + self.assertEqual(tc.z, 3) + + tc = TestClass(1, 2) + self.assertEqual(tc.x, 1) + self.assertEqual(tc.y, 2) + self.assertEqual(tc.z, 1) + + tc = TestClass(y=2, z=5, x=1) + self.assertEqual(tc.x, 1) + self.assertEqual(tc.y, 2) + self.assertEqual(tc.z, 5) + + def test_default_args_keyonly(self): + spec = [("x", int32), + ("y", int32), + ("z", int32), + ("a", int32)] + + TestClass = jitclass(TestClass1, spec) + + tc = TestClass(2, 3) + self.assertEqual(tc.x, 2) + self.assertEqual(tc.y, 3) + self.assertEqual(tc.z, 1) + self.assertEqual(tc.a, 5) + + tc = TestClass(y=4, x=2, a=42, z=100) + self.assertEqual(tc.x, 2) + self.assertEqual(tc.y, 4) + self.assertEqual(tc.z, 100) + self.assertEqual(tc.a, 42) + + tc = TestClass(y=4, x=2, a=42) + self.assertEqual(tc.x, 2) + self.assertEqual(tc.y, 4) + self.assertEqual(tc.z, 1) + self.assertEqual(tc.a, 42) + + tc = TestClass(y=4, x=2) + self.assertEqual(tc.x, 2) + self.assertEqual(tc.y, 4) + self.assertEqual(tc.z, 1) + self.assertEqual(tc.a, 5) + + def test_default_args_starargs_and_keyonly(self): + spec = [("x", int32), + ("y", int32), + ("z", int32), + ("args", types.UniTuple(int32, 2)), + ("a", int32)] + + with self.assertRaises(errors.UnsupportedError) as raises: + jitclass(TestClass2, spec) + + msg = "VAR_POSITIONAL argument type unsupported" + self.assertIn(msg, str(raises.exception)) + + def test_generator_method(self): + spec = [] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + pass + + def gen(self, niter): + for i in range(niter): + yield np.arange(i) + + def expected_gen(niter): + for i in range(niter): + yield np.arange(i) + + for niter in range(10): + for expect, got in zip(expected_gen(niter), TestClass().gen(niter)): + self.assertPreciseEqual(expect, got) + + def test_getitem(self): + spec = [("data", int32[:])] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + self.data = np.zeros(10, dtype=np.int32) + + def __setitem__(self, key, data): + self.data[key] = data + + def __getitem__(self, key): + return self.data[key] + + @njit + def create_and_set_indices(): + t = TestClass() + t[1] = 1 + t[2] = 2 + t[3] = 3 + return t + + @njit + def get_index(t, n): + return t[n] + + t = create_and_set_indices() + self.assertEqual(get_index(t, 1), 1) + self.assertEqual(get_index(t, 2), 2) + self.assertEqual(get_index(t, 3), 3) + + def test_getitem_unbox(self): + spec = [("data", int32[:])] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + self.data = np.zeros(10, dtype=np.int32) + + def __setitem__(self, key, data): + self.data[key] = data + + def __getitem__(self, key): + return self.data[key] + + t = TestClass() + t[1] = 10 + + @njit + def set2return1(t): + t[2] = 20 + return t[1] + + t_1 = set2return1(t) + self.assertEqual(t_1, 10) + self.assertEqual(t[2], 20) + + def test_getitem_complex_key(self): + spec = [("data", int32[:, :])] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + self.data = np.zeros((10, 10), dtype=np.int32) + + def __setitem__(self, key, data): + self.data[int(key.real), int(key.imag)] = data + + def __getitem__(self, key): + return self.data[int(key.real), int(key.imag)] + + t = TestClass() + + t[complex(1, 1)] = 3 + + @njit + def get_key(t, real, imag): + return t[complex(real, imag)] + + @njit + def set_key(t, real, imag, data): + t[complex(real, imag)] = data + + self.assertEqual(get_key(t, 1, 1), 3) + set_key(t, 2, 2, 4) + self.assertEqual(t[complex(2, 2)], 4) + + def test_getitem_tuple_key(self): + spec = [("data", int32[:, :])] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + self.data = np.zeros((10, 10), dtype=np.int32) + + def __setitem__(self, key, data): + self.data[key[0], key[1]] = data + + def __getitem__(self, key): + return self.data[key[0], key[1]] + + t = TestClass() + t[1, 1] = 11 + + @njit + def get11(t): + return t[1, 1] + + @njit + def set22(t, data): + t[2, 2] = data + + self.assertEqual(get11(t), 11) + set22(t, 22) + self.assertEqual(t[2, 2], 22) + + def test_getitem_slice_key(self): + spec = [("data", int32[:])] + + @jitclass(spec) + class TestClass(object): + def __init__(self): + self.data = np.zeros(10, dtype=np.int32) + + def __setitem__(self, slc, data): + self.data[slc.start] = data + self.data[slc.stop] = data + slc.step + + def __getitem__(self, slc): + return self.data[slc.start] + + t = TestClass() + # set t.data[1] = 1 and t.data[5] = 2 + t[1:5:1] = 1 + + self.assertEqual(t[1:1:1], 1) + self.assertEqual(t[5:5:5], 2) + + @njit + def get5(t): + return t[5:6:1] + + self.assertEqual(get5(t), 2) + + # sets t.data[2] = data, and t.data[6] = data + 1 + @njit + def set26(t, data): + t[2:6:1] = data + + set26(t, 2) + self.assertEqual(t[2:2:1], 2) + self.assertEqual(t[6:6:1], 3) + + def test_jitclass_longlabel_not_truncated(self): + # See issue #3872, llvm 7 introduced a max label length of 1024 chars + # Numba ships patched llvm 7.1 (ppc64le) and patched llvm 8 to undo this + # change, this test is here to make sure long labels are ok: + alphabet = [chr(ord("a") + x) for x in range(26)] + + spec = [(letter * 10, float64) for letter in alphabet] + spec.extend([(letter.upper() * 10, float64) for letter in alphabet]) + + @jitclass(spec) + class TruncatedLabel(object): + def __init__(self,): + self.aaaaaaaaaa = 10. + + def meth1(self): + self.bbbbbbbbbb = random.gauss(self.aaaaaaaaaa, self.aaaaaaaaaa) + + def meth2(self): + self.meth1() + + # unpatched LLVMs will raise here... + TruncatedLabel().meth2() + + def test_pickling(self): + @jitclass + class PickleTestSubject(object): + def __init__(self): + pass + + inst = PickleTestSubject() + ty = typeof(inst) + self.assertIsInstance(ty, types.ClassInstanceType) + pickled = pickle.dumps(ty) + self.assertIs(pickle.loads(pickled), ty) + + def test_static_methods(self): + @jitclass([("x", int32)]) + class Test1: + def __init__(self, x): + self.x = x + + def increase(self, y): + self.x = self.add(self.x, y) + return self.x + + @staticmethod + def add(a, b): + return a + b + + @staticmethod + def sub(a, b): + return a - b + + @jitclass([("x", int32)]) + class Test2: + def __init__(self, x): + self.x = x + + def increase(self, y): + self.x = self.add(self.x, y) + return self.x + + @staticmethod + def add(a, b): + return a - b + + self.assertIsInstance(Test1.add, Dispatcher) + self.assertIsInstance(Test1.sub, Dispatcher) + self.assertIsInstance(Test2.add, Dispatcher) + self.assertNotEqual(Test1.add, Test2.add) + + self.assertEqual(3, Test1.add(1, 2)) + self.assertEqual(-1, Test2.add(1, 2)) + self.assertEqual(4, Test1.sub(6, 2)) + + t1 = Test1(0) + t2 = Test2(0) + self.assertEqual(1, t1.increase(1)) + self.assertEqual(-1, t2.increase(1)) + self.assertEqual(2, t1.add(1, 1)) + self.assertEqual(0, t1.sub(1, 1)) + self.assertEqual(0, t2.add(1, 1)) + self.assertEqual(2j, t1.add(1j, 1j)) + self.assertEqual(1j, t1.sub(2j, 1j)) + self.assertEqual("foobar", t1.add("foo", "bar")) + + with self.assertRaises(AttributeError) as raises: + Test2.sub(3, 1) + self.assertIn("has no attribute 'sub'", + str(raises.exception)) + + with self.assertRaises(TypeError) as raises: + Test1.add(3) + self.assertIn("not enough arguments: expected 2, got 1", + str(raises.exception)) + + # Check error message for calling a static method as a class attr from + # another method (currently unsupported). + + @jitclass([]) + class Test3: + def __init__(self): + pass + + @staticmethod + def a_static_method(a, b): + pass + + def call_static(self): + return Test3.a_static_method(1, 2) + + invalid = Test3() + with self.assertRaises(errors.TypingError) as raises: + invalid.call_static() + + self.assertIn("Unknown attribute 'a_static_method'", + str(raises.exception)) + + def test_jitclass_decorator_usecases(self): + spec = OrderedDict(x=float64) + + @jitclass() + class Test1: + x: float + + def __init__(self): + self.x = 0 + + self.assertIsInstance(Test1, JitClassType) + self.assertDictEqual(Test1.class_type.struct, spec) + + @jitclass(spec=spec) + class Test2: + + def __init__(self): + self.x = 0 + + self.assertIsInstance(Test2, JitClassType) + self.assertDictEqual(Test2.class_type.struct, spec) + + @jitclass + class Test3: + x: float + + def __init__(self): + self.x = 0 + + self.assertIsInstance(Test3, JitClassType) + self.assertDictEqual(Test3.class_type.struct, spec) + + @jitclass(spec) + class Test4: + + def __init__(self): + self.x = 0 + + self.assertIsInstance(Test4, JitClassType) + self.assertDictEqual(Test4.class_type.struct, spec) + + def test_jitclass_function_usecases(self): + spec = OrderedDict(x=float64) + + class AnnotatedTest: + x: float + + def __init__(self): + self.x = 0 + + JitTest1 = jitclass(AnnotatedTest) + self.assertIsInstance(JitTest1, JitClassType) + self.assertDictEqual(JitTest1.class_type.struct, spec) + + class UnannotatedTest: + + def __init__(self): + self.x = 0 + + JitTest2 = jitclass(UnannotatedTest, spec) + self.assertIsInstance(JitTest2, JitClassType) + self.assertDictEqual(JitTest2.class_type.struct, spec) + + def test_jitclass_isinstance(self): + spec = OrderedDict(value=int32) + + @jitclass(spec) + class Foo(object): + def __init__(self, value): + self.value = value + + def getValue(self): + return self.value + + def getValueIncr(self): + return self.value + 1 + + @jitclass(spec) + class Bar(object): + def __init__(self, value): + self.value = value + + def getValue(self): + return self.value + + def test_jitclass_isinstance(obj): + if isinstance(obj, (Foo, Bar)): + # call something that both classes implements + x = obj.getValue() + if isinstance(obj, Foo): # something that only Foo implements + return obj.getValueIncr() + x, 'Foo' + else: + return obj.getValue() + x, 'Bar' + else: + return 'no match' + + pyfunc = test_jitclass_isinstance + cfunc = njit(test_jitclass_isinstance) + + self.assertIsInstance(Foo, JitClassType) + self.assertEqual(pyfunc(Foo(3)), cfunc(Foo(3))) + self.assertEqual(pyfunc(Bar(123)), cfunc(Bar(123))) + self.assertEqual(pyfunc(0), cfunc(0)) + + def test_jitclass_unsupported_dunder(self): + with self.assertRaises(TypeError) as e: + @jitclass + class Foo(object): + def __init__(self): + return + + def __enter__(self): + return None + Foo() + self.assertIn("Method '__enter__' is not supported.", str(e.exception)) + + def test_modulename(self): + @jitclass + class TestModname(object): + def __init__(self): + self.x = 12 + + thisModule = __name__ + classModule = TestModname.__module__ + self.assertEqual(thisModule, classModule) + + +class TestJitClassOverloads(MemoryLeakMixin, TestCase): + + class PyList: + def __init__(self): + self.x = [0] + + def append(self, y): + self.x.append(y) + + def clear(self): + self.x.clear() + + def __abs__(self): + return len(self.x) * 7 + + def __bool__(self): + return len(self.x) % 3 != 0 + + def __complex__(self): + c = complex(2) + if self.x: + c += self.x[0] + return c + + def __contains__(self, y): + return y in self.x + + def __float__(self): + f = 3.1415 + if self.x: + f += self.x[0] + return f + + def __int__(self): + i = 5 + if self.x: + i += self.x[0] + return i + + def __len__(self): + return len(self.x) + 1 + + def __str__(self): + if len(self.x) == 0: + return "PyList empty" + else: + return "PyList non-empty" + + @staticmethod + def get_int_wrapper(): + @jitclass([("x", types.intp)]) + class IntWrapper: + def __init__(self, value): + self.x = value + + def __eq__(self, other): + return self.x == other.x + + def __hash__(self): + return self.x + + def __lshift__(self, other): + return IntWrapper(self.x << other.x) + + def __rshift__(self, other): + return IntWrapper(self.x >> other.x) + + def __and__(self, other): + return IntWrapper(self.x & other.x) + + def __or__(self, other): + return IntWrapper(self.x | other.x) + + def __xor__(self, other): + return IntWrapper(self.x ^ other.x) + + return IntWrapper + + @staticmethod + def get_float_wrapper(): + @jitclass([("x", types.float64)]) + class FloatWrapper: + + def __init__(self, value): + self.x = value + + def __eq__(self, other): + return self.x == other.x + + def __hash__(self): + return self.x + + def __ge__(self, other): + return self.x >= other.x + + def __gt__(self, other): + return self.x > other.x + + def __le__(self, other): + return self.x <= other.x + + def __lt__(self, other): + return self.x < other.x + + def __add__(self, other): + return FloatWrapper(self.x + other.x) + + def __floordiv__(self, other): + return FloatWrapper(self.x // other.x) + + def __mod__(self, other): + return FloatWrapper(self.x % other.x) + + def __mul__(self, other): + return FloatWrapper(self.x * other.x) + + def __neg__(self, other): + return FloatWrapper(-self.x) + + def __pos__(self, other): + return FloatWrapper(+self.x) + + def __pow__(self, other): + return FloatWrapper(self.x ** other.x) + + def __sub__(self, other): + return FloatWrapper(self.x - other.x) + + def __truediv__(self, other): + return FloatWrapper(self.x / other.x) + + return FloatWrapper + + def assertSame(self, first, second, msg=None): + self.assertEqual(type(first), type(second), msg=msg) + self.assertEqual(first, second, msg=msg) + + def test_overloads(self): + # Check that the dunder methods are exposed on ClassInstanceType. + + JitList = jitclass({"x": types.List(types.intp)})(self.PyList) + + py_funcs = [ + lambda x: abs(x), + lambda x: x.__abs__(), + lambda x: bool(x), + lambda x: x.__bool__(), + lambda x: complex(x), + lambda x: x.__complex__(), + lambda x: 0 in x, # contains + lambda x: x.__contains__(0), + lambda x: float(x), + lambda x: x.__float__(), + lambda x: int(x), + lambda x: x.__int__(), + lambda x: len(x), + lambda x: x.__len__(), + lambda x: str(x), + lambda x: x.__str__(), + lambda x: 1 if x else 0, # truth + ] + jit_funcs = [njit(f) for f in py_funcs] + + py_list = self.PyList() + jit_list = JitList() + for py_f, jit_f in zip(py_funcs, jit_funcs): + self.assertSame(py_f(py_list), py_f(jit_list)) + self.assertSame(py_f(py_list), jit_f(jit_list)) + + py_list.append(2) + jit_list.append(2) + for py_f, jit_f in zip(py_funcs, jit_funcs): + self.assertSame(py_f(py_list), py_f(jit_list)) + self.assertSame(py_f(py_list), jit_f(jit_list)) + + py_list.append(-5) + jit_list.append(-5) + for py_f, jit_f in zip(py_funcs, jit_funcs): + self.assertSame(py_f(py_list), py_f(jit_list)) + self.assertSame(py_f(py_list), jit_f(jit_list)) + + py_list.clear() + jit_list.clear() + for py_f, jit_f in zip(py_funcs, jit_funcs): + self.assertSame(py_f(py_list), py_f(jit_list)) + self.assertSame(py_f(py_list), jit_f(jit_list)) + + def test_bool_fallback(self): + + def py_b(x): + return bool(x) + + jit_b = njit(py_b) + + @jitclass([("x", types.List(types.intp))]) + class LenClass: + def __init__(self, x): + self.x = x + + def __len__(self): + return len(self.x) % 4 + + def append(self, y): + self.x.append(y) + + def pop(self): + self.x.pop(0) + + obj = LenClass([1, 2, 3]) + self.assertTrue(py_b(obj)) + self.assertTrue(jit_b(obj)) + + obj.append(4) + self.assertFalse(py_b(obj)) + self.assertFalse(jit_b(obj)) + + obj.pop() + self.assertTrue(py_b(obj)) + self.assertTrue(jit_b(obj)) + + @jitclass([("y", types.float64)]) + class NormalClass: + def __init__(self, y): + self.y = y + + obj = NormalClass(0) + self.assertTrue(py_b(obj)) + self.assertTrue(jit_b(obj)) + + def test_numeric_fallback(self): + def py_c(x): + return complex(x) + + def py_f(x): + return float(x) + + def py_i(x): + return int(x) + + jit_c = njit(py_c) + jit_f = njit(py_f) + jit_i = njit(py_i) + + @jitclass([]) + class FloatClass: + def __init__(self): + pass + + def __float__(self): + return 3.1415 + + obj = FloatClass() + self.assertSame(py_c(obj), complex(3.1415)) + self.assertSame(jit_c(obj), complex(3.1415)) + self.assertSame(py_f(obj), 3.1415) + self.assertSame(jit_f(obj), 3.1415) + + with self.assertRaises(TypeError) as e: + py_i(obj) + self.assertIn("int", str(e.exception)) + with self.assertRaises(TypingError) as e: + jit_i(obj) + self.assertIn("int", str(e.exception)) + + @jitclass([]) + class IntClass: + def __init__(self): + pass + + def __int__(self): + return 7 + + obj = IntClass() + self.assertSame(py_i(obj), 7) + self.assertSame(jit_i(obj), 7) + + with self.assertRaises(TypeError) as e: + py_c(obj) + self.assertIn("complex", str(e.exception)) + with self.assertRaises(TypingError) as e: + jit_c(obj) + self.assertIn("complex", str(e.exception)) + with self.assertRaises(TypeError) as e: + py_f(obj) + self.assertIn("float", str(e.exception)) + with self.assertRaises(TypingError) as e: + jit_f(obj) + self.assertIn("float", str(e.exception)) + + @jitclass([]) + class IndexClass: + def __init__(self): + pass + + def __index__(self): + return 1 + + obj = IndexClass() + + self.assertSame(py_c(obj), complex(1)) + self.assertSame(jit_c(obj), complex(1)) + self.assertSame(py_f(obj), 1.) + self.assertSame(jit_f(obj), 1.) + self.assertSame(py_i(obj), 1) + self.assertSame(jit_i(obj), 1) + + @jitclass([]) + class FloatIntIndexClass: + def __init__(self): + pass + + def __float__(self): + return 3.1415 + + def __int__(self): + return 7 + + def __index__(self): + return 1 + + obj = FloatIntIndexClass() + self.assertSame(py_c(obj), complex(3.1415)) + self.assertSame(jit_c(obj), complex(3.1415)) + self.assertSame(py_f(obj), 3.1415) + self.assertSame(jit_f(obj), 3.1415) + self.assertSame(py_i(obj), 7) + self.assertSame(jit_i(obj), 7) + + def test_arithmetic_logical(self): + IntWrapper = self.get_int_wrapper() + FloatWrapper = self.get_float_wrapper() + + float_py_funcs = [ + lambda x, y: x == y, + lambda x, y: x != y, + lambda x, y: x >= y, + lambda x, y: x > y, + lambda x, y: x <= y, + lambda x, y: x < y, + lambda x, y: x + y, + lambda x, y: x // y, + lambda x, y: x % y, + lambda x, y: x * y, + lambda x, y: x ** y, + lambda x, y: x - y, + lambda x, y: x / y, + ] + int_py_funcs = [ + lambda x, y: x == y, + lambda x, y: x != y, + lambda x, y: x << y, + lambda x, y: x >> y, + lambda x, y: x & y, + lambda x, y: x | y, + lambda x, y: x ^ y, + ] + + test_values = [ + (0.0, 2.0), + (1.234, 3.1415), + (13.1, 1.01), + ] + + def unwrap(value): + return getattr(value, "x", value) + + for jit_f, (x, y) in itertools.product( + map(njit, float_py_funcs), test_values): + + py_f = jit_f.py_func + + expected = py_f(x, y) + jit_x = FloatWrapper(x) + jit_y = FloatWrapper(y) + + check = ( + self.assertEqual + if type(expected) is not float + else self.assertAlmostEqual + ) + check(expected, jit_f(x, y)) + check(expected, unwrap(py_f(jit_x, jit_y))) + check(expected, unwrap(jit_f(jit_x, jit_y))) + + for jit_f, (x, y) in itertools.product( + map(njit, int_py_funcs), test_values): + + py_f = jit_f.py_func + x, y = int(x), int(y) + + expected = py_f(x, y) + jit_x = IntWrapper(x) + jit_y = IntWrapper(y) + + self.assertEqual(expected, jit_f(x, y)) + self.assertEqual(expected, unwrap(py_f(jit_x, jit_y))) + self.assertEqual(expected, unwrap(jit_f(jit_x, jit_y))) + + def test_arithmetic_logical_inplace(self): + + # If __i*__ methods are not defined, should fall back to normal methods. + JitIntWrapper = self.get_int_wrapper() + JitFloatWrapper = self.get_float_wrapper() + + PyIntWrapper = JitIntWrapper.mro()[1] + PyFloatWrapper = JitFloatWrapper.mro()[1] + + @jitclass([("x", types.intp)]) + class JitIntUpdateWrapper(PyIntWrapper): + def __init__(self, value): + self.x = value + + def __ilshift__(self, other): + return JitIntUpdateWrapper(self.x << other.x) + + def __irshift__(self, other): + return JitIntUpdateWrapper(self.x >> other.x) + + def __iand__(self, other): + return JitIntUpdateWrapper(self.x & other.x) + + def __ior__(self, other): + return JitIntUpdateWrapper(self.x | other.x) + + def __ixor__(self, other): + return JitIntUpdateWrapper(self.x ^ other.x) + + @jitclass({"x": types.float64}) + class JitFloatUpdateWrapper(PyFloatWrapper): + + def __init__(self, value): + self.x = value + + def __iadd__(self, other): + return JitFloatUpdateWrapper(self.x + 2.718 * other.x) + + def __ifloordiv__(self, other): + return JitFloatUpdateWrapper(self.x * 2.718 // other.x) + + def __imod__(self, other): + return JitFloatUpdateWrapper(self.x % (other.x + 1)) + + def __imul__(self, other): + return JitFloatUpdateWrapper(self.x * other.x + 1) + + def __ipow__(self, other): + return JitFloatUpdateWrapper(self.x ** other.x + 1) + + def __isub__(self, other): + return JitFloatUpdateWrapper(self.x - 3.1415 * other.x) + + def __itruediv__(self, other): + return JitFloatUpdateWrapper((self.x + 1) / other.x) + + PyIntUpdateWrapper = JitIntUpdateWrapper.mro()[1] + PyFloatUpdateWrapper = JitFloatUpdateWrapper.mro()[1] + + def get_update_func(op): + template = f""" +def f(x, y): + x {op}= y + return x +""" + namespace = {} + exec(template, namespace) + return namespace["f"] + + float_py_funcs = [get_update_func(op) for op in [ + "+", "//", "%", "*", "**", "-", "/", + ]] + int_py_funcs = [get_update_func(op) for op in [ + "<<", ">>", "&", "|", "^", + ]] + + test_values = [ + (0.0, 2.0), + (1.234, 3.1415), + (13.1, 1.01), + ] + + for jit_f, (py_cls, jit_cls), (x, y) in itertools.product( + map(njit, float_py_funcs), + [ + (PyFloatWrapper, JitFloatWrapper), + (PyFloatUpdateWrapper, JitFloatUpdateWrapper) + ], + test_values): + py_f = jit_f.py_func + + expected = py_f(py_cls(x), py_cls(y)).x + self.assertAlmostEqual(expected, py_f(jit_cls(x), jit_cls(y)).x) + self.assertAlmostEqual(expected, jit_f(jit_cls(x), jit_cls(y)).x) + + for jit_f, (py_cls, jit_cls), (x, y) in itertools.product( + map(njit, int_py_funcs), + [ + (PyIntWrapper, JitIntWrapper), + (PyIntUpdateWrapper, JitIntUpdateWrapper) + ], + test_values): + x, y = int(x), int(y) + py_f = jit_f.py_func + + expected = py_f(py_cls(x), py_cls(y)).x + self.assertEqual(expected, py_f(jit_cls(x), jit_cls(y)).x) + self.assertEqual(expected, jit_f(jit_cls(x), jit_cls(y)).x) + + def test_hash_eq_ne(self): + + class HashEqTest: + x: int + + def __init__(self, x): + self.x = x + + def __hash__(self): + return self.x % 10 + + def __eq__(self, o): + return (self.x - o.x) % 20 == 0 + + class HashEqNeTest(HashEqTest): + def __ne__(self, o): + return (self.x - o.x) % 20 > 1 + + def py_hash(x): + return hash(x) + + def py_eq(x, y): + return x == y + + def py_ne(x, y): + return x != y + + def identity_decorator(f): + return f + + comparisons = [ + (0, 1), # Will give different ne results. + (2, 22), + (7, 10), + (3, 3), + ] + + for base_cls, use_jit in itertools.product( + [HashEqTest, HashEqNeTest], [False, True] + ): + decorator = njit if use_jit else identity_decorator + hash_func = decorator(py_hash) + eq_func = decorator(py_eq) + ne_func = decorator(py_ne) + + jit_cls = jitclass(base_cls) + + for v in [0, 2, 10, 24, -8]: + self.assertEqual(hash_func(jit_cls(v)), v % 10) + + for x, y in comparisons: + self.assertEqual( + eq_func(jit_cls(x), jit_cls(y)), + base_cls(x) == base_cls(y), + ) + self.assertEqual( + ne_func(jit_cls(x), jit_cls(y)), + base_cls(x) != base_cls(y), + ) + + def test_bool_fallback_len(self): + # Check that the fallback to using len(obj) to determine truth of an + # object is implemented correctly as per + # https://docs.python.org/3/library/stdtypes.html#truth-value-testing + # + # Relevant points: + # + # "By default, an object is considered true unless its class defines + # either a __bool__() method that returns False or a __len__() method + # that returns zero, when called with the object." + # + # and: + # + # "Operations and built-in functions that have a Boolean result always + # return 0 or False for false and 1 or True for true, unless otherwise + # stated." + + class NoBoolHasLen: + def __init__(self, val): + self.val = val + + def __len__(self): + return self.val + + def get_bool(self): + return bool(self) + + py_class = NoBoolHasLen + jitted_class = jitclass([('val', types.int64)])(py_class) + + py_class_0_bool = py_class(0).get_bool() + py_class_2_bool = py_class(2).get_bool() + jitted_class_0_bool = jitted_class(0).get_bool() + jitted_class_2_bool = jitted_class(2).get_bool() + + # Truth values from bool(obj) should be equal + self.assertEqual(py_class_0_bool, jitted_class_0_bool) + self.assertEqual(py_class_2_bool, jitted_class_2_bool) + + # Truth values from bool(obj) should be the same type + self.assertEqual(type(py_class_0_bool), type(jitted_class_0_bool)) + self.assertEqual(type(py_class_2_bool), type(jitted_class_2_bool)) + + def test_bool_fallback_default(self): + # Similar to test_bool_fallback, but checks the case where there is no + # __bool__() or __len__() defined, so the object should always be True. + + class NoBoolNoLen: + def __init__(self): + pass + + def get_bool(self): + return bool(self) + + py_class = NoBoolNoLen + jitted_class = jitclass([])(py_class) + + py_class_bool = py_class().get_bool() + jitted_class_bool = jitted_class().get_bool() + + # Truth values from bool(obj) should be equal + self.assertEqual(py_class_bool, jitted_class_bool) + + # Truth values from bool(obj) should be the same type + self.assertEqual(type(py_class_bool), type(jitted_class_bool)) + + def test_operator_reflection(self): + class OperatorsDefined: + def __init__(self, x): + self.x = x + + def __eq__(self, other): + return self.x == other.x + + def __le__(self, other): + return self.x <= other.x + + def __lt__(self, other): + return self.x < other.x + + def __ge__(self, other): + return self.x >= other.x + + def __gt__(self, other): + return self.x > other.x + + class NoOperatorsDefined: + def __init__(self, x): + self.x = x + + spec = [('x', types.int32)] + JitOperatorsDefined = jitclass(spec)(OperatorsDefined) + JitNoOperatorsDefined = jitclass(spec)(NoOperatorsDefined) + + py_ops_defined = OperatorsDefined(2) + py_ops_not_defined = NoOperatorsDefined(3) + + jit_ops_defined = JitOperatorsDefined(2) + jit_ops_not_defined = JitNoOperatorsDefined(3) + + self.assertEqual(py_ops_not_defined == py_ops_defined, + jit_ops_not_defined == jit_ops_defined) + + self.assertEqual(py_ops_not_defined <= py_ops_defined, + jit_ops_not_defined <= jit_ops_defined) + + self.assertEqual(py_ops_not_defined < py_ops_defined, + jit_ops_not_defined < jit_ops_defined) + + self.assertEqual(py_ops_not_defined >= py_ops_defined, + jit_ops_not_defined >= jit_ops_defined) + + self.assertEqual(py_ops_not_defined > py_ops_defined, + jit_ops_not_defined > jit_ops_defined) + + @skip_unless_scipy + def test_matmul_operator(self): + class ArrayAt: + def __init__(self, array): + self.arr = array + + def __matmul__(self, other): + return self.arr @ other.arr + + def __rmatmul__(self, other): + return other.arr @ self.arr + + def __imatmul__(self, other): + self.arr = self.arr @ other.arr + return self + + class ArrayNoAt: + def __init__(self, array): + self.arr = array + + n = 3 + np.random.seed(1) + vec = np.random.random(size=(n,)) + mat = np.random.random(size=(n, n)) + + vector_noat = ArrayNoAt(vec) + vector_at = ArrayAt(vec) + jit_vector_noat = jitclass(ArrayNoAt, spec={"arr": float64[::1]})(vec) + jit_vector_at = jitclass(ArrayAt, spec={"arr": float64[::1]})(vec) + + matrix_noat = ArrayNoAt(mat) + matrix_at = ArrayAt(mat) + jit_matrix_noat = jitclass(ArrayNoAt, spec={"arr": float64[:,::1]})(mat) + jit_matrix_at = jitclass(ArrayAt, spec={"arr": float64[:,::1]})(mat) + + # __matmul__ + np.testing.assert_allclose(vector_at @ vector_noat, + jit_vector_at @ jit_vector_noat) + np.testing.assert_allclose(vector_at @ matrix_noat, + jit_vector_at @ jit_matrix_noat) + np.testing.assert_allclose(matrix_at @ vector_noat, + jit_matrix_at @ jit_vector_noat) + np.testing.assert_allclose(matrix_at @ matrix_noat, + jit_matrix_at @ jit_matrix_noat) + + # __rmatmul__ + np.testing.assert_allclose(vector_noat @ vector_at, + jit_vector_noat @ jit_vector_at) + np.testing.assert_allclose(vector_noat @ matrix_at, + jit_vector_noat @ jit_matrix_at) + np.testing.assert_allclose(matrix_noat @ vector_at, + jit_matrix_noat @ jit_vector_at) + np.testing.assert_allclose(matrix_noat @ matrix_at, + jit_matrix_noat @ jit_matrix_at) + + # __imatmul__ + vector_at @= matrix_noat + matrix_at @= matrix_noat + jit_vector_at @= jit_matrix_noat + jit_matrix_at @= jit_matrix_noat + + np.testing.assert_allclose(vector_at.arr, jit_vector_at.arr) + np.testing.assert_allclose(matrix_at.arr, jit_matrix_at.arr) + + def test_arithmetic_logical_reflection(self): + class OperatorsDefined: + def __init__(self, x): + self.x = x + + def __radd__(self, other): + return other.x + self.x + + def __rsub__(self, other): + return other.x - self.x + + def __rmul__(self, other): + return other.x * self.x + + def __rtruediv__(self, other): + return other.x / self.x + + def __rfloordiv__(self, other): + return other.x // self.x + + def __rmod__(self, other): + return other.x % self.x + + def __rpow__(self, other): + return other.x ** self.x + + def __rlshift__(self, other): + return other.x << self.x + + def __rrshift__(self, other): + return other.x >> self.x + + def __rand__(self, other): + return other.x & self.x + + def __rxor__(self, other): + return other.x ^ self.x + + def __ror__(self, other): + return other.x | self.x + + class NoOperatorsDefined: + def __init__(self, x): + self.x = x + + float_op = ["+", "-", "*", "**", "/", "//", "%"] + int_op = [*float_op, "<<", ">>" , "&", "^", "|"] + + for test_type, test_op, test_value in [ + (int32, int_op, (2, 4)), + (float64, float_op, (2., 4.)), + (float64[::1], float_op, + (np.array([1., 2., 4.]), np.array([20., -24., 1.]))) + ]: + spec = {"x": test_type} + JitOperatorsDefined = jitclass(OperatorsDefined, spec) + JitNoOperatorsDefined = jitclass(NoOperatorsDefined, spec) + + py_ops_defined = OperatorsDefined(test_value[0]) # noqa: F841 + py_ops_not_defined = NoOperatorsDefined(test_value[1]) # noqa: F841 + + jit_ops_defined = JitOperatorsDefined(test_value[0]) # noqa: F841 + jit_ops_not_defined = JitNoOperatorsDefined(test_value[1]) # noqa: F841 E501 + + for op in test_op: + if not ("array" in str(test_type)): + self.assertEqual( + eval(f"py_ops_not_defined {op} py_ops_defined"), + eval(f"jit_ops_not_defined {op} jit_ops_defined") + ) + else: + self.assertTupleEqual( + tuple(eval(f"py_ops_not_defined {op} py_ops_defined")), + tuple(eval(f"jit_ops_not_defined {op} jit_ops_defined")) + ) + + def test_implicit_hash_compiles(self): + # Ensure that classes with __hash__ implicitly defined as None due to + # the presence of __eq__ are correctly handled by ignoring the __hash__ + # class member. + class ImplicitHash: + def __init__(self): + pass + + def __eq__(self, other): + return False + + jitted = jitclass([])(ImplicitHash) + instance = jitted() + + self.assertFalse(instance == instance) + + def test_invert_operator(self): + @jitclass([("x", types.intp)]) + class InvertWrapper: + def __init__(self, value): + self.x = value + + def __invert__(self): + return InvertWrapper(~self.x) + + obj = InvertWrapper(42) + # Python usage + py_result = ~obj + self.assertIsInstance(py_result, InvertWrapper) + self.assertEqual(py_result.x, ~42) + + # Numba-compiled usage + @njit + def do_invert(o): + return ~o + + njit_result = do_invert(obj) + self.assertIsInstance(njit_result, InvertWrapper) + self.assertEqual(njit_result.x, ~42) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitmethod.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitmethod.py new file mode 100644 index 0000000000000000000000000000000000000000..437c45b6bbdf00b490b49b569e8ebbe05ce63ad3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_jitmethod.py @@ -0,0 +1,70 @@ +import unittest + +import numpy as np + +from numba import jit +from numba.tests.support import override_config + + +class TestJITMethod(unittest.TestCase): + def test_bound_jit_method_with_loop_lift(self): + class Something(object): + def __init__(self, x0): + self.x0 = x0 + + @jit(forceobj=True) + def method(self, x): + a = np.empty(shape=5, dtype=np.float32) + x0 = self.x0 + + for i in range(a.shape[0]): + a[i] = x0 * x + + return a + + something = Something(3) + np.testing.assert_array_equal(something.method(5), + np.array([15, 15, 15, 15, 15], dtype=np.float32)) + + # Check that loop lifting in nopython mode was successful + [cres] = something.method.overloads.values() + jitloop = cres.lifted[0] + [loopcres] = jitloop.overloads.values() + self.assertTrue(loopcres.fndesc.native) + + def test_unbound_jit_method(self): + class Something(object): + def __init__(self, x0): + self.x0 = x0 + + @jit(forceobj=True) + def method(self): + return self.x0 + + something = Something(3) + self.assertEqual(Something.method(something), 3) + + +class TestDisabledJIT(unittest.TestCase): + def test_decorated_function(self): + with override_config('DISABLE_JIT', True): + def method(x): + return x + jitted = jit(method) + + self.assertEqual(jitted, method) + self.assertEqual(10, method(10)) + self.assertEqual(10, jitted(10)) + + def test_decorated_function_with_kwargs(self): + with override_config('DISABLE_JIT', True): + def method(x): + return x + jitted = jit(nopython=True)(method) + + self.assertEqual(jitted, method) + self.assertEqual(10, method(10)) + self.assertEqual(10, jitted(10)) + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_linalg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb80ae08d1071bb61af49b7068f3a629d179549 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_linalg.py @@ -0,0 +1,2696 @@ +import contextlib +import gc +from itertools import product, cycle +import sys +import warnings +from numbers import Number, Integral +import platform + +import numpy as np + +from numba import jit, njit, typeof +from numba.core import errors +from numba.tests.support import (TestCase, tag, needs_lapack, needs_blas, + _is_armv7l, EnableNRTStatsMixin) +from .matmul_usecase import matmul_usecase +import unittest + + +def dot2(a, b): + return np.dot(a, b) + + +def dot3(a, b, out): + return np.dot(a, b, out=out) + + +def vdot(a, b): + return np.vdot(a, b) + + +class TestProduct(EnableNRTStatsMixin, TestCase): + """ + Tests for dot products. + """ + + dtypes = (np.float64, np.float32, np.complex128, np.complex64) + + def setUp(self): + # Collect leftovers from previous test cases before checking for leaks + gc.collect() + super(TestProduct, self).setUp() + + def sample_vector(self, n, dtype): + # Be careful to generate only exactly representable float values, + # to avoid rounding discrepancies between Numpy and Numba + base = np.arange(n) + if issubclass(dtype, np.complexfloating): + return (base * (1 - 0.5j) + 2j).astype(dtype) + else: + return (base * 0.5 - 1).astype(dtype) + + def sample_matrix(self, m, n, dtype): + return self.sample_vector(m * n, dtype).reshape((m, n)) + + @contextlib.contextmanager + def check_contiguity_warning(self, pyfunc): + """ + Check performance warning(s) for non-contiguity. + """ + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', errors.NumbaPerformanceWarning) + yield + self.assertGreaterEqual(len(w), 1) + self.assertIs(w[0].category, errors.NumbaPerformanceWarning) + self.assertIn("faster on contiguous arrays", str(w[0].message)) + self.assertEqual(w[0].filename, pyfunc.__code__.co_filename) + # This works because our functions are one-liners + self.assertEqual(w[0].lineno, pyfunc.__code__.co_firstlineno + 1) + + def check_func(self, pyfunc, cfunc, args): + with self.assertNoNRTLeak(): + expected = pyfunc(*args) + got = cfunc(*args) + self.assertPreciseEqual(got, expected, ignore_sign_on_zero=True) + del got, expected + + + def _aligned_copy(self, arr): + # This exists for armv7l because NumPy wants aligned arrays for the + # `out` arg of functions, but np.empty/np.copy doesn't seem to always + # produce them, in particular for complex dtypes + size = (arr.size + 1) * arr.itemsize + 1 + datasize = arr.size * arr.itemsize + tmp = np.empty(size, dtype=np.uint8) + for i in range(arr.itemsize + 1): + new = tmp[i : i + datasize].view(dtype=arr.dtype) + if new.flags.aligned: + break + else: + raise Exception("Could not obtain aligned array") + if arr.flags.c_contiguous: + new = np.reshape(new, arr.shape, order='C') + else: + new = np.reshape(new, arr.shape, order='F') + new[:] = arr[:] + assert new.flags.aligned + return new + + def check_func_out(self, pyfunc, cfunc, args, out): + copier = self._aligned_copy if _is_armv7l else np.copy + with self.assertNoNRTLeak(): + expected = copier(out) + got = copier(out) + self.assertIs(pyfunc(*args, out=expected), expected) + self.assertIs(cfunc(*args, out=got), got) + self.assertPreciseEqual(got, expected, ignore_sign_on_zero=True) + del got, expected + + def assert_mismatching_sizes(self, cfunc, args, is_out=False): + with self.assertRaises(ValueError) as raises: + cfunc(*args) + msg = ("incompatible output array size" if is_out else + "incompatible array sizes") + self.assertIn(msg, str(raises.exception)) + + def assert_mismatching_dtypes(self, cfunc, args, func_name="np.dot()"): + with self.assertRaises(errors.TypingError) as raises: + cfunc(*args) + self.assertIn("%s arguments must all have the same dtype" + % (func_name,), + str(raises.exception)) + + def check_dot_vv(self, pyfunc, func_name): + n = 3 + cfunc = jit(nopython=True)(pyfunc) + for dtype in self.dtypes: + a = self.sample_vector(n, dtype) + b = self.sample_vector(n, dtype) + self.check_func(pyfunc, cfunc, (a, b)) + # Non-contiguous + self.check_func(pyfunc, cfunc, (a[::-1], b[::-1])) + + # Mismatching sizes + a = self.sample_vector(n - 1, np.float64) + b = self.sample_vector(n, np.float64) + self.assert_mismatching_sizes(cfunc, (a, b)) + # Mismatching dtypes + a = self.sample_vector(n, np.float32) + b = self.sample_vector(n, np.float64) + self.assert_mismatching_dtypes(cfunc, (a, b), func_name=func_name) + + @needs_blas + def test_dot_vv(self): + """ + Test vector * vector np.dot() + """ + self.check_dot_vv(dot2, "np.dot()") + + @needs_blas + def test_vdot(self): + """ + Test np.vdot() + """ + self.check_dot_vv(vdot, "np.vdot()") + + def check_dot_vm(self, pyfunc2, pyfunc3, func_name): + + def samples(m, n): + for order in 'CF': + a = self.sample_matrix(m, n, np.float64).copy(order=order) + b = self.sample_vector(n, np.float64) + yield a, b + for dtype in self.dtypes: + a = self.sample_matrix(m, n, dtype) + b = self.sample_vector(n, dtype) + yield a, b + # Non-contiguous + yield a[::-1], b[::-1] + + cfunc2 = jit(nopython=True)(pyfunc2) + if pyfunc3 is not None: + cfunc3 = jit(nopython=True)(pyfunc3) + + for m, n in [(2, 3), + (3, 0), + (0, 3) + ]: + for a, b in samples(m, n): + self.check_func(pyfunc2, cfunc2, (a, b)) + self.check_func(pyfunc2, cfunc2, (b, a.T)) + if pyfunc3 is not None: + for a, b in samples(m, n): + out = np.empty(m, dtype=a.dtype) + self.check_func_out(pyfunc3, cfunc3, (a, b), out) + self.check_func_out(pyfunc3, cfunc3, (b, a.T), out) + + # Mismatching sizes + m, n = 2, 3 + a = self.sample_matrix(m, n - 1, np.float64) + b = self.sample_vector(n, np.float64) + self.assert_mismatching_sizes(cfunc2, (a, b)) + self.assert_mismatching_sizes(cfunc2, (b, a.T)) + if pyfunc3 is not None: + out = np.empty(m, np.float64) + self.assert_mismatching_sizes(cfunc3, (a, b, out)) + self.assert_mismatching_sizes(cfunc3, (b, a.T, out)) + a = self.sample_matrix(m, m, np.float64) + b = self.sample_vector(m, np.float64) + out = np.empty(m - 1, np.float64) + self.assert_mismatching_sizes(cfunc3, (a, b, out), is_out=True) + self.assert_mismatching_sizes(cfunc3, (b, a.T, out), is_out=True) + # Mismatching dtypes + a = self.sample_matrix(m, n, np.float32) + b = self.sample_vector(n, np.float64) + self.assert_mismatching_dtypes(cfunc2, (a, b), func_name) + if pyfunc3 is not None: + a = self.sample_matrix(m, n, np.float64) + b = self.sample_vector(n, np.float64) + out = np.empty(m, np.float32) + self.assert_mismatching_dtypes(cfunc3, (a, b, out), func_name) + + @needs_blas + def test_dot_vm(self): + """ + Test vector * matrix and matrix * vector np.dot() + """ + self.check_dot_vm(dot2, dot3, "np.dot()") + + def check_dot_mm(self, pyfunc2, pyfunc3, func_name): + + def samples(m, n, k): + for order_a, order_b in product('CF', 'CF'): + a = self.sample_matrix(m, k, np.float64).copy(order=order_a) + b = self.sample_matrix(k, n, np.float64).copy(order=order_b) + yield a, b + for dtype in self.dtypes: + a = self.sample_matrix(m, k, dtype) + b = self.sample_matrix(k, n, dtype) + yield a, b + # Non-contiguous + yield a[::-1], b[::-1] + + cfunc2 = jit(nopython=True)(pyfunc2) + if pyfunc3 is not None: + cfunc3 = jit(nopython=True)(pyfunc3) + + # Test generic matrix * matrix as well as "degenerate" cases + # where one of the outer dimensions is 1 (i.e. really represents + # a vector, which may select a different implementation), + # one of the matrices is empty, or both matrices are empty. + for m, n, k in [(2, 3, 4), # Generic matrix * matrix + (1, 3, 4), # 2d vector * matrix + (1, 1, 4), # 2d vector * 2d vector + (0, 3, 2), # Empty matrix * matrix, empty output + (3, 0, 2), # Matrix * empty matrix, empty output + (0, 0, 3), # Both arguments empty, empty output + (3, 2, 0), # Both arguments empty, nonempty output + ]: + for a, b in samples(m, n, k): + self.check_func(pyfunc2, cfunc2, (a, b)) + self.check_func(pyfunc2, cfunc2, (b.T, a.T)) + if pyfunc3 is not None: + for a, b in samples(m, n, k): + out = np.empty((m, n), dtype=a.dtype) + self.check_func_out(pyfunc3, cfunc3, (a, b), out) + out = np.empty((n, m), dtype=a.dtype) + self.check_func_out(pyfunc3, cfunc3, (b.T, a.T), out) + + # Mismatching sizes + m, n, k = 2, 3, 4 + a = self.sample_matrix(m, k - 1, np.float64) + b = self.sample_matrix(k, n, np.float64) + self.assert_mismatching_sizes(cfunc2, (a, b)) + if pyfunc3 is not None: + out = np.empty((m, n), np.float64) + self.assert_mismatching_sizes(cfunc3, (a, b, out)) + a = self.sample_matrix(m, k, np.float64) + b = self.sample_matrix(k, n, np.float64) + out = np.empty((m, n - 1), np.float64) + self.assert_mismatching_sizes(cfunc3, (a, b, out), is_out=True) + # Mismatching dtypes + a = self.sample_matrix(m, k, np.float32) + b = self.sample_matrix(k, n, np.float64) + self.assert_mismatching_dtypes(cfunc2, (a, b), func_name) + if pyfunc3 is not None: + a = self.sample_matrix(m, k, np.float64) + b = self.sample_matrix(k, n, np.float64) + out = np.empty((m, n), np.float32) + self.assert_mismatching_dtypes(cfunc3, (a, b, out), func_name) + + @needs_blas + def test_dot_mm(self): + """ + Test matrix * matrix np.dot() + """ + self.check_dot_mm(dot2, dot3, "np.dot()") + + @needs_blas + def test_matmul_vv(self): + """ + Test vector @ vector + """ + self.check_dot_vv(matmul_usecase, "'@'") + + @needs_blas + def test_matmul_vm(self): + """ + Test vector @ matrix and matrix @ vector + """ + self.check_dot_vm(matmul_usecase, None, "'@'") + + @needs_blas + def test_matmul_mm(self): + """ + Test matrix @ matrix + """ + self.check_dot_mm(matmul_usecase, None, "'@'") + + @needs_blas + def test_contiguity_warnings(self): + m, k, n = 2, 3, 4 + dtype = np.float64 + a = self.sample_matrix(m, k, dtype)[::-1] + b = self.sample_matrix(k, n, dtype)[::-1] + out = np.empty((m, n), dtype) + + cfunc = jit(nopython=True)(dot2) + with self.check_contiguity_warning(cfunc.py_func): + cfunc(a, b) + cfunc = jit(nopython=True)(dot3) + with self.check_contiguity_warning(cfunc.py_func): + cfunc(a, b, out) + + a = self.sample_vector(n, dtype)[::-1] + b = self.sample_vector(n, dtype)[::-1] + + cfunc = jit(nopython=True)(vdot) + with self.check_contiguity_warning(cfunc.py_func): + cfunc(a, b) + + +# Implementation definitions for the purpose of jitting. + +def invert_matrix(a): + return np.linalg.inv(a) + + +def cholesky_matrix(a): + return np.linalg.cholesky(a) + + +def eig_matrix(a): + return np.linalg.eig(a) + + +def eigvals_matrix(a): + return np.linalg.eigvals(a) + + +def eigh_matrix(a): + return np.linalg.eigh(a) + + +def eigvalsh_matrix(a): + return np.linalg.eigvalsh(a) + + +def svd_matrix(a, full_matrices=1): + return np.linalg.svd(a, full_matrices) + + +def qr_matrix(a): + return np.linalg.qr(a) + + +def lstsq_system(A, B, rcond=-1): + return np.linalg.lstsq(A, B, rcond) + + +def solve_system(A, B): + return np.linalg.solve(A, B) + + +def pinv_matrix(A, rcond=1e-15): # 1e-15 from numpy impl + return np.linalg.pinv(A) + + +def slogdet_matrix(a): + return np.linalg.slogdet(a) + + +def det_matrix(a): + return np.linalg.det(a) + + +def norm_matrix(a, ord=None): + return np.linalg.norm(a, ord) + + +def cond_matrix(a, p=None): + return np.linalg.cond(a, p) + + +def matrix_rank_matrix(a, tol=None): + return np.linalg.matrix_rank(a, tol) + + +def matrix_power_matrix(a, n): + return np.linalg.matrix_power(a, n) + + +def trace_matrix(a, offset=0): + return np.trace(a, offset) + + +def trace_matrix_no_offset(a): + return np.trace(a) + + +def outer_matrix(a, b, out=None): + return np.outer(a, b, out=out) + + +def kron_matrix(a, b): + return np.kron(a, b) + + +class TestLinalgBase(EnableNRTStatsMixin, TestCase): + """ + Provides setUp and common data/error modes for testing np.linalg functions. + """ + + # supported dtypes + dtypes = (np.float64, np.float32, np.complex128, np.complex64) + + def setUp(self): + # Collect leftovers from previous test cases before checking for leaks + gc.collect() + super(TestLinalgBase, self).setUp() + + def sample_vector(self, n, dtype): + # Be careful to generate only exactly representable float values, + # to avoid rounding discrepancies between Numpy and Numba + base = np.arange(n) + if issubclass(dtype, np.complexfloating): + return (base * (1 - 0.5j) + 2j).astype(dtype) + else: + return (base * 0.5 + 1).astype(dtype) + + def specific_sample_matrix( + self, size, dtype, order, rank=None, condition=None): + """ + Provides a sample matrix with an optionally specified rank or condition + number. + + size: (rows, columns), the dimensions of the returned matrix. + dtype: the dtype for the returned matrix. + order: the memory layout for the returned matrix, 'F' or 'C'. + rank: the rank of the matrix, an integer value, defaults to full rank. + condition: the condition number of the matrix (defaults to 1.) + + NOTE: Only one of rank or condition may be set. + """ + + # default condition + d_cond = 1. + + if len(size) != 2: + raise ValueError("size must be a length 2 tuple.") + + if order not in ['F', 'C']: + raise ValueError("order must be one of 'F' or 'C'.") + + if dtype not in [np.float32, np.float64, np.complex64, np.complex128]: + raise ValueError("dtype must be a numpy floating point type.") + + if rank is not None and condition is not None: + raise ValueError("Only one of rank or condition can be specified.") + + if condition is None: + condition = d_cond + + if condition < 1: + raise ValueError("Condition number must be >=1.") + + np.random.seed(0) # repeatable seed + m, n = size + + if m < 0 or n < 0: + raise ValueError("Negative dimensions given for matrix shape.") + + minmn = min(m, n) + if rank is None: + rv = minmn + else: + if rank <= 0: + raise ValueError("Rank must be greater than zero.") + if not isinstance(rank, Integral): + raise ValueError("Rank must an integer.") + rv = rank + if rank > minmn: + raise ValueError("Rank given greater than full rank.") + + if m == 1 or n == 1: + # vector, must be rank 1 (enforced above) + # condition of vector is also 1 + if condition != d_cond: + raise ValueError( + "Condition number was specified for a vector (always 1.).") + maxmn = max(m, n) + Q = self.sample_vector(maxmn, dtype).reshape(m, n) + else: + # Build a sample matrix via combining SVD like inputs. + + # Create matrices of left and right singular vectors. + # This could use Modified Gram-Schmidt and perhaps be quicker, + # at present it uses QR decompositions to obtain orthonormal + # matrices. + tmp = self.sample_vector(m * m, dtype).reshape(m, m) + U, _ = np.linalg.qr(tmp) + # flip the second array, else for m==n the identity matrix appears + tmp = self.sample_vector(n * n, dtype)[::-1].reshape(n, n) + V, _ = np.linalg.qr(tmp) + # create singular values. + sv = np.linspace(d_cond, condition, rv) + S = np.zeros((m, n)) + idx = np.nonzero(np.eye(m, n)) + S[idx[0][:rv], idx[1][:rv]] = sv + Q = np.dot(np.dot(U, S), V.T) # construct + Q = np.array(Q, dtype=dtype, order=order) # sort out order/type + + return Q + + def assert_error(self, cfunc, args, msg, err=ValueError): + with self.assertRaises(err) as raises: + cfunc(*args) + self.assertIn(msg, str(raises.exception)) + + def assert_non_square(self, cfunc, args): + msg = "Last 2 dimensions of the array must be square." + self.assert_error(cfunc, args, msg, np.linalg.LinAlgError) + + def assert_wrong_dtype(self, name, cfunc, args): + msg = "np.linalg.%s() only supported on float and complex arrays" % name + self.assert_error(cfunc, args, msg, errors.TypingError) + + def assert_wrong_dimensions(self, name, cfunc, args, la_prefix=True): + prefix = "np.linalg" if la_prefix else "np" + msg = "%s.%s() only supported on 2-D arrays" % (prefix, name) + self.assert_error(cfunc, args, msg, errors.TypingError) + + def assert_no_nan_or_inf(self, cfunc, args): + msg = "Array must not contain infs or NaNs." + self.assert_error(cfunc, args, msg, np.linalg.LinAlgError) + + def assert_contig_sanity(self, got, expected_contig): + """ + This checks that in a computed result from numba (array, possibly tuple + of arrays) all the arrays are contiguous in memory and that they are + all at least one of "C_CONTIGUOUS" or "F_CONTIGUOUS". The computed + result of the contiguousness is then compared against a hardcoded + expected result. + + got: is the computed results from numba + expected_contig: is "C" or "F" and is the expected type of + contiguousness across all input values + (and therefore tests). + """ + + if isinstance(got, tuple): + # tuple present, check all results + for a in got: + self.assert_contig_sanity(a, expected_contig) + else: + if not isinstance(got, Number): + # else a single array is present + c_contig = got.flags.c_contiguous + f_contig = got.flags.f_contiguous + + # check that the result (possible set of) is at least one of + # C or F contiguous. + msg = "Results are not at least one of all C or F contiguous." + self.assertTrue(c_contig | f_contig, msg) + + msg = "Computed contiguousness does not match expected." + if expected_contig == "C": + self.assertTrue(c_contig, msg) + elif expected_contig == "F": + self.assertTrue(f_contig, msg) + else: + raise ValueError("Unknown contig") + + def assert_raise_on_singular(self, cfunc, args): + msg = "Matrix is singular to machine precision." + self.assert_error(cfunc, args, msg, err=np.linalg.LinAlgError) + + def assert_is_identity_matrix(self, got, rtol=None, atol=None): + """ + Checks if a matrix is equal to the identity matrix. + """ + # check it is square + self.assertEqual(got.shape[-1], got.shape[-2]) + # create identity matrix + eye = np.eye(got.shape[-1], dtype=got.dtype) + resolution = 5 * np.finfo(got.dtype).resolution + if rtol is None: + rtol = 10 * resolution + if atol is None: + atol = 100 * resolution # zeros tend to be fuzzy + # check it matches + np.testing.assert_allclose(got, eye, rtol, atol) + + def assert_invalid_norm_kind(self, cfunc, args): + """ + For use in norm() and cond() tests. + """ + msg = "Invalid norm order for matrices." + self.assert_error(cfunc, args, msg, ValueError) + + def assert_raise_on_empty(self, cfunc, args): + msg = 'Arrays cannot be empty' + self.assert_error(cfunc, args, msg, np.linalg.LinAlgError) + + +class TestTestLinalgBase(TestCase): + """ + The sample matrix code TestLinalgBase.specific_sample_matrix() + is a bit involved, this class tests it works as intended. + """ + + def test_specific_sample_matrix(self): + + # add a default test to the ctor, it never runs so doesn't matter + inst = TestLinalgBase('specific_sample_matrix') + + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + + # test loop + for size, dtype, order in product(sizes, inst.dtypes, 'FC'): + + m, n = size + minmn = min(m, n) + + # test default full rank + A = inst.specific_sample_matrix(size, dtype, order) + self.assertEqual(A.shape, size) + self.assertEqual(np.linalg.matrix_rank(A), minmn) + + # test reduced rank if a reduction is possible + if minmn > 1: + rank = minmn - 1 + A = inst.specific_sample_matrix(size, dtype, order, rank=rank) + self.assertEqual(A.shape, size) + self.assertEqual(np.linalg.matrix_rank(A), rank) + + resolution = 5 * np.finfo(dtype).resolution + + # test default condition + A = inst.specific_sample_matrix(size, dtype, order) + self.assertEqual(A.shape, size) + np.testing.assert_allclose(np.linalg.cond(A), + 1., + rtol=resolution, + atol=resolution) + + # test specified condition if matrix is > 1D + if minmn > 1: + condition = 10. + A = inst.specific_sample_matrix( + size, dtype, order, condition=condition) + self.assertEqual(A.shape, size) + np.testing.assert_allclose(np.linalg.cond(A), + 10., + rtol=resolution, + atol=resolution) + + # check errors are raised appropriately + def check_error(args, msg, err=ValueError): + with self.assertRaises(err) as raises: + inst.specific_sample_matrix(*args) + self.assertIn(msg, str(raises.exception)) + + # check the checker runs ok + with self.assertRaises(AssertionError) as raises: + msg = "blank" + check_error(((2, 3), np.float64, 'F'), msg, err=ValueError) + + # check invalid inputs... + + # bad size + msg = "size must be a length 2 tuple." + check_error(((1,), np.float64, 'F'), msg, err=ValueError) + + # bad order + msg = "order must be one of 'F' or 'C'." + check_error(((2, 3), np.float64, 'z'), msg, err=ValueError) + + # bad type + msg = "dtype must be a numpy floating point type." + check_error(((2, 3), np.int32, 'F'), msg, err=ValueError) + + # specifying both rank and condition + msg = "Only one of rank or condition can be specified." + check_error(((2, 3), np.float64, 'F', 1, 1), msg, err=ValueError) + + # specifying negative condition + msg = "Condition number must be >=1." + check_error(((2, 3), np.float64, 'F', None, -1), msg, err=ValueError) + + # specifying negative matrix dimension + msg = "Negative dimensions given for matrix shape." + check_error(((2, -3), np.float64, 'F'), msg, err=ValueError) + + # specifying negative rank + msg = "Rank must be greater than zero." + check_error(((2, 3), np.float64, 'F', -1), msg, err=ValueError) + + # specifying a rank greater than maximum rank + msg = "Rank given greater than full rank." + check_error(((2, 3), np.float64, 'F', 4), msg, err=ValueError) + + # specifying a condition number for a vector + msg = "Condition number was specified for a vector (always 1.)." + check_error(((1, 3), np.float64, 'F', None, 10), msg, err=ValueError) + + # specifying a non integer rank + msg = "Rank must an integer." + check_error(((2, 3), np.float64, 'F', 1.5), msg, err=ValueError) + + +class TestLinalgInv(TestLinalgBase): + """ + Tests for np.linalg.inv. + """ + + @needs_lapack + def test_linalg_inv(self): + """ + Test np.linalg.inv + """ + n = 10 + cfunc = jit(nopython=True)(invert_matrix) + + def check(a, **kwargs): + expected = invert_matrix(a) + got = cfunc(a) + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + + # try strict + try: + np.testing.assert_array_almost_equal_nulp(got, expected, + nulp=10) + except AssertionError: + # fall back to reconstruction + use_reconstruction = True + + if use_reconstruction: + rec = np.dot(got, a) + self.assert_is_identity_matrix(rec) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a) + + for dtype, order in product(self.dtypes, 'CF'): + a = self.specific_sample_matrix((n, n), dtype, order) + check(a) + + # 0 dimensioned matrix + check(np.empty((0, 0))) + + # Non square matrix + self.assert_non_square(cfunc, (np.ones((2, 3)),)) + + # Wrong dtype + self.assert_wrong_dtype("inv", cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions("inv", cfunc, (np.ones(10),)) + + # Singular matrix + self.assert_raise_on_singular(cfunc, (np.zeros((2, 2)),)) + + @needs_lapack + def test_no_input_mutation(self): + X = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + X_orig = np.copy(X) + + @jit(nopython=True) + def ainv(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return np.linalg.inv(X) + + expected = ainv.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = ainv(X, False) + np.testing.assert_allclose(X, X_orig) + + np.testing.assert_allclose(expected, got) + + +class TestLinalgCholesky(TestLinalgBase): + """ + Tests for np.linalg.cholesky. + """ + + def sample_matrix(self, m, dtype, order): + # pd. (positive definite) matrix has eigenvalues in Z+ + np.random.seed(0) # repeatable seed + A = np.random.rand(m, m) + # orthonormal q needed to form up q^{-1}*D*q + # no "orth()" in numpy + q, _ = np.linalg.qr(A) + L = np.arange(1, m + 1) # some positive eigenvalues + Q = np.dot(np.dot(q.T, np.diag(L)), q) # construct + Q = np.array(Q, dtype=dtype, order=order) # sort out order/type + return Q + + def assert_not_pd(self, cfunc, args): + msg = "Matrix is not positive definite." + self.assert_error(cfunc, args, msg, np.linalg.LinAlgError) + + @needs_lapack + def test_linalg_cholesky(self): + """ + Test np.linalg.cholesky + """ + n = 10 + cfunc = jit(nopython=True)(cholesky_matrix) + + def check(a): + expected = cholesky_matrix(a) + got = cfunc(a) + use_reconstruction = False + # check that the computed results are contig and in the same way + self.assert_contig_sanity(got, "C") + + # try strict + try: + np.testing.assert_array_almost_equal_nulp(got, expected, + nulp=10) + except AssertionError: + # fall back to reconstruction + use_reconstruction = True + + # try via reconstruction + if use_reconstruction: + rec = np.dot(got, np.conj(got.T)) + resolution = 5 * np.finfo(a.dtype).resolution + np.testing.assert_allclose( + a, + rec, + rtol=resolution, + atol=resolution + ) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a) + + for dtype, order in product(self.dtypes, 'FC'): + a = self.sample_matrix(n, dtype, order) + check(a) + + # 0 dimensioned matrix + check(np.empty((0, 0))) + + rn = "cholesky" + # Non square matrices + self.assert_non_square(cfunc, (np.ones((2, 3), dtype=np.float64),)) + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # not pd + self.assert_not_pd(cfunc, + (np.ones(4, dtype=np.float64).reshape(2, 2),)) + + +class TestLinalgEigenSystems(TestLinalgBase): + """ + Tests for np.linalg.eig/eigvals. + """ + + def sample_matrix(self, m, dtype, order): + # This is a tridiag with the same but skewed values on the diagonals + v = self.sample_vector(m, dtype) + Q = np.diag(v) + idx = np.nonzero(np.eye(Q.shape[0], Q.shape[1], 1)) + Q[idx] = v[1:] + idx = np.nonzero(np.eye(Q.shape[0], Q.shape[1], -1)) + Q[idx] = v[:-1] + Q = np.array(Q, dtype=dtype, order=order) + return Q + + def assert_no_domain_change(self, name, cfunc, args): + msg = name + "() argument must not cause a domain change." + self.assert_error(cfunc, args, msg) + + def _check_worker(self, cfunc, name, expected_res_len, + check_for_domain_change): + def check(*args): + expected = cfunc.py_func(*args) + got = cfunc(*args) + a = args[0] + # check that the returned tuple is same length + self.assertEqual(len(expected), len(got)) + # and that dimension is correct + res_is_tuple = False + if isinstance(got, tuple): + res_is_tuple = True + self.assertEqual(len(got), expected_res_len) + else: # its an array + self.assertEqual(got.ndim, expected_res_len) + + # and that the computed results are contig and in the same way + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + # try plain match of each array to np first + for k in range(len(expected)): + try: + np.testing.assert_array_almost_equal_nulp( + got[k], expected[k], nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + + # If plain match fails then reconstruction is used. + # this checks that A*V ~== V*diag(W) + # i.e. eigensystem ties out + # this is required as numpy uses only double precision lapack + # routines and computation of eigenvectors is numerically + # sensitive, numba uses the type specific routines therefore + # sometimes comes out with a different (but entirely + # valid) answer (eigenvectors are not unique etc.). + # This is only applicable if eigenvectors are computed + # along with eigenvalues i.e. result is a tuple. + resolution = 5 * np.finfo(a.dtype).resolution + if use_reconstruction: + if res_is_tuple: + w, v = got + # modify 'a' if hermitian eigensystem functionality is + # being tested. 'L' for use lower part is default and + # the only thing used at present so we conjugate transpose + # the lower part into the upper for use in the + # reconstruction. By construction the sample matrix is + # tridiag so this is just a question of copying the lower + # diagonal into the upper and conjugating on the way. + if name[-1] == 'h': + idxl = np.nonzero(np.eye(a.shape[0], a.shape[1], -1)) + idxu = np.nonzero(np.eye(a.shape[0], a.shape[1], 1)) + cfunc(*args) + # upper idx must match lower for default uplo="L" + # if complex, conjugate + a[idxu] = np.conj(a[idxl]) + # also, only the real part of the diagonals is + # considered in the calculation so the imag is zeroed + # out for the purposes of use in reconstruction. + a[np.diag_indices(a.shape[0])] = np.real(np.diag(a)) + + lhs = np.dot(a, v) + rhs = np.dot(v, np.diag(w)) + + np.testing.assert_allclose( + lhs.real, + rhs.real, + rtol=resolution, + atol=resolution + ) + if np.iscomplexobj(v): + np.testing.assert_allclose( + lhs.imag, + rhs.imag, + rtol=resolution, + atol=resolution + ) + else: + # This isn't technically reconstruction but is here to + # deal with that the order of the returned eigenvalues + # may differ in the case of routines just returning + # eigenvalues and there's no true reconstruction + # available with which to perform a check. + np.testing.assert_allclose( + np.sort(expected), + np.sort(got), + rtol=resolution, + atol=resolution + ) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(*args) + return check + + def checker_for_linalg_eig( + self, name, func, expected_res_len, check_for_domain_change=None): + """ + Test np.linalg.eig + """ + n = 10 + cfunc = jit(nopython=True)(func) + check = self._check_worker(cfunc, name, expected_res_len, + check_for_domain_change) + + + # The main test loop + for dtype, order in product(self.dtypes, 'FC'): + a = self.sample_matrix(n, dtype, order) + check(a) + + # Test both a real and complex type as the impls are different + for ty in [np.float32, np.complex64]: + + # 0 dimensioned matrix + check(np.empty((0, 0), dtype=ty)) + + # Non square matrices + self.assert_non_square(cfunc, (np.ones((2, 3), dtype=ty),)) + + # Wrong dtype + self.assert_wrong_dtype(name, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(name, cfunc, (np.ones(10, dtype=ty),)) + + # no nans or infs + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=ty),)) + + if check_for_domain_change: + # By design numba does not support dynamic return types, numpy does + # and uses this in the case of returning eigenvalues/vectors of + # a real matrix. The return type of np.linalg.eig(), when + # operating on a matrix in real space depends on the values present + # in the matrix itself (recalling that eigenvalues are the roots of the + # characteristic polynomial of the system matrix, which will by + # construction depend on the values present in the system matrix). + # This test asserts that if a domain change is required on the return + # type, i.e. complex eigenvalues from a real input, an error is raised. + # For complex types, regardless of the value of the imaginary part of + # the returned eigenvalues, a complex type will be returned, this + # follows numpy and fits in with numba. + + # First check that the computation is valid (i.e. in complex space) + A = np.array([[1, -2], [2, 1]]) + check(A.astype(np.complex128)) + # and that the imaginary part is nonzero + l, _ = func(A) + self.assertTrue(np.any(l.imag)) + + # Now check that the computation fails in real space + for ty in [np.float32, np.float64]: + self.assert_no_domain_change(name, cfunc, (A.astype(ty),)) + + @needs_lapack + def test_linalg_eig(self): + self.checker_for_linalg_eig("eig", eig_matrix, 2, True) + + @needs_lapack + def test_linalg_eigvals(self): + self.checker_for_linalg_eig("eigvals", eigvals_matrix, 1, True) + + @needs_lapack + def test_linalg_eigh(self): + self.checker_for_linalg_eig("eigh", eigh_matrix, 2, False) + + @needs_lapack + def test_linalg_eigvalsh(self): + self.checker_for_linalg_eig("eigvalsh", eigvalsh_matrix, 1, False) + + @needs_lapack + def test_no_input_mutation(self): + # checks inputs are not mutated + + for c in (('eig', 2, True), + ('eigvals', 1, True), + ('eigh', 2, False), + ('eigvalsh', 1, False)): + + m, nout, domain_change = c + + meth = getattr(np.linalg, m) + + @jit(nopython=True) + def func(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return meth(X) + + check = self._check_worker(func, m, nout, domain_change) + + for dtype in (np.float64, np.complex128): + with self.subTest(meth=meth, dtype=dtype): + # trivial system, doesn't matter, just checking if it gets + # mutated + X = np.array([[10., 1, 0, 1], + [1, 9, 0, 0], + [0, 0, 8, 0], + [1, 0, 0, 7], + ], order='F', dtype=dtype) + + X_orig = np.copy(X) + + expected = func.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = func(X, False) + np.testing.assert_allclose(X, X_orig) + + check(X, False) + + +class TestLinalgSvd(TestLinalgBase): + """ + Tests for np.linalg.svd. + """ + + # This checks that A ~= U*S*V**H, i.e. SV decomposition ties out. This is + # required as NumPy uses only double precision LAPACK routines and + # computation of SVD is numerically sensitive. Numba uses type-specific + # routines and therefore sometimes comes out with a different answer to + # NumPy (orthonormal bases are not unique, etc.). + + def check_reconstruction(self, a, got, expected): + u, sv, vt = got + + # Check they are dimensionally correct + for k in range(len(expected)): + self.assertEqual(got[k].shape, expected[k].shape) + + # Columns in u and rows in vt dictates the working size of s + s = np.zeros((u.shape[1], vt.shape[0])) + np.fill_diagonal(s, sv) + + rec = np.dot(np.dot(u, s), vt) + resolution = np.finfo(a.dtype).resolution + np.testing.assert_allclose( + a, + rec, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + + @needs_lapack + def test_linalg_svd(self): + """ + Test np.linalg.svd + """ + cfunc = jit(nopython=True)(svd_matrix) + + def check(a, **kwargs): + expected = svd_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + # check that the returned tuple is same length + self.assertEqual(len(expected), len(got)) + # and that length is 3 + self.assertEqual(len(got), 3) + # and that the computed results are contig and in the same way + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + # try plain match of each array to np first + for k in range(len(expected)): + + try: + np.testing.assert_array_almost_equal_nulp( + got[k], expected[k], nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + + if use_reconstruction: + self.check_reconstruction(a, got, expected) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # test: column vector, tall, wide, square, row vector + # prime sizes + sizes = [(7, 1), (7, 5), (5, 7), (3, 3), (1, 7)] + + # flip on reduced or full matrices + full_matrices = (True, False) + + # test loop + for size, dtype, fmat, order in \ + product(sizes, self.dtypes, full_matrices, 'FC'): + + a = self.specific_sample_matrix(size, dtype, order) + check(a, full_matrices=fmat) + + rn = "svd" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # no nans or infs + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + # empty + for sz in [(0, 1), (1, 0), (0, 0)]: + args = (np.empty(sz), True) + self.assert_raise_on_empty(cfunc, args) + + @needs_lapack + def test_no_input_mutation(self): + X = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + X_orig = np.copy(X) + + @jit(nopython=True) + def func(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return np.linalg.svd(X) + + expected = func.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = func(X, False) + np.testing.assert_allclose(X, X_orig) + + try: + for e_a, g_a in zip(expected, got): + np.testing.assert_allclose(e_a, g_a) + except AssertionError: + self.check_reconstruction(X, got, expected) + + +class TestLinalgQr(TestLinalgBase): + """ + Tests for np.linalg.qr. + """ + + @needs_lapack + def test_linalg_qr(self): + """ + Test np.linalg.qr + """ + cfunc = jit(nopython=True)(qr_matrix) + + def check(a, **kwargs): + expected = qr_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # check that the returned tuple is same length + self.assertEqual(len(expected), len(got)) + # and that length is 2 + self.assertEqual(len(got), 2) + # and that the computed results are contig and in the same way + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + # try plain match of each array to np first + for k in range(len(expected)): + try: + np.testing.assert_array_almost_equal_nulp( + got[k], expected[k], nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + + # if plain match fails then reconstruction is used. + # this checks that A ~= Q*R and that (Q^H)*Q = I + # i.e. QR decomposition ties out + # this is required as numpy uses only double precision lapack + # routines and computation of qr is numerically + # sensitive, numba using the type specific routines therefore + # sometimes comes out with a different answer (orthonormal bases + # are not unique etc.). + if use_reconstruction: + q, r = got + + # check they are dimensionally correct + for k in range(len(expected)): + self.assertEqual(got[k].shape, expected[k].shape) + + # check A=q*r + rec = np.dot(q, r) + resolution = np.finfo(a.dtype).resolution + np.testing.assert_allclose( + a, + rec, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + + # check q is orthonormal + self.assert_is_identity_matrix(np.dot(np.conjugate(q.T), q)) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # test: column vector, tall, wide, square, row vector + # prime sizes + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + + # test loop + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + a = self.specific_sample_matrix(size, dtype, order) + check(a) + + rn = "qr" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # no nans or infs + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + + # empty + for sz in [(0, 1), (1, 0), (0, 0)]: + self.assert_raise_on_empty(cfunc, (np.empty(sz),)) + + @needs_lapack + def test_no_input_mutation(self): + X = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + X_orig = np.copy(X) + + @jit(nopython=True) + def func(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return np.linalg.qr(X) + + expected = func.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = func(X, False) + np.testing.assert_allclose(X, X_orig) + + for e_a, g_a in zip(expected, got): + np.testing.assert_allclose(e_a, g_a) + + +class TestLinalgSystems(TestLinalgBase): + """ + Base class for testing "system" solvers from np.linalg. + Namely np.linalg.solve() and np.linalg.lstsq(). + """ + + # check for RHS with dimension > 2 raises + def assert_wrong_dimensions_1D(self, name, cfunc, args, la_prefix=True): + prefix = "np.linalg" if la_prefix else "np" + msg = "%s.%s() only supported on 1 and 2-D arrays" % (prefix, name) + self.assert_error(cfunc, args, msg, errors.TypingError) + + # check that a dimensionally invalid system raises + def assert_dimensionally_invalid(self, cfunc, args): + msg = "Incompatible array sizes, system is not dimensionally valid." + self.assert_error(cfunc, args, msg, np.linalg.LinAlgError) + + # check that args with differing dtypes raise + def assert_homogeneous_dtypes(self, name, cfunc, args): + msg = "np.linalg.%s() only supports inputs that have homogeneous dtypes." % name + self.assert_error(cfunc, args, msg, errors.TypingError) + + +class TestLinalgLstsq(TestLinalgSystems): + """ + Tests for np.linalg.lstsq. + """ + + # NOTE: The testing of this routine is hard as it has to handle numpy + # using double precision routines on single precision input, this has + # a knock on effect especially in rank deficient cases and cases where + # conditioning is generally poor. As a result computed ranks can differ + # and consequently the calculated residual can differ. + # The tests try and deal with this as best as they can through the use + # of reconstruction and measures like residual norms. + # Suggestions for improvements are welcomed! + + @needs_lapack + def test_linalg_lstsq(self): + """ + Test np.linalg.lstsq + """ + cfunc = jit(nopython=True)(lstsq_system) + + def check(A, B, **kwargs): + expected = lstsq_system(A, B, **kwargs) + got = cfunc(A, B, **kwargs) + + # check that the returned tuple is same length + self.assertEqual(len(expected), len(got)) + # and that length is 4 + self.assertEqual(len(got), 4) + # and that the computed results are contig and in the same way + self.assert_contig_sanity(got, "C") + + use_reconstruction = False + + # check the ranks are the same and continue to a standard + # match if that is the case (if ranks differ, then output + # in e.g. residual array is of different size!). + try: + self.assertEqual(got[2], expected[2]) + # try plain match of each array to np first + for k in range(len(expected)): + try: + np.testing.assert_array_almost_equal_nulp( + got[k], expected[k], nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + except AssertionError: + use_reconstruction = True + + if use_reconstruction: + x, res, rank, s = got + + # indicies in the output which are ndarrays + out_array_idx = [0, 1, 3] + + try: + # check the ranks are the same + self.assertEqual(rank, expected[2]) + # check they are dimensionally correct, skip [2] = rank. + for k in out_array_idx: + if isinstance(expected[k], np.ndarray): + self.assertEqual(got[k].shape, expected[k].shape) + except AssertionError: + # check the rank differs by 1. (numerical fuzz) + self.assertTrue(abs(rank - expected[2]) < 2) + + # check if A*X = B + resolution = np.finfo(A.dtype).resolution + try: + # this will work so long as the conditioning is + # ok and the rank is full + rec = np.dot(A, x) + np.testing.assert_allclose( + B, + rec, + rtol=10 * resolution, + atol=10 * resolution + ) + except AssertionError: + # system is probably under/over determined and/or + # poorly conditioned. Check slackened equality + # and that the residual norm is the same. + for k in out_array_idx: + try: + np.testing.assert_allclose( + expected[k], + got[k], + rtol=100 * resolution, + atol=100 * resolution + ) + except AssertionError: + # check the fail is likely due to bad conditioning + c = np.linalg.cond(A) + self.assertGreater(10 * c, (1. / resolution)) + + # make sure the residual 2-norm is ok + # if this fails its probably due to numpy using double + # precision LAPACK routines for singles. + res_expected = np.linalg.norm( + B - np.dot(A, expected[0])) + res_got = np.linalg.norm(B - np.dot(A, x)) + # rtol = 10. as all the systems are products of orthonormals + # and on the small side (rows, cols) < 100. + np.testing.assert_allclose( + res_expected, res_got, rtol=10.) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(A, B, **kwargs) + + # test: column vector, tall, wide, square, row vector + # prime sizes, the A's + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + # compatible B's for Ax=B must have same number of rows and 1 or more + # columns + + # This test takes ages! So combinations are trimmed via cycling + + # gets a dtype + cycle_dt = cycle(self.dtypes) + + orders = ['F', 'C'] + # gets a memory order flag + cycle_order = cycle(orders) + + # a specific condition number to use in the following tests + # there is nothing special about it other than it is not magic + specific_cond = 10. + + # inner test loop, extracted as there's additional logic etc required + # that'd end up with this being repeated a lot + def inner_test_loop_fn(A, dt, **kwargs): + # test solve Ax=B for (column, matrix) B, same dtype as A + b_sizes = (1, 13) + + for b_size in b_sizes: + + # check 2D B + b_order = next(cycle_order) + B = self.specific_sample_matrix( + (A.shape[0], b_size), dt, b_order) + check(A, B, **kwargs) + + # check 1D B + b_order = next(cycle_order) + tmp = B[:, 0].copy(order=b_order) + check(A, tmp, **kwargs) + + # test loop + for a_size in sizes: + + dt = next(cycle_dt) + a_order = next(cycle_order) + + # A full rank, well conditioned system + A = self.specific_sample_matrix(a_size, dt, a_order) + + # run the test loop + inner_test_loop_fn(A, dt) + + m, n = a_size + minmn = min(m, n) + + # operations that only make sense with a 2D matrix system + if m != 1 and n != 1: + + # Test a rank deficient system + r = minmn - 1 + A = self.specific_sample_matrix( + a_size, dt, a_order, rank=r) + # run the test loop + inner_test_loop_fn(A, dt) + + # Test a system with a given condition number for use in + # testing the rcond parameter. + # This works because the singular values in the + # specific_sample_matrix code are linspace (1, cond, [0... if + # rank deficient]) + A = self.specific_sample_matrix( + a_size, dt, a_order, condition=specific_cond) + # run the test loop + rcond = 1. / specific_cond + approx_half_rank_rcond = minmn * rcond + inner_test_loop_fn(A, dt, + rcond=approx_half_rank_rcond) + + # check empty arrays + empties = [ + [(0, 1), (1,)], # empty A, valid b + [(1, 0), (1,)], # empty A, valid b + [(1, 1), (0,)], # valid A, empty 1D b + [(1, 1), (1, 0)], # valid A, empty 2D b + ] + + for A, b in empties: + args = (np.empty(A), np.empty(b)) + self.assert_raise_on_empty(cfunc, args) + + # Test input validation + ok = np.array([[1., 2.], [3., 4.]], dtype=np.float64) + + # check ok input is ok + cfunc, (ok, ok) + + # check bad inputs + rn = "lstsq" + + # Wrong dtype + bad = np.array([[1, 2], [3, 4]], dtype=np.int32) + self.assert_wrong_dtype(rn, cfunc, (ok, bad)) + self.assert_wrong_dtype(rn, cfunc, (bad, ok)) + + # different dtypes + bad = np.array([[1, 2], [3, 4]], dtype=np.float32) + self.assert_homogeneous_dtypes(rn, cfunc, (ok, bad)) + self.assert_homogeneous_dtypes(rn, cfunc, (bad, ok)) + + # Dimension issue + bad = np.array([1, 2], dtype=np.float64) + self.assert_wrong_dimensions(rn, cfunc, (bad, ok)) + + # no nans or infs + bad = np.array([[1., 2., ], [np.inf, np.nan]], dtype=np.float64) + self.assert_no_nan_or_inf(cfunc, (ok, bad)) + self.assert_no_nan_or_inf(cfunc, (bad, ok)) + + # check 1D is accepted for B (2D is done previously) + # and then that anything of higher dimension raises + oneD = np.array([1., 2.], dtype=np.float64) + cfunc, (ok, oneD) + bad = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.float64) + self.assert_wrong_dimensions_1D(rn, cfunc, (ok, bad)) + + # check a dimensionally invalid system raises (1D and 2D cases + # checked) + bad1D = np.array([1.], dtype=np.float64) + bad2D = np.array([[1.], [2.], [3.]], dtype=np.float64) + self.assert_dimensionally_invalid(cfunc, (ok, bad1D)) + self.assert_dimensionally_invalid(cfunc, (ok, bad2D)) + + @needs_lapack + def test_issue3368(self): + X = np.array([[1., 7.54, 6.52], + [1., 2.70, 4.00], + [1., 2.50, 3.80], + [1., 1.15, 5.64], + [1., 4.22, 3.27], + [1., 1.41, 5.70],], order='F') + + X_orig = np.copy(X) + y = np.array([1., 2., 3., 4., 5., 6.]) + + @jit(nopython=True) + def f2(X, y, test): + if test: + # never executed, but necessary to trigger the bug + X = X[1:2, :] + return np.linalg.lstsq(X, y) + + f2(X, y, False) + np.testing.assert_allclose(X, X_orig) + + +class TestLinalgSolve(TestLinalgSystems): + """ + Tests for np.linalg.solve. + """ + + @needs_lapack + def test_linalg_solve(self): + """ + Test np.linalg.solve + """ + cfunc = jit(nopython=True)(solve_system) + + def check(a, b, **kwargs): + expected = solve_system(a, b, **kwargs) + got = cfunc(a, b, **kwargs) + + # check that the computed results are contig and in the same way + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + # try plain match of the result first + try: + np.testing.assert_array_almost_equal_nulp( + got, expected, nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + + # If plain match fails then reconstruction is used, + # this checks that AX ~= B. + # Plain match can fail due to numerical fuzziness associated + # with system size and conditioning, or more simply from + # numpy using double precision routines for computation that + # could be done in single precision (which is what numba does). + # Therefore minor differences in results can appear due to + # e.g. numerical roundoff being different between two precisions. + if use_reconstruction: + # check they are dimensionally correct + self.assertEqual(got.shape, expected.shape) + + # check AX=B + rec = np.dot(a, got) + resolution = np.finfo(a.dtype).resolution + np.testing.assert_allclose( + b, + rec, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, b, **kwargs) + + # test: prime size squares + sizes = [(1, 1), (3, 3), (7, 7)] + + # test loop + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + A = self.specific_sample_matrix(size, dtype, order) + + b_sizes = (1, 13) + + for b_size, b_order in product(b_sizes, 'FC'): + # check 2D B + B = self.specific_sample_matrix( + (A.shape[0], b_size), dtype, b_order) + check(A, B) + + # check 1D B + tmp = B[:, 0].copy(order=b_order) + check(A, tmp) + + # check empty + cfunc(np.empty((0, 0)), np.empty((0,))) + + # Test input validation + ok = np.array([[1., 0.], [0., 1.]], dtype=np.float64) + + # check ok input is ok + cfunc(ok, ok) + + # check bad inputs + rn = "solve" + + # Wrong dtype + bad = np.array([[1, 0], [0, 1]], dtype=np.int32) + self.assert_wrong_dtype(rn, cfunc, (ok, bad)) + self.assert_wrong_dtype(rn, cfunc, (bad, ok)) + + # different dtypes + bad = np.array([[1, 2], [3, 4]], dtype=np.float32) + self.assert_homogeneous_dtypes(rn, cfunc, (ok, bad)) + self.assert_homogeneous_dtypes(rn, cfunc, (bad, ok)) + + # Dimension issue + bad = np.array([1, 0], dtype=np.float64) + self.assert_wrong_dimensions(rn, cfunc, (bad, ok)) + + # no nans or infs + bad = np.array([[1., 0., ], [np.inf, np.nan]], dtype=np.float64) + self.assert_no_nan_or_inf(cfunc, (ok, bad)) + self.assert_no_nan_or_inf(cfunc, (bad, ok)) + + # check 1D is accepted for B (2D is done previously) + # and then that anything of higher dimension raises + ok_oneD = np.array([1., 2.], dtype=np.float64) + cfunc(ok, ok_oneD) + bad = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.float64) + self.assert_wrong_dimensions_1D(rn, cfunc, (ok, bad)) + + # check an invalid system raises (1D and 2D cases checked) + bad1D = np.array([1.], dtype=np.float64) + bad2D = np.array([[1.], [2.], [3.]], dtype=np.float64) + self.assert_dimensionally_invalid(cfunc, (ok, bad1D)) + self.assert_dimensionally_invalid(cfunc, (ok, bad2D)) + + # check that a singular system raises + bad2D = self.specific_sample_matrix((2, 2), np.float64, 'C', rank=1) + self.assert_raise_on_singular(cfunc, (bad2D, ok)) + + @needs_lapack + def test_no_input_mutation(self): + X = np.array([[1., 1, 1, 1], + [0., 1, 1, 1], + [0., 0, 1, 1], + [1., 0, 0, 1],], order='F') + + X_orig = np.copy(X) + y = np.array([1., 2., 3., 4]) + y_orig = np.copy(y) + + @jit(nopython=True) + def func(X, y, test): + if test: + # not executed, triggers A order in X + X = X[1:2, :] + return np.linalg.solve(X, y) + + expected = func.py_func(X, y, False) + np.testing.assert_allclose(X, X_orig) + np.testing.assert_allclose(y, y_orig) + + got = func(X, y, False) + np.testing.assert_allclose(X, X_orig) + np.testing.assert_allclose(y, y_orig) + + np.testing.assert_allclose(expected, got) + + +class TestLinalgPinv(TestLinalgBase): + """ + Tests for np.linalg.pinv. + """ + + @needs_lapack + def test_linalg_pinv(self): + """ + Test np.linalg.pinv + """ + cfunc = jit(nopython=True)(pinv_matrix) + + def check(a, **kwargs): + expected = pinv_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # check that the computed results are contig and in the same way + self.assert_contig_sanity(got, "F") + + use_reconstruction = False + # try plain match of each array to np first + + try: + np.testing.assert_array_almost_equal_nulp( + got, expected, nulp=10) + except AssertionError: + # plain match failed, test by reconstruction + use_reconstruction = True + + # If plain match fails then reconstruction is used. + # This can occur due to numpy using double precision + # LAPACK when single can be used, this creates round off + # problems. Also, if the matrix has machine precision level + # zeros in its singular values then the singular vectors are + # likely to vary depending on round off. + if use_reconstruction: + + # check they are dimensionally correct + self.assertEqual(got.shape, expected.shape) + + # check pinv(A)*A~=eye + # if the problem is numerical fuzz then this will probably + # work, if the problem is rank deficiency then it won't! + rec = np.dot(got, a) + try: + self.assert_is_identity_matrix(rec) + except AssertionError: + # check A=pinv(pinv(A)) + resolution = 5 * np.finfo(a.dtype).resolution + rec = cfunc(got) + np.testing.assert_allclose( + rec, + a, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + if a.shape[0] >= a.shape[1]: + # if it is overdetermined or fully determined + # use numba lstsq function (which is type specific) to + # compute the inverse and check against that. + lstsq = jit(nopython=True)(lstsq_system) + lstsq_pinv = lstsq( + a, np.eye( + a.shape[0]).astype( + a.dtype), **kwargs)[0] + np.testing.assert_allclose( + got, + lstsq_pinv, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + # check the 2 norm of the difference is small + self.assertLess(np.linalg.norm(got - expected), resolution) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # test: column vector, tall, wide, square, row vector + # prime sizes + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + + # When required, a specified condition number + specific_cond = 10. + + # test loop + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + # check a full rank matrix + a = self.specific_sample_matrix(size, dtype, order) + check(a) + + m, n = size + if m != 1 and n != 1: + # check a rank deficient matrix + minmn = min(m, n) + a = self.specific_sample_matrix(size, dtype, order, + condition=specific_cond) + rcond = 1. / specific_cond + approx_half_rank_rcond = minmn * rcond + check(a, rcond=approx_half_rank_rcond) + + # check empty + for sz in [(0, 1), (1, 0)]: + check(np.empty(sz)) + + rn = "pinv" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # no nans or infs + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + + @needs_lapack + def test_issue5870(self): + # testing for mutation of input matrix + @jit(nopython=True) + def some_fn(v): + return np.linalg.pinv(v[0]) + + v_data = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + v_orig = np.copy(v_data) + reshaped_v = v_data.reshape((1, 4, 4)) + + expected = some_fn.py_func(reshaped_v) + np.testing.assert_allclose(v_data, v_orig) + + got = some_fn(reshaped_v) + np.testing.assert_allclose(v_data, v_orig) + + np.testing.assert_allclose(expected, got) + + +class TestLinalgDetAndSlogdet(TestLinalgBase): + """ + Tests for np.linalg.det. and np.linalg.slogdet. + Exactly the same inputs are used for both tests as + det() is a trivial function of slogdet(), the tests + are therefore combined. + """ + + def check_det(self, cfunc, a, **kwargs): + expected = det_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + resolution = 5 * np.finfo(a.dtype).resolution + + # check the determinants are the same + np.testing.assert_allclose(got, expected, rtol=resolution) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + def check_slogdet(self, cfunc, a, **kwargs): + expected = slogdet_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # As numba returns python floats types and numpy returns + # numpy float types, some more adjustment and different + # types of comparison than those used with array based + # results is required. + + # check that the returned tuple is same length + self.assertEqual(len(expected), len(got)) + # and that length is 2 + self.assertEqual(len(got), 2) + + # check that the domain of the results match + for k in range(2): + self.assertEqual( + np.iscomplexobj(got[k]), + np.iscomplexobj(expected[k])) + + # turn got[0] into the same dtype as `a` + # this is so checking with nulp will work + got_conv = a.dtype.type(got[0]) + np.testing.assert_array_almost_equal_nulp( + got_conv, expected[0], nulp=10) + # compare log determinant magnitude with a more fuzzy value + # as numpy values come from higher precision lapack routines + resolution = 5 * np.finfo(a.dtype).resolution + np.testing.assert_allclose( + got[1], expected[1], rtol=resolution, atol=resolution) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + def do_test(self, rn, check, cfunc): + + # test: 1x1 as it is unusual, 4x4 as it is even and 7x7 as is it odd! + sizes = [(1, 1), (4, 4), (7, 7)] + + # test loop + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + # check a full rank matrix + a = self.specific_sample_matrix(size, dtype, order) + check(cfunc, a) + + # use a matrix of zeros to trip xgetrf U(i,i)=0 singular test + for dtype, order in product(self.dtypes, 'FC'): + a = np.zeros((3, 3), dtype=dtype) + check(cfunc, a) + + # check empty + check(cfunc, np.empty((0, 0))) + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # no nans or infs + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + + @needs_lapack + def test_linalg_det(self): + cfunc = jit(nopython=True)(det_matrix) + self.do_test("det", self.check_det, cfunc) + + @needs_lapack + def test_linalg_slogdet(self): + cfunc = jit(nopython=True)(slogdet_matrix) + self.do_test("slogdet", self.check_slogdet, cfunc) + + @needs_lapack + def test_no_input_mutation(self): + X = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + X_orig = np.copy(X) + + @jit(nopython=True) + def func(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return np.linalg.slogdet(X) + + expected = func.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = func(X, False) + np.testing.assert_allclose(X, X_orig) + + np.testing.assert_allclose(expected, got) + +# Use TestLinalgSystems as a base to get access to additional +# testing for 1 and 2D inputs. + + +class TestLinalgNorm(TestLinalgSystems): + """ + Tests for np.linalg.norm. + """ + + @needs_lapack + def test_linalg_norm(self): + """ + Test np.linalg.norm + """ + cfunc = jit(nopython=True)(norm_matrix) + + def check(a, **kwargs): + expected = norm_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # All results should be in the real domain + self.assertTrue(not np.iscomplexobj(got)) + + resolution = 5 * np.finfo(a.dtype).resolution + + # check the norms are the same to the arg `a` precision + np.testing.assert_allclose(got, expected, rtol=resolution) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # Check 1D inputs + sizes = [1, 4, 7] + nrm_types = [None, np.inf, -np.inf, 0, 1, -1, 2, -2, 5, 6.7, -4.3] + + # standard 1D input + for size, dtype, nrm_type in \ + product(sizes, self.dtypes, nrm_types): + a = self.sample_vector(size, dtype) + check(a, ord=nrm_type) + + # sliced 1D input + for dtype, nrm_type in \ + product(self.dtypes, nrm_types): + a = self.sample_vector(10, dtype)[::3] + check(a, ord=nrm_type) + + # Check 2D inputs: + # test: column vector, tall, wide, square, row vector + # prime sizes + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + nrm_types = [None, np.inf, -np.inf, 1, -1, 2, -2] + + # standard 2D input + for size, dtype, order, nrm_type in \ + product(sizes, self.dtypes, 'FC', nrm_types): + # check a full rank matrix + a = self.specific_sample_matrix(size, dtype, order) + check(a, ord=nrm_type) + + # check 2D slices work for the case where xnrm2 is called from + # BLAS (ord=None) to make sure it is working ok. + nrm_types = [None] + for dtype, nrm_type, order in \ + product(self.dtypes, nrm_types, 'FC'): + a = self.specific_sample_matrix((17, 13), dtype, order) + # contig for C order + check(a[:3], ord=nrm_type) + + # contig for Fortran order + check(a[:, 3:], ord=nrm_type) + + # contig for neither order + check(a[1, 4::3], ord=nrm_type) + + # check that numba returns zero for empty arrays. Numpy returns zero + # for most norm types and raises ValueError for +/-np.inf. + # there is not a great deal of consistency in Numpy's response so + # it is not being emulated in Numba + for dtype, nrm_type, order in \ + product(self.dtypes, nrm_types, 'FC'): + a = np.empty((0,), dtype=dtype, order=order) + self.assertEqual(cfunc(a, nrm_type), 0.0) + a = np.empty((0, 0), dtype=dtype, order=order) + self.assertEqual(cfunc(a, nrm_type), 0.0) + + rn = "norm" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue, reuse the test from the TestLinalgSystems class + self.assert_wrong_dimensions_1D( + rn, cfunc, (np.ones( + 12, dtype=np.float64).reshape( + 2, 2, 3),)) + + # no nans or infs for 2d case when SVD is used (e.g 2-norm) + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2.], [np.inf, np.nan]], + dtype=np.float64), 2)) + + # assert 2D input raises for an invalid norm kind kwarg + self.assert_invalid_norm_kind(cfunc, (np.array([[1., 2.], [3., 4.]], + dtype=np.float64), 6)) + + +class TestLinalgCond(TestLinalgBase): + """ + Tests for np.linalg.cond. + """ + + @needs_lapack + def test_linalg_cond(self): + """ + Test np.linalg.cond + """ + + cfunc = jit(nopython=True)(cond_matrix) + + def check(a, **kwargs): + expected = cond_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # All results should be in the real domain + self.assertTrue(not np.iscomplexobj(got)) + + resolution = 5 * np.finfo(a.dtype).resolution + + # check the cond is the same to the arg `a` precision + np.testing.assert_allclose(got, expected, rtol=resolution) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # valid p values (used to indicate norm type) + ps = [None, np.inf, -np.inf, 1, -1, 2, -2] + sizes = [(3, 3), (7, 7)] + + for size, dtype, order, p in \ + product(sizes, self.dtypes, 'FC', ps): + a = self.specific_sample_matrix(size, dtype, order) + check(a, p=p) + + # When p=None non-square matrices are accepted. + sizes = [(7, 1), (11, 5), (5, 11), (1, 7)] + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + a = self.specific_sample_matrix(size, dtype, order) + check(a) + + # empty + for sz in [(0, 1), (1, 0), (0, 0)]: + self.assert_raise_on_empty(cfunc, (np.empty(sz),)) + + # singular systems to trip divide-by-zero + x = np.array([[1, 0], [0, 0]], dtype=np.float64) + check(x) + check(x, p=2) + x = np.array([[0, 0], [0, 0]], dtype=np.float64) + check(x, p=-2) + + # try an ill-conditioned system with 2-norm, make sure np raises an + # overflow warning as the result is `+inf` and that the result from + # numba matches. + with warnings.catch_warnings(): + a = np.array([[1.e308, 0], [0, 0.1]], dtype=np.float64) + warnings.simplefilter("ignore", RuntimeWarning) + check(a) + + rn = "cond" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64),)) + + # no nans or infs when p="None" (default for kwarg). + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + + # assert raises for an invalid norm kind kwarg + self.assert_invalid_norm_kind(cfunc, (np.array([[1., 2.], [3., 4.]], + dtype=np.float64), 6)) + + +class TestLinalgMatrixRank(TestLinalgSystems): + """ + Tests for np.linalg.matrix_rank. + """ + + @needs_lapack + def test_linalg_matrix_rank(self): + """ + Test np.linalg.matrix_rank + """ + + cfunc = jit(nopython=True)(matrix_rank_matrix) + + def check(a, **kwargs): + expected = matrix_rank_matrix(a, **kwargs) + got = cfunc(a, **kwargs) + + # Ranks are integral so comparison should be trivial. + # check the rank is the same + np.testing.assert_allclose(got, expected) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + + for size, dtype, order in \ + product(sizes, self.dtypes, 'FC'): + # check full rank system + a = self.specific_sample_matrix(size, dtype, order) + check(a) + + # If the system is a matrix, check rank deficiency is reported + # correctly. Check all ranks from 0 to (full rank - 1). + tol = 1e-13 + # first check 1 to (full rank - 1) + for k in range(1, min(size) - 1): + # check rank k + a = self.specific_sample_matrix(size, dtype, order, rank=k) + self.assertEqual(cfunc(a), k) + check(a) + # check provision of a tolerance works as expected + # create a (m x n) diagonal matrix with a singular value + # guaranteed below the tolerance 1e-13 + m, n = a.shape + a[:, :] = 0. # reuse `a`'s memory + idx = np.nonzero(np.eye(m, n)) + if np.iscomplexobj(a): + b = 1. + np.random.rand(k) + 1.j +\ + 1.j * np.random.rand(k) + # min singular value is sqrt(2)*1e-14 + b[0] = 1e-14 + 1e-14j + else: + b = 1. + np.random.rand(k) + b[0] = 1e-14 # min singular value is 1e-14 + a[idx[0][:k], idx[1][:k]] = b.astype(dtype) + # rank should be k-1 (as tol is present) + self.assertEqual(cfunc(a, tol), k - 1) + check(a, tol=tol) + # then check zero rank + a[:, :] = 0. + self.assertEqual(cfunc(a), 0) + check(a) + # add in a singular value that is small + if np.iscomplexobj(a): + a[-1, -1] = 1e-14 + 1e-14j + else: + a[-1, -1] = 1e-14 + # check the system has zero rank to a given tolerance + self.assertEqual(cfunc(a, tol), 0) + check(a, tol=tol) + + # check the zero vector returns rank 0 and a nonzero vector + # returns rank 1. + for dt in self.dtypes: + a = np.zeros((5), dtype=dt) + self.assertEqual(cfunc(a), 0) + check(a) + # make it a nonzero vector + a[0] = 1. + self.assertEqual(cfunc(a), 1) + check(a) + + # empty + for sz in [(0, 1), (1, 0), (0, 0)]: + for tol in [None, 1e-13]: + self.assert_raise_on_empty(cfunc, (np.empty(sz), tol)) + + rn = "matrix_rank" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32),)) + + # Dimension issue + self.assert_wrong_dimensions_1D( + rn, cfunc, (np.ones( + 12, dtype=np.float64).reshape( + 2, 2, 3),)) + + # no nans or infs for 2D case + self.assert_no_nan_or_inf(cfunc, + (np.array([[1., 2., ], [np.inf, np.nan]], + dtype=np.float64),)) + + @needs_lapack + def test_no_input_mutation(self): + # this is here to test no input mutation by + # numba.np.linalg._compute_singular_values + # which is the workhorse for norm with 2d input, rank and cond. + + X = np.array([[1., 3, 2, 7,], + [-5, 4, 2, 3,], + [9, -3, 1, 1,], + [2, -2, 2, 8,]], order='F') + + X_orig = np.copy(X) + + @jit(nopython=True) + def func(X, test): + if test: + # not executed, but necessary to trigger A ordering in X + X = X[1:2, :] + return np.linalg.matrix_rank(X) + + expected = func.py_func(X, False) + np.testing.assert_allclose(X, X_orig) + + got = func(X, False) + np.testing.assert_allclose(X, X_orig) + + np.testing.assert_allclose(expected, got) + + +class TestLinalgMatrixPower(TestLinalgBase): + """ + Tests for np.linalg.matrix_power. + """ + + def assert_int_exponenent(self, cfunc, args): + # validate first arg is ok + cfunc(args[0], 1) + # pass in both args and assert fail + with self.assertRaises(errors.TypingError): + cfunc(*args) + + @needs_lapack + def test_linalg_matrix_power(self): + cfunc = jit(nopython=True)(matrix_power_matrix) + + def check(a, pwr): + expected = matrix_power_matrix(a, pwr) + got = cfunc(a, pwr) + + # check that the computed results are contig and in the same way + self.assert_contig_sanity(got, "C") + + res = 7 * np.finfo(a.dtype).resolution + np.testing.assert_allclose(got, expected, rtol=res, atol=res) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, pwr) + + sizes = [(1, 1), (5, 5), (7, 7)] + powers = [-33, -17] + list(range(-10, 10)) + [17, 33] + + for size, pwr, dtype, order in \ + product(sizes, powers, self.dtypes, 'FC'): + a = self.specific_sample_matrix(size, dtype, order) + check(a, pwr) + a = np.empty((0, 0), dtype=dtype, order=order) + check(a, pwr) + + rn = "matrix_power" + + # Wrong dtype + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32), 1)) + + # not an int power + self.assert_wrong_dtype(rn, cfunc, + (np.ones((2, 2), dtype=np.int32), 1)) + + # non square system + args = (np.ones((3, 5)), 1) + msg = 'input must be a square array' + self.assert_error(cfunc, args, msg) + + # Dimension issue + self.assert_wrong_dimensions(rn, cfunc, + (np.ones(10, dtype=np.float64), 1)) + + # non-integer supplied as exponent + self.assert_int_exponenent(cfunc, (np.ones((2, 2)), 1.2)) + + # singular matrix is not invertible + self.assert_raise_on_singular(cfunc, (np.array([[0., 0], [1, 1]]), -1)) + + +class TestTrace(TestLinalgBase): + """ + Tests for np.trace. + """ + + def setUp(self): + super(TestTrace, self).setUp() + # compile two versions, one with and one without the offset kwarg + self.cfunc_w_offset = jit(nopython=True)(trace_matrix) + self.cfunc_no_offset = jit(nopython=True)(trace_matrix_no_offset) + + def assert_int_offset(self, cfunc, a, **kwargs): + # validate first arg is ok + cfunc(a) + # pass in kwarg and assert fail + with self.assertRaises(errors.TypingError): + cfunc(a, **kwargs) + + def test_trace(self): + + def check(a, **kwargs): + if 'offset' in kwargs: + expected = trace_matrix(a, **kwargs) + cfunc = self.cfunc_w_offset + else: + expected = trace_matrix_no_offset(a, **kwargs) + cfunc = self.cfunc_no_offset + + got = cfunc(a, **kwargs) + + res = 5 * np.finfo(a.dtype).resolution + np.testing.assert_allclose(got, expected, rtol=res, atol=res) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # test: column vector, tall, wide, square, row vector + # prime sizes + sizes = [(7, 1), (11, 5), (5, 11), (3, 3), (1, 7)] + + # offsets to cover the range of the matrix sizes above + offsets = [-13, -12, -11] + list(range(-10, 10)) + [11, 12, 13] + + for size, offset, dtype, order in \ + product(sizes, offsets, self.dtypes, 'FC'): + a = self.specific_sample_matrix(size, dtype, order) + check(a, offset=offset) + if offset == 0: + check(a) + a = np.empty((0, 0), dtype=dtype, order=order) + check(a, offset=offset) + if offset == 0: + check(a) + + rn = "trace" + + # Dimension issue + self.assert_wrong_dimensions(rn, self.cfunc_w_offset, + (np.ones(10, dtype=np.float64), 1), False) + self.assert_wrong_dimensions(rn, self.cfunc_no_offset, + (np.ones(10, dtype=np.float64),), False) + + # non-integer supplied as exponent + self.assert_int_offset( + self.cfunc_w_offset, np.ones( + (2, 2)), offset=1.2) + + def test_trace_w_optional_input(self): + "Issue 2314" + @jit("(optional(float64[:,:]),)", nopython=True) + def tested(a): + return np.trace(a) + + a = np.ones((5, 5), dtype=np.float64) + tested(a) + + with self.assertRaises(TypeError) as raises: + tested(None) + + errmsg = str(raises.exception) + self.assertEqual('expected array(float64, 2d, A), got None', errmsg) + + +class TestBasics(TestLinalgSystems): # TestLinalgSystems for 1d test + + order1 = cycle(['F', 'C', 'C', 'F']) + order2 = cycle(['C', 'F', 'C', 'F']) + + # test: column vector, matrix, row vector, 1d sizes + # (7, 1, 3) and two scalars + sizes = [(7, 1), (3, 3), (1, 7), (7,), (1,), (3,), 3., 5.] + + def _assert_wrong_dim(self, rn, cfunc): + # Dimension issue + self.assert_wrong_dimensions_1D( + rn, cfunc, (np.array([[[1]]], dtype=np.float64), np.ones(1)), False) + self.assert_wrong_dimensions_1D( + rn, cfunc, (np.ones(1), np.array([[[1]]], dtype=np.float64)), False) + + def _gen_input(self, size, dtype, order): + if not isinstance(size, tuple): + return size + else: + if len(size) == 1: + return self.sample_vector(size[0], dtype) + else: + return self.sample_vector( + size[0] * size[1], + dtype).reshape( + size, order=order) + + def _get_input(self, size1, size2, dtype): + a = self._gen_input(size1, dtype, next(self.order1)) + b = self._gen_input(size2, dtype, next(self.order2)) + # force domain consistency as underlying ufuncs require it + if np.iscomplexobj(a): + b = b + 1j + if np.iscomplexobj(b): + a = a + 1j + return (a, b) + + def test_outer(self): + cfunc = jit(nopython=True)(outer_matrix) + + def check(a, b, **kwargs): + + # check without kwargs + expected = outer_matrix(a, b) + got = cfunc(a, b) + + res = 5 * np.finfo(np.asarray(a).dtype).resolution + np.testing.assert_allclose(got, expected, rtol=res, atol=res) + + # if kwargs present check with them too + if 'out' in kwargs: + got = cfunc(a, b, **kwargs) + np.testing.assert_allclose(got, expected, rtol=res, + atol=res) + np.testing.assert_allclose(kwargs['out'], expected, + rtol=res, atol=res) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, b, **kwargs) + + dts = cycle(self.dtypes) + for size1, size2 in product(self.sizes, self.sizes): + dtype = next(dts) + (a, b) = self._get_input(size1, size2, dtype) + check(a, b) + c = np.empty((np.asarray(a).size, np.asarray(b).size), + dtype=np.asarray(a).dtype) + check(a, b, out=c) + + self._assert_wrong_dim("outer", cfunc) + + def test_kron(self): + cfunc = jit(nopython=True)(kron_matrix) + + def check(a, b, **kwargs): + + expected = kron_matrix(a, b) + got = cfunc(a, b) + + res = 5 * np.finfo(np.asarray(a).dtype).resolution + np.testing.assert_allclose(got, expected, rtol=res, atol=res) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, b) + + for size1, size2, dtype in \ + product(self.sizes, self.sizes, self.dtypes): + (a, b) = self._get_input(size1, size2, dtype) + check(a, b) + + self._assert_wrong_dim("kron", cfunc) + + args = (np.empty(10)[::2], np.empty(10)[::2]) + msg = "only supports 'C' or 'F' layout" + self.assert_error(cfunc, args, msg, err=errors.TypingError) + + +class TestHelpers(TestCase): + def test_copy_to_fortran_order(self): + from numba.np.linalg import _copy_to_fortran_order + + def check(udt, expectfn, shapes, dtypes, orders): + for shape, dtype, order in product(shapes, dtypes, orders): + a = np.arange(np.prod(shape)).reshape(shape, order=order) + + r = udt(a) + # check correct operation + self.assertPreciseEqual(expectfn(a), r) + # check new copy has made + self.assertNotEqual(a.ctypes.data, r.ctypes.data) + + @njit + def direct_call(a): + return _copy_to_fortran_order(a) + + shapes = [(3, 4), (3, 2, 5)] + dtypes = [np.intp] + orders = ['C', 'F'] + check(direct_call, np.asfortranarray, shapes, dtypes, orders) + + + @njit + def slice_to_any(a): + # make a 'any' layout slice + sliced = a[::2][0] + return _copy_to_fortran_order(sliced) + + shapes = [(3, 3, 4), (3, 3, 2, 5)] + dtypes = [np.intp] + orders = ['C', 'F'] + + def expected_slice_to_any(a): + # make a 'any' layout slice + sliced = a[::2][0] + return np.asfortranarray(sliced) + + check(slice_to_any, expected_slice_to_any, shapes, dtypes, orders) + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_locals.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_locals.py new file mode 100644 index 0000000000000000000000000000000000000000..9546f58c1e6dfea5138996e7debcdb0b5a3828eb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_locals.py @@ -0,0 +1,18 @@ +from numba import float32, njit +import unittest + + +def foo(): + x = 123 + return x + + +class TestLocals(unittest.TestCase): + + def test_seed_types(self): + cfunc = njit((), locals={'x': float32})(foo) + self.assertEqual(cfunc.nopython_signatures[0].return_type, float32) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_looplifting.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_looplifting.py new file mode 100644 index 0000000000000000000000000000000000000000..2895244b1dac4f2bca51e489e7353487c5be6ea3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_looplifting.py @@ -0,0 +1,595 @@ +from io import StringIO +import numpy as np + +from numba.core import types +from numba.core.compiler import compile_extra, Flags +from numba.tests.support import TestCase, tag, MemoryLeakMixin +import unittest + + +looplift_flags = Flags() +looplift_flags.force_pyobject = True +looplift_flags.enable_looplift = True + +pyobject_looplift_flags = looplift_flags.copy() +pyobject_looplift_flags.enable_pyobject_looplift = True + + +def compile_isolated(pyfunc, argtypes, **kwargs): + from numba.core.registry import cpu_target + + kwargs.setdefault('return_type', None) + kwargs.setdefault('locals', {}) + return compile_extra( + cpu_target.typing_context, + cpu_target.target_context, + pyfunc, + argtypes, + **kwargs, + ) + + +def lift1(x): + # Outer needs object mode because of np.empty() + a = np.empty(3) + for i in range(a.size): + # Inner is nopython-compliant + a[i] = x + return a + + +def lift2(x): + # Outer needs object mode because of np.empty() + a = np.empty((3, 4)) + for i in range(a.shape[0]): + for j in range(a.shape[1]): + # Inner is nopython-compliant + a[i, j] = x + return a + + +def lift3(x): + # Output variable from the loop + _ = object() + a = np.arange(5, dtype=np.int64) + c = 0 + for i in range(a.shape[0]): + c += a[i] * x + return c + +def lift4(x): + # Output two variables from the loop + _ = object() + a = np.arange(5, dtype=np.int64) + c = 0 + d = 0 + for i in range(a.shape[0]): + c += a[i] * x + d += c + return c + d + +def lift5(x): + _ = object() + a = np.arange(4) + for i in range(a.shape[0]): + # Inner has a break statement + if i > 2: + break + return a + +def lift_gen1(x): + # Outer needs object mode because of np.empty() + a = np.empty(3) + yield 0 + for i in range(a.size): + # Inner is nopython-compliant + a[i] = x + yield np.sum(a) + +def lift_issue2561(): + np.empty(1) # This forces objectmode because no nrt + for i in range(10): + for j in range(10): + return 1 + return 2 + +def reject1(x): + a = np.arange(4) + for i in range(a.shape[0]): + # Inner returns a variable from outer "scope" => cannot loop-lift + return a + return a + + +def reject_gen1(x): + _ = object() + a = np.arange(4) + for i in range(a.shape[0]): + # Inner is a generator => cannot loop-lift + yield a[i] + +def reject_gen2(x): + _ = object() + a = np.arange(3) + for i in range(a.size): + # Middle has a yield => cannot loop-lift + res = a[i] + x + for j in range(i): + # Inner is nopython-compliant, but the current algorithm isn't + # able to separate it. + res = res ** 2 + yield res + +def reject_npm1(x): + a = np.empty(3, dtype=np.int32) + for i in range(a.size): + # Inner uses object() => cannot loop-lift + _ = object() + a[i] = np.arange(i + 1)[i] + + return a + + +class TestLoopLifting(MemoryLeakMixin, TestCase): + + def try_lift(self, pyfunc, argtypes): + from numba.core.registry import cpu_target + + cres = compile_extra( + cpu_target.typing_context, + cpu_target.target_context, + pyfunc, argtypes, + return_type=None, flags=looplift_flags, locals={}, + ) + # One lifted loop + self.assertEqual(len(cres.lifted), 1) + return cres + + def assert_lifted_native(self, cres): + # Check if we have lifted in nopython mode + jitloop = cres.lifted[0] + [loopcres] = jitloop.overloads.values() + self.assertTrue(loopcres.fndesc.native) # Lifted function is native + + def check_lift_ok(self, pyfunc, argtypes, args): + """ + Check that pyfunc can loop-lift even in nopython mode. + """ + cres = self.try_lift(pyfunc, argtypes) + expected = pyfunc(*args) + got = cres.entry_point(*args) + self.assert_lifted_native(cres) + # Check return values + self.assertPreciseEqual(expected, got) + + def check_lift_generator_ok(self, pyfunc, argtypes, args): + """ + Check that pyfunc (a generator function) can loop-lift even in + nopython mode. + """ + cres = self.try_lift(pyfunc, argtypes) + expected = list(pyfunc(*args)) + got = list(cres.entry_point(*args)) + self.assert_lifted_native(cres) + # Check return values + self.assertPreciseEqual(expected, got) + + def check_no_lift(self, pyfunc, argtypes, args): + """ + Check that pyfunc can't loop-lift. + """ + cres = compile_isolated(pyfunc, argtypes, + flags=looplift_flags) + self.assertFalse(cres.lifted) + expected = pyfunc(*args) + got = cres.entry_point(*args) + # Check return values + self.assertPreciseEqual(expected, got) + + def check_no_lift_generator(self, pyfunc, argtypes, args): + """ + Check that pyfunc (a generator function) can't loop-lift. + """ + cres = compile_isolated(pyfunc, argtypes, + flags=looplift_flags) + self.assertFalse(cres.lifted) + expected = list(pyfunc(*args)) + got = list(cres.entry_point(*args)) + self.assertPreciseEqual(expected, got) + + def test_lift1(self): + self.check_lift_ok(lift1, (types.intp,), (123,)) + + def test_lift2(self): + self.check_lift_ok(lift2, (types.intp,), (123,)) + + def test_lift3(self): + self.check_lift_ok(lift3, (types.intp,), (123,)) + + def test_lift4(self): + self.check_lift_ok(lift4, (types.intp,), (123,)) + + def test_lift5(self): + self.check_lift_ok(lift5, (types.intp,), (123,)) + + def test_lift_issue2561(self): + self.check_lift_ok(lift_issue2561, (), ()) + + def test_lift_gen1(self): + self.check_lift_generator_ok(lift_gen1, (types.intp,), (123,)) + + def test_reject1(self): + self.check_no_lift(reject1, (types.intp,), (123,)) + + def test_reject_gen1(self): + self.check_no_lift_generator(reject_gen1, (types.intp,), (123,)) + + def test_reject_gen2(self): + self.check_no_lift_generator(reject_gen2, (types.intp,), (123,)) + + +class TestLoopLiftingAnnotate(TestCase): + def test_annotate_1(self): + """ + Verify that annotation works as expected with one lifted loop + """ + from numba import jit + + # dummy function to force objmode + def bar(): + pass + + def foo(x): + bar() # force obj + for i in range(x.size): + x[i] += 1 + + return x + + cfoo = jit(forceobj=True)(foo) + + x = np.arange(10) + xcopy = x.copy() + r = cfoo(x) + np.testing.assert_equal(r, xcopy + 1) + + buf = StringIO() + cfoo.inspect_types(file=buf) + annotation = buf.getvalue() + buf.close() + + self.assertIn("The function contains lifted loops", annotation) + line = foo.__code__.co_firstlineno + 2 # 2 lines down from func head + self.assertIn("Loop at line {line}".format(line=line), annotation) + self.assertIn("Has 1 overloads", annotation) + + def test_annotate_2(self): + """ + Verify that annotation works as expected with two lifted loops + """ + from numba import jit + + # dummy function to force objmode + def bar(): + pass + + def foo(x): + bar() # force obj + # first lifted loop + for i in range(x.size): + x[i] += 1 + # second lifted loop + for j in range(x.size): + x[j] *= 2 + return x + + cfoo = jit(forceobj=True)(foo) + + x = np.arange(10) + xcopy = x.copy() + r = cfoo(x) + np.testing.assert_equal(r, (xcopy + 1) * 2) + + buf = StringIO() + cfoo.inspect_types(file=buf) + annotation = buf.getvalue() + buf.close() + + self.assertIn("The function contains lifted loops", annotation) + line1 = foo.__code__.co_firstlineno + 3 # 3 lines down from func head + line2 = foo.__code__.co_firstlineno + 6 # 6 lines down from func head + self.assertIn("Loop at line {line}".format(line=line1), annotation) + self.assertIn("Loop at line {line}".format(line=line2), annotation) + + +class TestLoopLiftingInAction(MemoryLeakMixin, TestCase): + def assert_has_lifted(self, jitted, loopcount): + lifted = jitted.overloads[jitted.signatures[0]].lifted + self.assertEqual(len(lifted), loopcount) + + def test_issue_734(self): + from numba import jit, void, int32, double + + @jit(void(int32, double[:]), forceobj=True) + def forloop_with_if(u, a): + if u == 0: + for i in range(a.shape[0]): + a[i] = a[i] * 2.0 + else: + for i in range(a.shape[0]): + a[i] = a[i] + 1.0 + + for u in (0, 1): + nb_a = np.arange(10, dtype='int32') + np_a = np.arange(10, dtype='int32') + forloop_with_if(u, nb_a) + forloop_with_if.py_func(u, np_a) + self.assertPreciseEqual(nb_a, np_a) + + def test_issue_812(self): + from numba import jit + + @jit('f8[:](f8[:])', forceobj=True) + def test(x): + res = np.zeros(len(x)) + ind = 0 + for ii in range(len(x)): + ind += 1 + res[ind] = x[ind] + if x[ind] >= 10: + break + + # Invalid loopjitting will miss the usage of `ind` in the + # following loop. + for ii in range(ind + 1, len(x)): + res[ii] = 0 + return res + + x = np.array([1., 4, 2, -3, 5, 2, 10, 5, 2, 6]) + np.testing.assert_equal(test.py_func(x), test(x)) + + def test_issue_2368(self): + from numba import jit + + def lift_issue2368(a, b): + s = 0 + for e in a: + s += e + h = b.__hash__() + return s, h + + a = np.ones(10) + b = object() + jitted = jit(forceobj=True)(lift_issue2368) + + expected = lift_issue2368(a, b) + got = jitted(a, b) + + self.assertEqual(expected[0], got[0]) + self.assertEqual(expected[1], got[1]) + + jitloop = jitted.overloads[jitted.signatures[0]].lifted[0] + [loopcres] = jitloop.overloads.values() + # assert lifted function is native + self.assertTrue(loopcres.fndesc.native) + + def test_no_iteration_w_redef(self): + # redefinition of res in the loop with no use of res should not + # prevent lifting + from numba import jit + + @jit(forceobj=True) + def test(n): + res = 0 + for i in range(n): + res = i + return res + + # loop count = 1, loop lift but loop body not execute + self.assertEqual(test.py_func(-1), test(-1)) + self.assert_has_lifted(test, loopcount=1) + # loop count = 1, loop will lift and will execute + self.assertEqual(test.py_func(1), test(1)) + self.assert_has_lifted(test, loopcount=1) + + def test_no_iteration(self): + from numba import jit + + @jit(forceobj=True) + def test(n): + res = 0 + for i in range(n): + res += i + return res + + # loop count = 1 + self.assertEqual(test.py_func(-1), test(-1)) + self.assert_has_lifted(test, loopcount=1) + # loop count = 1 + self.assertEqual(test.py_func(1), test(1)) + self.assert_has_lifted(test, loopcount=1) + + def test_define_in_loop_body(self): + # tests a definition in a loop that leaves the loop is liftable + from numba import jit + + @jit(forceobj=True) + def test(n): + for i in range(n): + res = i + return res + + # loop count = 1 + self.assertEqual(test.py_func(1), test(1)) + self.assert_has_lifted(test, loopcount=1) + + def test_invalid_argument(self): + """Test a problem caused by invalid discovery of loop argument + when a variable is used afterwards but not before. + + Before the fix, this will result in:: + + numba.ir.NotDefinedError: 'i' is not defined + """ + from numba import jit + + @jit(forceobj=True) + def test(arg): + if type(arg) == np.ndarray: # force object mode + if arg.ndim == 1: + result = 0.0 + j = 0 + for i in range(arg.shape[0]): + pass + else: + raise Exception + else: + result = 0.0 + i, j = 0, 0 + return result + + arg = np.arange(10) + self.assertEqual(test.py_func(arg), test(arg)) + + def test_conditionally_defined_in_loop(self): + from numba import jit + @jit(forceobj=True) + def test(): + x = 5 + y = 0 + for i in range(2): + if i > 0: + x = 6 + y += x + return y, x + + self.assertEqual(test.py_func(), test()) + self.assert_has_lifted(test, loopcount=1) + + def test_stack_offset_error_when_has_no_return(self): + from numba import jit + import warnings + + def pyfunc(a): + if a: + for i in range(10): + pass + + with warnings.catch_warnings(): + warnings.simplefilter("error") + + cfunc = jit(forceobj=True)(pyfunc) + self.assertEqual(pyfunc(True), cfunc(True)) + + def test_variable_scope_bug(self): + """ + https://github.com/numba/numba/issues/2179 + + Looplifting transformation is using the wrong version of variable `h`. + """ + from numba import jit + + def bar(x): + return x + + def foo(x): + h = 0. + for k in range(x): + h = h + k + h = h - bar(x) + return h + + cfoo = jit(forceobj=True)(foo) + self.assertEqual(foo(10), cfoo(10)) + + def test_recompilation_loop(self): + """ + https://github.com/numba/numba/issues/2481 + """ + from numba import jit + + def foo(x, y): + # slicing to make array `x` into different layout + # to cause a new compilation of the lifted loop + A = x[::y] + c = 1 + for k in range(A.size): + object() # to force objectmode and looplifting + c = c * A[::-1][k] # the slice that is failing in static_getitem + return c + + cfoo = jit(forceobj=True)(foo) + # First run just works + args = np.arange(10), 1 + self.assertEqual(foo(*args), cfoo(*args)) + # Exactly 1 lifted loop so far + self.assertEqual(len(cfoo.overloads[cfoo.signatures[0]].lifted), 1) + lifted = cfoo.overloads[cfoo.signatures[0]].lifted[0] + # The lifted loop has 1 signature + self.assertEqual(len(lifted.signatures), 1) + # Use different argument to trigger a new compilation of the lifted loop + args = np.arange(10), -1 + self.assertEqual(foo(*args), cfoo(*args)) + # Ensure that is really a new overload for the lifted loop + self.assertEqual(len(lifted.signatures), 2) + + + def test_lift_objectmode_issue_4223(self): + from numba import jit + + @jit(forceobj=True) + def foo(a, b, c, d, x0, y0, n): + xs, ys = np.zeros(n), np.zeros(n) + xs[0], ys[0] = x0, y0 + for i in np.arange(n-1): + xs[i+1] = np.sin(a * ys[i]) + c * np.cos(a * xs[i]) + ys[i+1] = np.sin(b * xs[i]) + d * np.cos(b * ys[i]) + object() # ensure object mode + return xs, ys + + kwargs = dict(a=1.7, b=1.7, c=0.6, d=1.2, x0=0, y0=0, n=200) + got = foo(**kwargs) + expected = foo.py_func(**kwargs) + self.assertPreciseEqual(got[0], expected[0]) + self .assertPreciseEqual(got[1], expected[1]) + [lifted] = foo.overloads[foo.signatures[0]].lifted + self.assertEqual(len(lifted.nopython_signatures), 1) + + def test_lift_zip_and_enumerate(self): + # From issue https://github.com/numba/numba/issues/10076 + from numba import jit + + @jit(forceobj=True) + def udt_zip(X, Y): + i = 0 + for x, y in zip(X, Y): + i = i + x + return i + + + @jit(forceobj=True) + def udt_enumerate(X, Y): + i = 0 + for n, x in enumerate(X): + i = i + x + return i + + + @jit(forceobj=True) + def udt_enumerate_zip(X, Y): + i = 0 + for n, (x, y) in enumerate(zip(X, Y)): + i = i + x + return i + + X = np.ones(5) + Y = np.ones(5) + + self.assertEqual(udt_zip(X, Y), udt_zip.py_func(X, Y)) + self.assertEqual(udt_enumerate(X, Y), udt_enumerate.py_func(X, Y)) + self.assertEqual(udt_enumerate_zip(X, Y), + udt_enumerate_zip.py_func(X, Y)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mangling.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mangling.py new file mode 100644 index 0000000000000000000000000000000000000000..ad1ff95c8f4115cb53fa7cfc111d9dead2bb2bc3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mangling.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +""" +Test function name mangling. +The mangling affects the ABI of numba compiled binaries. +""" +from numba.core import types +from numba.core.funcdesc import default_mangler +from numba.tests.support import unittest, TestCase + + +class TestMangling(TestCase): + def test_one_args(self): + fname = 'foo' + argtypes = types.int32, + name = default_mangler(fname, argtypes) + self.assertEqual(name, '_Z3fooi') + + def test_two_args(self): + fname = 'foo' + argtypes = types.int32, types.float32 + name = default_mangler(fname, argtypes) + self.assertEqual(name, '_Z3fooif') + + def test_unicode_fname(self): + fname = u'foàČ ' + argtypes = types.int32, types.float32 + name = default_mangler(fname, argtypes) + self.assertIsInstance(name, str) + # manually encode it + unichar = fname[2] + enc = ''.join('_{:02x}'.format(c) + for c in unichar.encode('utf8')) + text = 'fo' + enc + expect = '_Z{}{}if'.format(len(text), text) + self.assertEqual(name, expect) + # ensure result chars are in the right charset + self.assertRegex(name, r'^_Z[a-zA-Z0-9_\$]+$') + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mathlib.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mathlib.py new file mode 100644 index 0000000000000000000000000000000000000000..81a6edd25b1abd2eabe330c6d810a7d2125b6877 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mathlib.py @@ -0,0 +1,571 @@ +import itertools +import math +import sys +import unittest +import warnings + +import numpy as np + +from numba import njit, types +from numba.tests.support import TestCase +from numba.np import numpy_support +from numba.core.utils import PYVERSION + + +def sin(x): + return math.sin(x) + + +def cos(x): + return math.cos(x) + + +def tan(x): + return math.tan(x) + + +def sinh(x): + return math.sinh(x) + + +def cosh(x): + return math.cosh(x) + + +def tanh(x): + return math.tanh(x) + + +def asin(x): + return math.asin(x) + + +def acos(x): + return math.acos(x) + + +def atan(x): + return math.atan(x) + + +def atan2(y, x): + return math.atan2(y, x) + + +def asinh(x): + return math.asinh(x) + + +def acosh(x): + return math.acosh(x) + + +def atanh(x): + return math.atanh(x) + + +def sqrt(x): + return math.sqrt(x) + + +def npy_sqrt(x): + return np.sqrt(x) + + +def exp(x): + return math.exp(x) + +def exp2(x): + return math.exp2(x) + +def expm1(x): + return math.expm1(x) + + +def log(x): + return math.log(x) + + +def log1p(x): + return math.log1p(x) + + +def log10(x): + return math.log10(x) + + +def log2(x): + return math.log2(x) + + +def floor(x): + return math.floor(x) + + +def ceil(x): + return math.ceil(x) + + +def trunc(x): + return math.trunc(x) + + +def isnan(x): + return math.isnan(x) + + +def isinf(x): + return math.isinf(x) + + +def isfinite(x): + return math.isfinite(x) + + +def hypot(x, y): + return math.hypot(x, y) + + +def nextafter(x, y): + return math.nextafter(x, y) + + +def degrees(x): + return math.degrees(x) + + +def radians(x): + return math.radians(x) + + +def erf(x): + return math.erf(x) + + +def erfc(x): + return math.erfc(x) + + +def gamma(x): + return math.gamma(x) + + +def lgamma(x): + return math.lgamma(x) + + +def pow(x, y): + return math.pow(x, y) + +def gcd(x, y): + return math.gcd(x, y) + +def copysign(x, y): + return math.copysign(x, y) + + +def frexp(x): + return math.frexp(x) + + +def ldexp(x, e): + return math.ldexp(x, e) + + +def get_constants(): + return math.pi, math.e + + +class TestMathLib(TestCase): + + def test_constants(self): + cfunc = njit(get_constants) + self.assertPreciseEqual(cfunc(), cfunc.py_func()) + + def run_unary(self, pyfunc, x_types, x_values, prec='exact', **kwargs): + cfunc = njit(pyfunc) + for tx, vx in zip(x_types, x_values): + got = cfunc(vx) + expected = pyfunc(vx) + actual_prec = 'single' if tx is types.float32 else prec + msg = 'for input %r' % (vx,) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg, + **kwargs) + + def run_binary(self, pyfunc, x_types, x_values, y_values, prec='exact'): + cfunc = njit(pyfunc) + for ty, x, y in zip(x_types, x_values, y_values): + got = cfunc(x, y) + expected = pyfunc(x, y) + actual_prec = 'single' if ty is types.float32 else prec + msg = 'for inputs (%r, %r)' % (x, y) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg) + + def check_predicate_func(self, pyfunc): + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float32, types.float32, + types.float64, types.float64, types.float64] + x_values = [0, 0, 0, 0, 0, 0, + float('inf'), 0.0, float('nan'), + float('inf'), 0.0, float('nan')] + self.run_unary(pyfunc, x_types, x_values) + + def test_sin(self): + pyfunc = sin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + @unittest.skipIf(sys.platform == 'win32', + "not exactly equal on win32 (issue #597)") + def test_cos(self): + pyfunc = cos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_tan(self): + pyfunc = tan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_sqrt(self): + pyfunc = sqrt + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_npy_sqrt(self): + pyfunc = npy_sqrt + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + # XXX poor precision for int16 inputs + x_types = [types.int16, types.uint16] + self.run_unary(pyfunc, x_types, x_values, prec='single') + x_types = [types.int32, types.int64, + types.uint32, types.uint64, + types.float32, types.float64] + self.run_unary(pyfunc, x_types, x_values) + + def test_exp(self): + pyfunc = exp + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + @unittest.skipUnless(PYVERSION >= (3, 11), "needs Python 3.11+") + def test_exp2(self): + pyfunc = exp2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_expm1(self): + pyfunc = expm1 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_log(self): + pyfunc = log + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log1p(self): + pyfunc = log1p + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log10(self): + pyfunc = log10 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log2(self): + pyfunc = log2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_asin(self): + pyfunc = asin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_acos(self): + pyfunc = acos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan(self): + pyfunc = atan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan2(self): + pyfunc = atan2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_asinh(self): + pyfunc = asinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_acosh(self): + pyfunc = acosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atanh(self): + pyfunc = atanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_sinh(self): + pyfunc = sinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_cosh(self): + pyfunc = cosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_tanh(self): + pyfunc = tanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_floor(self): + pyfunc = floor + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_ceil(self): + pyfunc = ceil + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_trunc(self): + pyfunc = trunc + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_isnan(self): + self.check_predicate_func(isnan) + + def test_isinf(self): + self.check_predicate_func(isinf) + + def test_isfinite(self): + self.check_predicate_func(isfinite) + + def test_hypot(self): + pyfunc = hypot + x_types = [types.int64, types.uint64, + types.float32, types.float64] + x_values = [1, 2, 3, 4, 5, 6, .21, .34] + y_values = [x + 2 for x in x_values] + # Issue #563: precision issues with math.hypot() under Windows. + prec = 'single' + self.run_binary(pyfunc, x_types, x_values, y_values, prec) + # Check that values that overflow in naive implementations do not + # in the numba impl + + def naive_hypot(x, y): + return math.sqrt(x * x + y * y) + + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + dt = numpy_support.as_dtype(fltty).type + val = dt(np.finfo(dt).max / 30.) + nb_ans = cfunc(val, val) + self.assertPreciseEqual(nb_ans, pyfunc(val, val), prec='single') + self.assertTrue(np.isfinite(nb_ans)) + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + self.assertRaisesRegex(RuntimeWarning, + 'overflow encountered in .*scalar', + naive_hypot, val, val) + + def test_nextafter(self): + pyfunc = nextafter + x_types = [types.float32, types.float64, + types.int32, types.int64, + types.uint32, types.uint64] + x_values = [0.0, .21, .34, 1005382.042, -25.328] + y1_values = [x + 2 for x in x_values] + y2_values = [x - 2 for x in x_values] + + self.run_binary(pyfunc, x_types, x_values, y1_values) + self.run_binary(pyfunc, x_types, x_values, y2_values) + + # Test using pos/neg inf + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [math.inf]*3) + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [-math.inf]*3) + + # if both args to nextafter are equal, then it is returned unchanged. + self.run_binary(pyfunc, x_types, x_values, x_values) + + def test_degrees(self): + pyfunc = degrees + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_radians(self): + pyfunc = radians + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_erf(self): + pyfunc = erf + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=2) + + def test_erfc(self): + pyfunc = erfc + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=4) + + def test_gamma(self): + pyfunc = gamma + x_values = [1., -0.9, -0.5, 0.5] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=3) + x_values = [-0.1, 0.1, 2.5, 10.1, 50., float('inf')] + x_types = [types.float64] * len(x_values) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=8) + + def test_lgamma(self): + pyfunc = lgamma + x_values = [1., -0.9, -0.1, 0.1, 200., 1e10, 1e30, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_pow(self): + pyfunc = pow + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_gcd(self): + from itertools import product, repeat, chain + pyfunc = gcd + signed_args = product( + sorted(types.signed_domain), *repeat((-2, -1, 0, 1, 2, 7, 10), 2) + ) + unsigned_args = product( + sorted(types.unsigned_domain), *repeat((0, 1, 2, 7, 9, 16), 2) + ) + x_types, x_values, y_values = zip(*chain(signed_args, unsigned_args)) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_copysign(self): + pyfunc = copysign + value_types = [types.float32, types.float64] + values = [-2, -1, -0.0, 0.0, 1, 2, float('-inf'), float('inf'), + float('nan')] + x_types, x_values, y_values = list(zip( + *itertools.product(value_types, values, values))) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_frexp(self): + pyfunc = frexp + x_types = [types.float32, types.float64] + x_values = [-2.5, -0.0, 0.0, 3.5, + float('-inf'), float('inf'), float('nan')] + self.run_unary(pyfunc, x_types, x_values, prec='exact') + + def test_ldexp(self): + pyfunc = ldexp + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + for args in [(2.5, -2), (2.5, 1), (0.0, 0), (0.0, 1), + (-0.0, 0), (-0.0, 1), + (float('inf'), 0), (float('-inf'), 0), + (float('nan'), 0)]: + msg = 'for input %r' % (args,) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_misc_coverage_support.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_misc_coverage_support.py new file mode 100644 index 0000000000000000000000000000000000000000..7dee5cdd5054dddbefffee8775fda191e46ab01b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_misc_coverage_support.py @@ -0,0 +1,75 @@ +import unittest +from unittest.mock import patch + +from numba.tests.support import TestCase + +from numba import njit +from numba.core import ir +from numba.misc.coverage_support import NotifyLocBase, _the_registry + + +class TestMiscCoverageSupport(TestCase): + @TestCase.run_test_in_subprocess(envvars={"NUMBA_JIT_COVERAGE": "1"}) + def test_custom_loc_notifier(self): + class MyNotify(NotifyLocBase): + records = [] + + def notify(self, loc): + self.records.append(("NOTIFY", loc)) + + def close(self): + self.records.append(("CLOSE", None)) + + # Patch to install registry for testing + new_the_registry = _the_registry + [MyNotify] + gv = "numba.misc.coverage_support._the_registry" + with patch(gv, new_the_registry): + + @njit + def foo(): + return 123 + + res = foo() + + self.assertEqual(res, 123) + + # offset by +2 because: + # +1 for the decorator + # +1 for the `def` line + first_offset = 2 + offset = foo.__code__.co_firstlineno + first_offset + loc = ir.Loc(__file__, 1) + self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records) + self.assertIn(("CLOSE", None), MyNotify.records) + + # Test dead branch pruned + with patch(gv, new_the_registry): + cond = False + + @njit + def foo(): + if cond: + return 321 + return 123 + + res = foo() + + self.assertEqual(res, 123) + + # `if cond` line is compiled + offset = foo.__code__.co_firstlineno + first_offset + self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records) + + # ` return 321` line is not compiled + self.assertNotIn( + ("NOTIFY", loc.with_lineno(offset + 1)), MyNotify.records + ) + + # ` return 123` line is compiled + self.assertIn(("NOTIFY", loc.with_lineno(offset + 2)), MyNotify.records) + + self.assertIn(("CLOSE", None), MyNotify.records) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_multi3.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_multi3.py new file mode 100644 index 0000000000000000000000000000000000000000..018637922ac9dfc54a3b76ce1212df183c724d75 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_multi3.py @@ -0,0 +1,43 @@ +import random + +import numpy as np + +from numba import njit +from numba.core import types +import unittest + +class TestMulti3(unittest.TestCase): + """ + This test is only relevant for 32-bit architectures. + + Test __multi3 implementation in _helperlib.c. + The symbol defines a i128 multiplication. + It is necessary for working around an issue in LLVM (see issue #969). + The symbol does not exist in 32-bit platform, and should not be used by + LLVM. However, optimization passes will create i65 multiplication that + is then lowered to __multi3. + """ + def test_multi3(self): + @njit("(int64,)") + def func(x): + res = 0 + for i in range(x): + res += i + return res + + x_cases = [-1, 0, 1, 3, 4, 8, + 0xffffffff - 1, 0xffffffff, 0xffffffff + 1, + 0x123456789abcdef, -0x123456789abcdef] + for _ in range(500): + x_cases.append(random.randint(0, 0xffffffff)) + + def expected(x): + if x <= 0: return 0 + return ((x * (x - 1)) // 2) & (2**64 - 1) + + for x in x_cases: + self.assertEqual(expected(x), func(x)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nested_calls.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nested_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebbaf35d885ea4f4324127d1f66a0db2ab2b990 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nested_calls.py @@ -0,0 +1,167 @@ +""" +Test problems in nested calls. +Usually due to invalid type conversion between function boundaries. +""" + + +from numba import int32, int64 +from numba import jit, njit +from numba.core import types +from numba.extending import overload +from numba.tests.support import TestCase, tag +import unittest + + +@jit(nopython=True) +def f_inner(a, b, c): + return a, b, c + +def f(x, y, z): + return f_inner(x, c=y, b=z) + +@jit(nopython=True) +def g_inner(a, b=2, c=3): + return a, b, c + +def g(x, y, z): + return g_inner(x, b=y), g_inner(a=z, c=x) + +@jit(nopython=True) +def star_inner(a=5, *b): + return a, b + +def star(x, y, z): + return star_inner(a=x), star_inner(x, y, z) + +def star_call(x, y, z): + return star_inner(x, *y), star_inner(*z) + +@jit(nopython=True) +def argcast_inner(a, b): + if b: + # Here `a` is unified to int64 (from int32 originally) + a = int64(0) + return a + +def argcast(a, b): + return argcast_inner(int32(a), b) + + +def generated_inner(x, y=5, z=6): + assert 0, "unreachable" + + +@overload(generated_inner) +def ol_generated_inner(x, y=5, z=6): + if isinstance(x, types.Complex): + def impl(x, y=5, z=6): + return x + y, z + else: + def impl(x, y=5, z=6): + return x - y, z + return impl + + +def call_generated(a, b): + return generated_inner(a, z=b) + + +def nested_annotated() -> int: + def inner(inner_arg: int) -> int: + return inner_arg + return 1 + + +class TestNestedCall(TestCase): + + def compile_func(self, pyfunc, objmode=False): + def check(*args, **kwargs): + expected = pyfunc(*args, **kwargs) + result = f(*args, **kwargs) + self.assertPreciseEqual(result, expected) + flags = dict(forceobj=True) if objmode else dict(nopython=True) + f = jit(**flags)(pyfunc) + return f, check + + def test_boolean_return(self): + @jit(nopython=True) + def inner(x): + return not x + + @jit(nopython=True) + def outer(x): + if inner(x): + return True + else: + return False + + self.assertFalse(outer(True)) + self.assertTrue(outer(False)) + + def test_named_args(self, objmode=False): + """ + Test a nested function call with named (keyword) arguments. + """ + cfunc, check = self.compile_func(f, objmode) + check(1, 2, 3) + check(1, y=2, z=3) + + def test_named_args_objmode(self): + self.test_named_args(objmode=True) + + def test_default_args(self, objmode=False): + """ + Test a nested function call using default argument values. + """ + cfunc, check = self.compile_func(g, objmode) + check(1, 2, 3) + check(1, y=2, z=3) + + def test_default_args_objmode(self): + self.test_default_args(objmode=True) + + def test_star_args(self): + """ + Test a nested function call to a function with *args in its signature. + """ + cfunc, check = self.compile_func(star) + check(1, 2, 3) + + def test_star_call(self, objmode=False): + """ + Test a function call with a *args. + """ + cfunc, check = self.compile_func(star_call, objmode) + check(1, (2,), (3,)) + + def test_star_call_objmode(self): + self.test_star_call(objmode=True) + + def test_argcast(self): + """ + Issue #1488: implicitly casting an argument variable should not + break nested calls. + """ + cfunc, check = self.compile_func(argcast) + check(1, 0) + check(1, 1) + + def test_call_generated(self): + """ + Test a nested function call to a generated jit function. + """ + cfunc = jit(nopython=True)(call_generated) + self.assertPreciseEqual(cfunc(1, 2), (-4, 2)) + self.assertPreciseEqual(cfunc(1j, 2), (1j + 5, 2)) + + def test_nested_annotated(self): + """ + Tested a nested function with annotations. + """ + cfunc = njit()(nested_annotated) + # should not fail + cfunc() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_np_functions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_np_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..285e871ae4e83dd047ce486a947e92fc65cc8ca3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_np_functions.py @@ -0,0 +1,7194 @@ +# Tests numpy methods of + +import itertools +import math +import platform +import warnings +from functools import partial +from itertools import product +from textwrap import dedent + +import numpy as np + +from numba import jit, njit, typeof +from numba.core import types +from numba.typed import List, Dict +from numba.np.numpy_support import numpy_version +from numba.core.errors import (TypingError, NumbaDeprecationWarning) +from numba.core.config import IS_32BITS +from numba.core.utils import pysignature +from numba.np.extensions import cross2d +from numba.tests.support import (TestCase, MemoryLeakMixin, + needs_blas, run_in_subprocess, + skip_if_numpy_2, IS_NUMPY_2, + IS_MACOS_ARM64, REDUCED_TESTING, + skip_if_reduced_testing) +import unittest + + +def sinc(x): + return np.sinc(x) + + +def angle1(x): + return np.angle(x) + + +def angle2(x, deg): + return np.angle(x, deg) + + +def array_equal(a, b): + return np.array_equal(a, b) + + +def intersect1d_2(a, b): + return np.intersect1d(a, b) + + +def intersect1d_3(a, b, assume_unique=False): + return np.intersect1d(a, b, assume_unique) + + +def append(arr, values, axis): + return np.append(arr, values, axis=axis) + + +def count_nonzero(arr, axis): + return np.count_nonzero(arr, axis=axis) + + +def delete(arr, obj): + return np.delete(arr, obj) + + +def diff1(a): + return np.diff(a) + + +def diff2(a, n): + return np.diff(a, n) + + +def bincount1(a): + return np.bincount(a) + + +def bincount2(a, w): + return np.bincount(a, weights=w) + + +def bincount3(a, w=None, minlength=0): + return np.bincount(a, w, minlength) + + +def searchsorted(a, v): + return np.searchsorted(a, v) + + +def searchsorted_left(a, v): + return np.searchsorted(a, v, side='left') + + +def searchsorted_right(a, v): + return np.searchsorted(a, v, side='right') + + +def digitize(*args): + return np.digitize(*args) + + +def histogram(*args): + return np.histogram(*args) + + +def machar(*args): + return np.MachAr() + + +def iscomplex(x): + return np.iscomplex(x) + + +def iscomplexobj(x): + return np.iscomplexobj(x) + + +def isscalar(x): + return np.isscalar(x) + + +def isreal(x): + return np.isreal(x) + + +def isrealobj(x): + return np.isrealobj(x) + + +def isneginf(x, out=None): + return np.isneginf(x, out) + + +def isposinf(x, out=None): + return np.isposinf(x, out) + + +def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + return np.isclose(a, b, rtol, atol, equal_nan) + + +def isnat(x): + return np.isnat(x) + + +def iinfo(*args): + return np.iinfo(*args) + + +def finfo(*args): + return np.finfo(*args) + + +def finfo_machar(*args): + return np.finfo(*args).machar + + +def fliplr(a): + return np.fliplr(a) + + +def flipud(a): + return np.flipud(a) + + +def flip(a): + return np.flip(a) + + +def logspace2(start, stop): + return np.logspace(start, stop) + + +def logspace3(start, stop, num=50): + return np.logspace(start, stop, num=num) + + +def geomspace2(start, stop): + return np.geomspace(start, stop) + + +def geomspace3(start, stop, num=50): + return np.geomspace(start, stop, num=num) + + +def rot90(a): + return np.rot90(a) + + +def rot90_k(a, k=1): + return np.rot90(a, k) + + +def array_split(a, indices, axis=0): + return np.array_split(a, indices, axis=axis) + + +def split(a, indices, axis=0): + return np.split(a, indices, axis=axis) + + +def vsplit(a, ind_or_sec): + return np.vsplit(a, ind_or_sec) + + +def hsplit(a, ind_or_sec): + return np.hsplit(a, ind_or_sec) + + +def dsplit(a, ind_or_sec): + return np.dsplit(a, ind_or_sec) + + +def correlate(a, v, mode="valid"): + return np.correlate(a, v, mode=mode) + + +def convolve(a, v, mode="full"): + return np.convolve(a, v, mode=mode) + + +def tri_n(N): + return np.tri(N) + + +def tri_n_m(N, M=None): + return np.tri(N, M) + + +def tri_n_k(N, k=0): + return np.tri(N, k) + + +def tri_n_m_k(N, M=None, k=0): + return np.tri(N, M, k) + + +def tril_m(m): + return np.tril(m) + + +def tril_m_k(m, k=0): + return np.tril(m, k) + + +def tril_indices_n(n): + return np.tril_indices(n) + + +def tril_indices_n_k(n, k=0): + return np.tril_indices(n, k) + + +def tril_indices_n_m(n, m=None): + return np.tril_indices(n, m=m) + + +def tril_indices_n_k_m(n, k=0, m=None): + return np.tril_indices(n, k, m) + + +def tril_indices_from_arr(arr): + return np.tril_indices_from(arr) + + +def tril_indices_from_arr_k(arr, k=0): + return np.tril_indices_from(arr, k) + + +def triu_m(m): + return np.triu(m) + + +def triu_m_k(m, k=0): + return np.triu(m, k) + + +def triu_indices_n(n): + return np.triu_indices(n) + + +def triu_indices_n_k(n, k=0): + return np.triu_indices(n, k) + + +def triu_indices_n_m(n, m=None): + return np.triu_indices(n, m=m) + + +def triu_indices_n_k_m(n, k=0, m=None): + return np.triu_indices(n, k, m) + + +def triu_indices_from_arr(arr): + return np.triu_indices_from(arr) + + +def triu_indices_from_arr_k(arr, k=0): + return np.triu_indices_from(arr, k) + + +def vander(x, N=None, increasing=False): + return np.vander(x, N, increasing) + + +def partition(a, kth): + return np.partition(a, kth) + + +def argpartition(a, kth): + return np.argpartition(a, kth) + + +def cov(m, y=None, rowvar=True, bias=False, ddof=None): + return np.cov(m, y, rowvar, bias, ddof) + + +def corrcoef(x, y=None, rowvar=True): + return np.corrcoef(x, y, rowvar) + + +def ediff1d(ary, to_end=None, to_begin=None): + return np.ediff1d(ary, to_end, to_begin) + + +def roll(a, shift): + return np.roll(a, shift) + + +def asarray(a): + return np.asarray(a) + + +def asarray_kws(a, dtype): + return np.asarray(a, dtype=dtype) + + +def asfarray(a, dtype=np.float64): + return np.asfarray(a, dtype=dtype) + + +def asfarray_default_kwarg(a): + return np.asfarray(a) + + +def extract(condition, arr): + return np.extract(condition, arr) + + +def np_trapz(y): + return np.trapz(y) + + +def np_trapz_x(y, x): + return np.trapz(y, x) + + +def np_trapz_dx(y, dx): + return np.trapz(y, dx=dx) + + +def np_trapz_x_dx(y, x, dx): + return np.trapz(y, x, dx) + + +def np_trapezoid(y): + return np.trapezoid(y) + + +def np_trapezoid_x(y, x): + return np.trapezoid(y, x) + + +def np_trapezoid_dx(y, dx): + return np.trapezoid(y, dx=dx) + + +def np_trapezoid_x_dx(y, x, dx): + return np.trapezoid(y, x, dx) + + +def np_allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + return np.allclose(a, b, rtol, atol, equal_nan) + + +def np_average(a, axis=None, weights=None): + return np.average(a, axis=axis, weights=weights) + + +def interp(x, xp, fp): + return np.interp(x, xp, fp) + + +def np_repeat(a, repeats): + return np.repeat(a, repeats) + + +def array_repeat(a, repeats): + return np.asarray(a).repeat(repeats) + + +def np_select(condlist, choicelist, default=0): + return np.select(condlist, choicelist, default=default) + + +def np_select_defaults(condlist, choicelist): + return np.select(condlist, choicelist) + + +def np_bartlett(M): + return np.bartlett(M) + + +def np_blackman(M): + return np.blackman(M) + + +def np_hamming(M): + return np.hamming(M) + + +def np_hanning(M): + return np.hanning(M) + + +def np_kaiser(M, beta): + return np.kaiser(M, beta) + + +def np_cross(a, b): + return np.cross(a, b) + + +def np_trim_zeros(a, trim='fb'): + return np.trim_zeros(a, trim) + + +def nb_cross2d(a, b): + return cross2d(a, b) + + +def flip_lr(a): + return np.fliplr(a) + + +def flip_ud(a): + return np.flipud(a) + + +def np_union1d(a, b): + return np.union1d(a,b) + + +def np_asarray_chkfinite(a, dtype=None): + return np.asarray_chkfinite(a, dtype) + + +def unwrap(p, discont=None, axis=-1, period=6.283185307179586): + return np.unwrap(p, discont, axis, period=period) + + +def unwrap1(p): + return np.unwrap(p) + + +def unwrap13(p, period): + return np.unwrap(p, period=period) + + +def unwrap123(p, period, discont): + return np.unwrap(p, period=period, discont=discont) + + +def array_contains(a, key): + return key in a + + +def swapaxes(a, a1, a2): + return np.swapaxes(a, a1, a2) + + +def moveaxis(a, source, destination): + return np.moveaxis(a, source, destination) + + +def nan_to_num(X, copy=True, nan=0.0, posinf=None, neginf=None): + return np.nan_to_num(X, copy=copy, nan=nan, posinf=posinf, neginf=neginf) + + +def np_indices(dimensions): + return np.indices(dimensions) + + +def diagflat1(v): + return np.diagflat(v) + + +def diagflat2(v, k=0): + return np.diagflat(v, k) + + +def np_setxor1d_2(a, b): + return np.setxor1d(a, b) + + +def np_setxor1d_3(a, b, assume_unique=False): + return np.setxor1d(a, b, assume_unique) + + +def np_setdiff1d_2(a, b): + return np.setdiff1d(a, b) + + +def np_setdiff1d_3(a, b, assume_unique=False): + return np.setdiff1d(a, b, assume_unique) + + +def np_in1d_2(a, b): + return np.in1d(a, b) + + +def np_in1d_3a(a, b, assume_unique=False): + return np.in1d(a, b, assume_unique=assume_unique) + + +def np_in1d_3b(a, b, invert=False): + return np.in1d(a, b, invert=invert) + + +def np_in1d_4(a, b, assume_unique=False, invert=False): + return np.in1d(a, b, assume_unique, invert) + + +def np_isin_2(a, b): + return np.isin(a, b) + + +def np_isin_3a(a, b, assume_unique=False): + return np.isin(a, b, assume_unique=assume_unique) + + +def np_isin_3b(a, b, invert=False): + return np.isin(a, b, invert=invert) + + +def np_isin_4(a, b, assume_unique=False, invert=False): + return np.isin(a, b, assume_unique, invert) + + +class TestNPFunctions(MemoryLeakMixin, TestCase): + """ + Tests for various Numpy functions. + """ + + def setUp(self): + super(TestNPFunctions, self).setUp() + self.rnd = np.random.RandomState(42) + + def run_unary(self, pyfunc, x_types, x_values, func_extra_types=None, + func_extra_args=None, ignore_sign_on_zero=False, abs_tol=None, + **kwargs): + """ + Runs tests for a unary function operating in the numerical real space. + + Parameters + ---------- + pyfunc : a python function definition holding that calls the numpy + functions to be tested. + x_types: the types of the values being tested, see numba.types + x_values: the numerical values of the values to be tested + func_extra_types: the types of additional arguments to the numpy + function + func_extra_args: additional arguments to the numpy function + ignore_sign_on_zero: boolean as to whether to allow zero values + with incorrect signs to be considered equal + prec: the required precision match, see assertPreciseEqual + + Notes: + ------ + x_types and x_values must have the same length + + """ + for tx, vx in zip(x_types, x_values): + if func_extra_args is None: + func_extra_types = func_extra_args = [()] + for xtypes, xargs in zip(func_extra_types, func_extra_args): + cfunc = njit((tx,) + xtypes,)(pyfunc) + got = cfunc(vx, *xargs) + expected = pyfunc(vx, *xargs) + try: + scalty = tx.dtype + except AttributeError: + scalty = tx + prec = ('single' + if scalty in (types.float32, types.complex64) + else 'double') + msg = 'for input %r with prec %r' % (vx, prec) + self.assertPreciseEqual(got, expected, + prec=prec, + msg=msg, + ignore_sign_on_zero=ignore_sign_on_zero, + abs_tol=abs_tol, **kwargs) + + def test_sinc(self): + """ + Tests the sinc() function. + This test is purely to assert numerical computations are correct. + """ + + # Ignore sign of zeros, this will need masking depending on numpy + # version once the fix to numpy complex division is in upstream + # See: https://github.com/numpy/numpy/pull/6699 + isoz = True + + # Testing sinc(1.) leads to sin(pi)/pi, which is below machine + # precision in practice on most machines. Small floating point + # differences in sin() etc. may lead to large differences in the result + # that are at a range that is inaccessible using standard width + # floating point representations. + # e.g. Assume float64 type. + # sin(pi) ~= 1e-16, but should be zero + # sin(pi)/pi ~= 1e-17, should be zero, error carried from above + # float64 has log10(2^53)~=15.9 digits of precision and the magnitude + # change in the alg is > 16 digits (1.0...0 -> 0.0...0), + # so comparison via ULP is invalid. + # We therefore opt to assume that values under machine precision are + # equal in this case. + tol = "eps" + + pyfunc = sinc + + def check(x_types, x_values, **kwargs): + self.run_unary(pyfunc, x_types, x_values, + ignore_sign_on_zero=isoz, abs_tol=tol, + **kwargs) + + # real domain scalar context + x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5, 5e-21, -5e-21] + real_types = ([types.float64] + if REDUCED_TESTING + else [types.float32, types.float64]) + x_types = real_types * (len(x_values) // len(real_types) + 1) + check(x_types, x_values) + + # real domain vector context + x_values = [np.array(x_values, dtype=np.float64)] + x_types = [typeof(v) for v in x_values] + check(x_types, x_values) + + # complex domain scalar context + x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 0+1j, 0-1j, 0.5+0.0j, # noqa + -0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j, # noqa + # the following are to test sin(x)/x for small x + 5e-21+0j, -5e-21+0j, 5e-21j, +(0-5e-21j) # noqa + ] + complex_types = ([types.complex128] + if REDUCED_TESTING + else [types.complex64, types.complex128]) + x_types = complex_types * (len(x_values) // len(complex_types) + 1) + check(x_types, x_values, ulps=2) + + # complex domain vector context + x_values = [np.array(x_values, dtype=np.complex128)] + x_types = [typeof(v) for v in x_values] + check(x_types, x_values, ulps=2) + + def test_sinc_exceptions(self): + pyfunc = sinc + cfunc = jit(nopython=True)(pyfunc) + + with self.assertRaises(TypingError) as raises: + cfunc('str') + self.assertIn('Argument "x" must be a Number or array-like', + str(raises.exception)) + # Exceptions leak references + self.disable_leak_check() + + def test_contains(self): + def arrs(): + a_0 = np.arange(10, 50) + k_0 = 20 + + yield a_0, k_0 + + a_1 = np.arange(6) + k_1 = 10 + + yield a_1, k_1 + + single_val_a = np.asarray([20]) + k_in = 20 + k_out = 13 + + yield single_val_a, k_in + yield single_val_a, k_out + + empty_arr = np.asarray([]) + yield empty_arr, k_out + + # np scalars + + bool_arr = np.array([True, False]) + yield bool_arr, True + yield bool_arr, k_0 + + np.random.seed(2) + float_arr = np.random.rand(10) + np.random.seed(2) + rand_k = np.random.rand() + present_k = float_arr[0] + + yield float_arr, rand_k + yield float_arr, present_k + + complx_arr = float_arr.view(np.complex128) + yield complx_arr, complx_arr[0] + yield complx_arr, rand_k + + np.random.seed(2) + uint_arr = np.random.randint(10, size=15, dtype=np.uint8) + yield uint_arr, 5 + yield uint_arr, 25 + + pyfunc = array_contains + + cfunc = jit(nopython=True)(pyfunc) + + for arr, key in arrs(): + expected = pyfunc(arr, key) + received = cfunc(arr, key) + + self.assertPreciseEqual(expected, received) + + def test_angle(self): + """ + Tests the angle() function. + This test is purely to assert numerical computations are correct. + """ + pyfunc1 = angle1 + pyfunc2 = angle2 + + def check(x_types, x_values): + # angle(x) + self.run_unary(pyfunc1, x_types, x_values) + # angle(x, deg) + xtra_values = [(True,), (False,)] + xtra_types = [(types.bool_,)] * len(xtra_values) + self.run_unary(pyfunc2, x_types, x_values, + func_extra_types=xtra_types, + func_extra_args=xtra_values,) + + # real domain scalar context + x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5] + real_types = ([types.float64] + if REDUCED_TESTING + else [types.float32, types.float64]) + x_types = real_types * (len(x_values) // len(real_types) + 1) + check(x_types, x_values) + + # real domain vector context + x_values = [np.array(x_values, dtype=np.float64)] + x_types = [typeof(v) for v in x_values] + check(x_types, x_values) + + # complex domain scalar context + x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 1j, -1j, 0.5+0.0j, # noqa + -0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j] # noqa + complex_types = ([types.complex128] + if REDUCED_TESTING + else [types.complex64, types.complex128]) + x_types = complex_types * (len(x_values) // len(complex_types) + 1) + check(x_types, x_values) + + # complex domain vector context + x_values = np.array(x_values) + x_types = ([types.complex128] + if REDUCED_TESTING + else [types.complex64, types.complex128]) + check(x_types, x_values) + + def test_angle_return_type(self): + # see issue #8949 + def numba_angle(x): + r = np.angle(x) + return r.dtype + + pyfunc = numba_angle + x_values = [1., -1., 1. + 0j, -5 - 5j] + x_types = ['f4', 'f8', 'c8', 'c16'] + for val, typ in zip(x_values, x_types): + x = np.array([val], dtype=typ) + cfunc = jit(nopython=True)(pyfunc) + expected = pyfunc(x) + got = cfunc(x) + self.assertEqual(expected, got) + + def test_angle_exceptions(self): + pyfunc = angle1 + cfunc = jit(nopython=True)(pyfunc) + + with self.assertRaises(TypingError) as raises: + cfunc('hello') + self.assertIn('Argument "z" must be a complex or Array[complex]', + str(raises.exception)) + # Exceptions leak references + self.disable_leak_check() + + def test_array_equal(self): + def arrays(): + yield np.array([]), np.array([]) + yield np.array([1, 2]), np.array([1, 2]) + yield np.array([]), np.array([1]) + x = np.arange(10).reshape(5, 2) + x[1][1] = 30 + yield np.arange(10).reshape(5, 2), x + yield x, x + yield (1, 2, 3), (1, 2, 3) + yield 2, 2 + yield 3, 2 + yield True, True + yield True, False + yield True, 2 + yield True, 1 + yield False, 0 + + pyfunc = array_equal + cfunc = jit(nopython=True)(pyfunc) + + for arr, obj in arrays(): + expected = pyfunc(arr, obj) + got = cfunc(arr, obj) + self.assertPreciseEqual(expected, got) + + def test_array_equal_exception(self): + pyfunc = array_equal + cfunc = jit(nopython=True)(pyfunc) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(3 * 4).reshape(3, 4), None) + self.assertIn( + 'Both arguments to "array_equals" must be array-like', + str(raises.exception) + ) + + def test_intersect1d_2(self): + + def arrays(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons no intersection + yield [1], [1] # singletons one intersection + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2], [2, 1] + yield [1, 2, 3], [1, 2, 3] + # from numpy: + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L17 # noqa: E501 + yield [5, 7, 1, 2], [2, 4, 3, 1, 5] + yield [5, 5, 7, 1, 2], [2, 1, 4, 3, 3, 1, 5] + + pyfunc = intersect1d_2 + cfunc = jit(nopython=True)(pyfunc) + + for a, b in arrays(): + # a = np.array(a) + # b = np.array(b) + if isinstance(a, list): + a = List(a) + if isinstance(b, list): + b = List(b) + expected = pyfunc(a, b) + got = cfunc(a, b) + self.assertPreciseEqual(expected, got) + + def test_intersect1d_3(self): + + def arrays(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons no intersection + yield [1], [1] # singletons one intersection + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2], [2, 1] + yield [1, 2, 3], [1, 2, 3] + # from numpy: + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L17 # noqa: E501 + yield [5, 7, 1, 2], [2, 4, 3, 1, 5] + yield [5, 5, 7, 1, 2], [2, 1, 4, 3, 3, 1, 5] + + pyfunc = intersect1d_3 + cfunc = jit(nopython=True)(pyfunc) + + for a, b in arrays(): + if isinstance(a, list): + a = List(a) + if isinstance(b, list): + b = List(b) + expected = pyfunc(a, b, assume_unique=False) + got = cfunc(a, b, assume_unique=False) + self.assertPreciseEqual(expected, got) + if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b): + expected = pyfunc(a, b, assume_unique=True) + got = cfunc(a, b, assume_unique=True) + self.assertPreciseEqual(expected, got) + + def test_intersect1d_errors(self): + np_pyfunc = intersect1d_3 + np_nbfunc = njit(np_pyfunc) + + a = np.array([1]) + b = np.array([2]) + self.disable_leak_check() + with self.assertRaises(TypingError): + np_nbfunc(a, b, "foo") + with self.assertRaises(TypingError): + np_nbfunc("foo", b, True) + with self.assertRaises(TypingError): + np_nbfunc(a, "foo", True) + + def test_count_nonzero(self): + + def arrays(): + yield np.array([]), None + yield np.zeros(10), None + yield np.arange(10), None + yield np.ones(10, dtype=np.bool_), 0 + yield np.arange(3 * 4 * 5).reshape(3, 4, 5), None + yield np.arange(3 * 4).reshape(3, 4), 0 + yield np.arange(3 * 4).reshape(3, 4), 1 + + pyfunc = count_nonzero + cfunc = jit(nopython=True)(pyfunc) + + for arr, axis in arrays(): + expected = pyfunc(arr, axis) + got = cfunc(arr, axis) + self.assertPreciseEqual(expected, got) + + def test_np_append(self): + def arrays(): + yield 2, 2, None + yield np.arange(10), 3, None + yield np.arange(10), np.arange(3), None + yield np.arange(10).reshape(5, 2), np.arange(3), None + yield np.array([[1, 2, 3], [4, 5, 6]]), np.array([[7, 8, 9]]), 0 + arr = np.array([[1, 2, 3], [4, 5, 6]]) + yield arr, arr, 1 + + pyfunc = append + cfunc = jit(nopython=True)(pyfunc) + + for arr, obj, axis in arrays(): + expected = pyfunc(arr, obj, axis) + got = cfunc(arr, obj, axis) + self.assertPreciseEqual(expected, got) + + def test_np_append_exceptions(self): + pyfunc = append + cfunc = jit(nopython=True)(pyfunc) + arr = np.array([[1, 2, 3], [4, 5, 6]]) + values = np.array([[7, 8, 9]]) + axis = 0 + + # first argument must be array-like + with self.assertRaises(TypingError) as raises: + cfunc(None, values, axis) + self.assertIn( + 'The first argument "arr" must be array-like', + str(raises.exception) + ) + + # second argument must also be array-like + with self.assertRaises(TypingError) as raises: + cfunc(arr, None, axis) + self.assertIn( + 'The second argument "values" must be array-like', + str(raises.exception) + ) + + # third argument must be either nonelike or an integer + with self.assertRaises(TypingError) as raises: + cfunc(arr, values, axis=0.0) + self.assertIn( + 'The third argument "axis" must be an integer', + str(raises.exception) + ) + # Exceptions leak references + self.disable_leak_check() + + def test_delete(self): + + def arrays(): + # array, obj + # + # an array-like type + yield [1, 2, 3, 4, 5], 3 + yield [1, 2, 3, 4, 5], [2, 3] + # 1d array, scalar + yield np.arange(10), 3 + yield np.arange(10), -3 # Negative obj + # 1d array, list + yield np.arange(10), [3, 5, 6] + yield np.arange(10), [2, 3, 4, 5] + # 3d array, scalar + yield np.arange(3 * 4 * 5).reshape(3, 4, 5), 2 + # 3d array, list + yield np.arange(3 * 4 * 5).reshape(3, 4, 5), [5, 30, 27, 8] + # slices + yield [1, 2, 3, 4], slice(1, 3, 1) + yield np.arange(10), slice(10) + + pyfunc = delete + cfunc = jit(nopython=True)(pyfunc) + + for arr, obj in arrays(): + expected = pyfunc(arr, obj) + got = cfunc(arr, obj) + self.assertPreciseEqual(expected, got) + + def test_delete_exceptions(self): + pyfunc = delete + cfunc = jit(nopython=True)(pyfunc) + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc([1, 2], 3.14) + self.assertIn( + 'obj should be of Integer dtype', + str(raises.exception) + ) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(10), [3.5, 5.6, 6.2]) + self.assertIn( + 'obj should be of Integer dtype', + str(raises.exception) + ) + + with self.assertRaises(TypingError) as raises: + cfunc(2, 3) + self.assertIn( + 'arr must be either an Array or a Sequence', + str(raises.exception) + ) + + with self.assertRaises(IndexError) as raises: + cfunc([1, 2], 3) + self.assertIn( + 'obj must be less than the len(arr)', + str(raises.exception), + ) + # Exceptions leak references + self.disable_leak_check() + + def diff_arrays(self): + """ + Some test arrays for np.diff() + """ + a = np.arange(12) ** 3 + yield a + b = a.reshape((3, 4)) + yield b + c = np.arange(24).reshape((3, 2, 4)) ** 3 + yield c + + def test_diff1(self): + pyfunc = diff1 + cfunc = jit(nopython=True)(pyfunc) + for arr in self.diff_arrays(): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertPreciseEqual(expected, got) + + # 0-dim array + a = np.array(42) + with self.assertTypingError(): + cfunc(a) + + def test_diff2(self): + pyfunc = diff2 + cfunc = jit(nopython=True)(pyfunc) + for arr in self.diff_arrays(): + size = arr.shape[-1] + for n in (0, 1, 2, 3, size - 1, size, size + 1, 421): + expected = pyfunc(arr, n) + got = cfunc(arr, n) + self.assertPreciseEqual(expected, got) + + def test_diff2_exceptions(self): + pyfunc = diff2 + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # 0-dim array + arr = np.array(42) + with self.assertTypingError(): + cfunc(arr, 1) + + # Invalid `n` + arr = np.arange(10) + for n in (-1, -2, -42): + with self.assertRaises(ValueError) as raises: + cfunc(arr, n) + self.assertIn("order must be non-negative", str(raises.exception)) + # Exceptions leak references + self.disable_leak_check() + + def test_isscalar(self): + def values(): + yield 3 + yield np.asarray([3]) + yield (3,) + yield 3j + yield 'numba' + yield int(10) + yield np.int16(12345) + yield 4.234 + yield True + yield None + yield np.timedelta64(10, 'Y') + yield np.datetime64('nat') + yield np.datetime64(1, 'Y') + + pyfunc = isscalar + cfunc = jit(nopython=True)(pyfunc) + for x in values(): + expected = pyfunc(x) + got = cfunc(x) + self.assertEqual(expected, got, x) + + def test_isobj_functions(self): + def values(): + yield 1 + yield 1 + 0j + yield np.asarray([3, 1 + 0j, True]) + yield "hello world" + + @jit(nopython=True) + def optional_fn(x, cond, cfunc): + y = x if cond else None + return cfunc(y) + + pyfuncs = [iscomplexobj, isrealobj] + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + for x in values(): + expected = pyfunc(x) + got = cfunc(x) + self.assertEqual(expected, got) + + # optional type + expected_optional = optional_fn.py_func(x, True, pyfunc) + got_optional = optional_fn(x, True, cfunc) + self.assertEqual(expected_optional, got_optional) + + # none type + expected_none = optional_fn.py_func(x, False, pyfunc) + got_none = optional_fn(x, False, cfunc) + self.assertEqual(expected_none, got_none) + + self.assertEqual(len(cfunc.signatures), 8) + + def test_is_real_or_complex(self): + def values(): + yield np.array([1 + 1j, 1 + 0j, 4.5, 3, 2, 2j]) + yield np.array([1, 2, 3]) + yield 3 + yield 12j + yield 1 + 4j + yield 10 + 0j + yield (1 + 4j, 2 + 0j) + yield np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + + pyfuncs = [iscomplex, isreal] + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + for x in values(): + expected = pyfunc(x) + got = cfunc(x) + self.assertPreciseEqual(expected, got) + + def test_isneg_or_ispos_inf(self): + def values(): + yield -np.inf, None + yield np.inf, None + yield np.inf, None + yield np.asarray([-np.inf, 0., np.inf]), None + yield -np.inf, np.zeros(1, dtype=np.bool_) + yield np.inf, np.zeros(1, dtype=np.bool_) + yield np.inf, np.zeros(1, dtype=np.bool_) + yield -np.inf, np.empty(12) + yield np.asarray([-np.inf, 0., np.inf]), np.zeros(3, dtype=np.bool_) + + pyfuncs = [isneginf, isposinf] + for pyfunc in pyfuncs: + cfunc = jit(nopython=True)(pyfunc) + for x, out in values(): + expected = pyfunc(x, out) + got = cfunc(x, out) + self.assertPreciseEqual(expected, got) + + def test_isclose(self): + rtol = 1e-5 + atol = 1e-8 + arr = np.array([100, 1000]) + aran = np.arange(8).reshape((2, 2, 2)) + kw = {'rtol': rtol, 'atol': atol} + + def values(): + yield 1e10, 1.00001e10, {} + yield 1e10, np.nan, {} + yield np.array([1e-8, 1e-7]), np.array([0.0, 0.0]), {} + yield np.array([1e10, 1e-7]), np.array([1.00001e10, 1e-8]), {} + yield np.array([1e10, 1e-8]), np.array([1.00001e10, 1e-9]), {} + yield np.array([1e10, 1e-8]), np.array([1.0001e10, 1e-9]), {} + yield np.array([1.0, np.nan]), np.array([1.0, np.nan]), {} + yield np.array([1.0, np.nan]), np.array([1.0, np.nan]), {'equal_nan': True} # noqa + yield np.array([np.nan, np.nan]), np.array([1.0, np.nan]), {'equal_nan': True} # noqa + yield np.array([1e-100, 1e-7]), np.array([0.0, 0.0]), {'atol': 0.0} + yield np.array([1e-10, 1e-10]), np.array([1e-20, 0.0]), {} + yield np.array([1e-10, 1e-10]), np.array([1e-20, 0.999999e-10]), {'atol': 0.0} # noqa + yield np.array([1, np.inf, 2]), np.array([3, np.inf, 4]), kw + yield np.array([atol, np.inf, -np.inf, np.nan]), np.array([0]), kw + yield np.array([atol, np.inf, -np.inf, np.nan]), 0, kw + yield 0, np.array([atol, np.inf, -np.inf, np.nan]), kw + + # tests taken from + # https://github.com/numpy/numpy/blob/aac965af6032b69d5cb515ad785cc9a331e816f4/numpy/core/tests/test_numeric.py#L2298-L2335 # noqa: E501 + + # all close tests + yield np.array([0, 1]), np.array([1, 0]), kw + yield arr, arr, kw + yield np.array([1]), np.array([1 + rtol + atol]), kw + yield arr, arr + arr * rtol, kw + yield arr, arr + arr * rtol + atol, kw + yield aran, aran + aran * rtol, kw + yield np.inf, np.inf, kw + yield -np.inf, np.inf, kw + yield np.inf, np.array([np.inf]), kw + yield np.array([np.inf, -np.inf]), np.array([np.inf, -np.inf]), kw + + # none close tests + yield np.array([np.inf, 0]), np.array([1, np.inf]), kw + yield np.array([np.inf, -np.inf]), np.array([1, 0]), kw + yield np.array([np.inf, np.inf]), np.array([1, -np.inf]), kw + yield np.array([np.inf, np.inf]), np.array([1, 0]), kw + yield np.array([np.nan, 0]), np.array([np.nan, -np.inf]), kw + yield np.array([atol * 2]), np.array([0]), kw + yield np.array([1]), np.array([1 + rtol + atol * 2]), kw + yield aran, aran + rtol * 1.1 * aran + atol * 1.1, kw + yield np.array(np.array([np.inf, 1])), np.array(np.array([0, np.inf])), kw # noqa + + # some close tests + yield np.array([np.inf, 0]), np.array([atol * 2, atol * 2]), kw + yield np.array([np.inf, 0]), np.array([np.inf, atol * 2]), kw + yield np.array([atol, 1, 1e6 * (1 + 2 * rtol) + atol]), np.array([0, np.nan, 1e6]), kw # noqa + yield np.arange(3), np.array([0, 1, 2.1]), kw + yield np.nan, np.array([np.nan, np.nan, np.nan]), kw + yield np.array([0]), np.array([atol, np.inf, -np.inf, np.nan]), kw + yield 0, np.array([atol, np.inf, -np.inf, np.nan]), kw + + pyfunc = isclose + cfunc = jit(nopython=True)(pyfunc) + for a, b, kwargs in values(): + expected = pyfunc(a, b, **kwargs) + got = cfunc(a, b, **kwargs) + if isinstance(expected, np.bool_): + self.assertEqual(expected, got) + else: + self.assertTrue(np.array_equal(expected, got)) + + def isclose_exception(self): + pyfunc = isclose + cfunc = jit(nopython=True)(pyfunc) + inps = [ + (np.asarray([1e10, 1e-9, np.nan]), + np.asarray([1.0001e10, 1e-9]), + 1e-05, 1e-08, False, + "shape mismatch: objects cannot be broadcast to a single shape", + ValueError), + ('hello', 3, False, 1e-08, False, + 'The first argument "a" must be array-like', + TypingError), + (3, 'hello', False, 1e-08, False, + 'The second argument "b" must be array-like', + TypingError), + (2, 3, False, 1e-08, False, + 'The third argument "rtol" must be a floating point', + TypingError), + (2, 3, 1e-05, False, False, + 'The fourth argument "atol" must be a floating point', + TypingError), + (2, 3, 1e-05, 1e-08, 1, + 'The fifth argument "equal_nan" must be a boolean', + TypingError), + ] + + for a, b, rtol, atol, equal_nan, exc_msg, exc in inps: + with self.assertRaisesRegex(exc, exc_msg): + cfunc(a, b, rtol, atol, equal_nan) + + def bincount_sequences(self): + """ + Some test sequences for np.bincount() + """ + a = [1, 2, 5, 2, 3, 20] + b = np.array([5, 8, 42, 5]) + c = self.rnd.randint(0, 100, size=300).astype(np.int8) + return (a, b, c) + + def test_bincount1(self): + pyfunc = bincount1 + cfunc = jit(nopython=True)(pyfunc) + for seq in self.bincount_sequences(): + expected = pyfunc(seq) + got = cfunc(seq) + self.assertPreciseEqual(expected, got) + + def test_bincount1_exceptions(self): + pyfunc = bincount1 + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # Negative input + with self.assertRaises(ValueError) as raises: + cfunc([2, -1]) + self.assertIn("first argument must be non-negative", + str(raises.exception)) + # Exceptions leak references + self.disable_leak_check() + + def test_bincount2(self): + pyfunc = bincount2 + cfunc = jit(nopython=True)(pyfunc) + for seq in self.bincount_sequences(): + w = [math.sqrt(x) - 2 for x in seq] + # weights as list, then array, mixed types, check upcast is ok + for weights in (w, np.array(w), seq, np.array(seq)): + expected = pyfunc(seq, weights) + got = cfunc(seq, weights) + self.assertPreciseEqual(expected, got) + + def test_bincount2_exceptions(self): + pyfunc = bincount2 + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # Negative input + with self.assertRaises(ValueError) as raises: + cfunc([2, -1], [0, 0]) + self.assertIn("first argument must be non-negative", + str(raises.exception)) + + # Mismatching input sizes + with self.assertRaises(ValueError) as raises: + cfunc([2, -1], [0]) + self.assertIn("weights and list don't have the same length", + str(raises.exception)) + + def test_bincount3(self): + pyfunc = bincount3 + cfunc = jit(nopython=True)(pyfunc) + for seq in self.bincount_sequences(): + a_max = max(seq) + # Length should be a_max in the first case, minlength in the second + for minlength in (a_max, a_max + 2): + expected = pyfunc(seq, None, minlength) + got = cfunc(seq, None, minlength) + self.assertEqual(len(expected), len(got)) + self.assertPreciseEqual(expected, got) + + def test_bincount3_exceptions(self): + pyfunc = bincount3 + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # Negative input + with self.assertRaises(ValueError) as raises: + cfunc([2, -1], [0, 0]) + self.assertIn("first argument must be non-negative", + str(raises.exception)) + + # Negative minlength + with self.assertRaises(ValueError) as raises: + cfunc([17, 38], None, -1) + self.assertIn("'minlength' must not be negative", + str(raises.exception)) + + def test_searchsorted(self): + pyfunc = searchsorted + cfunc = jit(nopython=True)(pyfunc) + + pyfunc_left = searchsorted_left + cfunc_left = jit(nopython=True)(pyfunc_left) + + pyfunc_right = searchsorted_right + cfunc_right = jit(nopython=True)(pyfunc_right) + + def check(a, v): + expected = pyfunc(a, v) + got = cfunc(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_left(a, v) + got = cfunc_left(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_right(a, v) + got = cfunc_right(a, v) + self.assertPreciseEqual(expected, got) + + if REDUCED_TESTING: + # Minimal essential testing for reduced mode + bins = np.array([0, 1, 4]) # Simple sorted array + values = np.array([0, 2, 5]) # Simple test values + + # Test basic functionality only + check(bins, values[0]) # scalar + check(bins, values) # array + check(list(bins), values) # list input + return + + # First with integer values (no NaNs) + bins = np.arange(5) ** 2 + values = np.arange(20) - 1 + + for a in (bins, list(bins)): + # Scalar values + for v in values: + check(a, v) + # Array values + for v in (values, values.reshape((4, 5))): + check(a, v) + # Sequence values + check(a, list(values)) + + # Second with float values (including NaNs) + bins = np.float64(list(bins) + [float('nan')] * 7) / 2.0 + values = np.arange(20) - 0.5 + + for a in (bins, list(bins)): + # Scalar values + for v in values: + check(a, v) + # Array values + for v in (values, values.reshape((4, 5))): + check(a, v) + # Sequence values + check(a, list(values)) + + # nonsense value for 'side' raises TypingError + def bad_side(a, v): + return np.searchsorted(a, v, side='nonsense') + cfunc = jit(nopython=True)(bad_side) + with self.assertTypingError(): + cfunc([1,2], 1) + + # non-constant value for 'side' raises TypingError + def nonconst_side(a, v, side='left'): + return np.searchsorted(a, v, side=side) + cfunc = jit(nopython=True)(nonconst_side) + with self.assertTypingError(): + cfunc([1,2], 1, side='right') + + # Test unordered values + a = np.array([1, 2, 0]) + v = np.array( + [ + [5, 4], + [6, 7], + [2, 1], + [0, 3], + ] + ) + check(a, v) + + a = np.array([9, 1, 4, 2, 0, 3, 7, 6, 8]) + v = np.array( + [ + [5, 10], + [10, 5], + [-1, 5], + ] + ) + check(a, v) + + def test_searchsorted_supplemental(self): + pyfunc = searchsorted + cfunc = jit(nopython=True)(pyfunc) + + pyfunc_left = searchsorted_left + cfunc_left = jit(nopython=True)(pyfunc_left) + + pyfunc_right = searchsorted_right + cfunc_right = jit(nopython=True)(pyfunc_right) + + def check(a, v): + expected = pyfunc(a, v) + got = cfunc(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_left(a, v) + got = cfunc_left(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_right(a, v) + got = cfunc_right(a, v) + self.assertPreciseEqual(expected, got) + + if REDUCED_TESTING: + # Essential tests only - minimal cases + a = np.array([1, 3, 5]) + v = np.array([0, 2, 4, 6]) + check(a, v) + check(np.sort(a), v) + return + + element_pool = list(range(-5, 50)) + element_pool += [np.nan] * 5 + [np.inf] * 3 + [-np.inf] * 3 + + for i in range(1000): + sample_size = self.rnd.choice([5, 10, 25]) + + # `a` and `v` not sorted; either may have repeating values + a = self.rnd.choice(element_pool, sample_size) + v = self.rnd.choice(element_pool, sample_size + (i % 3 - 1)) + + # output should match numpy regardless of whether `a` is sorted + check(a, v) + check(np.sort(a), v) + + ones = np.ones(5) + nans = np.full(len(ones), fill_value=np.nan) + check(ones, ones) + + # `a` and / or `v` full of nans + check(ones, nans) + check(nans, ones) + check(nans, nans) + + # `a` and `v` are float32 + a = np.array([9, np.nan], dtype=np.float32) + v = np.array([np.nan], dtype=np.float32) + check(a, v) + + # `v` is zero size + a = np.arange(1) + v = np.arange(0) + check(a, v) + + # `a` and `v` booleans + a = np.array([False, False, True, True]) + v = np.array([False, True]) + check(a, v) + + # `v` is a (scalar) boolean + a = [1, 2, 3] + v = True + check(a, v) + + # `a` and `v` arrays of strings + a = np.array(['1', '2', '3']) + v = np.array(['2', '4']) + check(a, v) + + def test_searchsorted_complex(self): + pyfunc = searchsorted + cfunc = jit(nopython=True)(pyfunc) + + pyfunc_left = searchsorted_left + cfunc_left = jit(nopython=True)(pyfunc_left) + + pyfunc_right = searchsorted_right + cfunc_right = jit(nopython=True)(pyfunc_right) + + def check(a, v): + expected = pyfunc(a, v) + got = cfunc(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_left(a, v) + got = cfunc_left(a, v) + self.assertPreciseEqual(expected, got) + + expected = pyfunc_right(a, v) + got = cfunc_right(a, v) + self.assertPreciseEqual(expected, got) + + if REDUCED_TESTING: + # Essential complex number test only + a = np.array([1 + 0j, 2 + 1j, 3 + 0j]) + v = np.array([1 + 1j, 2 + 0j]) + check(a, v) + check(np.sort(a), v) + return + + pool = [0, 1, np.nan] + element_pool = [complex(*c) for c in itertools.product(pool, pool)] + + for i in range(100): + sample_size = self.rnd.choice([3, 5, len(element_pool)]) + + # `a` and `v` not sorted; either may have repeating values + a = self.rnd.choice(element_pool, sample_size) + v = self.rnd.choice(element_pool, sample_size + (i % 3 - 1)) + + # output should match numpy regardless of whether `a` is sorted + check(a, v) + check(np.sort(a), v) + + # check type promotion (a complex; v not so much) + check(a=np.array(element_pool), v=np.arange(2)) + + def test_digitize(self): + pyfunc = digitize + cfunc = jit(nopython=True)(pyfunc) + + def check(*args): + expected = pyfunc(*args) + got = cfunc(*args) + self.assertPreciseEqual(expected, got) + + values = np.float64((0, 0.99, 1, 4.4, 4.5, 7, 8, 9, 9.5, + float('inf'), float('-inf'), float('nan'))) + assert len(values) == 12 + self.rnd.shuffle(values) + + bins1 = np.float64([1, 3, 4.5, 8]) + bins2 = np.float64([1, 3, 4.5, 8, float('inf'), float('-inf')]) + bins3 = np.float64([1, 3, 4.5, 8, float('inf'), float('-inf')] + + [float('nan')] * 10) + + all_bins = [bins1, bins2, bins3] + xs = [values, values.reshape((3, 4))] + + # 2-ary digitize() + for bins in all_bins: + bins.sort() + for x in xs: + check(x, bins) + check(x, bins[::-1]) + + # 3-ary digitize() + for bins in all_bins: + for right in (True, False): + check(values, bins, right) + check(values, bins[::-1], right) + + # Sequence input + check(list(values), bins1) + + # per https://github.com/numba/numba/issues/8768 + check(np.array([np.nan, 1]), np.array([1.5, np.nan])) + + def test_digitize_non_monotonic_bins(self): + # Exceptions leak references + self.disable_leak_check() + + pyfunc = digitize + cfunc = jit(nopython=True)(pyfunc) + + def check_error(*args): + for fn in (pyfunc, cfunc): + with self.assertRaises(ValueError) as raises: + fn(*args) + + msg = 'bins must be monotonically increasing or decreasing' + self.assertIn(msg, str(raises.exception)) + + x = np.array([np.nan, 1]) + bins = np.array([np.nan, 1.5, 2.3, np.nan]) + check_error(x, bins) + + x = [-1, 0, 1, 2] + bins = [0, 0, 1, 0] + check_error(x, bins) + + bins = [1, 1, 0, 1] + check_error(x, bins) + + def test_digitize_supplemental(self): + # inspired by the tests in + # https://github.com/numpy/numpy/blob/a277f62/numpy/lib/tests/test_function_base.py + + pyfunc = digitize + cfunc = jit(nopython=True)(pyfunc) + + def check(*args): + expected = pyfunc(*args) + got = cfunc(*args) + self.assertPreciseEqual(expected, got) + + # forward + x = np.arange(-6, 5) + bins = np.arange(-5, 5) + check(x, bins) + + # reverse + x = np.arange(5, -6, -1) + bins = np.arange(5, -5, -1) + check(x, bins) + + # random + x = self.rnd.rand(10) + bins = np.linspace(x.min(), x.max(), 10) + check(x, bins) + + # right_basic + x = [1, 5, 4, 10, 8, 11, 0] + bins = [1, 5, 10] + check(x, bins) + + # right_open + x = np.arange(-6, 5) + bins = np.arange(-6, 4) + check(x, bins, True) + + # right_open_reverse + x = np.arange(5, -6, -1) + bins = np.arange(4, -6, -1) + check(x, bins, True) + + # right_open_random + x = self.rnd.rand(10) + bins = np.linspace(x.min(), x.max(), 10) + check(x, bins, True) + + # monotonic + x = [-1, 0, 1, 2] + bins = [0, 0, 1] + check(x, bins) + + bins = [1, 1, 0] + check(x, bins) + + bins = [1, 1, 1, 1] + check(x, bins) + + # large_integers_increasing + x = 2 ** 54 # loses precision in a float + check([x], [x - 1, x + 1]) + + def test_digitize_raise_if_x_complex(self): + # Exceptions leak references + self.disable_leak_check() + + pyfunc = digitize + cfunc = jit(nopython=True)(pyfunc) + + x = np.array([1 + 1j]) + y = np.array([1., 3., 4.5, 8.]) + msg = 'x may not be complex' + + for func in pyfunc, cfunc: + with self.assertTypingError() as raises: + func(x, y) + self.assertIn(msg, str(raises.exception)) + + def test_histogram(self): + pyfunc = histogram + cfunc = jit(nopython=True)(pyfunc) + + def check(*args): + pyhist, pybins = pyfunc(*args) + chist, cbins = cfunc(*args) + self.assertPreciseEqual(pyhist, chist) + # There can be a slight discrepancy in the linspace() result + # when `bins` is an integer... + self.assertPreciseEqual(pybins, cbins, prec='double', ulps=2) + + def check_values(values): + # Explicit bins array + # (note Numpy seems to not support NaN bins) + bins = np.float64([1, 3, 4.5, 8]) + check(values, bins) + check(values.reshape((3, 4)), bins) + + # Explicit number of bins + check(values, 7) + + # Explicit number of bins and bins range + check(values, 7, (1.0, 13.5)) + + # Implicit bins=10 + check(values) + + values = np.float64((0, 0.99, 1, 4.4, 4.5, 7, 8, + 9, 9.5, 42.5, -1.0, -0.0)) + assert len(values) == 12 + self.rnd.shuffle(values) + + check_values(values) + + def _test_correlate_convolve(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + # only 1d arrays are accepted, test varying lengths + # and varying dtype + + def check(lengths, dts, modes): + for dt1, dt2, n, m, mode in itertools.product( + dts, dts, lengths, lengths, modes + ): + a = np.arange(n, dtype=dt1) + v = np.arange(m, dtype=dt2) + + if np.issubdtype(dt1, np.complexfloating): + a = (a + 1j * a).astype(dt1) + if np.issubdtype(dt2, np.complexfloating): + v = (v + 1j * v).astype(dt2) + + expected = pyfunc(a, v, mode=mode) + got = cfunc(a, v, mode=mode) + + self.assertPreciseEqual(expected, got) + + if REDUCED_TESTING: + lengths = (1, 2) + dts = [np.float64, np.complex128] + modes = ["full", "valid"] + check(lengths, dts, modes) + return + + lengths = (1, 2, 3, 7) + dts = [np.int8, np.int32, np.int64, np.float32, np.float64, + np.complex64, np.complex128] + modes = ["full", "valid", "same"] + + check(lengths, dts, modes) + + _a = np.arange(12).reshape(4, 3) + _b = np.arange(12) + for x, y in [(_a, _b), (_b, _a)]: + with self.assertRaises(TypingError) as raises: + cfunc(x, y) + msg = 'only supported on 1D arrays' + self.assertIn(msg, str(raises.exception)) + + def test_correlate(self): + self._test_correlate_convolve(correlate) + + def _test_correlate_convolve_exceptions(self, fn): + # Exceptions leak references + self.disable_leak_check() + + # convolve raises if either array has a 0 dimension + _a = np.ones(shape=(0,)) + _b = np.arange(5) + cfunc = jit(nopython=True)(fn) + for x, y in [(_a, _b), (_b, _a)]: + with self.assertRaises(ValueError) as raises: + cfunc(x, y) + if len(x) == 0: + self.assertIn("'a' cannot be empty", str(raises.exception)) + else: + self.assertIn("'v' cannot be empty", str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(_b, _b, mode="invalid mode") + + self.assertIn("Invalid 'mode'", str(raises.exception)) + + def test_correlate_exceptions(self): + # correlate supported 0 dimension arrays until 1.18 + self._test_correlate_convolve_exceptions(correlate) + + def test_convolve(self): + self._test_correlate_convolve(convolve) + + def test_convolve_exceptions(self): + self._test_correlate_convolve_exceptions(convolve) + + def _check_output(self, pyfunc, cfunc, params, abs_tol=None): + expected = pyfunc(**params) + got = cfunc(**params) + self.assertPreciseEqual(expected, got, abs_tol=abs_tol) + + def test_vander_basic(self): + pyfunc = vander + cfunc = jit(nopython=True)(pyfunc) + _check_output = partial(self._check_output, pyfunc, cfunc) + + def _check(x): + if REDUCED_TESTING: + n_choices = [None, 1, 2] + increasing_choices = [False] + else: + n_choices = [None, 0, 1, 2, 3, 4] + increasing_choices = [True, False] + + # N and increasing defaulted + params = {'x': x} + _check_output(params) + + # N provided and increasing defaulted + for n in n_choices: + params = {'x': x, 'N': n} + _check_output(params) + + if not REDUCED_TESTING: + # increasing provided and N defaulted: + for increasing in increasing_choices: + params = {'x': x, 'increasing': increasing} + _check_output(params) + + # both n and increasing supplied + for n in n_choices: + for increasing in increasing_choices: + params = {'x': x, 'N': n, 'increasing': increasing} + _check_output(params) + + if REDUCED_TESTING: + # Minimal test cases for memory optimization + _check(np.array([1, 2, 3])) + _check(np.array([])) + _check([0, 1, 2]) + return + + _check(np.array([1, 2, 3, 5])) + _check(np.arange(7) - 10.5) + _check(np.linspace(3, 10, 5)) + _check(np.array([1.2, np.nan, np.inf, -np.inf])) + _check(np.array([])) + _check(np.arange(-5, 5) - 0.3) + + # # boolean array + _check(np.array([True] * 5 + [False] * 4)) + + # cycle through dtypes to check type promotion a la numpy + for dtype in np.int32, np.int64, np.float32, np.float64: + _check(np.arange(10, dtype=dtype)) + + # non array inputs + _check([0, 1, 2, 3]) + _check((4, 5, 6, 7)) + _check((0.0, 1.0, 2.0)) + _check(()) + + # edge cases + _check((3, 4.444, 3.142)) + _check((True, False, 4)) + + def test_vander_exceptions(self): + pyfunc = vander + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + x = np.arange(5) - 0.5 + + def _check_n(N): + with self.assertTypingError() as raises: + cfunc(x, N=N) + self.assertIn("Second argument N must be None or an integer", + str(raises.exception)) + + for N in 1.1, True, np.inf, [1, 2]: + _check_n(N) + + with self.assertRaises(ValueError) as raises: + cfunc(x, N=-1) + self.assertIn("Negative dimensions are not allowed", + str(raises.exception)) + + def _check_1d(x): + with self.assertRaises(ValueError) as raises: + cfunc(x) + self.assertEqual("x must be a one-dimensional array or sequence.", + str(raises.exception)) + + x = np.arange(27).reshape((3, 3, 3)) + _check_1d(x) + + x = ((2, 3), (4, 5)) + _check_1d(x) + + def test_tri_n_basic(self): + pyfunc = tri_n + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + def n_variations(): + return np.arange(-4, 8) # number of rows + + # N supplied, M and k defaulted + for n in n_variations(): + params = {'N': n} + _check(params) + + def test_tri_n_m_basic(self): + pyfunc = tri_n_m + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + def n_variations(): + return np.arange(-4, 8) # number of rows + + def m_variations(): + # number of columns + return itertools.chain.from_iterable(([None], range(-5, 9))) + + # N supplied, M and k defaulted + for n in n_variations(): + params = {'N': n} + _check(params) + + # N and M supplied, k defaulted + for n in n_variations(): + for m in m_variations(): + params = {'N': n, 'M': m} + _check(params) + + def test_tri_n_k_basic(self): + pyfunc = tri_n_k + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + def n_variations(): + return np.arange(-4, 8) # number of rows + + def k_variations(): + return np.arange(-10, 10) # offset + + # N supplied, M and k defaulted + for n in n_variations(): + params = {'N': n} + _check(params) + + # N and k supplied, M defaulted + for n in n_variations(): + for k in k_variations(): + params = {'N': n, 'k': k} + _check(params) + + def test_tri_n_m_k_basic(self): + pyfunc = tri_n_m_k + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + def n_variations(): + return np.arange(-4, 8) # number of rows + + def m_variations(): + # number of columns + return itertools.chain.from_iterable(([None], range(-5, 9))) + + def k_variations(): + return np.arange(-10, 10) # offset + + # N supplied, M and k defaulted + for n in n_variations(): + params = {'N': n} + _check(params) + + # N and M supplied, k defaulted + for n in n_variations(): + for m in m_variations(): + params = {'N': n, 'M': m} + _check(params) + + # N and k supplied, M defaulted + for n in n_variations(): + for k in k_variations(): + params = {'N': n, 'k': k} + _check(params) + + # N, M and k supplied + for n in n_variations(): + for k in k_variations(): + for m in m_variations(): + params = {'N': n, 'M': m, 'k': k} + _check(params) + + def test_tri_exceptions(self): + pyfunc = tri_n_m_k + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(k): + with self.assertTypingError() as raises: + cfunc(5, 6, k=k) + assert "k must be an integer" in str(raises.exception) + + for k in 1.5, True, np.inf, [1, 2]: + _check(k) + + def _triangular_matrix_tests_m(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + def _check(arr): + expected = pyfunc(arr) + got = cfunc(arr) + # TODO: Contiguity of result not consistent with numpy + self.assertEqual(got.dtype, expected.dtype) + np.testing.assert_array_equal(got, expected) + + return self._triangular_matrix_tests_inner(self, pyfunc, _check) + + def _triangular_matrix_tests_m_k(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + def _check(arr): + for k in itertools.chain.from_iterable(([None], range(-10, 10))): + if k is None: + params = {} + else: + params = {'k': k} + expected = pyfunc(arr, **params) + got = cfunc(arr, **params) + # TODO: Contiguity of result not consistent with numpy + self.assertEqual(got.dtype, expected.dtype) + np.testing.assert_array_equal(got, expected) + + return self._triangular_matrix_tests_inner(self, pyfunc, _check) + + @staticmethod + def _triangular_matrix_tests_inner(self, pyfunc, _check): + + def check_odd(a): + _check(a) + a = a.reshape((9, 7)) + _check(a) + a = a.reshape((7, 1, 3, 3)) + _check(a) + _check(a.T) + + def check_even(a): + _check(a) + a = a.reshape((4, 16)) + _check(a) + a = a.reshape((4, 2, 2, 4)) + _check(a) + _check(a.T) + + check_odd(np.arange(63) + 10.5) + check_even(np.arange(64) - 10.5) + + # edge cases + _check(np.arange(360).reshape(3, 4, 5, 6)) + _check(np.array([])) + _check(np.arange(9).reshape((3, 3))[::-1]) + _check(np.arange(9).reshape((3, 3), order='F')) + + arr = (np.arange(64) - 10.5).reshape((4, 2, 2, 4)) + _check(arr) + _check(np.asfortranarray(arr)) + + def _triangular_matrix_exceptions(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + a = np.ones((5, 6)) + with self.assertTypingError() as raises: + cfunc(a, k=1.5) + self.assertIn("k must be an integer", str(raises.exception)) + + def _triangular_indices_tests_base(self, pyfunc, args): + cfunc = jit(nopython=True)(pyfunc) + + for x in args: + expected = pyfunc(*x) + got = cfunc(*x) + self.assertEqual(type(expected), type(got)) + self.assertEqual(len(expected), len(got)) + for e, g in zip(expected, got): + np.testing.assert_array_equal(e, g) + + def _triangular_indices_tests_n(self, pyfunc): + self._triangular_indices_tests_base( + pyfunc, + [[n] for n in range(10)] + ) + + def _triangular_indices_tests_n_k(self, pyfunc): + self._triangular_indices_tests_base( + pyfunc, + [[n, k] for n in range(10) for k in range(-n - 1, n + 2)] + ) + + def _triangular_indices_tests_n_m(self, pyfunc): + self._triangular_indices_tests_base( + pyfunc, + [[n, m] for n in range(10) for m in range(2 * n)] + ) + + def _triangular_indices_tests_n_k_m(self, pyfunc): + self._triangular_indices_tests_base( + pyfunc, + [[n, k, m] for n in range(10) + for k in range(-n - 1, n + 2) + for m in range(2 * n)] + ) + + # Check jitted version works with default values for kwargs + cfunc = jit(nopython=True)(pyfunc) + cfunc(1) + + def _triangular_indices_from_tests_arr(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + for dtype in [int, float, bool]: + for n,m in itertools.product(range(10), range(10)): + arr = np.ones((n, m), dtype) + expected = pyfunc(arr) + got = cfunc(arr) + self.assertEqual(type(expected), type(got)) + self.assertEqual(len(expected), len(got)) + for e, g in zip(expected, got): + np.testing.assert_array_equal(e, g) + + def _triangular_indices_from_tests_arr_k(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + for dtype in [int, float, bool]: + for n,m in itertools.product(range(10), range(10)): + arr = np.ones((n, m), dtype) + for k in range(-10, 10): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertEqual(type(expected), type(got)) + self.assertEqual(len(expected), len(got)) + for e, g in zip(expected, got): + np.testing.assert_array_equal(e, g) + + def _triangular_indices_exceptions(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + parameters = pysignature(pyfunc).parameters + + with self.assertTypingError() as raises: + cfunc(1.0) + self.assertIn("n must be an integer", str(raises.exception)) + + if 'k' in parameters: + with self.assertTypingError() as raises: + cfunc(1, k=1.0) + self.assertIn("k must be an integer", str(raises.exception)) + + if 'm' in parameters: + with self.assertTypingError() as raises: + cfunc(1, m=1.0) + self.assertIn("m must be an integer", str(raises.exception)) + + def _triangular_indices_from_exceptions(self, pyfunc, test_k=True): + cfunc = jit(nopython=True)(pyfunc) + + for ndims in [0, 1, 3]: + a = np.ones([5] * ndims) + with self.assertTypingError() as raises: + cfunc(a) + self.assertIn("input array must be 2-d", str(raises.exception)) + + if test_k: + a = np.ones([5, 5]) + with self.assertTypingError() as raises: + cfunc(a, k=0.5) + self.assertIn("k must be an integer", str(raises.exception)) + + def test_tril_basic(self): + self._triangular_matrix_tests_m(tril_m) + self._triangular_matrix_tests_m_k(tril_m_k) + + def test_tril_exceptions(self): + self._triangular_matrix_exceptions(tril_m_k) + + def test_tril_indices(self): + self._triangular_indices_tests_n(tril_indices_n) + self._triangular_indices_tests_n_k(tril_indices_n_k) + self._triangular_indices_tests_n_m(tril_indices_n_m) + self._triangular_indices_tests_n_k_m(tril_indices_n_k_m) + self._triangular_indices_exceptions(tril_indices_n) + self._triangular_indices_exceptions(tril_indices_n_k) + self._triangular_indices_exceptions(tril_indices_n_m) + self._triangular_indices_exceptions(tril_indices_n_k_m) + + def test_tril_indices_from(self): + self._triangular_indices_from_tests_arr(tril_indices_from_arr) + self._triangular_indices_from_tests_arr_k(tril_indices_from_arr_k) + self._triangular_indices_from_exceptions(tril_indices_from_arr, False) + self._triangular_indices_from_exceptions(tril_indices_from_arr_k, True) + + def test_triu_basic(self): + self._triangular_matrix_tests_m(triu_m) + self._triangular_matrix_tests_m_k(triu_m_k) + + def test_triu_exceptions(self): + self._triangular_matrix_exceptions(triu_m_k) + + def test_triu_indices(self): + self._triangular_indices_tests_n(triu_indices_n) + self._triangular_indices_tests_n_k(triu_indices_n_k) + self._triangular_indices_tests_n_m(triu_indices_n_m) + self._triangular_indices_tests_n_k_m(triu_indices_n_k_m) + self._triangular_indices_exceptions(triu_indices_n) + self._triangular_indices_exceptions(triu_indices_n_k) + self._triangular_indices_exceptions(triu_indices_n_m) + self._triangular_indices_exceptions(triu_indices_n_k_m) + + def test_triu_indices_from(self): + self._triangular_indices_from_tests_arr(triu_indices_from_arr) + self._triangular_indices_from_tests_arr_k(triu_indices_from_arr_k) + self._triangular_indices_from_exceptions(triu_indices_from_arr, False) + self._triangular_indices_from_exceptions(triu_indices_from_arr_k, True) + + def test_indices_basic(self): + pyfunc = np_indices + cfunc = njit(np_indices) + + def inputs(): + # Taken from https://github.com/numpy/numpy/blob/db4f43983cb938f12c311e1f5b7165e270c393b4/numpy/core/tests/test_numeric.py#L3383-L3407 # noqa: E501 + yield (4, 3) + yield (4,) + yield (0,) + yield (2, 2, 3, 5) + + for dims in inputs(): + self.assertPreciseEqual(pyfunc(dims), cfunc(dims)) + + def test_indices_exception(self): + cfunc = njit(np_indices) + + self.disable_leak_check() + + errmsg = 'The argument "dimensions" must be a tuple of integers' + with self.assertRaises(TypingError) as raises: + cfunc("abc") + self.assertIn(errmsg, + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc((2.0, 3.0)) + self.assertIn(errmsg, + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc((2, 3.0)) + self.assertIn(errmsg, + str(raises.exception)) + + def partition_sanity_check(self, pyfunc, cfunc, a, kth): + # as NumPy uses a different algorithm, we do not expect to + # match outputs exactly... + expected = pyfunc(a, kth) + got = cfunc(a, kth) + + # but we do expect the unordered collection of elements up to the + # kth to tie out + self.assertPreciseEqual(np.unique(expected[:kth]), np.unique(got[:kth])) + + # likewise the unordered collection of elements from the kth onwards + self.assertPreciseEqual(np.unique(expected[kth:]), np.unique(got[kth:])) + + def argpartition_sanity_check(self, pyfunc, cfunc, a, kth): + # as NumPy uses a different algorithm, we do not expect to + # match outputs exactly... + expected = pyfunc(a, kth) + got = cfunc(a, kth) + + # but we do expect the unordered collection of elements up to the + # kth to tie out + self.assertPreciseEqual(np.unique(a[expected[:kth]]), + np.unique(a[got[:kth]])) + + # likewise the unordered collection of elements from the kth onwards + self.assertPreciseEqual(np.unique(a[expected[kth:]]), + np.unique(a[got[kth:]])) + + def test_partition_fuzz(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + j_range_args = ((10, 15) if REDUCED_TESTING else (10, 30)) + j_range = range(*j_range_args) + for j in j_range: + i_range_args = ((1, min(5, j - 2)) + if REDUCED_TESTING + else (1, j - 2)) + i_range = range(*i_range_args) + for i in i_range: + d = np.arange(j) + self.rnd.shuffle(d) + d = d % self.rnd.randint(2, 30) + idx = self.rnd.randint(d.size) + kth = [0, idx, i, i + 1, -idx, -i] # include negative kth's + tgt = np.sort(d)[kth] + self.assertPreciseEqual(cfunc(d, kth)[kth], + tgt) # a -> array + # Skip list/tuple variations in reduced mode + if not REDUCED_TESTING: + self.assertPreciseEqual(cfunc(d.tolist(), kth)[kth], + tgt) # a -> list + self.assertPreciseEqual(cfunc(tuple(d.tolist()), kth)[kth], + tgt) # a -> tuple + + for k in kth: + self.partition_sanity_check(pyfunc, cfunc, d, k) + + def test_argpartition_fuzz(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + j_range_args = ((10, 15) if REDUCED_TESTING else (10, 30)) + j_range = range(*j_range_args) + for j in j_range: + i_range_args = ((1, min(5, j - 2)) + if REDUCED_TESTING + else (1, j - 2)) + i_range = range(*i_range_args) + for i in i_range: + d = np.arange(j) + self.rnd.shuffle(d) + d = d % self.rnd.randint(2, 30) + idx = self.rnd.randint(d.size) + kth = [0, idx, i, i + 1, -idx, -i] # include negative kth's + tgt = np.argsort(d)[kth] + self.assertPreciseEqual(d[cfunc(d, kth)[kth]], + d[tgt]) # a -> array + # Skip list/tuple variations in reduced mode + if not REDUCED_TESTING: + self.assertPreciseEqual(d[cfunc(d.tolist(), kth)[kth]], + d[tgt]) # a -> list + self.assertPreciseEqual( + d[cfunc(tuple(d.tolist()), kth)[kth]], + d[tgt]) # a -> tuple + + for k in kth: + self.argpartition_sanity_check(pyfunc, cfunc, d, k) + + def test_partition_exception_out_of_range(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # Test out of range values in kth raise an error + a = np.arange(10) + + def _check(a, kth): + with self.assertRaises(ValueError) as e: + cfunc(a, kth) + assert str(e.exception) == "kth out of bounds" + + _check(a, 10) + _check(a, -11) + _check(a, (3, 30)) + + def test_argpartition_exception_out_of_range(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + # Test out of range values in kth raise an error + a = np.arange(10) + + def _check(a, kth): + with self.assertRaises(ValueError) as e: + cfunc(a, kth) + assert str(e.exception) == "kth out of bounds" + + _check(a, 10) + _check(a, -11) + _check(a, (3, 30)) + + def test_partition_exception_non_integer_kth(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn("Partition index must be integer", + str(raises.exception)) + + a = np.arange(10) + _check(a, 9.0) + _check(a, (3.3, 4.4)) + _check(a, np.array((1, 2, np.nan))) + + def test_argpartition_exception_non_integer_kth(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn("Partition index must be integer", + str(raises.exception)) + + a = np.arange(10) + _check(a, 9.0) + _check(a, (3.3, 4.4)) + _check(a, np.array((1, 2, np.nan))) + + def test_partition_exception_a_not_array_like(self): + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn('The first argument must be an array-like', + str(raises.exception)) + + _check(4, 0) + _check('Sausages', 0) + + def test_argpartition_exception_a_not_array_like(self): + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn('The first argument must be an array-like', + str(raises.exception)) + + _check(4, 0) + _check('Sausages', 0) + + def test_partition_exception_a_zero_dim(self): + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn('The first argument must be at least 1-D (found 0-D)', + str(raises.exception)) + + _check(np.array(1), 0) + + def test_argpartition_exception_a_zero_dim(self): + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertTypingError() as raises: + cfunc(a, kth) + self.assertIn('The first argument must be at least 1-D (found 0-D)', + str(raises.exception)) + + _check(np.array(1), 0) + + def test_partition_exception_kth_multi_dimensional(self): + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertRaises(ValueError) as raises: + cfunc(a, kth) + self.assertIn('kth must be scalar or 1-D', str(raises.exception)) + + _check(np.arange(10), kth=np.arange(6).reshape(3, 2)) + + def test_argpartition_exception_kth_multi_dimensional(self): + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check(a, kth): + with self.assertRaises(ValueError) as raises: + cfunc(a, kth) + self.assertIn('kth must be scalar or 1-D', str(raises.exception)) + + _check(np.arange(10), kth=np.arange(6).reshape(3, 2)) + + def test_partition_empty_array(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + def check(a, kth=0): + expected = pyfunc(a, kth) + got = cfunc(a, kth) + self.assertPreciseEqual(expected, got) + + # check axis handling for multidimensional empty arrays + a = np.array([]) + a = a.reshape((3, 2, 1, 0)) + + # include this with some other empty data structures + for arr in a, (), np.array([]): + check(arr) + + def test_argpartition_empty_array(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + def check(a, kth=0): + expected = pyfunc(a, kth) + got = cfunc(a, kth) + self.assertPreciseEqual(expected, got) + + # check axis handling for multidimensional empty arrays + a = np.array([]) + a = a.reshape((3, 2, 1, 0)) + + # include this with some other empty data structures + for arr in a, (), np.array([]): + check(arr) + + def test_partition_basic(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + d = np.array([]) + got = cfunc(d, 0) + self.assertPreciseEqual(d, got) + + d = np.ones(1) + got = cfunc(d, 0) + self.assertPreciseEqual(d, got) + + # kth not modified + kth = np.array([30, 15, 5]) + okth = kth.copy() + cfunc(np.arange(40), kth) + self.assertPreciseEqual(kth, okth) + + for r in ([2, 1], [1, 2], [1, 1]): + d = np.array(r) + tgt = np.sort(d) + for k in 0, 1: + self.assertPreciseEqual(cfunc(d, k)[k], tgt[k]) + self.partition_sanity_check(pyfunc, cfunc, d, k) + + for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1], + [1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]): + d = np.array(r) + tgt = np.sort(d) + for k in 0, 1, 2: + self.assertPreciseEqual(cfunc(d, k)[k], tgt[k]) + self.partition_sanity_check(pyfunc, cfunc, d, k) + + d = np.ones(50) + self.assertPreciseEqual(cfunc(d, 0), d) + + # sorted + d = np.arange(49) + for k in 5, 15: + self.assertEqual(cfunc(d, k)[k], k) + self.partition_sanity_check(pyfunc, cfunc, d, k) + + # rsorted, with input flavours: array, list and tuple + d = np.arange(47)[::-1] + for a in d, d.tolist(), tuple(d.tolist()): + self.assertEqual(cfunc(a, 6)[6], 6) + self.assertEqual(cfunc(a, 16)[16], 16) + self.assertPreciseEqual(cfunc(a, -6), cfunc(a, 41)) + self.assertPreciseEqual(cfunc(a, -16), cfunc(a, 31)) + self.partition_sanity_check(pyfunc, cfunc, d, -16) + + # median of 3 killer, O(n^2) on pure median 3 pivot quickselect + # exercises the median of median of 5 code used to keep O(n) + if REDUCED_TESTING: + # Use much smaller arrays to reduce memory usage + SIZE = 100 + else: + SIZE = 1000000 + d = np.arange(SIZE) + x = np.roll(d, d.size // 2) + mid = x.size // 2 + 1 + self.assertEqual(cfunc(x, mid)[mid], mid) + d = np.arange(SIZE + 1) + x = np.roll(d, d.size // 2 + 1) + mid = x.size // 2 + 1 + self.assertEqual(cfunc(x, mid)[mid], mid) + + # max + d = np.ones(10) + d[1] = 4 + self.assertEqual(cfunc(d, (2, -1))[-1], 4) + self.assertEqual(cfunc(d, (2, -1))[2], 1) + d[1] = np.nan + assert np.isnan(cfunc(d, (2, -1))[-1]) + + # equal elements + if REDUCED_TESTING: + # Use smaller array for equal elements test + d = np.arange(15) % 3 + tgt = np.sort(np.arange(15) % 3) + self.rnd.shuffle(d) + for i in range(0, d.size, 3): # Sample fewer indices + self.assertEqual(cfunc(d, i)[i], tgt[i]) + self.partition_sanity_check(pyfunc, cfunc, d, i) + else: + d = np.arange(47) % 7 + tgt = np.sort(np.arange(47) % 7) + self.rnd.shuffle(d) + for i in range(d.size): + self.assertEqual(cfunc(d, i)[i], tgt[i]) + self.partition_sanity_check(pyfunc, cfunc, d, i) + + d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 9]) + kth = [0, 3, 19, 20] + self.assertEqual(tuple(cfunc(d, kth)[kth]), (0, 3, 7, 7)) + + td = [(dt, s) for dt in [np.int32, np.float32] for s in (9, 16)] + for dt, s in td: + d = np.arange(s, dtype=dt) + self.rnd.shuffle(d) + d1 = np.tile(np.arange(s, dtype=dt), (4, 1)) + map(self.rnd.shuffle, d1) + for i in range(d.size): + p = cfunc(d, i) + self.assertEqual(p[i], i) + # all before are smaller + np.testing.assert_array_less(p[:i], p[i]) + # all after are larger + np.testing.assert_array_less(p[i], p[i + 1:]) + # sanity check + self.partition_sanity_check(pyfunc, cfunc, d, i) + + def test_argpartition_basic(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py # noqa: E501 + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + d = np.array([], dtype=np.int64) + expected = pyfunc(d, 0) + got = cfunc(d, 0) + self.assertPreciseEqual(expected, got) + + d = np.ones(1, dtype=np.int64) + expected = pyfunc(d, 0) + got = cfunc(d, 0) + self.assertPreciseEqual(expected, got) + + # kth not modified + kth = np.array([30, 15, 5]) + okth = kth.copy() + cfunc(np.arange(40), kth) + self.assertPreciseEqual(kth, okth) + + for r in ([2, 1], [1, 2], [1, 1]): + d = np.array(r) + tgt = np.argsort(d) + for k in 0, 1: + self.assertPreciseEqual(d[cfunc(d, k)[k]], d[tgt[k]]) + self.argpartition_sanity_check(pyfunc, cfunc, d, k) + + for r in ([3, 2, 1], [1, 2, 3], [2, 1, 3], [2, 3, 1], + [1, 1, 1], [1, 2, 2], [2, 2, 1], [1, 2, 1]): + d = np.array(r) + tgt = np.argsort(d) + for k in 0, 1, 2: + self.assertPreciseEqual(d[cfunc(d, k)[k]], d[tgt[k]]) + self.argpartition_sanity_check(pyfunc, cfunc, d, k) + + d = np.ones(50) + self.assertPreciseEqual(d[cfunc(d, 0)], d) + + # sorted + d = np.arange(49) + for k in 5, 15: + self.assertEqual(cfunc(d, k)[k], k) + self.partition_sanity_check(pyfunc, cfunc, d, k) + + # rsorted, with input flavours: array, list and tuple + d = np.arange(47)[::-1] + for a in d, d.tolist(), tuple(d.tolist()): + self.assertEqual(cfunc(a, 6)[6], 40) + self.assertEqual(cfunc(a, 16)[16], 30) + self.assertPreciseEqual(cfunc(a, -6), cfunc(a, 41)) + self.assertPreciseEqual(cfunc(a, -16), cfunc(a, 31)) + self.argpartition_sanity_check(pyfunc, cfunc, d, -16) + + # median of 3 killer, O(n^2) on pure median 3 pivot quickselect + # exercises the median of median of 5 code used to keep O(n) + if REDUCED_TESTING: + # Use much smaller arrays to reduce memory usage + SIZE = 1000 + else: + SIZE = 1000000 + + d = np.arange(SIZE) + x = np.roll(d, d.size // 2) + mid = x.size // 2 + 1 + self.assertEqual(x[cfunc(x, mid)[mid]], mid) + d = np.arange(SIZE + 1) + x = np.roll(d, d.size // 2 + 1) + mid = x.size // 2 + 1 + self.assertEqual(x[cfunc(x, mid)[mid]], mid) + + # max + d = np.ones(10) + d[1] = 4 + self.assertEqual(d[cfunc(d, (2, -1))[-1]], 4) + self.assertEqual(d[cfunc(d, (2, -1))[2]], 1) + d[1] = np.nan + assert np.isnan(d[cfunc(d, (2, -1))[-1]]) + + # equal elements + d = np.arange(47) % 7 + tgt = np.sort(np.arange(47) % 7) + self.rnd.shuffle(d) + for i in range(d.size): + self.assertEqual(d[cfunc(d, i)[i]], tgt[i]) + self.argpartition_sanity_check(pyfunc, cfunc, d, i) + + d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 9]) + kth = [0, 3, 19, 20] + self.assertEqual(tuple(d[cfunc(d, kth)[kth]]), (0, 3, 7, 7)) + + td = [(dt, s) for dt in [np.int32, np.float32] for s in (9, 16)] + for dt, s in td: + d = np.arange(s, dtype=dt) + self.rnd.shuffle(d) + d1 = np.tile(np.arange(s, dtype=dt), (4, 1)) + map(self.rnd.shuffle, d1) + for i in range(d.size): + p = d[cfunc(d, i)] + self.assertEqual(p[i], i) + # all before are smaller + np.testing.assert_array_less(p[:i], p[i]) + # all after are larger + np.testing.assert_array_less(p[i], p[i + 1:]) + # sanity check + self.argpartition_sanity_check(pyfunc, cfunc, d, i) + + def assert_partitioned(self, pyfunc, cfunc, d, kth): + prev = 0 + for k in np.sort(kth): + np.testing.assert_array_less(d[prev:k], d[k], + err_msg='kth %d' % k) + self.assertTrue((d[k:] >= d[k]).all(), + msg=("kth %d, %r not greater equal " + "%d" % (k, d[k:], d[k]))) + prev = k + 1 + self.partition_sanity_check(pyfunc, cfunc, d, k) + + def assert_argpartitioned(self, pyfunc, cfunc, d, kth): + prev = 0 + for k in np.sort(kth): + np.testing.assert_array_less(d[prev:k], d[k], + err_msg='kth %d' % k) + self.assertTrue((d[k:] >= d[k]).all(), + msg=("kth %d, %r not greater equal " + "%d" % (k, d[k:], d[k]))) + prev = k + 1 + self.argpartition_sanity_check(pyfunc, cfunc, d, k) + + def test_partition_iterative(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + assert_partitioned = partial(self.assert_partitioned, pyfunc, cfunc) + + d = np.array([3, 4, 2, 1]) + p = cfunc(d, (0, 3)) + assert_partitioned(p, (0, 3)) + assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3)) + + self.assertPreciseEqual(p, cfunc(d, (-3, -1))) + + d = np.arange(17) + self.rnd.shuffle(d) + self.assertPreciseEqual(np.arange(17), cfunc(d, list(range(d.size)))) + + # test unsorted kth + d = np.arange(17) + self.rnd.shuffle(d) + keys = np.array([1, 3, 8, -2]) + self.rnd.shuffle(d) + p = cfunc(d, keys) + assert_partitioned(p, keys) + self.rnd.shuffle(keys) + self.assertPreciseEqual(cfunc(d, keys), p) + + # equal kth + d = np.arange(20)[::-1] + assert_partitioned(cfunc(d, [5] * 4), [5]) + assert_partitioned(cfunc(d, [5] * 4 + [6, 13]), [5] * 4 + [6, 13]) + + def test_argpartition_iterative(self): + # inspired by the test of the same name in: + # https://github.com/numpy/numpy/blob/043a840/numpy/core/tests/test_multiarray.py + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + assert_argpartitioned = partial(self.assert_argpartitioned, + pyfunc, + cfunc) + + d = np.array([3, 4, 2, 1]) + p = d[cfunc(d, (0, 3))] + assert_argpartitioned(p, (0, 3)) + assert_argpartitioned(d[np.argpartition(d, (0, 3))], (0, 3)) + + self.assertPreciseEqual(p, d[cfunc(d, (-3, -1))]) + + d = np.arange(17) + self.rnd.shuffle(d) + self.assertPreciseEqual(np.arange(17), d[cfunc(d, list(range(d.size)))]) + + # test unsorted kth + d = np.arange(17) + self.rnd.shuffle(d) + keys = np.array([1, 3, 8, -2]) + self.rnd.shuffle(d) + p = d[cfunc(d, keys)] + assert_argpartitioned(p, keys) + self.rnd.shuffle(keys) + self.assertPreciseEqual(d[cfunc(d, keys)], p) + + # equal kth + d = np.arange(20)[::-1] + assert_argpartitioned(d[cfunc(d, [5] * 4)], [5]) + assert_argpartitioned(d[cfunc(d, [5] * 4 + [6, 13])], [5] * 4 + [6, 13]) + + def test_partition_multi_dim(self): + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + + def check(a, kth): + expected = pyfunc(a, kth) + got = cfunc(a, kth) + self.assertPreciseEqual(expected[:, :, kth], got[:, :, kth]) + + for s in np.ndindex(expected.shape[:-1]): + self.assertPreciseEqual(np.unique(expected[s][:kth]), + np.unique(got[s][:kth])) + self.assertPreciseEqual(np.unique(expected[s][kth:]), + np.unique(got[s][kth:])) + + def a_variations(a): + yield a + yield a.T + yield np.asfortranarray(a) + yield np.full_like(a, fill_value=np.nan) + yield np.full_like(a, fill_value=np.inf) + # multi-dimensional tuple input + yield (((1.0, 3.142, -np.inf, 3),),) + + a = np.linspace(1, 10, 48) + a[4:7] = np.nan + a[8] = -np.inf + a[9] = np.inf + a = a.reshape((4, 3, 4)) + + for arr in a_variations(a): + for k in range(-3, 3): + check(arr, k) + + def test_argpartition_multi_dim(self): + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + + def check(a, kth): + expected = pyfunc(a, kth) + got = cfunc(a, kth) + a = np.asarray(a) + idx = np.ndindex(a.shape[:-1]) + for s in idx: + self.assertPreciseEqual(a[s][expected[s][kth]], + a[s][got[s][kth]]) + + for s in np.ndindex(expected.shape[:-1]): + self.assertPreciseEqual(np.unique(a[s][expected[s][:kth]]), + np.unique(a[s][got[s][:kth]])) + self.assertPreciseEqual(np.unique(a[s][expected[s][kth:]]), + np.unique(a[s][got[s][kth:]])) + + def a_variations(a): + yield a + yield a.T + yield np.asfortranarray(a) + yield np.full_like(a, fill_value=np.nan) + yield np.full_like(a, fill_value=np.inf) + # multi-dimensional tuple input + yield (((1.0, 3.142, -np.inf, 3),),) + + a = np.linspace(1, 10, 48) + a[4:7] = np.nan + a[8] = -np.inf + a[9] = np.inf + a = a.reshape((4, 3, 4)) + + for arr in a_variations(a): + for k in range(-3, 3): + check(arr, k) + + def test_partition_boolean_inputs(self): + pyfunc = partition + cfunc = jit(nopython=True)(pyfunc) + kths = (-1, 0, 1) + if numpy_version < (2, 3): + kths = (True, False) + kths + + for d in np.linspace(1, 10, 17), np.array((True, False, True)): + for kth in kths: + self.partition_sanity_check(pyfunc, cfunc, d, kth) + + def test_argpartition_boolean_inputs(self): + pyfunc = argpartition + cfunc = jit(nopython=True)(pyfunc) + kths = (-1, 0, 1) + if numpy_version < (2, 3): + kths = (True, False) + kths + + for d in np.linspace(1, 10, 17), np.array((True, False, True)): + for kth in kths: + self.argpartition_sanity_check(pyfunc, cfunc, d, kth) + + @needs_blas + def test_cov_invalid_ddof(self): + pyfunc = cov + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + m = np.array([[0, 2], [1, 1], [2, 0]]).T + + for ddof in np.arange(4), 4j: + with self.assertTypingError() as raises: + cfunc(m, ddof=ddof) + self.assertIn('ddof must be a real numerical scalar type', + str(raises.exception)) + + for ddof in np.nan, np.inf: + with self.assertRaises(ValueError) as raises: + cfunc(m, ddof=ddof) + self.assertIn('Cannot convert non-finite ddof to integer', + str(raises.exception)) + + for ddof in 1.1, -0.7: + with self.assertRaises(ValueError) as raises: + cfunc(m, ddof=ddof) + self.assertIn('ddof must be integral value', str(raises.exception)) + + def corr_corrcoef_basic(self, pyfunc, first_arg_name): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + def input_variations(): + # array inputs + yield np.array([[0, 2], [1, 1], [2, 0]]).T + yield self.rnd.randn(100).reshape(5, 20) + yield np.asfortranarray(np.array([[0, 2], [1, 1], [2, 0]]).T) + yield self.rnd.randn(100).reshape(5, 20)[:, ::2] + yield np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964]) + yield np.full((4, 5), fill_value=True) + yield np.array([np.nan, 0.5969, -np.inf, 0.9918, 0.7964]) + yield np.linspace(-3, 3, 33).reshape(33, 1) + + # non-array inputs + yield ((0.1, 0.2), (0.11, 0.19), (0.09, 0.21)) # UniTuple + yield ((0.1, 0.2), (0.11, 0.19), (0.09j, 0.21j)) # Tuple + yield (-2.1, -1, 4.3) + yield (1, 2, 3) + yield [4, 5, 6] + yield ((0.1, 0.2, 0.3), (0.1, 0.2, 0.3)) + yield [(1, 2, 3), (1, 3, 2)] + yield 3.142 + yield ((1.1, 2.2, 1.5),) + + # empty data structures + yield np.array([]) + yield np.array([]).reshape(0, 2) + yield np.array([]).reshape(2, 0) + yield () + + # all inputs other than the first are defaulted + for input_arr in input_variations(): + _check({first_arg_name: input_arr}) + + @needs_blas + def test_corrcoef_basic(self): + pyfunc = corrcoef + self.corr_corrcoef_basic(pyfunc, first_arg_name='x') + + @needs_blas + def test_cov_basic(self): + pyfunc = cov + self.corr_corrcoef_basic(pyfunc, first_arg_name='m') + + @needs_blas + def test_cov_explicit_arguments(self): + pyfunc = cov + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + m = self.rnd.randn(105).reshape(15, 7) + y_choices = None, m[::-1] + rowvar_choices = False, True + bias_choices = False, True + ddof_choice = None, -1, 0, 1, 3.0, True + + products = itertools.product(y_choices, rowvar_choices, + bias_choices, ddof_choice) + for y, rowvar, bias, ddof in products: + params = {'m': m, 'y': y, 'ddof': ddof, + 'bias': bias, 'rowvar': rowvar} + _check(params) + + @needs_blas + def test_corrcoef_explicit_arguments(self): + pyfunc = corrcoef + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + x = self.rnd.randn(105).reshape(15, 7) + y_choices = None, x[::-1] + rowvar_choices = False, True + + for y, rowvar in itertools.product(y_choices, rowvar_choices): + params = {'x': x, 'y': y, 'rowvar': rowvar} + _check(params) + + def cov_corrcoef_edge_cases(self, pyfunc, first_arg_name): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + # some of these examples borrowed from numpy doc string examples: + # https://github.com/numpy/numpy/blob/v1.15.0/numpy/lib/function_base.py#L2199-L2231 # noqa: E501 + # some borrowed from TestCov and TestCorrCoef: + # https://github.com/numpy/numpy/blob/80d3a7a/numpy/lib/tests/test_function_base.py # noqa: E501 + m = np.array([-2.1, -1, 4.3]) + y = np.array([3, 1.1, 0.12]) + params = {first_arg_name: m, 'y': y} + _check(params) + + m = np.array([1, 2, 3]) # test case modified such that m is 1D + y = np.array([[1j, 2j, 3j]]) + params = {first_arg_name: m, 'y': y} + _check(params) + + m = np.array([1, 2, 3]) + y = (1j, 2j, 3j) + params = {first_arg_name: m, 'y': y} + _check(params) + params = {first_arg_name: y, 'y': m} # flip real and complex inputs + _check(params) + + m = np.array([1, 2, 3]) + y = (1j, 2j, 3) # note last item is not complex + params = {first_arg_name: m, 'y': y} + _check(params) + params = {first_arg_name: y, 'y': m} # flip real and complex inputs + _check(params) + + m = np.array([]) + y = np.array([]) + params = {first_arg_name: m, 'y': y} + _check(params) + + m = 1.1 + y = 2.2 + params = {first_arg_name: m, 'y': y} + _check(params) + + m = self.rnd.randn(10, 3) + y = np.array([-2.1, -1, 4.3]).reshape(1, 3) / 10 + params = {first_arg_name: m, 'y': y} + _check(params) + + m = np.array([-2.1, -1, 4.3]) + y = np.array([[3, 1.1, 0.12], [3, 1.1, 0.12]]) + params = {first_arg_name: m, 'y': y} + _check(params) + + for rowvar in False, True: + m = np.array([-2.1, -1, 4.3]) + y = np.array([[3, 1.1, 0.12], [3, 1.1, 0.12], [4, 1.1, 0.12]]) + params = {first_arg_name: m, 'y': y, 'rowvar': rowvar} + _check(params) + # swap m and y + params = {first_arg_name: y, 'y': m, 'rowvar': rowvar} + _check(params) + + @needs_blas + def test_corrcoef_edge_cases(self): + pyfunc = corrcoef + self.cov_corrcoef_edge_cases(pyfunc, first_arg_name='x') + + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + for x in (np.nan, -np.inf, 3.142, 0): + params = {'x': x} + _check(params) + + @needs_blas + def test_corrcoef_edge_case_extreme_values(self): + pyfunc = corrcoef + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + # extreme values + x = ((1e-100, 1e100), (1e100, 1e-100)) + params = {'x': x} + _check(params) + + @needs_blas + def test_cov_edge_cases(self): + pyfunc = cov + self.cov_corrcoef_edge_cases(pyfunc, first_arg_name='m') + + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-14) + + # invalid ddof + m = np.array([[0, 2], [1, 1], [2, 0]]).T + params = {'m': m, 'ddof': 5} + _check(params) + + @needs_blas + def test_cov_exceptions(self): + pyfunc = cov + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def _check_m(m): + with self.assertTypingError() as raises: + cfunc(m) + self.assertIn('m has more than 2 dimensions', str(raises.exception)) + + m = np.ones((5, 6, 7)) + _check_m(m) + + m = ((((1, 2, 3), (2, 2, 2)),),) + _check_m(m) + + m = [[[5, 6, 7]]] + _check_m(m) + + def _check_y(m, y): + with self.assertTypingError() as raises: + cfunc(m, y=y) + self.assertIn('y has more than 2 dimensions', str(raises.exception)) + + m = np.ones((5, 6)) + y = np.ones((5, 6, 7)) + _check_y(m, y) + + m = np.array((1.1, 2.2, 1.1)) + y = (((1.2, 2.2, 2.3),),) + _check_y(m, y) + + m = np.arange(3) + y = np.arange(4) + with self.assertRaises(ValueError) as raises: + cfunc(m, y=y) + self.assertIn('m and y have incompatible dimensions', + str(raises.exception)) + # Numpy raises ValueError: all the input array dimensions except for the + # concatenation axis must match exactly. + + m = np.array([-2.1, -1, 4.3]).reshape(1, 3) + with self.assertRaises(RuntimeError) as raises: + cfunc(m) + self.assertIn('2D array containing a single row is unsupported', + str(raises.exception)) + + def test_ediff1d_basic(self): + pyfunc = ediff1d + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + def to_variations(a): + yield None + yield a + # Skip additional type variations in reduced mode + if not REDUCED_TESTING: + yield a.astype(np.int16) + + def ary_variations(a): + yield a + # Skip reshape and type variations in reduced mode + if not REDUCED_TESTING: + yield a.reshape(3, 2, 2) + yield a.astype(np.int32) + + array_size = 6 if REDUCED_TESTING else 12 + for ary in ary_variations(np.linspace(-2, 7, array_size)): + params = {'ary': ary} + _check(params) + + for a in to_variations(ary): + params = {'ary': ary, 'to_begin': a} + _check(params) + + params = {'ary': ary, 'to_end': a} + _check(params) + + for b in to_variations(ary): + params = {'ary': ary, 'to_begin': a, 'to_end': b} + _check(params) + + def test_ediff1d_exceptions(self): + pyfunc = ediff1d + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc(np.array((True, True, False))) + + msg = "Boolean dtype is unsupported (as per NumPy)" + assert msg in str(e.exception) + + def test_fliplr_basic(self): + pyfunc = fliplr + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(10).reshape(5, 2) + yield np.arange(20).reshape(5, 2, 2) + yield ((1, 2),) + yield ([1, 2], [3, 4],) + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + + self.assertIn("Cannot np.fliplr on %s type" % types.unicode_type, + str(raises.exception)) + + def test_fliplr_exception(self): + pyfunc = fliplr + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(3)) + + self.assertIn("cannot index array", str(raises.exception)) + self.assertIn("with 2 indices", str(raises.exception)) + + def test_flipud_basic(self): + pyfunc = flipud + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield [1] + yield np.arange(10) + yield np.arange(10).reshape(5, 2) + yield np.arange(20).reshape(5, 2, 2) + yield ((1, 2),) + yield ([1, 2], [3, 4],) + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + + self.assertIn("Cannot np.flipud on %s type" % types.unicode_type, + str(raises.exception)) + + def test_flipud_exception(self): + pyfunc = flipud + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc(1) + + self.assertIn("cannot index array", str(raises.exception)) + self.assertIn("with 1 indices", str(raises.exception)) + + def test_flip_basic(self): + pyfunc = flip + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.array(1) + yield np.arange(10) + yield np.arange(10).reshape(5, 2) + yield np.arange(20).reshape(5, 2, 2) + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + with self.assertRaises(TypingError) as raises: + cfunc((1, 2, 3)) + + self.assertIn("Cannot np.flip on UniTuple", str(raises.exception)) + + def test_logspace2_basic(self): + + def inputs(): + #start, stop + yield 1, 60 + yield -1, 60 + yield -60, -1 + yield -1, -60 + yield 60, -1 + yield 1.0, 60.0 + yield -60.0, -1.0 + yield -1.0, 60.0 + yield 0.0, np.e + yield 0.0, np.pi + if numpy_version < (2, 0): + yield np.complex64(1), np.complex64(2) + yield np.complex64(2j), np.complex64(4j) + yield np.complex64(2), np.complex64(4j) + yield np.complex64(1 + 2j), np.complex64(3 + 4j) + yield np.complex64(1 - 2j), np.complex64(3 - 4j) + yield np.complex64(-1 + 2j), np.complex64(3 + 4j) + + pyfunc = logspace2 + cfunc = jit(nopython=True)(pyfunc) + + for start, stop in inputs(): + np.testing.assert_allclose(pyfunc(start, stop), cfunc(start, stop)) + + def test_logspace2_exception(self): + cfunc = jit(nopython=True)(logspace2) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", 5) + self.assertIn('The first argument "start" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(5, "abc") + self.assertIn('The second argument "stop" must be a number', + str(raises.exception)) + + def test_logspace3_basic(self): + + def inputs(): + #start, stop + yield 1, 60 + yield -1, 60 + yield -60, -1 + yield -1, -60 + yield 60, -1 + yield 1.0, 60.0 + yield -60.0, -1.0 + yield -1.0, 60.0 + yield 0.0, np.e + yield 0.0, np.pi + if numpy_version < (2, 0): + yield np.complex64(1), np.complex64(2) + yield np.complex64(2j), np.complex64(4j) + yield np.complex64(2), np.complex64(4j) + yield np.complex64(1 + 2j), np.complex64(3 + 4j) + yield np.complex64(1 - 2j), np.complex64(3 - 4j) + yield np.complex64(-1 + 2j), np.complex64(3 + 4j) + + pyfunc = logspace3 + cfunc = jit(nopython=True)(pyfunc) + + for start, stop in inputs(): + np.testing.assert_allclose(pyfunc(start, stop), cfunc(start, stop)) + + def test_logspace3_with_num_basic(self): + + def inputs(): + #start, stop, num + yield 1, 60, 20 + yield -1, 60, 30 + yield -60, -1, 40 + yield -1, -60, 50 + yield 60, -1, 60 + yield 1.0, 60.0, 70 + yield -60.0, -1.0, 80 + yield -1.0, 60.0, 90 + yield 0.0, np.e, 20 + yield 0.0, np.pi, 30 + if numpy_version < (2, 0): + yield np.complex64(1), np.complex64(2), 40 + yield np.complex64(2j), np.complex64(4j), 50 + yield np.complex64(2), np.complex64(4j), 60 + yield np.complex64(1 + 2j), np.complex64(3 + 4j), 70 + yield np.complex64(1 - 2j), np.complex64(3 - 4j), 80 + yield np.complex64(-1 + 2j), np.complex64(3 + 4j), 90 + + pyfunc = logspace3 + cfunc = jit(nopython=True)(pyfunc) + + for start, stop, num in inputs(): + np.testing.assert_allclose(pyfunc(start, stop, num), + cfunc(start, stop, num)) + + def test_logspace3_exception(self): + cfunc = jit(nopython=True)(logspace3) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", 5) + self.assertIn('The first argument "start" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(5, "abc") + self.assertIn('The second argument "stop" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(0, 5, "abc") + self.assertIn('The third argument "num" must be an integer', + str(raises.exception)) + + def test_geomspace2_basic(self): + + def inputs(): + #start, stop + yield -1, -60 + yield 1.0, 60.0 + yield -60.0, -1.0 + yield 1, 1000 + yield 1000, 1 + yield 1, 256 + yield -1000, -1 + yield -1, np.complex64(2j) + yield np.complex64(2j), -1 + yield -1.0, np.complex64(2j) + yield np.complex64(1j), np.complex64(1000j) + yield np.complex64(-1 + 0j), np.complex64(1 + 0j) + yield np.complex64(1), np.complex64(2) + yield np.complex64(2j), np.complex64(4j) + yield np.complex64(2), np.complex64(4j) + yield np.complex64(1 + 2j), np.complex64(3 + 4j) + yield np.complex64(1 - 2j), np.complex64(3 - 4j) + yield np.complex64(-1 + 2j), np.complex64(3 + 4j) + + pyfunc = geomspace2 + cfunc = jit(nopython=True)(pyfunc) + + for start, stop in inputs(): + self.assertPreciseEqual(pyfunc(start, stop), + cfunc(start, stop), + abs_tol=1e-12) + + def test_geomspace2_exception(self): + cfunc = jit(nopython=True)(geomspace2) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", 5) + self.assertIn('The argument "start" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(5, "abc") + self.assertIn('The argument "stop" must be a number', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(0, 5) + self.assertIn('Geometric sequence cannot include zero', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(5, 0) + self.assertIn('Geometric sequence cannot include zero', + str(raises.exception)) + + def test_geomspace3_basic(self): + + def inputs(): + #start, stop, num + yield -1, -60, 50 + yield 1.0, 60.0, 70 + yield -60.0, -1.0, 80 + yield 1, 1000, 4 + yield 1, 1000, 3 + yield 1000, 1, 4 + yield 1, 256, 9 + yield -1000, -1, 4 + yield -1, np.complex64(2j), 10 + yield np.complex64(2j), -1, 20 + yield -1.0, np.complex64(2j), 30 + yield np.complex64(1j), np.complex64(1000j), 4 + yield np.complex64(-1 + 0j), np.complex64(1 + 0j), 5 + yield np.complex64(1), np.complex64(2), 40 + yield np.complex64(2j), np.complex64(4j), 50 + yield np.complex64(2), np.complex64(4j), 60 + yield np.complex64(1 + 2j), np.complex64(3 + 4j), 70 + yield np.complex64(1 - 2j), np.complex64(3 - 4j), 80 + yield np.complex64(-1 + 2j), np.complex64(3 + 4j), 90 + + pyfunc = geomspace3 + cfunc = jit(nopython=True)(pyfunc) + + for start, stop, num in inputs(): + self.assertPreciseEqual(pyfunc(start, stop, num), + cfunc(start, stop, num), + abs_tol=1e-14) + + def test_geomspace3_exception(self): + cfunc = jit(nopython=True)(geomspace3) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", 5, 10) + self.assertIn('The argument "start" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(5, "abc", 10) + self.assertIn('The argument "stop" must be a number', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(5, 10, "abc") + self.assertIn('The argument "num" must be an integer', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(0, 5, 5) + self.assertIn('Geometric sequence cannot include zero', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(5, 0, 5) + self.assertIn('Geometric sequence cannot include zero', + str(raises.exception)) + + def test_geomspace_numpy(self): + cfunc2 = jit(nopython=True)(geomspace2) + cfunc3 = jit(nopython=True)(geomspace3) + pfunc3 = geomspace3 + + # https://github.com/numpy/numpy/blob/ab2178b47c0ee834180c318db196976623710691/numpy/core/tests/test_function_base.py#L122C3-L142 + # test_basic + y = cfunc2(1, 1e6) + self.assertEqual(len(y), 50) + y = cfunc3(1, 1e6, num=100) + self.assertEqual(y[-1], 10 ** 6) + y = cfunc3(1, 1e6, num=7) + self.assertPreciseEqual(y, pfunc3(1,1e6, num=7)) + + y = cfunc3(8, 2, num=3) + self.assertPreciseEqual(y, pfunc3(8, 2, num=3)) + self.assertTrue([x == 0 for x in y.imag]) + + y = cfunc3(-1, -100, num=3) + self.assertPreciseEqual(y, pfunc3(-1, -100, num=3)) + self.assertTrue([x == 0 for x in y.imag]) + + y = cfunc3(-100, -1, num=3) + self.assertPreciseEqual(y, pfunc3(-100, -1, num=3)) + self.assertTrue([x == 0 for x in y.imag]) + + # test_boundaries_match_start_and_stop_exactly + start = 0.3 + stop = 20.3 + + y = cfunc3(start, stop, num=1) + self.assertPreciseEqual(y[0], start) + + y = cfunc3(start, stop, num=3) + self.assertPreciseEqual(y[0], start) + self.assertPreciseEqual(y[-1], stop) + + # test_nan_interior + with np.errstate(invalid='ignore'): + y = cfunc3(-3, 3, num=4) + + self.assertPreciseEqual(y[0], -3.0) + self.assertTrue(np.isnan(y[1:-1]).all()) + self.assertPreciseEqual(y[3], 3.0) + + # test_complex + # Purely imaginary + y = cfunc3(1j, 16j, num=5) + self.assertPreciseEqual(y, pfunc3(1j, 16j, num=5), abs_tol=1e-14) + self.assertTrue([x == 0 for x in y.real]) + + y = cfunc3(-4j, -324j, num=5) + self.assertPreciseEqual(y, pfunc3(-4j, -324j, num=5), abs_tol=1e-13) + self.assertTrue([x == 0 for x in y.real]) + + y = cfunc3(1 + 1j, 1000 + 1000j, num=4) + self.assertPreciseEqual(y, + pfunc3(1 + 1j, 1000 + 1000j, num=4), + abs_tol=1e-13) + + y = cfunc3(-1 + 1j, -1000 + 1000j, num=4) + self.assertPreciseEqual(y, + pfunc3(-1 + 1j, -1000 + 1000j, num=4), + abs_tol=1e-13) + + # Logarithmic spirals + if numpy_version < (2, 0): + y = cfunc3(-1 + 0j, 1 + 0j, num=3) + self.assertPreciseEqual(y, pfunc3(-1 + 0j, 1 + 0j, num=3)) + + y = cfunc3(0 + 3j, -3 + 0j, 3) + self.assertPreciseEqual(y, pfunc3(0 + 3j, -3 + 0j, 3), abs_tol=1e-15) + y = cfunc3(0 + 3j, 3 + 0j, 3) + self.assertPreciseEqual(y, pfunc3(0 + 3j, 3 + 0j, 3), abs_tol=1e-15) + y = cfunc3(-3 + 0j, 0 - 3j, 3) + self.assertPreciseEqual(y, pfunc3(-3 + 0j, 0 - 3j, 3), abs_tol=1e-15) + y = cfunc3(0 + 3j, -3 + 0j, 3) + self.assertPreciseEqual(y, pfunc3(0 + 3j, -3 + 0j, 3), abs_tol=1e-15) + y = cfunc3(-2 - 3j, 5 + 7j, 7) + self.assertPreciseEqual(y, pfunc3(-2 - 3j, 5 + 7j, 7), abs_tol=1e-14) + + y = cfunc3(3j, -5, 2) + self.assertPreciseEqual(y, pfunc3(3j, -5, 2)) + y = cfunc3(-5, 3j, 2) + self.assertPreciseEqual(y, pfunc3(-5, 3j, 2)) + + def test_rot90_basic(self): + pyfunc = rot90 + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(10).reshape(5, 2) + yield np.arange(20).reshape(5, 2, 2) + yield np.arange(64).reshape(2, 2, 2, 2, 2, 2) + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_rot90_with_k_basic(self): + pyfunc = rot90_k + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(10).reshape(5, 2) + yield np.arange(20).reshape(5, 2, 2) + yield np.arange(64).reshape(2, 2, 2, 2, 2, 2) + + for a in a_variations(): + for k in range(-5, 6): + expected = pyfunc(a, k) + got = cfunc(a, k) + self.assertPreciseEqual(expected, got) + + def test_rot90_exception(self): + pyfunc = rot90_k + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + + self.assertIn('The first argument "m" must be an array', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(4).reshape(2, 2), k="abc") + + self.assertIn('The second argument "k" must be an integer', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(3)) + + self.assertIn("Input must be >= 2-d.", str(raises.exception)) + + def _check_split(self, func): + # Since np.split and np.array_split are very similar + pyfunc = func + cfunc = jit(nopython=True)(pyfunc) + + def args_variations(): + a = np.arange(100) + yield a, 2 + yield a, 2, 0 + yield a, [1, 4, 72] + yield list(a), [1, 4, 72] + yield tuple(a), [1, 4, 72] + yield a, [1, 4, 72], 0 + yield list(a), [1, 4, 72], 0 + yield tuple(a), [1, 4, 72], 0 + + a = np.arange(64).reshape(4, 4, 4) + yield a, 2 + yield a, 2, 0 + yield a, 2, 1 + yield a, [2, 1, 5] + yield a, [2, 1, 5], 1 + yield a, [2, 1, 5], 2 + yield a, [1, 3] + yield a, [1, 3], 1 + yield a, [1, 3], 2 + yield a, [1], -1 + yield a, [1], -2 + yield a, [1], -3 + yield a, np.array([], dtype=np.int64), 0 + + a = np.arange(100).reshape(2, -1) + yield a, 1 + yield a, 1, 0 + yield a, [1], 0 + yield a, 50, 1 + yield a, np.arange(10, 50, 10), 1 + yield a, (1,) + yield a, (np.int32(4), 10) + + a = np.array([]) + yield a, 1 + yield a, 2 + yield a, (2, 3), 0 + yield a, 1, 0 + + a = np.array([[]]) + yield a, 1 + yield a, (2, 3), 1 + yield a, 1, 0 + yield a, 1, 1 + + for args in args_variations(): + expected = pyfunc(*args) + got = cfunc(*args) + + np.testing.assert_equal(expected, list(got)) + + def _check_array_split(self, func): + # array_split specific checks, mainly dealing with `int`s + pyfunc = func + cfunc = jit(nopython=True)(pyfunc) + + def args_variations(): + yield np.arange(8), 3 + yield list(np.arange(8)), 3 + yield tuple(np.arange(8)), 3 + yield np.arange(24).reshape(12, 2), 5 + + for args in args_variations(): + expected = pyfunc(*args) + got = cfunc(*args) + + np.testing.assert_equal(expected, list(got)) + + def test_array_split_basic(self): + self._check_split(array_split) + self._check_array_split(array_split) + + def test_split_basic(self): + self._check_split(split) + + self.disable_leak_check() # The exception leaks + with self.assertRaises(ValueError) as raises: + njit(split)(np.ones(5), 2) + self.assertIn( + "array split does not result in an equal division", + str(raises.exception) + ) + + with self.assertRaises(ValueError) as raises: + njit(split)(np.ones(5), [3], axis=-3) + self.assertIn("np.split: Argument axis out of bounds", + str(raises.exception)) + + def test_vhdsplit_basic(self): + # split and array_split have more comprehensive tests of splitting. + # only do simple tests on vsplit, hsplit and dsplit + # Based on tests from https://github.com/numpy/numpy/blob/f0befec40376fc46fdaceac2c49c7349ad671bde/numpy/lib/tests/test_shape_base.py#L538-L624 # noqa: E501 + def inputs1D(): + # test_1D_array + yield np.array([1, 2, 3, 4]), 2 + yield np.array([1., 2., 3., 4.]), 2 + + def inputs2D(): + # test_2D_array + yield np.array([[1, 2, 3, 4], [1, 2, 3, 4]]), 2 + yield np.array([[1., 2., 3., 4.], [1., 2., 3., 4.]]), 2 + yield np.arange(16.0).reshape(4, 4), 2 + yield np.arange(16.0).reshape(4, 4), np.array([3, 6]) + yield np.arange(16.0).reshape(4, 4), [3, 6] + yield np.arange(16.0).reshape(4, 4), (3, 6) + yield np.arange(8.0).reshape(2, 2, 2), 2 + + def inputs3D(): + # test_3D_array + np.array([[[1, 2, 3, 4], + [1, 2, 3, 4]], + [[1, 2, 3, 4], + [1, 2, 3, 4]]]), 2 + yield np.arange(16.0).reshape(2, 2, 4), 2 + yield np.arange(16.0).reshape(2, 2, 4), np.array([3, 6]) + yield np.arange(16.0).reshape(2, 2, 4), [3, 6] + yield np.arange(16.0).reshape(2, 2, 4), (3, 6) + yield np.arange(8.0).reshape(2, 2, 2), 2 + + inputs = [inputs1D(), inputs2D(), inputs3D()] + for (f, mindim, name) in [(vsplit, 2, "vsplit"), + (hsplit, 1, "hsplit"), + (dsplit, 3, "dsplit")]: + pyfunc = f + cfunc = njit(pyfunc) + for i in range(mindim, 4): + for a, ind_or_sec in inputs[i - 1]: + self.assertPreciseEqual(pyfunc(a, ind_or_sec), + cfunc(a, ind_or_sec)) + + def test_vhdsplit_exception(self): + # Single test method for vsplit, hsplit and dsplit exceptions + for (f, mindim, name) in [(vsplit, 2, "vsplit"), + (hsplit, 1, "hsplit"), + (dsplit, 3, "dsplit")]: + cfunc = jit(nopython=True)(f) + self.disable_leak_check() + with self.assertRaises(TypingError) as raises: + cfunc(1, 2) + self.assertIn('The argument "ary" must be an array', + str(raises.exception)) + with self.assertRaises(TypingError) as raises: + cfunc("abc", 2) + self.assertIn('The argument "ary" must be an array', + str(raises.exception)) + with self.assertRaises(TypingError) as raises: + cfunc(np.array([[1, 2, 3, 4], [1, 2, 3, 4]]), "abc") + self.assertIn(('The argument "indices_or_sections" must be int or ' + '1d-array'), + str(raises.exception)) + with self.assertRaises(ValueError) as raises: + cfunc(np.array(1), 2) + self.assertIn(name + ' only works on arrays of ' + str(mindim) + + ' or more dimensions', + str(raises.exception)) + + def test_roll_basic(self): + pyfunc = roll + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(7) + yield np.arange(3 * 4 * 5).reshape(3, 4, 5) + yield [1.1, 2.2, 3.3] + yield (True, False, True) + yield False + yield 4 + yield (9,) + yield np.asfortranarray(np.array([[1.1, np.nan], [np.inf, 7.8]])) + yield np.array([]) + yield () + + def shift_variations(): + return itertools.chain.from_iterable(((True, False), + range(-10, 10))) + + for a in a_variations(): + for shift in shift_variations(): + expected = pyfunc(a, shift) + got = cfunc(a, shift) + self.assertPreciseEqual(expected, got) + + def test_roll_exceptions(self): + pyfunc = roll + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + for shift in 1.1, (1, 2): + with self.assertTypingError() as e: + cfunc(np.arange(10), shift) + + msg = "shift must be an integer" + assert msg in str(e.exception) + + def test_extract_basic(self): + pyfunc = extract + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + a = np.arange(10) + self.rnd.shuffle(a) + threshold_range = range(-1, 5) if REDUCED_TESTING else range(-3, 13) + for threshold in threshold_range: + cond = a > threshold + _check({'condition': cond, 'arr': a}) + + if REDUCED_TESTING: + a = np.arange(12).reshape(3, 4) + else: + a = np.arange(60).reshape(4, 5, 3) + cond = a > 5.2 + _check({'condition': cond, 'arr': a}) + + a = ((1, 2, 3), (3, 4, 5), (4, 5, 6)) + cond = np.eye(3).flatten() + _check({'condition': cond, 'arr': a}) + + a = [1.1, 2.2, 3.3, 4.4] + cond = [1, 1, 0, 1] + _check({'condition': cond, 'arr': a}) + + a = np.linspace(-2, 10, 6) + element_pool = (True, False, np.nan, -1, -1.0, -1.2, 1, 1.0, 1.5j) + if REDUCED_TESTING: + # Reduce combinations to limit memory usage + for cond in itertools.islice( + itertools.combinations_with_replacement(element_pool, 3), + 10): + _check({'condition': cond, 'arr': a[:3]}) + _check({'condition': np.array(cond), 'arr': a[:3]}) + else: + for cond in itertools.combinations_with_replacement( + element_pool, 4): + _check({'condition': cond, 'arr': a}) + _check({'condition': np.array(cond).reshape(2, 2), 'arr': a}) + + a = np.array([1, 2, 3]) + cond = np.array([]) + _check({'condition': cond, 'arr': a}) + + a = np.array([1, 2, 3]) + cond = np.array([1, 0, 1, 0]) # but [1, 0, 1, 0, 1] raises + _check({'condition': cond, 'arr': a}) + + a = np.array([[1, 2, 3], [4, 5, 6]]) + cond = [1, 0, 1, 0, 1, 0] # but [1, 0, 1, 0, 1, 0, 1] raises + _check({'condition': cond, 'arr': a}) + + a = np.array([[1, 2, 3], [4, 5, 6]]) + cond = np.array([1, 0, 1, 0, 1, 0, 0, 0]).reshape(2, 2, 2) + _check({'condition': cond, 'arr': a}) + + a = np.asfortranarray(np.arange(60).reshape(3, 4, 5)) + cond = np.repeat((0, 1), 30) + _check({'condition': cond, 'arr': a}) + _check({'condition': cond, 'arr': a[::-1]}) + + a = np.array(4) + for cond in 0, 1: + _check({'condition': cond, 'arr': a}) + + a = 1 + cond = 1 + _check({'condition': cond, 'arr': a}) + + a = np.array(1) + cond = np.array([True, False]) + _check({'condition': cond, 'arr': a}) + + a = np.arange(4) + cond = np.array([1, 0, 1, 0, 0, 0]).reshape(2, 3) * 1j + _check({'condition': cond, 'arr': a}) + + def test_extract_exceptions(self): + pyfunc = extract + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + a = np.array([]) + cond = np.array([1, 2, 3]) + + with self.assertRaises(ValueError) as e: + cfunc(cond, a) + self.assertIn('Cannot extract from an empty array', str(e.exception)) + + def _check(cond, a): + msg = 'condition shape inconsistent with arr shape' + with self.assertRaises(ValueError) as e: + cfunc(cond, a) + self.assertIn(msg, str(e.exception)) + + a = np.array([[1, 2, 3], [1, 2, 3]]) + cond = [1, 0, 1, 0, 1, 0, 1] + _check(cond, a) + + a = np.array([1, 2, 3]) + cond = np.array([1, 0, 1, 0, 1]) + _check(cond, a) + + a = np.array(60) # note, this is 0D + cond = 0, 1 + _check(cond, a) + + a = np.arange(4) + cond = np.array([True, False, False, False, True]) + _check(cond, a) + + a = np.arange(4) + cond = np.array([True, False, True, False, False, True, False]) + _check(cond, a) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_np_trapezoid_basic(self): + self.test_np_trapz_basic(pyfunc=np_trapezoid) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + def test_np_trapz_basic(self, pyfunc=np_trapz): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + y = [1, 2, 3] + _check({'y': y}) + + y = (3, 1, 2, 2, 2) + _check({'y': y}) + + y = np.arange(15).reshape(3, 5) + _check({'y': y}) + + y = np.linspace(-10, 10, 60).reshape(4, 3, 5) + _check({'y': y}, abs_tol=1e-13) + + self.rnd.shuffle(y) + _check({'y': y}, abs_tol=1e-13) + + y = np.array([]) + _check({'y': y}) + + y = np.array([3.142, np.nan, np.inf, -np.inf, 5]) + _check({'y': y}) + + y = np.arange(20) + np.linspace(0, 10, 20) * 1j + _check({'y': y}) + + y = np.array([], dtype=np.complex128) + _check({'y': y}) + + y = (True, False, True) + _check({'y': y}) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_np_trapezoid_x_basic(self): + self.test_np_trapz_x_basic(pyfunc=np_trapezoid_x) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + def test_np_trapz_x_basic(self, pyfunc=np_trapz_x): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + y = [1, 2, 3] + x = [4, 6, 8] + _check({'y': y, 'x': x}) + + y = [1, 2, 3, 4, 5] + x = (4, 6) + _check({'y': y, 'x': x}) + + y = (1, 2, 3, 4, 5) + x = [4, 5, 6, 7, 8] + _check({'y': y, 'x': x}) + + y = np.array([1, 2, 3, 4, 5]) + x = [4, 4] + _check({'y': y, 'x': x}) + + y = np.array([]) + x = np.array([2, 3]) + _check({'y': y, 'x': x}) + + y = (1, 2, 3, 4, 5) + x = None + _check({'y': y, 'x': x}) + + y = np.arange(20).reshape(5, 4) + x = np.array([4, 5]) + _check({'y': y, 'x': x}) + + y = np.arange(20).reshape(5, 4) + x = np.array([4, 5, 6, 7]) + _check({'y': y, 'x': x}) + + y = np.arange(60).reshape(5, 4, 3) + x = np.array([4, 5]) + _check({'y': y, 'x': x}) + + y = np.arange(60).reshape(5, 4, 3) + x = np.array([4, 5, 7]) + _check({'y': y, 'x': x}) + + y = np.arange(60).reshape(5, 4, 3) + self.rnd.shuffle(y) + x = y + 1.1 + self.rnd.shuffle(x) + _check({'y': y, 'x': x}) + + y = np.arange(20) + x = y + np.linspace(0, 10, 20) * 1j + _check({'y': y, 'x': x}) + + y = np.array([1, 2, 3]) + x = np.array([1 + 1j, 1 + 2j]) + _check({'y': y, 'x': x}) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_trapezoid_numpy_questionable(self): + self.test_trapz_numpy_questionable(pyfunc=np_trapezoid) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + @unittest.skip('NumPy behaviour questionable') + def test_trapz_numpy_questionable(self, pyfunc=np_trapz): + # https://github.com/numpy/numpy/issues/12858 + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + # passes (NumPy and Numba return 2.0) + y = np.array([True, False, True, True]).astype(int) + _check({'y': y}) + + # fails (NumPy returns 1.5; Numba returns 2.0) + y = np.array([True, False, True, True]) + _check({'y': y}) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_np_trapezoid_dx_basic(self): + self.test_np_trapz_dx_basic(pyfunc=np_trapezoid_dx) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + def test_np_trapz_dx_basic(self, pyfunc=np_trapz_dx): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + y = [1, 2, 3] + dx = 2 + _check({'y': y, 'dx': dx}) + + y = [1, 2, 3, 4, 5] + dx = [1, 4, 5, 6] + _check({'y': y, 'dx': dx}) + + y = [1, 2, 3, 4, 5] + dx = [1, 4, 5, 6] + _check({'y': y, 'dx': dx}) + + y = np.linspace(-2, 5, 10) + dx = np.nan + _check({'y': y, 'dx': dx}) + + y = np.linspace(-2, 5, 10) + dx = np.inf + _check({'y': y, 'dx': dx}) + + y = np.linspace(-2, 5, 10) + dx = np.linspace(-2, 5, 9) + _check({'y': y, 'dx': dx}, abs_tol=1e-13) + + y = np.arange(60).reshape(4, 5, 3) * 1j + dx = np.arange(40).reshape(4, 5, 2) + _check({'y': y, 'dx': dx}) + + x = np.arange(-10, 10, .1) + r = cfunc(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1) + # check integral of normal equals 1 + np.testing.assert_almost_equal(r, 1, 7) + + y = np.arange(20) + dx = 1j + _check({'y': y, 'dx': dx}) + + y = np.arange(20) + dx = np.array([5]) + _check({'y': y, 'dx': dx}) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_np_trapezoid_x_dx_basic(self): + self.test_np_trapz_x_dx_basic(pyfunc=np_trapezoid_x_dx) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + def test_np_trapz_x_dx_basic(self, pyfunc=np_trapz_x_dx): + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + # dx should be ignored + for dx in (None, 2, np.array([1, 2, 3, 4, 5])): + y = [1, 2, 3] + x = [4, 6, 8] + _check({'y': y, 'x': x, 'dx': dx}) + + y = [1, 2, 3, 4, 5] + x = [4, 6] + _check({'y': y, 'x': x, 'dx': dx}) + + y = [1, 2, 3, 4, 5] + x = [4, 5, 6, 7, 8] + _check({'y': y, 'x': x, 'dx': dx}) + + y = np.arange(60).reshape(4, 5, 3) + self.rnd.shuffle(y) + x = y * 1.1 + x[2, 2, 2] = np.nan + _check({'y': y, 'x': x, 'dx': dx}) + + @unittest.skipUnless(IS_NUMPY_2, "New in numpy 2.0+") + def test_np_trapezoid_x_dx_exceptions(self): + self.test_np_trapz_x_dx_exceptions(pyfunc=np_trapezoid_x_dx) + + @unittest.skipIf(numpy_version >= (2, 4), "np.trapz removed in NumPy 2.4+") + def test_np_trapz_x_dx_exceptions(self, pyfunc=np_trapz_x_dx): + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + def check_not_ok(params): + with self.assertRaises(ValueError) as e: + cfunc(*params) + + self.assertIn('unable to broadcast', str(e.exception)) + + y = [1, 2, 3, 4, 5] + for x in [4, 5, 6, 7, 8, 9], [4, 5, 6]: + check_not_ok((y, x, 1.0)) + + y = np.arange(60).reshape(3, 4, 5) + x = np.arange(36).reshape(3, 4, 3) + check_not_ok((y, x, 1.0)) + + y = np.arange(60).reshape(3, 4, 5) + x = np.array([4, 5, 6, 7]) + check_not_ok((y, x, 1.0)) + + y = [1, 2, 3, 4, 5] + dx = np.array([1.0, 2.0]) + check_not_ok((y, None, dx)) + + y = np.arange(60).reshape(3, 4, 5) + dx = np.arange(60).reshape(3, 4, 5) + check_not_ok((y, None, dx)) + + with self.assertTypingError() as e: + y = np.array(4) + check_not_ok((y, None, 1.0)) + + self.assertIn('y cannot be 0D', str(e.exception)) + + for y in 5, False, np.nan: + with self.assertTypingError() as e: + cfunc(y, None, 1.0) + + self.assertIn('y cannot be a scalar', str(e.exception)) + + def test_average(self): + + #array of random numbers + N = 100 + a = np.random.ranf(N) * 100 + w = np.random.ranf(N) * 100 + w0 = np.zeros(N) + + #boolean array and weights + a_bool = np.random.ranf(N) > 0.5 + w_bool = np.random.ranf(N) > 0.5 + + #array of random ints + a_int = np.random.randint(101, size=N) + w_int = np.random.randint(101, size=N) + + #3D array of random numbers + d0 = 100 + d1 = 50 + d2 = 25 + a_3d = np.random.rand(d0,d1,d2) * 100 + w_3d = np.random.rand(d0,d1,d2) * 100 + + pyfunc = np_average + cfunc = jit(nopython=True)(pyfunc) + + #test case for average with weights + #(number of elements in array and weight array are equal) + self.assertAlmostEqual( pyfunc(a,weights=w), + cfunc(a,weights=w), places=10) + self.assertAlmostEqual( pyfunc(a_3d,weights=w_3d), + cfunc(a_3d,weights=w_3d), places=10) + + #test case for average with array and weights with + #int datatype (number of elements in array and weight array are equal) + self.assertAlmostEqual( pyfunc(a_int,weights=w_int), + cfunc(a_int,weights=w_int), places=10) + + #test case for average with boolean weights + self.assertAlmostEqual( pyfunc(a,weights=w_bool), + cfunc(a,weights=w_bool), places=10) + self.assertAlmostEqual( pyfunc(a_bool,weights=w), + cfunc(a_bool,weights=w), places=10) + self.assertAlmostEqual( pyfunc(a_bool, weights=w_bool), + cfunc(a_bool, weights=w_bool), places=10) + + #test case for average without weights + self.assertAlmostEqual(pyfunc(a), cfunc(a), places=10) + self.assertAlmostEqual(pyfunc(a_3d), cfunc(a_3d), places=10) + + def test_weights_zero_sum(data, weights): + with self.assertRaises(ZeroDivisionError) as e: + cfunc(data, weights=weights) + err = e.exception + self.assertEqual(str(err), + "Weights sum to zero, can't be normalized.") + + #test case when sum of weights is zero + test_weights_zero_sum(a, weights=w0) + + def test_1D_weights(data, weights): + with self.assertRaises(TypeError) as e: + cfunc(data, weights=weights) + err = e.exception + self.assertEqual(str(err), + "1D weights expected when shapes of " + "a and weights differ.") + + def test_1D_weights_axis(data, axis, weights): + with self.assertRaises(TypeError) as e: + cfunc(data, axis=axis, weights=weights) + err = e.exception + self.assertEqual(str(err), + "Numba does not support average with axis.") + + def test_axis(data, axis): + with self.assertRaises(TypeError) as e: + cfunc(data, axis=axis) + err = e.exception + self.assertEqual(str(err), + "Numba does not support average with axis.") + + #small case to test exceptions for 2D array and 1D weights + data = np.arange(6).reshape((3,2,1)) + w = np.asarray([[1. / 4, 3. / 4]]) + + #test axis + test_axis(data, axis=1) + + #test shape mismatch + test_1D_weights(data, weights=w) + + #test axis and with weights provided + test_1D_weights_axis(data, axis=1, weights=w) + + def test_allclose(self): + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + min_int = np.iinfo(np.int_).min + a = np.array([min_int], dtype=np.int_) + + simple_data = [ + (np.asarray([1e10, 1e-7]), np.asarray([1.00001e10, 1e-8])), + (np.asarray([1e10, 1e-8]), np.asarray([1.00001e10, 1e-9])), + (np.asarray([1e10, 1e-8]), np.asarray([1.0001e10, 1e-9])), + (np.asarray([1e10]), np.asarray([1.0001e10, 1e-9])), + (1.0, 1.0), + (np.array([np.inf, 1]), np.array([0, np.inf])), + (a, a) + ] + + for a, b in simple_data: + py_result = pyfunc(a, b) + c_result = cfunc(a, b) + self.assertEqual(py_result, c_result) + + a = np.asarray([1.0, np.nan]) + b = np.asarray([1.0, np.nan]) + self.assertFalse(cfunc(a, b)) + self.assertEqual(pyfunc(a, b, equal_nan=True), + cfunc(a, b, equal_nan=True)) + + b = np.asarray([np.nan, 1.0]) + self.assertEqual(pyfunc(a, b), cfunc(a, b)) + + noise_levels = [1.0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 0.0] + zero_array = np.zeros((25, 4)) + a = np.random.ranf((25, 4)) + for noise in noise_levels: + for rtol in noise_levels: + for atol in noise_levels: + py_result = pyfunc(zero_array, noise, + atol=atol, rtol=rtol) + c_result = cfunc(zero_array, noise, + atol=atol, rtol=rtol) + self.assertEqual(py_result, c_result) + + py_result = pyfunc(noise, zero_array, + atol=atol, rtol=rtol) + c_result = cfunc(noise, zero_array, + atol=atol, rtol=rtol) + self.assertEqual(py_result, c_result) + + py_result = pyfunc(np.asarray([noise]), zero_array, + atol=atol, rtol=rtol) + c_result = cfunc(np.asarray([noise]), zero_array, + atol=atol, rtol=rtol) + self.assertEqual(py_result, c_result) + + py_result = pyfunc(a, a + noise, atol=atol, rtol=rtol) + c_result = cfunc(a, a + noise, atol=atol, rtol=rtol) + self.assertEqual(py_result, c_result) + + py_result = pyfunc(a + noise, a, atol=atol, rtol=rtol) + c_result = cfunc(a + noise, a, atol=atol, rtol=rtol) + self.assertEqual(py_result, c_result) + + def test_ip_allclose_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2402-L2420 # noqa: E501 + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + arr = np.array([100.0, 1000.0]) + aran = np.arange(125).astype(dtype=np.float64).reshape((5, 5, 5)) + + atol = 1e-8 + rtol = 1e-5 + + numpy_data = [ + (np.asarray([1, 0]), np.asarray([1, 0])), + (np.asarray([atol]), np.asarray([0.0])), + (np.asarray([1.0]), np.asarray([1 + rtol + atol])), + (arr, arr + arr * rtol), + (arr, arr + arr * rtol + atol * 2), + (aran, aran + aran * rtol), + (np.inf, np.inf), + (np.inf, np.asarray([np.inf])) + ] + + for (x, y) in numpy_data: + self.assertEqual(pyfunc(x, y), cfunc(x, y)) + + def test_ip_not_allclose_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2422-L2441 # noqa: E501 + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + aran = np.arange(125).astype(dtype=np.float64).reshape((5, 5, 5)) + + atol = 1e-8 + rtol = 1e-5 + + numpy_data = [ + (np.asarray([np.inf, 0]), np.asarray([1.0, np.inf])), + (np.asarray([np.inf, 0]), np.asarray([1.0, 0])), + (np.asarray([np.inf, np.inf]), np.asarray([1.0, np.inf])), + (np.asarray([np.inf, np.inf]), np.asarray([1.0, 0.0])), + (np.asarray([-np.inf, 0.0]), np.asarray([np.inf, 0.0])), + (np.asarray([np.nan, 0.0]), np.asarray([np.nan, 0.0])), + (np.asarray([atol * 2]), np.asarray([0.0])), + (np.asarray([1.0]), np.asarray([1 + rtol + atol * 2])), + (aran, aran + aran * atol + atol * 2), + (np.array([np.inf, 1.0]), np.array([0.0, np.inf])) + ] + + for (x, y) in numpy_data: + self.assertEqual(pyfunc(x, y), cfunc(x, y)) + + def test_return_class_is_ndarray_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2460-L2468 # noqa: E501 + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + class Foo(np.ndarray): + def __new__(cls, *args, **kwargs): + return np.array(*args, **kwargs).view(cls) + + a = Foo([1]) + self.assertTrue(type(cfunc(a, a)) is bool) + + def test_equalnan_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2456-L2458 # noqa: E501 + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + x = np.array([1.0, np.nan]) + + self.assertEqual(pyfunc(x, x, equal_nan=True), + cfunc(x, x, equal_nan=True)) + + def test_no_parameter_modification_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2443-L2448 # noqa: E501 + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + x = np.array([np.inf, 1]) + y = np.array([0, np.inf]) + + cfunc(x, y) + np.testing.assert_array_equal(x, np.array([np.inf, 1])) + np.testing.assert_array_equal(y, np.array([0, np.inf])) + + def test_min_int_numpy(self): + # https://github.com/numpy/numpy/blob/4adc87dff15a247e417d50f10cc4def8e1c17a03/numpy/core/tests/test_numeric.py#L2450-L2454 # noqa: E501 + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + min_int = np.iinfo(np.int_).min + a = np.array([min_int], dtype=np.int_) + + self.assertEqual(pyfunc(a, a), cfunc(a, a)) + + def test_allclose_exception(self): + self.disable_leak_check() + + pyfunc = np_allclose + cfunc = jit(nopython=True)(pyfunc) + + inps = [ + (np.asarray([1e10, 1e-9, np.nan]), + np.asarray([1.0001e10, 1e-9]), + 1e-05, 1e-08, False, + "shape mismatch: objects cannot be broadcast to a single shape", + ValueError), + ('hello', 3, False, 1e-08, False, + 'The first argument "a" must be array-like', + TypingError), + (3, 'hello', False, 1e-08, False, + 'The second argument "b" must be array-like', + TypingError), + (2, 3, False, 1e-08, False, + 'The third argument "rtol" must be a floating point', + TypingError), + (2, 3, 1e-05, False, False, + 'The fourth argument "atol" must be a floating point', + TypingError), + (2, 3, 1e-05, 1e-08, 1, + 'The fifth argument "equal_nan" must be a boolean', + TypingError), + ] + + for a, b, rtol, atol, equal_nan, exc_msg, exc in inps: + with self.assertRaisesRegex(exc, exc_msg): + cfunc(a, b, rtol, atol, equal_nan) + + def test_interp_basic(self): + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc, abs_tol=1e-10) + + x = np.linspace(-5, 5, 25) + xp = np.arange(-4, 8) + fp = xp + 1.5 + _check(params={'x': x, 'xp': xp, 'fp': fp}) + self.rnd.shuffle(x) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + self.rnd.shuffle(fp) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x[:5] = np.nan + x[-5:] = np.inf + self.rnd.shuffle(x) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + fp[:5] = np.nan + fp[-5:] = -np.inf + self.rnd.shuffle(fp) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.arange(-4, 8) + xp = x + 1 + fp = x + 2 + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = (2.2, 3.3, -5.0) + xp = (2, 3, 4) + fp = (5, 6, 7) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = ((2.2, 3.3, -5.0), (1.2, 1.3, 4.0)) + xp = np.linspace(-4, 4, 10) + fp = np.arange(-5, 5) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([1.4, np.nan, np.inf, -np.inf, 0.0, -9.1]) + x = x.reshape(3, 2, order='F') + xp = np.linspace(-4, 4, 10) + fp = np.arange(-5, 5) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + for x in range(-2, 4): + xp = [0, 1, 2] + fp = (3, 4, 5) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([]) + xp = [0, 1, 2] + fp = (3, 4, 5) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.linspace(0, 25, 60).reshape(3, 4, 5) + xp = np.arange(20) + fp = xp - 10 + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.nan + xp = np.arange(5) + fp = np.full(5, np.nan) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.nan + xp = [3] + fp = [4] + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.arange(-4, 8) + xp = x + fp = x + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = [True, False] + xp = np.arange(-4, 8) + fp = xp + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = [-np.inf, -1.0, 0.0, 1.0, np.inf] + xp = np.arange(-4, 8) + fp = xp * 2.2 + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.linspace(-10, 10, 10) + xp = np.array([-np.inf, -1.0, 0.0, 1.0, np.inf]) + fp = xp * 2.2 + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = self.rnd.randn(100) + xp = np.linspace(-3, 3, 100) + fp = np.full(100, fill_value=3.142) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + for factor in 1, -1: + x = np.array([5, 6, 7]) * factor + xp = [1, 2] + fp = [3, 4] + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = 1 + xp = [1] + fp = [True] + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + x = np.linspace(0, 1, 5) + y = np.linspace(0, 1, 5) + x0 = np.linspace(0, 1, 50) + out = cfunc(x0, x, y) + np.testing.assert_almost_equal(out, x0) + + x = np.array([1, 2, 3, 4]) + xp = np.array([1, 2, 3, 4]) + fp = np.array([1, 2, 3.01, 4]) + _check(params={'x': x, 'xp': xp, 'fp': fp}) + + xp = [1] + fp = [np.inf] + _check(params={'x': 1, 'xp': xp, 'fp': fp}) + + x = np.array([1, 2, 2.5, 3, 4]) + xp = np.array([1, 2, 3, 4]) + fp = np.array([1, 2, np.nan, 4]) + _check({'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([1, 1.5, 2, 2.5, 3, 4, 4.5, 5, 5.5]) + xp = np.array([1, 2, 3, 4, 5]) + fp = np.array([np.nan, 2, np.nan, 4, np.nan]) + _check({'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([1, 2, 2.5, 3, 4]) + xp = np.array([1, 2, 3, 4]) + fp = np.array([1, 2, np.inf, 4]) + _check({'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([1, 1.5, np.nan, 2.5, -np.inf, 4, 4.5, 5, np.inf, 0, 7]) + xp = np.array([1, 2, 3, 4, 5, 6]) + fp = np.array([1, 2, np.nan, 4, 3, np.inf]) + _check({'x': x, 'xp': xp, 'fp': fp}) + + x = np.array([3.10034867, 3.0999066, 3.10001529]) + xp = np.linspace(0, 10, 1 + 20000) + fp = np.sin(xp / 2.0) + _check({'x': x, 'xp': xp, 'fp': fp}) + + x = self.rnd.uniform(0, 2 * np.pi, (100,)) + xp = np.linspace(0, 2 * np.pi, 1000) + fp = np.cos(xp) + exact = np.cos(x) + got = cfunc(x, xp, fp) + np.testing.assert_allclose(exact, got, atol=1e-5) + + # very dense calibration + x = self.rnd.randn(10) + xp = np.linspace(-10, 10, 1000) + fp = np.ones_like(xp) + _check({'x': x, 'xp': xp, 'fp': fp}) + + # very sparse calibration + x = self.rnd.randn(1000) + xp = np.linspace(-10, 10, 10) + fp = np.ones_like(xp) + _check({'x': x, 'xp': xp, 'fp': fp}) + + def _make_some_values_non_finite(self, a): + p = a.size // 100 + np.put(a, self.rnd.choice(range(a.size), p, replace=False), np.nan) + np.put(a, self.rnd.choice(range(a.size), p, replace=False), -np.inf) + np.put(a, self.rnd.choice(range(a.size), p, replace=False), np.inf) + + def arrays(self, ndata): + # much_finer_grid + yield np.linspace(2.0, 7.0, 1 + ndata * 5) + # finer_grid + yield np.linspace(2.0, 7.0, 1 + ndata) + # similar_grid + yield np.linspace(2.1, 6.8, 1 + ndata // 2) + # coarser_grid + yield np.linspace(2.1, 7.5, 1 + ndata // 2) + # much_coarser_grid + yield np.linspace(1.1, 9.5, 1 + ndata // 5) + # finer_stretched_grid + yield np.linspace(3.1, 5.3, 1 + ndata) * 1.09 + # similar_stretched_grid + yield np.linspace(3.1, 8.3, 1 + ndata // 2) * 1.09 + # finer_compressed_grid + yield np.linspace(3.1, 5.3, 1 + ndata) * 0.91 + # similar_compressed_grid + yield np.linspace(3.1, 8.3, 1 + ndata // 2) * 0.91 + # warped_grid + yield np.linspace(3.1, 5.3, 1 + ndata // 2) + 0.3 * np.sin( + np.arange(1 + ndata / 2) * np.pi / (1 + ndata / 2)) + # very_low_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=0.5 / ndata) + # low_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=2.0 / ndata) + # med_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=5.0 / ndata) + # high_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=20.0 / ndata) + # very_high_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=50.0 / ndata) + # extreme_noise_grid + yield np.linspace(3.1, 5.3, 1 + ndata) + self.rnd.normal( + size=1 + ndata, scale=200.0 / ndata) + # random_fine_grid + yield self.rnd.rand(1 + ndata) * 9.0 + 0.6 + # random_grid + yield self.rnd.rand(1 + ndata * 2) * 4.0 + 1.3 + + def test_interp_stress_tests(self): + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + + ndata = 20000 + xp = np.linspace(0, 10, 1 + ndata) + fp = np.sin(xp / 2.0) + + for x in self.arrays(ndata): + atol = 1e-14 # using abs_tol as otherwise fails on 32bit builds + + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + # no longer require xp to be monotonically increasing + # (in keeping with numpy) even if the output might not + # be meaningful; shuffle all inputs + self.rnd.shuffle(x) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + self.rnd.shuffle(xp) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + self.rnd.shuffle(fp) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + # add some values non finite + self._make_some_values_non_finite(x) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + self._make_some_values_non_finite(xp) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + self._make_some_values_non_finite(fp) + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got, abs_tol=atol) + + @unittest.skipIf(IS_NUMPY_2 and IS_MACOS_ARM64, "NEP 50 interaction issue.") + def test_interp_complex_stress_tests(self): + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + + ndata = 2000 + xp = np.linspace(0, 10, 1 + ndata) + + real = np.sin(xp / 2.0) + real[:200] = self.rnd.choice([np.inf, -np.inf, np.nan], 200) + self.rnd.shuffle(real) + + imag = np.cos(xp / 2.0) + imag[:200] = self.rnd.choice([np.inf, -np.inf, np.nan], 200) + self.rnd.shuffle(imag) + + fp = real + 1j * imag + + for x in self.arrays(ndata): + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + np.testing.assert_allclose(expected, got, equal_nan=True) + + self.rnd.shuffle(x) + self.rnd.shuffle(xp) + self.rnd.shuffle(fp) + np.testing.assert_allclose(expected, got, equal_nan=True) + + def test_interp_exceptions(self): + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + x = np.array([1, 2, 3]) + xp = np.array([]) + fp = np.array([]) + + with self.assertRaises(ValueError) as e: + cfunc(x, xp, fp) + + msg = "array of sample points is empty" + self.assertIn(msg, str(e.exception)) + + x = 1 + xp = np.array([1, 2, 3]) + fp = np.array([1, 2]) + + with self.assertRaises(ValueError) as e: + cfunc(x, xp, fp) + + msg = "fp and xp are not of the same size." + self.assertIn(msg, str(e.exception)) + + x = 1 + xp = np.arange(6).reshape(3, 2) + fp = np.arange(6) + + with self.assertTypingError() as e: + cfunc(x, xp, fp) + + msg = "xp must be 1D" + self.assertIn(msg, str(e.exception)) + + x = 1 + xp = np.arange(6) + fp = np.arange(6).reshape(3, 2) + + with self.assertTypingError() as e: + cfunc(x, xp, fp) + + msg = "fp must be 1D" + self.assertIn(msg, str(e.exception)) + + x = 1 + 1j + xp = np.arange(6) + fp = np.arange(6) + + with self.assertTypingError() as e: + cfunc(x, xp, fp) + + complex_dtype_msg = ( + "Cannot cast array data from complex dtype " + "to float64 dtype" + ) + self.assertIn(complex_dtype_msg, str(e.exception)) + + x = 1 + xp = (np.arange(6) + 1j).astype(np.complex64) + fp = np.arange(6) + + with self.assertTypingError() as e: + cfunc(x, xp, fp) + + self.assertIn(complex_dtype_msg, str(e.exception)) + + def test_interp_non_finite_calibration(self): + # examples from + # https://github.com/numpy/numpy/issues/12951 + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + _check = partial(self._check_output, pyfunc, cfunc) + + xp = np.array([0, 1, 9, 10]) + fp = np.array([-np.inf, 0.1, 0.9, np.inf]) + x = np.array([0.2, 9.5]) + params = {'x': x, 'xp': xp, 'fp': fp} + _check(params) + + xp = np.array([-np.inf, 1, 9, np.inf]) + fp = np.array([0, 0.1, 0.9, 1]) + x = np.array([0.2, 9.5]) + params = {'x': x, 'xp': xp, 'fp': fp} + _check(params) + + def test_interp_supplemental_tests(self): + # inspired by class TestInterp + # https://github.com/numpy/numpy/blob/f5b6850f231/numpy/lib/tests/test_function_base.py # noqa: E501 + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + + for size in range(1, 10): + xp = np.arange(size, dtype=np.double) + yp = np.ones(size, dtype=np.double) + incpts = np.array([-1, 0, size - 1, size], dtype=np.double) + decpts = incpts[::-1] + + incres = cfunc(incpts, xp, yp) + decres = cfunc(decpts, xp, yp) + inctgt = np.array([1, 1, 1, 1], dtype=float) + dectgt = inctgt[::-1] + np.testing.assert_almost_equal(incres, inctgt) + np.testing.assert_almost_equal(decres, dectgt) + + x = np.linspace(0, 1, 5) + y = np.linspace(0, 1, 5) + x0 = 0 + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + x0 = 0.3 + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + x0 = np.float32(0.3) + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + x0 = np.float64(0.3) + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + x0 = np.nan + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + + x = np.linspace(0, 1, 5) + y = np.linspace(0, 1, 5) + x0 = np.array(0.3) + np.testing.assert_almost_equal(cfunc(x0, x, y), x0) + + xp = np.arange(0, 10, 0.0001) + fp = np.sin(xp) + np.testing.assert_almost_equal(cfunc(np.pi, xp, fp), 0.0) + + def test_interp_supplemental_complex_tests(self): + # inspired by class TestInterp + # https://github.com/numpy/numpy/blob/f5b6850f231/numpy/lib/tests/test_function_base.py # noqa: E501 + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + + x = np.linspace(0, 1, 5) + y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5)) * 1.0j + x0 = 0.3 + y0 = x0 + (1 + x0) * 1.0j + np.testing.assert_almost_equal(cfunc(x0, x, y), y0) + + def test_interp_float_precision_handled_per_numpy(self): + # test cases from https://github.com/numba/numba/issues/4890 + pyfunc = interp + cfunc = jit(nopython=True)(pyfunc) + dtypes = [np.float32, np.float64, np.int32, np.int64] + + for combo in itertools.combinations_with_replacement(dtypes, 3): + xp_dtype, fp_dtype, x_dtype = combo + xp = np.arange(10, dtype=xp_dtype) + fp = (xp ** 2).astype(fp_dtype) + x = np.linspace(2, 3, 10, dtype=x_dtype) + + expected = pyfunc(x, xp, fp) + got = cfunc(x, xp, fp) + self.assertPreciseEqual(expected, got) + + def test_isnat(self): + def values(): + yield np.datetime64("2016-01-01") + yield np.datetime64("NaT") + yield np.datetime64('NaT', 'ms') + yield np.datetime64('NaT', 'ns') + yield np.datetime64('2038-01-19T03:14:07') + + yield np.timedelta64('NaT', "ms") + yield np.timedelta64(34, "ms") + + for unit in ['Y', 'M', 'W', 'D', + 'h', 'm', 's', 'ms', 'us', + 'ns', 'ps', 'fs', 'as']: + yield np.array([123, -321, "NaT"], + dtype=' 5], [x, x ** 2], 0)) + # test with two tuples + test_cases.append(((x < 3, x > 5), (x, x ** 2), 0)) + # test with one list and one tuple + test_cases.append(([x < 3, x > 5], (x, x ** 2), 0)) + # test with one tuple and one list + test_cases.append(((x < 3, x > 5), [x, x ** 2], 0)) + + for condlist, choicelist, default in test_cases: + self.assertPreciseEqual(np_pyfunc(condlist, choicelist, default), + np_nbfunc(condlist, choicelist, default)) + + np_pyfunc_defaults = np_select_defaults + np_nbfunc_defaults = njit(np_select_defaults) + # check the defaults work, using whatever the last input was + self.assertPreciseEqual(np_pyfunc_defaults(condlist, choicelist), + np_nbfunc_defaults(condlist, choicelist)) + + def test_select_exception(self): + np_nbfunc = njit(np_select) + x = np.arange(10) + self.disable_leak_check() + for condlist, choicelist, default, expected_error, expected_text in [ + # Each test case below is one tuple. + # Each tuple is separated by the description of the intended error + + # passing condlist of dim zero + ([np.array(True), np.array([False, True, False])], + [np.array(1), np.arange(12).reshape(4, 3)], 0, + TypingError, "condlist arrays must be of at least dimension 1"), + # condlist and choicelist with different dimensions + ([np.array(True), np.array(False)], [np.array([1]), np.array([2])], + 0, TypingError, "condlist and choicelist elements must have the " + "same number of dimensions"), + # condlist and choicelist with different dimensions + ([np.array([True]), np.array([False])], + [np.array([[1]]), np.array([[2]])], 0, TypingError, + "condlist and choicelist elements must have the " + "same number of dimensions"), + # passing choicelist of dim zero + ([np.array(True), np.array(False)], [np.array(1), np.array(2)], 0, + TypingError, "condlist arrays must be of at least dimension 1"), + # passing an array as condlist instead of a list or tuple + (np.isnan(np.array([1, 2, 3, np.nan, 5, 7])), + np.array([1, 2, 3, np.nan, 5, 7]), 0, TypingError, + "condlist must be a List or a Tuple"), + # default is a list + ([True], [0], [0], TypingError, + "default must be a scalar"), + # condlist with ints instead of booleans + ([(x < 3).astype(int), (x > 5).astype(int)], [x, x ** 2], 0, + TypingError, "condlist arrays must contain booleans"), + # condlist and choicelist of different length + ([x > 9, x > 8, x > 7, x > 6], [x, x**2, x], 0, ValueError, + "list of cases must be same length as list of conditions"), + + # condlist contains tuples instead of arrays + # if in the future numba's np.where accepts tuples, the + # implementation of np.select should also accept them and + # the following two test cases should be normal tests + # instead of negative tests + + # test with lists of length 100 of tuples of length 1 for condlist + ([(False,)] * 100, [np.array([1])] * 100, 0, TypingError, + 'items of condlist must be arrays'), + # test with lists of length 100 of tuples of length 1 for choicelist + ([np.array([False])] * 100, [(1,)] * 100, 0, TypingError, + 'items of choicelist must be arrays'), + ]: + with self.assertRaises(expected_error) as e: + np_nbfunc(condlist, choicelist, default) + self.assertIn(expected_text, str(e.exception)) + + def test_windowing(self): + def check_window(func): + np_pyfunc = func + np_nbfunc = njit(func) + + for M in [0, 1, 5, 12]: + expected = np_pyfunc(M) + got = np_nbfunc(M) + self.assertPreciseEqual(expected, got, prec='double') + + for M in ['a', 1.1, 1j]: + with self.assertRaises(TypingError) as raises: + np_nbfunc(1.1) + self.assertIn("M must be an integer", str(raises.exception)) + + check_window(np_bartlett) + check_window(np_blackman) + check_window(np_hamming) + check_window(np_hanning) + + # Test np.kaiser separately + np_pyfunc = np_kaiser + np_nbfunc = njit(np_kaiser) + + for M in [0, 1, 5, 12]: + for beta in [0.0, 5.0, 14.0]: + expected = np_pyfunc(M, beta) + got = np_nbfunc(M, beta) + + if IS_32BITS or platform.machine() in ['ppc64le', 'aarch64']: + self.assertPreciseEqual(expected, + got, prec='double', ulps=2) + else: + self.assertPreciseEqual(expected, got, prec='double', + ulps=2) + + for M in ['a', 1.1, 1j]: + with self.assertRaises(TypingError) as raises: + np_nbfunc(M, 1.0) + self.assertIn("M must be an integer", str(raises.exception)) + + for beta in ['a', 1j]: + with self.assertRaises(TypingError) as raises: + np_nbfunc(5, beta) + self.assertIn("beta must be an integer or float", + str(raises.exception)) + + def test_cross(self): + pyfunc = np_cross + cfunc = jit(nopython=True)(pyfunc) + pairs = [ + # 3x3 (n-dims) + ( + np.array([[1, 2, 3], [4, 5, 6]]), + np.array([[4, 5, 6], [1, 2, 3]]) + ), + # 2x3 array-like (n-dims) + ( + np.array([[1, 2, 3], [4, 5, 6]]), + ((4, 5), (1, 2)) + ), + # 3x3 (1-dim) with type promotion + ( + np.array([1, 2, 3], dtype=np.int64), + np.array([4, 5, 6], dtype=np.float64) + ), + # 3x3 array-like (1-dim) + ( + (1, 2, 3), + (4, 5, 6) + ), + # 2x3 (1-dim) + ( + np.array([1, 2]), + np.array([4, 5, 6]) + ), + # 3x3 (with broadcasting 1d x 2d) + ( + np.array([1, 2, 3]), + np.array([[4, 5, 6], [1, 2, 3]]) + ), + # 3x3 (with broadcasting 2d x 1d) + ( + np.array([[1, 2, 3], [4, 5, 6]]), + np.array([1, 2, 3]) + ), + # 3x2 (with higher order broadcasting) + ( + np.arange(36).reshape(6, 2, 3), + np.arange(4).reshape(2, 2) + ) + ] + + for x, y in pairs: + expected = pyfunc(x, y) + got = cfunc(x, y) + self.assertPreciseEqual(expected, got) + + def test_cross_exceptions(self): + pyfunc = np_cross + cfunc = jit(nopython=True)(pyfunc) + self.disable_leak_check() + + # test incompatible dimensions for ndim == 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.arange(4), + np.arange(3) + ) + self.assertIn( + 'Incompatible dimensions for cross product', + str(raises.exception) + ) + + # test 2d cross product error for ndim == 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.array((1, 2)), + np.array((3, 4)) + ) + self.assertIn( + 'Dimensions for both inputs is 2.', + str(raises.exception) + ) + + self.assertIn( + '`cross2d(a, b)` from `numba.np.extensions`.', + str(raises.exception) + ) + + # test incompatible dimensions for ndim > 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.arange(8).reshape((2, 4)), + np.arange(6)[::-1].reshape((2, 3)) + ) + self.assertIn( + 'Incompatible dimensions for cross product', + str(raises.exception) + ) + + # test 2d cross product error for ndim == 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.arange(8).reshape((4, 2)), + np.arange(8)[::-1].reshape((4, 2)) + ) + self.assertIn( + 'Dimensions for both inputs is 2', + str(raises.exception) + ) + + # test non-array-like input + with self.assertRaises(TypingError) as raises: + cfunc( + set([1, 2, 3]), + set([4, 5, 6]) + ) + self.assertIn( + 'Inputs must be array-like.', + str(raises.exception) + ) + + def test_cross2d(self): + pyfunc = np_cross + cfunc = njit(nb_cross2d) + pairs = [ + # 2x2 (n-dims) + ( + np.array([[1, 2], [4, 5]]), + np.array([[4, 5], [1, 2]]) + ), + # 2x2 array-like (n-dims) + ( + np.array([[1, 2], [4, 5]]), + ((4, 5), (1, 2)) + ), + # 2x2 (1-dim) with type promotion + ( + np.array([1, 2], dtype=np.int64), + np.array([4, 5], dtype=np.float64) + ), + # 2x2 array-like (1-dim) + ( + (1, 2), + (4, 5) + ), + # 2x2 (with broadcasting 1d x 2d) + ( + np.array([1, 2]), + np.array([[4, 5], [1, 2]]) + ), + # 2x2 (with broadcasting 2d x 1d) + ( + np.array([[1, 2], [4, 5]]), + np.array([1, 2]) + ), + # 2x2 (with higher order broadcasting) + ( + np.arange(36).reshape(6, 3, 2), + np.arange(6).reshape(3, 2) + ) + ] + + for x, y in pairs: + expected = pyfunc(x, y) + got = cfunc(x, y) + self.assertPreciseEqual(expected, got) + + def test_cross2d_exceptions(self): + cfunc = njit(nb_cross2d) + self.disable_leak_check() + + # test incompatible dimensions for ndim == 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.array((1, 2, 3)), + np.array((4, 5, 6)) + ) + self.assertIn( + 'Incompatible dimensions for 2D cross product', + str(raises.exception) + ) + + # test incompatible dimensions for ndim > 1 + with self.assertRaises(ValueError) as raises: + cfunc( + np.arange(6).reshape((2, 3)), + np.arange(6)[::-1].reshape((2, 3)) + ) + self.assertIn( + 'Incompatible dimensions for 2D cross product', + str(raises.exception) + ) + + # test non-array-like input + with self.assertRaises(TypingError) as raises: + cfunc( + set([1, 2]), + set([4, 5]) + ) + self.assertIn( + 'Inputs must be array-like.', + str(raises.exception) + ) + + def test_trim_zeros(self): + + def arrays(): + yield np.array([]) + yield np.zeros(5) + yield np.zeros(1) + yield np.array([1, 2, 3]) + yield np.array([0, 1, 2, 3]) + yield np.array([0., 1., 2., np.nan, 0.]) + yield np.array(['0', 'Hello', 'world']) + + def explicit_trim(): + yield np.array([0, 1, 2, 0, 0]), 'FB' + yield np.array([0, 1, 2]), 'B' + yield np.array([np.nan, 0., 1.2, 2.3, 0.]), 'b' + yield np.array([0, 0, 1, 2, 5]), 'f' + if numpy_version < (2, 2): + # abf and d are not supported in numpy >= 2.2 + yield np.array([0, 1, 2, 0]), 'abf' + yield np.array([0, 4, 0]), 'd' + + yield np.array(['\0', '1', '2']), 'f' + + pyfunc = np_trim_zeros + cfunc = jit(nopython=True)(pyfunc) + + for arr in arrays(): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertPreciseEqual(expected, got) + + for arr, trim in explicit_trim(): + expected = pyfunc(arr, trim) + got = cfunc(arr, trim) + self.assertPreciseEqual(expected, got) + + def test_trim_zeros_numpy(self): + # https://github.com/numpy/numpy/blob/9d8d46ad615a7e13256b930146ac369f651016c0/numpy/lib/tests/test_function_base.py#L1251-L1313 + a = np.array([0, 0, 1, 0, 2, 3, 4, 0]) + b = a.astype(float) + c = a.astype(complex) + # d = a.astype(object) + values = [a, b, c] + + # test_basic + slc = np.s_[2:-1] + for arr in values: + res = np_trim_zeros(arr) + self.assertPreciseEqual(res, arr[slc]) + + # test_leading_skip + slc = np.s_[:-1] + for arr in values: + res = np_trim_zeros(arr, trim='b') + self.assertPreciseEqual(res, arr[slc]) + + # test_trailing_skip + slc = np.s_[2:] + for arr in values: + res = np_trim_zeros(arr, trim='F') + self.assertPreciseEqual(res, arr[slc]) + + # test_all_zero + for _arr in values: + arr = np.zeros_like(_arr, dtype=_arr.dtype) + + res1 = np_trim_zeros(arr, trim='B') + assert len(res1) == 0 + + res2 = np_trim_zeros(arr, trim='f') + assert len(res2) == 0 + + # test_size_zero + arr = np.zeros(0) + res = np_trim_zeros(arr) + self.assertPreciseEqual(arr, res) + + # test_overflow + for arr in [np.array([0, 2**62, 0]), np.array([0, 2**63, 0]), + np.array([0, 2**64, 0])]: + slc = np.s_[1:2] + res = np_trim_zeros(arr) + self.assertPreciseEqual(res, arr[slc]) + + # test_no_trim + arr = np.array([None, 1, None]) + res = np_trim_zeros(arr) + self.assertPreciseEqual(arr, res) + + # test_list_to_list + res = np_trim_zeros(a.tolist()) + assert isinstance(res, list) + + def test_trim_zeros_exceptions(self): + self.disable_leak_check() + cfunc = jit(nopython=True)(np_trim_zeros) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([[1, 2, 3], [4, 5, 6]])) + self.assertIn( + 'array must be 1D', + str(raises.exception) + ) + + with self.assertRaises(TypingError) as raises: + cfunc(3) + self.assertIn( + 'The first argument must be an array', + str(raises.exception) + ) + + with self.assertRaises(TypingError) as raises: + cfunc({0, 1, 2}) + self.assertIn( + 'The first argument must be an array', + str(raises.exception) + ) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([0, 1, 2]), 1) + self.assertIn( + 'The second argument must be a string', + str(raises.exception) + ) + + def test_union1d(self): + pyfunc = np_union1d + cfunc = jit(nopython=True)(pyfunc) + arrays = [ + # Test 1d arrays + ( + np.array([1, 2, 3]), + np.array([2, 3, 4]) + ), + # Test 2d with 1d array + ( + np.array([[1, 2, 3], [2, 3, 4]]), + np.array([2, 5, 6]) + ), + # Test 3d with 1d array + ( + np.arange(0, 20).reshape(2,2,5), + np.array([1, 20, 21]) + ), + # Test 2d with 3d array + ( + np.arange(0, 10).reshape(2,5), + np.arange(0, 20).reshape(2,5,2) + ), + # Test other array-like + ( + np.array([False, True, 7]), + np.array([1, 2, 3]) + ) + ] + + for a, b in arrays: + expected = pyfunc(a,b) + got = cfunc(a,b) + self.assertPreciseEqual(expected, got) + + def test_union1d_exceptions(self): + cfunc = jit(nopython=True)(np_union1d) + self.disable_leak_check() + + # Test inputs not array-like + with self.assertRaises(TypingError) as raises: + cfunc("Hello", np.array([1,2])) + self.assertIn( + "The arguments to np.union1d must be array-like", + str(raises.exception) + ) + with self.assertRaises(TypingError) as raises: + cfunc(np.array([1,2]), "Hello") + self.assertIn( + "The arguments to np.union1d must be array-like", + str(raises.exception) + ) + with self.assertRaises(TypingError) as raises: + cfunc("Hello", "World") + self.assertIn( + "The arguments to np.union1d must be array-like", + str(raises.exception) + ) + + # Test Unicode array exceptions + with self.assertRaises(TypingError) as raises: + cfunc(np.array(['hello', 'world']), np.array(['a', 'b'])) + self.assertIn( + "For Unicode arrays, arrays must have same dtype", + str(raises.exception) + ) + with self.assertRaises(TypingError) as raises: + cfunc(np.array(['c', 'd']), np.array(['foo', 'bar'])) + self.assertIn( + "For Unicode arrays, arrays must have same dtype", + str(raises.exception) + ) + with self.assertRaises(TypingError) as raises: + cfunc(np.array(['c', 'd']), np.array([1, 2])) + self.assertIn( + "For Unicode arrays, arrays must have same dtype", + str(raises.exception) + ) + with self.assertRaises(TypingError) as raises: + cfunc(np.array(['c', 'd']), np.array([1.1, 2.5])) + self.assertIn( + "For Unicode arrays, arrays must have same dtype", + str(raises.exception) + ) + + def test_asarray_chkfinite(self): + pyfunc = np_asarray_chkfinite + cfunc = jit(nopython=True)(pyfunc) + self.disable_leak_check() + + pairs = [ + #1D array with all args + ( + np.array([1, 2, 3]), + np.float32, + ), + #1D array + ( + np.array([1, 2, 3]), + ), + #1D array-like + ( + [1, 2, 3, 4], + ), + # 2x2 (n-dims) + ( + np.array([[1, 2], [3, 4]]), + np.float32, + ), + # 2x2 array-like (n-dims) + ( + ((1, 2), (3, 4)), + np.int64 + ), + # 2x2 (1-dim) with type promotion + ( + np.array([1, 2], dtype=np.int64), + ), + # 3x2 (with higher order broadcasting) + ( + np.arange(36).reshape(6, 2, 3), + ), + ] + + for pair in pairs: + expected = pyfunc(*pair) + got = cfunc(*pair) + self.assertPreciseEqual(expected, got) + + def test_asarray_chkfinite_exceptions(self): + cfunc = jit(nopython=True)(np_asarray_chkfinite) + self.disable_leak_check() + + #test for single value + with self.assertRaises(TypingError) as e: + cfunc(2) + msg = "The argument to np.asarray_chkfinite must be array-like" + self.assertIn(msg, str(e.exception)) + + #test for NaNs + with self.assertRaises(ValueError) as e: + cfunc(np.array([2, 4, np.nan, 5])) + self.assertIn("array must not contain infs or NaNs", str(e.exception)) + + #test for infs + with self.assertRaises(ValueError) as e: + cfunc(np.array([1, 2, np.inf, 4])) + self.assertIn("array must not contain infs or NaNs", str(e.exception)) + + #test for dtype + with self.assertRaises(TypingError) as e: + cfunc(np.array([1, 2, 3, 4]), 'float32') + self.assertIn("dtype must be a valid Numpy dtype", str(e.exception)) + + def test_unwrap_basic(self): + pyfunc = unwrap + cfunc = njit(pyfunc) + + pyfunc1 = unwrap1 + cfunc1 = njit(pyfunc1) + + pyfunc13 = unwrap13 + cfunc13 = njit(pyfunc13) + + pyfunc123 = unwrap123 + cfunc123 = njit(pyfunc123) + # Based on tests from https://github.com/numpy/numpy/blob/3032e84ff34f20def2ef4ebf9f8695947af3fd24/numpy/lib/tests/test_function_base.py#L1979-L2003 # noqa: E501 + # Additional tests are included to ensure proper support for + # higher dimensional arrays + + # p only + def inputs1(): + yield np.array([1, 1 + 2 * np.pi]) + phase = np.linspace(0, np.pi, num=5) + phase[3:] += np.pi + yield phase + yield np.arange(16).reshape((4,4)) + yield np.arange(160, step=10).reshape((4,4)) + yield np.arange(240, step=10).reshape((2,3,4)) + + for p in inputs1(): + self.assertPreciseEqual(pyfunc1(p), cfunc1(p)) + + uneven_seq = np.array([0, 75, 150, 225, 300, 430]) + wrap_uneven = np.mod(uneven_seq, 250) + + # p and period only + def inputs13(): + yield np.array([1, 1 + 256]), 255 + yield np.array([0, 75, 150, 225, 300]), 255 + yield np.array([0, 1, 2, -1, 0]), 4 + yield np.array([2, 3, 4, 5, 2, 3, 4, 5]), 4 + yield wrap_uneven, 250 + + # check that you can set axis=-1 without errors + self.assertPreciseEqual(pyfunc(wrap_uneven, axis=-1, period=250), + cfunc(wrap_uneven, axis=-1, period=250)) + + for p, period in inputs13(): + self.assertPreciseEqual(pyfunc13(p, period=period), + cfunc13(p, period=period)) + + # p, period and discont + def inputs123(): + yield wrap_uneven, 250, 140 + + for p, period, discont in inputs123(): + self.assertPreciseEqual(pyfunc123(p, period=period, + discont=discont), + cfunc123(p, period=period, + discont=discont)) + + def test_unwrap_exception(self): + cfunc = njit(unwrap) + self.disable_leak_check() + + with self.assertRaises(TypingError) as e: + cfunc('abc') + self.assertIn('The argument "p" must be array-like', + str(e.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.array([1, 2]), 'abc') + self.assertIn('The argument "discont" must be a scalar', + str(e.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.array([1, 2]), 3, period='abc') + self.assertIn('The argument "period" must be a scalar', + str(e.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.array([1, 2]), 3, axis='abc') + self.assertIn('The argument "axis" must be an integer', + str(e.exception)) + + with self.assertRaises(ValueError) as e: + cfunc(np.array([1, 2]), 3, axis=2) + self.assertIn('Value for argument "axis" is not supported', + str(e.exception)) + + def test_swapaxes_basic(self): + pyfunc = swapaxes + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(10) + yield np.arange(10).reshape(2, 5) + yield np.arange(60).reshape(5, 4, 3) + + for a in a_variations(): + for a1 in range(-a.ndim, a.ndim): + for a2 in range(-a.ndim, a.ndim): + expected = pyfunc(a, a1, a2) + got = cfunc(a, a1, a2) + self.assertPreciseEqual(expected, got) + + def test_swapaxes_exception(self): + pyfunc = swapaxes + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc('abc', 0, 0) + + self.assertIn('The first argument "a" must be an array', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(4), 'abc', 0) + + self.assertIn('The second argument "axis1" must be an integer', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(4), 0, 'abc') + + self.assertIn('The third argument "axis2" must be an integer', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(4), 1, 0) + + self.assertIn('np.swapaxes: Argument axis1 out of bounds', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(8).reshape(2, 4), 0, -3) + + self.assertIn('np.swapaxes: Argument axis2 out of bounds', + str(raises.exception)) + + def test_moveaxis_basic(self): + pyfunc = moveaxis + cfunc = jit(nopython=True)(pyfunc) + + a = np.arange(120).reshape(1, 2, 3, 4, 5) + + for source, destination in ( + (0, -1), + (1, 3), + ((0, 1), (-1, -2)), + ((0, 1), (-2, -1)), + ((1, -3), (-2, 4)), + ): + expected = pyfunc(a, source, destination) + got = cfunc(a, source, destination) + self.assertPreciseEqual(expected, got) + + def test_moveaxis_exception(self): + pyfunc = moveaxis + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc('abc', 0, 1) + + self.assertIn('The first argument "a" must be an array', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(4), 'abc', 0) + + self.assertIn( + 'second argument "source" must be an integer or sequence', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.arange(4), 0, 'abc') + + self.assertIn( + 'third argument "destination" must be an integer or sequence', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(4), 1, 0) + + self.assertIn('np.moveaxis: Argument source out of bounds', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(8).reshape(2, 4), (0, 1), (1, -3,)) + + self.assertIn('np.moveaxis: Argument destination out of bounds', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(8).reshape(2, 4), (0, 0), (0, 1)) + + self.assertIn('np.moveaxis: repeated axis in source argument', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.arange(8).reshape(2, 4), (0, 1), (1, -1)) + + self.assertIn('np.moveaxis: repeated axis in destination argument', + str(raises.exception)) + + def test_take_along_axis(self): + a = np.arange(24).reshape((3, 1, 4, 2)) + + # For now axis must be literal, test explicitly defined implementations + @njit + def axis_none(a, i): + return np.take_along_axis(a, i, axis=None) + + indices = np.array([1, 2], dtype=np.uint64) + self.assertPreciseEqual(axis_none(a, indices), + axis_none.py_func(a, indices)) + + def gen(axis): + @njit + def impl(a, i): + return np.take_along_axis(a, i, axis) + return impl + + for i in range(-1, a.ndim): + jfunc = gen(i) + ai = np.argsort(a, axis=i) + self.assertPreciseEqual(jfunc(a, ai), jfunc.py_func(a, ai)) + + def test_take_along_axis_broadcasting(self): + # Based on + # https://github.com/numpy/numpy/blob/v1.21.0/numpy/lib/tests/test_shape_base.py#L74-L79 + # This demonstrates that arrays are broadcast before the algorithm is + # applied. + arr = np.ones((3, 4, 1)) + ai = np.ones((1, 2, 5), dtype=np.intp) + + def gen(axis): + @njit + def impl(a, i): + return np.take_along_axis(a, i, axis) + return impl + + # Check same axis but expressed as positive/negative value + for i in (1, -2): + check = gen(i) + expected = check.py_func(arr, ai) + actual = check(arr, ai) + self.assertPreciseEqual(expected, actual) + self.assertEqual(actual.shape, (3, 2, 5)) + + def test_take_along_axis_exceptions(self): + arr2d = np.arange(8).reshape(2, 4) + # Valid indices when axis=None is passed to take_along_axis: + indices_none = np.array([0, 1], dtype=np.uint64) + indices = np.ones((2, 4), dtype=np.uint64) + + # For now axis must be literal, so we need to construct functions with + # explicit axis: + def gen(axis): + @njit + def impl(a, i): + return np.take_along_axis(a, i, axis) + return impl + + with self.assertRaises(TypingError) as raises: + gen("a")(arr2d, indices) + self.assertIn("axis must be an integer", str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(-3)(arr2d, indices) + self.assertIn("axis is out of bounds", str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(2)(arr2d, indices) + self.assertIn("axis is out of bounds", str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(None)(12, indices_none) + self.assertIn('"arr" must be an array', str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(None)(arr2d, 5) + self.assertIn('"indices" must be an array', str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(None)(arr2d, np.array([0.0, 1.0])) + self.assertIn( + 'indices array must contain integers', + str(raises.exception) + ) + + @njit + def not_literal_axis(a, i, axis): + return np.take_along_axis(a, i, axis) + + with self.assertRaises(TypingError) as raises: + not_literal_axis(arr2d, indices, 0) + self.assertIn("axis must be a literal value", str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + gen(0)(arr2d, np.array([0, 1], dtype=np.uint64)) + self.assertIn("must have the same number of dimensions", + str(raises.exception)) + + # With axis None, array's ndim is implicitly 1. + with self.assertRaises(TypingError) as raises: + gen(None)(arr2d, arr2d) + self.assertIn("must have the same number of dimensions", + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + gen(0)(arr2d, np.ones((2, 3), dtype=np.uint64)) + self.assertIn("dimensions don't match", str(raises.exception)) + # Exceptions leak references + self.disable_leak_check() + + def test_nan_to_num(self): + # Test cases are from + # https://github.com/numpy/numpy/blob/8ff45c5bb520db04af8720bf1d34a392a8d2561a/numpy/lib/tests/test_type_check.py#L350-L452 + values = [ + np.nan, + 1, + 1.1, + 1 + 1j, + complex(-np.inf, np.nan), + complex(np.nan, np.nan), + np.array([1], dtype=int), + np.array([complex(-np.inf, np.inf), complex(1, np.nan), + complex(np.nan, 1), complex(np.inf, -np.inf)]), + np.array([0.1, 1.0, 0.4]), + np.array([1, 2, 3]), + np.array([[0.1, 1.0, 0.4], [0.4, 1.2, 4.0]]), + np.array([0.1, np.nan, 0.4]), + np.array([[0.1, np.nan, 0.4], [np.nan, 1.2, 4.0]]), + np.array([-np.inf, np.nan, np.inf]), + np.array([-np.inf, np.nan, np.inf], dtype=np.float32) + ] + nans = [0.0, 10] + posinfs = [None, 1000.0] + neginfs = [None, -1000.0] + + pyfunc = nan_to_num + cfunc = njit(nan_to_num) + + for value, nan, posinf, neginf in product( + values, nans, posinfs, neginfs + ): + expected = pyfunc(value, nan=nan, posinf=posinf, neginf=neginf) + got = cfunc(value, nan=nan, posinf=posinf, neginf=neginf) + self.assertPreciseEqual(expected, got) + + def test_nan_to_num_copy_false(self): + # Check that copy=False operates in-place. + cfunc = njit(nan_to_num) + + x = np.array([0.1, 0.4, np.nan, np.inf, -np.inf]) + expected = np.array([1.0, 1000.0, -1000.0]) + cfunc( + x, + copy=False, + nan=expected[0], + posinf=expected[1], + neginf=expected[2] + ) + self.assertPreciseEqual(x[-3:], expected) + + x_complex = np.array( + [ + 0.1, + 0.4, + complex(np.nan, np.nan), + complex(np.inf, np.nan), + complex(np.nan, -np.inf) + ] + ) + cfunc( + x_complex, + copy=False, + nan=expected[0], + posinf=expected[1], + neginf=expected[2] + ) + self.assertPreciseEqual( + x_complex[-3:], + np.array([1. + 1.j, 1e3 + 1.j, 1. - 1000.j]) + ) + + def test_nan_to_num_invalid_argument(self): + cfunc = njit(nan_to_num) + + with self.assertTypingError() as raises: + cfunc("invalid_input") + self.assertIn("The first argument must be a scalar or an array-like", + str(raises.exception)) + + def test_diagflat_basic(self): + pyfunc1 = diagflat1 + cfunc1 = njit(pyfunc1) + pyfunc2 = diagflat2 + cfunc2 = njit(pyfunc2) + + def inputs(): + yield np.array([1,2]), 1 + yield np.array([[1,2],[3,4]]), -2 + yield np.arange(8).reshape((2,2,2)), 2 + yield [1, 2], 1 + yield np.array([]), 1 + + for v, k in inputs(): + self.assertPreciseEqual(pyfunc1(v), cfunc1(v)) + self.assertPreciseEqual(pyfunc2(v, k), cfunc2(v, k)) + + def test_diagflat1_exception(self): + pyfunc = diagflat1 + cfunc = njit(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + self.assertIn('The argument "v" must be array-like', + str(raises.exception)) + + def test_diagflat2_exception(self): + pyfunc = diagflat2 + cfunc = njit(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", 2) + self.assertIn('The argument "v" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc([1, 2], "abc") + self.assertIn('The argument "k" must be an integer', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc([1, 2], 3.0) + self.assertIn('The argument "k" must be an integer', + str(raises.exception)) + + @staticmethod + def _setxor_arrays(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons - xor == union + yield [1], [1] # singletons - xor == nothing + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2, 2], [2, 2, 3] + yield [1, 2], [2, 1] + yield [1, 2, 3], [1, 2, 3] + yield [2, 3, 4, 0], [1, 3] + # from numpy: + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L86 # noqa: E501 + yield [5, 7, 1, 2], [2, 4, 3, 1, 5] + yield [1, 2, 3], [6, 5, 4] + yield [1, 8, 2, 3], [1, 2, 3, 4, 5, 6] + + def test_setxor1d_2(self): + np_pyfunc = np_setxor1d_2 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2) + got = np_nbfunc(ar1, ar2) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._setxor_arrays(): + check(a, b) + + def test_setxor1d_3(self): + np_pyfunc = np_setxor1d_3 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2, assume_unique) + got = np_nbfunc(ar1, ar2, assume_unique) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._setxor_arrays(): + check(a, b) + if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b): + check(a, b, True) + + def test_setxor1d_errors(self): + np_pyfunc = np_setxor1d_3 + np_nbfunc = njit(np_pyfunc) + + a = np.array([1]) + b = np.array([2]) + self.disable_leak_check() + with self.assertRaises(TypingError): + np_nbfunc(a, b, "foo") + with self.assertRaises(TypingError): + np_nbfunc("foo", b, True) + with self.assertRaises(TypingError): + np_nbfunc(a, "foo", True) + + @staticmethod + def _setdiff_arrays(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons - diff == [1] + yield [1], [1] # singletons - diff == nothing + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2, 2], [2, 2, 3] + yield [1, 2], [2, 1] + yield [1, 2, 3], [1, 2, 3] + yield [2, 3, 4, 0], [1, 3] + + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L558 # noqa: E501 + yield (np.array([6, 5, 4, 7, 1, 2, 7, 4]), + np.array([2, 4, 3, 3, 2, 1, 5])) + yield np.arange(21), np.arange(19) + yield np.array([3, 2, 1]), np.array([7, 5, 2]) + + def test_setdiff1d_2(self): + np_pyfunc = np_setdiff1d_2 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2) + got = np_nbfunc(ar1, ar2) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._setdiff_arrays(): + check(a, b) + + def test_setdiff1d_3(self): + np_pyfunc = np_setdiff1d_3 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2, assume_unique) + got = np_nbfunc(ar1, ar2, assume_unique) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._setdiff_arrays(): + check(a, b) + if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b): + check(a, b, True) + + def test_setdiff1d_errors(self): + np_pyfunc = np_setdiff1d_3 + np_nbfunc = njit(np_pyfunc) + + a = np.array([1]) + b = np.array([2]) + self.disable_leak_check() + with self.assertRaises(TypingError): + np_nbfunc(a, b, "foo") + with self.assertRaises(TypingError): + np_nbfunc("foo", b, True) + with self.assertRaises(TypingError): + np_nbfunc(a, "foo", True) + + @staticmethod + def _in1d_arrays(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons - False + yield [1], [1] # singletons - True + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2, 2], [2, 2, 3] + yield [1, 2], [2, 1] + yield [1, 2, 3], [1, 2, 3] + yield [2, 3, 4, 0], [3, 1] + yield [2, 3], np.arange(20) # Test the "sorting" method. + yield [2, 3], np.tile(np.arange(5), 4) + + @unittest.skipIf(numpy_version >= (2, 4), "np.in1d removed in NumPy 2.4+") + def test_in1d_2(self): + np_pyfunc = np_in1d_2 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2) + got = np_nbfunc(ar1, ar2) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._in1d_arrays(): + check(a, b) + + @unittest.skipIf(numpy_version >= (2, 4), "np.in1d removed in NumPy 2.4+") + def test_in1d_3a(self): + np_pyfunc = np_in1d_3a + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2, assume_unique) + got = np_nbfunc(ar1, ar2, assume_unique) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._in1d_arrays(): + check(a, b) + if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b): + check(a, b, assume_unique=True) + + @unittest.skipIf(numpy_version >= (2, 4), "np.in1d removed in NumPy 2.4+") + def test_in1d_3b(self): + np_pyfunc = np_in1d_3b + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, invert=False): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2, invert) + got = np_nbfunc(ar1, ar2, invert) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._in1d_arrays(): + check(a, b, invert=False) + check(a, b, invert=True) + + @unittest.skipIf(numpy_version >= (2, 4), "np.in1d removed in NumPy 2.4+") + def test_in1d_4(self): + np_pyfunc = np_in1d_4 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False, invert=False): + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + expected = np_pyfunc(ar1, ar2, assume_unique, invert) + got = np_nbfunc(ar1, ar2, assume_unique, invert) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._in1d_arrays(): + check(a, b, invert=False) + check(a, b, invert=True) + if len(np.unique(a)) == len(a) and len(np.unique(b)) == len(b): + check(a, b, assume_unique=True, invert=False) + check(a, b, assume_unique=True, invert=True) + + @unittest.skipIf(numpy_version >= (2, 4), "np.in1d removed in NumPy 2.4+") + def test_in1d_errors(self): + np_pyfunc = np_in1d_4 + np_nbfunc = njit(np_pyfunc) + + a = np.array([1]) + b = np.array([2]) + x = np_nbfunc(a, b) + self.assertPreciseEqual(x, np.array([False])) + + self.disable_leak_check() + with self.assertRaises(TypingError): + np_nbfunc(a, b, "foo", False) + with self.assertRaises(TypingError): + np_nbfunc(a, b, False, "foo") + with self.assertRaises(TypingError): + np_nbfunc("foo", b, True, False) + with self.assertRaises(TypingError): + np_nbfunc(a, "foo", True, False) + + @njit() + def np_in1d_kind(a, b, kind): + return np.in1d(a, b, kind=kind) + + with self.assertRaises(TypingError): + np_in1d_kind(a, b, kind=None) + with self.assertRaises(TypingError): + np_in1d_kind(a, b, kind="table") + + @classmethod + def _isin_arrays(cls): + if REDUCED_TESTING: + return cls._isin_arrays_reduced() + else: + return cls._isin_arrays_full() + + @staticmethod + def _isin_arrays_reduced(): + # Minimal test cases for memory optimization + yield [1], [1] # singletons - True + yield [1], [2] # singletons - False + yield [2, 3], [3, 4] # basic arrays + + # One numpy array test + a = np.arange(4).reshape([2, 2]) + b = np.array([2, 3]) + yield a, b + + @staticmethod + def _isin_arrays_full(): + yield (List.empty_list(types.float64), + List.empty_list(types.float64)) # two empty arrays + yield (np.zeros((1, 0), dtype=np.int64), + List.empty_list(types.int64)) # two-dim array - shape (1, 0) + yield (np.zeros((0, 0), dtype=np.int64), + List.empty_list(types.int64)) + yield (np.zeros((0, 1), dtype=np.int64), + List.empty_list(types.int64)) + yield [1], List.empty_list(types.float64) # empty right + yield List.empty_list(types.float64), [1] # empty left + yield [1], [2] # singletons - False + yield [1], [1] # singletons - True + yield [1, 2], [1] + yield [1, 2, 2], [2, 2] + yield [1, 2, 2], [2, 2, 3] + yield [1, 2], [2, 1] + yield [2, 3], np.arange(20) # Test the "sorting" method. + yield [2, 3], np.tile(np.arange(5), 4) + yield np.arange(30).reshape(2, 3, 5), [5, 7, 10, 15] # 3d + + # from numpy + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L200 # noqa: E501 + a = np.arange(24).reshape([2, 3, 4]) + b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]]) + yield a, b + yield np.array(3), b + yield a, np.array(3) + yield np.array(3), np.array(3) + yield 5, b + yield a, 6 + yield 5, 6 + yield List.empty_list(types.int64), b + yield a, List.empty_list(types.int64) + + for dtype in [bool, np.int64, np.float64]: + if dtype in {np.int64, np.float64}: + ar = np.array([10, 20, 30], dtype=dtype) + elif dtype in {bool}: + ar = np.array([True, False, False]) + + empty_array = np.array([], dtype=dtype) + + yield empty_array, ar + yield ar, empty_array + yield empty_array, empty_array + + for mult in (1, 10): + yield [5, 7, 1, 2], [2, 4, 3, 1, 5] * mult + yield [8, 7, 1, 2], [2, 4, 3, 1, 5] * mult + yield [4, 7, 1, 8], [2, 4, 3, 1, 5] * mult + a = [5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5] + yield a, [2, 3, 4] * mult + yield a, [2, 3, 4] * mult + [5, 5, 4] * mult + yield np.array([5, 7, 1, 2]), np.array([2, 4, 3, 1, 5] * mult) + yield np.array([5, 7, 1, 1, 2]), np.array([2, 4, 3, 3, 1, 5] * mult) + yield np.array([5, 5]), np.array([2, 2] * mult) + + yield np.array([5]), np.array([2]) + yield np.array([True, False]), np.array([False, False, False]) + + for dtype1, dtype2 in [ + (np.int8, np.int16), + (np.int16, np.int8), + (np.uint8, np.uint16), + (np.uint16, np.uint8), + (np.uint8, np.int16), + (np.int16, np.uint8), + ]: + is_dtype2_signed = np.issubdtype(dtype2, np.signedinteger) + ar1 = np.array([0, 0, 1, 1], dtype=dtype1) + + if is_dtype2_signed: + ar2 = np.array([-128, 0, 127], dtype=dtype2) + else: + ar2 = np.array([127, 0, 255], dtype=dtype2) + + yield ar1, ar2 + + for dtype in np.typecodes["AllInteger"]: + a = np.array([True, False, False], dtype=bool) + b = np.array([0, 0, 0, 0], dtype=dtype) + yield a, b + yield b, a + + def test_isin_2(self): + np_pyfunc = np_isin_2 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2): + expected = np_pyfunc(ar1, ar2) + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + got = np_nbfunc(ar1, ar2) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._isin_arrays(): + check(a, b) + + @skip_if_reduced_testing + def test_isin_3a(self): + np_pyfunc = np_isin_3a + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False): + expected = np_pyfunc(ar1, ar2, assume_unique) + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + got = np_nbfunc(ar1, ar2, assume_unique) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._isin_arrays(): + check(a, b) + + try: + len_a = len(a) + except TypeError: + len_a = 1 + try: + len_b = len(b) + except TypeError: + len_b = 1 + if len(np.unique(a)) == len_a and len(np.unique(b)) == len_b: + check(a, b, assume_unique=True) + + @skip_if_reduced_testing + def test_isin_3b(self): + np_pyfunc = np_isin_3b + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, invert=False): + expected = np_pyfunc(ar1, ar2, invert) + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + got = np_nbfunc(ar1, ar2, invert) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._isin_arrays(): + check(a, b, invert=False) + check(a, b, invert=True) + + @skip_if_reduced_testing + def test_isin_4(self): + np_pyfunc = np_isin_4 + np_nbfunc = njit(np_pyfunc) + + def check(ar1, ar2, assume_unique=False, invert=False): + expected = np_pyfunc(ar1, ar2, assume_unique, invert) + if isinstance(ar1, list): + ar1 = List(ar1) + if isinstance(ar2, list): + ar2 = List(ar2) + got = np_nbfunc(ar1, ar2, assume_unique, invert) + self.assertPreciseEqual(expected, got, msg=f"ar1={ar1}, ar2={ar2}") + + for a, b in self._isin_arrays(): + check(a, b, invert=False) + check(a, b, invert=True) + + try: + len_a = len(a) + except TypeError: + len_a = 1 + try: + len_b = len(b) + except TypeError: + len_b = 1 + if len(np.unique(a)) == len_a and len(np.unique(b)) == len_b: + check(a, b, assume_unique=True, invert=False) + check(a, b, assume_unique=True, invert=True) + + def test_isin_errors(self): + np_pyfunc = np_isin_4 + np_nbfunc = njit(np_pyfunc) + + a = np.array([1]) + b = np.array([2]) + x = np_nbfunc(a, b) + self.assertPreciseEqual(x, np.array([False])) + + self.disable_leak_check() + with self.assertRaises(TypingError): + np_nbfunc(a, b, "foo", False) + with self.assertRaises(TypingError): + np_nbfunc(a, b, False, "foo") + with self.assertRaises(TypingError): + np_nbfunc("foo", b, True, False) + with self.assertRaises(TypingError): + np_nbfunc(a, "foo", True, False) + + @njit() + def np_isin_kind(a, b, kind): + return np.isin(a, b, kind=kind) + + with self.assertRaises(TypingError): + np_isin_kind(a, b, kind=None) + with self.assertRaises(TypingError): + np_isin_kind(a, b, kind="table") + + def test_setops_manyways(self): + # https://github.com/numpy/numpy/blob/b0371ef240560e78b651a5d7c9407ae3212a3d56/numpy/lib/tests/test_arraysetops.py#L588 # noqa: E501 + nb_setxor1d = njit(np_setxor1d_2) + nb_intersect1d = njit(intersect1d_2) + nb_union1d = njit(np_union1d) + nb_setdiff1d = njit(np_setdiff1d_2) + + a = np.array([5, 7, 1, 2, 8]) + b = np.array([9, 8, 2, 4, 3, 1, 5]) + + c1 = nb_setxor1d(a, b) + aux1 = nb_intersect1d(a, b) + aux2 = nb_union1d(a, b) + c2 = nb_setdiff1d(aux2, aux1) + self.assertPreciseEqual(c1, c2) + + +class TestNPMachineParameters(TestCase): + # tests np.finfo, np.iinfo, np.MachAr + + template = ''' +def foo(): + ty = np.%s + return np.%s(ty) +''' + + def check(self, func, attrs, *args): + pyfunc = func + cfunc = jit(nopython=True)(pyfunc) + + expected = pyfunc(*args) + got = cfunc(*args) + + # check result + for attr in attrs: + self.assertPreciseEqual(getattr(expected, attr), + getattr(got, attr)) + + def create_harcoded_variant(self, basefunc, ty): + #create an instance of using the function with a hardcoded type + #and eval it into existence, return the function for use + tystr = ty.__name__ + basestr = basefunc.__name__ + funcstr = self.template % (tystr, basestr) + dct = {} + exec(compile(funcstr, '', 'exec'), globals(), dct) + return dct['foo'] + + @unittest.skipIf(numpy_version >= (1, 24), "NumPy < 1.24 required") + def test_MachAr(self): + attrs = ('ibeta', 'it', 'machep', 'eps', 'negep', 'epsneg', 'iexp', + 'minexp', 'xmin', 'maxexp', 'xmax', 'irnd', 'ngrd', + 'epsilon', 'tiny', 'huge', 'precision', 'resolution',) + self.check(machar, attrs) + + def test_finfo(self): + types = [np.float32, np.float64, np.complex64, np.complex128] + attrs = ('eps', 'epsneg', 'iexp', 'machep', 'max', 'maxexp', 'negep', + 'nexp', 'nmant', 'precision', 'resolution', 'tiny', 'bits',) + for ty in types: + self.check(finfo, attrs, ty(1)) + hc_func = self.create_harcoded_variant(np.finfo, ty) + self.check(hc_func, attrs) + + # check unsupported attr raises + with self.assertRaises(TypingError) as raises: + cfunc = jit(nopython=True)(finfo_machar) + cfunc(7.) + msg = "Unknown attribute 'machar' of type finfo" + self.assertIn(msg, str(raises.exception)) + + # check invalid type raises + with self.assertTypingError(): + cfunc = jit(nopython=True)(finfo) + cfunc(np.int32(7)) + + def test_iinfo(self): + # check types and instances of types + types = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, + np.uint32, np.uint64] + attrs = ('min', 'max', 'bits',) + for ty in types: + self.check(iinfo, attrs, ty(1)) + hc_func = self.create_harcoded_variant(np.iinfo, ty) + self.check(hc_func, attrs) + + # check invalid type raises + with self.assertTypingError(): + cfunc = jit(nopython=True)(iinfo) + cfunc(np.float64(7)) + + @unittest.skipUnless(numpy_version < (1, 24), "Needs NumPy < 1.24") + @TestCase.run_test_in_subprocess + def test_np_MachAr_deprecation_np122(self): + # Tests that Numba is replaying the NumPy 1.22 deprecation warning + # raised on the getattr of 'MachAr' on the NumPy module. + # Needs to be run in a subprocess as the warning is generated from the + # typing part of the `np.MachAr` overload, which may already have been + # executed for the given types and so an empty in memory cache is + # needed. + msg = r'.*`np.MachAr` is deprecated \(NumPy 1.22\)' + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('ignore') # override warning behavior + warnings.filterwarnings("always", message=msg, + category=NumbaDeprecationWarning,) + f = njit(lambda : np.MachAr().eps) + f() + + self.assertEqual(len(w), 1) + self.assertIn('`np.MachAr` is deprecated', str(w[0])) + + +class TestRegistryImports(TestCase): + + def test_unsafe_import_in_registry(self): + # See 8940 + # This should not fail + code = dedent(""" + import numba + import numpy as np + @numba.njit + def foo(): + np.array([1 for _ in range(1)]) + foo() + print("OK") + """) + result, error = run_in_subprocess(code) + # Assert that the bytestring "OK" was printed to stdout + self.assertEqual(b"OK", result.strip()) + self.assertEqual(b"", error.strip(), msg=f"--ERROR--\n{error}\n") + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1e1043ebb999254c1b1847423e1a9b4ab1d039 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt.py @@ -0,0 +1,856 @@ +import math +import os +import platform +import sys +import re + +import numpy as np + +from numba import njit +from numba.core import types +from numba.core.runtime import ( + rtsys, + nrtopt, + _nrt_python, + nrt, +) +from numba.core.extending import intrinsic, include_path +from numba.core.typing import signature +from numba.core.imputils import impl_ret_untracked +from llvmlite import ir +import llvmlite.binding as llvm +from numba.core.unsafe.nrt import NRT_get_api + +from numba.tests.support import (EnableNRTStatsMixin, TestCase, temp_directory, + import_dynamic, skip_if_32bit, + skip_unless_cffi, run_in_subprocess) +from numba.core.registry import cpu_target +import unittest + + +linux_only = unittest.skipIf(not sys.platform.startswith('linux'), + 'linux only test') +x86_only = unittest.skipIf(platform.machine() not in ('i386', 'x86_64'), + 'x86 only test') + + +class Dummy(object): + alive = 0 + + def __init__(self): + type(self).alive += 1 + + def __del__(self): + type(self).alive -= 1 + + +class TestNrtMemInfoNotInitialized(unittest.TestCase): + """ + Unit test for checking the use of the NRT fails if the + initialization sequence has not been run. + """ + _numba_parallel_test_ = False + + def test_init_fail(self): + methods = {'library': (), + 'meminfo_new': ((), ()), + 'meminfo_alloc': ((),), + } + + for meth, args in methods.items(): + try: + with self.assertRaises(RuntimeError) as raises: + rtsys._init = False + fn = getattr(rtsys, meth) + fn(*args) + + msg = "Runtime must be initialized before use." + self.assertIn(msg, str(raises.exception)) + finally: + rtsys._init = True + + +class TestNrtMemInfo(unittest.TestCase): + """ + Unit test for core MemInfo functionality + """ + + def setUp(self): + # Reset the Dummy class + Dummy.alive = 0 + # initialize the NRT (in case the tests are run in isolation) + rtsys.initialize(cpu_target.target_context) + super(TestNrtMemInfo, self).setUp() + + def test_meminfo_refct_1(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + del d + self.assertEqual(Dummy.alive, 1) + mi.acquire() + self.assertEqual(mi.refcount, 2) + self.assertEqual(Dummy.alive, 1) + mi.release() + self.assertEqual(mi.refcount, 1) + del mi + self.assertEqual(Dummy.alive, 0) + + def test_meminfo_refct_2(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + del d + self.assertEqual(Dummy.alive, 1) + for ct in range(100): + mi.acquire() + self.assertEqual(mi.refcount, 1 + 100) + self.assertEqual(Dummy.alive, 1) + for _ in range(100): + mi.release() + self.assertEqual(mi.refcount, 1) + del mi + self.assertEqual(Dummy.alive, 0) + + def test_fake_memoryview(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + mview = memoryview(mi) + self.assertEqual(mi.refcount, 1) + self.assertEqual(addr, mi.data) + self.assertFalse(mview.readonly) + self.assertIs(mi, mview.obj) + self.assertTrue(mview.c_contiguous) + self.assertEqual(mview.itemsize, 1) + self.assertEqual(mview.ndim, 1) + del d + del mi + + self.assertEqual(Dummy.alive, 1) + del mview + self.assertEqual(Dummy.alive, 0) + + def test_memoryview(self): + from ctypes import c_uint32, c_void_p, POINTER, cast + + dtype = np.dtype(np.uint32) + bytesize = dtype.itemsize * 10 + mi = rtsys.meminfo_alloc(bytesize, safe=True) + addr = mi.data + c_arr = cast(c_void_p(mi.data), POINTER(c_uint32 * 10)) + # Check 0xCB-filling + for i in range(10): + self.assertEqual(c_arr.contents[i], 0xcbcbcbcb) + + # Init array with ctypes + for i in range(10): + c_arr.contents[i] = i + 1 + mview = memoryview(mi) + self.assertEqual(mview.nbytes, bytesize) + self.assertFalse(mview.readonly) + self.assertIs(mi, mview.obj) + self.assertTrue(mview.c_contiguous) + self.assertEqual(mview.itemsize, 1) + self.assertEqual(mview.ndim, 1) + del mi + arr = np.ndarray(dtype=dtype, shape=mview.nbytes // dtype.itemsize, + buffer=mview) + del mview + # Modify array with NumPy + np.testing.assert_equal(np.arange(arr.size) + 1, arr) + + arr += 1 + + # Check value reflected in ctypes + for i in range(10): + self.assertEqual(c_arr.contents[i], i + 2) + + self.assertEqual(arr.ctypes.data, addr) + del arr + # At this point the memory is zero filled + # We can't check this deterministically because the memory could be + # consumed by another thread. + + def test_buffer(self): + from ctypes import c_uint32, c_void_p, POINTER, cast + + dtype = np.dtype(np.uint32) + bytesize = dtype.itemsize * 10 + mi = rtsys.meminfo_alloc(bytesize, safe=True) + self.assertEqual(mi.refcount, 1) + addr = mi.data + c_arr = cast(c_void_p(addr), POINTER(c_uint32 * 10)) + # Check 0xCB-filling + for i in range(10): + self.assertEqual(c_arr.contents[i], 0xcbcbcbcb) + + # Init array with ctypes + for i in range(10): + c_arr.contents[i] = i + 1 + + arr = np.ndarray(dtype=dtype, shape=bytesize // dtype.itemsize, + buffer=mi) + self.assertEqual(mi.refcount, 1) + del mi + # Modify array with NumPy + np.testing.assert_equal(np.arange(arr.size) + 1, arr) + + arr += 1 + + # Check value reflected in ctypes + for i in range(10): + self.assertEqual(c_arr.contents[i], i + 2) + + self.assertEqual(arr.ctypes.data, addr) + del arr + # At this point the memory is zero filled + # We can't check this deterministically because the memory could be + # consumed by another thread. + + @skip_if_32bit + def test_allocate_invalid_size(self): + # Checks that attempting to allocate too big a region fails gracefully. + size = types.size_t.maxval // 8 // 2 + for pred in (True, False): + with self.assertRaises(MemoryError) as raises: + rtsys.meminfo_alloc(size, safe=pred) + self.assertIn(f"Requested allocation of {size} bytes failed.", + str(raises.exception)) + + def test_allocate_negative_size(self): + # Checks that attempting to allocate negative number of bytes fails + # gracefully. + size = -10 + for pred in (True, False): + with self.assertRaises(ValueError) as raises: + rtsys.meminfo_alloc(size, safe=pred) + msg = f"Cannot allocate a negative number of bytes: {size}." + self.assertIn(msg, str(raises.exception)) + + +class TestTracemalloc(unittest.TestCase): + """ + Test NRT-allocated memory can be tracked by tracemalloc. + """ + + def measure_memory_diff(self, func): + try: + import tracemalloc + except ImportError: + self.skipTest("tracemalloc not available") + tracemalloc.start() + try: + before = tracemalloc.take_snapshot() + # Keep the result and only delete it after taking a snapshot + res = func() + after = tracemalloc.take_snapshot() + del res + return after.compare_to(before, 'lineno') + finally: + tracemalloc.stop() + + def test_snapshot(self): + N = 1000000 + dtype = np.int8 + + @njit + def alloc_nrt_memory(): + """ + Allocate and return a large array. + """ + return np.empty(N, dtype) + + def keep_memory(): + return alloc_nrt_memory() + + def release_memory(): + alloc_nrt_memory() + + alloc_lineno = keep_memory.__code__.co_firstlineno + 1 + + # Warmup JIT + alloc_nrt_memory() + + # The large NRT-allocated array should appear topmost in the diff + diff = self.measure_memory_diff(keep_memory) + stat = diff[0] + # There is a slight overhead, so the allocated size won't exactly be N + self.assertGreaterEqual(stat.size, N) + self.assertLess(stat.size, N * 1.015, + msg=("Unexpected allocation overhead encountered. " + "May be due to difference in CPython " + "builds or running under coverage")) + frame = stat.traceback[0] + self.assertEqual(os.path.basename(frame.filename), "test_nrt.py") + self.assertEqual(frame.lineno, alloc_lineno) + + # If NRT memory is released before taking a snapshot, it shouldn't + # appear. + diff = self.measure_memory_diff(release_memory) + stat = diff[0] + # Something else appears, but nothing the magnitude of N + self.assertLess(stat.size, N * 0.01) + + +class TestNRTIssue(TestCase): + def test_issue_with_refct_op_pruning(self): + """ + GitHub Issue #1244 https://github.com/numba/numba/issues/1244 + """ + @njit + def calculate_2D_vector_mag(vector): + x, y = vector + + return math.sqrt(x ** 2 + y ** 2) + + @njit + def normalize_2D_vector(vector): + normalized_vector = np.empty(2, dtype=np.float64) + + mag = calculate_2D_vector_mag(vector) + x, y = vector + + normalized_vector[0] = x / mag + normalized_vector[1] = y / mag + + return normalized_vector + + @njit + def normalize_vectors(num_vectors, vectors): + normalized_vectors = np.empty((num_vectors, 2), dtype=np.float64) + + for i in range(num_vectors): + vector = vectors[i] + + normalized_vector = normalize_2D_vector(vector) + + normalized_vectors[i, 0] = normalized_vector[0] + normalized_vectors[i, 1] = normalized_vector[1] + + return normalized_vectors + + num_vectors = 10 + test_vectors = np.random.random((num_vectors, 2)) + got = normalize_vectors(num_vectors, test_vectors) + expected = normalize_vectors.py_func(num_vectors, test_vectors) + + np.testing.assert_almost_equal(expected, got) + + def test_incref_after_cast(self): + # Issue #1427: when casting a value before returning it, the + # cast result should be incref'ed, not the original value. + def f(): + return 0.0, np.zeros(1, dtype=np.int32) + + # Note the return type isn't the same as the tuple type above: + # the first element is a complex rather than a float. + cfunc = njit((types.Tuple((types.complex128, + types.Array(types.int32, 1, 'C') )))())(f) + z, arr = cfunc() + self.assertPreciseEqual(z, 0j) + self.assertPreciseEqual(arr, np.zeros(1, dtype=np.int32)) + + def test_refct_pruning_issue_1511(self): + @njit + def f(): + a = np.ones(10, dtype=np.float64) + b = np.ones(10, dtype=np.float64) + return a, b[:] + + a, b = f() + np.testing.assert_equal(a, b) + np.testing.assert_equal(a, np.ones(10, dtype=np.float64)) + + def test_refct_pruning_issue_1526(self): + @njit + def udt(image, x, y): + next_loc = np.where(image == 1) + + if len(next_loc[0]) == 0: + y_offset = 1 + x_offset = 1 + else: + y_offset = next_loc[0][0] + x_offset = next_loc[1][0] + + next_loc_x = (x - 1) + x_offset + next_loc_y = (y - 1) + y_offset + + return next_loc_x, next_loc_y + + a = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 0, 0]]) + expect = udt.py_func(a, 1, 6) + got = udt(a, 1, 6) + + self.assertEqual(expect, got) + + @TestCase.run_test_in_subprocess + def test_no_nrt_on_njit_decoration(self): + # Checks that the NRT is not initialized/compiled as a result of + # decorating a function with `@njit`. + from numba import njit + + # check the NRT is not initialized. + self.assertFalse(rtsys._init) + + # decorate + @njit + def foo(): + return 123 + + # check the NRT is still not initialized + self.assertFalse(rtsys._init) + + # execute + self.assertEqual(foo(), foo.py_func()) + + # check the NRT is still now initialized as execution has definitely + # occurred. + self.assertTrue(rtsys._init) + + +class TestRefCtPruning(unittest.TestCase): + + sample_llvm_ir = ''' +define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr { +entry: +tail call void @NRT_incref(i8* %arg.xs.0) +tail call void @NRT_incref(i8* %arg.ys.0) +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) +%.251 = icmp sgt i64 %arg.xs.5.0, 0 +br i1 %.251, label %B42.preheader, label %B160 + +B42.preheader: ; preds = %entry +%0 = add i64 %arg.xs.5.0, 1 +br label %B42 + +B42: ; preds = %B40.backedge, %B42.preheader +%lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ] +%lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ] +%lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ] +%.381 = load double, double* %lsr.iv1, align 8 +%.420 = load double, double* %lsr.iv, align 8 +%.458 = fcmp ole double %.381, %arg.bounds.1 +%not..432 = fcmp oge double %.381, %arg.bounds.0 +%"$phi82.1.1" = and i1 %.458, %not..432 +br i1 %"$phi82.1.1", label %B84, label %B40.backedge + +B84: ; preds = %B42 +%.513 = fcmp ole double %.420, %arg.bounds.3 +%not..487 = fcmp oge double %.420, %arg.bounds.2 +%"$phi106.1.1" = and i1 %.513, %not..487 +br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge + +B160: ; preds = %B40.backedge, %entry +tail call void @NRT_decref(i8* %arg.ys.0) +tail call void @NRT_decref(i8* %arg.xs.0) +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) +store i8* null, i8** %retptr, align 8 +ret i32 0 + +B108.endif.endif.endif: ; preds = %B84 +%.575 = fmul double %.381, %arg.vt.0 +%.583 = fadd double %.575, %arg.vt.1 +%.590 = fptosi double %.583 to i64 +%.630 = fmul double %.420, %arg.vt.2 +%.638 = fadd double %.630, %arg.vt.3 +%.645 = fptosi double %.638 to i64 +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) ; GONE 1 +tail call void @NRT_decref(i8* null) ; GONE 2 +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3 +%.62.i.i = icmp slt i64 %.645, 0 +%.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0 +%.64.i.i = add i64 %.63.i.i, %.645 +%.65.i.i = icmp slt i64 %.590, 0 +%.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0 +%.67.i.i = add i64 %.66.i.i, %.590 +%.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1 +%.87.i.i = add i64 %.67.i.i, %.84.i.i +%.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i +%.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3 +%.99.i.i = add i32 %.89.i.i, 1 +store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3 +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4 +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) ; GONE 5 +br label %B40.backedge + +B40.backedge: ; preds = %B108.endif.endif.endif, %B84, %B42 +%scevgep = getelementptr double, double* %lsr.iv, i64 1 +%scevgep2 = getelementptr double, double* %lsr.iv1, i64 1 +%lsr.iv.next = add i64 %lsr.iv3, -1 +%.294 = icmp sgt i64 %lsr.iv.next, 1 +br i1 %.294, label %B42, label %B160 +} + ''' # noqa + + def test_refct_pruning_op_recognize(self): + input_ir = self.sample_llvm_ir + input_lines = list(input_ir.splitlines()) + before_increfs = [ln for ln in input_lines if 'NRT_incref' in ln] + before_decrefs = [ln for ln in input_lines if 'NRT_decref' in ln] + + # prune + output_ir = nrtopt._remove_redundant_nrt_refct(input_ir) + output_lines = list(output_ir.splitlines()) + after_increfs = [ln for ln in output_lines if 'NRT_incref' in ln] + after_decrefs = [ln for ln in output_lines if 'NRT_decref' in ln] + + # check + self.assertNotEqual(before_increfs, after_increfs) + self.assertNotEqual(before_decrefs, after_decrefs) + + pruned_increfs = set(before_increfs) - set(after_increfs) + pruned_decrefs = set(before_decrefs) - set(after_decrefs) + + # the symm difference == or-combined + combined = pruned_increfs | pruned_decrefs + self.assertEqual(combined, pruned_increfs ^ pruned_decrefs) + pruned_lines = '\n'.join(combined) + + # all GONE lines are pruned + for i in [1, 2, 3, 4, 5]: + gone = '; GONE {}'.format(i) + self.assertIn(gone, pruned_lines) + # no other lines + self.assertEqual(len(list(pruned_lines.splitlines())), len(combined)) + + @unittest.skip("Pass removed as it was buggy. Re-enable when fixed.") + def test_refct_pruning_with_branches(self): + '''testcase from #2350''' + @njit + def _append_non_na(x, y, agg, field): + if not np.isnan(field): + agg[y, x] += 1 + + @njit + def _append(x, y, agg, field): + if not np.isnan(field): + if np.isnan(agg[y, x]): + agg[y, x] = field + else: + agg[y, x] += field + + @njit + def append(x, y, agg, field): + _append_non_na(x, y, agg, field) + _append(x, y, agg, field) + + # Disable python wrapper to avoid detecting necessary + # refcount inside it + @njit(no_cpython_wrapper=True) + def extend(arr, field): + for i in range(arr.shape[0]): + for j in range(arr.shape[1]): + append(j, i, arr, field) + + # Compile + extend.compile("(f4[:,::1], f4)") + + # Test there are no reference count operations + llvmir = str(extend.inspect_llvm(extend.signatures[0])) + refops = list(re.finditer(r'(NRT_incref|NRT_decref)\([^\)]+\)', llvmir)) + self.assertEqual(len(refops), 0) + + @linux_only + @x86_only + def test_inline_asm(self): + """The InlineAsm class from llvmlite.ir has no 'name' attr the refcount + pruning pass should be tolerant to this""" + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + llvm.initialize_native_asmparser() + + @intrinsic + def bar(tyctx, x, y): + def codegen(cgctx, builder, sig, args): + (arg_0, arg_1) = args + fty = ir.FunctionType(ir.IntType(32), [ir.IntType(32), + ir.IntType(32)]) + mul = builder.asm(fty, "mov $2, $0; imul $1, $0", "=&r,r,r", + (arg_0, arg_1), name="asm_mul", + side_effect=False) + return impl_ret_untracked(cgctx, builder, sig.return_type, mul) + return signature(types.int32, types.int32, types.int32), codegen + + @njit(['int32(int32)']) + def foo(x): + x += 1 + z = bar(x, 2) + return z + + self.assertEqual(foo(10), 22) # expect (10 + 1) * 2 = 22 + + +@skip_unless_cffi +class TestNrtExternalCFFI(EnableNRTStatsMixin, TestCase): + """Testing the use of externally compiled C code that use NRT + """ + def setUp(self): + # initialize the NRT (in case the tests are run in isolation) + cpu_target.target_context + super(TestNrtExternalCFFI, self).setUp() + + def compile_cffi_module(self, name, source, cdef): + from cffi import FFI + + ffi = FFI() + ffi.set_source(name, source, include_dirs=[include_path()]) + ffi.cdef(cdef) + tmpdir = temp_directory("cffi_test_{}".format(name)) + ffi.compile(tmpdir=tmpdir) + sys.path.append(tmpdir) + try: + mod = import_dynamic(name) + finally: + sys.path.remove(tmpdir) + + return ffi, mod + + def get_nrt_api_table(self): + from cffi import FFI + + ffi = FFI() + nrt_get_api = ffi.cast("void* (*)()", _nrt_python.c_helpers['get_api']) + table = nrt_get_api() + return table + + def test_manage_memory(self): + name = "{}_test_manage_memory".format(self.__class__.__name__) + source = r""" +#include +#include "numba/core/runtime/nrt_external.h" + +int status = 0; + +void my_dtor(void *ptr) { + free(ptr); + status = 0xdead; +} + +NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt) { + void * data = malloc(10); + NRT_MemInfo *mi = nrt->manage_memory(data, my_dtor); + nrt->acquire(mi); + nrt->release(mi); + status = 0xa110c; + return mi; +} + """ + cdef = """ +void* test_nrt_api(void *nrt); +extern int status; + """ + + ffi, mod = self.compile_cffi_module(name, source, cdef) + # Init status is 0 + self.assertEqual(mod.lib.status, 0) + table = self.get_nrt_api_table() + out = mod.lib.test_nrt_api(table) + # status is now 0xa110c + self.assertEqual(mod.lib.status, 0xa110c) + mi_addr = int(ffi.cast("size_t", out)) + mi = nrt.MemInfo(mi_addr) + self.assertEqual(mi.refcount, 1) + del mi # force deallocation on mi + # status is now 0xdead + self.assertEqual(mod.lib.status, 0xdead) + + def test_allocate(self): + name = "{}_test_allocate".format(self.__class__.__name__) + source = r""" +#include +#include "numba/core/runtime/nrt_external.h" + +NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt, size_t n) { + size_t *data = NULL; + NRT_MemInfo *mi = nrt->allocate(n); + data = nrt->get_data(mi); + data[0] = 0xded; + data[1] = 0xabc; + data[2] = 0xdef; + return mi; +} + """ + cdef = "void* test_nrt_api(void *nrt, size_t n);" + ffi, mod = self.compile_cffi_module(name, source, cdef) + + table = self.get_nrt_api_table() + + numbytes = 3 * np.dtype(np.intp).itemsize + out = mod.lib.test_nrt_api(table, numbytes) + + mi_addr = int(ffi.cast("size_t", out)) + mi = nrt.MemInfo(mi_addr) + self.assertEqual(mi.refcount, 1) + + buffer = ffi.buffer(ffi.cast("char [{}]".format(numbytes), mi.data)) + arr = np.ndarray(shape=(3,), dtype=np.intp, buffer=buffer) + np.testing.assert_equal(arr, [0xded, 0xabc, 0xdef]) + + def test_get_api(self): + from cffi import FFI + + @njit + def test_nrt_api(): + return NRT_get_api() + + ffi = FFI() + expect = int(ffi.cast('size_t', self.get_nrt_api_table())) + got = test_nrt_api() + self.assertEqual(expect, got) + + +class TestNrtStatistics(TestCase): + + def setUp(self): + # Store the current stats state + self.__stats_state = _nrt_python.memsys_stats_enabled() + + def tearDown(self): + # Set stats state back to whatever it was before the test ran + if self.__stats_state: + _nrt_python.memsys_enable_stats() + else: + _nrt_python.memsys_disable_stats() + + def test_stats_env_var_explicit_on(self): + # Checks that explicitly turning the stats on via the env var works. + src = """if 1: + from numba import njit + import numpy as np + from numba.core.runtime import rtsys, _nrt_python + from numba.core.registry import cpu_target + + @njit + def foo(): + return np.arange(10)[0] + + # initialize the NRT before use + rtsys.initialize(cpu_target.target_context) + assert _nrt_python.memsys_stats_enabled() + orig_stats = rtsys.get_allocation_stats() + foo() + new_stats = rtsys.get_allocation_stats() + total_alloc = new_stats.alloc - orig_stats.alloc + total_free = new_stats.free - orig_stats.free + total_mi_alloc = new_stats.mi_alloc - orig_stats.mi_alloc + total_mi_free = new_stats.mi_free - orig_stats.mi_free + + expected = 1 + assert total_alloc == expected + assert total_free == expected + assert total_mi_alloc == expected + assert total_mi_free == expected + """ + # Check env var explicitly being set works + env = os.environ.copy() + env['NUMBA_NRT_STATS'] = "1" + run_in_subprocess(src, env=env) + + def check_env_var_off(self, env): + + src = """if 1: + from numba import njit + import numpy as np + from numba.core.runtime import rtsys, _nrt_python + + @njit + def foo(): + return np.arange(10)[0] + + assert _nrt_python.memsys_stats_enabled() == False + try: + rtsys.get_allocation_stats() + except RuntimeError as e: + assert "NRT stats are disabled." in str(e) + """ + run_in_subprocess(src, env=env) + + def test_stats_env_var_explicit_off(self): + # Checks that explicitly turning the stats off via the env var works. + env = os.environ.copy() + env['NUMBA_NRT_STATS'] = "0" + self.check_env_var_off(env) + + def test_stats_env_var_default_off(self): + # Checks that the env var not being set is the same as "off", i.e. + # default for Numba is off. + env = os.environ.copy() + env.pop('NUMBA_NRT_STATS', None) + self.check_env_var_off(env) + + def test_stats_status_toggle(self): + + @njit + def foo(): + tmp = np.ones(3) + return np.arange(5 * tmp[0]) + + # Switch on stats + _nrt_python.memsys_enable_stats() + # check the stats are on + self.assertTrue(_nrt_python.memsys_stats_enabled()) + + for i in range(2): + # capture the stats state + stats_1 = rtsys.get_allocation_stats() + # Switch off stats + _nrt_python.memsys_disable_stats() + # check the stats are off + self.assertFalse(_nrt_python.memsys_stats_enabled()) + # run something that would move the counters were they enabled + foo() + # Switch on stats + _nrt_python.memsys_enable_stats() + # check the stats are on + self.assertTrue(_nrt_python.memsys_stats_enabled()) + # capture the stats state (should not have changed) + stats_2 = rtsys.get_allocation_stats() + # run something that will move the counters + foo() + # capture the stats state (should have changed) + stats_3 = rtsys.get_allocation_stats() + # check stats_1 == stats_2 + self.assertEqual(stats_1, stats_2) + # check stats_2 < stats_3 + self.assertLess(stats_2, stats_3) + + def test_rtsys_stats_query_raises_exception_when_disabled(self): + # Checks that the standard rtsys.get_allocation_stats() query raises + # when stats counters are turned off. + + _nrt_python.memsys_disable_stats() + self.assertFalse(_nrt_python.memsys_stats_enabled()) + + with self.assertRaises(RuntimeError) as raises: + rtsys.get_allocation_stats() + + self.assertIn("NRT stats are disabled.", str(raises.exception)) + + def test_nrt_explicit_stats_query_raises_exception_when_disabled(self): + # Checks the various memsys_get_stats functions raise if queried when + # the stats counters are disabled. + method_variations = ('alloc', 'free', 'mi_alloc', 'mi_free') + for meth in method_variations: + stats_func = getattr(_nrt_python, f'memsys_get_stats_{meth}') + with self.subTest(stats_func=stats_func): + # Turn stats off + _nrt_python.memsys_disable_stats() + self.assertFalse(_nrt_python.memsys_stats_enabled()) + with self.assertRaises(RuntimeError) as raises: + stats_func() + self.assertIn("NRT stats are disabled.", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt_refct.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt_refct.py new file mode 100644 index 0000000000000000000000000000000000000000..3049c7a3b3cb7239394b02d75f4d14f3bf2abd8b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nrt_refct.py @@ -0,0 +1,115 @@ +""" +Tests issues or edge cases for producing invalid NRT refct +""" + + +import gc + +import numpy as np + +import unittest +from numba import njit +from numba.core.runtime import rtsys +from numba.tests.support import TestCase, EnableNRTStatsMixin + + +class TestNrtRefCt(EnableNRTStatsMixin, TestCase): + + def setUp(self): + # Clean up any NRT-backed objects hanging in a dead reference cycle + gc.collect() + super(TestNrtRefCt, self).setUp() + + def test_no_return(self): + """ + Test issue #1291 + """ + + @njit + def foo(n): + for i in range(n): + temp = np.zeros(2) + return 0 + + n = 10 + init_stats = rtsys.get_allocation_stats() + foo(n) + cur_stats = rtsys.get_allocation_stats() + self.assertEqual(cur_stats.alloc - init_stats.alloc, n) + self.assertEqual(cur_stats.free - init_stats.free, n) + + def test_escaping_var_init_in_loop(self): + """ + Test issue #1297 + """ + + @njit + def g(n): + + x = np.zeros((n, 2)) + + for i in range(n): + y = x[i] + + for i in range(n): + y = x[i] + + return 0 + + init_stats = rtsys.get_allocation_stats() + g(10) + cur_stats = rtsys.get_allocation_stats() + self.assertEqual(cur_stats.alloc - init_stats.alloc, 1) + self.assertEqual(cur_stats.free - init_stats.free, 1) + + def test_invalid_computation_of_lifetime(self): + """ + Test issue #1573 + """ + @njit + def if_with_allocation_and_initialization(arr1, test1): + tmp_arr = np.zeros_like(arr1) + + for i in range(tmp_arr.shape[0]): + pass + + if test1: + np.zeros_like(arr1) + + return tmp_arr + + arr = np.random.random((5, 5)) # the values are not consumed + + init_stats = rtsys.get_allocation_stats() + if_with_allocation_and_initialization(arr, False) + cur_stats = rtsys.get_allocation_stats() + self.assertEqual(cur_stats.alloc - init_stats.alloc, + cur_stats.free - init_stats.free) + + def test_del_at_beginning_of_loop(self): + """ + Test issue #1734 + """ + @njit + def f(arr): + res = 0 + + for i in (0, 1): + # `del t` is issued here before defining t. It must be + # correctly handled by the lowering phase. + t = arr[i] + if t[i] > 1: + res += t[i] + + return res + + arr = np.ones((2, 2)) + init_stats = rtsys.get_allocation_stats() + f(arr) + cur_stats = rtsys.get_allocation_stats() + self.assertEqual(cur_stats.alloc - init_stats.alloc, + cur_stats.free - init_stats.free) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_num_threads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_num_threads.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd51ac3dda7056919d9fe1218ffe33c1b97cdbb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_num_threads.py @@ -0,0 +1,632 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function, absolute_import, division + +import sys +import os +import re +import multiprocessing +import unittest + +import numpy as np + +from numba import (njit, set_num_threads, get_num_threads, prange, config, + threading_layer, guvectorize) +from numba.np.ufunc.parallel import get_thread_id +from numba.core.errors import TypingError +from numba.tests.support import TestCase, skip_parfors_unsupported, tag +from numba.tests.test_parallel_backend import TestInSubprocess + + +class TestNumThreads(TestCase): + _numba_parallel_test_ = False + + def setUp(self): + # Make sure the num_threads is set to the max. This also makes sure + # the threads are launched. + set_num_threads(config.NUMBA_NUM_THREADS) + + def check_mask(self, expected, result): + # There's no guarantee that TBB will use a full mask worth of + # threads if it deems it inefficient to do so + if threading_layer() == 'tbb': + self.assertTrue(np.all(result <= expected)) + elif threading_layer() in ('omp', 'workqueue'): + np.testing.assert_equal(expected, result) + else: + assert 0, 'unreachable' + + @skip_parfors_unsupported + def test_set_num_threads_type(self): + + @njit + def foo(): + set_num_threads('wrong_type') + + expected = "The number of threads specified must be an integer" + for fn, errty in ((foo, TypingError), (foo.py_func, TypeError)): + with self.assertRaises(errty) as raises: + fn() + self.assertIn(expected, str(raises.exception)) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic(self): + max_threads = config.NUMBA_NUM_THREADS + + self.assertEqual(get_num_threads(), max_threads) + set_num_threads(2) + self.assertEqual(get_num_threads(), 2) + set_num_threads(max_threads) + self.assertEqual(get_num_threads(), max_threads) + + with self.assertRaises(ValueError): + set_num_threads(0) + + with self.assertRaises(ValueError): + set_num_threads(max_threads + 1) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic_jit(self): + max_threads = config.NUMBA_NUM_THREADS + + @njit + def get_n(): + return get_num_threads() + + self.assertEqual(get_n(), max_threads) + set_num_threads(2) + self.assertEqual(get_n(), 2) + set_num_threads(max_threads) + self.assertEqual(get_n(), max_threads) + + @njit + def set_get_n(n): + set_num_threads(n) + return get_num_threads() + + self.assertEqual(set_get_n(2), 2) + self.assertEqual(set_get_n(max_threads), max_threads) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic_guvectorize(self): + max_threads = config.NUMBA_NUM_THREADS + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def get_n(x): + x[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, max_threads) + set_num_threads(2) + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, 2) + set_num_threads(max_threads) + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, max_threads) + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def set_get_n(n): + set_num_threads(n[0]) + n[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + x[0] = 2 + set_get_n(x) + np.testing.assert_equal(x, 2) + x = np.zeros((5000000,), dtype=np.int64) + x[0] = max_threads + set_get_n(x) + np.testing.assert_equal(x, max_threads) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_outside_jit(self): + + # Test set_num_threads outside a jitted function + set_num_threads(2) + + @njit(parallel=True) + def test_func(): + x = 5 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_num_threads() + return buf + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def test_gufunc(x): + x[:] = get_num_threads() + + out = test_func() + np.testing.assert_equal(out, 2) + + x = np.zeros((5000000,), dtype=np.int64) + test_gufunc(x) + np.testing.assert_equal(x, 2) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_inside_jit(self): + # Test set_num_threads inside a jitted function + @njit(parallel=True) + def test_func(nthreads): + x = 5 + buf = np.empty((x,)) + set_num_threads(nthreads) + for i in prange(x): + buf[i] = get_num_threads() + return buf + + mask = 2 + out = test_func(mask) + np.testing.assert_equal(out, mask) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_inside_guvectorize(self): + # Test set_num_threads inside a jitted guvectorize function + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def test_func(x): + set_num_threads(x[0]) + x[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + mask = 2 + x[0] = mask + test_func(x) + np.testing.assert_equal(x, mask) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_get_num_threads_truth_outside_jit(self): + + for mask in range(2, min(6, config.NUMBA_NUM_THREADS + 1)): + set_num_threads(mask) + + # a lot of work, hopefully will trigger "mask" count of threads to + # join the parallel region (for those backends with dynamic threads) + @njit(parallel=True) + def test_func(): + x = 5000000 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_thread_id() + return len(np.unique(buf)), get_num_threads() + + out = test_func() + self.check_mask((mask, mask), out) + + @guvectorize(['void(int64[:], int64[:])'], + '(n), (m)', + nopython=True, + target='parallel') + def test_gufunc(x, out): + x[:] = get_thread_id() + out[0] = get_num_threads() + + # Reshape to force parallelism + x = np.full((5000000,), -1, dtype=np.int64).reshape((100, 50000)) + out = np.zeros((1,), dtype=np.int64) + test_gufunc(x, out) + self.check_mask(mask, out) + self.check_mask(mask, len(np.unique(x))) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_get_num_threads_truth_inside_jit(self): + + for mask in range(2, min(6, config.NUMBA_NUM_THREADS + 1)): + + # a lot of work, hopefully will trigger "mask" count of threads to + # join the parallel region (for those backends with dynamic threads) + @njit(parallel=True) + def test_func(): + set_num_threads(mask) + x = 5000000 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_thread_id() + return len(np.unique(buf)), get_num_threads() + + out = test_func() + self.check_mask((mask, mask), out) + + @guvectorize(['void(int64[:], int64[:])'], + '(n), (m)', + nopython=True, + target='parallel') + def test_gufunc(x, out): + set_num_threads(mask) + x[:] = get_thread_id() + out[0] = get_num_threads() + + # Reshape to force parallelism + x = np.full((5000000,), -1, dtype=np.int64).reshape((100, 50000)) + out = np.zeros((1,), dtype=np.int64) + test_gufunc(x, out) + self.check_mask(mask, out) + self.check_mask(mask, len(np.unique(x))) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_nested_parallelism_1(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that get_num_threads is ok in nesting + mask = config.NUMBA_NUM_THREADS - 1 + + N = config.NUMBA_NUM_THREADS + M = 2 * config.NUMBA_NUM_THREADS + + @njit(parallel=True) + def child_func(buf, fid): + M, N = buf.shape + for i in prange(N): + buf[fid, i] = get_num_threads() + + def get_test(test_type): + if test_type == 'njit': + def test_func(nthreads, py_func=False): + @njit(parallel=True) + def _test_func(nthreads): + acc = 0 + buf = np.zeros((M, N)) + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + # set threads in parent function + set_num_threads(local_mask) + if local_mask < N: + child_func(buf, local_mask) + acc += get_num_threads() + return acc, buf + if py_func: + return _test_func.py_func(nthreads) + else: + return _test_func(nthreads) + + elif test_type == 'guvectorize': + def test_func(nthreads, py_func=False): + def _test_func(acc, buf, local_mask): + set_num_threads(nthreads) + # set threads in parent function + set_num_threads(local_mask[0]) + if local_mask[0] < N: + child_func(buf, local_mask[0]) + acc[0] += get_num_threads() + + buf = np.zeros((M, N), dtype=np.int64) + acc = np.zeros((M, 1), dtype=np.int64) + local_mask = (1 + np.arange(M) % mask).reshape((M, 1)) + sig = ['void(int64[:], int64[:, :], int64[:])'] + layout = '(p), (n, m), (p)' + if not py_func: + _test_func = guvectorize(sig, layout, nopython=True, + target='parallel')(_test_func) + else: + _test_func = guvectorize(sig, layout, + forceobj=True)(_test_func) + _test_func(acc, buf, local_mask) + return acc, buf + + return test_func + + for test_type in ['njit', 'guvectorize']: + test_func = get_test(test_type) + got_acc, got_arr = test_func(mask) + exp_acc, exp_arr = test_func(mask, py_func=True) + np.testing.assert_equal(exp_acc, got_acc) + np.testing.assert_equal(exp_arr, got_arr) + + # check the maths reconciles, guvectorize does not reduce, njit does + math_acc_exp = 1 + np.arange(M) % mask + if test_type == 'guvectorize': + math_acc = math_acc_exp.reshape((M, 1)) + else: + math_acc = np.sum(math_acc_exp) + + np.testing.assert_equal(math_acc, got_acc) + + math_arr = np.zeros((M, N)) + for i in range(1, N): + # there's branches on 1, ..., num_threads - 1 + math_arr[i, :] = i + np.testing.assert_equal(math_arr, got_arr) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_nested_parallelism_2(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that get_num_threads is ok in nesting + + N = config.NUMBA_NUM_THREADS + 1 + M = 4 * config.NUMBA_NUM_THREADS + 1 + + def get_impl(child_type, test_type): + + if child_type == 'parallel': + child_dec = njit(parallel=True) + elif child_type == 'njit': + child_dec = njit(parallel=False) + elif child_type == 'none': + def child_dec(x): + return x + + @child_dec + def child(buf, fid): + M, N = buf.shape + set_num_threads(fid) # set threads in child function + for i in prange(N): + buf[fid, i] = get_num_threads() + + if test_type in ['parallel', 'njit', 'none']: + if test_type == 'parallel': + test_dec = njit(parallel=True) + elif test_type == 'njit': + test_dec = njit(parallel=False) + elif test_type == 'none': + def test_dec(x): + return x + + @test_dec + def test_func(nthreads): + buf = np.zeros((M, N)) + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + # when the threads exit the child functions they should + # have a TLS slot value of the local mask as it was set + # in child + if local_mask < config.NUMBA_NUM_THREADS: + child(buf, local_mask) + assert get_num_threads() == local_mask + return buf + else: + if test_type == 'guvectorize': + test_dec = guvectorize(['int64[:,:], int64[:]'], + '(n, m), (k)', nopython=True, + target='parallel') + elif test_type == 'guvectorize-obj': + test_dec = guvectorize(['int64[:,:], int64[:]'], + '(n, m), (k)', forceobj=True) + + def test_func(nthreads): + @test_dec + def _test_func(buf, local_mask): + set_num_threads(nthreads) + # when the threads exit the child functions they should + # have a TLS slot value of the local mask as it was set + # in child + if local_mask[0] < config.NUMBA_NUM_THREADS: + child(buf, local_mask[0]) + assert get_num_threads() == local_mask[0] + + buf = np.zeros((M, N), dtype=np.int64) + local_mask = (1 + np.arange(M) % mask).reshape((M, 1)) + _test_func(buf, local_mask) + return buf + + return test_func + + mask = config.NUMBA_NUM_THREADS - 1 + + res_arrays = {} + for test_type in ['parallel', 'njit', 'none', + 'guvectorize', 'guvectorize-obj']: + for child_type in ['parallel', 'njit', 'none']: + if child_type == 'none' and test_type != 'none': + continue + set_num_threads(mask) + res_arrays[test_type, child_type] = get_impl( + child_type, test_type)(mask) + + py_arr = res_arrays['none', 'none'] + for arr in res_arrays.values(): + np.testing.assert_equal(arr, py_arr) + + # check the maths reconciles + math_arr = np.zeros((M, N)) + # there's branches on modulo mask but only NUMBA_NUM_THREADS funcs + for i in range(1, config.NUMBA_NUM_THREADS): + math_arr[i, :] = i + + np.testing.assert_equal(math_arr, py_arr) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + # This test needs at least 3 threads to run, N>=2 for the launch, M>=N+1 for + # the nested function + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 3, "Not enough CPU cores") + def _test_nested_parallelism_3(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that the right number of threads are present in nesting + # this relies on there being a load of cores present + BIG = 1000000 + + @njit(parallel=True) + def work(local_nt): # arg is value 3 + tid = np.zeros(BIG) + acc = 0 + set_num_threads(local_nt) # set to 3 threads + for i in prange(BIG): + acc += 1 + tid[i] = get_thread_id() + return acc, np.unique(tid) + + @njit(parallel=True) + def test_func_jit(nthreads): + set_num_threads(nthreads) # set to 2 threads + lens = np.zeros(nthreads) + total = 0 + for i in prange(nthreads): + my_acc, tids = work(nthreads + 1) # call with value 3 + lens[i] = len(tids) + total += my_acc + return total, np.unique(lens) + + NT = 2 + expected_acc = BIG * NT + expected_thread_count = NT + 1 + + got_acc, got_tc = test_func_jit(NT) + self.assertEqual(expected_acc, got_acc) + self.check_mask(expected_thread_count, got_tc) + + def test_guvectorize(nthreads): + @guvectorize(['int64[:], int64[:]'], + '(n), (n)', + nopython=True, + target='parallel') + def test_func_guvectorize(total, lens): + my_acc, tids = work(nthreads + 1) + lens[0] = len(tids) + total[0] += my_acc + + total = np.zeros((nthreads, 1), dtype=np.int64) + lens = np.zeros(nthreads, dtype=np.int64).reshape((nthreads, 1)) + + test_func_guvectorize(total, lens) + # vectorize does not reduce, so total is summed + return total.sum(), np.unique(lens) + + got_acc, got_tc = test_guvectorize(NT) + + self.assertEqual(expected_acc, got_acc) + self.check_mask(expected_thread_count, got_tc) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + @unittest.skipIf(not sys.platform.startswith('linux'), "Linux only") + def _test_threadmask_across_fork(self): + forkctx = multiprocessing.get_context('fork') + + @njit + def foo(): + return get_num_threads() + + def wrap(queue): + queue.put(foo()) + + mask = 1 + self.assertEqual(foo(), config.NUMBA_NUM_THREADS) + set_num_threads(mask) + self.assertEqual(foo(), mask) + shared_queue = forkctx.Queue() + # check TLS slot inheritance in fork + p = forkctx.Process(target=wrap, args=(shared_queue,)) + p.start() + p.join() + self.assertEqual(shared_queue.get(), mask) + + def tearDown(self): + set_num_threads(config.NUMBA_NUM_THREADS) + + @skip_parfors_unsupported + def _test_get_thread_id_not_parallel(self): + python_get_thread_id = get_thread_id() + check_array_size = 8 + + @njit(parallel=False) + def par_false(size): + njit_par_false_tid = get_thread_id() + res = np.ones(size) + for i in prange(size): + res[i] = get_thread_id() + return njit_par_false_tid, res + + @njit(parallel=True) + def par_true(size): + njit_par_true_tid = get_thread_id() + res = np.ones(size) + for i in range(size): + res[i] = get_thread_id() + return njit_par_true_tid, res + + self.assertEqual(python_get_thread_id, 0) + njit_par_false_tid, njit_par_false_arr = par_false(check_array_size) + self.assertEqual(njit_par_false_tid, 0) + np.testing.assert_equal(njit_par_false_arr, 0) + njit_par_true_tid, njit_par_true_arr = par_true(check_array_size) + self.assertEqual(njit_par_true_tid, 0) + np.testing.assert_equal(njit_par_true_arr, 0) + + +class TestNumThreadsBackends(TestInSubprocess, TestCase): + _class = TestNumThreads + _DEBUG = False + + # 1 is mainly here to ensure tests skip correctly + num_threads = [i for i in [1, 2, 4, 8, 16] if i <= config.NUMBA_NUM_THREADS] + + def run_test_in_separate_process(self, test, threading_layer, num_threads): + env_copy = os.environ.copy() + env_copy['NUMBA_THREADING_LAYER'] = str(threading_layer) + env_copy['NUMBA_NUM_THREADS'] = str(num_threads) + cmdline = [sys.executable, "-m", "numba.runtests", "-v", test] + return self.run_cmd(cmdline, env_copy) + + @classmethod + def _inject(cls, name, backend, backend_guard, num_threads): + themod = cls.__module__ + thecls = cls._class.__name__ + injected_method = '%s.%s.%s' % (themod, thecls, name) + + def test_template(self): + o, e = self.run_test_in_separate_process(injected_method, backend, + num_threads) + if self._DEBUG: + print('stdout:\n "%s"\n stderr:\n "%s"' % (o, e)) + # If the test was skipped in the subprocess, then mark this as a + # skipped test. + m = re.search(r"\.\.\. skipped '(.*?)'", e) + if m is not None: + self.skipTest(m.group(1)) + self.assertIn('OK', e) + self.assertTrue('FAIL' not in e) + self.assertTrue('ERROR' not in e) + + injected_test = "%s_%s_%s_threads" % (name[1:], backend, num_threads) + setattr(cls, injected_test, + tag('long_running')(backend_guard(test_template))) + + @classmethod + def generate(cls): + for name in cls._class.__dict__.copy(): + for backend, backend_guard in cls.backends.items(): + for num_threads in cls.num_threads: + if not name.startswith('_test_'): + continue + cls._inject(name, backend, backend_guard, num_threads) + + +TestNumThreadsBackends.generate() + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numpyadapt.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numpyadapt.py new file mode 100644 index 0000000000000000000000000000000000000000..8df1f028813cee233e67c610e7feddcc8bc14ce2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numpyadapt.py @@ -0,0 +1,43 @@ +from ctypes import * + +import numpy as np + +import unittest +from numba import _helperlib + + +class ArrayStruct3D(Structure): + # Mimic the structure defined in numba.targets.arrayobj's make_array() + _fields_ = [ + ("meminfo", c_void_p), + ("parent", c_void_p), + ("nitems", c_ssize_t), + ("itemsize", c_ssize_t), + ("data", c_void_p), + ("shape", (c_ssize_t * 3)), + ("strides", (c_ssize_t * 3)), + ] + + +class TestArrayAdaptor(unittest.TestCase): + def test_array_adaptor(self): + arystruct = ArrayStruct3D() + + adaptorptr = _helperlib.c_helpers['adapt_ndarray'] + adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr) + + ary = np.arange(60).reshape(2, 3, 10) + status = adaptor(ary, byref(arystruct)) + self.assertEqual(status, 0) + self.assertEqual(arystruct.data, ary.ctypes.data) + self.assertNotEqual(arystruct.meminfo, 0) + self.assertEqual(arystruct.parent, id(ary)) + self.assertEqual(arystruct.nitems, 60) + self.assertEqual(arystruct.itemsize, ary.itemsize) + for i in range(3): + self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i]) + self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i]) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optional.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optional.py new file mode 100644 index 0000000000000000000000000000000000000000..f043cebee22b050c24afdb9b2af0827cccd41fe8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optional.py @@ -0,0 +1,254 @@ +import itertools + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase + + +def return_double_or_none(x): + if x: + ret = None + else: + ret = 1.2 + return ret + + +def return_different_statement(x): + if x: + return None + else: + return 1.2 + + +def return_bool_optional_or_none(x, y): + if y: + z = False + else: + z = None + if x == 2: + # A boolean + return True + elif x == 1: + # A runtime optional + return z + else: + # None + return None + + +def is_this_a_none(x): + if x: + val_or_none = None + else: + val_or_none = x + + if val_or_none is None: + return x - 1 + + if val_or_none is not None: + return x + 1 + + +def a_is_b(a, b): + """ + Note in nopython mode, this operation does not make much sense. + Because we don't have objects anymore. + `a is b` is always False if not operating on None and Optional type + """ + return a is b + + +def a_is_not_b(a, b): + """ + This is `not (a is b)` + """ + return a is not b + + +class TestOptional(TestCase): + + _numba_parallel_test_ = False + + def test_return_double_or_none(self): + pyfunc = return_double_or_none + cfunc = njit((types.boolean,))(pyfunc) + + for v in [True, False]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_return_different_statement(self): + pyfunc = return_different_statement + cfunc = njit((types.boolean,))(pyfunc) + + for v in [True, False]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_return_bool_optional_or_none(self): + pyfunc = return_bool_optional_or_none + cfunc = njit((types.int32, types.int32,))(pyfunc) + + for x, y in itertools.product((0, 1, 2), (0, 1)): + self.assertPreciseEqual(pyfunc(x, y), cfunc(x, y)) + + def test_is_this_a_none(self): + pyfunc = is_this_a_none + cfunc = njit((types.intp,))(pyfunc) + + for v in [-1, 0, 1, 2]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_is_this_a_none_objmode(self): + pyfunc = is_this_a_none + cfunc = jit((types.intp,), forceobj=True)(pyfunc) + self.assertTrue(cfunc.overloads[cfunc.signatures[0]].objectmode) + for v in [-1, 0, 1, 2]: + self.assertPreciseEqual(pyfunc(v), cfunc(v)) + + def test_a_is_b_intp(self): + pyfunc = a_is_b + cfunc = njit((types.intp, types.intp))(pyfunc) + # integer identity relies on `==` + self.assertTrue(cfunc(1, 1)) + self.assertFalse(cfunc(1, 2)) + + def test_a_is_not_b_intp(self): + pyfunc = a_is_not_b + cfunc = njit((types.intp, types.intp))(pyfunc) + # integer identity relies on `==` + self.assertFalse(cfunc(1, 1)) + self.assertTrue(cfunc(1, 2)) + + def test_optional_float(self): + def pyfunc(x, y): + if y is None: + return x + else: + return x + y + + cfunc = njit("(float64, optional(float64))")(pyfunc) + self.assertAlmostEqual(pyfunc(1., 12.3), cfunc(1., 12.3)) + self.assertAlmostEqual(pyfunc(1., None), cfunc(1., None)) + + def test_optional_array(self): + def pyfunc(x, y): + if y is None: + return x + else: + y[0] += x + return y[0] + + cfunc = njit("(float32, optional(float32[:]))")(pyfunc) + cy = np.array([12.3], dtype=np.float32) + py = cy.copy() + self.assertAlmostEqual(pyfunc(1., py), cfunc(1., cy)) + np.testing.assert_almost_equal(py, cy) + self.assertAlmostEqual(pyfunc(1., None), cfunc(1., None)) + + def test_optional_array_error(self): + def pyfunc(y): + return y[0] + + cfunc = njit("(optional(int32[:]),)")(pyfunc) + with self.assertRaises(TypeError) as raised: + cfunc(None) + self.assertIn('expected array(int32, 1d, A), got None', + str(raised.exception)) + + y = np.array([0xabcd], dtype=np.int32) + self.assertEqual(cfunc(y), pyfunc(y)) + + def test_optional_array_attribute(self): + """ + Check that we can access attribute of an optional + """ + def pyfunc(arr, do_it): + opt = None + if do_it: # forces `opt` to be an optional of arr + opt = arr + return opt.shape[0] + + cfunc = njit(pyfunc) + arr = np.arange(5) + self.assertEqual(pyfunc(arr, True), cfunc(arr, True)) + + def test_assign_to_optional(self): + """ + Check that we can assign to a variable of optional type + """ + @njit + def make_optional(val, get_none): + if get_none: + ret = None + else: + ret = val + return ret + + @njit + def foo(val, run_second): + a = make_optional(val, True) + if run_second: + a = make_optional(val, False) + return a + + self.assertIsNone(foo(123, False)) + self.assertEqual(foo(231, True), 231) + + def test_optional_thru_omitted_arg(self): + """ + Issue 1868 + """ + + def pyfunc(x=None): + if x is None: + x = 1 + return x + + cfunc = njit(pyfunc) + self.assertEqual(pyfunc(), cfunc()) + self.assertEqual(pyfunc(3), cfunc(3)) + + def test_optional_unpack(self): + """ + Issue 2171 + """ + def pyfunc(x): + if x is None: + return + else: + a, b = x + return a, b + + tup = types.Tuple([types.intp] * 2) + opt_tup = types.Optional(tup) + sig = (opt_tup,) + cfunc = njit(sig)(pyfunc) + self.assertEqual(pyfunc(None), cfunc(None)) + self.assertEqual(pyfunc((1, 2)), cfunc((1, 2))) + + def test_many_optional_none_returns(self): + """ + Issue #4058 + """ + @njit + def foo(maybe): + lx = None + if maybe: + lx = 10 + return 1, lx + + def work(): + tmp = [] + for _ in range(20000): + maybe = False + _ = foo(maybe) + + # this caused "Fatal Python error: deallocating None" as there was no + # incref being made on the returned None. + work() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_overlap.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_overlap.py new file mode 100644 index 0000000000000000000000000000000000000000..eecf77c099ce9359a5ed298f84c5eefaa7076883 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_overlap.py @@ -0,0 +1,134 @@ +import numpy as np + +from numba import jit +from numba.core import types +from numba.tests.support import TestCase, tag +import unittest + + +# Array overlaps involving a displacement + +def array_overlap1(src, dest, k=1): + assert src.shape == dest.shape + dest[k:] = src[:-k] + +def array_overlap2(src, dest, k=1): + assert src.shape == dest.shape + dest[:-k] = src[k:] + +def array_overlap3(src, dest, k=1): + assert src.shape == dest.shape + dest[:,:-k] = src[:,k:] + +def array_overlap4(src, dest, k=1): + assert src.shape == dest.shape + dest[:,k:] = src[:,:-k] + +def array_overlap5(src, dest, k=1): + assert src.shape == dest.shape + dest[...,:-k] = src[...,k:] + +def array_overlap6(src, dest, k=1): + assert src.shape == dest.shape + dest[...,k:] = src[...,:-k] + +# Array overlaps involving an in-place reversal + +def array_overlap11(src, dest): + assert src.shape == dest.shape + dest[::-1] = src + +def array_overlap12(src, dest): + assert src.shape == dest.shape + dest[:] = src[::-1] + +def array_overlap13(src, dest): + assert src.shape == dest.shape + dest[:,::-1] = src + +def array_overlap14(src, dest): + assert src.shape == dest.shape + dest[:] = src[:,::-1] + +def array_overlap15(src, dest): + assert src.shape == dest.shape + dest[...,::-1] = src + +def array_overlap16(src, dest): + assert src.shape == dest.shape + dest[:] = src[...,::-1] + + +class TestArrayOverlap(TestCase): + + def check_overlap(self, pyfunc, min_ndim, have_k_argument=False): + N = 4 + + def vary_layouts(orig): + yield orig.copy(order='C') + yield orig.copy(order='F') + a = orig[::-1].copy()[::-1] + assert not a.flags.c_contiguous and not a.flags.f_contiguous + yield a + + def check(pyfunc, cfunc, pydest, cdest, kwargs): + pyfunc(pydest, pydest, **kwargs) + cfunc(cdest, cdest, **kwargs) + self.assertPreciseEqual(pydest, cdest) + + cfunc = jit(nopython=True)(pyfunc) + # Check for up to 3d arrays + for ndim in range(min_ndim, 4): + shape = (N,) * ndim + orig = np.arange(0, N**ndim).reshape(shape) + # Note we cannot copy a 'A' layout array exactly (bitwise), + # so instead we call vary_layouts() twice + for pydest, cdest in zip(vary_layouts(orig), vary_layouts(orig)): + if have_k_argument: + for k in range(1, N): + check(pyfunc, cfunc, pydest, cdest, dict(k=k)) + else: + check(pyfunc, cfunc, pydest, cdest, {}) + + def check_overlap_with_k(self, pyfunc, min_ndim): + self.check_overlap(pyfunc, min_ndim=min_ndim, have_k_argument=True) + + def test_overlap1(self): + self.check_overlap_with_k(array_overlap1, min_ndim=1) + + def test_overlap2(self): + self.check_overlap_with_k(array_overlap2, min_ndim=1) + + def test_overlap3(self): + self.check_overlap_with_k(array_overlap3, min_ndim=2) + + def test_overlap4(self): + self.check_overlap_with_k(array_overlap4, min_ndim=2) + + def test_overlap5(self): + self.check_overlap_with_k(array_overlap5, min_ndim=1) + + def test_overlap6(self): + self.check_overlap_with_k(array_overlap6, min_ndim=1) + + def test_overlap11(self): + self.check_overlap(array_overlap11, min_ndim=1) + + def test_overlap12(self): + self.check_overlap(array_overlap12, min_ndim=1) + + def test_overlap13(self): + self.check_overlap(array_overlap13, min_ndim=2) + + def test_overlap14(self): + self.check_overlap(array_overlap14, min_ndim=2) + + def test_overlap15(self): + self.check_overlap(array_overlap15, min_ndim=1) + + def test_overlap16(self): + self.check_overlap(array_overlap16, min_ndim=1) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors.py new file mode 100644 index 0000000000000000000000000000000000000000..407e0e7863fa61ed4053f55c9fe57d54c0b0dc49 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors.py @@ -0,0 +1,4970 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + + +import math +import os +import re +import dis +import numbers +import platform +import sys +import subprocess +import types as pytypes +import warnings +from functools import reduce +import numpy as np +from numpy.random import randn +import operator +from collections import defaultdict, namedtuple +import copy +from itertools import cycle, chain +import subprocess as subp + +import numba.parfors.parfor +from numba import (njit, prange, parallel_chunksize, + get_parallel_chunksize, set_parallel_chunksize, + set_num_threads, get_num_threads, typeof) +from numba.core import (types, errors, ir, rewrites, + typed_passes, inline_closurecall, config, compiler, cpu) +from numba.typed import Dict, List + +from numba.extending import (overload_method, register_model, + typeof_impl, unbox, NativeValue, models) +from numba.core.registry import cpu_target +from numba.core.annotations import type_annotations +from numba.core.ir_utils import (find_callname, guard, build_definitions, + get_definition, is_getitem, is_setitem, + index_var_of_get_setitem) +from numba.np.unsafe.ndarray import empty_inferred as unsafe_empty +from numba.core.compiler import (CompilerBase, DefaultPassBuilder) +from numba.core.compiler_machinery import register_pass, AnalysisPass +from numba.core.typed_passes import IRLegalization +from numba.tests.support import (TestCase, captured_stdout, MemoryLeakMixin, + override_env_config, linux_only, tag, + skip_parfors_unsupported, _32bit, needs_blas, + needs_lapack, disabled_test, skip_unless_scipy, + needs_subprocess, + skip_ppc64le_invalid_ctr_loop) +from numba.core.extending import register_jitable +from numba.core.bytecode import _fix_LOAD_GLOBAL_arg +from numba.core import utils + +import cmath +import unittest + +# NOTE: Each parfors test class is run in separate subprocess, this is to reduce +# memory pressure in CI settings. The environment variable "SUBPROC_TEST" is +# used to determine whether a test is skipped or not, such that if you want to +# run any parfors test directly this environment variable can be set. The +# subprocesses running the test classes set this environment variable as the new +# process starts which enables the tests within the process. The decorator +# @needs_subprocess is used to ensure the appropriate test skips are made. + + +@skip_parfors_unsupported +class TestParforsRunner(TestCase): + + _numba_parallel_test_ = False + + # Each test class can run for 30 minutes before time out. Extend this to an + # hour on aarch64 (some public CI systems were timing out). + _TIMEOUT = 1800 if platform.machine() != 'aarch64' else 3600 + + """This is the test runner for all the parfors tests, it runs them in + subprocesses as described above. The convention for the test method naming + is: `test_` where is the name of the test class in + this module. + """ + def runner(self): + themod = self.__module__ + test_clazz_name = self.id().split('.')[-1].split('_')[-1] + # don't specify a given test, it's an entire class that needs running + self.subprocess_test_runner(test_module=themod, + test_class=test_clazz_name, + timeout=self._TIMEOUT) + + def test_TestParforBasic(self): + self.runner() + + def test_TestParforNumericalMisc(self): + self.runner() + + def test_TestParforNumPy(self): + self.runner() + + def test_TestParfors(self): + self.runner() + + def test_TestParforsBitMask(self): + self.runner() + + def test_TestParforsDiagnostics(self): + self.runner() + + def test_TestParforsLeaks(self): + self.runner() + + def test_TestParforsMisc(self): + self.runner() + + def test_TestParforsOptions(self): + self.runner() + + def test_TestParforsSlice(self): + self.runner() + + def test_TestParforsVectorizer(self): + self.runner() + + def test_TestPrangeBasic(self): + self.runner() + + def test_TestPrangeSpecific(self): + self.runner() + + +x86_only = unittest.skipIf(platform.machine() not in ('i386', 'x86_64'), 'x86 only test') + +_GLOBAL_INT_FOR_TESTING1 = 17 +_GLOBAL_INT_FOR_TESTING2 = 5 + +TestNamedTuple = namedtuple('TestNamedTuple', ('part0', 'part1')) + + +def null_comparer(a, b): + """ + Used with check_arq_equality to indicate that we do not care + whether the value of the parameter at the end of the function + has a particular value. + """ + pass + + +@needs_subprocess +class TestParforsBase(TestCase): + """ + Base class for testing parfors. + Provides functions for compilation and three way comparison between + python functions, njit'd functions and parfor njit'd functions. + """ + + _numba_parallel_test_ = False + + def _compile_this(self, func, sig, **flags): + # This method originally used `compile_isolated` which returns a + # "CompileResult", hence this does the same. + return njit(sig, **flags)(func).overloads[sig] + + def compile_parallel(self, func, sig): + return self._compile_this(func, sig, parallel=True) + + def compile_parallel_fastmath(self, func, sig): + return self._compile_this(func, sig, parallel=True, fastmath=True) + + def compile_njit(self, func, sig): + return self._compile_this(func, sig) + + def compile_all(self, pyfunc, *args, **kwargs): + sig = tuple([numba.typeof(x) for x in args]) + + # compile the prange injected function + cpfunc = self.compile_parallel(pyfunc, sig) + + # compile a standard njit of the original function + cfunc = self.compile_njit(pyfunc, sig) + + return cfunc, cpfunc + + def check_parfors_vs_others(self, pyfunc, cfunc, cpfunc, *args, **kwargs): + """ + Checks python, njit and parfor impls produce the same result. + + Arguments: + pyfunc - the python function to test + cfunc - CompilerResult from njit of pyfunc + cpfunc - CompilerResult from njit(parallel=True) of pyfunc + args - arguments for the function being tested + Keyword Arguments: + scheduler_type - 'signed', 'unsigned' or None, default is None. + Supply in cases where the presence of a specific + scheduler is to be asserted. + fastmath_pcres - a fastmath parallel compile result, if supplied + will be run to make sure the result is correct + check_arg_equality - some functions need to check that a + parameter is modified rather than a certain + value returned. If this keyword argument + is supplied, it should be a list of + comparison functions such that the i'th + function in the list is used to compare the + i'th parameter of the njit and parallel=True + functions against the i'th parameter of the + standard Python function, asserting if they + differ. The length of this list must be equal + to the number of parameters to the function. + The null comparator is available for use + when you do not desire to test if some + particular parameter is changed. + Remaining kwargs are passed to np.testing.assert_almost_equal + """ + scheduler_type = kwargs.pop('scheduler_type', None) + check_fastmath = kwargs.pop('check_fastmath', None) + fastmath_pcres = kwargs.pop('fastmath_pcres', None) + check_scheduling = kwargs.pop('check_scheduling', True) + check_args_for_equality = kwargs.pop('check_arg_equality', None) + + def copy_args(*args): + if not args: + return tuple() + new_args = [] + for x in args: + if isinstance(x, np.ndarray): + new_args.append(x.copy('k')) + elif isinstance(x, np.number): + new_args.append(x.copy()) + elif isinstance(x, numbers.Number): + new_args.append(x) + elif x is None: + new_args.append(x) + elif isinstance(x, tuple): + new_args.append(copy.deepcopy(x)) + elif isinstance(x, list): + new_args.append(x[:]) + elif isinstance(x, Dict): + new_args.append(copy.copy(x)) + elif isinstance(x, List): + new_args.append(copy.copy(x)) + else: + raise ValueError('Unsupported argument type encountered') + return tuple(new_args) + + # python result + py_args = copy_args(*args) + py_expected = pyfunc(*py_args) + + # njit result + njit_args = copy_args(*args) + njit_output = cfunc.entry_point(*njit_args) + + # parfor result + parfor_args = copy_args(*args) + parfor_output = cpfunc.entry_point(*parfor_args) + + if check_args_for_equality is None: + np.testing.assert_almost_equal(njit_output, py_expected, **kwargs) + np.testing.assert_almost_equal(parfor_output, py_expected, **kwargs) + self.assertEqual(type(njit_output), type(parfor_output)) + else: + assert(len(py_args) == len(check_args_for_equality)) + for pyarg, njitarg, parforarg, argcomp in zip( + py_args, njit_args, parfor_args, check_args_for_equality): + argcomp(njitarg, pyarg, **kwargs) + argcomp(parforarg, pyarg, **kwargs) + + if check_scheduling: + self.check_scheduling(cpfunc, scheduler_type) + + # if requested check fastmath variant + if fastmath_pcres is not None: + parfor_fastmath_output = fastmath_pcres.entry_point(*copy_args(*args)) + np.testing.assert_almost_equal(parfor_fastmath_output, py_expected, + **kwargs) + + def check(self, pyfunc, *args, **kwargs): + """Checks that pyfunc compiles for *args under parallel=True and njit + and asserts that all version execute and produce the same result""" + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def check_variants(self, impl, arg_gen, **kwargs): + """Run self.check(impl, ...) on array data generated from arg_gen. + """ + for args in arg_gen(): + with self.subTest(list(map(typeof, args))): + self.check(impl, *args, **kwargs) + + def count_parfors_variants(self, impl, arg_gen, **kwargs): + """Run self.countParfors(impl, ...) on array types generated from + arg_gen. + """ + for args in arg_gen(): + with self.subTest(list(map(typeof, args))): + argtys = tuple(map(typeof, args)) + # At least one parfors + self.assertGreaterEqual(countParfors(impl, argtys), 1) + + def check_scheduling(self, cres, scheduler_type): + # make sure parfor set up scheduling + scheduler_str = '@do_scheduling' + if scheduler_type is not None: + if scheduler_type in ['signed', 'unsigned']: + scheduler_str += '_' + scheduler_type + else: + msg = "Unknown scheduler_type specified: %s" + raise ValueError(msg % scheduler_type) + + self.assertIn(scheduler_str, cres.library.get_llvm_str()) + + def gen_linspace(self, n, ct): + """Make *ct* sample 1D arrays of length *n* using np.linspace(). + """ + def gen(): + yield np.linspace(0, 1, n) + yield np.linspace(2, 1, n) + yield np.linspace(1, 2, n) + + src = cycle(gen()) + return [next(src) for i in range(ct)] + + def gen_linspace_variants(self, ct): + """Make 1D, 2D, 3D variants of the data in C and F orders + """ + # 1D + yield self.gen_linspace(10, ct=ct) + + # 2D + arr2ds = [x.reshape((2, 3)) + for x in self.gen_linspace(n=2 * 3, ct=ct)] + yield arr2ds + # Fortran order + yield [np.asfortranarray(x) for x in arr2ds] + + # 3D + arr3ds = [x.reshape((2, 3, 4)) + for x in self.gen_linspace(n=2 * 3 * 4, ct=ct)] + yield arr3ds + # Fortran order + yield [np.asfortranarray(x) for x in arr3ds] + + def _filter_mod(self, mod, magicstr, checkstr=None): + """ helper function to filter out modules by name""" + filt = [x for x in mod if magicstr in x.name] + if checkstr is not None: + for x in filt: + assert checkstr in str(x) + return filt + + def _get_gufunc_modules(self, cres, magicstr, checkstr=None): + """ gets the gufunc LLVM Modules""" + _modules = [x for x in cres.library._codegen._engine._ee._modules] + # make sure to only use modules that are actually used by cres and + # aren't just in the EE by virtue of shared compilation context. + potential_matches = self._filter_mod(_modules, magicstr, + checkstr=checkstr) + + lib_asm = cres.library.get_asm_str() + ret = [] + for mod in potential_matches: + if mod.name in lib_asm: + ret.append(mod) + return ret + + def _get_gufunc_info(self, cres, fn): + """ helper for gufunc IR/asm generation""" + # get the gufunc modules + magicstr = '__numba_parfor_gufunc' + gufunc_mods = self._get_gufunc_modules(cres, magicstr) + x = dict() + for mod in gufunc_mods: + x[mod.name] = fn(mod) + return x + + def _get_gufunc_ir(self, cres): + """ + Returns the IR of the gufuncs used as parfor kernels + as a dict mapping the gufunc name to its IR. + + Arguments: + cres - a CompileResult from `njit(parallel=True, ...)` + """ + return self._get_gufunc_info(cres, str) + + def _get_gufunc_asm(self, cres): + """ + Returns the assembly of the gufuncs used as parfor kernels + as a dict mapping the gufunc name to its assembly. + + Arguments: + cres - a CompileResult from `njit(parallel=True, ...)` + """ + tm = cres.library._codegen._tm + def emit_asm(mod): + return str(tm.emit_assembly(mod)) + return self._get_gufunc_info(cres, emit_asm) + + def assert_fastmath(self, pyfunc, sig): + """ + Asserts that the fastmath flag has some effect in that suitable + instructions are now labelled as `fast`. Whether LLVM can actually do + anything to optimise better now the derestrictions are supplied is + another matter! + + Arguments: + pyfunc - a function that contains operations with parallel semantics + sig - the type signature of pyfunc + """ + + cres = self.compile_parallel_fastmath(pyfunc, sig) + _ir = self._get_gufunc_ir(cres) + + def _get_fast_instructions(ir): + splitted = ir.splitlines() + fast_inst = [] + for x in splitted: + m = re.search(r'\bfast\b', x) # \b for wholeword + if m is not None: + fast_inst.append(x) + return fast_inst + + def _assert_fast(instrs): + ops = ('fadd', 'fsub', 'fmul', 'fdiv', 'frem', 'fcmp', 'call') + for inst in instrs: + count = 0 + for op in ops: + match = op + ' fast' + if match in inst: + count += 1 + self.assertTrue(count > 0) + + for name, guir in _ir.items(): + inst = _get_fast_instructions(guir) + _assert_fast(inst) + + +def blackscholes_impl(sptprice, strike, rate, volatility, timev): + # blackscholes example + logterm = np.log(sptprice / strike) + powterm = 0.5 * volatility * volatility + den = volatility * np.sqrt(timev) + d1 = (((rate + powterm) * timev) + logterm) / den + d2 = d1 - den + NofXd1 = 0.5 + 0.5 * 2.0 * d1 + NofXd2 = 0.5 + 0.5 * 2.0 * d2 + futureValue = strike * np.exp(- rate * timev) + c1 = futureValue * NofXd2 + call = sptprice * NofXd1 - c1 + put = call - futureValue + sptprice + return put + + +def lr_impl(Y, X, w, iterations): + # logistic regression example + for i in range(iterations): + w -= np.dot(((1.0 / (1.0 + np.exp(-Y * np.dot(X, w))) - 1.0) * Y), X) + return w + +def example_kmeans_test(A, numCenter, numIter, init_centroids): + centroids = init_centroids + N, D = A.shape + + for l in range(numIter): + dist = np.array([[math.sqrt(np.sum((A[i,:]-centroids[j,:])**2)) + for j in range(numCenter)] for i in range(N)]) + labels = np.array([dist[i,:].argmin() for i in range(N)]) + + centroids = np.array([[np.sum(A[labels==i, j])/np.sum(labels==i) + for j in range(D)] for i in range(numCenter)]) + + return centroids + +def get_optimized_numba_ir(test_func, args, **kws): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_func) + if kws: + options = cpu.ParallelOptions(kws) + else: + options = cpu.ParallelOptions(True) + + tp = TestPipeline(typingctx, targetctx, args, test_ir) + + typingctx.refresh() + targetctx.refresh() + + inline_pass = inline_closurecall.InlineClosureCallPass(tp.state.func_ir, + options, + typed=True) + inline_pass.run() + + rewrites.rewrite_registry.apply('before-inference', tp.state) + + tp.state.typemap, tp.state.return_type, tp.state.calltypes, _ = \ + typed_passes.type_inference_stage(tp.state.typingctx, + tp.state.targetctx, tp.state.func_ir, tp.state.args, None) + + type_annotations.TypeAnnotation( + func_ir=tp.state.func_ir, + typemap=tp.state.typemap, + calltypes=tp.state.calltypes, + lifted=(), + lifted_from=None, + args=tp.state.args, + return_type=tp.state.return_type, + html_output=config.HTML) + + diagnostics = numba.parfors.parfor.ParforDiagnostics() + + preparfor_pass = numba.parfors.parfor.PreParforPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.typingctx, tp.state.targetctx, options, + swapped=diagnostics.replaced_fns) + preparfor_pass.run() + + rewrites.rewrite_registry.apply('after-inference', tp.state) + + flags = compiler.Flags() + parfor_pass = numba.parfors.parfor.ParforPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + parfor_pass = numba.parfors.parfor.ParforFusionPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + parfor_pass = numba.parfors.parfor.ParforPreLoweringPass( + tp.state.func_ir, tp.state.typemap, tp.state.calltypes, + tp.state.return_type, tp.state.typingctx, tp.state.targetctx, + options, flags, tp.state.metadata, diagnostics=diagnostics) + parfor_pass.run() + test_ir._definitions = build_definitions(test_ir.blocks) + + return test_ir, tp + +def countParfors(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + ret_count = 0 + + for label, block in test_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += 1 + + return ret_count + + +def countArrays(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + return _count_arrays_inner(test_ir.blocks, tp.state.typemap) + +def get_init_block_size(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + blocks = test_ir.blocks + + ret_count = 0 + + for label, block in blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += len(inst.init_block.body) + + return ret_count + +def _count_arrays_inner(blocks, typemap): + ret_count = 0 + arr_set = set() + + for label, block in blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, numba.parfors.parfor.Parfor): + parfor_blocks = inst.loop_body.copy() + parfor_blocks[0] = inst.init_block + ret_count += _count_arrays_inner(parfor_blocks, typemap) + if (isinstance(inst, ir.Assign) + and isinstance(typemap[inst.target.name], + types.ArrayCompatible)): + arr_set.add(inst.target.name) + + ret_count += len(arr_set) + return ret_count + +def countArrayAllocs(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + ret_count = 0 + + for block in test_ir.blocks.values(): + ret_count += _count_array_allocs_inner(test_ir, block) + + return ret_count + +def _count_array_allocs_inner(func_ir, block): + ret_count = 0 + for inst in block.body: + if isinstance(inst, numba.parfors.parfor.Parfor): + ret_count += _count_array_allocs_inner(func_ir, inst.init_block) + for b in inst.loop_body.values(): + ret_count += _count_array_allocs_inner(func_ir, b) + + if (isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Expr) + and inst.value.op == 'call' + and (guard(find_callname, func_ir, inst.value) == ('empty', 'numpy') + or guard(find_callname, func_ir, inst.value) + == ('empty_inferred', 'numba.np.unsafe.ndarray'))): + ret_count += 1 + + return ret_count + +def countNonParforArrayAccesses(test_func, args, **kws): + test_ir, tp = get_optimized_numba_ir(test_func, args, **kws) + return _count_non_parfor_array_accesses_inner(test_ir, test_ir.blocks, + tp.state.typemap) + +def _count_non_parfor_array_accesses_inner(f_ir, blocks, typemap, parfor_indices=None): + ret_count = 0 + if parfor_indices is None: + parfor_indices = set() + + for label, block in blocks.items(): + for stmt in block.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + parfor_indices.add(stmt.index_var.name) + parfor_blocks = stmt.loop_body.copy() + parfor_blocks[0] = stmt.init_block + ret_count += _count_non_parfor_array_accesses_inner( + f_ir, parfor_blocks, typemap, parfor_indices) + + # getitem + elif (is_getitem(stmt) and isinstance(typemap[stmt.value.value.name], + types.ArrayCompatible) and not _uses_indices( + f_ir, index_var_of_get_setitem(stmt), parfor_indices)): + ret_count += 1 + + # setitem + elif (is_setitem(stmt) and isinstance(typemap[stmt.target.name], + types.ArrayCompatible) and not _uses_indices( + f_ir, index_var_of_get_setitem(stmt), parfor_indices)): + ret_count += 1 + + # find parfor_index aliases + elif (isinstance(stmt, ir.Assign) and + isinstance(stmt.value, ir.Var) and + stmt.value.name in parfor_indices): + parfor_indices.add(stmt.target.name) + + return ret_count + +def _uses_indices(f_ir, index, index_set): + if index.name in index_set: + return True + + ind_def = guard(get_definition, f_ir, index) + if isinstance(ind_def, ir.Expr) and ind_def.op == 'build_tuple': + varnames = set(v.name for v in ind_def.items) + return len(varnames & index_set) != 0 + + return False + + +class TestPipeline(object): + def __init__(self, typingctx, targetctx, args, test_ir): + self.state = compiler.StateDict() + self.state.typingctx = typingctx + self.state.targetctx = targetctx + self.state.args = args + self.state.func_ir = test_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + self.state.metadata = {} + + +@skip_parfors_unsupported +class TestParforBasic(TestParforsBase): + """Smoke tests for the parfors transforms. These tests check the most basic + functionality""" + + def __init__(self, *args): + TestParforsBase.__init__(self, *args) + # these are used in the mass of simple tests + m = np.reshape(np.arange(12.), (3, 4)) + self.simple_args = [np.arange(3.), np.arange(4.), m, m.T] + + def test_simple01(self): + def test_impl(): + return np.ones(()) + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_simple02(self): + def test_impl(): + return np.ones((1,)) + self.check(test_impl) + + def test_simple03(self): + def test_impl(): + return np.ones((1, 2)) + self.check(test_impl) + + def test_simple04(self): + def test_impl(): + return np.ones(1) + self.check(test_impl) + + def test_simple07(self): + def test_impl(): + return np.ones((1, 2), dtype=np.complex128) + self.check(test_impl) + + def test_simple08(self): + def test_impl(): + return np.ones((1, 2)) + np.ones((1, 2)) + self.check(test_impl) + + def test_simple09(self): + def test_impl(): + return np.ones((1, 1)) + self.check(test_impl) + + def test_simple10(self): + def test_impl(): + return np.ones((0, 0)) + self.check(test_impl) + + def test_simple11(self): + def test_impl(): + return np.ones((10, 10)) + 1. + self.check(test_impl) + + def test_simple12(self): + def test_impl(): + return np.ones((10, 10)) + np.complex128(1.) + self.check(test_impl) + + def test_simple13(self): + def test_impl(): + return np.complex128(1.) + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_simple14(self): + def test_impl(): + return np.ones((10, 10))[0::20] + self.check(test_impl) + + def test_simple15(self): + def test_impl(v1, v2, m1, m2): + return v1 + v1 + self.check(test_impl, *self.simple_args) + + def test_simple16(self): + def test_impl(v1, v2, m1, m2): + return m1 + m1 + self.check(test_impl, *self.simple_args) + + def test_simple17(self): + def test_impl(v1, v2, m1, m2): + return m2 + v1 + self.check(test_impl, *self.simple_args) + + @needs_lapack + def test_simple18(self): + def test_impl(v1, v2, m1, m2): + return m1.T + np.linalg.svd(m2)[1] + self.check(test_impl, *self.simple_args) + + @needs_blas + def test_simple19(self): + def test_impl(v1, v2, m1, m2): + return np.dot(m1, v2) + self.check(test_impl, *self.simple_args) + + @needs_blas + def test_simple20(self): + def test_impl(v1, v2, m1, m2): + return np.dot(m1, m2) + # gemm is left to BLAS + with self.assertRaises(AssertionError) as raises: + self.check(test_impl, *self.simple_args) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + @needs_blas + def test_simple21(self): + def test_impl(v1, v2, m1, m2): + return np.dot(v1, v1) + self.check(test_impl, *self.simple_args) + + def test_simple22(self): + def test_impl(v1, v2, m1, m2): + return np.sum(v1 + v1) + self.check(test_impl, *self.simple_args) + + def test_simple23(self): + def test_impl(v1, v2, m1, m2): + x = 2 * v1 + y = 2 * v1 + return 4 * np.sum(x**2 + y**2 < 1) / 10 + self.check(test_impl, *self.simple_args) + + def test_simple24(self): + def test_impl(): + n = 20 + A = np.ones((n, n)) + b = np.arange(n) + return np.sum(A[:, b]) + self.check(test_impl) + + @disabled_test + def test_simple_operator_15(self): + """same as corresponding test_simple_ case but using operator.add""" + def test_impl(v1, v2, m1, m2): + return operator.add(v1, v1) + + self.check(test_impl, *self.simple_args) + + @disabled_test + def test_simple_operator_16(self): + def test_impl(v1, v2, m1, m2): + return operator.add(m1, m1) + + self.check(test_impl, *self.simple_args) + + @disabled_test + def test_simple_operator_17(self): + def test_impl(v1, v2, m1, m2): + return operator.add(m2, v1) + + self.check(test_impl, *self.simple_args) + + def test_inplace_alias(self): + # issue7201 + def test_impl(a): + a += 1 + a[:] = 3 + + def comparer(a, b): + np.testing.assert_equal(a, b) + + x = np.ones(1) + self.check(test_impl, x, check_arg_equality=[comparer]) + + +@skip_parfors_unsupported +class TestParforNumericalMisc(TestParforsBase): + """ Miscellaneous 'classical' numerical tests """ + + def test_pi(self): + def test_impl(n): + x = 2 * np.random.ranf(n) - 1 + y = 2 * np.random.ranf(n) - 1 + return 4 * np.sum(x**2 + y**2 < 1) / n + + self.check(test_impl, 100000, decimal=1) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_blackscholes(self): + # blackscholes takes 5 1D float array args + args = (numba.float64[:], ) * 5 + self.assertEqual(countParfors(blackscholes_impl, args), 1) + + @needs_blas + def test_logistic_regression(self): + args = (numba.float64[:], numba.float64[:,:], numba.float64[:], + numba.int64) + self.assertEqual(countParfors(lr_impl, args), 2) + self.assertEqual(countArrayAllocs(lr_impl, args), 1) + + def test_kmeans(self): + np.random.seed(0) + N = 1024 + D = 10 + centers = 3 + A = np.random.ranf((N, D)) + init_centroids = np.random.ranf((centers, D)) + self.check(example_kmeans_test, A, centers, 3, init_centroids, + decimal=1) + # TODO: count parfors after k-means fusion is working + # requires recursive parfor counting + arg_typs = (types.Array(types.float64, 2, 'C'), types.intp, types.intp, + types.Array(types.float64, 2, 'C')) + self.assertEqual( + countNonParforArrayAccesses(example_kmeans_test, arg_typs), 0) + + +@skip_parfors_unsupported +class TestParforNumPy(TestParforsBase): + """Tests NumPy functionality under parfors""" + + @needs_blas + def test_mvdot(self): + def test_impl(a, v): + return np.dot(a, v) + + A = np.linspace(0, 1, 20).reshape(2, 10) + v = np.linspace(2, 1, 10) + + self.check(test_impl, A, v) + + def test_fuse_argmin_argmax_max_min(self): + for op in [np.argmin, np.argmax, np.min, np.max]: + def test_impl(n): + A = np.ones(n) + C = op(A) + B = A.sum() + return B + C + self.check(test_impl, 256) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_np_random_func_direct_import(self): + def test_impl(n): + A = randn(n) + return A[0] + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_arange(self): + # test with stop only + def test_impl1(n): + return np.arange(n) + # start and stop + def test_impl2(s, n): + return np.arange(s, n) + # start, step, stop + def test_impl3(s, n, t): + return np.arange(s, n, t) + + for arg in [11, 128, 30.0, complex(4,5), complex(5,4)]: + self.check(test_impl1, arg) + self.check(test_impl2, 2, arg) + self.check(test_impl3, 2, arg, 2) + + def test_arange_dtype(self): + # test with stop only + def test_impl1(n): + return np.arange(n, dtype=np.float32) + # start and stop + def test_impl2(s, n): + return np.arange(s, n, dtype=np.float32) + # start, step, stop + def test_impl3(s, n, t): + return np.arange(s, n, t, dtype=np.float32) + + for arg in [11, 128, 30.0]: + self.check(test_impl1, arg) + self.check(test_impl2, 2, arg) + self.check(test_impl3, 2, arg, 2) + + def test_linspace(self): + # without num + def test_impl1(start, stop): + return np.linspace(start, stop) + # with num + def test_impl2(start, stop, num): + return np.linspace(start, stop, num) + + for arg in [11, 128, 30.0, complex(4,5), complex(5,4)]: + self.check(test_impl1, 2, arg) + self.check(test_impl2, 2, arg, 30) + + def test_mean(self): + def test_impl(A): + return A.mean() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + self.check(test_impl, A) + self.check(test_impl, B) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 1, 'C'), )), 1) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 2, 'C'), )), 1) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_var(self): + def test_impl(A): + return A.var() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + C = A + 1j * A + self.check(test_impl, A) + self.check(test_impl, B) + self.check(test_impl, C) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 1, 'C'), )), 2) + self.assertEqual(countParfors(test_impl, (types.Array(types.float64, 2, 'C'), )), 2) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_std(self): + def test_impl(A): + return A.std() + N = 100 + A = np.random.ranf(N) + B = np.random.randint(10, size=(N, 3)) + C = A + 1j * A + self.check(test_impl, A) + self.check(test_impl, B) + self.check(test_impl, C) + argty = (types.Array(types.float64, 1, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 2) + self.assertEqual(countParfors(test_impl, argty), 2) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_random_parfor(self): + """ + Test function with only a random call to make sure a random function + like ranf is actually translated to a parfor. + """ + def test_impl(n): + A = np.random.ranf((n, n)) + return A + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_randoms(self): + def test_impl(n): + A = np.random.standard_normal(size=(n, n)) + B = np.random.randn(n, n) + C = np.random.normal(0.0, 1.0, (n, n)) + D = np.random.chisquare(1.0, (n, n)) + E = np.random.randint(1, high=3, size=(n, n)) + F = np.random.triangular(1, 2, 3, (n, n)) + return np.sum(A+B+C+D+E+F) + + n = 128 + cpfunc = self.compile_parallel(test_impl, (numba.typeof(n),)) + parfor_output = cpfunc.entry_point(n) + py_output = test_impl(n) + # check results within 5% since random numbers generated in parallel + np.testing.assert_allclose(parfor_output, py_output, rtol=0.05) + self.assertEqual(countParfors(test_impl, (types.int64, )), 1) + + def test_dead_randoms(self): + def test_impl(n): + A = np.random.standard_normal(size=(n, n)) + B = np.random.randn(n, n) + C = np.random.normal(0.0, 1.0, (n, n)) + D = np.random.chisquare(1.0, (n, n)) + E = np.random.randint(1, high=3, size=(n, n)) + F = np.random.triangular(1, 2, 3, (n, n)) + return 3 + + n = 128 + cpfunc = self.compile_parallel(test_impl, (numba.typeof(n),)) + parfor_output = cpfunc.entry_point(n) + py_output = test_impl(n) + self.assertEqual(parfor_output, py_output) + self.assertEqual(countParfors(test_impl, (types.int64, )), 0) + + def test_min(self): + def test_impl1(A): + return A.min() + + def test_impl2(A): + return np.min(A) + + n = 211 + A = np.random.ranf(n) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([np.inf, np.inf]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = ("zero-size array to reduction operation " + "minimum which has no identity") + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_max(self): + def test_impl1(A): + return A.max() + + def test_impl2(A): + return np.max(A) + + n = 211 + A = np.random.ranf(n) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([-np.inf, -np.inf]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = ("zero-size array to reduction operation " + "maximum which has no identity") + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_argmax(self): + def test_impl1(A): + return A.argmax() + + def test_impl2(A): + return np.argmax(A) + + n = 211 + A = np.array([1., 0., 3., 2., 3.]) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([1., 0., np.nan, 2., 3.]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = 'attempt to get argmax of an empty sequence' + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_argmin(self): + def test_impl1(A): + return A.argmin() + + def test_impl2(A): + return np.argmin(A) + + n = 211 + A = np.array([1., 0., 2., 0., 3.]) + B = np.random.randint(10, size=n).astype(np.int32) + C = np.random.ranf((n, n)) # test multi-dimensional array + D = np.array([1., 0., np.nan, 0., 3.]) + self.check(test_impl1, A) + self.check(test_impl1, B) + self.check(test_impl1, C) + self.check(test_impl1, D) + self.check(test_impl2, A) + self.check(test_impl2, B) + self.check(test_impl2, C) + self.check(test_impl2, D) + + # checks that 0d array input raises + msg = 'attempt to get argmin of an empty sequence' + for impl in (test_impl1, test_impl2): + pcfunc = self.compile_parallel(impl, (types.int64[:],)) + with self.assertRaises(ValueError) as e: + pcfunc.entry_point(np.array([], dtype=np.int64)) + self.assertIn(msg, str(e.exception)) + + # Test variants + data_gen = lambda: self.gen_linspace_variants(1) + self.check_variants(test_impl1, data_gen) + self.count_parfors_variants(test_impl1, data_gen) + self.check_variants(test_impl2, data_gen) + self.count_parfors_variants(test_impl2, data_gen) + + def test_ndarray_fill(self): + def test_impl(x): + x.fill(7.0) + return x + x = np.zeros(10) + self.check(test_impl, x) + argty = (types.Array(types.float64, 1, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 1) + + def test_ndarray_fill2d(self): + def test_impl(x): + x.fill(7.0) + return x + x = np.zeros((2,2)) + self.check(test_impl, x) + argty = (types.Array(types.float64, 2, 'C'),) + self.assertEqual(countParfors(test_impl, argty), 1) + + def test_reshape_with_neg_one(self): + # issue3314 + def test_impl(a, b): + result_matrix = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1, 1) + result_data = sub_a / z + result_matrix[:,:,0] = result_data + return result_matrix + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + + self.check(test_impl, a, b) + + def test_reshape_with_large_neg(self): + # issue3314 + def test_impl(a, b): + result_matrix = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1307, 1) + result_data = sub_a / z + result_matrix[:,:,0] = result_data + return result_matrix + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + + self.check(test_impl, a, b) + + def test_reshape_with_too_many_neg_one(self): + # issue3314 + with self.assertRaises(errors.UnsupportedRewriteError) as raised: + @njit(parallel=True) + def test_impl(a, b): + rm = np.zeros((b, b, 1), dtype=np.float64) + sub_a = a[0:b] + a = sub_a.size + b = a / 1 + z = sub_a.reshape(-1, -1) + result_data = sub_a / z + rm[:,:,0] = result_data + return rm + + a = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]) + b = 3 + test_impl(a, b) + + msg = ("The reshape API may only include one negative argument.") + self.assertIn(msg, str(raised.exception)) + + def test_0d_array(self): + def test_impl(n): + return np.sum(n) + np.prod(n) + np.min(n) + np.max(n) + np.var(n) + self.check(test_impl, np.array(7), check_scheduling=False) + + def test_real_imag_attr(self): + # See issue 8012 + def test_impl(z): + return np.sum(z.real ** 2 + z.imag ** 2) + + z = np.arange(5) * (1 + 1j) + self.check(test_impl, z) + self.assertEqual(countParfors(test_impl, (types.complex128[::1],)), 1) + + +class TestParforsUnsupported(TestCase): + """Tests for unsupported use of parfors""" + @unittest.skipIf(not _32bit, "Only impacts 32 bit hardware") + @needs_blas + def test_unsupported_combination_raises(self): + """ + This test is in place until issues with the 'parallel' + target on 32 bit hardware are fixed. + """ + with self.assertRaises(errors.UnsupportedParforsError) as raised: + @njit(parallel=True) + def ddot(a, v): + return np.dot(a, v) + + A = np.linspace(0, 1, 20).reshape(2, 10) + v = np.linspace(2, 1, 10) + ddot(A, v) + + msg = ("The 'parallel' target is not currently supported on 32 bit " + "hardware") + self.assertIn(msg, str(raised.exception)) + +@skip_parfors_unsupported +class TestParfors(TestParforsBase): + """ Tests cpython, reduction and various parfors features""" + + def test_arraymap(self): + def test_impl(a, x, y): + return a * x + y + + self.check_variants(test_impl, lambda: self.gen_linspace_variants(3)) + + def test_0d_broadcast(self): + def test_impl(): + X = np.array(1) + Y = np.ones((10, 12)) + return np.sum(X + Y) + self.check(test_impl) + self.assertEqual(countParfors(test_impl, ()), 1) + + def test_2d_parfor(self): + def test_impl(): + X = np.ones((10, 12)) + Y = np.zeros((10, 12)) + return np.sum(X + Y) + self.check(test_impl) + self.assertEqual(countParfors(test_impl, ()), 1) + + def test_nd_parfor(self): + def case1(): + X = np.ones((10, 12)) + Y = np.zeros((10, 12)) + yield (X, Y) + + data_gen = lambda: chain(case1(), self.gen_linspace_variants(2)) + + def test_impl(X, Y): + return np.sum(X + Y) + + self.check_variants(test_impl, data_gen) + self.count_parfors_variants(test_impl, data_gen) + + def test_np_func_direct_import(self): + from numpy import ones # import here becomes FreeVar + def test_impl(n): + A = ones(n) + return A[0] + n = 111 + self.check(test_impl, n) + + def test_size_assertion(self): + def test_impl(m, n): + A = np.ones(m) + B = np.ones(n) + return np.sum(A + B) + + self.check(test_impl, 10, 10) + with self.assertRaises(AssertionError) as raises: + cfunc = njit(parallel=True)(test_impl) + cfunc(10, 9) + msg = "Sizes of A, B do not match" + self.assertIn(msg, str(raises.exception)) + + def test_cfg(self): + # from issue #2477 + def test_impl(x, is_positive, N): + for i in numba.prange(2): + for j in range( i*N//2, (i+1)*N//2 ): + is_positive[j] = 0 + if x[j] > 0: + is_positive[j] = 1 + + return is_positive + + N = 100 + x = np.random.rand(N) + is_positive = np.zeros(N) + self.check(test_impl, x, is_positive, N) + + def test_reduce(self): + def test_impl(A): + init_val = 10 + return reduce(lambda a,b: min(a, b), A, init_val) + + n = 211 + A = np.random.ranf(n) + self.check(test_impl, A) + A = np.random.randint(10, size=n).astype(np.int32) + self.check(test_impl, A) + + # test checking the number of arguments for the reduce function + def test_impl(): + g = lambda x: x ** 2 + return reduce(g, np.array([1, 2, 3, 4, 5]), 2) + with self.assertTypingError(): + self.check(test_impl) + + # test checking reduction over bitarray masked arrays + n = 160 + A = np.random.randint(10, size=n).astype(np.int32) + def test_impl(A): + return np.sum(A[A>=3]) + self.check(test_impl, A) + # TODO: this should fuse + # self.assertTrue(countParfors(test_impl, (numba.float64[:],)) == 1) + + def test_impl(A): + B = A[:,0] + return np.sum(A[B>=3,1]) + self.check(test_impl, A.reshape((16,10))) + # TODO: this should also fuse + #self.assertTrue(countParfors(test_impl, (numba.float64[:,:],)) == 1) + + def test_impl(A): + B = A[:,0] + return np.sum(A[B>=3,1:2]) + self.check(test_impl, A.reshape((16,10))) + # this doesn't fuse due to mixed indices + self.assertEqual(countParfors(test_impl, (numba.float64[:,:],)), 2) + + def test_impl(A): + min_val = np.amin(A) + return A - min_val + self.check(test_impl, A) + # this doesn't fuse due to use of reduction variable + self.assertEqual(countParfors(test_impl, (numba.float64[:],)), 2) + + def test_use_of_reduction_var1(self): + def test_impl(): + acc = 0 + for i in prange(1): + acc = cmath.sqrt(acc) + return acc + + # checks that invalid use of reduction variable is detected + msg = ("Use of reduction variable acc in an unsupported reduction function.") + with self.assertRaises(ValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_unsupported_floordiv1(self): + def test_impl(): + acc = 100 + for i in prange(2): + acc //= 2 + return acc + + # checks that invalid use of ifloordiv reduction operator is detected + msg = ("Parallel floordiv reductions are not supported. " + "If all divisors are integers then a floordiv " + "reduction can in some cases be parallelized as " + "a multiply reduction followed by a floordiv of " + "the resulting product.") + with self.assertRaises(errors.NumbaValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_unsupported_xor1(self): + def test_impl(): + acc = 100 + for i in prange(2): + acc ^= i + 2 + return acc + + msg = ("Use of reduction variable acc in an unsupported reduction function.") + with self.assertRaises(ValueError) as e: + pcfunc = self.compile_parallel(test_impl, ()) + self.assertIn(msg, str(e.exception)) + + def test_parfor_array_access1(self): + # signed index of the prange generated by sum() should be replaced + # resulting in array A to be eliminated (see issue #2846) + def test_impl(n): + A = np.ones(n) + return A.sum() + + n = 211 + self.check(test_impl, n) + self.assertEqual(countArrays(test_impl, (types.intp,)), 0) + + def test_parfor_array_access2(self): + # in this test, the prange index has the same name (i) in two loops + # thus, i has multiple definitions and is harder to replace + def test_impl(n): + A = np.ones(n) + m = 0 + n = 0 + for i in numba.prange(len(A)): + m += A[i] + + for i in numba.prange(len(A)): + if m == n: # access in another block + n += A[i] + + return m + n + + n = 211 + self.check(test_impl, n) + self.assertEqual(countNonParforArrayAccesses(test_impl, (types.intp,)), 0) + + def test_parfor_array_access3(self): + def test_impl(n): + A = np.ones(n, np.int64) + m = 0 + for i in numba.prange(len(A)): + m += A[i] + if m==2: + i = m + + n = 211 + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.check(test_impl, n) + self.assertIn("Overwrite of parallel loop index", str(raises.exception)) + + @needs_blas + def test_parfor_array_access4(self): + # in this test, one index of a multi-dim access should be replaced + # np.dot parallel implementation produces this case + def test_impl(A, b): + return np.dot(A, b) + + n = 211 + d = 4 + A = np.random.ranf((n, d)) + b = np.random.ranf(d) + self.check(test_impl, A, b) + # make sure the parfor index is replaced in build_tuple of access to A + test_ir, tp = get_optimized_numba_ir( + test_impl, (types.Array(types.float64, 2, 'C'), + types.Array(types.float64, 1, 'C'))) + # this code should have one basic block after optimization + self.assertTrue(len(test_ir.blocks) == 1 and 0 in test_ir.blocks) + block = test_ir.blocks[0] + parfor_found = False + parfor = None + for stmt in block.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + parfor_found = True + parfor = stmt + + self.assertTrue(parfor_found) + build_tuple_found = False + # there should be only one build_tuple + for bl in parfor.loop_body.values(): + for stmt in bl.body: + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'build_tuple'): + build_tuple_found = True + self.assertTrue(parfor.index_var in stmt.value.items) + + self.assertTrue(build_tuple_found) + + def test_parfor_dtype_type(self): + # test array type replacement creates proper type + def test_impl(a): + for i in numba.prange(len(a)): + a[i] = a.dtype.type(0) + return a[4] + + a = np.ones(10) + self.check(test_impl, a) + + def test_parfor_array_access5(self): + # one dim is slice in multi-dim access + def test_impl(n): + X = np.ones((n, 3)) + y = 0 + for i in numba.prange(n): + y += X[i,:].sum() + return y + + n = 211 + self.check(test_impl, n) + self.assertEqual(countNonParforArrayAccesses(test_impl, (types.intp,)), 0) + + @disabled_test # Test itself is problematic, see #3155 + def test_parfor_hoist_setitem(self): + # Make sure that read of out is not hoisted. + def test_impl(out): + for i in prange(10): + out[0] = 2 * out[0] + return out[0] + + out = np.ones(1) + self.check(test_impl, out) + + @needs_blas + def test_parfor_generate_fuse(self): + # issue #2857 + def test_impl(N, D): + w = np.ones(D) + X = np.ones((N, D)) + Y = np.ones(N) + for i in range(3): + B = (-Y * np.dot(X, w)) + + return B + + n = 211 + d = 3 + self.check(test_impl, n, d) + self.assertEqual(countArrayAllocs(test_impl, (types.intp, types.intp)), 4) + self.assertEqual(countParfors(test_impl, (types.intp, types.intp)), 4) + + def test_ufunc_expr(self): + # issue #2885 + def test_impl(A, B): + return np.bitwise_and(A, B) + + A = np.ones(3, np.uint8) + B = np.ones(3, np.uint8) + B[1] = 0 + self.check(test_impl, A, B) + + def test_find_callname_intrinsic(self): + def test_impl(n): + A = unsafe_empty((n,)) + for i in range(n): + A[i] = i + 2.0 + return A + + # the unsafe allocation should be found even though it is imported + # as a different name + self.assertEqual(countArrayAllocs(test_impl, (types.intp,)), 1) + + def test_reduction_var_reuse(self): + # issue #3139 + def test_impl(n): + acc = 0 + for i in prange(n): + acc += 1 + + for i in prange(n): + acc += 2 + + return acc + self.check(test_impl, 16) + + def test_non_identity_initial(self): + # issue #7344 + def test_impl(A, cond): + s = 1 + for i in prange(A.shape[0]): + if cond[i]: + s += 1 + return s + self.check(test_impl, np.ones(10), np.ones(10).astype('bool')) + + def test_if_not_else_reduction(self): + # issue #7344 + def test_impl(A, cond): + s = 1 + t = 10 + for i in prange(A.shape[0]): + if cond[i]: + s += 1 + t += 1 + else: + s += 2 + return s + t + self.check(test_impl, np.ones(10), np.ones(10).astype('bool')) + + def test_two_d_array_reduction_reuse(self): + def test_impl(n): + shp = (13, 17) + size = shp[0] * shp[1] + result1 = np.zeros(shp, np.int_) + tmp = np.arange(size).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_one_d_array_reduction(self): + def test_impl(n): + result = np.zeros(1, np.int_) + + for i in numba.prange(n): + result += np.array([i], np.int_) + + return result + + self.check(test_impl, 100) + + def test_two_d_array_reduction(self): + def test_impl(n): + shp = (13, 17) + size = shp[0] * shp[1] + result1 = np.zeros(shp, np.int_) + tmp = np.arange(size).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_two_d_array_reduction_with_float_sizes(self): + # result1 is float32 and tmp is float64. + # Tests reduction with differing dtypes. + def test_impl(n): + shp = (2, 3) + result1 = np.zeros(shp, np.float32) + tmp = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).reshape(shp) + + for i in numba.prange(n): + result1 += tmp + + return result1 + + self.check(test_impl, 100) + + def test_two_d_array_reduction_prod(self): + def test_impl(n): + shp = (13, 17) + result1 = 2 * np.ones(shp, np.int_) + tmp = 2 * np.ones_like(result1) + + for i in numba.prange(n): + result1 *= tmp + + return result1 + + self.check(test_impl, 100) + + def test_three_d_array_reduction(self): + def test_impl(n): + shp = (3, 2, 7) + result1 = np.zeros(shp, np.int_) + + for i in numba.prange(n): + result1 += np.ones(shp, np.int_) + + return result1 + + self.check(test_impl, 100) + + def test_preparfor_canonicalize_kws(self): + # test canonicalize_array_math typing for calls with kw args + def test_impl(A): + return A.argsort() + 1 + + n = 211 + A = np.arange(n) + self.check(test_impl, A) + + def test_preparfor_datetime64(self): + # test array.dtype transformation for datetime64 + def test_impl(A): + return A.dtype + + A = np.empty(1, np.dtype('datetime64[ns]')) + cpfunc = self.compile_parallel(test_impl, (numba.typeof(A),)) + self.assertEqual(cpfunc.entry_point(A), test_impl(A)) + + def test_no_hoisting_with_member_function_call(self): + def test_impl(X): + n = X.shape[0] + acc = 0 + for i in prange(n): + R = {1, 2, 3} + R.add(i) + tmp = 0 + for x in R: + tmp += x + acc += tmp + return acc + + self.check(test_impl, np.random.ranf(128)) + + def test_array_compare_scalar(self): + """ issue3671: X != 0 becomes an arrayexpr with operator.ne. + That is turned into a parfor by devectorizing. Make sure + the return type of the devectorized operator.ne + on integer types works properly. + """ + def test_impl(): + X = np.zeros(10, dtype=np.int_) + return X != 0 + + self.check(test_impl) + + def test_array_analysis_optional_def(self): + def test_impl(x, half): + size = len(x) + parr = x[0:size] + + if half: + parr = x[0:size//2] + + return parr.sum() + x = np.ones(20) + self.check(test_impl, x, True, check_scheduling=False) + + def test_prange_side_effects(self): + def test_impl(a, b): + data = np.empty(len(a), dtype=np.float64) + size = len(data) + for i in numba.prange(size): + data[i] = a[i] + for i in numba.prange(size): + data[i] = data[i] + b[i] + return data + + x = np.arange(10 ** 2, dtype=float) + y = np.arange(10 ** 2, dtype=float) + + self.check(test_impl, x, y) + self.assertEqual(countParfors(test_impl, + (types.Array(types.float64, 1, 'C'), + types.Array(types.float64, 1, 'C'))), 1) + + def test_tuple1(self): + def test_impl(a): + atup = (3, 4) + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0] + atup[1] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_tuple2(self): + def test_impl(a): + atup = a.shape + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_tuple3(self): + def test_impl(a): + atup = (np.arange(10), 4) + b = 7 + for i in numba.prange(len(a)): + a[i] += atup[0][5] + atup[1] + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple1(self): + def test_impl(a): + antup = TestNamedTuple(part0=3, part1=4) + b = 7 + for i in numba.prange(len(a)): + a[i] += antup.part0 + antup.part1 + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple2(self): + TestNamedTuple2 = namedtuple('TestNamedTuple2', ('part0', 'part1')) + def test_impl(a): + antup = TestNamedTuple2(part0=3, part1=4) + b = 7 + for i in numba.prange(len(a)): + a[i] += antup.part0 + antup.part1 + b + return a + + x = np.arange(10) + self.check(test_impl, x) + + def test_namedtuple3(self): + # issue5872: test that a.y[:] = 5 is not removed as + # deadcode. + TestNamedTuple3 = namedtuple(f'TestNamedTuple3',['y']) + + def test_impl(a): + a.y[:] = 5 + + def comparer(a, b): + np.testing.assert_almost_equal(a.y, b.y) + + x = TestNamedTuple3(y=np.zeros(10)) + self.check(test_impl, x, check_arg_equality=[comparer]) + + def test_inplace_binop(self): + def test_impl(a, b): + b += a + return b + + X = np.arange(10) + 10 + Y = np.arange(10) + 100 + self.check(test_impl, X, Y) + self.assertEqual(countParfors(test_impl, + (types.Array(types.float64, 1, 'C'), + types.Array(types.float64, 1, 'C'))), 1) + + def test_tuple_concat(self): + # issue5383 + def test_impl(a): + n = len(a) + array_shape = n, n + indices = np.zeros(((1,) + array_shape + (1,)), dtype=np.uint64) + k_list = indices[0, :] + + for i, g in enumerate(a): + k_list[i, i] = i + return k_list + + x = np.array([1, 1]) + self.check(test_impl, x) + + def test_tuple_concat_with_reverse_slice(self): + # issue5383 + def test_impl(a): + n = len(a) + array_shape = n, n + indices = np.zeros(((1,) + array_shape + (1,))[:-1], + dtype=np.uint64) + k_list = indices[0, :] + + for i, g in enumerate(a): + k_list[i, i] = i + return k_list + + x = np.array([1, 1]) + self.check(test_impl, x) + + def test_array_tuple_concat(self): + # issue6399 + def test_impl(a): + S = (a,) + (a, a) + return S[0].sum() + + x = np.ones((3,3)) + self.check(test_impl, x) + + def test_high_dimension1(self): + # issue6749 + def test_impl(x): + return x * 5.0 + x = np.ones((2, 2, 2, 2, 2, 15)) + self.check(test_impl, x) + + def test_tuple_arg(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.empty(sz), sz) + + def test_tuple_arg_not_whole_array(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz), (10, 3)) + + def test_tuple_for_pndindex(self): + def test_impl(x): + sz = (10, 5) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz)) + + def test_tuple_arg_literal(self): + def test_impl(x, first): + sz = (first, 5) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10, 5) + self.check(test_impl, np.zeros(sz), 10) + + def test_tuple_of_literal_nonliteral(self): + # This test has to be done manually as the self.check uses + # compile_isolated and one function cannot "see" the other + + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + + def call(x, fn): + return fn(x, (10, 3)) # Only want to iterate to the 3rd + + get_input = lambda: np.zeros((10, 10)) + expected = call(get_input(), test_impl) + + def check(dec): + f1 = dec(test_impl) + f2 = njit(call) # no parallel semantics in the caller + got = f2(get_input(), f1) + self.assertPreciseEqual(expected, got) + + for d in (njit, njit(parallel=True)): + check(d) + + def test_tuple_arg_1d(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10,) + self.check(test_impl, np.zeros(sz), sz) + + def test_tuple_arg_1d_literal(self): + def test_impl(x): + sz = (10,) + for i in numba.pndindex(sz): + x[i] = 1 + return x + sz = (10,) + self.check(test_impl, np.zeros(sz)) + + def test_int_arg_pndindex(self): + def test_impl(x, sz): + for i in numba.pndindex(sz): + x[i] = 1 + return x + self.check(test_impl, np.zeros((10, 10)), 3) + + def test_prange_unknown_call1(self): + @register_jitable + def issue7854_proc(u, i, even, size): + for j in range((even + i + 1) % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + + # issue7854 + # Forbid fusion in unanalyzable call inside prange. + def test_impl(u, size): + for i in numba.prange(1, size - 1): + issue7854_proc(u, i, 0, size) + for i in numba.prange(1, size - 1): + issue7854_proc(u, i, 1, size) + return u + + size = 4 + u = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, u, size) + + def test_prange_index_calc1(self): + # Should forbid fusion due to cross-iteration dependency as + # detected by loop index calcuation (i+1) as array index. + def test_impl(u, size): + for i in numba.prange(1, size - 1): + for j in range((i + 1) % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + for i in numba.prange(1, size - 1): + for j in range(i % 2 + 1, size - 1, 2): + u[i, j] = u[i + 1, j] + 1 + return u + + size = 4 + u = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, u, size) + + def test_prange_reverse_order1(self): + # Testing if reversed loop index usage as array index + # prevents fusion. + def test_impl(a, b, size): + for i in numba.prange(size): + for j in range(size): + a[i, j] = b[i, j] + 1 + for i in numba.prange(size): + for j in range(size): + b[j, i] = 3 + return a[0, 0] + b[0, 0] + + size = 10 + a = np.zeros((size, size)) + b = np.zeros((size, size)) + cptypes = (numba.float64[:, ::1], numba.float64[:, ::1], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, b, size) + + def test_prange_parfor_index_then_not(self): + # Testing if accessing an array first with a parfor index then + # without will prevent fusion. + def test_impl(a, size): + b = 0 + for i in numba.prange(size): + a[i] = i + for i in numba.prange(size): + b += a[5] + return b + + size = 10 + a = np.zeros(size) + cptypes = (numba.float64[:], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, size) + + def test_prange_parfor_index_const_tuple_fusion(self): + # Testing if accessing a tuple with prange index + # and later with a constant will not prevent fusion. + def test_impl(a, tup, size): + acc = 0 + for i in numba.prange(size): + a[i] = i + tup[i] + for i in numba.prange(size): + acc += a[i] + tup[1] + return acc + + size = 10 + a = np.zeros(size) + b = tuple(a) + cptypes = (numba.float64[:], + types.containers.UniTuple(types.float64, size), + types.intp) + self.assertEqual(countParfors(test_impl, cptypes), 1) + self.check(test_impl, a, b, size) + + def test_prange_non_parfor_index_then_opposite(self): + # Testing if accessing an array first without a parfor index then + # with will prevent fusion. + def test_impl(a, b, size): + for i in numba.prange(size): + b[i] = a[5] + for i in numba.prange(size): + a[i] = i + # Need this to stop previous prange from being optimized away. + b[0] += a[0] + return b + + size = 10 + a = np.zeros(size) + b = np.zeros(size) + cptypes = (numba.float64[:], numba.float64[:], types.int64) + self.assertEqual(countParfors(test_impl, cptypes), 2) + self.check(test_impl, a, b, size) + + def test_prange_optional(self): + def test_impl(arr, pred=None): + for i in prange(1): + if pred is not None: + arr[i] = 0.0 + + arr = np.ones(10) + self.check(test_impl, arr, None, + check_arg_equality=[np.testing.assert_almost_equal, + lambda x, y: x == y]) + self.assertEqual(arr.sum(), 10.0) + + def test_untraced_value_tuple(self): + # This is a test for issue #6478. + def test_impl(): + a = (1.2, 1.3) + return a[0] + + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_recursive_untraced_value_tuple(self): + # This is a test for issue #6478. + def test_impl(): + a = ((1.2, 1.3),) + return a[0][0] + + with self.assertRaises(AssertionError) as raises: + self.check(test_impl) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + def test_untraced_value_parfor(self): + # This is a test for issue #6478. + def test_impl(arr): + a = (1.2, 1.3) + n1 = len(arr) + arr2 = np.empty(n1, np.float64) + for i in prange(n1): + arr2[i] = arr[i] * a[0] + n2 = len(arr2) + arr3 = np.empty(n2, np.float64) + for j in prange(n2): + arr3[j] = arr2[j] - a[1] + total = 0.0 + n3 = len(arr3) + for k in prange(n3): + total += arr3[k] + return total + a[0] + + arg = (types.Array(types.int64, 1, 'C'), ) + self.assertEqual(countParfors(test_impl, arg), 1) + + arr = np.arange(10, dtype=np.int64) + self.check(test_impl, arr) + + def test_setitem_2d_one_replaced(self): + # issue7843 + def test_impl(x): + count = 0 + for n in range(x.shape[0]): + # Useless "if" necessary to trigger bug. + if n: + n + x[count, :] = 1 + count += 1 + return x + + self.check(test_impl, np.zeros((3, 1))) + + def test_1array_control_flow(self): + # issue8146 + def test_impl(arr, flag1, flag2): + inv = np.arange(arr.size) + if flag1: + return inv.astype(np.float64) + if flag2: + ret = inv[inv] + else: + ret = inv[inv - 1] + return ret / arr.size + + arr = np.arange(100) + self.check(test_impl, arr, True, False) + self.check(test_impl, arr, True, True) + self.check(test_impl, arr, False, False) + + def test_2array_1_control_flow(self): + # issue8146 + def test_impl(arr, l, flag): + inv1 = np.arange(arr.size) + inv2 = np.arange(l, arr.size + l) + if flag: + ret = inv1[inv1] + else: + ret = inv1[inv1 - 1] + return ret / inv2 + + arr = np.arange(100) + self.check(test_impl, arr, 10, True) + self.check(test_impl, arr, 10, False) + + def test_2array_2_control_flow(self): + # issue8146 + def test_impl(arr, l, flag): + inv1 = np.arange(arr.size) + inv2 = np.arange(l, arr.size + l) + if flag: + ret1 = inv1[inv1] + ret2 = inv2[inv1] + else: + ret1 = inv1[inv1 - 1] + ret2 = inv2[inv1 - 1] + return ret1 / ret2 + + arr = np.arange(100) + self.check(test_impl, arr, 10, True) + self.check(test_impl, arr, 10, False) + + def test_issue8515(self): + # issue8515: an array is filled in the first prange and + # then accessed with c[i - 1] in the next prange which + # should prevent fusion with the previous prange. + def test_impl(n): + r = np.zeros(n, dtype=np.intp) + c = np.zeros(n, dtype=np.intp) + for i in prange(n): + for j in range(i): + c[i] += 1 + + for i in prange(n): + if i == 0: + continue + r[i] = c[i] - c[i - 1] + return r[1:] + + self.check(test_impl, 15) + self.assertEqual(countParfors(test_impl, (types.int64, )), 2) + + def test_issue9029(self): + # issue9029: too many parfors executed in one function + # overflowed the stack. + def test_impl(i1, i2): + N = 30 + S = 3 + a = np.empty((N,N)) + # The stack should overflow if there are 30*30*2 (# of parfors) + # iterations. + for y in range(N): + for x in range(N): + values = np.ones(S) + v = values[0] + + p2 = np.empty(S) + for i in prange(i1, i2): + p2[i] = 1 + j = p2[0] + + a[y,x] = v + j + return a + + # We pass in 0 and 3 so that the function can't analyze the loop + # bounds on the prange to generate a signed loop whereas the + # np.ones will be an unsigned loop. + self.check(test_impl, 0, 3) + + def test_fusion_no_side_effects(self): + def test_impl(a, b): + X = np.ones(100) + b = math.ceil(b) + Y = np.ones(100) + c = int(max(a, b)) + return X + Y + c + self.check(test_impl, 3.7, 4.3) + self.assertEqual(countParfors(test_impl, (types.float64, types.float64)), 1) + + def test_issue9256_lower_sroa_conflict(self): + @njit(parallel=True) + def def_in_loop(x): + c = 0 + set_num_threads(1) + for i in prange(x): + c = i + return c + + self.assertEqual(def_in_loop(10), def_in_loop.py_func(10)) + + def test_issue9256_lower_sroa_conflict_variant1(self): + def def_in_loop(x): + c = x + set_num_threads(1) + for _i in prange(x): + if c: # forces 3 SSA versions + d = x + 4 + return c, d > 0 + + expected = def_in_loop(4) + self.assertEqual(expected, njit(parallel=False)(def_in_loop)(4)) + self.assertEqual(expected, njit(parallel=True)(def_in_loop)(4)) + + def test_issue9256_lower_sroa_conflict_variant2(self): + def def_in_loop(x): + c = x + set_num_threads(1) + for _i in prange(x): + if c: + for _j in range(x): # forces 4 SSA versions + d = x + 4 + return c, d > 0 + + expected = def_in_loop(4) + self.assertEqual(expected, njit(parallel=False)(def_in_loop)(4)) + self.assertEqual(expected, njit(parallel=True)(def_in_loop)(4)) + + @needs_lapack # use of np.linalg.solve + @skip_ppc64le_invalid_ctr_loop + def test_issue9490_non_det_ssa_problem(self): + # Test modified to include https://github.com/numba/numba/issues/9581 + # which is an issue with hoisting + cmd = [ + sys.executable, + "-m", + "numba.tests.parfor_iss9490_usecase", + ] + envs = { + **os.environ, + # Reproducer consistently fail with the following hashseed. + "PYTHONHASHSEED": "1", + # See https://github.com/numba/numba/issues/9501 + # for details of why num-thread pinning is needed. + "NUMBA_NUM_THREADS": "1", + } + try: + subp.check_output(cmd, env=envs, + stderr=subp.STDOUT, + encoding='utf-8') + except subp.CalledProcessError as e: + msg = f"subprocess failed with output:\n{e.output}" + self.fail(msg=msg) + + +@skip_parfors_unsupported +class TestParforsLeaks(MemoryLeakMixin, TestParforsBase): + def check(self, pyfunc, *args, **kwargs): + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def test_reduction(self): + # issue4299 + def test_impl(arr): + return arr.sum() + + arr = np.arange(10).astype(np.float64) + self.check(test_impl, arr) + + def test_multiple_reduction_vars(self): + + def test_impl(arr): + a = 0. + b = 1. + for i in prange(arr.size): + a += arr[i] + b += 1. / (arr[i] + 1) + return a * b + arr = np.arange(10).astype(np.float64) + self.check(test_impl, arr) + + +@skip_parfors_unsupported +class TestParforsSlice(TestParforsBase): + + def test_parfor_slice1(self): + def test_impl(a): + (n,) = a.shape + b = a[0:n-2] + a[1:n-1] + return b + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice2(self): + def test_impl(a, m): + (n,) = a.shape + b = a[0:n-2] + a[1:m] + return b + + # runtime assertion should succeed + self.check(test_impl, np.ones(10), 9) + # next we expect failure + with self.assertRaises(AssertionError) as raises: + njit(parallel=True)(test_impl)(np.ones(10),10) + self.assertIn("do not match", str(raises.exception)) + + def test_parfor_slice3(self): + def test_impl(a): + (m,n) = a.shape + b = a[0:m-1,0:n-1] + a[1:m,1:n] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice4(self): + def test_impl(a): + (m,n) = a.shape + b = a[:,0:n-1] + a[:,1:n] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice5(self): + def test_impl(a): + (m,n) = a.shape + b = a[0:m-1,:] + a[1:m,:] + return b + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice6(self): + def test_impl(a): + b = a.transpose() + c = a[1,:] + b[:,1] + return c + + self.check(test_impl, np.ones((4,3))) + + def test_parfor_slice7(self): + def test_impl(a): + b = a.transpose() + c = a[1,:] + b[1,:] + return c + + # runtime check should succeed + self.check(test_impl, np.ones((3,3))) + # next we expect failure + with self.assertRaises(AssertionError) as raises: + njit(parallel=True)(test_impl)(np.ones((3,4))) + self.assertIn("do not match", str(raises.exception)) + + @disabled_test + def test_parfor_slice8(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[1:m,1:n] = a[1:m,1:n] + return b + + self.check(test_impl, np.arange(9).reshape((3,3))) + + @disabled_test + def test_parfor_slice9(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[1:n,1:m] = a[:,1:m] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + @disabled_test + def test_parfor_slice10(self): + def test_impl(a): + (m,n) = a.shape + b = a.transpose() + b[2,1:m] = a[2,1:m] + return b + + self.check(test_impl, np.arange(9).reshape((3,3))) + + def test_parfor_slice11(self): + def test_impl(a): + (m,n,l) = a.shape + b = a.copy() + b[:,1,1:l] = a[:,2,1:l] + return b + + self.check(test_impl, np.arange(27).reshape((3,3,3))) + + def test_parfor_slice12(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,1:-1] = a[0,:-2] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice13(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + c = -1 + b[1,1:c] = a[0,-n:c-1] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice14(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,:-1] = a[0,-3:4] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + def test_parfor_slice15(self): + def test_impl(a): + (m,n) = a.shape + b = a.copy() + b[1,-(n-1):] = a[0,-3:4] + return b + + self.check(test_impl, np.arange(12).reshape((3,4))) + + @disabled_test + def test_parfor_slice16(self): + """ This test is disabled because if n is larger than the array size + then n and n-1 will both be the end of the array and thus the + slices will in fact be of different sizes and unable to fuse. + """ + def test_impl(a, b, n): + assert(a.shape == b.shape) + a[1:n] = 10 + b[0:(n-1)] = 10 + return a * b + + self.check(test_impl, np.ones(10), np.zeros(10), 8) + args = (numba.float64[:], numba.float64[:], numba.int64) + self.assertEqual(countParfors(test_impl, args), 2) + + def test_parfor_slice17(self): + def test_impl(m, A): + B = np.zeros(m) + n = len(A) + B[-n:] = A + return B + + self.check(test_impl, 10, np.ones(10)) + + def test_parfor_slice18(self): + # issue 3534 + def test_impl(): + a = np.zeros(10) + a[1:8] = np.arange(0, 7) + y = a[3] + return y + + self.check(test_impl) + + def test_parfor_slice19(self): + # issues #3561 and #3554, empty slice binop + def test_impl(X): + X[:0] += 1 + return X + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice20(self): + # issue #4075, slice size + def test_impl(): + a = np.ones(10) + c = a[1:] + s = len(c) + return s + + self.check(test_impl, check_scheduling=False) + + def test_parfor_slice21(self): + def test_impl(x1, x2): + x1 = x1.reshape(x1.size, 1) + x2 = x2.reshape(x2.size, 1) + return x1 >= x2[:-1, :] + + x1 = np.random.rand(5) + x2 = np.random.rand(6) + self.check(test_impl, x1, x2) + + def test_parfor_slice22(self): + def test_impl(x1, x2): + b = np.zeros((10,)) + for i in prange(1): + b += x1[:, x2] + return b + + x1 = np.zeros((10,7)) + x2 = np.array(4) + self.check(test_impl, x1, x2) + + def test_parfor_slice23(self): + # issue #4630 + def test_impl(x): + x[:0] = 2 + return x + + self.check(test_impl, np.ones(10)) + + def test_parfor_slice24(self): + def test_impl(m, A, n): + B = np.zeros(m) + C = B[n:] + C = A[:len(C)] + return B + + for i in range(-15, 15): + self.check(test_impl, 10, np.ones(10), i) + + def test_parfor_slice25(self): + def test_impl(m, A, n): + B = np.zeros(m) + C = B[:n] + C = A[:len(C)] + return B + + for i in range(-15, 15): + self.check(test_impl, 10, np.ones(10), i) + + def test_parfor_slice26(self): + def test_impl(a): + (n,) = a.shape + b = a.copy() + b[-(n-1):] = a[-3:4] + return b + + self.check(test_impl, np.arange(4)) + + def test_parfor_slice27(self): + # issue5601: tests array analysis of the slice with + # n_valid_vals of unknown size. + def test_impl(a): + n_valid_vals = 0 + + for i in prange(a.shape[0]): + if a[i] != 0: + n_valid_vals += 1 + + if n_valid_vals: + unused = a[:n_valid_vals] + + return 0 + + self.check(test_impl, np.arange(3)) + + def test_parfor_array_access_lower_slice(self): + for ts in [slice(1, 3, None), slice(2, None, None), slice(None, 2, -1), + slice(None, None, None), slice(None, None, -2)]: + + def test_impl(n): + X = np.arange(n * 4).reshape((n, 4)) + y = 0 + for i in numba.prange(n): + y += X[i, ts].sum() + return y + + n = 10 + self.check(test_impl, n) + + X = np.arange(n * 4).reshape((n, 4)) + + def test_impl(X): + y = 0 + for i in numba.prange(X.shape[0]): + y += X[i, ts].sum() + return y + + self.check(test_impl, X) + + +@skip_parfors_unsupported +class TestParforsOptions(TestParforsBase): + + def test_parfor_options(self): + def test_impl(a): + n = a.shape[0] + b = np.ones(n) + c = np.array([ i for i in range(n) ]) + b[:n] = a + b * c + for i in prange(n): + c[i] = b[i] * a[i] + return reduce(lambda x,y:x+y, c, 0) + + self.check(test_impl, np.ones(10)) + args = (numba.float64[:],) + # everything should fuse with default option + self.assertEqual(countParfors(test_impl, args), 1) + # with no fusion + self.assertEqual(countParfors(test_impl, args, fusion=False), 6) + # with no fusion, comprehension + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False), 5) + #with no fusion, comprehension, setitem + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False), 4) + # with no fusion, comprehension, prange + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False), 3) + # with no fusion, comprehension, prange, reduction + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False, + reduction=False), 2) + # with no fusion, comprehension, prange, reduction, numpy + self.assertEqual(countParfors(test_impl, args, fusion=False, + comprehension=False, setitem=False, prange=False, + reduction=False, numpy=False), 0) + + +@skip_parfors_unsupported +class TestParforsBitMask(TestParforsBase): + + def test_parfor_bitmask1(self): + def test_impl(a, n): + b = a > n + a[b] = 0 + return a + + self.check(test_impl, np.arange(10), 5) + + def test_parfor_bitmask2(self): + def test_impl(a, b): + a[b] = 0 + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask3(self): + def test_impl(a, b): + a[b] = a[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask4(self): + def test_impl(a, b): + a[b] = (2 * a)[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask5(self): + def test_impl(a, b): + a[b] = a[b] * a[b] + return a + + a = np.arange(10) + b = a > 5 + self.check(test_impl, a, b) + + def test_parfor_bitmask6(self): + def test_impl(a, b, c): + a[b] = c + return a + + a = np.arange(10) + b = a > 5 + c = np.zeros(sum(b)) + + # expect failure due to lack of parallelism + with self.assertRaises(AssertionError) as raises: + self.check(test_impl, a, b, c) + self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) + + +@skip_parfors_unsupported +class TestParforsMisc(TestParforsBase): + """ + Tests miscellaneous parts of ParallelAccelerator use. + """ + def test_no_warn_if_cache_set(self): + + def pyfunc(): + arr = np.ones(100) + for i in prange(arr.size): + arr[i] += i + return arr + + cfunc = njit(parallel=True, cache=True)(pyfunc) + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter('always') + warnings.filterwarnings(action="ignore", + module="typeguard") + # Filter out warnings about TBB interface mismatch + warnings.filterwarnings(action='ignore', + message=r".*TBB_INTERFACE_VERSION.*", + category=numba.errors.NumbaWarning, + module=r'numba\.np\.ufunc\.parallel.*') + cfunc() + + self.assertEqual(len(raised_warnings), 0) + + # Make sure the dynamic globals flag is set + has_dynamic_globals = [cres.library.has_dynamic_globals + for cres in cfunc.overloads.values()] + self.assertEqual(has_dynamic_globals, [False]) + + def test_statement_reordering_respects_aliasing(self): + def impl(): + a = np.zeros(10) + a[1:8] = np.arange(0, 7) + print('a[3]:', a[3]) + print('a[3]:', a[3]) + return a + + cres = self.compile_parallel(impl, ()) + with captured_stdout() as stdout: + cres.entry_point() + for line in stdout.getvalue().splitlines(): + self.assertEqual('a[3]: 2.0', line) + + def test_parfor_ufunc_typing(self): + def test_impl(A): + return np.isinf(A) + + A = np.array([np.inf, 0.0]) + cfunc = njit(parallel=True)(test_impl) + # save global state + old_seq_flag = numba.parfors.parfor.sequential_parfor_lowering + try: + numba.parfors.parfor.sequential_parfor_lowering = True + np.testing.assert_array_equal(test_impl(A), cfunc(A)) + finally: + # recover global state + numba.parfors.parfor.sequential_parfor_lowering = old_seq_flag + + def test_init_block_dce(self): + # issue4690 + def test_impl(): + res = 0 + arr = [1,2,3,4,5] + numba.parfors.parfor.init_prange() + dummy = arr + for i in numba.prange(5): + res += arr[i] + return res + dummy[2] + + self.assertEqual(get_init_block_size(test_impl, ()), 0) + + def test_alias_analysis_for_parfor1(self): + def test_impl(): + acc = 0 + for _ in range(4): + acc += 1 + + data = np.zeros((acc,)) + return data + + self.check(test_impl) + + def test_no_state_change_in_gufunc_lowering_on_error(self): + # tests #5098, if there's an exception arising in gufunc lowering the + # sequential_parfor_lowering global variable should remain as False on + # stack unwind. + + BROKEN_MSG = 'BROKEN_MSG' + + @register_pass(mutates_CFG=True, analysis_only=False) + class BreakParfors(AnalysisPass): + _name = "break_parfors" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + for blk in state.func_ir.blocks.values(): + for stmt in blk.body: + if isinstance(stmt, numba.parfors.parfor.Parfor): + # races should be a set(), that list is iterable + # permits it to get through to the + # _create_gufunc_for_parfor_body routine at which + # point it needs to be a set so e.g. set.difference + # can be computed, this therefore creates an error + # in the right location. + class Broken(list): + + def difference(self, other): + raise errors.LoweringError(BROKEN_MSG) + + stmt.races = Broken() + return True + + + class BreakParforsCompiler(CompilerBase): + + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(BreakParfors, IRLegalization) + pm.finalize() + return [pm] + + + @njit(parallel=True, pipeline_class=BreakParforsCompiler) + def foo(): + x = 1 + for _ in prange(1): + x += 1 + return x + + # assert default state for global + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + + with self.assertRaises(errors.LoweringError) as raises: + foo() + + self.assertIn(BROKEN_MSG, str(raises.exception)) + + # assert state has not changed + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + + def test_issue_5098(self): + class DummyType(types.Opaque): + pass + + dummy_type = DummyType("my_dummy") + register_model(DummyType)(models.OpaqueModel) + + class Dummy(object): + pass + + @typeof_impl.register(Dummy) + def typeof_Dummy(val, c): + return dummy_type + + @unbox(DummyType) + def unbox_index(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + @overload_method(DummyType, "method1", jit_options={"parallel":True}) + def _get_method1(obj, arr, func): + def _foo(obj, arr, func): + def baz(a, f): + c = a.copy() + c[np.isinf(a)] = np.nan + return f(c) + + length = len(arr) + output_arr = np.empty(length, dtype=np.float64) + for i in prange(length): + output_arr[i] = baz(arr[i], func) + for i in prange(length - 1): + output_arr[i] += baz(arr[i], func) + return output_arr + return _foo + + @njit + def bar(v): + return v.mean() + + @njit + def test1(d): + return d.method1(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), bar) + + save_state = numba.parfors.parfor.sequential_parfor_lowering + self.assertFalse(save_state) + try: + test1(Dummy()) + self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering) + finally: + # always set the sequential_parfor_lowering state back to the + # original state + numba.parfors.parfor.sequential_parfor_lowering = save_state + + def test_oversized_tuple_as_arg_to_kernel(self): + + @njit(parallel=True) + def oversize_tuple(idx): + big_tup = (1,2,3,4) + z = 0 + for x in prange(10): + z += big_tup[idx] + return z + + with override_env_config('NUMBA_PARFOR_MAX_TUPLE_SIZE', '3'): + with self.assertRaises(errors.UnsupportedParforsError) as raises: + oversize_tuple(0) + + errstr = str(raises.exception) + self.assertIn("Use of a tuple", errstr) + self.assertIn("in a parallel region", errstr) + + def test_issue5167(self): + + def ndvi_njit(img_nir, img_red): + fillvalue = 0 + out_img = np.full(img_nir.shape, fillvalue, dtype=img_nir.dtype) + dims = img_nir.shape + for y in prange(dims[0]): + for x in prange(dims[1]): + out_img[y, x] = ((img_nir[y, x] - img_red[y, x]) / + (img_nir[y, x] + img_red[y, x])) + return out_img + + tile_shape = (4, 4) + array1 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape) + array2 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape) + self.check(ndvi_njit, array1, array2) + + def test_issue5065(self): + + def reproducer(a, dist, dist_args): + result = np.zeros((a.shape[0], a.shape[0]), dtype=np.float32) + for i in prange(a.shape[0]): + for j in range(i + 1, a.shape[0]): + d = dist(a[i], a[j], *dist_args) + result[i, j] = d + result[j, i] = d + return result + + @njit + def euclidean(x, y): + result = 0.0 + for i in range(x.shape[0]): + result += (x[i] - y[i]) ** 2 + return np.sqrt(result) + + a = np.random.random(size=(5, 2)) + + got = njit(parallel=True)(reproducer)(a.copy(), euclidean,()) + expected = reproducer(a.copy(), euclidean,()) + + np.testing.assert_allclose(got, expected) + + def test_issue5001(self): + + def test_numba_parallel(myarray): + result = [0] * len(myarray) + for i in prange(len(myarray)): + result[i] = len(myarray[i]) + return result + + myarray = (np.empty(100),np.empty(50)) + self.check(test_numba_parallel, myarray) + + def test_issue3169(self): + + @njit + def foo(grids): + pass + + @njit(parallel=True) + def bar(grids): + for x in prange(1): + foo(grids) + + # returns nothing, just check it compiles + bar(([1],) * 2) + + @disabled_test + def test_issue4846(self): + + mytype = namedtuple("mytype", ("a", "b")) + + def outer(mydata): + for k in prange(3): + inner(k, mydata) + return mydata.a + + @njit(nogil=True) + def inner(k, mydata): + f = (k, mydata.a) + g = (k, mydata.b) + + mydata = mytype(a="a", b="b") + + self.check(outer, mydata) + + def test_issue3748(self): + + def test1b(): + x = (1, 2, 3, 4, 5) + a = 0 + for i in prange(len(x)): + a += x[i] + return a + + self.check(test1b,) + + def test_issue5277(self): + + def parallel_test(size, arr): + for x in prange(size[0]): + for y in prange(size[1]): + arr[y][x] = x * 4.5 + y + return arr + + size = (10, 10) + arr = np.zeros(size, dtype=int) + + self.check(parallel_test, size, arr) + + def test_issue5570_ssa_races(self): + @njit(parallel=True) + def foo(src, method, out): + for i in prange(1): + for j in range(1): + out[i, j] = 1 + if method: + out += 1 + return out + + src = np.zeros((5,5)) + method = 57 + out = np.zeros((2, 2)) + + self.assertPreciseEqual( + foo(src, method, out), + foo.py_func(src, method, out) + ) + + def test_issue6095_numpy_max(self): + @njit(parallel=True) + def find_maxima_3D_jit(args): + package = args + for index in range(0, 10): + z_stack = package[index, :, :] + return np.max(z_stack) + + np.random.seed(0) + args = np.random.random((10, 10, 10)) + self.assertPreciseEqual( + find_maxima_3D_jit(args), + find_maxima_3D_jit.py_func(args), + ) + + def test_issue5942_1(self): + # issue5942: tests statement reordering of + # aliased arguments. + def test_impl(gg, gg_next): + gs = gg.shape + d = gs[0] + for i_gg in prange(d): + gg_next[i_gg, :] = gg[i_gg, :] + gg_next[i_gg, 0] += 1 + + return gg_next + + d = 4 + k = 2 + + gg = np.zeros((d, k), dtype = np.int32) + gg_next = np.zeros((d, k), dtype = np.int32) + self.check(test_impl, gg, gg_next) + + def test_issue5942_2(self): + # issue5942: tests statement reordering + def test_impl(d, k): + gg = np.zeros((d, k), dtype = np.int32) + gg_next = np.zeros((d, k), dtype = np.int32) + + for i_gg in prange(d): + for n in range(k): + gg[i_gg, n] = i_gg + gg_next[i_gg, :] = gg[i_gg, :] + gg_next[i_gg, 0] += 1 + + return gg_next + + d = 4 + k = 2 + + self.check(test_impl, d, k) + + @skip_unless_scipy + def test_issue6102(self): + # The problem is originally observed on Python3.8 because of the + # changes in how loops are represented in 3.8 bytecode. + @njit(parallel=True) + def f(r): + for ir in prange(r.shape[0]): + dist = np.inf + tr = np.array([0, 0, 0], dtype=np.float32) + for i in [1, 0, -1]: + dist_t = np.linalg.norm(r[ir, :] + i) + if dist_t < dist: + dist = dist_t + tr = np.array([i, i, i], dtype=np.float32) + r[ir, :] += tr + return r + + r = np.array([[0., 0., 0.], [0., 0., 1.]]) + self.assertPreciseEqual(f(r), f.py_func(r)) + + def test_issue6774(self): + + def test_impl(): + n = 5 + na_mask = np.ones((n,)) + result = np.empty((n - 1,)) + for i in prange(len(result)): + result[i] = np.sum(na_mask[i:i + 1]) + return result + + self.check(test_impl) + + def test_issue4963_globals(self): + def test_impl(): + buf = np.zeros((_GLOBAL_INT_FOR_TESTING1, _GLOBAL_INT_FOR_TESTING2)) + return buf + self.check(test_impl) + + def test_issue4963_freevars(self): + _FREEVAR_INT_FOR_TESTING1 = 17 + _FREEVAR_INT_FOR_TESTING2 = 5 + def test_impl(): + buf = np.zeros((_FREEVAR_INT_FOR_TESTING1, _FREEVAR_INT_FOR_TESTING2)) + return buf + self.check(test_impl) + + def test_issue_9182_recursion_error(self): + from numba.types import ListType, Tuple, intp + + @numba.njit + def _sink(x): + pass + + + @numba.njit(cache=False, parallel=True) + def _ground_node_rule( + clauses, + nodes, + ): + for piter in prange(len(nodes)): + for clause in clauses: + clause_type = clause[0] + clause_variables = clause[2] + if clause_type == 0: + clause_var_1 = clause_variables[0] + elif len(clause_variables) == 2: + clause_var_1, clause_var_2 = ( + clause_variables[0], + clause_variables[1], + ) + + elif len(clause_variables) == 4: + pass + + if clause_type == 1: + _sink(clause_var_1) + _sink(clause_var_2) + + _ground_node_rule.compile( + ( + ListType(Tuple([intp, intp, ListType(intp)])), + ListType(intp), + ) + ) + + def test_lookup_cycle_detection(self): + # This test is added due to a bug discovered in the PR 9244 patch. + # The cyclic detection was incorrectly flagging cycles. + @njit(parallel=True) + def foo(): + # The following `acc` variable is used in the `lookup()` function + # in parfor's reduction code. + acc = 0 + for n in prange(1): + for i in range(1): + for j in range(1): + acc += 1 + return acc + + self.assertEqual(foo(), foo.py_func()) + + def test_issue_9678_build_map(self): + def issue_9678(num_nodes): + out = 0 + for inode_uint in numba.prange(num_nodes): + inode = numba.int64(inode_uint) + p = {inode: 0.0} # mainly this build_map bytecode here + for _ in range(5): + p[inode] += 1 # and here + out += p[inode] + return out + + num_nodes = 12 + issue_9678_serial = numba.jit(parallel=False)(issue_9678) + issue_9678_parallel = numba.jit(parallel=True)(issue_9678) + self.assertEqual(issue_9678_serial(num_nodes), + issue_9678_parallel(num_nodes)) + + +@skip_parfors_unsupported +class TestParforsDiagnostics(TestParforsBase): + + def check(self, pyfunc, *args, **kwargs): + cfunc, cpfunc = self.compile_all(pyfunc, *args) + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + + def assert_fusion_equivalence(self, got, expected): + a = self._fusion_equivalent(got) + b = self._fusion_equivalent(expected) + self.assertEqual(a, b) + + def _fusion_equivalent(self, thing): + # parfors indexes the Parfors class instance id's from wherever the + # internal state happens to be. To assert fusion equivalence we just + # check that the relative difference between fusion adjacency lists + # is the same. For example: + # {3: [2, 1]} is the same as {13: [12, 11]} + # this function strips the indexing etc out returning something suitable + # for checking equivalence + new = defaultdict(list) + min_key = min(thing.keys()) + for k in sorted(thing.keys()): + new[k - min_key] = [x - min_key for x in thing[k]] + return new + + def assert_diagnostics(self, diagnostics, parfors_count=None, + fusion_info=None, nested_fusion_info=None, + replaced_fns=None, hoisted_allocations=None): + if parfors_count is not None: + self.assertEqual(parfors_count, diagnostics.count_parfors()) + if fusion_info is not None: + self.assert_fusion_equivalence(fusion_info, diagnostics.fusion_info) + if nested_fusion_info is not None: + self.assert_fusion_equivalence(nested_fusion_info, + diagnostics.nested_fusion_info) + if replaced_fns is not None: + repl = diagnostics.replaced_fns.values() + for x in replaced_fns: + for replaced in repl: + if replaced[0] == x: + break + else: + msg = "Replacement for %s was not found. Had %s" % (x, repl) + raise AssertionError(msg) + + if hoisted_allocations is not None: + hoisted_allocs = diagnostics.hoisted_allocations() + self.assertEqual(hoisted_allocations, len(hoisted_allocs)) + + # just make sure that the dump() function doesn't have an issue! + with captured_stdout(): + for x in range(1, 5): + diagnostics.dump(x) + + def test_array_expr(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.zeros(n) + return a + b + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1, + fusion_info = {3: [4, 5]}) + + def test_prange(self): + def test_impl(): + n = 10 + a = np.empty(n) + for i in prange(n): + a[i] = i * 10 + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1) + + def test_user_varname(self): + """make sure original user variable name is used in fusion info + """ + def test_impl(): + n = 10 + x = np.ones(n) + a = np.sin(x) + b = np.cos(a * a) + acc = 0 + for i in prange(n - 2): + for j in prange(n - 1): + acc += b[i] + b[j + 1] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + # make sure original 'n' variable name is used in fusion report for loop + # dimension mismatch + self.assertTrue( + any("slice(0, n, 1)" in r.message for r in diagnostics.fusion_reports)) + + def test_nested_prange(self): + def test_impl(): + n = 10 + a = np.empty((n, n)) + for i in prange(n): + for j in prange(n): + a[i, j] = i * 10 + j + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2, + nested_fusion_info={2: [1]}) + + def test_function_replacement(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.argmin(a) + return b + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1, + fusion_info={2: [3]}, + replaced_fns = [('argmin', 'numpy'),]) + + def test_reduction(self): + def test_impl(): + n = 10 + a = np.ones(n + 1) # prevent fusion + acc = 0 + for i in prange(n): + acc += a[i] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2) + + def test_reduction_binop(self): + def test_impl(): + n = 10 + a = np.ones(n + 1) # prevent fusion + acc = 0 + for i in prange(n): + acc = acc - a[i] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=2) + + def test_setitem(self): + def test_impl(): + n = 10 + a = np.ones(n) + a[:] = 7 + return a + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, parfors_count=1) + + def test_allocation_hoisting(self): + def test_impl(): + n = 10 + m = 5 + acc = 0 + for i in prange(n): + temp = np.zeros((m,)) # the np.empty call should get hoisted + for j in range(m): + temp[j] = i + acc += temp[-1] + return acc + + self.check(test_impl,) + cpfunc = self.compile_parallel(test_impl, ()) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + self.assert_diagnostics(diagnostics, hoisted_allocations=1) + + +class TestPrangeBase(TestParforsBase): + + def generate_prange_func(self, pyfunc, patch_instance): + """ + This function does the actual code augmentation to enable the explicit + testing of `prange` calls in place of `range`. + """ + pyfunc_code = pyfunc.__code__ + + prange_names = list(pyfunc_code.co_names) + + if patch_instance is None: + # patch all instances, cheat by just switching + # range for prange + assert 'range' in pyfunc_code.co_names + prange_names = tuple([x if x != 'range' else 'prange' + for x in pyfunc_code.co_names]) + new_code = bytes(pyfunc_code.co_code) + else: + # patch specified instances... + # find where 'range' is in co_names + range_idx = pyfunc_code.co_names.index('range') + range_locations = [] + # look for LOAD_GLOBALs that point to 'range' + for instr in dis.Bytecode(pyfunc_code): + if instr.opname == 'LOAD_GLOBAL': + if _fix_LOAD_GLOBAL_arg(instr.arg) == range_idx: + range_locations.append(instr.offset + 1) + # add in 'prange' ref + prange_names.append('prange') + prange_names = tuple(prange_names) + prange_idx = len(prange_names) - 1 + if utils.PYVERSION in ((3, 11), (3, 12), (3, 13), (3, 14)): + # this is the inverse of _fix_LOAD_GLOBAL_arg + prange_idx = 1 + (prange_idx << 1) + elif utils.PYVERSION in ((3, 10),): + pass + else: + raise NotImplementedError(utils.PYVERSION) + new_code = bytearray(pyfunc_code.co_code) + assert len(patch_instance) <= len(range_locations) + # patch up the new byte code + for i in patch_instance: + idx = range_locations[i] + new_code[idx] = prange_idx + new_code = bytes(new_code) + + # create code object with prange mutation + prange_code = pyfunc_code.replace(co_code=new_code, + co_names=prange_names) + + # get function + pfunc = pytypes.FunctionType(prange_code, globals()) + + return pfunc + + def prange_tester(self, pyfunc, *args, **kwargs): + """ + The `prange` tester + This is a hack. It basically switches out range calls for prange. + It does this by copying the live code object of a function + containing 'range' then copying the .co_names and mutating it so + that 'range' is replaced with 'prange'. It then creates a new code + object containing the mutation and instantiates a function to contain + it. At this point three results are created: + 1. The result of calling the original python function. + 2. The result of calling a njit compiled version of the original + python function. + 3. The result of calling a njit(parallel=True) version of the mutated + function containing `prange`. + The three results are then compared and the `prange` based function's + llvm_ir is inspected to ensure the scheduler code is present. + + Arguments: + pyfunc - the python function to test + args - data arguments to pass to the pyfunc under test + + Keyword Arguments: + patch_instance - iterable containing which instances of `range` to + replace. If not present all instance of `range` are + replaced. + scheduler_type - 'signed', 'unsigned' or None, default is None. + Supply in cases where the presence of a specific + scheduler is to be asserted. + check_fastmath - if True then a check will be performed to ensure the + IR contains instructions labelled with 'fast' + check_fastmath_result - if True then a check will be performed to + ensure the result of running with fastmath + on matches that of the pyfunc + Remaining kwargs are passed to np.testing.assert_almost_equal + + + Example: + def foo(): + acc = 0 + for x in range(5): + for y in range(10): + acc +=1 + return acc + + # calling as + prange_tester(foo) + # will test code equivalent to + # def foo(): + # acc = 0 + # for x in prange(5): # <- changed + # for y in prange(10): # <- changed + # acc +=1 + # return acc + + # calling as + prange_tester(foo, patch_instance=[1]) + # will test code equivalent to + # def foo(): + # acc = 0 + # for x in range(5): # <- outer loop (0) unchanged + # for y in prange(10): # <- inner loop (1) changed + # acc +=1 + # return acc + + """ + patch_instance = kwargs.pop('patch_instance', None) + check_fastmath = kwargs.pop('check_fastmath', False) + check_fastmath_result = kwargs.pop('check_fastmath_result', False) + + pfunc = self.generate_prange_func(pyfunc, patch_instance) + + # Compile functions + # compile a standard njit of the original function + sig = tuple([numba.typeof(x) for x in args]) + cfunc = self.compile_njit(pyfunc, sig) + + # compile the prange injected function + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter('always') + cpfunc = self.compile_parallel(pfunc, sig) + + # if check_fastmath is True then check fast instructions + if check_fastmath: + self.assert_fastmath(pfunc, sig) + + # if check_fastmath_result is True then compile a function + # so that the parfors checker can assert the result is ok. + if check_fastmath_result: + fastcpfunc = self.compile_parallel_fastmath(pfunc, sig) + kwargs = dict({'fastmath_pcres': fastcpfunc}, **kwargs) + + self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs) + return raised_warnings + + +@skip_parfors_unsupported +class TestPrangeBasic(TestPrangeBase): + """ Tests Prange """ + + def test_prange01(self): + def test_impl(): + n = 4 + A = np.zeros(n) + for i in range(n): + A[i] = 2.0 * i + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange02(self): + def test_impl(): + n = 4 + A = np.zeros(n - 1) + for i in range(1, n): + A[i - 1] = 2.0 * i + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03(self): + def test_impl(): + s = 10 + for i in range(10): + s += 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03mul(self): + def test_impl(): + s = 3 + for i in range(10): + s *= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03sub(self): + def test_impl(): + s = 100 + for i in range(10): + s -= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange03div(self): + def test_impl(): + s = 10 + for i in range(10): + s /= 2 + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange04(self): + def test_impl(): + a = 2 + b = 3 + A = np.empty(4) + for i in range(4): + if i == a: + A[i] = b + else: + A[i] = 0 + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange05(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(1, n - 1, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange06(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(1, 1, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange07(self): + def test_impl(): + n = 4 + A = np.ones((n), dtype=np.float64) + s = 0 + for i in range(n, 1): + s += A[i] + return s + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange08(self): + def test_impl(): + n = 4 + A = np.ones((n)) + acc = 0 + for i in range(len(A)): + for j in range(len(A)): + acc += A[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange08_1(self): + def test_impl(): + n = 4 + A = np.ones((n)) + acc = 0 + for i in range(4): + for j in range(4): + acc += A[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange09(self): + def test_impl(): + n = 4 + acc = 0 + for i in range(n): + for j in range(n): + acc += 1 + return acc + # patch inner loop to 'prange' + self.prange_tester(test_impl, patch_instance=[1], + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange10(self): + def test_impl(): + n = 4 + acc2 = 0 + for j in range(n): + acc1 = 0 + for i in range(n): + acc1 += 1 + acc2 += acc1 + return acc2 + # patch outer loop to 'prange' + self.prange_tester(test_impl, patch_instance=[0], + scheduler_type='unsigned', + check_fastmath=True) + + @unittest.skip("list append is not thread-safe yet (#2391, #2408)") + def test_prange11(self): + def test_impl(): + n = 4 + return [np.sin(j) for j in range(n)] + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange12(self): + def test_impl(): + acc = 0 + n = 4 + X = np.ones(n) + for i in range(-len(X)): + acc += X[i] + return acc + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + + def test_prange13(self): + def test_impl(n): + acc = 0 + for i in range(n): + acc += 1 + return acc + self.prange_tester(test_impl, np.int32(4), scheduler_type='unsigned', + check_fastmath=True) + + def test_prange14(self): + def test_impl(A): + s = 3 + for i in range(len(A)): + s += A[i]*2 + return s + # this tests reduction detection well since the accumulated variable + # is initialized before the parfor and the value accessed from the array + # is updated before accumulation + self.prange_tester(test_impl, np.random.ranf(4), + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange15(self): + # from issue 2587 + # test parfor type inference when there is multi-dimensional indexing + def test_impl(N): + acc = 0 + for i in range(N): + x = np.ones((1, 1)) + acc += x[0, 0] + return acc + self.prange_tester(test_impl, 1024, scheduler_type='unsigned', + check_fastmath=True) + + # Tests for negative ranges + def test_prange16(self): + def test_impl(N): + acc = 0 + for i in range(-N, N): + acc += 2 + return acc + self.prange_tester(test_impl, 1024, scheduler_type='signed', + check_fastmath=True) + + def test_prange17(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-N, N): + acc += X[i] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange18(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-N, 5): + acc += X[i] + for j in range(-4, N): + acc += X[j] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange19(self): + def test_impl(N): + acc = 0 + M = N + 4 + X = np.ones((N, M)) + for i in range(-N, N): + for j in range(-M, M): + acc += X[i, j] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange20(self): + def test_impl(N): + acc = 0 + X = np.ones(N) + for i in range(-1, N): + acc += X[i] + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange21(self): + def test_impl(N): + acc = 0 + for i in range(-3, -1): + acc += 3 + return acc + self.prange_tester(test_impl, 9, scheduler_type='signed', + check_fastmath=True) + + def test_prange22(self): + def test_impl(): + a = 0 + b = 3 + A = np.empty(4) + for i in range(-2, 2): + if i == a: + A[i] = b + elif i < 1: + A[i] = -1 + else: + A[i] = 7 + return A + self.prange_tester(test_impl, scheduler_type='signed', + check_fastmath=True, check_fastmath_result=True) + + def test_prange23(self): + # test non-contig input + def test_impl(A): + for i in range(len(A)): + A[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange24(self): + # test non-contig input, signed range + def test_impl(A): + for i in range(-len(A), 0): + A[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='signed', + check_fastmath=True, check_fastmath_result=True) + + def test_prange25(self): + def test_impl(A): + n = len(A) + buf = [np.zeros_like(A) for _ in range(n)] + for i in range(n): + buf[i] = A + i + return buf + A = np.ones((10,)) + self.prange_tester(test_impl, A, patch_instance=[1], + scheduler_type='unsigned', check_fastmath=True, + check_fastmath_result=True) + + cpfunc = self.compile_parallel(test_impl, (numba.typeof(A),)) + diagnostics = cpfunc.metadata['parfor_diagnostics'] + hoisted_allocs = diagnostics.hoisted_allocations() + self.assertEqual(len(hoisted_allocs), 0) + + def test_prange26(self): + def test_impl(A): + B = A[::3] + for i in range(len(B)): + B[i] = i + return A + A = np.zeros(32)[::2] + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange27(self): + # issue5597: usedef error in parfor + def test_impl(a, b, c): + for j in range(b[0]-1): + for k in range(2): + z = np.abs(a[c-1:c+1]) + return 0 + + # patch inner loop to 'prange' + self.prange_tester(test_impl, + np.arange(20), + np.asarray([4,4,4,4,4,4,4,4,4,4]), + 0, + patch_instance=[1], + scheduler_type='unsigned', + check_fastmath=True) + + def test_prange28(self): + # issue7105: label conflict in nested parfor + def test_impl(x, y): + out = np.zeros(len(y)) + for idx in range(0, len(y)): + i0 = y[idx, 0] + i1 = y[idx, 1] + Pt1 = x[i0] + Pt2 = x[i1] + v = Pt1 - Pt2 + vl2 = v[0] + v[1] + out[idx] = vl2 + return out + + X = np.array([[-1., -1.], + [-1., 1.], + [ 0., 0.], + [ 1., -1.], + [ 1., 0.], + [ 1., 1.]]) + + Y = np.array([[0, 1], + [1, 2], + [2, 3], + [3, 4], + [4, 5]]) + + self.prange_tester(test_impl, X, Y, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + + def test_prange29(self): + # issue7630: SSA renaming in prange header + def test_impl(flag): + result = 0 + if flag: + for i in range(1): + result += 1 + else: + for i in range(1): + result -= 3 + return result + + self.prange_tester(test_impl, True) + self.prange_tester(test_impl, False) + + def test_prange30(self): + # issue7675: broadcast setitem + def test_impl(x, par, numthreads): + n_par = par.shape[0] + n_x = len(x) + result = np.zeros((n_par, n_x), dtype=np.float64) + chunklen = (len(x) + numthreads - 1) // numthreads + + for i in range(numthreads): + start = i * chunklen + stop = (i + 1) * chunklen + result[:, start:stop] = x[start:stop] * par[:] + + return result + + x = np.array(np.arange(0, 6, 1.0)) + par = np.array([1.0, 2.0, 3.0]) + + self.prange_tester(test_impl, x, par, 2) + + +@register_jitable +def test_call_hoisting_outcall(a,b): + return (a, b) + + +@skip_parfors_unsupported +class TestPrangeSpecific(TestPrangeBase): + """ Tests specific features/problems found under prange""" + + def test_prange_two_instances_same_reduction_var(self): + # issue4922 - multiple uses of same reduction variable + def test_impl(n): + c = 0 + for i in range(n): + c += 1 + if i > 10: + c += 1 + return c + self.prange_tester(test_impl, 9) + + def test_prange_conflicting_reduction_ops(self): + def test_impl(n): + c = 0 + for i in range(n): + c += 1 + if i > 10: + c *= 1 + return c + + with self.assertRaises(errors.UnsupportedError) as raises: + self.prange_tester(test_impl, 9) + msg = ('Reduction variable c has multiple conflicting reduction ' + 'operators.') + self.assertIn(msg, str(raises.exception)) + + def test_prange_two_conditional_reductions(self): + # issue6414 + def test_impl(): + A = B = 0 + for k in range(1): + if k == 2: + A += 1 + else: + x = np.zeros((1, 1)) + if x[0, 0]: + B += 1 + return A, B + self.prange_tester(test_impl) + + def test_prange_nested_reduction1(self): + def test_impl(): + A = 0 + for k in range(1): + for i in range(1): + if i == 0: + A += 1 + return A + self.prange_tester(test_impl) + + @disabled_test + def test_check_error_model(self): + def test_impl(): + n = 32 + A = np.zeros(n) + for i in range(n): + A[i] = 1 / i # div-by-zero when i = 0 + return A + + with self.assertRaises(ZeroDivisionError) as raises: + test_impl() + + # compile parallel functions + pfunc = self.generate_prange_func(test_impl, None) + pcres = self.compile_parallel(pfunc, ()) + pfcres = self.compile_parallel_fastmath(pfunc, ()) + + # should raise + with self.assertRaises(ZeroDivisionError) as raises: + pcres.entry_point() + + # should not raise + result = pfcres.entry_point() + self.assertEqual(result[0], np.inf) + + def test_check_alias_analysis(self): + # check alias analysis reports ok + def test_impl(A): + for i in range(len(A)): + B = A[i] + B[:] = 1 + return A + A = np.zeros(32).reshape(4, 8) + self.prange_tester(test_impl, A, scheduler_type='unsigned', + check_fastmath=True, check_fastmath_result=True) + pfunc = self.generate_prange_func(test_impl, None) + sig = tuple([numba.typeof(A)]) + cres = self.compile_parallel_fastmath(pfunc, sig) + _ir = self._get_gufunc_ir(cres) + for k, v in _ir.items(): + for line in v.splitlines(): + # get the fn definition line + if 'define' in line and k in line: + # there should only be 2x noalias, one on each of the first + # 2 args (retptr, excinfo). + # Note: used to be 3x no noalias, but env arg is dropped. + self.assertEqual(line.count('noalias'), 2) + break + + def test_prange_raises_invalid_step_size(self): + def test_impl(N): + acc = 0 + for i in range(0, N, 2): + acc += 2 + return acc + + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.prange_tester(test_impl, 1024) + msg = 'Only constant step size of 1 is supported for prange' + self.assertIn(msg, str(raises.exception)) + + @unittest.skip("skip due to issue #10203: https://github.com/numba/numba/issues/10203") + def test_prange_fastmath_check_works(self): + # this function will benefit from `fastmath`, the div will + # get optimised to a multiply by reciprocal and the accumulator + # then becomes an fmadd: A = A + i * 0.5 + def test_impl(): + n = 128 + A = 0 + for i in range(n): + A += i / 2.0 + return A + self.prange_tester(test_impl, scheduler_type='unsigned', + check_fastmath=True) + pfunc = self.generate_prange_func(test_impl, None) + cres = self.compile_parallel_fastmath(pfunc, ()) + ir = self._get_gufunc_ir(cres) + _id = '%[A-Z_0-9]?(.[0-9]+)+[.]?[i]?' + recipr_str = r'\s+%s = fmul fast double %s, 5.000000e-01' + reciprocal_inst = re.compile(recipr_str % (_id, _id)) + fadd_inst = re.compile(r'\s+%s = fadd fast double %s, %s' + % (_id, _id, _id)) + # check there is something like: + # %.329 = fmul fast double %.325, 5.000000e-01 + # %.337 = fadd fast double %A.07, %.329 + found = False + for name, kernel in ir.items(): + # make sure to look at the kernel corresponding to the cres/pfunc + if name in cres.library.get_llvm_str(): + splitted = kernel.splitlines() + for i, x in enumerate(splitted): + if reciprocal_inst.match(x): + self.assertTrue(fadd_inst.match(splitted[i + 1])) + found = True + break + + self.assertTrue(found, "fast instruction pattern was not found.") + + def test_parfor_alias1(self): + def test_impl(n): + b = np.zeros((n, n)) + a = b[0] + for j in range(n): + a[j] = j + 1 + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_alias2(self): + def test_impl(n): + b = np.zeros((n, n)) + for i in range(n): + a = b[i] + for j in range(n): + a[j] = i + j + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_alias3(self): + def test_impl(n): + b = np.zeros((n, n, n)) + for i in range(n): + a = b[i] + for j in range(n): + c = a[j] + for k in range(n): + c[k] = i + j + k + return b.sum() + self.prange_tester(test_impl, 4) + + def test_parfor_race_1(self): + def test_impl(x, y): + for j in range(y): + k = x + return k + raised_warnings = self.prange_tester(test_impl, 10, 20) + warning_obj = raised_warnings[0] + expected_msg = ("Variable k used in parallel loop may be written to " + "simultaneously by multiple workers and may result " + "in non-deterministic or unintended results.") + self.assertIn(expected_msg, str(warning_obj.message)) + + def test_nested_parfor_push_call_vars(self): + """ issue 3686: if a prange has something inside it that causes + a nested parfor to be generated and both the inner and outer + parfor use the same call variable defined outside the parfors + then ensure that when that call variable is pushed into the + parfor that the call variable isn't duplicated with the same + name resulting in a redundant type lock. + """ + def test_impl(): + B = 0 + f = np.negative + for i in range(1): + this_matters = f(1.) + B += f(np.zeros(1,))[0] + for i in range(2): + this_matters = f(1.) + B += f(np.zeros(1,))[0] + + return B + self.prange_tester(test_impl) + + def test_copy_global_for_parfor(self): + """ issue4903: a global is copied next to a parfor so that + it can be inlined into the parfor and thus not have to be + passed to the parfor (i.e., an unsupported function type). + This global needs to be renamed in the block into which + it is copied. + """ + def test_impl(zz, tc): + lh = np.zeros(len(tc)) + lc = np.zeros(len(tc)) + for i in range(1): + nt = tc[i] + for t in range(nt): + lh += np.exp(zz[i, t]) + for t in range(nt): + lc += np.exp(zz[i, t]) + return lh, lc + + m = 2 + zz = np.ones((m, m, m)) + tc = np.ones(m, dtype=np.int_) + self.prange_tester(test_impl, zz, tc, patch_instance=[0]) + + def test_multiple_call_getattr_object(self): + def test_impl(n): + B = 0 + f = np.negative + for i in range(1): + this_matters = f(1.0) + B += f(n) + + return B + self.prange_tester(test_impl, 1.0) + + def test_argument_alias_recarray_field(self): + # Test for issue4007. + def test_impl(n): + for i in range(len(n)): + n.x[i] = 7.0 + return n + X1 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + X2 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + X3 = np.zeros(10, dtype=[('x', float), ('y', int), ]) + v1 = X1.view(np.recarray) + v2 = X2.view(np.recarray) + v3 = X3.view(np.recarray) + + # Numpy doesn't seem to support almost equal on recarray. + # So, we convert to list and use assertEqual instead. + python_res = list(test_impl(v1)) + njit_res = list(njit(test_impl)(v2)) + pa_func = njit(test_impl, parallel=True) + pa_res = list(pa_func(v3)) + self.assertEqual(python_res, njit_res) + self.assertEqual(python_res, pa_res) + + def test_mutable_list_param(self): + """ issue3699: test that mutable variable to call in loop + is not hoisted. The call in test_impl forces a manual + check here rather than using prange_tester. + """ + @njit + def list_check(X): + """ If the variable X is hoisted in the test_impl prange + then subsequent list_check calls would return increasing + values. + """ + ret = X[-1] + a = X[-1] + 1 + X.append(a) + return ret + def test_impl(n): + for i in prange(n): + X = [100] + a = list_check(X) + return a + python_res = test_impl(10) + njit_res = njit(test_impl)(10) + pa_func = njit(test_impl, parallel=True) + pa_res = pa_func(10) + self.assertEqual(python_res, njit_res) + self.assertEqual(python_res, pa_res) + + def test_list_comprehension_prange(self): + # issue4569 + def test_impl(x): + return np.array([len(x[i]) for i in range(len(x))]) + x = [np.array([1,2,3], dtype=int),np.array([1,2], dtype=int)] + self.prange_tester(test_impl, x) + + def test_ssa_false_reduction(self): + # issue5698 + # SSA for h creates assignments to h that make it look like a + # reduction variable except that it lacks an associated + # reduction operator. Test here that h is excluded as a + # reduction variable. + def test_impl(image, a, b): + empty = np.zeros(image.shape) + for i in range(image.shape[0]): + r = image[i][0] / 255.0 + if a == 0: + h = 0 + if b == 0: + h = 0 + empty[i] = [h, h, h] + return empty + + image = np.zeros((3, 3), dtype=np.int32) + self.prange_tester(test_impl, image, 0, 0) + + def test_list_setitem_hoisting(self): + # issue5979 + # Don't hoist list initialization if list item set. + def test_impl(): + n = 5 + a = np.empty(n, dtype=np.int64) + for k in range(5): + X = [0] + X[0] = 1 + a[k] = X[0] + return a + + self.prange_tester(test_impl) + + def test_tuple_hoisting(self): + # issue9529 + def test_impl(inputs): + outputs = [(Dict.empty(key_type=types.int64, value_type=types.float64), np.zeros(1)) for _ in range(len(inputs))] + for i in range(len(inputs)): + y = inputs[i] + out = np.zeros(1) + out[0] = i + outputs[i] = (inputs[i], out) + return outputs[0][1][0] + + N = config.NUMBA_NUM_THREADS + 1 + self.prange_tester(test_impl, [Dict.empty(key_type=types.int64, value_type=types.float64) for i in range(N)], patch_instance=[1]) + + def test_call_hoisting(self): + # issue9529 + def test_impl(inputs): + outputs = [(Dict.empty(key_type=types.int64, value_type=types.float64), np.zeros(1)) for _ in range(len(inputs))] + for i in range(len(inputs)): + y = inputs[i] + out = np.zeros(1) + out[0] = i + outputs[i] = test_call_hoisting_outcall(inputs[i], out) + return outputs[0][1][0] + + N = config.NUMBA_NUM_THREADS + 1 + self.prange_tester(test_impl, [Dict.empty(key_type=types.int64, value_type=types.float64) for i in range(N)], patch_instance=[1]) + + def test_record_array_setitem(self): + # issue6704 + state_dtype = np.dtype([('var', np.int32)]) + + def test_impl(states): + for i in range(1): + states[i]['var'] = 1 + + def comparer(a, b): + assert(a[0]['var'] == b[0]['var']) + + self.prange_tester(test_impl, + np.zeros(shape=1, dtype=state_dtype), + check_arg_equality=[comparer]) + + def test_record_array_setitem_yield_array(self): + state_dtype = np.dtype([('x', np.intp)]) + + def test_impl(states): + n = states.size + for i in range(states.size): + states["x"][i] = 7 + i + return states + + states = np.zeros(10, dtype=state_dtype) + + def comparer(a, b): + np.testing.assert_equal(a, b) + + self.prange_tester(test_impl, + states, + check_arg_equality=[comparer]) + + def test_issue7501(self): + def test_impl(size, case): + result = np.zeros((size,)) + if case == 1: + for i in range(size): + result[i] += 1 + else: + for i in range(size): + result[i] += 2 + return result[0] + + self.prange_tester(test_impl, 3, 1) + + def test_kde_example(self): + def test_impl(X): + # KDE example + b = 0.5 + points = np.array([-1.0, 2.0, 5.0]) + N = points.shape[0] + n = X.shape[0] + exps = 0 + for i in range(n): + p = X[i] + d = (-(p - points)**2) / (2 * b**2) + m = np.min(d) + exps += m - np.log(b * N) + np.log(np.sum(np.exp(d - m))) + return exps + + n = 128 + X = np.random.ranf(n) + self.prange_tester(test_impl, X) + + @skip_parfors_unsupported + def test_issue7578(self): + def test_impl(x): + A = np.zeros_like(x) + tmp = np.cos(x) # this can be any 1-arity ufunc + + for i in range(len(x)): + A[i] = tmp.sum() + + return A + + x = np.arange(10.) + self.prange_tester(test_impl, x) + +@skip_parfors_unsupported +class TestParforChunksizing(TestCase): + """ + Tests chunksize handling in ParallelAccelerator. + """ + _numba_parallel_test_ = False + + def setUp(self): + set_parallel_chunksize(0) + + def tearDown(self): + set_parallel_chunksize(0) + + def test_python_parallel_chunksize_basic(self): + # Test basic chunksize operations outside njit. + self.assertEqual(get_parallel_chunksize(), 0) + set_parallel_chunksize(8) + self.assertEqual(get_parallel_chunksize(), 8) + set_parallel_chunksize(0) + self.assertEqual(get_parallel_chunksize(), 0) + + def test_python_with_chunksize(self): + # Test "with parallel_chunksize" outside njit. + self.assertEqual(get_parallel_chunksize(), 0) + with parallel_chunksize(8): + self.assertEqual(get_parallel_chunksize(), 8) + self.assertEqual(get_parallel_chunksize(), 0) + + def test_njit_parallel_chunksize_basic(self): + # Test basic chunksize operations inside njit. + @njit + def get_cs(): + return get_parallel_chunksize() + + @njit + def set_cs(x): + return set_parallel_chunksize(x) + + self.assertEqual(get_cs(), 0) + set_cs(8) + self.assertEqual(get_cs(), 8) + set_cs(0) + self.assertEqual(get_cs(), 0) + + def test_njit_with_chunksize(self): + # Test "with parallel_chunksize" inside njit. + @njit + def test_impl(x): + cs1 = get_parallel_chunksize() + with parallel_chunksize(8): + cs2 = get_parallel_chunksize() + cs3 = get_parallel_chunksize() + return cs1, cs2, cs3 + + cs1, cs2, cs3 = test_impl(8) + + self.assertEqual(cs1, 0) + self.assertEqual(cs2, 8) + self.assertEqual(cs3, 0) + + def test_all_iterations_reset_chunksize(self): + """ Test that all the iterations get run if you set the + chunksize. Also check that the chunksize that each + worker thread sees has been reset to 0. """ + + @njit(parallel=True) + def test_impl(cs, n): + res = np.zeros(n) + inner_cs = np.full(n, -13) + with numba.parallel_chunksize(cs): + for i in numba.prange(n): + inner_cs[i] = numba.get_parallel_chunksize() + res[i] = 13 + return res, inner_cs + + # Test a variety of array and chunk sizes. + # 1000 is a round number, 997 is prime, 943 is product of two + # primes, 961 is square of a prime. + for j in [1000, 997, 943, 961]: + for i in range(15): + res, inner_cs = test_impl(i+1, j) + self.assertTrue(np.all(res == 13)) + self.assertTrue(np.all(inner_cs == 0)) + + def test_njit_parallel_chunksize_negative(self): + # Test negative set_parallel_chunksize inside njit. + with self.assertRaises(ValueError) as raised: + @njit + def neg_test(): + set_parallel_chunksize(-1) + + neg_test() + + msg = "chunksize must be greater than or equal to zero" + self.assertIn(msg, str(raised.exception)) + + def test_python_parallel_chunksize_negative(self): + # Test negative set_parallel_chunksize outside njit. + with self.assertRaises(ValueError) as raised: + set_parallel_chunksize(-1) + + msg = "chunksize must be greater than or equal to zero" + self.assertIn(msg, str(raised.exception)) + + def test_njit_parallel_chunksize_invalid_type(self): + with self.assertRaises(errors.TypingError) as raised: + @njit + def impl(): + set_parallel_chunksize('invalid_type') + + impl() + + msg = "The parallel chunksize must be an integer" + self.assertIn(msg, str(raised.exception)) + + def test_python_parallel_chunksize_invalid_type(self): + with self.assertRaises(TypeError) as raised: + set_parallel_chunksize('invalid_type') + + msg = "The parallel chunksize must be an integer" + self.assertIn(msg, str(raised.exception)) + + +@skip_parfors_unsupported +@x86_only +class TestParforsVectorizer(TestPrangeBase): + + # env mutating test + _numba_parallel_test_ = False + + def get_gufunc_asm(self, func, schedule_type, *args, **kwargs): + + fastmath = kwargs.pop('fastmath', False) + cpu_name = kwargs.pop('cpu_name', 'skylake-avx512') + assertions = kwargs.pop('assertions', True) + # force LLVM to use zmm registers for vectorization + # https://reviews.llvm.org/D67259 + cpu_features = kwargs.pop('cpu_features', '-prefer-256-bit') + + env_opts = {'NUMBA_CPU_NAME': cpu_name, + 'NUMBA_CPU_FEATURES': cpu_features, + } + + overrides = [] + for k, v in env_opts.items(): + overrides.append(override_env_config(k, v)) + + with overrides[0], overrides[1]: + sig = tuple([numba.typeof(x) for x in args]) + pfunc_vectorizable = self.generate_prange_func(func, None) + if fastmath == True: + cres = self.compile_parallel_fastmath(pfunc_vectorizable, sig) + else: + cres = self.compile_parallel(pfunc_vectorizable, sig) + + # get the gufunc asm + asm = self._get_gufunc_asm(cres) + + if assertions: + schedty = re.compile(r'call\s+\w+\*\s+@do_scheduling_(\w+)\(') + matches = schedty.findall(cres.library.get_llvm_str()) + self.assertGreaterEqual(len(matches), 1) # at least 1 parfor call + self.assertEqual(matches[0], schedule_type) + self.assertNotEqual(asm, {}) + + return asm + + @linux_only + @TestCase.run_test_in_subprocess + def test_vectorizer_fastmath_asm(self): + """ This checks that if fastmath is set and the underlying hardware + is suitable, and the function supplied is amenable to fastmath based + vectorization, that the vectorizer actually runs. + """ + + # This function will benefit from `fastmath` if run on a suitable + # target. The vectorizer should unwind the loop and generate + # packed dtype=double add and sqrt instructions. + def will_vectorize(A): + n = len(A) + acc = 0 + for i in range(n): + acc += np.sqrt(i) + return acc + + arg = np.zeros(10) + + fast_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=True) + slow_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=False) + for v in fast_asm.values(): + # should unwind and call vector sqrt then vector add + # all on packed doubles using zmm's + self.assertTrue('vaddpd' in v) + self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v) + self.assertTrue('zmm' in v) + + for v in slow_asm.values(): + # vector variants should not be present + self.assertTrue('vaddpd' not in v) + self.assertTrue('vsqrtpd' not in v) + # check scalar variant is present + self.assertTrue('vsqrtsd' in v and '__svml_sqrt' not in v) + self.assertTrue('vaddsd' in v) + # check no zmm addressing is present + self.assertTrue('zmm' not in v) + + @linux_only + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'}) + def test_unsigned_refusal_to_vectorize(self): + """ This checks that if fastmath is set and the underlying hardware + is suitable, and the function supplied is amenable to fastmath based + vectorization, that the vectorizer actually runs. + """ + + def will_not_vectorize(A): + n = len(A) + for i in range(-n, 0): + A[i] = np.sqrt(A[i]) + return A + + def will_vectorize(A): + n = len(A) + for i in range(n): + A[i] = np.sqrt(A[i]) + return A + + arg = np.zeros(10) + + # Boundschecking breaks vectorization + self.assertFalse(config.BOUNDSCHECK) + novec_asm = self.get_gufunc_asm(will_not_vectorize, 'signed', arg, + fastmath=True) + + vec_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg, + fastmath=True) + + for v in novec_asm.values(): + # vector variant should not be present + self.assertTrue('vsqrtpd' not in v) + # check scalar variant is present + self.assertTrue('vsqrtsd' in v) + # check no zmm addressing is present + self.assertTrue('zmm' not in v) + + for v in vec_asm.values(): + # should unwind and call vector sqrt then vector mov + # all on packed doubles using zmm's + self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v) + self.assertTrue('vmovupd' in v) + self.assertTrue('zmm' in v) + + @linux_only + # needed as 32bit doesn't have equivalent signed/unsigned instruction + # generation for this function + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'}) + def test_signed_vs_unsigned_vec_asm(self): + """ This checks vectorization for signed vs unsigned variants of a + trivial accumulator, the only meaningful difference should be the + presence of signed vs. unsigned unpack instructions (for the + induction var). + """ + def signed_variant(): + n = 4096 + A = 0. + for i in range(-n, 0): + A += i + return A + + def unsigned_variant(): + n = 4096 + A = 0. + for i in range(n): + A += i + return A + + # Boundschecking breaks the diff check below because of the pickled exception + self.assertFalse(config.BOUNDSCHECK) + signed_asm = self.get_gufunc_asm(signed_variant, 'signed', + fastmath=True) + unsigned_asm = self.get_gufunc_asm(unsigned_variant, 'unsigned', + fastmath=True) + + def strip_instrs(asm): + acc = [] + for x in asm.splitlines(): + spd = x.strip() + # filter out anything that isn't a trivial instruction + # and anything with the gufunc id as it contains an address + if spd != '' and not (spd.startswith('.') + or spd.startswith('_') + or spd.startswith('"') + or '__numba_parfor_gufunc' in spd): + acc.append(re.sub('[\t]', '', spd)) + return acc + + for k, v in signed_asm.items(): + signed_instr = strip_instrs(v) + break + + for k, v in unsigned_asm.items(): + unsigned_instr = strip_instrs(v) + break + + from difflib import SequenceMatcher as sm + # make sure that the only difference in instruction (if there is a + # difference) is the char 'u'. For example: + # vcvtsi2sdq vs. vcvtusi2sdq + self.assertEqual(len(signed_instr), len(unsigned_instr)) + for a, b in zip(signed_instr, unsigned_instr): + if a == b: + continue + else: + s = sm(lambda x: x == '\t', a, b) + ops = s.get_opcodes() + for op in ops: + if op[0] == 'insert': + self.assertEqual(b[op[-2]:op[-1]], 'u') + + +@skip_parfors_unsupported +class TestParforReductionSetNumThreads(TestCase): + """Test execution correctness on reductions with set_num_threads. + """ + def test_add(self): + N = config.NUMBA_NUM_THREADS + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 0 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc += gnt + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + def test_mul(self): + # This min will prevent larger thread counts from generating + # overflow in the loop below. + N = min(4, config.NUMBA_NUM_THREADS) + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 1 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc *= gnt + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + def test_max(self): + N = config.NUMBA_NUM_THREADS + M = 2 * N + mask = N - 1 + + @njit(parallel=True) + def udt(nthreads): + acc = 1 + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + set_num_threads(local_mask) + gnt = get_num_threads() + acc = max(acc, gnt) + return acc + + expect = udt.py_func(mask) + got = udt(mask) + self.assertPreciseEqual(expect, got) + + +@skip_parfors_unsupported +class TestDiagnosticEnvVar(TestCase): + @TestCase.run_test_in_subprocess() + def test_diagnostics_env_var1(self): + os.environ['NUMBA_PARALLEL_DIAGNOSTICS']='4' + with captured_stdout() as stdout: + @njit(parallel=True) + def impl(): + n = 100 + b = np.zeros((n), dtype=np.float64) + for i in prange(n): + b[i] = 1 + return b + + impl() + the_output = stdout.getvalue() + self.assertIn("Parallel Accelerator Optimizing", the_output) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_caching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..87ee3c0e1a2deb35ce4ef84f4aa67ff313f3d973 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_caching.py @@ -0,0 +1,83 @@ +import os.path +import subprocess +import sys + +import numpy as np + +from numba.tests.support import skip_parfors_unsupported +from .test_caching import DispatcherCacheUsecasesTest + + +@skip_parfors_unsupported +class TestParforsCache(DispatcherCacheUsecasesTest): + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "parfors_cache_usecases.py") + modname = "parfors_caching_test_fodder" + + def run_test(self, fname, num_funcs=1): + mod = self.import_module() + self.check_pycache(0) + f = getattr(mod, fname) + ary = np.ones(10) + # The result of these functions is derived from e.g. out of order + # accumulation so allclose should be fine. + np.testing.assert_allclose(f(ary), f.py_func(ary)) + + dynamic_globals = [cres.library.has_dynamic_globals + for cres in f.overloads.values()] + [cres] = f.overloads.values() + self.assertEqual(dynamic_globals, [False]) + # For each cached func, there're 2 entries (index + data) + self.check_pycache(num_funcs * 2) + + self.run_in_separate_process() + + def test_arrayexprs(self): + f = 'arrayexprs_case' + self.run_test(f) + + def test_prange(self): + f = 'prange_case' + self.run_test(f) + + def test_caller(self): + f = 'caller_case' + # num_funcs=3 because, there's the `caller_case()` which calls + # the `prange_case()` and `arrayexprs_case()` + self.run_test(f, num_funcs=3) + + +@skip_parfors_unsupported +class TestParforsCacheChangingThreads(DispatcherCacheUsecasesTest): + # NOTE: This test is checking issue #7518, that thread counts are not + # baked into cached objects. + + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "parfors_cache_usecases.py") + modname = "parfors_caching_test_fodder" + + def run_in_separate_process(self, thread_count): + # Cached functions can be run from a distinct process. + code = """if 1: + import sys + + sys.path.insert(0, %(tempdir)r) + mod = __import__(%(modname)r) + mod.self_run() + """ % dict(tempdir=self.tempdir, modname=self.modname) + + new_env = {**os.environ, "NUMBA_NUM_THREADS" : str(thread_count)} + popen = subprocess.Popen([sys.executable, "-c", code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=new_env) + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError(f"process failed with code {popen.returncode}:" + f"stderr follows\n{err.decode()}\n") + + def test_caching(self): + self.check_pycache(0) + self.run_in_separate_process(1) + self.check_pycache(3 * 2) # ran 3 functions, 2 entries each + self.run_in_separate_process(2) + self.check_pycache(3 * 2) # ran 3 functions, 2 entries each diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_passes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_passes.py new file mode 100644 index 0000000000000000000000000000000000000000..2e8c23fe6ca75236b1acd5faf9bf76953d8840dd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_parfors_passes.py @@ -0,0 +1,676 @@ +""" +Tests for sub-components of parfors. +These tests are aimed to produce a good-enough coverage of parfor passes +so that refactoring on these passes are easier with faster testing turnaround. +""" +import unittest +from functools import reduce + +import numpy as np + +from numba import njit, typeof, prange, pndindex +import numba.parfors.parfor +from numba.core import ( + rewrites, + typed_passes, + untyped_passes, + inline_closurecall, + compiler, + cpu, + errors +) +from numba.core.registry import cpu_target +from numba.tests.support import (TestCase, is_parfors_unsupported) + + +class MyPipeline(object): + def __init__(self, typingctx, targetctx, args, test_ir): + self.state = compiler.StateDict() + self.state.typingctx = typingctx + self.state.targetctx = targetctx + self.state.args = args + self.state.func_ir = test_ir + self.state.typemap = None + self.state.return_type = None + self.state.calltypes = None + self.state.metadata = {} + + +class BaseTest(TestCase): + @classmethod + def _run_parfor(cls, test_func, args, swap_map=None): + # TODO: refactor this with get_optimized_numba_ir() where this is + # copied from + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_func) + options = cpu.ParallelOptions(True) + + tp = MyPipeline(typingctx, targetctx, args, test_ir) + + typingctx.refresh() + targetctx.refresh() + + inline_pass = inline_closurecall.InlineClosureCallPass( + tp.state.func_ir, options, typed=True + ) + inline_pass.run() + + rewrites.rewrite_registry.apply("before-inference", tp.state) + + untyped_passes.ReconstructSSA().run_pass(tp.state) + + ( + tp.state.typemap, + tp.state.return_type, + tp.state.calltypes, + _ + ) = typed_passes.type_inference_stage( + tp.state.typingctx, tp.state.targetctx, tp.state.func_ir, + tp.state.args, None + ) + + typed_passes.PreLowerStripPhis().run_pass(tp.state) + + diagnostics = numba.parfors.parfor.ParforDiagnostics() + + preparfor_pass = numba.parfors.parfor.PreParforPass( + tp.state.func_ir, + tp.state.typemap, + tp.state.calltypes, + tp.state.typingctx, + tp.state.targetctx, + options, + swapped=diagnostics.replaced_fns, + replace_functions_map=swap_map, + ) + preparfor_pass.run() + + rewrites.rewrite_registry.apply("after-inference", tp.state) + return tp, options, diagnostics, preparfor_pass + + @classmethod + def run_parfor_sub_pass(cls, test_func, args): + tp, options, diagnostics, _ = cls._run_parfor(test_func, args) + + flags = compiler.Flags() + parfor_pass = numba.parfors.parfor.ParforPass( + tp.state.func_ir, + tp.state.typemap, + tp.state.calltypes, + tp.state.return_type, + tp.state.typingctx, + tp.state.targetctx, + options, + flags, + tp.state.metadata, + diagnostics=diagnostics, + ) + parfor_pass._pre_run() + # Run subpass + sub_pass = cls.sub_pass_class(parfor_pass) + sub_pass.run(parfor_pass.func_ir.blocks) + + return sub_pass + + @classmethod + def run_parfor_pre_pass(cls, test_func, args, swap_map=None): + tp, options, diagnostics, preparfor_pass = cls._run_parfor( + test_func, args, swap_map + ) + return preparfor_pass + + def _run_parallel(self, func, *args, **kwargs): + cfunc = njit(parallel=True)(func) + expect = func(*args, **kwargs) + got = cfunc(*args, **kwargs) + return expect, got + + def run_parallel(self, func, *args, **kwargs): + if is_parfors_unsupported: + # Skip + return + expect, got = self._run_parallel(func, *args, **kwargs) + self.assertPreciseEqual(expect, got) + + def run_parallel_check_output_array(self, func, *args, **kwargs): + if is_parfors_unsupported: + # Skip + return + expect, got = self._run_parallel(func, *args, **kwargs) + # Don't match the value, just the return type. must return array + self.assertIsInstance(expect, np.ndarray) + self.assertIsInstance(got, np.ndarray) + self.assertEqual(expect.shape, got.shape) + + def check_records(self, records): + for rec in records: + self.assertIsInstance(rec["new"], numba.parfors.parfor.Parfor) + + +class TestConvertSetItemPass(BaseTest): + sub_pass_class = numba.parfors.parfor.ConvertSetItemPass + + def test_setitem_full_slice(self): + def test_impl(): + n = 10 + a = np.ones(n) + a[:] = 7 + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "slice") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_setitem_slice_stop_bound(self): + def test_impl(): + n = 10 + a = np.ones(n) + a[:5] = 7 + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "slice") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_setitem_slice_start_bound(self): + def test_impl(): + n = 10 + a = np.ones(n) + a[4:] = 7 + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "slice") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_setitem_gather_if_scalar(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.ones_like(a, dtype=np.bool_) + a[b] = 7 + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "masked_assign_broadcast_scalar") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_setitem_gather_if_array(self): + def test_impl(): + n = 10 + a = np.ones(n) + b = np.ones_like(a, dtype=np.bool_) + c = np.ones_like(a) + a[b] = c[b] + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "masked_assign_array") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + +class TestConvertNumpyPass(BaseTest): + sub_pass_class = numba.parfors.parfor.ConvertNumpyPass + + def check_numpy_allocators(self, fn): + def test_impl(): + n = 10 + a = fn(n) + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "numpy_allocator") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def check_numpy_random(self, fn): + def test_impl(): + n = 10 + a = fn(n) + return a + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "numpy_allocator") + self.check_records(sub_pass.rewritten) + + self.run_parallel_check_output_array(test_impl) + + def test_numpy_allocators(self): + fns = [np.ones, np.zeros] + for fn in fns: + with self.subTest(fn.__name__): + self.check_numpy_allocators(fn) + + def test_numpy_random(self): + fns = [np.random.random] + for fn in fns: + with self.subTest(fn.__name__): + self.check_numpy_random(fn) + + def test_numpy_arrayexpr(self): + def test_impl(a, b): + return a + b + + a = b = np.ones(10) + + args = (a, b) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "arrayexpr") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + def test_numpy_arrayexpr_ufunc(self): + def test_impl(a, b): + return np.sin(-a) + np.float64(1) / np.sqrt(b) + + a = b = np.ones(10) + + args = (a, b) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "arrayexpr") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + def test_numpy_arrayexpr_boardcast(self): + def test_impl(a, b): + return a + b + np.array(1) + + a = np.ones(10) + b = np.ones((3, 10)) + + args = (a, b) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "arrayexpr") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + def test_numpy_arrayexpr_reshaped(self): + def test_impl(a, b): + a = a.reshape(1, a.size) # shape[0] is now constant + return a + b + + a = np.ones(10) + b = np.ones(10) + + args = (a, b) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "arrayexpr") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + +class TestConvertReducePass(BaseTest): + sub_pass_class = numba.parfors.parfor.ConvertReducePass + + def test_reduce_max_basic(self): + def test_impl(arr): + return reduce(lambda x, y: max(x, y), arr, 0.0) + + x = np.ones(10) + args = (x,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "reduce") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + def test_reduce_max_masked(self): + def test_impl(arr): + return reduce(lambda x, y: max(x, y), arr[arr > 5], 0.0) + + x = np.ones(10) + args = (x,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "reduce") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl, *args) + + +class TestConvertLoopPass(BaseTest): + sub_pass_class = numba.parfors.parfor.ConvertLoopPass + + def test_prange_reduce_simple(self): + def test_impl(): + n = 20 + c = 0 + for i in prange(n): + c += i + return c + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_prange_map_simple(self): + def test_impl(): + n = 20 + arr = np.ones(n) + for i in prange(n): + arr[i] += i + return arr + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_prange_two_args(self): + def test_impl(): + n = 20 + arr = np.ones(n) + for i in prange(3, n): + arr[i] += i + return arr + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_prange_three_args(self): + def test_impl(): + n = 20 + arr = np.ones(n) + for i in prange(3, n, 2): + arr[i] += i + return arr + + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.run_parfor_sub_pass(test_impl, ()) + self.assertIn( + "Only constant step size of 1 is supported for prange", + str(raises.exception), + ) + + def test_prange_map_inner_loop(self): + def test_impl(): + n = 20 + arr = np.ones((n, n)) + for i in prange(n): + for j in range(i): + arr[i, j] += i + j * n + return arr + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + + self.run_parallel(test_impl) + + def test_prange_map_nested_prange(self): + def test_impl(): + n = 20 + arr = np.ones((n, n)) + for i in prange(n): + for j in prange(i): + arr[i, j] += i + j * n + return arr + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 2) + self.check_records(sub_pass.rewritten) + for record in sub_pass.rewritten: + self.assertEqual(record["reason"], "loop") + + self.run_parallel(test_impl) + + def test_prange_map_none_index(self): + def test_impl(): + n = 20 + arr = np.ones(n) + for i in prange(n): + inner = arr[i : i + 1] + inner[()] += 1 + return arr + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + self.check_records(sub_pass.rewritten) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + + self.run_parallel(test_impl) + + def test_prange_map_overwrite_index(self): + def test_impl(): + n = 20 + arr = np.ones(n) + for i in prange(n): + i += 1 + arr[i - 1] = i + return arr + + with self.assertRaises(errors.UnsupportedRewriteError) as raises: + self.run_parfor_sub_pass(test_impl, ()) + self.assertIn( + "Overwrite of parallel loop index", + str(raises.exception), + ) + + def test_init_prange(self): + def test_impl(): + n = 20 + arr = np.ones(n) + numba.parfors.parfor.init_prange() + val = 0 + for i in numba.parfors.parfor.internal_prange(len(arr)): + val += arr[i] + return val + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + self.check_records(sub_pass.rewritten) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + + self.run_parallel(test_impl) + + def test_pndindex(self): + def test_impl(): + n = 20 + arr = np.ones((n, n)) + val = 0 + for idx in pndindex(arr.shape): + val += idx[0] * idx[1] + return val + + sub_pass = self.run_parfor_sub_pass(test_impl, ()) + self.assertEqual(len(sub_pass.rewritten), 1) + self.check_records(sub_pass.rewritten) + + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + + self.run_parallel(test_impl) + + def test_numpy_sum(self): + def test_impl(arr): + return np.sum(arr) + + shape = 11, 13 + arr = np.arange(np.prod(shape)).reshape(shape) + args = (arr,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + self.run_parallel(test_impl, *args) + + def test_numpy_sum_bool_array_masked(self): + def test_impl(arr): + sliced = arr[:, 0] + return np.sum(arr[sliced >= 3, 1:2]) + + shape = 11, 13 + arr = np.arange(np.prod(shape)).reshape(shape) + args = (arr,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + self.run_parallel(test_impl, *args) + + def test_numpy_sum_int_array_masked(self): + def test_impl(arr): + sel = np.arange(arr.shape[1]) + return np.sum(arr[:, sel]) + + shape = 11, 13 + arr = np.arange(np.prod(shape)).reshape(shape) + args = (arr,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + # 1 for arange; 1 for sum + self.assertEqual(len(sub_pass.rewritten), 2) + for record in sub_pass.rewritten: + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + self.run_parallel(test_impl, *args) + + def test_numpy_fill_method(self): + def test_impl(arr): + arr.fill(3) + return arr + + shape = 11, 13 + arr = np.arange(np.prod(shape)).reshape(shape) + args = (arr,) + argtypes = [typeof(x) for x in args] + + sub_pass = self.run_parfor_sub_pass(test_impl, argtypes) + # 1 for arange; 1 for sum + self.assertEqual(len(sub_pass.rewritten), 1) + [record] = sub_pass.rewritten + self.assertEqual(record["reason"], "loop") + self.check_records(sub_pass.rewritten) + self.run_parallel(test_impl, *args) + + +class TestPreParforPass(BaseTest): + class sub_pass_class: + def __init__(self, pass_states): + pass + + def run(self, blocks): + pass + + def test_dtype_conversion(self): + # array.dtype are converted to np.dtype(array) in the PreParforPass + def test_impl(a): + b = np.ones(20, dtype=a.dtype) + return b + + arr = np.arange(10) + args = (arr,) + argtypes = [typeof(x) for x in args] + + pre_pass = self.run_parfor_pre_pass(test_impl, argtypes) + self.assertEqual(pre_pass.stats["replaced_func"], 0) + self.assertEqual(pre_pass.stats["replaced_dtype"], 1) + self.run_parallel(test_impl, *args) + + def test_sum_replacement(self): + def test_impl(a): + return np.sum(a) + + arr = np.arange(10) + args = (arr,) + argtypes = [typeof(x) for x in args] + + pre_pass = self.run_parfor_pre_pass(test_impl, argtypes) + self.assertEqual(pre_pass.stats["replaced_func"], 1) + self.assertEqual(pre_pass.stats["replaced_dtype"], 0) + self.run_parallel(test_impl, *args) + + def test_replacement_map(self): + def test_impl(a): + return np.sum(a) + + arr = np.arange(10) + args = (arr,) + argtypes = [typeof(x) for x in args] + + swap_map = numba.parfors.parfor.swap_functions_map.copy() + swap_map.pop(("sum", "numpy")) + pre_pass = self.run_parfor_pre_pass(test_impl, argtypes, swap_map) + self.assertEqual(pre_pass.stats["replaced_func"], 0) + self.assertEqual(pre_pass.stats["replaced_dtype"], 0) + self.run_parallel(test_impl, *args) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pipeline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..5a04da1bb69bc2c71c711452c4438a3337e2a779 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pipeline.py @@ -0,0 +1,143 @@ +from numba.core.compiler import Compiler, DefaultPassBuilder +from numba.core.compiler_machinery import (FunctionPass, AnalysisPass, + register_pass) +from numba.core.untyped_passes import InlineInlinables +from numba.core.typed_passes import IRLegalization +from numba import jit, objmode, njit, cfunc +from numba.core import types, postproc, errors +from numba.core.ir import FunctionIR +from numba.tests.support import TestCase + + +class TestCustomPipeline(TestCase): + def setUp(self): + super(TestCustomPipeline, self).setUp() + + # Define custom pipeline class + class CustomPipeline(Compiler): + custom_pipeline_cache = [] + + def compile_extra(self, func): + # Store the compiled function + self.custom_pipeline_cache.append(func) + return super(CustomPipeline, self).compile_extra(func) + + def compile_ir(self, func_ir, *args, **kwargs): + # Store the compiled function + self.custom_pipeline_cache.append(func_ir) + return super(CustomPipeline, self).compile_ir( + func_ir, *args, **kwargs) + + self.pipeline_class = CustomPipeline + + def test_jit_custom_pipeline(self): + self.assertListEqual(self.pipeline_class.custom_pipeline_cache, []) + + @jit(pipeline_class=self.pipeline_class) + def foo(x): + return x + + self.assertEqual(foo(4), 4) + self.assertListEqual(self.pipeline_class.custom_pipeline_cache, + [foo.py_func]) + + def test_cfunc_custom_pipeline(self): + self.assertListEqual(self.pipeline_class.custom_pipeline_cache, []) + + @cfunc(types.int64(types.int64), pipeline_class=self.pipeline_class) + def foo(x): + return x + + self.assertEqual(foo(4), 4) + self.assertListEqual(self.pipeline_class.custom_pipeline_cache, + [foo.__wrapped__]) + + def test_objmode_custom_pipeline(self): + self.assertListEqual(self.pipeline_class.custom_pipeline_cache, []) + + @jit(pipeline_class=self.pipeline_class) + def foo(x): + with objmode(x="intp"): + x += int(0x1) + return x + + arg = 123 + self.assertEqual(foo(arg), arg + 1) + # Two items in the list. + self.assertEqual(len(self.pipeline_class.custom_pipeline_cache), 2) + # First item is the `foo` function + first = self.pipeline_class.custom_pipeline_cache[0] + self.assertIs(first, foo.py_func) + # Second item is a FunctionIR of the obj-lifted function + second = self.pipeline_class.custom_pipeline_cache[1] + self.assertIsInstance(second, FunctionIR) + + +class TestPassManagerFunctionality(TestCase): + + def _create_pipeline_w_del(self, base=None, inject_after=None): + """ + Creates a new compiler pipeline with the _InjectDelsPass injected after + the pass supplied in kwarg 'inject_after'. + """ + self.assertTrue(inject_after is not None) + self.assertTrue(base is not None) + + @register_pass(mutates_CFG=False, analysis_only=False) + class _InjectDelsPass(base): + """ + This pass injects ir.Del nodes into the IR + """ + _name = "inject_dels_%s" % str(base) + + def __init__(self): + base.__init__(self) + + def run_pass(self, state): + pp = postproc.PostProcessor(state.func_ir) + pp.run(emit_dels=True) + return True + + class TestCompiler(Compiler): + + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(_InjectDelsPass, inject_after) + pm.finalize() + return [pm] + + return TestCompiler + + def test_compiler_error_on_ir_del_from_functionpass(self): + new_compiler = self._create_pipeline_w_del(FunctionPass, + InlineInlinables) + + @njit(pipeline_class=new_compiler) + def foo(x): + return x + 1 + + with self.assertRaises(errors.CompilerError) as raises: + foo(10) + + errstr = str(raises.exception) + + self.assertIn("Illegal IR, del found at:", errstr) + self.assertIn("del x", errstr) + + def test_no_compiler_error_on_ir_del_after_legalization(self): + # Legalization should be the last FunctionPass to execute so it's fine + # for it to emit ir.Del nodes as no further FunctionPasses will run and + # therefore the checking routine in the PassManager won't execute. + # This test adds a new pass that is an AnalysisPass into the pipeline + # after legalisation, this pass will return with already existing dels + # in the IR but by virtue of it being an AnalysisPass the checking + # routine won't execute. + + new_compiler = self._create_pipeline_w_del(AnalysisPass, + IRLegalization) + + @njit(pipeline_class=new_compiler) + def foo(x): + return x + 1 + + self.assertTrue(foo(10), foo.py_func(10)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_practical_lowering_issues.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_practical_lowering_issues.py new file mode 100644 index 0000000000000000000000000000000000000000..a069591946a845e3456d4499ca94845025e165c8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_practical_lowering_issues.py @@ -0,0 +1,212 @@ +""" +Tests for practical lowering specific errors. +""" + +import numpy as np +from numba import njit +from numba.core import types, ir +from numba.core.compiler import CompilerBase, DefaultPassBuilder +from numba.core.typed_passes import NopythonTypeInference +from numba.core.compiler_machinery import register_pass, FunctionPass + +from numba.tests.support import MemoryLeakMixin, TestCase + + +def issue7507_lround(a): + """Dummy function used in test""" + pass + + +class TestLowering(MemoryLeakMixin, TestCase): + def test_issue4156_loop_vars_leak(self): + """Test issues with zero-filling of refct'ed variables inside loops. + + Before the fix, the in-loop variables are always zero-filled at their + definition location. As a result, their state from the previous + iteration is erased. No decref is applied. To fix this, the + zero-filling must only happen once after the alloca at the function + entry block. The loop variables are technically defined once per + function (one alloca per definition per function), but semantically + defined once per assignment. Semantically, their lifetime stop only + when the variable is re-assigned or when the function ends. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for n in range(N): + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant1(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding an outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for x in range(N): + for y in range(N): + n = x + y + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant2(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding deeper outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + for y in range(N): + n = x + y + z + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant3(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding inner loop around allocation + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + n = x + z + if n >= 0: + for y in range(N): + # `vec` would leak without the fix. + vec = np.ones(y) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant4(self): + """Variant of test_issue4156_loop_vars_leak. + + Interleaves loops and allocations + """ + @njit + def udt(N): + sum_vec = 0 + + for n in range(N): + vec = np.zeros(7) + for n in range(N): + z = np.zeros(7) + sum_vec += vec[0] + z[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue_with_literal_in_static_getitem(self): + """Test an issue with literal type used as index of static_getitem + """ + + @register_pass(mutates_CFG=False, analysis_only=False) + class ForceStaticGetitemLiteral(FunctionPass): + + _name = "force_static_getitem_literal" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + repl = {} + # Force the static_getitem to have a literal type as + # index to replicate the problem. + for inst, sig in state.calltypes.items(): + if (isinstance(inst, ir.Expr) and + inst.op == 'static_getitem'): + [obj, idx] = sig.args + new_sig = sig.replace(args=(obj, + types.literal(inst.index))) + repl[inst] = new_sig + state.calltypes.update(repl) + return True + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(ForceStaticGetitemLiteral, + NopythonTypeInference) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomPipeline) + def foo(arr): + return arr[4] # force static_getitem + + arr = np.arange(10) + got = foo(arr) + expect = foo.py_func(arr) + self.assertEqual(got, expect) + + def test_issue7507(self): + """ + Test a problem with BaseContext.get_function() because of changes + related to the new style error handling. + """ + from numba.core.typing.templates import AbstractTemplate, infer_global + from numba.core.imputils import lower_builtin + + @infer_global(issue7507_lround) + class lroundTemplate(AbstractTemplate): + key = issue7507_lround + + def generic(self, args, kws): + signature = types.int64(types.float64) + + # insert a new builtin during the compilation process + @lower_builtin(issue7507_lround, types.float64) + def codegen(context, builder, sig, args): + # Simply truncate with the cast to integer. + return context.cast(builder, args[0], sig.args[0], + sig.return_type) + + return signature + + @njit('int64(float64)') + def foo(a): + return issue7507_lround(a) + + self.assertEqual(foo(3.4), 3) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pycc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pycc.py new file mode 100644 index 0000000000000000000000000000000000000000..2ee13d3c2357c4ec99fff7bf0ef23434e695a78f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pycc.py @@ -0,0 +1,405 @@ +import contextlib +import importlib +import os +import shutil +import subprocess +import sys +import tempfile +from unittest import skip +from ctypes import * + +import numpy as np + +import llvmlite.binding as ll + +from numba.core import utils +from numba.tests.support import (TestCase, tag, import_dynamic, temp_directory, + has_blas, needs_setuptools, skip_if_py313plus_on_windows, + skip_if_linux_aarch64, skip_if_freethreading) + +import unittest + + +_skip_reason = 'windows only' +_windows_only = unittest.skipIf(not sys.platform.startswith('win'), + _skip_reason) + + +base_path = os.path.dirname(os.path.abspath(__file__)) + + +def unset_macosx_deployment_target(): + """Unset MACOSX_DEPLOYMENT_TARGET because we are not building portable + libraries + """ + if 'MACOSX_DEPLOYMENT_TARGET' in os.environ: + del os.environ['MACOSX_DEPLOYMENT_TARGET'] + + +@needs_setuptools +@skip_if_freethreading +class TestCompilerChecks(TestCase): + + # NOTE: THIS TEST MUST ALWAYS RUN ON WINDOWS, DO NOT SKIP + @_windows_only + def test_windows_compiler_validity(self): + # When inside conda-build VSINSTALLDIR should be set and windows should + # have a valid compiler available, `external_compiler_works()` should + # agree with this. If this is not the case then error out to alert devs. + + # This is a local import to avoid deprecation warnings being generated + # through the use of the numba.pycc module. + from numba.pycc.platform import external_compiler_works + is_running_conda_build = os.environ.get('CONDA_BUILD', None) is not None + if is_running_conda_build: + if os.environ.get('VSINSTALLDIR', None) is not None: + self.assertTrue(external_compiler_works()) + + +@skip_if_freethreading +class BasePYCCTest(TestCase): + + def setUp(self): + unset_macosx_deployment_target() + + self.tmpdir = temp_directory('test_pycc') + # Make sure temporary files and directories created by + # distutils don't clutter the top-level /tmp + tempfile.tempdir = self.tmpdir + + def tearDown(self): + tempfile.tempdir = None + # Since we're executing the module-under-test several times + # from the same process, we must clear the exports registry + # between invocations. + + # This is a local import to avoid deprecation warnings being generated + # through the use of the numba.pycc module. + from numba.pycc.decorators import clear_export_registry + clear_export_registry() + + @contextlib.contextmanager + def check_c_ext(self, extdir, name): + sys.path.append(extdir) + try: + lib = import_dynamic(name) + yield lib + finally: + sys.path.remove(extdir) + sys.modules.pop(name, None) + + +@needs_setuptools +@skip_if_py313plus_on_windows +@skip_if_linux_aarch64 +class TestCC(BasePYCCTest): + + def setUp(self): + super(TestCC, self).setUp() + self.skip_if_no_external_compiler() # external compiler needed + from numba.tests import compile_with_pycc + self._test_module = compile_with_pycc + importlib.reload(self._test_module) + + @contextlib.contextmanager + def check_cc_compiled(self, cc): + #cc.verbose = True + cc.output_dir = self.tmpdir + cc.compile() + + with self.check_c_ext(self.tmpdir, cc.name) as lib: + yield lib + + def check_cc_compiled_in_subprocess(self, lib, code): + prolog = """if 1: + import sys + import types + # to disable numba package + sys.modules['numba'] = types.ModuleType('numba') + try: + from numba import njit + except ImportError: + pass + else: + raise RuntimeError('cannot disable numba package') + + sys.path.insert(0, %(path)r) + import %(name)s as lib + """ % {'name': lib.__name__, + 'path': os.path.dirname(lib.__file__)} + code = prolog.strip(' ') + code + subprocess.check_call([sys.executable, '-c', code]) + + def test_cc_properties(self): + cc = self._test_module.cc + self.assertEqual(cc.name, 'pycc_test_simple') + + # Inferred output directory + d = self._test_module.cc.output_dir + self.assertTrue(os.path.isdir(d), d) + + # Inferred output filename + f = self._test_module.cc.output_file + self.assertFalse(os.path.exists(f), f) + self.assertTrue(os.path.basename(f).startswith('pycc_test_simple.'), f) + if sys.platform.startswith('linux'): + self.assertTrue(f.endswith('.so'), f) + # This is a local import to avoid deprecation warnings being + # generated through the use of the numba.pycc module. + from numba.pycc.platform import find_pyext_ending + self.assertIn(find_pyext_ending(), f) + + def test_compile(self): + with self.check_cc_compiled(self._test_module.cc) as lib: + res = lib.multi(123, 321) + self.assertPreciseEqual(res, 123 * 321) + res = lib.multf(987, 321) + self.assertPreciseEqual(res, 987.0 * 321.0) + res = lib.square(5) + self.assertPreciseEqual(res, 25) + self.assertIs(lib.get_none(), None) + with self.assertRaises(ZeroDivisionError): + lib.div(1, 0) + + def check_compile_for_cpu(self, cpu_name): + cc = self._test_module.cc + cc.target_cpu = cpu_name + + with self.check_cc_compiled(cc) as lib: + res = lib.multi(123, 321) + self.assertPreciseEqual(res, 123 * 321) + self.assertEqual(lib.multi.__module__, 'pycc_test_simple') + + def test_compile_for_cpu(self): + # Compiling for the host CPU should always succeed + self.check_compile_for_cpu(ll.get_host_cpu_name()) + + def test_compile_for_cpu_host(self): + # Compiling for the host CPU should always succeed + self.check_compile_for_cpu("host") + + def test_compile_helperlib(self): + with self.check_cc_compiled(self._test_module.cc_helperlib) as lib: + res = lib.power(2, 7) + self.assertPreciseEqual(res, 128) + for val in (-1, -1 + 0j, np.complex128(-1)): + res = lib.sqrt(val) + self.assertPreciseEqual(res, 1j) + for val in (4, 4.0, np.float64(4)): + res = lib.np_sqrt(val) + self.assertPreciseEqual(res, 2.0) + res = lib.spacing(1.0) + self.assertPreciseEqual(res, 2**-52) + # Implicit seeding at startup should guarantee a non-pathological + # start state. + self.assertNotEqual(lib.random(-1), lib.random(-1)) + res = lib.random(42) + expected = np.random.RandomState(42).random_sample() + self.assertPreciseEqual(res, expected) + res = lib.size(np.float64([0] * 3)) + self.assertPreciseEqual(res, 3) + + code = """if 1: + from numpy.testing import assert_equal, assert_allclose + res = lib.power(2, 7) + assert res == 128 + res = lib.random(42) + assert_allclose(res, %(expected)s) + res = lib.spacing(1.0) + assert_allclose(res, 2**-52) + """ % {'expected': expected} + self.check_cc_compiled_in_subprocess(lib, code) + + def test_compile_nrt(self): + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + # Sanity check + self.assertPreciseEqual(lib.zero_scalar(1), 0.0) + res = lib.zeros(3) + self.assertEqual(list(res), [0, 0, 0]) + if has_blas: + res = lib.vector_dot(4) + self.assertPreciseEqual(res, 30.0) + # test argsort + val = np.float64([2., 5., 1., 3., 4.]) + res = lib.np_argsort(val) + expected = np.argsort(val) + self.assertPreciseEqual(res, expected) + + code = """if 1: + from numpy.testing import assert_equal + from numpy import float64, argsort + res = lib.zero_scalar(1) + assert res == 0.0 + res = lib.zeros(3) + assert list(res) == [0, 0, 0] + if %(has_blas)s: + res = lib.vector_dot(4) + assert res == 30.0 + val = float64([2., 5., 1., 3., 4.]) + res = lib.np_argsort(val) + expected = argsort(val) + assert_equal(res, expected) + """ % dict(has_blas=has_blas) + self.check_cc_compiled_in_subprocess(lib, code) + + def test_hashing(self): + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + res = lib.hash_literal_str_A() + self.assertPreciseEqual(res, hash("A")) + res = lib.hash_str("A") + self.assertPreciseEqual(res, hash("A")) + + code = """if 1: + from numpy.testing import assert_equal + res = lib.hash_literal_str_A() + assert_equal(res, hash("A")) + res = lib.hash_str("A") + assert_equal(res, hash("A")) + """ + self.check_cc_compiled_in_subprocess(lib, code) + + def test_c_extension_usecase(self): + # Test C-extensions + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + arr = np.arange(128, dtype=np.intp) + got = lib.dict_usecase(arr) + expect = arr * arr + self.assertPreciseEqual(got, expect) + + def test_dynamic_exc(self): + """See https://github.com/numba/numba/issues/9948 + + Dynamic exception uses a symbol that in PYCC compilation must become + linkonce_odr linkage to prevent symbol collision. + """ + with self.check_cc_compiled(self._test_module.cc_dynexc) as lib: + # these cases do not raise + a = np.zeros((2, 2), dtype=np.float64) + b = np.ones((2, 2), dtype=np.float64) + lib.do_setitem1(a, b) + self.assertPreciseEqual(a, b) + + a = np.zeros((2, 2), dtype=np.float64) + lib.do_setitem2(a, b) + self.assertPreciseEqual(a, b) + + # these cases will raise a dynamic exc + a = np.zeros((2, 2), dtype=np.float64) + b = np.ones((2, 3), dtype=np.float64) + with self.assertRaises(ValueError) as raises: + lib.do_setitem1(a, b) + + self.assertIn( + f"cannot assign slice of shape {b.shape} from " + f"input of shape {a.shape}", + str(raises.exception)) + + a = np.zeros((4, 6), dtype=np.float64) + b = np.ones((4, 5), dtype=np.float64) + with self.assertRaises(ValueError) as raises: + lib.do_setitem2(a, b) + + self.assertIn( + f"cannot assign slice of shape {b.shape} from " + f"input of shape {a.shape}", + str(raises.exception)) + + +@needs_setuptools +@skip_if_py313plus_on_windows +@skip_if_linux_aarch64 +@skip_if_freethreading +class TestDistutilsSupport(TestCase): + + def setUp(self): + super().setUp() + self.skip_if_no_external_compiler() # external compiler needed + + unset_macosx_deployment_target() + + # Copy the test project into a temp directory to avoid + # keeping any build leftovers in the source tree + self.tmpdir = temp_directory('test_pycc_distutils') + source_dir = os.path.join(base_path, 'pycc_distutils_usecase') + self.usecase_dir = os.path.join(self.tmpdir, 'work') + shutil.copytree(source_dir, self.usecase_dir) + + def check_setup_py(self, setup_py_file): + # Compute PYTHONPATH to ensure the child processes see this Numba + import numba + numba_path = os.path.abspath(os.path.dirname( + os.path.dirname(numba.__file__))) + env = dict(os.environ) + if env.get('PYTHONPATH', ''): + env['PYTHONPATH'] = numba_path + os.pathsep + env['PYTHONPATH'] + else: + env['PYTHONPATH'] = numba_path + + def run_python(args): + p = subprocess.Popen([sys.executable] + args, + cwd=self.usecase_dir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + out, _ = p.communicate() + rc = p.wait() + if rc != 0: + self.fail("python failed with the following output:\n%s" + % out.decode('utf-8', 'ignore')) + + run_python([setup_py_file, "build_ext", "--inplace"]) + code = """if 1: + import pycc_compiled_module as lib + assert lib.get_const() == 42 + res = lib.ones(3) + assert list(res) == [1.0, 1.0, 1.0] + """ + run_python(["-c", code]) + + def check_setup_nested_py(self, setup_py_file): + # Compute PYTHONPATH to ensure the child processes see this Numba + import numba + numba_path = os.path.abspath(os.path.dirname( + os.path.dirname(numba.__file__))) + env = dict(os.environ) + if env.get('PYTHONPATH', ''): + env['PYTHONPATH'] = numba_path + os.pathsep + env['PYTHONPATH'] + else: + env['PYTHONPATH'] = numba_path + + def run_python(args): + p = subprocess.Popen([sys.executable] + args, + cwd=self.usecase_dir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + out, _ = p.communicate() + rc = p.wait() + if rc != 0: + self.fail("python failed with the following output:\n%s" + % out.decode('utf-8', 'ignore')) + + run_python([setup_py_file, "build_ext", "--inplace"]) + code = """if 1: + import nested.pycc_compiled_module as lib + assert lib.get_const() == 42 + res = lib.ones(3) + assert list(res) == [1.0, 1.0, 1.0] + """ + run_python(["-c", code]) + + def test_setup_py_distutils(self): + self.check_setup_py("setup_distutils.py") + + def test_setup_py_distutils_nested(self): + self.check_setup_nested_py("setup_distutils_nested.py") + + def test_setup_py_setuptools(self): + self.check_setup_py("setup_setuptools.py") + + def test_setup_py_setuptools_nested(self): + self.check_setup_nested_py("setup_setuptools_nested.py") + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_python_int.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_python_int.py new file mode 100644 index 0000000000000000000000000000000000000000..19405ca7f3ae46390e6b364187c679f3d24e6a14 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_python_int.py @@ -0,0 +1,51 @@ +import unittest +from numba import jit +from numba.core import types + + +force_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def return_int(a, b): + return a + b + + +class TestPythonInt(unittest.TestCase): + + # Issue #474: ints should be returned rather than longs under Python 2, + # as much as possible. + + def test_int_return_type(self, flags=force_pyobj_flags, + int_type=types.int64, operands=(3, 4)): + pyfunc = return_int + cfunc = jit((int_type, int_type), **flags)(pyfunc) + expected = pyfunc(*operands) + got = cfunc(*operands) + self.assertIs(type(got), type(expected)) + self.assertEqual(got, expected) + + def test_int_return_type_npm(self): + self.test_int_return_type(flags=no_pyobj_flags) + + def test_unsigned_int_return_type(self, flags=force_pyobj_flags): + self.test_int_return_type(int_type=types.uint64, flags=flags) + + def test_unsigned_int_return_type_npm(self): + self.test_unsigned_int_return_type(flags=no_pyobj_flags) + + def test_long_int_return_type(self, flags=force_pyobj_flags): + # Same but returning a 64-bit integer. The return type should be + # `int` on 64-bit builds, `long` on 32-bit ones (or Windows). + self.test_int_return_type(flags=flags, operands=(2**33, 2**40)) + + def test_long_int_return_type_npm(self): + self.test_long_int_return_type(flags=no_pyobj_flags) + + def test_longer_int_return_type(self, flags=force_pyobj_flags): + # This won't be supported in nopython mode. + self.test_int_return_type(flags=flags, operands=(2**70, 2**75)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pythonapi.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pythonapi.py new file mode 100644 index 0000000000000000000000000000000000000000..297b6e3394473edf896dcb427ebf2c494fc772f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_pythonapi.py @@ -0,0 +1,123 @@ +import ctypes +import unittest +from numba.core import types +from numba.core.extending import intrinsic +from numba import jit, njit +from numba.tests.support import captured_stdout + + +@intrinsic +def _pyapi_bytes_as_string(typingctx, csrc, size): + sig = types.voidptr(csrc, size) # cstring == void* + + def codegen(context, builder, sig, args): + [csrc, size] = args + api = context.get_python_api(builder) + b = api.bytes_from_string_and_size(csrc, size) + return api.bytes_as_string(b) + return sig, codegen + + +def PyBytes_AsString(uni): + # test_PyBytes_AsString will call this function with a unicode type. + # We then use the underlying buffer to create a PyBytes object and call the + # PyBytes_AsString function with PyBytes object as argument + return _pyapi_bytes_as_string(uni._data, uni._length) + + +@intrinsic +def _pyapi_bytes_as_string_and_size(typingctx, csrc, size): + # return a tuple containing the c-string and size + retty = types.Tuple.from_types((csrc, size)) + sig = retty(csrc, size) + + def codegen(context, builder, sig, args): + [csrc, size] = args + pyapi = context.get_python_api(builder) + b = pyapi.bytes_from_string_and_size(csrc, size) + p_cstr = builder.alloca(pyapi.cstring) + p_size = builder.alloca(pyapi.py_ssize_t) + pyapi.bytes_as_string_and_size(b, p_cstr, p_size) + + cstr = builder.load(p_cstr) + size = builder.load(p_size) + tup = context.make_tuple(builder, sig.return_type, (cstr, size)) + return tup + return sig, codegen + + +def PyBytes_AsStringAndSize(uni): + return _pyapi_bytes_as_string_and_size(uni._data, uni._length) + + +class TestPythonAPI(unittest.TestCase): + + def test_PyBytes_AsString(self): + cfunc = jit(nopython=True)(PyBytes_AsString) + cstr = cfunc('hello') # returns a cstring + + fn = ctypes.pythonapi.PyBytes_FromString + fn.argtypes = [ctypes.c_void_p] + fn.restype = ctypes.py_object + obj = fn(cstr) + + # Use the cstring created from bytes_as_string to create a python + # bytes object + self.assertEqual(obj, b'hello') + + def test_PyBytes_AsStringAndSize(self): + cfunc = jit(nopython=True)(PyBytes_AsStringAndSize) + tup = cfunc('hello\x00world') # returns a tuple: cstring and its size + + fn = ctypes.pythonapi.PyBytes_FromStringAndSize + fn.argtypes = [ctypes.c_void_p, ctypes.c_size_t] + fn.restype = ctypes.py_object + obj = fn(tup[0], tup[1]) + + # Use the cstring created from bytes_from_string_and_size to create + # a python bytes object + self.assertEqual(obj, b'hello\x00world') + + +class PythonAPIEmptyArgs(unittest.TestCase): + def test_empty_args(self): + def callme(**kwargs): + print("callme", kwargs) + + @intrinsic + def py_call(tyctx): + def codegen(context, builder, sig, args): + pyapi = context.get_python_api(builder) + gil = pyapi.gil_ensure() + + num = pyapi.long_from_longlong( + context.get_constant(types.intp, 0xCAFE) + ) + kwds = pyapi.dict_pack({"key": num}.items()) + fn_print = pyapi.unserialize(pyapi.serialize_object(callme)) + # segfault: https://github.com/numba/numba/issues/5871 + res = pyapi.call(fn_print, None, kwds) + + pyapi.decref(res) + pyapi.decref(fn_print) + pyapi.decref(kwds) + pyapi.decref(num) + + pyapi.gil_release(gil) + return res + + return types.none(), codegen + + @njit + def foo(): + py_call() + + with captured_stdout() as out: + foo() + d = {"key": 0xCAFE} + expected = f"callme {d}\n" + self.assertEqual(out.getvalue(), expected) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_recarray_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_recarray_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..06464b470f3ee56dd6435b9218cc4ae63c596fa4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_recarray_usecases.py @@ -0,0 +1,146 @@ +import sys +import unittest + +import numpy as np + +from numba import njit +from numba.core import types +from numba.tests.support import captured_stdout, TestCase +from numba.np import numpy_support + + +def usecase1(arr1, arr2): + """Base on https://github.com/numba/numba/issues/370 + + Modified to add test-able side effect. + """ + n1 = arr1.size + n2 = arr2.size + + for i1 in range(n1): + st1 = arr1[i1] + for i2 in range(n2): + st2 = arr2[i2] + st2.row += st1.p * st2.p + st1.row - st1.col + + st1.p += st2.p + st1.col -= st2.col + + +def usecase2(x, N): + """ + Base on test1 of https://github.com/numba/numba/issues/381 + """ + for k in range(N): + y = x[k] + print(y.f1, y.s1, y.f2) + + +def usecase3(x, N): + """ + Base on test2 of https://github.com/numba/numba/issues/381 + """ + for k in range(N): + print(x.f1[k], x.s1[k], x.f2[k]) + + +def usecase4(x, N): + """ + Base on test3 of https://github.com/numba/numba/issues/381 + """ + for k in range(N): + y = x[k] + print(y.f1, x.s1[k], y.f2) + + +def usecase5(x, N): + """ + Base on test4 of https://github.com/numba/numba/issues/381 + """ + for k in range(N): + print(x[k].f1, x.s1[k], x[k].f2) + + +class TestRecordUsecase(TestCase): + + def setUp(self): + fields = [('f1', '0 (True). + + Note: The exact statistic varies across platform. + + NOTE: Tests using this `check` method need to run in subprocesses as + `njit` sets up the module pass manager etc once and the overrides have + no effect else. + """ + + with override_config('LLVM_REFPRUNE_PASS', '1'): + cres = njit((*argtys,))(func).overloads[(*argtys,)] + + pstats = cres.metadata.get('prune_stats', None) + self.assertIsNotNone(pstats) + + for k, v in prune_types.items(): + stat = getattr(pstats, k, None) + self.assertIsNotNone(stat) + msg = f'failed checking {k}' + if v: + if k == 'fanout_raise': + self.assertGreaterEqual(stat, 0, msg=msg) + else: + self.assertGreater(stat, 0, msg=msg) + else: + self.assertEqual(stat, 0, msg=msg) + + @TestCase.run_test_in_subprocess + def test_basic_block_1(self): + # some nominally involved control flow and ops, there's only basic_block + # opportunities present here. + def func(n): + a = np.zeros(n) + acc = 0 + if n > 4: + b = a[1:] + acc += b[1] + else: + c = a[:-1] + acc += c[0] + return acc + + self.check(func, (types.intp), basicblock=True) + + @TestCase.run_test_in_subprocess + def test_diamond_1(self): + # most basic?! diamond + def func(n): + a = np.ones(n) + x = 0 + if n > 2: + x = a.sum() + return x + 1 + + # disable fanout pruning + with set_refprune_flags('per_bb,diamond'): + self.check(func, (types.intp), basicblock=True, diamond=True, + fanout=False, fanout_raise=False) + + @TestCase.run_test_in_subprocess + def test_diamond_2(self): + # more complex diamonds + def func(n): + con = [] + for i in range(n): + con.append(np.arange(i)) + c = 0.0 + for arr in con: + c += arr.sum() / (1 + arr.size) + return c + + # disable fanout pruning + with set_refprune_flags('per_bb,diamond'): + self.check(func, (types.intp), basicblock=True, diamond=True, + fanout=False, fanout_raise=False) + + @TestCase.run_test_in_subprocess + def test_fanout_1(self): + # most basic?! fan-out + def func(n): + a = np.zeros(n) + b = np.zeros(n) + x = (a, b) + acc = 0. + for i in x: + acc += i[0] + return acc + + self.check(func, (types.intp), basicblock=True, fanout=True) + + @TestCase.run_test_in_subprocess + def test_fanout_2(self): + # fanout with raise + def func(n): + a = np.zeros(n) + b = np.zeros(n) + x = (a, b) + for i in x: + if n: + raise ValueError + return x + + with set_refprune_flags('per_bb,fanout'): + self.check(func, (types.intp), basicblock=True, diamond=False, + fanout=True, fanout_raise=False) + + @TestCase.run_test_in_subprocess + def test_fanout_3(self): + # fanout with raise + def func(n): + ary = np.arange(n) + # basically an impl of array.sum + c = 0 + # The raise is from StopIteration of next(iterator) implicit in + # the for loop + for v in np.nditer(ary): + c += v.item() + return 1 + + with set_refprune_flags('per_bb,fanout_raise'): + self.check(func, (types.intp), basicblock=True, diamond=False, + fanout=False, fanout_raise=True) + + +class TestRefPruneFlags(TestCase): + def setUp(self): + warnings.simplefilter('error', NumbaInvalidConfigWarning) + + def tearDown(self): + warnings.resetwarnings() + + def test_warn_invalid_flags(self): + with set_refprune_flags('abc,per_bb,cde'): + with self.assertWarns(NumbaInvalidConfigWarning) as cm: + optval = _parse_refprune_flags() + self.assertEqual(len(cm.warnings), 2) + self.assertIn('abc', str(cm.warnings[0].message)) + self.assertIn('cde', str(cm.warnings[1].message)) + self.assertEqual(optval, llvm.RefPruneSubpasses.PER_BB) + + def test_valid_flag(self): + with set_refprune_flags('per_bb, diamond, fanout,fanout_raise'): + optval = _parse_refprune_flags() + self.assertEqual(optval, llvm.RefPruneSubpasses.ALL) + + def test_the_all_flag(self): + with set_refprune_flags('all'): + optval = _parse_refprune_flags() + self.assertEqual(optval, llvm.RefPruneSubpasses.ALL) + + def test_some_flags(self): + with set_refprune_flags('per_bb, fanout'): + optval = _parse_refprune_flags() + enumcls = llvm.RefPruneSubpasses + self.assertEqual(optval, enumcls.PER_BB | enumcls.FANOUT) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_return_values.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_return_values.py new file mode 100644 index 0000000000000000000000000000000000000000..b3496d28311319bd5327c65d5dc4067392830e6a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_return_values.py @@ -0,0 +1,74 @@ +""" +Test return values +""" + + +import math + +import unittest +from numba import jit +from numba.core import types +from numba.core.errors import TypingError, NumbaTypeError + + +enable_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def get_nopython_func(): + return abs + +def get_pyobj_func(): + return open + +def get_module_func(): + return math.floor + + +class TestReturnValues(unittest.TestCase): + + def test_nopython_func(self, flags=enable_pyobj_flags): + # Test returning func that is supported in nopython mode + pyfunc = get_nopython_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, abs) + else: + self.fail("Unexpected successful compilation.") + + def test_nopython_func_npm(self): + with self.assertRaises(NumbaTypeError): + self.test_nopython_func(flags=no_pyobj_flags) + + def test_pyobj_func(self, flags=enable_pyobj_flags): + # Test returning func that is only supported in object mode + pyfunc = get_pyobj_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, open) + else: + self.fail("Unexpected successful compilation.") + + def test_pyobj_func_npm(self): + with self.assertRaises(TypingError): + self.test_pyobj_func(flags=no_pyobj_flags) + + def test_module_func(self, flags=enable_pyobj_flags): + # Test returning imported func that is only supported in object mode + pyfunc = get_module_func + cfunc = jit((), **flags)(pyfunc) + if flags == enable_pyobj_flags: + result = cfunc() + self.assertEqual(result, math.floor) + else: + self.fail("Unexpected successful compilation.") + + def test_module_func_npm(self): + with self.assertRaises(NumbaTypeError): + self.test_module_func(flags=no_pyobj_flags) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_runtests.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..099582c3c4d67786a3af2a9863c6db29c7c47428 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_runtests.py @@ -0,0 +1,284 @@ +import os +import sys +import subprocess + +from numba import cuda +import unittest +import itertools + +try: + import git # noqa: F401 from gitpython package +except ImportError: + has_gitpython = False +else: + has_gitpython = True + +try: + import yaml # from pyyaml package +except ImportError: + has_pyyaml = False +else: + has_pyyaml = True + + +class TestCase(unittest.TestCase): + """These test cases are meant to test the Numba test infrastructure itself. + Therefore, the logic used here shouldn't use numba.testing, but only the + upstream unittest, and run the numba test suite only in a subprocess.""" + + def get_testsuite_listing(self, args, *, subp_kwargs=None): + """ + Use `subp_kwargs` to pass extra argument to `subprocess.check_output`. + """ + subp_kwargs = subp_kwargs or {} + cmd = [sys.executable, '-m', 'numba.runtests', '-l'] + list(args) + out_bytes = subprocess.check_output(cmd, **subp_kwargs) + lines = out_bytes.decode('UTF-8').splitlines() + lines = [line for line in lines if line.strip()] + return lines + + def check_listing_prefix(self, prefix): + listing = self.get_testsuite_listing([prefix]) + for ln in listing[:-1]: + errmsg = '{!r} not startswith {!r}'.format(ln, prefix) + self.assertTrue(ln.startswith(prefix), msg=errmsg) + + def check_testsuite_size(self, args, minsize): + """ + Check that the reported numbers of tests are at least *minsize*. + """ + lines = self.get_testsuite_listing(args) + last_line = lines[-1] + self.assertTrue('tests found' in last_line) + number = int(last_line.split(' ')[0]) + # There may be some "skipped" messages at the beginning, + # so do an approximate check. + self.assertIn(len(lines), range(number + 1, number + 20)) + self.assertGreaterEqual(number, minsize) + return lines + + def check_all(self, ids): + lines = self.check_testsuite_size(ids, 5000) + # CUDA should be included by default + self.assertTrue(any('numba.cuda.tests.' in line for line in lines)) + # As well as subpackage + self.assertTrue(any('numba.tests.npyufunc.test_' in line + for line in lines),) + + def _get_numba_tests_from_listing(self, listing): + """returns a filter on strings starting with 'numba.', useful for + selecting the 'numba' test names from a test listing.""" + return filter(lambda x: x.startswith('numba.'), listing) + + def test_default(self): + self.check_all([]) + + def test_all(self): + self.check_all(['numba.tests']) + + def test_cuda(self): + # Even without CUDA enabled, there is at least one test + # (in numba.cuda.tests.nocuda) + minsize = 100 if cuda.is_available() else 1 + self.check_testsuite_size(['numba.cuda.tests'], minsize) + + @unittest.skipIf(not cuda.is_available(), "NO CUDA") + def test_cuda_submodules(self): + self.check_listing_prefix('numba.cuda.tests.cudadrv') + self.check_listing_prefix('numba.cuda.tests.cudapy') + self.check_listing_prefix('numba.cuda.tests.nocuda') + self.check_listing_prefix('numba.cuda.tests.cudasim') + + def test_module(self): + self.check_testsuite_size(['numba.tests.test_storeslice'], 2) + self.check_testsuite_size(['numba.tests.test_nested_calls'], 10) + # Several modules + self.check_testsuite_size(['numba.tests.test_nested_calls', + 'numba.tests.test_storeslice'], 12) + + def test_subpackage(self): + self.check_testsuite_size(['numba.tests.npyufunc'], 50) + + def test_random(self): + self.check_testsuite_size( + ['--random', '0.1', 'numba.tests.npyufunc'], 5) + + def test_include_exclude_tags(self): + def get_count(arg_list): + lines = self.get_testsuite_listing(arg_list) + self.assertIn('tests found', lines[-1]) + count = int(lines[-1].split()[0]) + self.assertTrue(count > 0) + return count + + tags = ['long_running', 'long_running, important'] + + total = get_count(['numba.tests']) + + for tag in tags: + included = get_count(['--tags', tag, 'numba.tests']) + excluded = get_count(['--exclude-tags', tag, 'numba.tests']) + self.assertEqual(total, included + excluded) + + # check syntax with `=` sign in + included = get_count(['--tags=%s' % tag, 'numba.tests']) + excluded = get_count(['--exclude-tags=%s' % tag, 'numba.tests']) + self.assertEqual(total, included + excluded) + + def test_check_shard(self): + tmpAll = self.get_testsuite_listing([]) + tmp1 = self.get_testsuite_listing(['-j', '0:2']) + tmp2 = self.get_testsuite_listing(['-j', '1:2']) + + lAll = set(self._get_numba_tests_from_listing(tmpAll)) + l1 = set(self._get_numba_tests_from_listing(tmp1)) + l2 = set(self._get_numba_tests_from_listing(tmp2)) + + # The difference between two adjacent shards should be less than 5% of + # the total + self.assertLess(abs(len(l2) - len(l1)), len(lAll) / 20) + self.assertLess(len(l1), len(lAll)) + self.assertLess(len(l2), len(lAll)) + + def test_check_sharding_equivalent(self): + # get some shards + sharded = list() + for i in range(3): + subset = self.get_testsuite_listing(['-j', '{}:3'.format(i)]) + slist = [*self._get_numba_tests_from_listing(subset)] + sharded.append(slist) + + # get the always running tests + tmp = self.get_testsuite_listing(['--tag', 'always_test']) + always_running = set(self._get_numba_tests_from_listing(tmp)) + + # make sure there is at least one test that always runs + self.assertGreaterEqual(len(always_running), 1) + + # check that each shard contains no repeats + sharded_sets = [set(x) for x in sharded] + for i in range(len(sharded)): + self.assertEqual(len(sharded_sets[i]), len(sharded[i])) + + # check that the always running tests are in every shard, and then + # remove them from the shards + for shard in sharded_sets: + for test in always_running: + self.assertIn(test, shard) + shard.remove(test) + self.assertNotIn(test, shard) + + # check that there is no overlap between the shards + for a, b in itertools.combinations(sharded_sets, 2): + self.assertFalse(a & b) + + # check that the sum of the shards and the always running tests is the + # same as the full listing + + sum_of_parts = set() + for x in sharded_sets: + sum_of_parts.update(x) + sum_of_parts.update(always_running) + + full_listing = set(self._get_numba_tests_from_listing( + self.get_testsuite_listing([]))) + + self.assertEqual(sum_of_parts, full_listing) + + @unittest.skipUnless(has_gitpython, "Requires gitpython") + def test_gitdiff(self): + # Check for git + try: + subprocess.call("git", + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + except FileNotFoundError: + self.skipTest("no git available") + + # default + outs = self.get_testsuite_listing(['-g']) + self.assertNotIn("Git diff by common ancestor", outs) + # using ancestor + outs = self.get_testsuite_listing(['-g=ancestor']) + self.assertIn("Git diff by common ancestor", outs) + # misspelled ancestor + subp_kwargs = dict(stderr=subprocess.DEVNULL) + with self.assertRaises(subprocess.CalledProcessError): + self.get_testsuite_listing(['-g=ancest'], subp_kwargs=subp_kwargs) + + @unittest.skipUnless(has_pyyaml, "Requires pyyaml") + def test_azure_config(self): + from yaml import Loader + base_path = os.path.dirname(os.path.abspath(__file__)) + azure_pipe = os.path.join(base_path, '..', '..', 'azure-pipelines.yml') + if not os.path.isfile(azure_pipe): + self.skipTest("'azure-pipelines.yml' is not available") + with open(os.path.abspath(azure_pipe), 'rt') as f: + data = f.read() + pipe_yml = yaml.load(data, Loader=Loader) + + templates = pipe_yml['jobs'] + # first look at the items in the first template, this is linux. + start_indexes = [] + tmplt = templates[0] + matrix = tmplt['parameters']['matrix'] + for setup in matrix.values(): + start_indexes.append(setup['TEST_START_INDEX']) + + # next look at the items in the windows only template + winpath = ['..', '..', 'buildscripts', 'azure', 'azure-windows.yml'] + azure_windows = os.path.join(base_path, *winpath) + if not os.path.isfile(azure_windows): + self.skipTest("'azure-windows.yml' is not available") + with open(os.path.abspath(azure_windows), 'rt') as f: + data = f.read() + windows_yml = yaml.load(data, Loader=Loader) + + # There's only one template in windows and its keyed differently to the + # above, get its matrix. + matrix = windows_yml['jobs'][0]['strategy']['matrix'] + for setup in matrix.values(): + start_indexes.append(setup['TEST_START_INDEX']) + + # sanity checks + # 1. That the TEST_START_INDEX is unique + self.assertEqual(len(start_indexes), len(set(start_indexes))) + # 2. That the TEST_START_INDEX is a complete range + lim_start_index = max(start_indexes) + 1 + expected = [*range(lim_start_index)] + self.assertEqual(sorted(start_indexes), expected) + # 3. That the number of indexes matches the declared test count + self.assertEqual(lim_start_index, pipe_yml['variables']['TEST_COUNT']) + + def test_no_compilation_on_list(self): + # Checks that the test suite doesn't do any CPU-side compilation on + # listing of tests. + code = """if 1: + from unittest import mock + from llvmlite import binding as llvm + error = RuntimeError("Detected compilation during test listing") + with mock.patch.object(llvm.ExecutionEngine, 'finalize_object', + side_effect=error): + import numba + {0} + """ + + # Run with a jit function in the test to demonstrate failure + with self.assertRaises(subprocess.CalledProcessError) as raises: + cmd = [sys.executable, "-c", code.format("numba.njit(lambda:0)()")] + subprocess.check_output(cmd, + stderr=subprocess.STDOUT, + timeout=60) + self.assertIn("Detected compilation during test listing", + raises.exception.stdout.decode('UTF-8')) + + # Run to validate the test suite does not trigger compilation during + # listing. + cmd = [sys.executable, "-c", code.format("numba.test('-l')")] + subprocess.check_call(cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL,) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ssa.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ssa.py new file mode 100644 index 0000000000000000000000000000000000000000..49e28c05f2aaa6e1aee6411bba6700784da4d01e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ssa.py @@ -0,0 +1,631 @@ +""" +Tests for SSA reconstruction +""" +import sys +import copy +import logging + +import numpy as np + +from numba import njit, jit, types +from numba.core import errors, ir +from numba.core.compiler_machinery import FunctionPass, register_pass +from numba.core.compiler import DefaultPassBuilder, CompilerBase +from numba.core.untyped_passes import ReconstructSSA, PreserveIR +from numba.core.typed_passes import NativeLowering +from numba.extending import overload +from numba.tests.support import MemoryLeakMixin, TestCase, override_config + + +_DEBUG = False + +if _DEBUG: + # Enable debug logger on SSA reconstruction + ssa_logger = logging.getLogger("numba.core.ssa") + ssa_logger.setLevel(level=logging.DEBUG) + ssa_logger.addHandler(logging.StreamHandler(sys.stderr)) + + +class SSABaseTest(TestCase): + + def check_func(self, func, *args): + got = func(*copy.deepcopy(args)) + exp = func.py_func(*copy.deepcopy(args)) + self.assertEqual(got, exp) + + +class TestSSA(SSABaseTest): + """ + Contains tests to help isolate problems in SSA + """ + + def test_argument_name_reused(self): + @njit + def foo(x): + x += 1 + return x + + self.check_func(foo, 123) + + def test_if_else_redefine(self): + @njit + def foo(x, y): + z = x * y + if x < y: + z = x + else: + z = y + return z + + self.check_func(foo, 3, 2) + self.check_func(foo, 2, 3) + + def test_sum_loop(self): + @njit + def foo(n): + c = 0 + for i in range(n): + c += i + return c + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def test_sum_loop_2vars(self): + @njit + def foo(n): + c = 0 + d = n + for i in range(n): + c += i + d += n + return c, d + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def test_sum_2d_loop(self): + @njit + def foo(n): + c = 0 + for i in range(n): + for j in range(n): + c += j + c += i + return c + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def check_undefined_var(self, should_warn): + @njit + def foo(n): + if n: + if n > 0: + c = 0 + return c + else: + # variable c is not defined in this branch + c += 1 + return c + + if should_warn: + with self.assertWarns(errors.NumbaWarning) as warns: + # n=1 so we won't actually run the branch with the uninitialized + self.check_func(foo, 1) + self.assertIn("Detected uninitialized variable c", + str(warns.warning)) + else: + self.check_func(foo, 1) + + with self.assertRaises(UnboundLocalError): + foo.py_func(0) + + def test_undefined_var(self): + with override_config('ALWAYS_WARN_UNINIT_VAR', 0): + self.check_undefined_var(should_warn=False) + with override_config('ALWAYS_WARN_UNINIT_VAR', 1): + self.check_undefined_var(should_warn=True) + + def test_phi_propagation(self): + @njit + def foo(actions): + n = 1 + + i = 0 + ct = 0 + while n > 0 and i < len(actions): + n -= 1 + + while actions[i]: + if actions[i]: + if actions[i]: + n += 10 + actions[i] -= 1 + else: + if actions[i]: + n += 20 + actions[i] += 1 + + ct += n + ct += n + return ct, n + + self.check_func(foo, np.array([1, 2])) + + def test_unhandled_undefined(self): + def function1(arg1, arg2, arg3, arg4, arg5): + # This function is auto-generated. + if arg1: + var1 = arg2 + var2 = arg3 + var3 = var2 + var4 = arg1 + return + else: + if arg2: + if arg4: + var5 = arg4 # noqa: F841 + return + else: + var6 = var4 + return + return var6 + else: + if arg5: + if var1: + if arg5: + var1 = var6 + return + else: + var7 = arg2 # noqa: F841 + return arg2 + return + else: + if var2: + arg5 = arg2 + return arg1 + else: + var6 = var3 + return var4 + return + return + else: + var8 = var1 + return + return var8 + var9 = var3 # noqa: F841 + var10 = arg5 # noqa: F841 + return var1 + + # The argument values is not critical for re-creating the bug + # because the bug is in compile-time. + expect = function1(2, 3, 6, 0, 7) + got = njit(function1)(2, 3, 6, 0, 7) + self.assertEqual(expect, got) + + +class TestReportedSSAIssues(SSABaseTest): + # Tests from issues + # https://github.com/numba/numba/issues?q=is%3Aopen+is%3Aissue+label%3ASSA + + def test_issue2194(self): + + @njit + def foo(): + V = np.empty(1) + s = np.uint32(1) + + for i in range(s): + V[i] = 1 + for i in range(s, 1): + pass + + self.check_func(foo, ) + + def test_issue3094(self): + + @njit + def doit(x): + return x + + @njit + def foo(pred): + if pred: + x = True + else: + x = False + # do something with x + return doit(x) + + self.check_func(foo, False) + + def test_issue3931(self): + + @njit + def foo(arr): + for i in range(1): + arr = arr.reshape(3 * 2) + arr = arr.reshape(3, 2) + return (arr) + + np.testing.assert_allclose(foo(np.zeros((3, 2))), + foo.py_func(np.zeros((3, 2)))) + + def test_issue3976(self): + + def overload_this(a): + return 'dummy' + + @njit + def foo(a): + if a: + s = 5 + s = overload_this(s) + else: + s = 'b' + + return s + + @overload(overload_this) + def ol(a): + return overload_this + + self.check_func(foo, True) + + def test_issue3979(self): + + @njit + def foo(A, B): + x = A[0] + y = B[0] + for i in A: + x = i + for i in B: + y = i + return x, y + + self.check_func(foo, (1, 2), ('A', 'B')) + + def test_issue5219(self): + + def overload_this(a, b=None): + if isinstance(b, tuple): + b = b[0] + return b + + @overload(overload_this) + def ol(a, b=None): + b_is_tuple = isinstance(b, (types.Tuple, types.UniTuple)) + + def impl(a, b=None): + if b_is_tuple is True: + b = b[0] + return b + return impl + + @njit + def test_tuple(a, b): + overload_this(a, b) + + self.check_func(test_tuple, 1, (2, )) + + def test_issue5223(self): + + @njit + def bar(x): + if len(x) == 5: + return x + x = x.copy() + for i in range(len(x)): + x[i] += 1 + return x + + a = np.ones(5) + a.flags.writeable = False + + np.testing.assert_allclose(bar(a), bar.py_func(a)) + + def test_issue5243(self): + + @njit + def foo(q): + lin = np.array((0.1, 0.6, 0.3)) + stencil = np.zeros((3, 3)) + stencil[0, 0] = q[0, 0] + return lin[0] + + self.check_func(foo, np.zeros((2, 2))) + + def test_issue5482_missing_variable_init(self): + # Test error that lowering fails because variable is missing + # a definition before use. + @njit("(intp, intp, intp)") + def foo(x, v, n): + for i in range(n): + if i == 0: + if i == x: + pass + else: + problematic = v + else: + if i == x: + pass + else: + problematic = problematic + v + return problematic + + def test_issue5482_objmode_expr_null_lowering(self): + # Existing pipelines will not have the Expr.null in objmode. + # We have to create a custom pipeline to force a SSA reconstruction + # and stripping. + from numba.core.compiler import CompilerBase, DefaultPassBuilder + from numba.core.untyped_passes import ReconstructSSA, IRProcessing + from numba.core.typed_passes import PreLowerStripPhis + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_objectmode_pipeline(self.state) + # Force SSA reconstruction and stripping + pm.add_pass_after(ReconstructSSA, IRProcessing) + pm.add_pass_after(PreLowerStripPhis, ReconstructSSA) + pm.finalize() + return [pm] + + @jit("(intp, intp, intp)", looplift=False, + pipeline_class=CustomPipeline) + def foo(x, v, n): + for i in range(n): + if i == n: + if i == x: + pass + else: + problematic = v + else: + if i == x: + pass + else: + problematic = problematic + v + return problematic + + def test_issue5493_unneeded_phi(self): + # Test error that unneeded phi is inserted because variable does not + # have a dominance definition. + data = (np.ones(2), np.ones(2)) + A = np.ones(1) + B = np.ones((1,1)) + + def foo(m, n, data): + if len(data) == 1: + v0 = data[0] + else: + v0 = data[0] + # Unneeded PHI node for `problematic` would be placed here + for _ in range(1, len(data)): + v0 += A + + for t in range(1, m): + for idx in range(n): + t = B + + if idx == 0: + if idx == n - 1: + pass + else: + problematic = t + else: + if idx == n - 1: + pass + else: + problematic = problematic + t + return problematic + + expect = foo(10, 10, data) + res1 = njit(foo)(10, 10, data) + res2 = jit(forceobj=True, looplift=False)(foo)(10, 10, data) + np.testing.assert_array_equal(expect, res1) + np.testing.assert_array_equal(expect, res2) + + def test_issue5623_equal_statements_in_same_bb(self): + + def foo(pred, stack): + i = 0 + c = 1 + + if pred is True: + stack[i] = c + i += 1 + stack[i] = c + i += 1 + + python = np.array([0, 666]) + foo(True, python) + + nb = np.array([0, 666]) + njit(foo)(True, nb) + + expect = np.array([1, 1]) + + np.testing.assert_array_equal(python, expect) + np.testing.assert_array_equal(nb, expect) + + def test_issue5678_non_minimal_phi(self): + # There should be only one phi for variable "i" + + from numba.core.compiler import CompilerBase, DefaultPassBuilder + from numba.core.untyped_passes import ( + ReconstructSSA, FunctionPass, register_pass, + ) + + phi_counter = [] + + @register_pass(mutates_CFG=False, analysis_only=True) + class CheckSSAMinimal(FunctionPass): + # A custom pass to count the number of phis + + _name = self.__class__.__qualname__ + ".CheckSSAMinimal" + + def __init__(self): + super().__init__(self) + + def run_pass(self, state): + ct = 0 + for blk in state.func_ir.blocks.values(): + ct += len(list(blk.find_exprs('phi'))) + phi_counter.append(ct) + return True + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(CheckSSAMinimal, ReconstructSSA) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomPipeline) + def while_for(n, max_iter=1): + a = np.empty((n,n)) + i = 0 + while i <= max_iter: + for j in range(len(a)): + for k in range(len(a)): + a[j,k] = j + k + i += 1 + return a + + # Runs fine? + self.assertPreciseEqual(while_for(10), while_for.py_func(10)) + # One phi? + self.assertEqual(phi_counter, [1]) + + def test_issue9242_use_not_dom_def(self): + from numba.core.ir import FunctionIR + from numba.core.compiler_machinery import ( + AnalysisPass, + register_pass, + ) + + def check(fir: FunctionIR): + [blk, *_] = fir.blocks.values() + var = blk.scope.get("d") + defn = fir.get_definition(var) + self.assertEqual(defn.op, "phi") + self.assertIn(ir.UNDEFINED, defn.incoming_values) + + @register_pass(mutates_CFG=False, analysis_only=True) + class SSACheck(AnalysisPass): + """ + Check SSA on variable `d` + """ + + _name = "SSA_Check" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + check(state.func_ir) + return False + + class SSACheckPipeline(CompilerBase): + """Inject SSACheck pass into the default pipeline following the SSA + pass + """ + + def define_pipelines(self): + pipeline = DefaultPassBuilder.define_nopython_pipeline( + self.state, "ssa_check_custom_pipeline") + + pipeline._finalized = False + pipeline.add_pass_after(SSACheck, ReconstructSSA) + + pipeline.finalize() + return [pipeline] + + @njit(pipeline_class=SSACheckPipeline) + def py_func(a): + c = a > 0 + if c: + d = a + 5 # d is only defined here; undef in the else branch + + return c and d > 0 + + py_func(10) + + +class TestSROAIssues(MemoryLeakMixin, TestCase): + # This tests issues related to the SROA optimization done in lowering, which + # reduces time spent in the LLVM SROA pass. The optimization is related to + # SSA and tries to reduce the number of alloca statements for variables with + # only a single assignment. + def test_issue7258_multiple_assignment_post_SSA(self): + # This test adds a pass that will duplicate assignment statements to + # variables named "foobar". + # In the reported issue, the bug will cause a memory leak. + cloned = [] + + @register_pass(analysis_only=False, mutates_CFG=True) + class CloneFoobarAssignments(FunctionPass): + # A pass that clones variable assignments into "foobar" + _name = "clone_foobar_assignments_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + mutated = False + for blk in state.func_ir.blocks.values(): + to_clone = [] + # find assignments to "foobar" + for assign in blk.find_insts(ir.Assign): + if assign.target.name == "foobar": + to_clone.append(assign) + # clone + for assign in to_clone: + clone = copy.deepcopy(assign) + blk.insert_after(clone, assign) + mutated = True + # keep track of cloned statements + cloned.append(clone) + return mutated + + class CustomCompiler(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline( + self.state, "custom_pipeline", + ) + pm._finalized = False + # Insert the cloning pass after SSA + pm.add_pass_after(CloneFoobarAssignments, ReconstructSSA) + # Capture IR post lowering + pm.add_pass_after(PreserveIR, NativeLowering) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomCompiler) + def udt(arr): + foobar = arr + 1 # this assignment will be cloned + return foobar + + arr = np.arange(10) + # Verify that the function works as expected + self.assertPreciseEqual(udt(arr), arr + 1) + # Verify that the expected statement is cloned + self.assertEqual(len(cloned), 1) + self.assertEqual(cloned[0].target.name, "foobar") + # Verify in the Numba IR that the expected statement is cloned + nir = udt.overloads[udt.signatures[0]].metadata['preserved_ir'] + self.assertEqual(len(nir.blocks), 1, + "only one block") + [blk] = nir.blocks.values() + assigns = blk.find_insts(ir.Assign) + foobar_assigns = [stmt for stmt in assigns + if stmt.target.name == "foobar"] + self.assertEqual( + len(foobar_assigns), 2, + "expected two assignment statements into 'foobar'", + ) + self.assertEqual( + foobar_assigns[0], foobar_assigns[1], + "expected the two assignment statements to be the same", + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_svml.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_svml.py new file mode 100644 index 0000000000000000000000000000000000000000..a0785cf7c212a5351bab933ae7b94a485de347dd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_svml.py @@ -0,0 +1,411 @@ +import math +import numpy as np +import numbers +import re +import traceback +import multiprocessing as mp + +import numba +from numba import njit, prange +from numba.core import config +from numba.tests.support import TestCase, tag, override_env_config +import unittest + +needs_svml = unittest.skipUnless(config.USING_SVML, + "SVML tests need SVML to be present") + +# a map of float64 vector lengths with corresponding CPU architecture +vlen2cpu = {2: 'nehalem', 4: 'haswell', 8: 'skylake-avx512'} +# force LLVM to use AVX512 registers for vectorization +# https://reviews.llvm.org/D67259 +vlen2cpu_features = {2: '', 4: '', 8: '-prefer-256-bit'} + +# env vars to force CPU as skylake-avx512. +# force LLVM to use AVX512 registers for vectorization +# https://reviews.llvm.org/D67259 +_skylake_axv512_envvars = {'NUMBA_CPU_NAME': 'skylake-avx512', + 'NUMBA_CPU_FEATURES': '-prefer-256-bit'} + +# K: SVML functions, V: python functions which are expected to be SIMD-vectorized +# using SVML, explicit references to Python functions here are mostly for sake of +# instant import checks. +# TODO: [] and comments below mean unused/untested SVML function, it's to be +# either enabled or to be replaced with the explanation why the function +# cannot be used in Numba +# TODO: this test does not support functions with more than 1 arguments yet +# The test logic should be modified if there is an SVML function being used under +# different name or module from Python +svml_funcs = { + "sin": [np.sin, math.sin], + "cos": [np.cos, math.cos], + "pow": [], # pow, math.pow], + "exp": [np.exp, math.exp], + "log": [np.log, math.log], + "acos": [math.acos], + "acosh": [math.acosh], + "asin": [math.asin], + "asinh": [math.asinh], + "atan2": [], # math.atan2], + "atan": [math.atan], + "atanh": [math.atanh], + "cbrt": [], # np.cbrt], + "cdfnorm": [], + "cdfnorminv": [], + "ceil": [], # np.ceil, math.ceil], + "cosd": [], + "cosh": [np.cosh, math.cosh], + "erf": [math.erf], # np.erf is available in Intel Distribution + "erfc": [math.erfc], + "erfcinv": [], + "erfinv": [], + "exp10": [], + "exp2": [], # np.exp2], + "expm1": [np.expm1, math.expm1], + "floor": [], # np.floor, math.floor], + "fmod": [], # np.fmod, math.fmod], + "hypot": [], # np.hypot, math.hypot], + "invsqrt": [], # available in Intel Distribution + "log10": [np.log10, math.log10], + "log1p": [np.log1p, math.log1p], + "log2": [], # np.log2], + "logb": [], + "nearbyint": [], + "rint": [], # np.rint], + "round": [], # round], + "sind": [], + "sinh": [np.sinh, math.sinh], + "tan": [np.tan, math.tan], + "tanh": [np.tanh, math.tanh], + "trunc": [], # np.trunc, math.trunc], +} +# TODO: these functions are not vectorizable with complex types +complex_funcs_exclude = ["tan", "log10", "expm1", "log1p", "tanh", "log"] + +# remove untested entries +svml_funcs = {k: v for k, v in svml_funcs.items() if len(v) > 0} +# lists for functions which belong to numpy and math modules correpondently +numpy_funcs = [f for f, v in svml_funcs.items() if " 1: + x.append(2.) + count += 1 + + l = List() + l.append(1.) + l.append(1.) + l.append(1.) + with self.assertRaises(RuntimeError) as raises: + foo(l) + + msg = "list was mutated during iteration" + self.assertIn(msg, str(raises.exception)) + + +class TestNoneType(MemoryLeakMixin, TestCase): + + def test_append_none(self): + @njit + def impl(): + l = List() + l.append(None) + return l + + self.assertEqual(impl.py_func(), impl()) + + def test_len_none(self): + @njit + def impl(): + l = List() + l.append(None) + return len(l) + + self.assertEqual(impl.py_func(), impl()) + + def test_getitem_none(self): + @njit + def impl(): + l = List() + l.append(None) + return l[0] + + self.assertEqual(impl.py_func(), impl()) + + def test_setitem_none(self): + @njit + def impl(): + l = List() + l.append(None) + l[0] = None + return l + + self.assertEqual(impl.py_func(), impl()) + + def test_equals_none(self): + @njit + def impl(): + l = List() + l.append(None) + m = List() + m.append(None) + return l == m, l != m, l < m, l <= m, l > m, l >= m + + self.assertEqual(impl.py_func(), impl()) + + def test_not_equals_none(self): + @njit + def impl(): + l = List() + l.append(None) + m = List() + m.append(1) + return l == m, l != m, l < m, l <= m, l > m, l >= m + + self.assertEqual(impl.py_func(), impl()) + + def test_iter_none(self): + @njit + def impl(): + l = List() + l.append(None) + l.append(None) + l.append(None) + count = 0 + for i in l: + count += 1 + return count + + self.assertEqual(impl.py_func(), impl()) + + def test_none_typed_method_fails(self): + """ Test that unsupported operations on List[None] raise. """ + def generate_function(line1, line2): + context = {} + exec(dedent(""" + from numba.typed import List + def bar(): + lst = List() + {} + {} + """.format(line1, line2)), context) + return njit(context["bar"]) + for line1, line2 in ( + ("lst.append(None)", "lst.pop()"), + ("lst.append(None)", "del lst[0]"), + ("lst.append(None)", "lst.count(None)"), + ("lst.append(None)", "lst.index(None)"), + ("lst.append(None)", "lst.insert(0, None)"), + ("" , "lst.insert(0, None)"), + ("lst.append(None)", "lst.clear()"), + ("lst.append(None)", "lst.copy()"), + ("lst.append(None)", "lst.extend([None])"), + ("", "lst.extend([None])"), + ("lst.append(None)", "lst.remove(None)"), + ("lst.append(None)", "lst.reverse()"), + ("lst.append(None)", "None in lst"), + ): + with self.assertRaises(TypingError) as raises: + foo = generate_function(line1, line2) + foo() + self.assertIn( + "method support for List[None] is limited", + str(raises.exception), + ) + + +class TestAllocation(MemoryLeakMixin, TestCase): + + def test_allocation(self): + # kwarg version + for i in range(16): + tl = List.empty_list(types.int32, allocated=i) + self.assertEqual(tl._allocated(), i) + + # posarg version + for i in range(16): + tl = List.empty_list(types.int32, i) + self.assertEqual(tl._allocated(), i) + + def test_allocation_njit(self): + # kwarg version + @njit + def foo(i): + tl = List.empty_list(types.int32, allocated=i) + return tl._allocated() + + for j in range(16): + self.assertEqual(foo(j), j) + + # posarg version + @njit + def foo(i): + tl = List.empty_list(types.int32, i) + return tl._allocated() + + for j in range(16): + self.assertEqual(foo(j), j) + + def test_growth_and_shrinkage(self): + tl = List.empty_list(types.int32) + growth_before = {0: 0, 4:4, 8:8, 16:16} + growth_after = {0: 4, 4:8, 8:16, 16:25} + for i in range(17): + if i in growth_before: + self.assertEqual(growth_before[i], tl._allocated()) + tl.append(i) + if i in growth_after: + self.assertEqual(growth_after[i], tl._allocated()) + + shrink_before = {17: 25, 12:25, 9:18, 6:12, 4:8, 3:6, 2:5, 1:4} + shrink_after = {17: 25, 12:18, 9:12, 6:8, 4:6, 3:5, 2:4, 1:0} + for i in range(17, 0, -1): + if i in shrink_before: + self.assertEqual(shrink_before[i], tl._allocated()) + tl.pop() + if i in shrink_after: + self.assertEqual(shrink_after[i], tl._allocated()) + + +class TestExtend(MemoryLeakMixin, TestCase): + + def test_extend_other(self): + @njit + def impl(other): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend(other) + return l + + other = List.empty_list(types.int32) + for x in range(10): + other.append(x) + + expected = impl.py_func(other) + got = impl(other) + self.assertEqual(expected, got) + + def test_extend_self(self): + @njit + def impl(): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend(l) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_tuple(self): + @njit + def impl(): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend((100,200,300)) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_single_value_container(self): + @njit + def impl(): + l = List() + l.extend((100,)) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_empty_unrefined(self): + # Extending an unrefined list with an empty iterable doesn't work in a + # jit compiled function as the list remains untyped. + l = List() + ret = l.extend(tuple()) + self.assertIsNone(ret) + self.assertEqual(len(l), 0) + self.assertFalse(l._typed) + + def test_extend_empty_refiend(self): + # Extending a refined list with an empty iterable doesn't work in a + # jit compiled function as the (empty) argument can't be typed + l = List((1,)) + l.extend(tuple()) + self.assertEqual(len(l), 1) + self.assertTrue(l._typed) + + +@njit +def cmp(a, b): + return a < b, a <= b, a == b, a != b, a >= b, a > b + + +class TestComparisons(MemoryLeakMixin, TestCase): + + def _cmp_dance(self, expected, pa, pb, na, nb): + # interpreter with regular list + self.assertEqual(cmp.py_func(pa, pb), expected) + + # interpreter with typed-list + py_got = cmp.py_func(na, nb) + self.assertEqual(py_got, expected) + + # compiled with typed-list + jit_got = cmp(na, nb) + self.assertEqual(jit_got, expected) + + def test_empty_vs_empty(self): + pa, pb = [], [] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_empty_vs_singleton(self): + pa, pb = [], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_empty(self): + pa, pb = [0], [] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_equal(self): + pa, pb = [0], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_less_than(self): + pa, pb = [0], [1] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_greater_than(self): + pa, pb = [1], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_equal(self): + pa, pb = [1, 2, 3], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_shorter(self): + pa, pb = [1, 2], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_second_shorter(self): + pa, pb = [1, 2, 3], [1, 2] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_less_than(self): + pa, pb = [1, 2, 2], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_greater_than(self): + pa, pb = [1, 2, 3], [1, 2, 2] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_equals_non_list(self): + l = to_tl([1, 2, 3]) + self.assertFalse(any(cmp.py_func(l, 1))) + self.assertFalse(any(cmp(l, 1))) + + +class TestListInferred(TestCase): + + def test_simple_refine_append(self): + @njit + def foo(): + l = List() + l.append(1) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [1]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_simple_refine_insert(self): + @njit + def foo(): + l = List() + l.insert(0, 1) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [1]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_extend_list(self): + @njit + def foo(): + a = List() + b = List() + for i in range(3): + b.append(i) + a.extend(b) + return a + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [0, 1, 2]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_extend_set(self): + @njit + def foo(): + l = List() + l.extend((0, 1, 2)) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [0, 1, 2]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_list_extend_iter(self): + @njit + def foo(): + l = List() + d = Dict() + d[0] = 0 + # d.keys() provides a DictKeysIterableType + l.extend(d.keys()) + return l + + got = foo() + self.assertEqual(0, got[0]) + + +class TestListRefctTypes(MemoryLeakMixin, TestCase): + + def test_str_item(self): + @njit + def foo(): + l = List.empty_list(types.unicode_type) + for s in ("a", "ab", "abc", "abcd"): + l.append(s) + return l + + l = foo() + expected = ["a", "ab", "abc", "abcd"] + for i, s in enumerate(expected): + self.assertEqual(l[i], s) + self.assertEqual(list(l), expected) + # Test insert replacement + l[3] = 'uxyz' + self.assertEqual(l[3], 'uxyz') + # Test list growth + nelem = 100 + for i in range(4, nelem): + l.append(str(i)) + self.assertEqual(l[i], str(i)) + + def test_str_item_refcount_replace(self): + @njit + def foo(): + # use some tricks to make ref-counted unicode + i, j = 'ab', 'c' + a = i + j + m, n = 'zy', 'x' + z = m + n + l = List.empty_list(types.unicode_type) + l.append(a) + # This *should* dec' a and inc' z thus tests that items that are + # replaced are also dec'ed. + l[0] = z + ra, rz = get_refcount(a), get_refcount(z) + return l, ra, rz + + l, ra, rz = foo() + self.assertEqual(l[0], "zyx") + self.assertEqual(ra, 1) + self.assertEqual(rz, 2) + + def test_dict_as_item_in_list(self): + @njit + def foo(): + l = List.empty_list(Dict.empty(int32, int32)) + d = Dict.empty(int32, int32) + d[0] = 1 + # This increments the refcount for d + l.append(d) + return get_refcount(d) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(2, c) + + def test_dict_as_item_in_list_multi_refcount(self): + @njit + def foo(): + l = List.empty_list(Dict.empty(int32, int32)) + d = Dict.empty(int32, int32) + d[0] = 1 + # This increments the refcount for d, twice + l.append(d) + l.append(d) + return get_refcount(d) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(3, c) + + def test_list_as_value_in_dict(self): + @njit + def foo(): + d = Dict.empty(int32, List.empty_list(int32)) + l = List.empty_list(int32) + l.append(0) + # This increments the refcount for l + d[0] = l + return get_refcount(l) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(2, c) + + def test_list_as_item_in_list(self): + nested_type = types.ListType(types.int32) + + @njit + def foo(): + la = List.empty_list(nested_type) + lb = List.empty_list(types.int32) + lb.append(1) + la.append(lb) + return la + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + + def test_array_as_item_in_list(self): + nested_type = types.Array(types.float64, 1, 'C') + + @njit + def foo(): + l = List.empty_list(nested_type) + a = np.zeros((1,)) + l.append(a) + return l + + expected = foo.py_func() + got = foo() + # Need to compare the nested arrays + self.assertTrue(np.all(expected[0] == got[0])) + + def test_array_pop_from_single_value_list(self): + @njit + def foo(): + l = List((np.zeros((1,)),)) + l.pop() + return l + + expected, got = foo.py_func(), foo() + # Need to compare the nested arrays + self.assertEqual(len(expected), 0) + self.assertEqual(len(got), 0) + # FIXME comparison of empty array-typed lists fails + # self.assertEqual(expected, got) + + def test_5264(self): + # Test the reproducer from #5264 and make sure it doesn't segfault + float_array = types.float64[:] + l = List.empty_list(float_array) + l.append(np.ones(3,dtype=np.float64)) + l.pop() + self.assertEqual(0, len(l)) + + def test_jitclass_as_item_in_list(self): + + spec = [ + ('value', int32), # a simple scalar field + ('array', float32[:]), # an array field + ] + + @jitclass(spec) + class Bag(object): + def __init__(self, value): + self.value = value + self.array = np.zeros(value, dtype=np.float32) + + @property + def size(self): + return self.array.size + + def increment(self, val): + for i in range(self.size): + self.array[i] += val + return self.array + + @njit + def foo(): + l = List() + l.append(Bag(21)) + l.append(Bag(22)) + l.append(Bag(23)) + return l + + expected = foo.py_func() + got = foo() + + def bag_equal(one, two): + # jitclasses couldn't override __eq__ at time of writing + self.assertEqual(one.value, two.value) + np.testing.assert_allclose(one.array, two.array) + + [bag_equal(a, b) for a, b in zip(expected, got)] + + def test_4960(self): + # Test the reproducer from #4960 and make sure it doesn't segfault + @jitclass([('value', int32)]) + class Simple(object): + def __init__(self, value): + self.value = value + + @njit + def foo(): + l = List((Simple(23),Simple(24))) + l.pop() + return l + + l = foo() + self.assertEqual(1, len(l)) + + def test_storage_model_mismatch(self): + # https://github.com/numba/numba/issues/4520 + # check for storage model mismatch in refcount ops generation + lst = List() + ref = [ + ("a", True, "a"), + ("b", False, "b"), + ("c", False, "c"), + ] + # populate + for x in ref: + lst.append(x) + # test + for i, x in enumerate(ref): + self.assertEqual(lst[i], ref[i]) + + def test_equals_on_list_with_dict_for_equal_lists(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d = List(), Dict() + d["a"] = 1 + c.append(d) + + self.assertEqual(a, c) + + def test_equals_on_list_with_dict_for_unequal_dicts(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d = List(), Dict() + d["a"] = 2 + c.append(d) + + self.assertNotEqual(a, c) + + def test_equals_on_list_with_dict_for_unequal_lists(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d, e = List(), Dict(), Dict() + d["a"] = 1 + e["b"] = 2 + c.append(d) + c.append(e) + + self.assertNotEqual(a, c) + + +class TestListSort(MemoryLeakMixin, TestCase): + def setUp(self): + super(TestListSort, self).setUp() + np.random.seed(0) + + def make(self, ctor, data): + lst = ctor() + lst.extend(data) + return lst + + def make_both(self, data): + return { + 'py': self.make(list, data), + 'nb': self.make(List, data), + } + + def test_sort_no_args(self): + def udt(lst): + lst.sort() + return lst + + for nelem in [13, 29, 127]: + my_lists = self.make_both(np.random.randint(0, nelem, nelem)) + self.assertEqual(list(udt(my_lists['nb'])), udt(my_lists['py'])) + + def test_sort_all_args(self): + def udt(lst, key, reverse): + lst.sort(key=key, reverse=reverse) + return lst + + possible_keys = [ + lambda x: -x, # negative + lambda x: 1 / (1 + x), # make float + lambda x: (x, -x), # tuple + lambda x: x, # identity + ] + possible_reverse = [True, False] + for key, reverse in product(possible_keys, possible_reverse): + my_lists = self.make_both(np.random.randint(0, 100, 23)) + msg = "case for key={} reverse={}".format(key, reverse) + self.assertEqual( + list(udt(my_lists['nb'], key=key, reverse=reverse)), + udt(my_lists['py'], key=key, reverse=reverse), + msg=msg, + ) + + def test_sort_dispatcher_key(self): + def udt(lst, key): + lst.sort(key=key) + return lst + + my_lists = self.make_both(np.random.randint(0, 100, 31)) + py_key = lambda x: x + 1 + nb_key = njit(lambda x: x + 1) + # test typedlist with jitted function + self.assertEqual( + list(udt(my_lists['nb'], key=nb_key)), + udt(my_lists['py'], key=py_key), + ) + # test typedlist with and without jitted function + self.assertEqual( + list(udt(my_lists['nb'], key=nb_key)), + list(udt(my_lists['nb'], key=py_key)), + ) + + def test_sort_in_jit_w_lambda_key(self): + @njit + def udt(lst): + lst.sort(key=lambda x: -x) + return lst + + lst = self.make(List, np.random.randint(0, 100, 31)) + self.assertEqual(udt(lst), udt.py_func(lst)) + + def test_sort_in_jit_w_global_key(self): + @njit + def keyfn(x): + return -x + + @njit + def udt(lst): + lst.sort(key=keyfn) + return lst + + lst = self.make(List, np.random.randint(0, 100, 31)) + self.assertEqual(udt(lst), udt.py_func(lst)) + + def test_sort_on_arrays(self): + @njit + def foo(lst): + lst.sort(key=lambda arr: np.sum(arr)) + return lst + + arrays = [np.random.random(3) for _ in range(10)] + my_lists = self.make_both(arrays) + self.assertEqual( + list(foo(my_lists['nb'])), + foo.py_func(my_lists['py']), + ) + + +class TestImmutable(MemoryLeakMixin, TestCase): + + def test_is_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + return l._is_mutable() + self.assertTrue(foo()) + self.assertTrue(foo.py_func()) + + def test_make_immutable_is_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return l._is_mutable() + self.assertFalse(foo()) + self.assertFalse(foo.py_func()) + + def test_length_still_works_when_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return len(l),l._is_mutable() + length, mutable = foo() + self.assertEqual(length, 1) + self.assertFalse(mutable) + + def test_getitem_still_works_when_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return l[0], l._is_mutable() + test_item, mutable = foo() + self.assertEqual(test_item, 1) + self.assertFalse(mutable) + + def test_append_fails(self): + self.disable_leak_check() + + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + l.append(1) + + for func in (foo, foo.py_func): + with self.assertRaises(ValueError) as raises: + func() + self.assertIn( + 'list is immutable', + str(raises.exception), + ) + + def test_mutation_fails(self): + """ Test that any attempt to mutate an immutable typed list fails. """ + self.disable_leak_check() + + def generate_function(line): + context = {} + exec(dedent(""" + from numba.typed import List + def bar(): + lst = List() + lst.append(1) + lst._make_immutable() + {} + """.format(line)), context) + return njit(context["bar"]) + for line in ("lst.append(0)", + "lst[0] = 0", + "lst.pop()", + "del lst[0]", + "lst.extend((0,))", + "lst.insert(0, 0)", + "lst.clear()", + "lst.reverse()", + "lst.sort()", + ): + foo = generate_function(line) + for func in (foo, foo.py_func): + with self.assertRaises(ValueError) as raises: + func() + self.assertIn( + "list is immutable", + str(raises.exception), + ) + + +class TestGetItemIndexType(MemoryLeakMixin, TestCase): + + def test_indexing_with_uint8(self): + """ Test for reproducer at https://github.com/numba/numba/issues/7250 + """ + @njit + def foo(): + l = List.empty_list(uint8) + for i in range(129): + l.append(uint8(i)) + a = uint8(128) + return l[a] + + self.assertEqual(foo(), 128) + + +class TestListFromIter(MemoryLeakMixin, TestCase): + + def test_simple_iterable_types(self): + """Test all simple iterables that a List can be constructed from.""" + + def generate_function(line): + context = {} + code = dedent(""" + from numba.typed import List + def bar(): + {} + return l + """).format(line) + exec(code, context) + return njit(context["bar"]) + for line in ("l = List([0, 1, 2])", + "l = List(range(3))", + "l = List(List([0, 1, 2]))", + "l = List((0, 1, 2))", + "l = List(set([0, 1, 2]))", + ): + foo = generate_function(line) + cf_received, py_received = foo(), foo.py_func() + for result in (cf_received, py_received): + for i in range(3): + self.assertEqual(i, result[i]) + + def test_unicode(self): + """Test that a List can be created from a unicode string.""" + @njit + def foo(): + l = List("abc") + return l + expected = List() + for i in ("a", "b", "c"): + expected.append(i) + self.assertEqual(foo.py_func(), expected) + self.assertEqual(foo(), expected) + + def test_dict_iters(self): + """Test that a List can be created from Dict iterators.""" + + def generate_function(line): + context = {} + code = dedent(""" + from numba.typed import List, Dict + def bar(): + d = Dict() + d[0], d[1], d[2] = "a", "b", "c" + {} + return l + """).format(line) + exec(code, context) + return njit(context["bar"]) + + def generate_expected(values): + expected = List() + for i in values: + expected.append(i) + return expected + + for line, values in ( + ("l = List(d)", (0, 1, 2)), + ("l = List(d.keys())", (0, 1, 2)), + ("l = List(d.values())", ("a", "b", "c")), + ("l = List(d.items())", ((0, "a"), (1, "b"), (2, "c"))), + ): + foo, expected = generate_function(line), generate_expected(values) + for func in (foo, foo.py_func): + self.assertEqual(func(), expected) + + def test_ndarray_scalar(self): + + @njit + def foo(): + return List(np.ones(3)) + + expected = List() + for i in range(3): + expected.append(1) + + self.assertEqual(expected, foo()) + self.assertEqual(expected, foo.py_func()) + + def test_ndarray_oned(self): + + @njit + def foo(): + return List(np.array(1)) + + expected = List() + expected.append(1) + + self.assertEqual(expected, foo()) + self.assertEqual(expected, foo.py_func()) + + def test_ndarray_twod(self): + + @njit + def foo(x): + return List(x) + + carr = np.array([[1, 2], [3, 4]]) + farr = np.asfortranarray(carr) + aarr = np.arange(8).reshape((2, 4))[:, ::2] + + for layout, arr in zip('CFA', (carr, farr, aarr)): + self.assertEqual(typeof(arr).layout, layout) + expected = List() + expected.append(arr[0, :]) + expected.append(arr[1, :]) + received = foo(arr) + + np.testing.assert_equal(expected[0], received[0]) + np.testing.assert_equal(expected[1], received[1]) + + pyreceived = foo.py_func(arr) + + np.testing.assert_equal(expected[0], pyreceived[0]) + np.testing.assert_equal(expected[1], pyreceived[1]) + + def test_exception_on_plain_int(self): + @njit + def foo(): + l = List(23) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List(23) + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + def test_exception_on_inhomogeneous_tuple(self): + @njit + def foo(): + l = List((1, 1.0)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + with self.assertRaises(TypingError) as raises: + List((1, 1.0)) + # FIXME this bails with a length casting error when we attempt to + # append 1.0 to an int typed list. + + def test_exception_on_too_many_args(self): + @njit + def foo(): + l = List((0, 1, 2), (3, 4, 5)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() expected at most 1 argument, got 2", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List((0, 1, 2), (3, 4, 5)) + self.assertIn( + "List() expected at most 1 argument, got 2", + str(raises.exception), + ) + + @njit + def foo(): + l = List((0, 1, 2), (3, 4, 5), (6, 7, 8)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() expected at most 1 argument, got 3", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List((0, 1, 2), (3, 4, 5), (6, 7, 8)) + self.assertIn( + "List() expected at most 1 argument, got 3", + str(raises.exception), + ) + + def test_exception_on_kwargs(self): + @njit + def foo(): + l = List(iterable=(0, 1, 2)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() takes no keyword arguments", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List(iterable=(0, 1, 2)) + self.assertIn( + "List() takes no keyword arguments", + str(raises.exception), + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typedobjectutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typedobjectutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f93d6252db85d83595cbf1ce814b7167a32426d4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typedobjectutils.py @@ -0,0 +1,68 @@ +""" +Unit-tests for `typedobjectutils.py` +""" + +import warnings + + +from numba.core import types +from numba.tests.support import TestCase +from numba.typed.typedobjectutils import _sentry_safe_cast + + +class TestTypedObjectUtils(TestCase): + def test_sentry_safe_cast_warnings(self): + warn_cases = [] + warn_cases += [ + # integer cases + (types.int32, types.int16), + (types.int32, types.uint32), + (types.int64, types.uint32), + # float cases + (types.float64, types.float32), + # complex cases + (types.complex128, types.complex64), + # int to float cases + (types.int32, types.float32), + (types.int64, types.float32), + # tuple-of-ints to tuple-of-floats, + (types.Tuple([types.int32]), types.Tuple([types.float32])), + ] + + for fromty, toty in warn_cases: + with self.subTest(fromty=fromty, toty=toty): + with warnings.catch_warnings(record=True) as w: + _sentry_safe_cast(fromty, toty) + self.assertEqual(len(w), 1) + # Make sure the warning is about unsafe cast + self.assertIn( + "unsafe cast from {} to {}".format(fromty, toty), + str(w[0]), + ) + + def test_sentry_safe_cast_no_warn(self): + ok_cases = [] + ok_cases += [ + # integer cases + (types.int32, types.int64), + (types.uint8, types.int32), + # float cases + (types.float32, types.float64), + # complex cases + (types.complex64, types.complex128), + # int to float cases + (types.int32, types.float64), + (types.uint8, types.float32), + # float to complex cases + (types.float32, types.complex128), + (types.float64, types.complex128), + # tuple-of-ints to tuple-of-ints, + (types.Tuple([types.int32]), types.Tuple([types.int64])), + ] + + for fromty, toty in ok_cases: + with self.subTest(fromty=fromty, toty=toty): + with warnings.catch_warnings(record=True) as w: + _sentry_safe_cast(fromty, toty) + # Expect no warnings + self.assertEqual(len(w), 0) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typenames.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typenames.py new file mode 100644 index 0000000000000000000000000000000000000000..531a8929747d8d565d71d7594904fc8229d01e0a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typenames.py @@ -0,0 +1,17 @@ +import numpy as np + +from numba.core import types +import unittest + + +class TestTypeNames(unittest.TestCase): + def test_numpy_integers(self): + expect = getattr(types, "int%d" % (np.dtype("int").itemsize * 8)) + self.assertEqual(types.int_, expect) + + expect = getattr(types, "uint%d" % (np.dtype("uint").itemsize * 8)) + self.assertEqual(types.uint, expect) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typingerror.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typingerror.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6b6cd3e0e9f6a93e1b508699fbddbe35dd85ab --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typingerror.py @@ -0,0 +1,236 @@ +import math +import re +import textwrap +import operator + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.core.errors import TypingError +from numba.core.types.functions import _header_lead +from numba.tests.support import TestCase + + +def what(): + pass + +def foo(): + return what() + +def bar(x): + return x.a + +def issue_868(a): + return a.shape * 2 + +def impossible_return_type(x): + if x > 0: + return () + else: + return 1j + +def bad_hypot_usage(): + return math.hypot(1) + +def imprecise_list(): + l = [] + return len(l) + +def using_imprecise_list(): + a = np.array([]) + return a.astype(np.int32) + +def unknown_module(): + return numpyz.int32(0) + +def nop(x, y, z): + pass + +def array_setitem_invalid_cast(): + arr = np.empty(1, dtype=np.float64) + arr[0] = 1j # invalid cast from complex to float + return arr + + +class Foo(object): + def __repr__(self): + return "" + + +class TestTypingError(unittest.TestCase): + + def test_unknown_function(self): + try: + njit((),)(foo) + except TypingError as e: + self.assertIn("Untyped global name 'what'", str(e)) + else: + self.fail("Should raise error") + + def test_unknown_attrs(self): + try: + njit((types.int32,),)(bar) + except TypingError as e: + self.assertIn("Unknown attribute 'a' of type int32", str(e)) + else: + self.fail("Should raise error") + + def test_unknown_module(self): + # This used to print "'object' object has no attribute 'int32'" + with self.assertRaises(TypingError) as raises: + njit((),)(unknown_module) + self.assertIn("name 'numpyz' is not defined", str(raises.exception)) + + def test_issue_868(self): + ''' + Summary: multiplying a scalar by a non-scalar would cause a crash in + type inference because TimeDeltaMixOp always assumed at least one of + its operands was an NPTimeDelta in its generic() method. + ''' + with self.assertRaises(TypingError) as raises: + njit((types.Array(types.int32, 1, 'C'),))(issue_868) + + expected = ((_header_lead + " Function() found " + "for signature:\n \n >>> mul(UniTuple({} x 1), {})") + .format(str(types.intp), types.IntegerLiteral(2))) + self.assertIn(expected, str(raises.exception)) + self.assertIn("During: typing of", str(raises.exception)) + + def test_return_type_unification(self): + with self.assertRaises(TypingError) as raises: + njit((types.int32,))(impossible_return_type,) + msg = ("Can't unify return type from the following types: Tuple(), " + "complex128") + self.assertIn(msg, str(raises.exception)) + + def test_bad_hypot_usage(self): + with self.assertRaises(TypingError) as raises: + njit((),)(bad_hypot_usage,) + + errmsg = str(raises.exception) + # Make sure it listed the known signatures. + # This is sensitive to the formatting of the error message. + self.assertIn(" * (float64, float64) -> float64", errmsg) + + # find the context lines + ctx_lines = [x for x in errmsg.splitlines() if "During:" in x ] + + # Check contextual msg + self.assertTrue(re.search(r'.*During: resolving callee type: Function.*hypot', ctx_lines[0])) + self.assertTrue(re.search(r'.*During: typing of call .*test_typingerror.py', ctx_lines[1])) + + + def test_imprecise_list(self): + """ + Type inference should catch that a list type's remain imprecise, + instead of letting lowering fail. + """ + with self.assertRaises(TypingError) as raises: + njit((),)(imprecise_list) + + errmsg = str(raises.exception) + msg = ("Cannot infer the type of variable 'l', have imprecise type: " + "list(undefined)") + self.assertIn(msg, errmsg) + # check help message has gone in + self.assertIn("For Numba to be able to compile a list", errmsg) + + def test_using_imprecise_list(self): + """ + Type inference should report informative error about untyped list. + TODO: #2931 + """ + with self.assertRaises(TypingError) as raises: + njit((),)(using_imprecise_list) + + errmsg = str(raises.exception) + self.assertIn("Undecided type", errmsg) + + def test_array_setitem_invalid_cast(self): + with self.assertRaises(TypingError) as raises: + njit((),)(array_setitem_invalid_cast) + + errmsg = str(raises.exception) + self.assertIn( + _header_lead + " Function({})".format(operator.setitem), + errmsg, + ) + self.assertIn( + "(array(float64, 1d, C), Literal[int](0), complex128)", + errmsg, + ) + + def test_template_rejection_error_message_cascade(self): + from numba import njit + @njit + def foo(): + z = 1 + for a, b in enumerate(z): + pass + return z + + with self.assertRaises(TypingError) as raises: + foo() + errmsg = str(raises.exception) + expected = "No match." + self.assertIn(expected, errmsg) + + ctx_lines = [x for x in errmsg.splitlines() if "During:" in x ] + search = [r'.*During: resolving callee type: Function.*enumerate', + r'.*During: typing of call .*test_typingerror.py'] + for i, x in enumerate(search): + self.assertTrue(re.search(x, ctx_lines[i])) + + +class TestArgumentTypingError(unittest.TestCase): + """ + Test diagnostics of typing errors caused by argument inference failure. + """ + + def test_unsupported_array_dtype(self): + # See issue #1943 + cfunc = jit(nopython=True)(nop) + a = np.ones(3) + a = a.astype(a.dtype.newbyteorder()) + with self.assertRaises(TypingError) as raises: + cfunc(1, a, a) + expected = f"Unsupported array dtype: {a.dtype}" + self.assertIn(expected, str(raises.exception)) + + def test_unsupported_type(self): + cfunc = jit(nopython=True)(nop) + foo = Foo() + with self.assertRaises(TypingError) as raises: + cfunc(1, foo, 1) + + expected=re.compile(("This error may have been caused by the following " + r"argument\(s\):\n- argument 1:.*Cannot determine " + "Numba type of " + "")) + self.assertTrue(expected.search(str(raises.exception)) is not None) + + +class TestCallError(unittest.TestCase): + def test_readonly_array(self): + @jit("(f8[:],)", nopython=True) + def inner(x): + return x + + @jit(nopython=True) + def outer(): + return inner(gvalues) + + gvalues = np.ones(10, dtype=np.float64) + + with self.assertRaises(TypingError) as raises: + outer() + + got = str(raises.exception) + pat = r"Invalid use of.*readonly array\(float64, 1d, C\)" + self.assertIsNotNone(re.search(pat, got)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62004deb0a7c8868993b48ac4597a24433ce449c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/__init__.py @@ -0,0 +1,20 @@ +import importlib + + +_delayed_symbols = { + "Dict": ".typeddict", + "List": ".typedlist", +} + + +def __getattr__(name): + # Uses PEP-562 but requires python>3.6 + if name in _delayed_symbols: + modpath = _delayed_symbols[name] + mod = importlib.import_module(modpath, __name__) + return getattr(mod, name) + else: + try: + return importlib.import_module(f".{name}", __name__) + except ModuleNotFoundError: + raise AttributeError diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..fc35e0dc1bcea3c98db2b4f130620caca351096f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictimpl.py @@ -0,0 +1,43 @@ +""" +This file implements the lowering for `dict()` +""" +from numba.core import types +from numba.core.imputils import lower_builtin + + +_message_dict_support = """ +Unsupported use of `dict()` with keyword argument(s). \ +The only supported uses are `dict()` or `dict(*iterable)`. +""".strip() + + +@lower_builtin(dict, types.IterableType) +def dict_constructor(context, builder, sig, args): + from numba.typed import Dict + + dicttype = sig.return_type + kt, vt = dicttype.key_type, dicttype.value_type + + def dict_impl(iterable): + res = Dict.empty(kt, vt) + for k, v in iterable: + res[k] = v + return res + + return context.compile_internal(builder, dict_impl, sig, args) + + +@lower_builtin(dict) +def impl_dict(context, builder, sig, args): + """ + The `dict()` implementation simply forwards the work to `Dict.empty()`. + """ + from numba.typed import Dict + + dicttype = sig.return_type + kt, vt = dicttype.key_type, dicttype.value_type + + def call_ctor(): + return Dict.empty(kt, vt) + + return context.compile_internal(builder, call_ctor, sig, args) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictobject.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictobject.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b6b000f10c8c73296f2428e9d69b2c42aaef39 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/dictobject.py @@ -0,0 +1,1367 @@ +""" +Compiler-side implementation of the dictionary. +""" +import ctypes +import operator +from enum import IntEnum + +from llvmlite import ir + +from numba import _helperlib + +from numba.core.extending import ( + overload, + overload_method, + overload_attribute, + intrinsic, + register_model, + models, + lower_builtin, + lower_cast, + make_attribute_wrapper, +) +from numba.core.imputils import iternext_impl, impl_ret_untracked +from numba.core import types, cgutils +from numba.core.types import ( + DictType, + DictItemsIterableType, + DictKeysIterableType, + DictValuesIterableType, + DictIteratorType, + Type, +) +from numba.core.imputils import impl_ret_borrowed, RefType +from numba.core.errors import TypingError, LoweringError, NumbaTypeError +from numba.core import typing +from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional, + _sentry_safe_cast_default, + _get_incref_decref, + _get_equal, _container_get_data,) + +ll_dict_type = cgutils.voidptr_t +ll_dictiter_type = cgutils.voidptr_t +ll_voidptr_type = cgutils.voidptr_t +ll_status = cgutils.int32_t +ll_ssize_t = cgutils.intp_t +ll_hash = ll_ssize_t +ll_bytes = cgutils.voidptr_t + + +_meminfo_dictptr = types.MemInfoPointer(types.voidptr) + + +# The following enums must match _dictobject.c + +class DKIX(IntEnum): + """Special return value of dict lookup. + """ + EMPTY = -1 + + +class Status(IntEnum): + """Status code for other dict operations. + """ + OK = 0 + OK_REPLACED = 1 + ERR_NO_MEMORY = -1 + ERR_DICT_MUTATED = -2 + ERR_ITER_EXHAUSTED = -3 + ERR_DICT_EMPTY = -4 + ERR_CMP_FAILED = -5 + + +def new_dict(key, value, n_keys=0): + """Construct a new dict with enough space for *n_keys* without a resize. + + Parameters + ---------- + key, value : TypeRef + Key type and value type of the new dict. + n_keys : int, default 0 + The number of keys to insert without needing a resize. + A value of 0 creates a dict with minimum size. + """ + # With JIT disabled, ignore all arguments and return a Python dict. + return dict() + + +@register_model(DictType) +class DictModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('meminfo', _meminfo_dictptr), + ('data', types.voidptr), # ptr to the C dict + ] + super(DictModel, self).__init__(dmm, fe_type, members) + + +@register_model(DictItemsIterableType) +@register_model(DictKeysIterableType) +@register_model(DictValuesIterableType) +@register_model(DictIteratorType) +class DictIterModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('parent', fe_type.parent), # reference to the dict + ('state', types.voidptr), # iterator state in C code + ] + super(DictIterModel, self).__init__(dmm, fe_type, members) + + +# Make _parent available to make len simple +make_attribute_wrapper(DictItemsIterableType, "parent", "_parent") +make_attribute_wrapper(DictKeysIterableType, "parent", "_parent") +make_attribute_wrapper(DictValuesIterableType, "parent", "_parent") + + +def _raise_if_error(context, builder, status, msg): + """Raise an internal error depending on the value of *status* + """ + ok_status = status.type(int(Status.OK)) + with builder.if_then(builder.icmp_signed('!=', status, ok_status)): + context.call_conv.return_user_exc(builder, RuntimeError, (msg,)) + + +@intrinsic +def _as_meminfo(typingctx, dctobj): + """Returns the MemInfoPointer of a dictionary. + """ + if not isinstance(dctobj, types.DictType): + raise TypingError('expected *dctobj* to be a DictType') + + def codegen(context, builder, sig, args): + [td] = sig.args + [d] = args + # Incref + context.nrt.incref(builder, td, d) + ctor = cgutils.create_struct_proxy(td) + dstruct = ctor(context, builder, value=d) + # Returns the plain MemInfo + return dstruct.meminfo + + sig = _meminfo_dictptr(dctobj) + return sig, codegen + + +@intrinsic +def _from_meminfo(typingctx, mi, dicttyperef): + """Recreate a dictionary from a MemInfoPointer + """ + if mi != _meminfo_dictptr: + raise TypingError('expected a MemInfoPointer for dict.') + dicttype = dicttyperef.instance_type + if not isinstance(dicttype, DictType): + raise TypingError('expected a {}'.format(DictType)) + + def codegen(context, builder, sig, args): + [tmi, tdref] = sig.args + td = tdref.instance_type + [mi, _] = args + + ctor = cgutils.create_struct_proxy(td) + dstruct = ctor(context, builder) + + data_pointer = context.nrt.meminfo_data(builder, mi) + data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer()) + + dstruct.data = builder.load(data_pointer) + dstruct.meminfo = mi + + return impl_ret_borrowed( + context, + builder, + dicttype, + dstruct._getvalue(), + ) + + sig = dicttype(mi, dicttyperef) + return sig, codegen + + +def _call_dict_free(context, builder, ptr): + """Call numba_dict_free(ptr) + """ + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type], + ) + free = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_free') + builder.call(free, [ptr]) + + +def _imp_dtor(context, module): + """Define the dtor for dictionary + """ + llvoidptr = context.get_value_type(types.voidptr) + llsize = context.get_value_type(types.uintp) + fnty = ir.FunctionType( + ir.VoidType(), + [llvoidptr, llsize, llvoidptr], + ) + fname = '_numba_dict_dtor' + fn = cgutils.get_or_insert_function(module, fnty, fname) + + if fn.is_declaration: + # Set linkage + fn.linkage = 'linkonce_odr' + # Define + builder = ir.IRBuilder(fn.append_basic_block()) + dp = builder.bitcast(fn.args[0], ll_dict_type.as_pointer()) + d = builder.load(dp) + _call_dict_free(context, builder, d) + builder.ret_void() + + return fn + + +@intrinsic +def _dict_new_sized(typingctx, n_keys, keyty, valty): + """Wrap numba_dict_new_sized. + + Allocate a new dictionary object with enough space to hold + *n_keys* keys without needing a resize. + + Parameters + ---------- + keyty, valty: Type + Type of the key and value, respectively. + n_keys: int + The number of keys to insert without needing a resize. + A value of 0 creates a dict with minimum size. + """ + resty = types.voidptr + sig = resty(n_keys, keyty, valty) + + def codegen(context, builder, sig, args): + n_keys = builder.bitcast(args[0], ll_ssize_t) + + # Determine sizeof key and value types + ll_key = context.get_data_type(keyty.instance_type) + ll_val = context.get_data_type(valty.instance_type) + sz_key = context.get_abi_sizeof(ll_key) + sz_val = context.get_abi_sizeof(ll_val) + + refdp = cgutils.alloca_once(builder, ll_dict_type, zfill=True) + + argtys = [ll_dict_type.as_pointer(), ll_ssize_t, ll_ssize_t, ll_ssize_t] + fnty = ir.FunctionType(ll_status, argtys) + fn = ir.Function(builder.module, fnty, 'numba_dict_new_sized') + + args = [refdp, n_keys, ll_ssize_t(sz_key), ll_ssize_t(sz_val)] + status = builder.call(fn, args) + + allocated_failed_msg = "Failed to allocate dictionary" + _raise_if_error(context, builder, status, msg=allocated_failed_msg) + + dp = builder.load(refdp) + return dp + + return sig, codegen + + +@intrinsic +def _dict_set_method_table(typingctx, dp, keyty, valty): + """Wrap numba_dict_set_method_table + """ + resty = types.void + sig = resty(dp, keyty, valty) + + def codegen(context, builder, sig, args): + vtablety = ir.LiteralStructType([ + ll_voidptr_type, # equal + ll_voidptr_type, # key incref + ll_voidptr_type, # key decref + ll_voidptr_type, # val incref + ll_voidptr_type, # val decref + ]) + setmethod_fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type, vtablety.as_pointer()] + ) + setmethod_fn = ir.Function( + builder.module, + setmethod_fnty, + name='numba_dict_set_method_table', + ) + dp = args[0] + vtable = cgutils.alloca_once(builder, vtablety, zfill=True) + + # install key incref/decref + key_equal_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0) + key_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1) + key_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 2) + val_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 3) + val_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 4) + + dm_key = context.data_model_manager[keyty.instance_type] + if dm_key.contains_nrt_meminfo(): + equal = _get_equal(context, builder.module, dm_key, 'dict_key') + key_incref, key_decref = _get_incref_decref( + context, builder.module, dm_key, 'dict_key' + ) + builder.store( + builder.bitcast(equal, key_equal_ptr.type.pointee), + key_equal_ptr, + ) + builder.store( + builder.bitcast(key_incref, key_incref_ptr.type.pointee), + key_incref_ptr, + ) + builder.store( + builder.bitcast(key_decref, key_decref_ptr.type.pointee), + key_decref_ptr, + ) + + dm_val = context.data_model_manager[valty.instance_type] + if dm_val.contains_nrt_meminfo(): + val_incref, val_decref = _get_incref_decref( + context, builder.module, dm_val, 'dict_value' + ) + builder.store( + builder.bitcast(val_incref, val_incref_ptr.type.pointee), + val_incref_ptr, + ) + builder.store( + builder.bitcast(val_decref, val_decref_ptr.type.pointee), + val_decref_ptr, + ) + + builder.call(setmethod_fn, [dp, vtable]) + + return sig, codegen + + +@intrinsic +def _dict_insert(typingctx, d, key, hashval, val): + """Wrap numba_dict_insert + """ + resty = types.int32 + sig = resty(d, d.key_type, types.intp, d.value_type) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_bytes, ll_hash, ll_bytes, ll_bytes], + ) + [d, key, hashval, val] = args + [td, tkey, thashval, tval] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_insert') + + dm_key = context.data_model_manager[tkey] + dm_val = context.data_model_manager[tval] + + data_key = dm_key.as_data(builder, key) + data_val = dm_val.as_data(builder, val) + + ptr_key = cgutils.alloca_once_value(builder, data_key) + cgutils.memset_padding(builder, ptr_key) + + ptr_val = cgutils.alloca_once_value(builder, data_val) + # TODO: the ptr_oldval is not used. needed for refct + ptr_oldval = cgutils.alloca_once(builder, data_val.type) + + dp = _container_get_data(context, builder, td, d) + status = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + hashval, + _as_bytes(builder, ptr_val), + _as_bytes(builder, ptr_oldval), + ], + ) + return status + + return sig, codegen + + +@intrinsic +def _dict_length(typingctx, d): + """Wrap numba_dict_length + + Returns the length of the dictionary. + """ + resty = types.intp + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_ssize_t, + [ll_dict_type], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_length') + [d] = args + [td] = sig.args + dp = _container_get_data(context, builder, td, d) + n = builder.call(fn, [dp]) + return n + + return sig, codegen + + +@intrinsic +def _dict_dump(typingctx, d): + """Dump the dictionary keys and values. + Wraps numba_dict_dump for debugging. + """ + resty = types.void + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dict_type], + ) + [td] = sig.args + [d] = args + dp = _container_get_data(context, builder, td, d) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_dump') + + builder.call(fn, [dp]) + + return sig, codegen + + +@intrinsic +def _dict_lookup(typingctx, d, key, hashval): + """Wrap numba_dict_lookup + + Returns 2-tuple of (intp, ?value_type) + """ + resty = types.Tuple([types.intp, types.Optional(d.value_type)]) + sig = resty(d, key, hashval) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_ssize_t, + [ll_dict_type, ll_bytes, ll_hash, ll_bytes], + ) + [td, tkey, thashval] = sig.args + [d, key, hashval] = args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_lookup') + + dm_key = context.data_model_manager[tkey] + dm_val = context.data_model_manager[td.value_type] + + data_key = dm_key.as_data(builder, key) + ptr_key = cgutils.alloca_once_value(builder, data_key) + cgutils.memset_padding(builder, ptr_key) + + ll_val = context.get_data_type(td.value_type) + ptr_val = cgutils.alloca_once(builder, ll_val) + + dp = _container_get_data(context, builder, td, d) + ix = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + hashval, + _as_bytes(builder, ptr_val), + ], + ) + # Load value if output is available + found = builder.icmp_signed('>', ix, ix.type(int(DKIX.EMPTY))) + + out = context.make_optional_none(builder, td.value_type) + pout = cgutils.alloca_once_value(builder, out) + + with builder.if_then(found): + val = dm_val.load_from_data_pointer(builder, ptr_val) + context.nrt.incref(builder, td.value_type, val) + loaded = context.make_optional_value(builder, td.value_type, val) + builder.store(loaded, pout) + + out = builder.load(pout) + return context.make_tuple(builder, resty, [ix, out]) + + return sig, codegen + + +@intrinsic +def _dict_popitem(typingctx, d): + """Wrap numba_dict_popitem + """ + + keyvalty = types.Tuple([d.key_type, d.value_type]) + resty = types.Tuple([types.int32, types.Optional(keyvalty)]) + sig = resty(d) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_bytes, ll_bytes], + ) + [d] = args + [td] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_popitem') + + dm_key = context.data_model_manager[td.key_type] + dm_val = context.data_model_manager[td.value_type] + + ptr_key = cgutils.alloca_once(builder, dm_key.get_data_type()) + ptr_val = cgutils.alloca_once(builder, dm_val.get_data_type()) + + dp = _container_get_data(context, builder, td, d) + status = builder.call( + fn, + [ + dp, + _as_bytes(builder, ptr_key), + _as_bytes(builder, ptr_val), + ], + ) + out = context.make_optional_none(builder, keyvalty) + pout = cgutils.alloca_once_value(builder, out) + + cond = builder.icmp_signed('==', status, status.type(int(Status.OK))) + with builder.if_then(cond): + key = dm_key.load_from_data_pointer(builder, ptr_key) + val = dm_val.load_from_data_pointer(builder, ptr_val) + keyval = context.make_tuple(builder, keyvalty, [key, val]) + optkeyval = context.make_optional_value(builder, keyvalty, keyval) + builder.store(optkeyval, pout) + + out = builder.load(pout) + return cgutils.pack_struct(builder, [status, out]) + + return sig, codegen + + +@intrinsic +def _dict_delitem(typingctx, d, hk, ix): + """Wrap numba_dict_delitem + """ + resty = types.int32 + sig = resty(d, hk, types.intp) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_dict_type, ll_hash, ll_ssize_t], + ) + [d, hk, ix] = args + [td, thk, tix] = sig.args + + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_delitem') + + dp = _container_get_data(context, builder, td, d) + status = builder.call(fn, [dp, hk, ix]) + return status + + return sig, codegen + + +def _iterator_codegen(resty): + """The common codegen for iterator intrinsics. + + Populates the iterator struct and increfs. + """ + + def codegen(context, builder, sig, args): + [d] = args + [td] = sig.args + iterhelper = context.make_helper(builder, resty) + iterhelper.parent = d + iterhelper.state = iterhelper.state.type(None) + return impl_ret_borrowed( + context, + builder, + resty, + iterhelper._getvalue(), + ) + + return codegen + + +@intrinsic +def _dict_items(typingctx, d): + """Get dictionary iterator for .items()""" + resty = types.DictItemsIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _dict_keys(typingctx, d): + """Get dictionary iterator for .keys()""" + resty = types.DictKeysIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _dict_values(typingctx, d): + """Get dictionary iterator for .values()""" + resty = types.DictValuesIterableType(d) + sig = resty(d) + codegen = _iterator_codegen(resty) + return sig, codegen + + +@intrinsic +def _make_dict(typingctx, keyty, valty, ptr): + """Make a dictionary struct with the given *ptr* + + Parameters + ---------- + keyty, valty: Type + Type of the key and value, respectively. + ptr : llvm pointer value + Points to the dictionary object. + """ + dict_ty = types.DictType(keyty.instance_type, valty.instance_type) + + def codegen(context, builder, signature, args): + [_, _, ptr] = args + ctor = cgutils.create_struct_proxy(dict_ty) + dstruct = ctor(context, builder) + dstruct.data = ptr + + alloc_size = context.get_abi_sizeof( + context.get_value_type(types.voidptr), + ) + dtor = _imp_dtor(context, builder.module) + meminfo = context.nrt.meminfo_alloc_dtor( + builder, + context.get_constant(types.uintp, alloc_size), + dtor, + ) + + data_pointer = context.nrt.meminfo_data(builder, meminfo) + data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer()) + builder.store(ptr, data_pointer) + + dstruct.meminfo = meminfo + + return dstruct._getvalue() + + sig = dict_ty(keyty, valty, ptr) + return sig, codegen + + +@overload(new_dict) +def impl_new_dict(key, value, n_keys=0): + """Creates a new dictionary with *key* and *value* as the type + of the dictionary key and value, respectively. *n_keys* is the + number of keys to insert without requiring a resize, where a + value of 0 creates a dictionary with minimum size. + """ + if any([ + not isinstance(key, Type), + not isinstance(value, Type), + ]): + raise NumbaTypeError("expecting *key* and *value* to be a Numba Type") + + keyty, valty = key, value + + def imp(key, value, n_keys=0): + if n_keys < 0: + raise RuntimeError("expecting *n_keys* to be >= 0") + dp = _dict_new_sized(n_keys, keyty, valty) + _dict_set_method_table(dp, keyty, valty) + d = _make_dict(keyty, valty, dp) + return d + + return imp + + +@overload(len) +def impl_len(d): + """len(dict) + """ + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_length(d) + + return impl + + +@overload(len) +def impl_len_iters(d): + """len(dict.keys()), len(dict.values()), len(dict.items()) + """ + if not isinstance(d, (DictKeysIterableType, + DictValuesIterableType, DictItemsIterableType)): + return + + def impl(d): + return _dict_length(d._parent) + + return impl + + +@overload_method(types.DictType, '__setitem__') +@overload(operator.setitem) +def impl_setitem(d, key, value): + if not isinstance(d, types.DictType): + return + + keyty, valty = d.key_type, d.value_type + + def impl(d, key, value): + castedkey = _cast(key, keyty) + castedval = _cast(value, valty) + status = _dict_insert(d, castedkey, hash(castedkey), castedval) + if status == Status.OK: + return + elif status == Status.OK_REPLACED: + # replaced + # XXX handle refcount + return + elif status == Status.ERR_CMP_FAILED: + raise ValueError('key comparison failed') + else: + raise RuntimeError('dict.__setitem__ failed unexpectedly') + + if d.is_precise(): + # Handle the precise case. + return impl + else: + # Handle the imprecise case. + d = d.refine(key, value) + # Re-bind the key type and value type to match the arguments. + keyty, valty = d.key_type, d.value_type + # Create the signature that we wanted this impl to have. + sig = typing.signature(types.void, d, keyty, valty) + return sig, impl + + +@overload_method(types.DictType, 'get') +def impl_get(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + keyty = dct.key_type + valty = dct.value_type + _sentry_safe_cast_default(default, valty) + + def impl(dct, key, default=None): + castedkey = _cast(key, keyty) + ix, val = _dict_lookup(dct, castedkey, hash(castedkey)) + if ix > DKIX.EMPTY: + return val + return default + + return impl + + +@overload_attribute(types.DictType, '__hash__') +def impl_hash(dct): + if not isinstance(dct, types.DictType): + return + return lambda dct: None + + +@overload(operator.getitem) +def impl_getitem(d, key): + if not isinstance(d, types.DictType): + return + + keyty = d.key_type + + def impl(d, key): + castedkey = _cast(key, keyty) + ix, val = _dict_lookup(d, castedkey, hash(castedkey)) + if ix == DKIX.EMPTY: + raise KeyError(key) + elif ix < DKIX.EMPTY: + raise AssertionError("internal dict error during lookup") + else: + return _nonoptional(val) + + return impl + + +@overload_method(types.DictType, 'popitem') +def impl_popitem(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + status, keyval = _dict_popitem(d) + if status == Status.OK: + return _nonoptional(keyval) + elif status == Status.ERR_DICT_EMPTY: + raise KeyError() + else: + raise AssertionError('internal dict error during popitem') + + return impl + + +@overload_method(types.DictType, 'pop') +def impl_pop(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + + keyty = dct.key_type + valty = dct.value_type + should_raise = isinstance(default, types.Omitted) + _sentry_safe_cast_default(default, valty) + + def impl(dct, key, default=None): + castedkey = _cast(key, keyty) + hashed = hash(castedkey) + ix, val = _dict_lookup(dct, castedkey, hashed) + if ix == DKIX.EMPTY: + if should_raise: + raise KeyError() + else: + return default + elif ix < DKIX.EMPTY: + raise AssertionError("internal dict error during lookup") + else: + status = _dict_delitem(dct, hashed, ix) + if status != Status.OK: + raise AssertionError("internal dict error during delitem") + return val + + return impl + + +@overload(operator.delitem) +def impl_delitem(d, k): + if not isinstance(d, types.DictType): + return + + def impl(d, k): + d.pop(k) + return impl + + +@overload(operator.contains) +def impl_contains(d, k): + if not isinstance(d, types.DictType): + return + + keyty = d.key_type + + def impl(d, k): + k = _cast(k, keyty) + ix, val = _dict_lookup(d, k, hash(k)) + return ix > DKIX.EMPTY + return impl + + +@overload_method(types.DictType, 'clear') +def impl_clear(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + while len(d): + d.popitem() + + return impl + + +@overload_method(types.DictType, 'copy') +def impl_copy(d): + if not isinstance(d, types.DictType): + return + + key_type, val_type = d.key_type, d.value_type + + def impl(d): + newd = new_dict(key_type, val_type, n_keys=len(d)) + for k, v in d.items(): + newd[k] = v + return newd + + return impl + + +@overload_method(types.DictType, 'setdefault') +def impl_setdefault(dct, key, default=None): + if not isinstance(dct, types.DictType): + return + + def impl(dct, key, default=None): + if key not in dct: + dct[key] = default + return dct[key] + + return impl + + +@overload_method(types.DictType, 'items') +def impl_items(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + it = _dict_items(d) + return it + + return impl + + +@overload_method(types.DictType, 'keys') +def impl_keys(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_keys(d) + + return impl + + +@overload_method(types.DictType, 'values') +def impl_values(d): + if not isinstance(d, types.DictType): + return + + def impl(d): + return _dict_values(d) + + return impl + + +@overload_method(types.DictType, 'update') +def ol_dict_update(d, other): + if not isinstance(d, types.DictType): + return + if not isinstance(other, types.DictType): + return + + def impl(d, other): + for k, v in other.items(): + d[k] = v + return impl + + +@overload(operator.eq) +def impl_equal(da, db): + if not isinstance(da, types.DictType): + return + if not isinstance(db, types.DictType): + # If RHS is not a dictionary, always returns False + def impl_type_mismatch(da, db): + return False + return impl_type_mismatch + + otherkeyty = db.key_type + + def impl_type_matched(da, db): + if len(da) != len(db): + return False + for ka, va in da.items(): + # Cast key from LHS to the key-type of RHS + kb = _cast(ka, otherkeyty) + ix, vb = _dict_lookup(db, kb, hash(kb)) + if ix <= DKIX.EMPTY: + # Quit early if the key is not found + return False + if va != vb: + # Quit early if the values do not match + return False + return True + + return impl_type_matched + + +@overload(operator.ne) +def impl_not_equal(da, db): + if not isinstance(da, types.DictType): + return + + def impl(da, db): + return not (da == db) + + return impl + + +@lower_builtin('getiter', types.DictItemsIterableType) +@lower_builtin('getiter', types.DictKeysIterableType) +@lower_builtin('getiter', types.DictValuesIterableType) +def impl_iterable_getiter(context, builder, sig, args): + """Implement iter() for .keys(), .values(), .items() + """ + iterablety = sig.args[0] + it = context.make_helper(builder, iterablety.iterator_type, args[0]) + + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dictiter_type, ll_dict_type], + ) + + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_dict_iter') + + proto = ctypes.CFUNCTYPE(ctypes.c_size_t) + dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof']) + state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof()) + + pstate = cgutils.alloca_once(builder, state_type, zfill=True) + it.state = _as_bytes(builder, pstate) + + dp = _container_get_data(context, builder, iterablety.parent, it.parent) + builder.call(fn, [it.state, dp]) + return impl_ret_borrowed( + context, + builder, + sig.return_type, + it._getvalue(), + ) + + +@lower_builtin('getiter', types.DictType) +def impl_dict_getiter(context, builder, sig, args): + """Implement iter(Dict). Semantically equivalent to dict.keys() + """ + [td] = sig.args + [d] = args + iterablety = types.DictKeysIterableType(td) + it = context.make_helper(builder, iterablety.iterator_type) + + fnty = ir.FunctionType( + ir.VoidType(), + [ll_dictiter_type, ll_dict_type], + ) + + fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_dict_iter') + + proto = ctypes.CFUNCTYPE(ctypes.c_size_t) + dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof']) + state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof()) + + pstate = cgutils.alloca_once(builder, state_type, zfill=True) + it.state = _as_bytes(builder, pstate) + it.parent = d + + dp = _container_get_data(context, builder, iterablety.parent, args[0]) + builder.call(fn, [it.state, dp]) + return impl_ret_borrowed( + context, + builder, + sig.return_type, + it._getvalue(), + ) + + +@lower_builtin('iternext', types.DictIteratorType) +@iternext_impl(RefType.BORROWED) +def impl_iterator_iternext(context, builder, sig, args, result): + iter_type = sig.args[0] + it = context.make_helper(builder, iter_type, args[0]) + + p2p_bytes = ll_bytes.as_pointer() + + iternext_fnty = ir.FunctionType( + ll_status, + [ll_bytes, p2p_bytes, p2p_bytes] + ) + iternext = cgutils.get_or_insert_function( + builder.module, iternext_fnty, 'numba_dict_iter_next', + ) + key_raw_ptr = cgutils.alloca_once(builder, ll_bytes) + val_raw_ptr = cgutils.alloca_once(builder, ll_bytes) + + status = builder.call(iternext, (it.state, key_raw_ptr, val_raw_ptr)) + # TODO: no handling of error state i.e. mutated dictionary + # all errors are treated as exhausted iterator + is_valid = builder.icmp_unsigned('==', status, status.type(0)) + result.set_valid(is_valid) + + with builder.if_then(is_valid): + yield_type = iter_type.yield_type + key_ty, val_ty = iter_type.parent.keyvalue_type + + dm_key = context.data_model_manager[key_ty] + dm_val = context.data_model_manager[val_ty] + + key_ptr = builder.bitcast( + builder.load(key_raw_ptr), + dm_key.get_data_type().as_pointer(), + ) + val_ptr = builder.bitcast( + builder.load(val_raw_ptr), + dm_val.get_data_type().as_pointer(), + ) + + key = dm_key.load_from_data_pointer(builder, key_ptr) + val = dm_val.load_from_data_pointer(builder, val_ptr) + + # All dict iterators use this common implementation. + # Their differences are resolved here. + if isinstance(iter_type.iterable, DictItemsIterableType): + # .items() + tup = context.make_tuple(builder, yield_type, [key, val]) + result.yield_(tup) + elif isinstance(iter_type.iterable, DictKeysIterableType): + # .keys() + result.yield_(key) + elif isinstance(iter_type.iterable, DictValuesIterableType): + # .values() + result.yield_(val) + else: + # unreachable + raise AssertionError('unknown type: {}'.format(iter_type.iterable)) + + +def build_map(context, builder, dict_type, item_types, items): + + if isinstance(dict_type, types.LiteralStrKeyDict): + unliteral_tys = [x for x in + dict_type.literal_value.values()] + nbty = types.NamedTuple(unliteral_tys, + dict_type.tuple_ty) + values = [x[1] for x in items] + # replace with make_tuple call? + tup = context.get_constant_undef(nbty) + literal_tys = [x for x in dict_type.literal_value.values()] + + # this is to deal with repeated keys + value_index = dict_type.value_index + if value_index is None: + # 1:1 map keys:values + value_indexer = range(len(values)) + else: + # 1:>1 map keys:values, e.g. {'a':1, 'a': 'foo'} + value_indexer = value_index.values() + + for i, ix in enumerate(value_indexer): + val = values[ix] + casted = context.cast(builder, val, literal_tys[i], + unliteral_tys[i]) + tup = builder.insert_value(tup, casted, i) + d = tup + context.nrt.incref(builder, nbty, d) + + else: + from numba.typed import Dict + + dt = types.DictType(dict_type.key_type, dict_type.value_type) + kt, vt = dict_type.key_type, dict_type.value_type + sig = typing.signature(dt) + + def make_dict(): + return Dict.empty(kt, vt) + + d = context.compile_internal(builder, make_dict, sig, ()) + + if items: + for (kt, vt), (k, v) in zip(item_types, items): + sig = typing.signature(types.void, dt, kt, vt) + args = d, k, v + + def put(d, k, v): + d[k] = v + + context.compile_internal(builder, put, sig, args) + + return d + + +# ------------------------------------------------------------------------------ +# Literal dictionaries +# ------------------------------------------------------------------------------ + +@intrinsic +def _mixed_values_to_tuple(tyctx, d): + keys = [x for x in d.literal_value.keys()] + literal_tys = [x for x in d.literal_value.values()] + + def impl(cgctx, builder, sig, args): + lld, = args + impl = cgctx.get_function('static_getitem', + types.none(d, types.literal('dummy'))) + items = [] + for k in range(len(keys)): + item = impl(builder, (lld, k),) + casted = cgctx.cast(builder, item, literal_tys[k], d.types[k]) + items.append(casted) + cgctx.nrt.incref(builder, d.types[k], item) + ret = cgctx.make_tuple(builder, sig.return_type, items) + return ret + sig = types.Tuple(d.types)(d) + return sig, impl + + +@overload_method(types.LiteralStrKeyDict, 'values') +def literalstrkeydict_impl_values(d): + # This requires faking a values() iterator simply as a tuple, creating a + # type specialising iterator would be possible but horrendous and end up + # down the "versioned" loop body route. + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return _mixed_values_to_tuple(d) + return impl + + +@overload_method(types.LiteralStrKeyDict, 'keys') +def literalstrkeydict_impl_keys(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + # create a key iterator by specialising a DictType instance with the + # literal keys and returning that + t = tuple([x.literal_value for x in d.literal_value.keys()]) + + def impl(d): + d = dict() + for x in t: + d[x] = 0 + return d.keys() + return impl + + +# have to lower_builtin as this inherits from tuple and literal, both of which +# provide a match, hence ambiguous before proper resolution gets a chance +@lower_builtin(operator.eq, types.LiteralStrKeyDict, types.LiteralStrKeyDict) +def literalstrkeydict_impl_equals(context, builder, sig, args): + tu, tv = sig.args + u, v = args + pred = tu.literal_value == tv.literal_value + res = context.get_constant(types.boolean, pred) + return impl_ret_untracked(context, builder, sig.return_type, res) + + +@overload(operator.getitem) +@overload_method(types.LiteralStrKeyDict, 'get') +def literalstrkeydict_impl_get(dct, *args): + if not isinstance(dct, types.LiteralStrKeyDict): + return + msg = ("Cannot get{item}() on a literal dictionary, return type cannot be " + "statically determined") + raise TypingError(msg) + + +@overload_method(types.LiteralStrKeyDict, 'copy') +def literalstrkeydict_impl_copy(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return d + return impl + + +@intrinsic +def _str_items_mixed_values_to_tuple(tyctx, d): + keys = [x for x in d.literal_value.keys()] + literal_tys = [x for x in d.literal_value.values()] + + def impl(cgctx, builder, sig, args): + + lld, = args + impl = cgctx.get_function('static_getitem', + types.none(d, types.literal('dummy'))) + items = [] + from numba.cpython.unicode import make_string_from_constant + for k in range(len(keys)): + item = impl(builder, (lld, k),) + casted = cgctx.cast(builder, item, literal_tys[k], d.types[k]) + cgctx.nrt.incref(builder, d.types[k], item) + keydata = make_string_from_constant(cgctx, builder, + types.unicode_type, + keys[k].literal_value) + pair = cgctx.make_tuple(builder, + types.Tuple([types.unicode_type, + d.types[k]]), (keydata, casted)) + items.append(pair) + ret = cgctx.make_tuple(builder, sig.return_type, items) + return ret + kvs = [types.Tuple((types.unicode_type, x)) for x in d.types] + sig = types.Tuple(kvs)(d) + return sig, impl + + +@overload_method(types.LiteralStrKeyDict, 'items') +def literalstrkeydict_impl_items(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d): + return _str_items_mixed_values_to_tuple(d) + return impl + + +@overload(operator.contains) +def literalstrkeydict_impl_contains(d, k): + if not isinstance(d, types.LiteralStrKeyDict): + return + + def impl(d, k): + for key in d.keys(): + if k == key: + return True + return False + return impl + + +@overload(len) +def literalstrkeydict_impl_len(d): + if not isinstance(d, types.LiteralStrKeyDict): + return + l = d.count + return lambda d: l + + +@overload(operator.setitem) +def literalstrkeydict_banned_impl_setitem(d, key, value): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@overload(operator.delitem) +def literalstrkeydict_banned_impl_delitem(d, k): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@overload_method(types.LiteralStrKeyDict, 'popitem') +@overload_method(types.LiteralStrKeyDict, 'pop') +@overload_method(types.LiteralStrKeyDict, 'clear') +@overload_method(types.LiteralStrKeyDict, 'setdefault') +@overload_method(types.LiteralStrKeyDict, 'update') +def literalstrkeydict_banned_impl_mutators(d, *args): + if not isinstance(d, types.LiteralStrKeyDict): + return + raise TypingError("Cannot mutate a literal dictionary") + + +@lower_cast(types.LiteralStrKeyDict, types.LiteralStrKeyDict) +def cast_LiteralStrKeyDict_LiteralStrKeyDict(context, builder, fromty, toty, + val): + # should have been picked up by typing + for (k1, v1), (k2, v2) in zip(fromty.literal_value.items(), + toty.literal_value.items()): + # these checks are just guards, typing should have picked up any + # problems + if k1 != k2: # keys must be same + msg = "LiteralDictionary keys are not the same {} != {}" + raise LoweringError(msg.format(k1, k2)) + # values must be same ty + if context.typing_context.unify_pairs(v1, v2) is None: + msg = "LiteralDictionary values cannot by unified, have {} and {}" + raise LoweringError(msg.format(v1, v2)) + else: + fromty = types.Tuple(fromty.types) + toty = types.Tuple(toty.types) + olditems = cgutils.unpack_tuple(builder, val, len(fromty)) + items = [context.cast(builder, v, f, t) + for v, f, t in zip(olditems, fromty, toty)] + return context.make_tuple(builder, toty, items) + + +@lower_cast(types.DictType, types.DictType) +def cast_DictType_DictType(context, builder, fromty, toty, val): + # should have been picked up by typing + return val diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/listobject.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/listobject.py new file mode 100644 index 0000000000000000000000000000000000000000..d4309bf11e4f1b98a5a9c2c676ec2ca48274bdfb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/listobject.py @@ -0,0 +1,1538 @@ +""" +Compiler-side implementation of the Numba typed-list. +""" +import operator +from enum import IntEnum + +from llvmlite import ir + +from numba.core.extending import ( + overload, + overload_method, + overload_attribute, + register_jitable, + intrinsic, + register_model, + models, + lower_builtin, +) +from numba.core.imputils import iternext_impl +from numba.core import types, cgutils +from numba.core.types import ( + ListType, + ListTypeIterableType, + ListTypeIteratorType, + Type, + NoneType, +) +from numba.core.imputils import impl_ret_borrowed, RefType +from numba.core.errors import TypingError, NumbaTypeError +from numba.core import typing +from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional, + _get_incref_decref, + _container_get_data, + _container_get_meminfo,) +from numba.cpython import listobj + +ll_list_type = cgutils.voidptr_t +ll_listiter_type = cgutils.voidptr_t +ll_voidptr_type = cgutils.voidptr_t +ll_status = cgutils.int32_t +ll_ssize_t = cgutils.intp_t +ll_bytes = cgutils.voidptr_t + + +_meminfo_listptr = types.MemInfoPointer(types.voidptr) + +INDEXTY = types.intp + +index_types = types.integer_domain + +DEFAULT_ALLOCATED = 0 + + +@register_model(ListType) +class ListModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('meminfo', _meminfo_listptr), + ('data', types.voidptr), # ptr to the C list + ] + super(ListModel, self).__init__(dmm, fe_type, members) + + +@register_model(ListTypeIterableType) +@register_model(ListTypeIteratorType) +class ListIterModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('size', types.intp), # the size of the iteration space + ('parent', fe_type.parent), # the parent list + ('index', types.EphemeralPointer(types.intp)), # current index + ] + super(ListIterModel, self).__init__(dmm, fe_type, members) + + +class ListStatus(IntEnum): + """Status code for other list operations. + """ + LIST_OK = 0, + LIST_ERR_INDEX = -1 + LIST_ERR_NO_MEMORY = -2 + LIST_ERR_MUTATED = -3 + LIST_ERR_ITER_EXHAUSTED = -4 + LIST_ERR_IMMUTABLE = -5 + + +class ErrorHandler(object): + """ErrorHandler for calling codegen functions from this file. + + Stores the state needed to raise an exception from nopython mode. + """ + + def __init__(self, context): + self.context = context + + def __call__(self, builder, status, msg): + ok_status = status.type(int(ListStatus.LIST_OK)) + with builder.if_then(builder.icmp_signed('!=', status, ok_status), + likely=True): + self.context.call_conv.return_user_exc( + builder, RuntimeError, (msg,)) + + +def _check_for_none_typed(lst, method): + if isinstance(lst.dtype, NoneType): + raise TypingError("method support for List[None] is limited, " + "not supported: '{}'.".format(method)) + + +@intrinsic +def _as_meminfo(typingctx, lstobj): + """Returns the MemInfoPointer of a list. + """ + if not isinstance(lstobj, types.ListType): + raise TypingError('expected *lstobj* to be a ListType') + + def codegen(context, builder, sig, args): + [tl] = sig.args + [l] = args + # Incref + context.nrt.incref(builder, tl, l) + ctor = cgutils.create_struct_proxy(tl) + lstruct = ctor(context, builder, value=l) + # Returns the plain MemInfo + return lstruct.meminfo + + sig = _meminfo_listptr(lstobj) + return sig, codegen + + +@intrinsic +def _from_meminfo(typingctx, mi, listtyperef): + """Recreate a list from a MemInfoPointer + """ + if mi != _meminfo_listptr: + raise TypingError('expected a MemInfoPointer for list.') + listtype = listtyperef.instance_type + if not isinstance(listtype, ListType): + raise TypingError('expected a {}'.format(ListType)) + + def codegen(context, builder, sig, args): + [tmi, tdref] = sig.args + td = tdref.instance_type + [mi, _] = args + + ctor = cgutils.create_struct_proxy(td) + dstruct = ctor(context, builder) + + data_pointer = context.nrt.meminfo_data(builder, mi) + data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer()) + + dstruct.data = builder.load(data_pointer) + dstruct.meminfo = mi + + return impl_ret_borrowed( + context, + builder, + listtype, + dstruct._getvalue(), + ) + + sig = listtype(mi, listtyperef) + return sig, codegen + + +def _list_codegen_set_method_table(context, builder, lp, itemty): + vtablety = ir.LiteralStructType([ + ll_voidptr_type, # item incref + ll_voidptr_type, # item decref + ]) + setmethod_fnty = ir.FunctionType( + ir.VoidType(), + [ll_list_type, vtablety.as_pointer()] + ) + + setmethod_fn = cgutils.get_or_insert_function( + builder.module, + setmethod_fnty, + 'numba_list_set_method_table') + vtable = cgutils.alloca_once(builder, vtablety, zfill=True) + + # install item incref/decref + item_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0) + item_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1) + + dm_item = context.data_model_manager[itemty] + if dm_item.contains_nrt_meminfo(): + item_incref, item_decref = _get_incref_decref( + context, builder.module, dm_item, "list" + ) + builder.store( + builder.bitcast(item_incref, item_incref_ptr.type.pointee), + item_incref_ptr, + ) + builder.store( + builder.bitcast(item_decref, item_decref_ptr.type.pointee), + item_decref_ptr, + ) + + builder.call(setmethod_fn, [lp, vtable]) + + +@intrinsic +def _list_set_method_table(typingctx, lp, itemty): + """Wrap numba_list_set_method_table + """ + resty = types.void + sig = resty(lp, itemty) + + def codegen(context, builder, sig, args): + _list_codegen_set_method_table( + context, builder, args[0], itemty.instance_type) + + return sig, codegen + + +@lower_builtin(operator.is_, types.ListType, types.ListType) +def list_is(context, builder, sig, args): + a_meminfo = _container_get_meminfo(context, builder, sig.args[0], args[0]) + b_meminfo = _container_get_meminfo(context, builder, sig.args[1], args[1]) + ma = builder.ptrtoint(a_meminfo, cgutils.intp_t) + mb = builder.ptrtoint(b_meminfo, cgutils.intp_t) + return builder.icmp_signed('==', ma, mb) + + +def _call_list_free(context, builder, ptr): + """Call numba_list_free(ptr) + """ + fnty = ir.FunctionType( + ir.VoidType(), + [ll_list_type], + ) + free = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_free') + builder.call(free, [ptr]) + + +# FIXME: this needs a careful review +def _imp_dtor(context, module): + """Define the dtor for list + """ + llvoidptr = context.get_value_type(types.voidptr) + llsize = context.get_value_type(types.uintp) + fnty = ir.FunctionType( + ir.VoidType(), + [llvoidptr, llsize, llvoidptr], + ) + fname = '_numba_list_dtor' + fn = cgutils.get_or_insert_function(module, fnty, fname) + + if fn.is_declaration: + # Set linkage + fn.linkage = 'linkonce_odr' + # Define + builder = ir.IRBuilder(fn.append_basic_block()) + lp = builder.bitcast(fn.args[0], ll_list_type.as_pointer()) + l = builder.load(lp) + _call_list_free(context, builder, l) + builder.ret_void() + + return fn + + +def new_list(item, allocated=DEFAULT_ALLOCATED): + """Construct a new list. (Not implemented in the interpreter yet) + + Parameters + ---------- + item: TypeRef + Item type of the new list. + allocated: int + number of items to pre-allocate + + """ + # With JIT disabled, ignore all arguments and return a Python list. + return list() + + +def _add_meminfo(context, builder, lstruct): + alloc_size = context.get_abi_sizeof( + context.get_value_type(types.voidptr), + ) + dtor = _imp_dtor(context, builder.module) + meminfo = context.nrt.meminfo_alloc_dtor( + builder, + context.get_constant(types.uintp, alloc_size), + dtor, + ) + + data_pointer = context.nrt.meminfo_data(builder, meminfo) + data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer()) + builder.store(lstruct.data, data_pointer) + lstruct.meminfo = meminfo + + +@intrinsic +def _make_list(typingctx, itemty, ptr): + """Make a list struct with the given *ptr* + + Parameters + ---------- + itemty: Type + Type of the item. + ptr : llvm pointer value + Points to the list object. + """ + list_ty = types.ListType(itemty.instance_type) + + def codegen(context, builder, signature, args): + ptr = args[1] + ctor = cgutils.create_struct_proxy(list_ty) + lstruct = ctor(context, builder) + lstruct.data = ptr + _add_meminfo(context, builder, lstruct) + return lstruct._getvalue() + + sig = list_ty(itemty, ptr) + return sig, codegen + + +def _list_new_codegen(context, builder, itemty, new_size, error_handler): + fnty = ir.FunctionType( + ll_status, + [ll_list_type.as_pointer(), ll_ssize_t, ll_ssize_t], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_list_new') + # Determine sizeof item types + ll_item = context.get_data_type(itemty) + sz_item = context.get_abi_sizeof(ll_item) + reflp = cgutils.alloca_once(builder, ll_list_type, zfill=True) + status = builder.call( + fn, + [reflp, ll_ssize_t(sz_item), new_size], + ) + msg = "Failed to allocate list" + error_handler( + builder, + status, + msg, + ) + lp = builder.load(reflp) + return lp + + +@intrinsic +def _list_new(typingctx, itemty, allocated): + """Wrap numba_list_new. + + Allocate a new list object with zero capacity. + + Parameters + ---------- + itemty: Type + Type of the items + allocated: int + number of items to pre-allocate + + """ + resty = types.voidptr + sig = resty(itemty, allocated) + + def codegen(context, builder, sig, args): + error_handler = ErrorHandler(context) + return _list_new_codegen(context, + builder, + itemty.instance_type, + args[1], + error_handler, + ) + + return sig, codegen + + +@overload(new_list) +def impl_new_list(item, allocated=DEFAULT_ALLOCATED): + """Creates a new list. + + Parameters + ---------- + item: Numba type + type of the list item. + allocated: int + number of items to pre-allocate + + """ + if not isinstance(item, Type): + raise NumbaTypeError("expecting *item* to be a Numba Type") + + itemty = item + + def imp(item, allocated=DEFAULT_ALLOCATED): + if allocated < 0: + raise RuntimeError("expecting *allocated* to be >= 0") + lp = _list_new(itemty, allocated) + _list_set_method_table(lp, itemty) + l = _make_list(itemty, lp) + return l + + return imp + + +@overload(len) +def impl_len(l): + """len(list) + """ + if isinstance(l, types.ListType): + def impl(l): + return _list_length(l) + + return impl + + +@intrinsic +def _list_length(typingctx, l): + """Wrap numba_list_length + + Returns the length of the list. + """ + sig = types.intp(l) + + def codegen(context, builder, sig, args): + [tl] = sig.args + [l] = args + fnty = ir.FunctionType( + ll_ssize_t, + [ll_list_type], + ) + fname = 'numba_list_size_address' + fn = cgutils.get_or_insert_function(builder.module, fnty, fname) + fn.attributes.add('alwaysinline') + fn.attributes.add('readonly') + fn.attributes.add('nounwind') + lp = _container_get_data(context, builder, tl, l) + len_addr = builder.call(fn, [lp,],) + ptr = builder.inttoptr(len_addr, cgutils.intp_t.as_pointer()) + return builder.load(ptr) + + return sig, codegen + + +@overload_method(types.ListType, "_allocated") +def impl_allocated(l): + """list._allocated() + """ + if isinstance(l, types.ListType): + def impl(l): + return _list_allocated(l) + + return impl + + +@intrinsic +def _list_allocated(typingctx, l): + """Wrap numba_list_allocated + + Returns the allocation of the list. + """ + resty = types.intp + sig = resty(l) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_ssize_t, + [ll_list_type], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_allocated') + [l] = args + [tl] = sig.args + lp = _container_get_data(context, builder, tl, l) + n = builder.call(fn, [lp]) + return n + + return sig, codegen + + +@overload_method(types.ListType, "_is_mutable") +def impl_is_mutable(l): + """list._is_mutable()""" + if isinstance(l, types.ListType): + def impl(l): + return bool(_list_is_mutable(l)) + + return impl + + +@intrinsic +def _list_is_mutable(typingctx, l): + """Wrap numba_list_is_mutable + + Returns the state of the is_mutable member + """ + resty = types.int32 + sig = resty(l) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_list_type], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_is_mutable') + [l] = args + [tl] = sig.args + lp = _container_get_data(context, builder, tl, l) + n = builder.call(fn, [lp]) + return n + + return sig, codegen + + +@overload_method(types.ListType, "_make_mutable") +def impl_make_mutable(l): + """list._make_mutable()""" + if isinstance(l, types.ListType): + def impl(l): + _list_set_is_mutable(l, 1) + + return impl + + +@overload_method(types.ListType, "_make_immutable") +def impl_make_immutable(l): + """list._make_immutable()""" + if isinstance(l, types.ListType): + def impl(l): + _list_set_is_mutable(l, 0) + + return impl + + +@intrinsic +def _list_set_is_mutable(typingctx, l, is_mutable): + """Wrap numba_list_set_mutable + + Sets the state of the is_mutable member. + """ + resty = types.void + sig = resty(l, is_mutable) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ir.VoidType(), + [ll_list_type, cgutils.intp_t], + ) + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_set_is_mutable') + [l, i] = args + [tl, ti] = sig.args + lp = _container_get_data(context, builder, tl, l) + builder.call(fn, [lp, i]) + + return sig, codegen + + +@intrinsic +def _list_append(typingctx, l, item): + """Wrap numba_list_append + """ + resty = types.int32 + sig = resty(l, l.item_type) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_list_type, ll_bytes], + ) + [l, item] = args + [tl, titem] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_append') + + dm_item = context.data_model_manager[titem] + + data_item = dm_item.as_data(builder, item) + + ptr_item = cgutils.alloca_once_value(builder, data_item) + + lp = _container_get_data(context, builder, tl, l) + status = builder.call( + fn, + [ + lp, + _as_bytes(builder, ptr_item), + ], + ) + return status + + return sig, codegen + + +@overload_method(types.ListType, 'append') +def impl_append(l, item): + if not isinstance(l, types.ListType): + return + + itemty = l.item_type + + def impl(l, item): + casteditem = _cast(item, itemty) + status = _list_append(l, casteditem) + if status == ListStatus.LIST_OK: + return + elif status == ListStatus.LIST_ERR_IMMUTABLE: + raise ValueError('list is immutable') + elif status == ListStatus.LIST_ERR_NO_MEMORY: + raise MemoryError('Unable to allocate memory to append item') + else: + raise RuntimeError('list.append failed unexpectedly') + + if l.is_precise(): + # Handle the precise case. + return impl + else: + # Handle the imprecise case. + l = l.refine(item) + # Re-bind the item type to match the arguments. + itemty = l.item_type + # Create the signature that we wanted this impl to have. + sig = typing.signature(types.void, l, itemty) + return sig, impl + + +@intrinsic +def fix_index(tyctx, list_ty, index_ty): + sig = types.intp(list_ty, index_ty) + + def codegen(context, builder, sig, args): + [list_ty, index_ty] = sig.args + [ll_list, ll_idx] = args + is_negative = builder.icmp_signed('<', ll_idx, + ir.Constant(ll_idx.type, 0)) + fast_len_sig, length_fn = _list_length._defn(context.typing_context, + list_ty) + length = length_fn(context, builder, fast_len_sig, (ll_list,)) + # length is an intp + # index can be any sort of int + # indexing in general is done with a ssize_t which correlates to an + # intp. In llvmlite sext and trunc are guarded to return the value + # itself if the types are the same, so there's no need to handle the + # "equal widths" case separately. This sexts/truncs the index to the + # length type such that `add` works for the wraparound case. + st = 'sext' if ll_idx.type.width < length.type.width else 'trunc' + op = getattr(builder, st) + fixedup_idx = op(ll_idx, length.type) + wrapped_index = builder.add(fixedup_idx, length) + return builder.select(is_negative, wrapped_index, fixedup_idx) + return sig, codegen + + +@register_jitable +def handle_index(l, index): + """Handle index. + + If the index is negative, convert it. If the index is out of range, raise + an IndexError. + """ + # convert negative indices to positive ones + index = fix_index(l, index) + # check that the index is in range + if index < 0 or index >= len(l): + raise IndexError("list index out of range") + return index + + +@register_jitable +def handle_slice(l, s): + """Handle slice. + + Convert a slice object for a given list into a range object that can be + used to index the list. Many subtle caveats here, especially if the step is + negative. + """ + if len(l) == 0: # ignore slice for empty list + return range(0) + ll, sa, so, se = len(l), s.start, s.stop, s.step + if se > 0: + start = max(ll + sa, 0) if s.start < 0 else min(ll, sa) + stop = max(ll + so, 0) if so < 0 else min(ll, so) + elif se < 0: + start = max(ll + sa, -1) if s.start < 0 else min(ll - 1, sa) + stop = max(ll + so, -1) if so < 0 else min(ll, so) + else: + # should be caught earlier, but isn't, so we raise here + raise ValueError("slice step cannot be zero") + return range(start, stop, s.step) + + +def _gen_getitem(borrowed): + + @intrinsic + def impl(typingctx, l_ty, index_ty): + + is_none = isinstance(l_ty.item_type, types.NoneType) + if is_none: + resty = types.Tuple([types.int32, l_ty.item_type]) + else: + resty = types.Tuple([types.int32, types.Optional(l_ty.item_type)]) + sig = resty(l_ty, index_ty) + + def codegen(context, builder, sig, args): + [tl, tindex] = sig.args + [l, index] = args + fnty = ir.FunctionType( + ll_voidptr_type, + [ll_list_type], + ) + fname = 'numba_list_base_ptr' + fn = cgutils.get_or_insert_function(builder.module, fnty, fname) + fn.attributes.add('alwaysinline') + fn.attributes.add('nounwind') + fn.attributes.add('readonly') + + lp = _container_get_data(context, builder, tl, l) + + base_ptr = builder.call( + fn, + [lp,], + ) + + llty = context.get_data_type(tl.item_type) + casted_base_ptr = builder.bitcast(base_ptr, llty.as_pointer()) + + item_ptr = cgutils.gep(builder, casted_base_ptr, index) + + if is_none: + out = builder.load(item_ptr) + else: + out = context.make_optional_none(builder, tl.item_type) + pout = cgutils.alloca_once_value(builder, out) + + dm_item = context.data_model_manager[tl.item_type] + item = dm_item.load_from_data_pointer(builder, item_ptr) + if not borrowed: + context.nrt.incref(builder, tl.item_type, item) + + if is_none: + loaded = item + else: + loaded = context.make_optional_value(builder, tl.item_type, + item) + builder.store(loaded, pout) + + out = builder.load(pout) + return context.make_tuple(builder, resty, [ll_status(0), out]) + + return sig, codegen + return impl + + +_list_getitem = _gen_getitem(False) +_list_getitem_borrowed = _gen_getitem(True) + + +@overload(operator.getitem) +def impl_getitem(l, index): + if not isinstance(l, types.ListType): + return + + indexty = INDEXTY + itemty = l.item_type + IS_NOT_NONE = not isinstance(l.item_type, types.NoneType) + + if index in index_types: + if IS_NOT_NONE: + def integer_non_none_impl(l, index): + castedindex = _cast(index, indexty) + handledindex = handle_index(l, castedindex) + status, item = _list_getitem(l, handledindex) + if status == ListStatus.LIST_OK: + return _nonoptional(item) + else: + raise AssertionError("internal list error during getitem") + return integer_non_none_impl + else: + def integer_none_impl(l, index): + index = handle_index(l, index) + return None + return integer_none_impl + + elif isinstance(index, types.SliceType): + def slice_impl(l, index): + newl = new_list(itemty) + for i in handle_slice(l, index): + newl.append(l[i]) + return newl + + return slice_impl + + else: + raise TypingError("list indices must be integers or slices") + + +@intrinsic +def _list_setitem(typingctx, l, index, item): + """Wrap numba_list_setitem + """ + resty = types.int32 + sig = resty(l, index, item) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_list_type, ll_ssize_t, ll_bytes], + ) + [l, index, item] = args + [tl, tindex, titem] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_setitem') + + dm_item = context.data_model_manager[titem] + data_item = dm_item.as_data(builder, item) + ptr_item = cgutils.alloca_once_value(builder, data_item) + + lp = _container_get_data(context, builder, tl, l) + status = builder.call( + fn, + [ + lp, + index, + _as_bytes(builder, ptr_item), + ], + ) + return status + + return sig, codegen + + +@overload(operator.setitem) +def impl_setitem(l, index, item): + if not isinstance(l, types.ListType): + return + + indexty = INDEXTY + itemty = l.item_type + + if index in index_types: + def impl_integer(l, index, item): + index = handle_index(l, index) + castedindex = _cast(index, indexty) + casteditem = _cast(item, itemty) + status = _list_setitem(l, castedindex, casteditem) + if status == ListStatus.LIST_OK: + return + elif status == ListStatus.LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + else: + raise AssertionError("internal list error during settitem") + + return impl_integer + + elif isinstance(index, types.SliceType): + if not isinstance(item, types.IterableType): + raise TypingError("can only assign an iterable when using a slice " + "with assignment/setitem") + + def impl_slice(l, index, item): + if not l._is_mutable(): + raise ValueError("list is immutable") + # special case "a[i:j] = a", need to copy first + if l is item: + item = item.copy() + slice_range = handle_slice(l, index) + # non-extended (simple) slices + if slice_range.step == 1: + # replace + if len(item) == len(slice_range): + for i, j in zip(slice_range, item): + l[i] = j + # replace and insert + if len(item) > len(slice_range): + # do the replaces we can + for i, j in zip(slice_range, item[:len(slice_range)]): + l[i] = j + # insert the remaining ones + insert_range = range(slice_range.stop, + slice_range.stop + + len(item) - len(slice_range)) + for i, k in zip(insert_range, item[len(slice_range):]): + # FIXME: This may be slow. Each insert can incur a + # memory copy of one or more items. + l.insert(i, k) + # replace and delete + if len(item) < len(slice_range): + # do the replaces we can + replace_range = range(slice_range.start, + slice_range.start + len(item)) + for i,j in zip(replace_range, item): + l[i] = j + # delete remaining ones + del l[slice_range.start + len(item):slice_range.stop] + # Extended slices + else: + if len(slice_range) != len(item): + raise ValueError("length mismatch for extended slice " + "and sequence") + # extended slice can only replace + for i, j in zip(slice_range, item): + l[i] = j + + return impl_slice + + else: + raise TypingError("list indices must be integers or slices") + + +@overload_method(types.ListType, 'pop') +def impl_pop(l, index=-1): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'pop') + + indexty = INDEXTY + + # FIXME: this type check works, but it isn't clear why and if it optimal + if (isinstance(index, int) + or index in index_types + or isinstance(index, types.Omitted)): + def impl(l, index=-1): + if len(l) == 0: + raise IndexError("pop from empty list") + cindex = _cast(handle_index(l, index), indexty) + item = l[cindex] + del l[cindex] + return item + return impl + + else: + raise TypingError("argument for pop must be an integer") + + +@intrinsic +def _list_delitem(typingctx, l, index): + resty = types.int32 + sig = resty(l, index) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_list_type, ll_ssize_t], + ) + [tl, tindex] = sig.args + [l, index] = args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_delitem') + + lp = _container_get_data(context, builder, tl, l) + status = builder.call(fn, [lp, index]) + return status + + return sig, codegen + + +@intrinsic +def _list_delete_slice(typingctx, l, start, stop, step): + """Wrap numba_list_delete_slice + """ + resty = types.int32 + sig = resty(l, start, stop, step) + + def codegen(context, builder, sig, args): + fnty = ir.FunctionType( + ll_status, + [ll_list_type, ll_ssize_t, ll_ssize_t, ll_ssize_t], + ) + [l, start, stop, step] = args + [tl, tstart, tstop, tstep] = sig.args + fn = cgutils.get_or_insert_function(builder.module, fnty, + 'numba_list_delete_slice') + + lp = _container_get_data(context, builder, tl, l) + status = builder.call( + fn, + [ + lp, + start, + stop, + step, + ], + ) + return status + + return sig, codegen + + +@overload(operator.delitem) +def impl_delitem(l, index): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'delitem') + + if index in index_types: + def integer_impl(l, index): + cindex = _cast(handle_index(l, index), INDEXTY) + status = _list_delitem(l, cindex) + if status == ListStatus.LIST_OK: + return + elif status == ListStatus.LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + else: + raise AssertionError("internal list error during delitem") + return integer_impl + + elif isinstance(index, types.SliceType): + def slice_impl(l, index): + slice_range = handle_slice(l, index) + status = _list_delete_slice( + l, + slice_range.start, + slice_range.stop, + slice_range.step) + if status == ListStatus.LIST_ERR_MUTATED: + raise ValueError("list is immutable") + return slice_impl + + else: + raise TypingError("list indices must be integers or slices") + + +@overload(operator.contains) +def impl_contains(l, item): + if not isinstance(l, types.ListType): + return + + itemty = l.item_type + _check_for_none_typed(l, "__contains__") + + def impl(l, item): + casteditem = _cast(item, itemty) + for i in l: + if i == casteditem: + return True + else: + return False + return impl + + +@overload_method(types.ListType, 'count') +def impl_count(l, item): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'count') + + itemty = l.item_type + + def impl(l, item): + casteditem = _cast(item, itemty) + total = 0 + for i in l: + if i == casteditem: + total += 1 + return total + + return impl + + +@overload_method(types.ListType, 'extend') +def impl_extend(l, iterable): + if not isinstance(l, types.ListType): + return + if not isinstance(iterable, types.IterableType): + raise TypingError("extend argument must be iterable") + + _check_for_none_typed(l, 'extend') + + def select_impl(): + if isinstance(iterable, types.ListType): + def impl(l, iterable): + if not l._is_mutable(): + raise ValueError("list is immutable") + # guard against l.extend(l) + if l is iterable: + iterable = iterable.copy() + for i in iterable: + l.append(i) + + return impl + else: + def impl(l, iterable): + for i in iterable: + l.append(i) + + return impl + + if l.is_precise(): + # Handle the precise case. + return select_impl() + else: + # Handle the imprecise case, try to 'guess' the underlying type of the + # values in the iterable. + if hasattr(iterable, "dtype"): # tuples and arrays + ty = iterable.dtype + elif hasattr(iterable, "item_type"): # lists + ty = iterable.item_type + elif hasattr(iterable, "yield_type"): # iterators and generators + ty = iterable.yield_type + elif isinstance(iterable, types.UnicodeType): + ty = iterable + else: + raise TypingError("unable to extend list, iterable is missing " + "either *dtype*, *item_type* or *yield_type*.") + l = l.refine(ty) + # Create the signature that we wanted this impl to have + sig = typing.signature(types.void, l, iterable) + return sig, select_impl() + + +@overload_method(types.ListType, 'insert') +def impl_insert(l, index, item): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'insert') + # insert can refine + if isinstance(item, NoneType): + raise TypingError("method support for List[None] is limited") + + if index in index_types: + def impl(l, index, item): + # If the index is larger than the size of the list or if the list is + # empty, just append. + if index >= len(l) or len(l) == 0: + l.append(item) + # Else, do the insert dance + else: + # convert negative indices + if index < 0: + # if the index is still negative after conversion, use 0 + index = max(len(l) + index, 0) + # grow the list by one, make room for item to insert + l.append(l[0]) + # reverse iterate over the list and shift all elements + i = len(l) - 1 + while (i > index): + l[i] = l[i - 1] + i -= 1 + # finally, insert the item + l[index] = item + + if l.is_precise(): + # Handle the precise case. + return impl + else: + # Handle the imprecise case + l = l.refine(item) + # Re-bind the item type to match the arguments. + itemty = l.item_type + # Create the signature that we wanted this impl to have. + sig = typing.signature(types.void, l, INDEXTY, itemty) + return sig, impl + else: + raise TypingError("list insert indices must be integers") + + +@overload_method(types.ListType, 'remove') +def impl_remove(l, item): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'remove') + + itemty = l.item_type + + def impl(l, item): + casteditem = _cast(item, itemty) + for i, n in enumerate(l): + if casteditem == n: + del l[i] + return + else: + raise ValueError("list.remove(x): x not in list") + + return impl + + +@overload_method(types.ListType, 'clear') +def impl_clear(l): + if not isinstance(l, types.ListType): + return + + def impl(l): + while len(l): + del l[-1] + + return impl + + +@overload_method(types.ListType, 'reverse') +def impl_reverse(l): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'reverse') + + def impl(l): + if not l._is_mutable(): + raise ValueError("list is immutable") + front = 0 + back = len(l) - 1 + while front < back: + l[front], l[back] = l[back], l[front] + front += 1 + back -= 1 + + return impl + + +@overload_method(types.ListType, 'copy') +def impl_copy(l): + + _check_for_none_typed(l, 'copy') + + itemty = l.item_type + + if isinstance(l, types.ListType): + def impl(l): + newl = new_list(itemty, len(l)) + for i in l: + newl.append(i) + return newl + + return impl + + +@overload_method(types.ListType, 'index') +def impl_index(l, item, start=None, end=None): + if not isinstance(l, types.ListType): + return + + _check_for_none_typed(l, 'index') + + itemty = l.item_type + + def check_arg(arg, name): + if not (arg is None + or arg in index_types + or isinstance(arg, (types.Omitted, types.NoneType))): + raise TypingError("{} argument for index must be an integer" + .format(name)) + check_arg(start, "start") + check_arg(end, "end") + + def impl(l, item, start=None, end=None): + casteditem = _cast(item, itemty) + for i in handle_slice(l, slice(start, end, 1)): + if l[i] == casteditem: + return i + else: + raise ValueError("item not in list") + + return impl + + +@overload_method(types.ListType, "sort") +def ol_list_sort(lst, key=None, reverse=False): + # The following is mostly borrowed from listobj.ol_list_sort + from numba.typed import List + + listobj._sort_check_key(key) + listobj._sort_check_reverse(reverse) + + if cgutils.is_nonelike(key): + KEY = False + sort_f = listobj.sort_forwards + sort_b = listobj.sort_backwards + elif isinstance(key, types.Dispatcher): + KEY = True + sort_f = listobj.arg_sort_forwards + sort_b = listobj.arg_sort_backwards + + def impl(lst, key=None, reverse=False): + if not lst._is_mutable(): + raise ValueError("list is immutable") + if KEY is True: + # There's an unknown refct problem in reflected list. + # Using an explicit loop with typedlist somehow "fixed" it. + _lst = List() + for x in lst: + _lst.append(key(x)) + else: + _lst = lst + if reverse is False or reverse == 0: + tmp = sort_f(_lst) + else: + tmp = sort_b(_lst) + if KEY is True: + # There's an unknown refct problem in reflected list. + # Using an explicit loop with typedlist somehow "fixed" it. + ordered = List() + for i in tmp: + ordered.append(lst[i]) + lst[:] = ordered + return impl + + +@overload_method(types.ListType, "getitem_unchecked") +def ol_getitem_unchecked(lst, index): + if not isinstance(index, types.Integer): + return + + def impl(lst, index): + index = fix_index(lst, index) + castedindex = _cast(index, types.intp) + _, item = _list_getitem(lst, castedindex) + return _nonoptional(item) + return impl + + +@overload_attribute(types.ListType, '__hash__') +def ol_list_hash(lst): + if not isinstance(lst, types.ListType): + return + return lambda lst: None + + +@overload_attribute(types.ListType, '_dtype') +def impl_dtype(l): + if not isinstance(l, types.ListType): + return + dt = l.dtype + + def impl(l): + return dt + + return impl + + +def _equals_helper(this, other, OP): + if not isinstance(this, types.ListType): + return + if not isinstance(other, types.ListType): + return lambda this, other: False + + this_is_none = isinstance(this.dtype, types.NoneType) + other_is_none = isinstance(other.dtype, types.NoneType) + + if this_is_none or other_is_none: + def impl_some_none(this, other): + def equals(this, other): + # Equal if both none-typed and have equal length + return bool(this_is_none == other_is_none + and len(this) == len(other)) + return OP(equals(this, other)) + return impl_some_none + else: + def impl_not_none(this, other): + def equals(this, other): + if len(this) != len(other): + return False + for i in range(len(this)): + if this[i] != other[i]: + return False + else: + return True + return OP(equals(this, other)) + return impl_not_none + + +@overload(operator.eq) +def impl_equals(this, other): + return _equals_helper(this, other, operator.truth) + + +@overload(operator.ne) +def impl_not_equals(this, other): + return _equals_helper(this, other, operator.not_) + + +@register_jitable +def compare_not_none(this, other): + """Oldschool (python 2.x) cmp. + + if this < other return -1 + if this = other return 0 + if this > other return 1 + """ + if len(this) != len(other): + return -1 if len(this) < len(other) else 1 + for i in range(len(this)): + this_item, other_item = this[i], other[i] + if this_item != other_item: + return -1 if this_item < other_item else 1 + else: + return 0 + + +@register_jitable +def compare_some_none(this, other, this_is_none, other_is_none): + """Oldschool (python 2.x) cmp for None typed lists. + + if this < other return -1 + if this = other return 0 + if this > other return 1 + """ + if len(this) != len(other): + return -1 if len(this) < len(other) else 1 + if this_is_none and other_is_none: # both none + return 0 + # to get here there is precisely one none, and if the first is none, by + # induction, the second cannot be + return -1 if this_is_none else 1 + + +def compare_helper(this, other, accepted): + if not isinstance(this, types.ListType): + return + if not isinstance(other, types.ListType): + return lambda this, other: False + + this_is_none = isinstance(this.dtype, types.NoneType) + other_is_none = isinstance(other.dtype, types.NoneType) + + if this_is_none or other_is_none: + def impl(this, other): + return compare_some_none( + this, other, this_is_none, other_is_none) in accepted + else: + def impl(this, other): + return compare_not_none(this, other) in accepted + return impl + + +@overload(operator.lt) +def impl_less_than(this, other): + return compare_helper(this, other, (-1, )) + + +@overload(operator.le) +def impl_less_than_or_equal(this, other): + return compare_helper(this, other, (-1, 0)) + + +@overload(operator.gt) +def impl_greater_than(this, other): + return compare_helper(this, other, (1,)) + + +@overload(operator.ge) +def impl_greater_than_or_equal(this, other): + return compare_helper(this, other, (0, 1)) + + +class ListIterInstance(object): + + def __init__(self, context, builder, iter_type, iter_val): + self._context = context + self._builder = builder + self._iter_ty = iter_type + self._list_ty = self._iter_ty.parent + self._iter = context.make_helper(builder, iter_type, iter_val) + + @classmethod + def from_list(cls, context, builder, iter_type, list_val): + self = cls(context, builder, iter_type, None) + index = context.get_constant(types.intp, 0) + self._iter.index = cgutils.alloca_once_value(builder, index) + self._iter.parent = list_val + self._iter.size = cls._size_of_list(context, builder, self._list_ty, + self._iter.parent) + return self + + @classmethod + def _size_of_list(cls, context, builder, list_ty, ll_list): + tyctx = context.typing_context + fnty = tyctx.resolve_value_type(len) + sig = fnty.get_call_type(tyctx, (list_ty,), {}) + impl = context.get_function(fnty, sig) + return impl(builder, (ll_list,)) + + @property + def size(self): + tyctx = self._context.typing_context + fnty = tyctx.resolve_value_type(len) + ty = self._list_ty + sig = fnty.get_call_type(tyctx, (ty,), {}) + impl = self._context.get_function(fnty, sig) + return impl(self._builder, (self._iter.parent,)) + + @property + def value(self): + return self._iter._getvalue() + + def getitem(self, index): + tyctx = self._context.typing_context + ty = self._list_ty + sig, fn = _list_getitem_borrowed._defn(tyctx, ty, types.intp) + + statnitem = fn(self._context, self._builder, sig, (self._iter.parent, + index)) + _, item = cgutils.unpack_tuple(self._builder, statnitem) + retty = sig.return_type[1] + if isinstance(self._list_ty.dtype, types.NoneType): + raw_ty = self._list_ty.dtype + else: + raw_ty = retty.type + raw_item = self._context.cast(self._builder, item, retty, raw_ty) + return raw_item + + @property + def index(self): + return self._builder.load(self._iter.index) + + @index.setter + def index(self, value): + self._builder.store(value, self._iter.index) + + +@lower_builtin('getiter', types.ListType) +def getiter_list(context, builder, sig, args): + inst = ListIterInstance.from_list(context, builder, sig.return_type, + args[0]) + return impl_ret_borrowed(context, builder, sig.return_type, inst.value) + + +@lower_builtin('iternext', types.ListTypeIteratorType) +@iternext_impl(RefType.BORROWED) +def iternext_listiter(context, builder, sig, args, result): + inst = ListIterInstance(context, builder, sig.args[0], args[0]) + index = inst.index + + nitems = inst.size # this is current size + init_size = inst._iter.size # this is initial size + + # if the current count is different to the initial count, bail, list is + # being mutated whilst iterated. + is_mutated = builder.icmp_signed('!=', init_size, nitems) + with builder.if_then(is_mutated, likely=False): + context.call_conv.return_user_exc( + builder, RuntimeError, ("list was mutated during iteration",)) + + is_valid = builder.icmp_signed('<', index, nitems) + result.set_valid(is_valid) + with builder.if_then(is_valid): + result.yield_(inst.getitem(index)) + inst.index = builder.add(index, context.get_constant(types.intp, 1)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/py.typed b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typeddict.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typeddict.py new file mode 100644 index 0000000000000000000000000000000000000000..a542063dcb569c123f6d1ba309846edae8f8e98d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typeddict.py @@ -0,0 +1,417 @@ +""" +Python wrapper that connects CPython interpreter to the numba dictobject. +""" +from collections.abc import MutableMapping, Iterable, Mapping +from numba.core.types import DictType +from numba.core.imputils import numba_typeref_ctor +from numba import njit, typeof +from numba.core import types, errors, config, cgutils +from numba.core.extending import ( + overload, + box, + unbox, + NativeValue, + type_callable, + overload_classmethod, +) +from numba.typed import dictobject +from numba.core.typing import signature + + +@njit +def _make_dict(keyty, valty, n_keys=0): + return dictobject._as_meminfo(dictobject.new_dict(keyty, valty, + n_keys=n_keys)) + + +@njit +def _length(d): + return len(d) + + +@njit +def _setitem(d, key, value): + d[key] = value + + +@njit +def _getitem(d, key): + return d[key] + + +@njit +def _delitem(d, key): + del d[key] + + +@njit +def _contains(d, key): + return key in d + + +@njit +def _get(d, key, default): + return d.get(key, default) + + +@njit +def _setdefault(d, key, default): + return d.setdefault(key, default) + + +@njit +def _iter(d): + return list(d.keys()) + + +@njit +def _popitem(d): + return d.popitem() + + +@njit +def _copy(d): + return d.copy() + + +def _from_meminfo_ptr(ptr, dicttype): + d = Dict(meminfo=ptr, dcttype=dicttype) + return d + + +class Dict(MutableMapping): + """A typed-dictionary usable in Numba compiled functions. + + Implements the MutableMapping interface. + """ + + def __new__(cls, dcttype=None, meminfo=None, n_keys=0): + if config.DISABLE_JIT: + return dict.__new__(dict) + else: + return object.__new__(cls) + + @classmethod + def empty(cls, key_type, value_type, n_keys=0): + """Create a new empty Dict with *key_type* and *value_type* + as the types for the keys and values of the dictionary respectively. + + Optionally, allocate enough memory to hold *n_keys* without requiring + resizes. The default value of 0 returns a dict with minimum size. + """ + if config.DISABLE_JIT: + return dict() + else: + return cls(dcttype=DictType(key_type, value_type), n_keys=n_keys) + + def __init__(self, *args, **kwargs): + """ + For users, the constructor does not take any parameters. + The keyword arguments are for internal use only. + + Parameters + ---------- + dcttype : numba.core.types.DictType; keyword-only + Used internally for the dictionary type. + meminfo : MemInfo; keyword-only + Used internally to pass the MemInfo object when boxing. + """ + if kwargs: + self._dict_type, self._opaque = self._parse_arg(**kwargs) + else: + self._dict_type = None + + if args: + # CPython checks for at most 1 argument + # https://github.com/python/cpython/blob/f215d7cac9a6f9b51ba864e4252686dee4e45d64/Objects/dictobject.c#L2693-L2695 + _len = len(args) + if _len > 1: + raise errors.TypingError("Dict expect at most 1 argument, " + f"got {_len}") + + # check if argument is iterable + arg = args[0] + if not isinstance(arg, Iterable): + msg = (f"'{type(arg)}' object is not iterable. Supported type " + "constructor are Dict() and Dict(iterable)") + raise errors.TypingError(msg) + elif isinstance(arg, Mapping): + raise errors.TypingError("dict(mapping) is not supported") + + for idx, item in enumerate(arg): + if len(item) != 2: + msg = (f"dictionary update sequence element #{idx} has " + f"length {len(item)}; 2 is required") + raise ValueError(msg) + k, v = item + self.__setitem__(k, v) + + def _parse_arg(self, dcttype, meminfo=None, n_keys=0): + if not isinstance(dcttype, DictType): + raise TypeError('*dcttype* must be a DictType') + + if meminfo is not None: + opaque = meminfo + else: + opaque = _make_dict(dcttype.key_type, dcttype.value_type, + n_keys=n_keys) + return dcttype, opaque + + @property + def _numba_type_(self): + if self._dict_type is None: + raise TypeError("invalid operation on untyped dictionary") + return self._dict_type + + @property + def _typed(self): + """Returns True if the dictionary is typed. + """ + return self._dict_type is not None + + def _initialise_dict(self, key, value): + dcttype = types.DictType(typeof(key), typeof(value)) + self._dict_type, self._opaque = self._parse_arg(dcttype) + + def __getitem__(self, key): + if not self._typed: + raise KeyError(key) + else: + return _getitem(self, key) + + def __setitem__(self, key, value): + if not self._typed: + self._initialise_dict(key, value) + return _setitem(self, key, value) + + def __delitem__(self, key): + if not self._typed: + raise KeyError(key) + _delitem(self, key) + + def __iter__(self): + if not self._typed: + return iter(()) + else: + return iter(_iter(self)) + + def __len__(self): + if not self._typed: + return 0 + else: + return _length(self) + + def __contains__(self, key): + if len(self) == 0: + return False + else: + return _contains(self, key) + + def __str__(self): + buf = [] + for k, v in self.items(): + buf.append("{}: {}".format(k, v)) + return '{{{0}}}'.format(', '.join(buf)) + + def __repr__(self): + body = str(self) + prefix = str(self._dict_type) + return "{prefix}({body})".format(prefix=prefix, body=body) + + def get(self, key, default=None): + if not self._typed: + return default + return _get(self, key, default) + + def setdefault(self, key, default=None): + if not self._typed: + if default is not None: + self._initialise_dict(key, default) + return _setdefault(self, key, default) + + def popitem(self): + if len(self) == 0: + raise KeyError('dictionary is empty') + return _popitem(self) + + def copy(self): + return _copy(self) + + +@overload_classmethod(types.DictType, 'empty') +def typeddict_empty(cls, key_type, value_type, n_keys=0): + if cls.instance_type is not DictType: + return + + def impl(cls, key_type, value_type, n_keys=0): + return dictobject.new_dict(key_type, value_type, n_keys=n_keys) + + return impl + + +@box(types.DictType) +def box_dicttype(typ, val, c): + context = c.context + builder = c.builder + + # XXX deduplicate + ctor = cgutils.create_struct_proxy(typ) + dstruct = ctor(context, builder, value=val) + # Returns the plain MemInfo + boxed_meminfo = c.box( + types.MemInfoPointer(types.voidptr), + dstruct.meminfo, + ) + + modname = c.context.insert_const_string( + c.builder.module, 'numba.typed.typeddict', + ) + typeddict_mod = c.pyapi.import_module(modname) + fmp_fn = c.pyapi.object_getattr_string(typeddict_mod, '_from_meminfo_ptr') + + dicttype_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ)) + + result_var = builder.alloca(c.pyapi.pyobj) + builder.store(cgutils.get_null_value(c.pyapi.pyobj), result_var) + with builder.if_then(cgutils.is_not_null(builder, dicttype_obj)): + res = c.pyapi.call_function_objargs( + fmp_fn, (boxed_meminfo, dicttype_obj), + ) + c.pyapi.decref(fmp_fn) + c.pyapi.decref(typeddict_mod) + c.pyapi.decref(boxed_meminfo) + builder.store(res, result_var) + return builder.load(result_var) + + +@unbox(types.DictType) +def unbox_dicttype(typ, val, c): + context = c.context + + # Check that `type(val) is Dict` + dict_type = c.pyapi.unserialize(c.pyapi.serialize_object(Dict)) + valtype = c.pyapi.object_type(val) + same_type = c.builder.icmp_unsigned("==", valtype, dict_type) + + with c.builder.if_else(same_type) as (then, orelse): + with then: + miptr = c.pyapi.object_getattr_string(val, '_opaque') + + mip_type = types.MemInfoPointer(types.voidptr) + native = c.unbox(mip_type, miptr) + + mi = native.value + + argtypes = mip_type, typeof(typ) + + def convert(mi, typ): + return dictobject._from_meminfo(mi, typ) + + sig = signature(typ, *argtypes) + nil_typeref = context.get_constant_null(argtypes[1]) + args = (mi, nil_typeref) + is_error, dctobj = c.pyapi.call_jit_code(convert, sig, args) + # decref here because we are stealing a reference. + c.context.nrt.decref(c.builder, typ, dctobj) + + c.pyapi.decref(miptr) + bb_unboxed = c.builder.basic_block + + with orelse: + # Raise error on incorrect type + c.pyapi.err_format( + "PyExc_TypeError", + "can't unbox a %S as a %S", + valtype, dict_type, + ) + bb_else = c.builder.basic_block + + # Phi nodes to gather the output + dctobj_res = c.builder.phi(dctobj.type) + is_error_res = c.builder.phi(is_error.type) + + dctobj_res.add_incoming(dctobj, bb_unboxed) + dctobj_res.add_incoming(dctobj.type(None), bb_else) + + is_error_res.add_incoming(is_error, bb_unboxed) + is_error_res.add_incoming(cgutils.true_bit, bb_else) + + # cleanup + c.pyapi.decref(dict_type) + c.pyapi.decref(valtype) + + return NativeValue(dctobj_res, is_error=is_error_res) + + +@type_callable(DictType) +def typeddict_call(context): + """ + Defines typing logic for ``Dict()`` and ``Dict(iterable)``. + Produces Dict[undefined, undefined] or Dict[key, value] + """ + def typer(arg=None): + if arg is None: + return types.DictType(types.undefined, types.undefined) + elif isinstance(arg, types.DictType): + return arg + elif isinstance(arg, types.Tuple) and len(arg) == 0: # Dict(()) + msg = "non-precise type 'dict(())'" + raise errors.TypingError(msg) + elif isinstance(arg, types.IterableType): + dtype = arg.iterator_type.yield_type + if isinstance(dtype, types.UniTuple): + key = value = dtype.key[0] + return types.DictType(key, value) + elif isinstance(dtype, types.Tuple): + key, value = dtype.key + return types.DictType(key, value) + return typer + + +@overload(numba_typeref_ctor) +def impl_numba_typeref_ctor(cls, *args): + """ + Defines lowering for ``Dict()`` and ``Dict(iterable)``. + + The type-inferred version of the dictionary ctor. + + Parameters + ---------- + cls : TypeRef + Expecting a TypeRef of a precise DictType. + args: tuple + A tuple that contains a single iterable (optional) + + Returns + ------- + impl : function + An implementation suitable for lowering the constructor call. + + See also: `redirect_type_ctor` in numba/cpython/builtins.py + """ + dict_ty = cls.instance_type + if not isinstance(dict_ty, types.DictType): + return # reject + # Ensure the dictionary is precisely typed. + if not dict_ty.is_precise(): + msg = "expecting a precise DictType but got {}".format(dict_ty) + raise errors.LoweringError(msg) + + key_type = types.TypeRef(dict_ty.key_type) + value_type = types.TypeRef(dict_ty.value_type) + + if args: + if isinstance(args[0], types.IterableType): + def impl(cls, *args): + # Instantiate an empty dict and populate it with values from + # the iterable. + d = Dict.empty(key_type, value_type) + for k, v in args[0]: + d[k] = v + return d + else: + def impl(cls, *args): + # Simply call .empty() with the key/value types from *cls* + return Dict.empty(key_type, value_type) + + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedlist.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedlist.py new file mode 100644 index 0000000000000000000000000000000000000000..2c90dabeac43c5728ab2242e5ac75b7ad0e266c2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedlist.py @@ -0,0 +1,688 @@ +""" +Python wrapper that connects CPython interpreter to the Numba typed-list. + +This is the code that is used when creating typed lists outside of a `@jit` +context and when returning a typed-list from a `@jit` decorated function. It +basically a Python class that has a Numba allocated typed-list under the hood +and uses `@jit` functions to access it. Since it inherits from MutableSequence +it should really quack like the CPython `list`. + +""" +from collections.abc import MutableSequence + +from numba.core.types import ListType +from numba.core.imputils import numba_typeref_ctor +from numba.core.dispatcher import Dispatcher +from numba.core import types, config, cgutils +from numba import njit, typeof +from numba.core.extending import ( + overload, + box, + unbox, + NativeValue, + type_callable, + overload_classmethod, +) +from numba.typed import listobject +from numba.core.errors import TypingError, LoweringError +from numba.core.typing.templates import Signature +import typing as pt + + +Int_or_Slice = pt.Union["pt.SupportsIndex", slice] + + +T_co = pt.TypeVar('T_co', covariant=True) + + +class _Sequence(pt.Protocol[T_co]): + def __getitem__(self, i: int) -> T_co: + ... + + def __len__(self) -> int: + ... + + +DEFAULT_ALLOCATED = listobject.DEFAULT_ALLOCATED + + +@njit +def _make_list(itemty, allocated=DEFAULT_ALLOCATED): + return listobject._as_meminfo(listobject.new_list(itemty, + allocated=allocated)) + + +@njit +def _length(l): + return len(l) + + +@njit +def _allocated(l): + return l._allocated() + + +@njit +def _is_mutable(l): + return l._is_mutable() + + +@njit +def _make_mutable(l): + return l._make_mutable() + + +@njit +def _make_immutable(l): + return l._make_immutable() + + +@njit +def _append(l, item): + l.append(item) + + +@njit +def _setitem(l, i, item): + l[i] = item + + +@njit +def _getitem(l, i): + return l[i] + + +@njit +def _contains(l, item): + return item in l + + +@njit +def _count(l, item): + return l.count(item) + + +@njit +def _pop(l, i): + return l.pop(i) + + +@njit +def _delitem(l, i): + del l[i] + + +@njit +def _extend(l, iterable): + return l.extend(iterable) + + +@njit +def _insert(l, i, item): + l.insert(i, item) + + +@njit +def _remove(l, item): + l.remove(item) + + +@njit +def _clear(l): + l.clear() + + +@njit +def _reverse(l): + l.reverse() + + +@njit +def _copy(l): + return l.copy() + + +@njit +def _eq(t, o): + return t == o + + +@njit +def _ne(t, o): + return t != o + + +@njit +def _lt(t, o): + return t < o + + +@njit +def _le(t, o): + return t <= o + + +@njit +def _gt(t, o): + return t > o + + +@njit +def _ge(t, o): + return t >= o + + +@njit +def _index(l, item, start, end): + return l.index(item, start, end) + + +@njit +def _sort(l, key, reverse): + return l.sort(key, reverse) + + +def _from_meminfo_ptr(ptr, listtype): + return List(meminfo=ptr, lsttype=listtype) + + +T = pt.TypeVar('T') +T_or_ListT = pt.Union[T, 'List[T]'] + + +class List(MutableSequence, pt.Generic[T]): + """A typed-list usable in Numba compiled functions. + + Implements the MutableSequence interface. + """ + + _legal_kwargs = ["lsttype", "meminfo", "allocated"] + + def __new__(cls, + *args, + lsttype=None, + meminfo=None, + allocated=DEFAULT_ALLOCATED, + **kwargs): + if config.DISABLE_JIT: + return list(*args, **kwargs) + else: + return object.__new__(cls) + + @classmethod + def empty_list(cls, item_type, allocated=DEFAULT_ALLOCATED): + """Create a new empty List. + + Parameters + ---------- + item_type: Numba type + type of the list item. + allocated: int + number of items to pre-allocate + """ + if config.DISABLE_JIT: + return list() + else: + return cls(lsttype=ListType(item_type), allocated=allocated) + + def __init__(self, *args, **kwargs): + """ + For users, the constructor does not take any parameters. + The keyword arguments are for internal use only. + + Parameters + ---------- + args: iterable + The iterable to initialize the list from + lsttype : numba.core.types.ListType; keyword-only + Used internally for the list type. + meminfo : MemInfo; keyword-only + Used internally to pass the MemInfo object when boxing. + allocated: int; keyword-only + Used internally to pre-allocate space for items + """ + illegal_kwargs = any((kw not in self._legal_kwargs for kw in kwargs)) + if illegal_kwargs or args and kwargs: + raise TypeError("List() takes no keyword arguments") + if kwargs: + self._list_type, self._opaque = self._parse_arg(**kwargs) + else: + self._list_type = None + if args: + if not 0 <= len(args) <= 1: + raise TypeError( + "List() expected at most 1 argument, got {}" + .format(len(args)) + ) + iterable = args[0] + # Special case Numpy scalars or anything that quacks like a + # NumPy Array. + if hasattr(iterable, "ndim") and iterable.ndim == 0: + self.append(iterable.item()) + else: + try: + iter(iterable) + except TypeError: + raise TypeError("List() argument must be iterable") + for i in args[0]: + self.append(i) + + def _parse_arg(self, lsttype, meminfo=None, allocated=DEFAULT_ALLOCATED): + if not isinstance(lsttype, ListType): + raise TypeError('*lsttype* must be a ListType') + + if meminfo is not None: + opaque = meminfo + else: + opaque = _make_list(lsttype.item_type, allocated=allocated) + return lsttype, opaque + + @property + def _numba_type_(self): + if self._list_type is None: + raise TypeError("invalid operation on untyped list") + return self._list_type + + @property + def _typed(self): + """Returns True if the list is typed. + """ + return self._list_type is not None + + @property + def _dtype(self): + if not self._typed: + raise RuntimeError("invalid operation on untyped list") + return self._list_type.dtype + + def _initialise_list(self, item): + lsttype = types.ListType(typeof(item)) + self._list_type, self._opaque = self._parse_arg(lsttype) + + def __len__(self) -> int: + if not self._typed: + return 0 + else: + return _length(self) + + def _allocated(self): + if not self._typed: + return DEFAULT_ALLOCATED + else: + return _allocated(self) + + def _is_mutable(self): + return _is_mutable(self) + + def _make_mutable(self): + return _make_mutable(self) + + def _make_immutable(self): + return _make_immutable(self) + + def __eq__(self, other): + return _eq(self, other) + + def __ne__(self, other): + return _ne(self, other) + + def __lt__(self, other): + return _lt(self, other) + + def __le__(self, other): + return _le(self, other) + + def __gt__(self, other): + return _gt(self, other) + + def __ge__(self, other): + return _ge(self, other) + + def append(self, item: T) -> None: + if not self._typed: + self._initialise_list(item) + _append(self, item) + + # noqa F811 comments required due to github.com/PyCQA/pyflakes/issues/592 + # noqa E704 required to follow overload style of using ... in the same line + @pt.overload # type: ignore[override] + def __setitem__(self, i: int, o: T) -> None: ... # noqa: F811, E704 + @pt.overload + def __setitem__(self, s: slice, o: 'List[T]') -> None: ... # noqa: F811, E704, E501 + + def __setitem__(self, i: Int_or_Slice, item: T_or_ListT) -> None: # noqa: F811, E501 + if not self._typed: + self._initialise_list(item) + _setitem(self, i, item) + + # noqa F811 comments required due to github.com/PyCQA/pyflakes/issues/592 + # noqa E704 required to follow overload style of using ... in the same line + @pt.overload + def __getitem__(self, i: int) -> T: ... # noqa: F811, E704 + @pt.overload + def __getitem__(self, i: slice) -> 'List[T]': ... # noqa: F811, E704 + + def __getitem__(self, i: Int_or_Slice) -> T_or_ListT: # noqa: F811 + if not self._typed: + raise IndexError + else: + return _getitem(self, i) + + def __iter__(self) -> pt.Iterator[T]: + for i in range(len(self)): + yield self[i] + + def __contains__(self, item: T) -> bool: # type: ignore[override] + return _contains(self, item) + + def __delitem__(self, i: Int_or_Slice) -> None: + _delitem(self, i) + + def insert(self, i: int, item: T) -> None: + if not self._typed: + self._initialise_list(item) + _insert(self, i, item) + + def count(self, item: T) -> int: + return _count(self, item) + + def pop(self, i: "pt.SupportsIndex" = -1) -> T: + return _pop(self, i) + + def extend(self, iterable: "_Sequence[T]") -> None: #type: ignore[override] + # Empty iterable, do nothing + if len(iterable) == 0: + return None + if not self._typed: + # Need to get the first element of the iterable to initialise the + # type of the list. FIXME: this may be a problem if the iterable + # can not be sliced. + self._initialise_list(iterable[0]) + return _extend(self, iterable) + + def remove(self, item: T) -> None: + return _remove(self, item) + + def clear(self): + return _clear(self) + + def reverse(self): + return _reverse(self) + + def copy(self): + return _copy(self) + + def index(self, item: T, start: pt.Optional[int] = None, + stop: pt.Optional[int] = None) -> int: + return _index(self, item, start, stop) + + def sort(self, key=None, reverse=False): + """Sort the list inplace. + + See also ``list.sort()`` + """ + # If key is not already a dispatcher object, make it so + if callable(key) and not isinstance(key, Dispatcher): + key = njit(key) + return _sort(self, key, reverse) + + def __str__(self): + buf = [] + for x in self: + buf.append("{}".format(x)) + # Check whether the code was invoked from IPython shell + try: + get_ipython + preview = ', '.join(buf[:1000]) + suffix = ', ...' if len(buf) > 1000 else '' + return '[{0}{1}]'.format(preview, suffix) + except (NameError, IndexError): + return '[{0}]'.format(', '.join(buf)) + + def __repr__(self): + body = str(self) + prefix = str(self._list_type) if self._typed else "ListType[Undefined]" + return "{prefix}({body})".format(prefix=prefix, body=body) + + +@overload_classmethod(ListType, 'empty_list') +def typedlist_empty(cls, item_type, allocated=DEFAULT_ALLOCATED): + if cls.instance_type is not ListType: + return + + def impl(cls, item_type, allocated=DEFAULT_ALLOCATED): + return listobject.new_list(item_type, allocated=allocated) + + return impl + + +@box(types.ListType) +def box_lsttype(typ, val, c): + context = c.context + builder = c.builder + + # XXX deduplicate + ctor = cgutils.create_struct_proxy(typ) + lstruct = ctor(context, builder, value=val) + # Returns the plain MemInfo + boxed_meminfo = c.box( + types.MemInfoPointer(types.voidptr), + lstruct.meminfo, + ) + + modname = c.context.insert_const_string( + c.builder.module, 'numba.typed.typedlist', + ) + typedlist_mod = c.pyapi.import_module(modname) + fmp_fn = c.pyapi.object_getattr_string(typedlist_mod, '_from_meminfo_ptr') + + lsttype_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ)) + + result_var = builder.alloca(c.pyapi.pyobj) + builder.store(cgutils.get_null_value(c.pyapi.pyobj), result_var) + + with builder.if_then(cgutils.is_not_null(builder, lsttype_obj)): + res = c.pyapi.call_function_objargs( + fmp_fn, (boxed_meminfo, lsttype_obj), + ) + c.pyapi.decref(fmp_fn) + c.pyapi.decref(typedlist_mod) + c.pyapi.decref(boxed_meminfo) + builder.store(res, result_var) + return builder.load(result_var) + + +@unbox(types.ListType) +def unbox_listtype(typ, val, c): + context = c.context + builder = c.builder + + # Check that `type(val) is Dict` + list_type = c.pyapi.unserialize(c.pyapi.serialize_object(List)) + valtype = c.pyapi.object_type(val) + same_type = builder.icmp_unsigned("==", valtype, list_type) + + with c.builder.if_else(same_type) as (then, orelse): + with then: + miptr = c.pyapi.object_getattr_string(val, '_opaque') + + native = c.unbox(types.MemInfoPointer(types.voidptr), miptr) + + mi = native.value + ctor = cgutils.create_struct_proxy(typ) + lstruct = ctor(context, builder) + + data_pointer = context.nrt.meminfo_data(builder, mi) + data_pointer = builder.bitcast( + data_pointer, + listobject.ll_list_type.as_pointer(), + ) + + lstruct.data = builder.load(data_pointer) + lstruct.meminfo = mi + + lstobj = lstruct._getvalue() + c.pyapi.decref(miptr) + bb_unboxed = c.builder.basic_block + + with orelse: + # Raise error on incorrect type + c.pyapi.err_format( + "PyExc_TypeError", + "can't unbox a %S as a %S", + valtype, list_type, + ) + bb_else = c.builder.basic_block + + # Phi nodes to gather the output + lstobj_res = c.builder.phi(lstobj.type) + is_error_res = c.builder.phi(cgutils.bool_t) + + lstobj_res.add_incoming(lstobj, bb_unboxed) + lstobj_res.add_incoming(lstobj.type(None), bb_else) + + is_error_res.add_incoming(cgutils.false_bit, bb_unboxed) + is_error_res.add_incoming(cgutils.true_bit, bb_else) + + # cleanup + c.pyapi.decref(list_type) + c.pyapi.decref(valtype) + + return NativeValue(lstobj_res, is_error=is_error_res) + + +# +# The following contains the logic for the type-inferred constructor +# + +def _guess_dtype(iterable): + """Guess the correct dtype of the iterable type. """ + if not isinstance(iterable, types.IterableType): + raise TypingError( + "List() argument must be iterable") + # Special case for nested NumPy arrays. + elif isinstance(iterable, types.Array) and iterable.ndim > 1: + return iterable.copy(ndim=iterable.ndim - 1, layout='A') + elif hasattr(iterable, "dtype"): + return iterable.dtype + elif hasattr(iterable, "yield_type"): + return iterable.yield_type + elif isinstance(iterable, types.UnicodeType): + return iterable + elif isinstance(iterable, types.DictType): + return iterable.key_type + else: + # This should never happen, since the 'dtype' of any iterable + # should have determined above. + raise TypingError( + "List() argument does not have a suitable dtype") + + +@type_callable(ListType) +def typedlist_call(context): + """Defines typing logic for ``List()`` and ``List(iterable)``. + + If no argument is given, the returned typer types a new typed-list with an + undefined item type. If a single argument is given it must be iterable with + a guessable 'dtype'. In this case, the typer types a new typed-list with + the type set to the 'dtype' of the iterable arg. + + Parameters + ---------- + arg : single iterable (optional) + The single optional argument. + + Returns + ------- + typer : function + A typer suitable to type constructor calls. + + Raises + ------ + The returned typer raises a TypingError in case of unsuitable arguments. + + """ + + class Typer(object): + + def attach_sig(self): + from inspect import signature as mypysig + + def mytyper(iterable): + pass + self.pysig = mypysig(mytyper) + + def __call__(self, *args, **kwargs): + if kwargs: + raise TypingError( + "List() takes no keyword arguments" + ) + elif args: + if not 0 <= len(args) <= 1: + raise TypingError( + "List() expected at most 1 argument, got {}" + .format(len(args)) + ) + rt = types.ListType(_guess_dtype(args[0])) + self.attach_sig() + return Signature(rt, args, None, pysig=self.pysig) + else: + item_type = types.undefined + return types.ListType(item_type) + + return Typer() + + +@overload(numba_typeref_ctor) +def impl_numba_typeref_ctor(cls, *args): + """Defines lowering for ``List()`` and ``List(iterable)``. + + This defines the lowering logic to instantiate either an empty typed-list + or a typed-list initialised with values from a single iterable argument. + + Parameters + ---------- + cls : TypeRef + Expecting a TypeRef of a precise ListType. + args: tuple + A tuple that contains a single iterable (optional) + + Returns + ------- + impl : function + An implementation suitable for lowering the constructor call. + + See also: `redirect_type_ctor` in numba/cpython/bulitins.py + """ + list_ty = cls.instance_type + if not isinstance(list_ty, types.ListType): + return # reject + # Ensure the list is precisely typed. + if not list_ty.is_precise(): + msg = "expecting a precise ListType but got {}".format(list_ty) + raise LoweringError(msg) + + item_type = types.TypeRef(list_ty.item_type) + if args: + # special case 0d Numpy arrays + if isinstance(args[0], types.Array) and args[0].ndim == 0: + def impl(cls, *args): + # Instantiate an empty list and populate it with the single + # value from the array. + r = List.empty_list(item_type) + r.append(args[0].item()) + return r + else: + def impl(cls, *args): + # Instantiate an empty list and populate it with values from + # the iterable. + r = List.empty_list(item_type) + for i in args[0]: + r.append(i) + return r + else: + def impl(cls, *args): + # Simply call .empty_list with the item type from *cls* + return List.empty_list(item_type) + + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedobjectutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedobjectutils.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb20488ea55e171b8bb0acca3c49f7b3adf484d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/typed/typedobjectutils.py @@ -0,0 +1,200 @@ +""" Common compiler level utilities for typed dict and list. """ + +import operator +import warnings + +from llvmlite import ir + +from numba.core import types, cgutils +from numba.core import typing +from numba.core.registry import cpu_target +from numba.core.typeconv import Conversion +from numba.core.extending import intrinsic +from numba.core.errors import (TypingError, NumbaTypeSafetyWarning, + NumbaTypeError) + + +def _as_bytes(builder, ptr): + """Helper to do (void*)ptr + """ + return builder.bitcast(ptr, cgutils.voidptr_t) + + +@intrinsic +def _cast(typingctx, val, typ): + """Cast *val* to *typ* + """ + def codegen(context, builder, signature, args): + [val, typ] = args + context.nrt.incref(builder, signature.return_type, val) + return val + # Using implicit casting in argument types + casted = typ.instance_type + _sentry_safe_cast(val, casted) + sig = casted(casted, typ) + return sig, codegen + + +def _sentry_safe_cast(fromty, toty): + """Check and raise TypingError if *fromty* cannot be safely cast to *toty* + """ + tyctxt = cpu_target.typing_context + fromty, toty = map(types.unliteral, (fromty, toty)) + by = tyctxt.can_convert(fromty, toty) + + def warn(): + m = 'unsafe cast from {} to {}. Precision may be lost.' + warnings.warn(m.format(fromty, toty), + category=NumbaTypeSafetyWarning) + + isint = lambda x: isinstance(x, types.Integer) + isflt = lambda x: isinstance(x, types.Float) + iscmplx = lambda x: isinstance(x, types.Complex) + isdict = lambda x: isinstance(x, types.DictType) + # Only check against numeric types. + if by is None or by > Conversion.safe: + if isint(fromty) and isint(toty): + # Accept if both types are ints + warn() + elif isint(fromty) and isflt(toty): + # Accept if ints to floats + warn() + elif isflt(fromty) and isflt(toty): + # Accept if floats to floats + warn() + elif iscmplx(fromty) and iscmplx(toty): + # Accept if complex to complex + warn() + elif isdict(fromty) and isdict(toty): + pass # it's complaining about initial values being different + elif not isinstance(toty, types.Number): + # Non-numbers + warn() + else: + # Make it a hard error for numeric type that changes domain. + m = 'cannot safely cast {} to {}. Please cast explicitly.' + raise TypingError(m.format(fromty, toty)) + + +def _sentry_safe_cast_default(default, valty): + """Similar to _sentry_safe_cast but handle default value. + """ + # Handle default values + # TODO: simplify default values; too many possible way to spell None + if default is None: + return + if isinstance(default, (types.Omitted, types.NoneType)): + return + return _sentry_safe_cast(default, valty) + + +@intrinsic +def _nonoptional(typingctx, val): + """Typing trick to cast Optional[T] to T + """ + if not isinstance(val, types.Optional): + raise NumbaTypeError('expected an optional') + + def codegen(context, builder, sig, args): + context.nrt.incref(builder, sig.return_type, args[0]) + return args[0] + + casted = val.type + sig = casted(casted) + return sig, codegen + + +def _container_get_data(context, builder, container_ty, c): + """Helper to get the C list pointer in a numba containers. + """ + ctor = cgutils.create_struct_proxy(container_ty) + conatainer_struct = ctor(context, builder, value=c) + return conatainer_struct.data + + +def _container_get_meminfo(context, builder, container_ty, c): + """Helper to get the meminfo for a container + """ + ctor = cgutils.create_struct_proxy(container_ty) + conatainer_struct = ctor(context, builder, value=c) + return conatainer_struct.meminfo + + +def _get_incref_decref(context, module, datamodel, container_element_type): + assert datamodel.contains_nrt_meminfo() + + fe_type = datamodel.fe_type + data_ptr_ty = datamodel.get_data_type().as_pointer() + refct_fnty = ir.FunctionType(ir.VoidType(), [data_ptr_ty]) + incref_fn = cgutils.get_or_insert_function( + module, refct_fnty, '.numba_{}.{}_incref'.format( + context.fndesc.mangled_name, container_element_type),) + + builder = ir.IRBuilder(incref_fn.append_basic_block()) + context.nrt.incref( + builder, fe_type, + datamodel.load_from_data_pointer(builder, incref_fn.args[0]), + ) + builder.ret_void() + + decref_fn = cgutils.get_or_insert_function( + module, refct_fnty, name='.numba_{}.{}_decref'.format( + context.fndesc.mangled_name, container_element_type),) + builder = ir.IRBuilder(decref_fn.append_basic_block()) + context.nrt.decref( + builder, fe_type, + datamodel.load_from_data_pointer(builder, decref_fn.args[0]), + ) + builder.ret_void() + + return incref_fn, decref_fn + + +def _get_equal(context, module, datamodel, container_element_type): + assert datamodel.contains_nrt_meminfo() + + fe_type = datamodel.fe_type + data_ptr_ty = datamodel.get_data_type().as_pointer() + + wrapfnty = context.call_conv.get_function_type(types.int32, + [fe_type, fe_type]) + argtypes = [fe_type, fe_type] + + def build_wrapper(fn): + builder = ir.IRBuilder(fn.append_basic_block()) + args = context.call_conv.decode_arguments(builder, argtypes, fn) + + sig = typing.signature(types.boolean, fe_type, fe_type) + op = operator.eq + fnop = context.typing_context.resolve_value_type(op) + fnop.get_call_type(context.typing_context, sig.args, {}) + eqfn = context.get_function(fnop, sig) + res = eqfn(builder, args) + intres = context.cast(builder, res, types.boolean, types.int32) + context.call_conv.return_value(builder, intres) + + wrapfn = cgutils.get_or_insert_function( + module, wrapfnty, name='.numba_{}.{}_equal.wrap'.format( + context.fndesc.mangled_name, container_element_type)) + build_wrapper(wrapfn) + + equal_fnty = ir.FunctionType(ir.IntType(32), [data_ptr_ty, data_ptr_ty]) + equal_fn = cgutils.get_or_insert_function( + module, equal_fnty, name='.numba_{}.{}_equal'.format( + context.fndesc.mangled_name, container_element_type),) + builder = ir.IRBuilder(equal_fn.append_basic_block()) + lhs = datamodel.load_from_data_pointer(builder, equal_fn.args[0]) + rhs = datamodel.load_from_data_pointer(builder, equal_fn.args[1]) + + status, retval = context.call_conv.call_function( + builder, wrapfn, types.int32, argtypes, [lhs, rhs], + ) + with builder.if_then(status.is_ok, likely=True): + with builder.if_then(status.is_none): + builder.ret(context.get_constant(types.int32, 0)) + retval = context.cast(builder, retval, types.boolean, types.int32) + builder.ret(retval) + # Error out + builder.ret(context.get_constant(types.int32, -1)) + + return equal_fn diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/types/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..825cc24401cd83f70f5fa44574a0d1f33553aa23 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/types/__init__.py @@ -0,0 +1,3 @@ +import sys +from numba.core.utils import _RedirectSubpackage +sys.modules[__name__] = _RedirectSubpackage(locals(), "numba.core.types") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/uritemplate-4.2.0.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/uritemplate-4.2.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..41c87e7cf26b0f948798e79b1b882a0940fbcb32 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/uritemplate-4.2.0.dist-info/licenses/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to uritemplate are +made under the terms of *both* these licenses. diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc0f23740c0ca95156650ae18362b6c5bc5d57fb Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..610f64baf678246f3e248f267fe02be571451f7d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_base_connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fa552ae2aa5811ab6f0d70bc695dc125c45e0ca Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_collections.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a91ba5cf56f66172c425614ad16128929fe5a8b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_request_methods.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b06dda9ddfddb9a1a2bd098e7e8a9205b764298e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/_version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9e03ee13d929c732c7e8e8ba27f53d156f15506 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ec5f0089066ac3f914570690f7ff8f67a9d1276 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/connectionpool.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efa34eb27991504301a3da3c0d375ec49f54b701 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/exceptions.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/fields.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/fields.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5c66548f10bd703b3915c8bef5ad2f2492bf790 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/fields.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5b920848f087ec0cc963b1e008422e6b838becf Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/filepost.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ce16c20ceb19f4370e95ff933e1463d3f1343b0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/poolmanager.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/response.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb085dadc08215191d8b8c8fbd513b1191d71e1d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/__pycache__/response.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d491db24b8a95f1be59082b880d376d128c22131 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3afe06122957e73a4f4ab3120076520db0681481 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..823e621572bd9a6d3d1ccf2848fecf329a21372a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/__pycache__/socks.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b62b25e932566f7ae7599c1cedec2b8f30d95b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] + urllib3.connection.VerifiedHTTPSConnection = EmscriptenHTTPSConnection # type: ignore[assignment] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43dbab3bd3b8f8c1b8e193084aa12cf4071018e9 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26629de0de0a3384f0ba3207a385ed2df01dd83 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7202bb298a562b5520e275203aa474828dddf5db Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/fetch.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a3d90d088e1d62f20f92ded115741735c16f17a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/request.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c0058cd40d163586d4a797e798f056fad7eac82 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/__pycache__/response.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/connection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..63f79dd3be803db09671c909f79316c3f65d6916 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + response_class: type[BaseHTTPResponse] = EmscriptenHttpResponseWrapper + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + if self.port is not None: + port = f":{self.port}" + else: + port = "" + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}{port}{url}" + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: ( + None | _TYPE_SOCKET_OPTIONS + ) = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..faf141e1fa4113a0c14480d1681ddecb9678ced4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = new Map(); +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + connections.delete(connectionID); + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections.get(connectionID); + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + connections.delete(connectionID); + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections.get(connectionID).value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections.get(connectionID).curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections.set(connectionID, { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }); + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/fetch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..612cfddc4c28d2f0edf47522278fa6d9b7906623 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/fetch.py @@ -0,0 +1,726 @@ +""" +Support for streaming http requests in emscripten. + +A few caveats - + +If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled +https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md +*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the +JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case +timeouts and streaming should just work. + +Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. + +This approach has several caveats: + +Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. +Streaming only works if you're running pyodide in a web worker. + +Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch +operation, so it requires that you have crossOriginIsolation enabled, by serving over https +(or from localhost) with the two headers below set: + + Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp + +You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in +JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole +request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. + +Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once +control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. + +NB: in this code, there are a lot of JavaScript objects. They are named js_* +to make it clear what type of object they are. +""" + +from __future__ import annotations + +import io +import json +from email.parser import Parser +from importlib.resources import files +from typing import TYPE_CHECKING, Any + +import js # type: ignore[import-not-found] +from pyodide.ffi import ( # type: ignore[import-not-found] + JsArray, + JsException, + JsProxy, + to_js, +) + +if TYPE_CHECKING: + from typing_extensions import Buffer + +from .request import EmscriptenRequest +from .response import EmscriptenResponse + +""" +There are some headers that trigger unintended CORS preflight requests. +See also https://github.com/koenvo/pyodide-http/issues/22 +""" +HEADERS_TO_IGNORE = ("user-agent",) + +SUCCESS_HEADER = -1 +SUCCESS_EOF = -2 +ERROR_TIMEOUT = -3 +ERROR_EXCEPTION = -4 + + +class _RequestError(Exception): + def __init__( + self, + message: str | None = None, + *, + request: EmscriptenRequest | None = None, + response: EmscriptenResponse | None = None, + ): + self.request = request + self.response = response + self.message = message + super().__init__(self.message) + + +class _StreamingError(_RequestError): + pass + + +class _TimeoutError(_RequestError): + pass + + +def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: + return to_js(dict_val, dict_converter=js.Object.fromEntries) + + +class _ReadStream(io.RawIOBase): + def __init__( + self, + int_buffer: JsArray, + byte_buffer: JsArray, + timeout: float, + worker: JsProxy, + connection_id: int, + request: EmscriptenRequest, + ): + self.int_buffer = int_buffer + self.byte_buffer = byte_buffer + self.read_pos = 0 + self.read_len = 0 + self.connection_id = connection_id + self.worker = worker + self.timeout = int(1000 * timeout) if timeout > 0 else None + self.is_live = True + self._is_closed = False + self.request: EmscriptenRequest | None = request + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.int_buffer = None + self.byte_buffer = None + self._is_closed = True + self.request = None + if self.is_live: + self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) + self.is_live = False + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def readinto(self, byte_obj: Buffer) -> int: + if not self.int_buffer: + raise _StreamingError( + "No buffer for stream in _ReadStream.readinto", + request=self.request, + response=None, + ) + if self.read_len == 0: + # wait for the worker to send something + js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) + self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) + if ( + js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) + == "timed-out" + ): + raise _TimeoutError + data_len = self.int_buffer[0] + if data_len > 0: + self.read_len = data_len + self.read_pos = 0 + elif data_len == ERROR_EXCEPTION: + string_len = self.int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", + request=self.request, + response=None, + ) + else: + # EOF, free the buffers and return zero + # and free the request + self.is_live = False + self.close() + return 0 + # copy from int32array to python bytes + ret_length = min(self.read_len, len(memoryview(byte_obj))) + subarray = self.byte_buffer.subarray( + self.read_pos, self.read_pos + ret_length + ).to_py() + memoryview(byte_obj)[0:ret_length] = subarray + self.read_len -= ret_length + self.read_pos += ret_length + return ret_length + + +class _StreamingFetcher: + def __init__(self) -> None: + # make web-worker and data buffer on startup + self.streaming_ready = False + streaming_worker_code = ( + files(__package__) + .joinpath("emscripten_fetch_worker.js") + .read_text(encoding="utf-8") + ) + js_data_blob = js.Blob.new( + to_js([streaming_worker_code], create_pyproxies=False), + _obj_from_dict({"type": "application/javascript"}), + ) + + def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: + def onMsg(e: JsProxy) -> None: + self.streaming_ready = True + js_resolve_fn(e) + + def onErr(e: JsProxy) -> None: + js_reject_fn(e) # Defensive: never happens in ci + + self.js_worker.onmessage = onMsg + self.js_worker.onerror = onErr + + js_data_url = js.URL.createObjectURL(js_data_blob) + self.js_worker = js.globalThis.Worker.new(js_data_url) + self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) + + def send(self, request: EmscriptenRequest) -> EmscriptenResponse: + headers = { + k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE + } + + body = request.body + fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} + # start the request off in the worker + timeout = int(1000 * request.timeout) if request.timeout > 0 else None + js_shared_buffer = js.SharedArrayBuffer.new(1048576) + js_int_buffer = js.Int32Array.new(js_shared_buffer) + js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) + + js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) + js.Atomics.notify(js_int_buffer, 0) + js_absolute_url = js.URL.new(request.url, js.location).href + self.js_worker.postMessage( + _obj_from_dict( + { + "buffer": js_shared_buffer, + "url": js_absolute_url, + "fetchParams": fetch_data, + } + ) + ) + # wait for the worker to send something + js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) + if js_int_buffer[0] == ERROR_TIMEOUT: + raise _TimeoutError( + "Timeout connecting to streaming request", + request=request, + response=None, + ) + elif js_int_buffer[0] == SUCCESS_HEADER: + # got response + # header length is in second int of intBuffer + string_len = js_int_buffer[1] + # decode the rest to a JSON string + js_decoder = js.TextDecoder.new() + # this does a copy (the slice) because decode can't work on shared array + # for some silly reason + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + # get it as an object + response_obj = json.loads(json_str) + return EmscriptenResponse( + request=request, + status_code=response_obj["status"], + headers=response_obj["headers"], + body=_ReadStream( + js_int_buffer, + js_byte_buffer, + request.timeout, + self.js_worker, + response_obj["connectionID"], + request, + ), + ) + elif js_int_buffer[0] == ERROR_EXCEPTION: + string_len = js_int_buffer[1] + # decode the error string + js_decoder = js.TextDecoder.new() + json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) + raise _StreamingError( + f"Exception thrown in fetch: {json_str}", request=request, response=None + ) + else: + raise _StreamingError( + f"Unknown status from worker in fetch: {js_int_buffer[0]}", + request=request, + response=None, + ) + + +class _JSPIReadStream(io.RawIOBase): + """ + A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch + response. This requires support for WebAssembly JavaScript Promise Integration + in the containing browser, and for pyodide to be launched via runPythonAsync. + + :param js_read_stream: + The JavaScript stream reader + + :param timeout: + Timeout in seconds + + :param request: + The request we're handling + + :param response: + The response this stream relates to + + :param js_abort_controller: + A JavaScript AbortController object, used for timeouts + """ + + def __init__( + self, + js_read_stream: Any, + timeout: float, + request: EmscriptenRequest, + response: EmscriptenResponse, + js_abort_controller: Any, # JavaScript AbortController for timeouts + ): + self.js_read_stream = js_read_stream + self.timeout = timeout + self._is_closed = False + self._is_done = False + self.request: EmscriptenRequest | None = request + self.response: EmscriptenResponse | None = response + self.current_buffer = None + self.current_buffer_pos = 0 + self.js_abort_controller = js_abort_controller + + def __del__(self) -> None: + self.close() + + # this is compatible with _base_connection + def is_closed(self) -> bool: + return self._is_closed + + # for compatibility with RawIOBase + @property + def closed(self) -> bool: + return self.is_closed() + + def close(self) -> None: + if self.is_closed(): + return + self.read_len = 0 + self.read_pos = 0 + self.js_read_stream.cancel() + self.js_read_stream = None + self._is_closed = True + self._is_done = True + self.request = None + self.response = None + super().close() + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def seekable(self) -> bool: + return False + + def _get_next_buffer(self) -> bool: + result_js = _run_sync_with_timeout( + self.js_read_stream.read(), + self.timeout, + self.js_abort_controller, + request=self.request, + response=self.response, + ) + if result_js.done: + self._is_done = True + return False + else: + self.current_buffer = result_js.value.to_py() + self.current_buffer_pos = 0 + return True + + def readinto(self, byte_obj: Buffer) -> int: + if self.current_buffer is None: + if not self._get_next_buffer() or self.current_buffer is None: + self.close() + return 0 + ret_length = min( + len(byte_obj), len(self.current_buffer) - self.current_buffer_pos + ) + byte_obj[0:ret_length] = self.current_buffer[ + self.current_buffer_pos : self.current_buffer_pos + ret_length + ] + self.current_buffer_pos += ret_length + if self.current_buffer_pos == len(self.current_buffer): + self.current_buffer = None + return ret_length + + +# check if we are in a worker or not +def is_in_browser_main_thread() -> bool: + return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window + + +def is_cross_origin_isolated() -> bool: + return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated + + +def is_in_node() -> bool: + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + and hasattr(js.process.release, "name") + and js.process.release.name == "node" + ) + + +def is_worker_available() -> bool: + return hasattr(js, "Worker") and hasattr(js, "Blob") + + +_fetcher: _StreamingFetcher | None = None + +if is_worker_available() and ( + (is_cross_origin_isolated() and not is_in_browser_main_thread()) + and (not is_in_node()) +): + _fetcher = _StreamingFetcher() +else: + _fetcher = None + + +NODE_JSPI_ERROR = ( + "urllib3 only works in Node.js with pyodide.runPythonAsync" + " and requires the flag --experimental-wasm-stack-switching in " + " versions of node <24." +) + + +def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: + if has_jspi(): + return send_jspi_request(request, True) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + + if _fetcher and streaming_ready(): + return _fetcher.send(request) + else: + _show_streaming_warning() + return None + + +_SHOWN_TIMEOUT_WARNING = False + + +def _show_timeout_warning() -> None: + global _SHOWN_TIMEOUT_WARNING + if not _SHOWN_TIMEOUT_WARNING: + _SHOWN_TIMEOUT_WARNING = True + message = "Warning: Timeout is not available on main browser thread" + js.console.warn(message) + + +_SHOWN_STREAMING_WARNING = False + + +def _show_streaming_warning() -> None: + global _SHOWN_STREAMING_WARNING + if not _SHOWN_STREAMING_WARNING: + _SHOWN_STREAMING_WARNING = True + message = "Can't stream HTTP requests because: \n" + if not is_cross_origin_isolated(): + message += " Page is not cross-origin isolated\n" + if is_in_browser_main_thread(): + message += " Python is running in main browser thread\n" + if not is_worker_available(): + message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in + if streaming_ready() is False: + message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch +is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" + from js import console + + console.warn(message) + + +def send_request(request: EmscriptenRequest) -> EmscriptenResponse: + if has_jspi(): + return send_jspi_request(request, False) + elif is_in_node(): + raise _RequestError( + message=NODE_JSPI_ERROR, + request=request, + response=None, + ) + try: + js_xhr = js.XMLHttpRequest.new() + + if not is_in_browser_main_thread(): + js_xhr.responseType = "arraybuffer" + if request.timeout: + js_xhr.timeout = int(request.timeout * 1000) + else: + js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") + if request.timeout: + # timeout isn't available on the main thread - show a warning in console + # if it is set + _show_timeout_warning() + + js_xhr.open(request.method, request.url, False) + for name, value in request.headers.items(): + if name.lower() not in HEADERS_TO_IGNORE: + js_xhr.setRequestHeader(name, value) + + js_xhr.send(to_js(request.body)) + + headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) + + if not is_in_browser_main_thread(): + body = js_xhr.response.to_py().tobytes() + else: + body = js_xhr.response.encode("ISO-8859-15") + return EmscriptenResponse( + status_code=js_xhr.status, headers=headers, body=body, request=request + ) + except JsException as err: + if err.name == "TimeoutError": + raise _TimeoutError(err.message, request=request) + elif err.name == "NetworkError": + raise _RequestError(err.message, request=request) + else: + # general http error + raise _RequestError(err.message, request=request) + + +def send_jspi_request( + request: EmscriptenRequest, streaming: bool +) -> EmscriptenResponse: + """ + Send a request using WebAssembly JavaScript Promise Integration + to wrap the asynchronous JavaScript fetch api (experimental). + + :param request: + Request to send + + :param streaming: + Whether to stream the response + + :return: The response object + :rtype: EmscriptenResponse + """ + timeout = request.timeout + js_abort_controller = js.AbortController.new() + headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} + req_body = request.body + fetch_data = { + "headers": headers, + "body": to_js(req_body), + "method": request.method, + "signal": js_abort_controller.signal, + } + # Node.js returns the whole response (unlike opaqueredirect in browsers), + # so urllib3 can set `redirect: manual` to control redirects itself. + # https://stackoverflow.com/a/78524615 + if _is_node_js(): + fetch_data["redirect"] = "manual" + # Call JavaScript fetch (async api, returns a promise) + fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) + # Now suspend WebAssembly until we resolve that promise + # or time out. + response_js = _run_sync_with_timeout( + fetcher_promise_js, + timeout, + js_abort_controller, + request=request, + response=None, + ) + headers = {} + header_iter = response_js.headers.entries() + while True: + iter_value_js = header_iter.next() + if getattr(iter_value_js, "done", False): + break + else: + headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) + status_code = response_js.status + body: bytes | io.RawIOBase = b"" + + response = EmscriptenResponse( + status_code=status_code, headers=headers, body=b"", request=request + ) + if streaming: + # get via inputstream + if response_js.body is not None: + # get a reader from the fetch response + body_stream_js = response_js.body.getReader() + body = _JSPIReadStream( + body_stream_js, timeout, request, response, js_abort_controller + ) + else: + # get directly via arraybuffer + # n.b. this is another async JavaScript call. + body = _run_sync_with_timeout( + response_js.arrayBuffer(), + timeout, + js_abort_controller, + request=request, + response=response, + ).to_py() + response.body = body + return response + + +def _run_sync_with_timeout( + promise: Any, + timeout: float, + js_abort_controller: Any, + request: EmscriptenRequest | None, + response: EmscriptenResponse | None, +) -> Any: + """ + Await a JavaScript promise synchronously with a timeout which is implemented + via the AbortController + + :param promise: + Javascript promise to await + + :param timeout: + Timeout in seconds + + :param js_abort_controller: + A JavaScript AbortController object, used on timeout + + :param request: + The request being handled + + :param response: + The response being handled (if it exists yet) + + :raises _TimeoutError: If the request times out + :raises _RequestError: If the request raises a JavaScript exception + + :return: The result of awaiting the promise. + """ + timer_id = None + if timeout > 0: + timer_id = js.setTimeout( + js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) + ) + try: + from pyodide.ffi import run_sync + + # run_sync here uses WebAssembly JavaScript Promise Integration to + # suspend python until the JavaScript promise resolves. + return run_sync(promise) + except JsException as err: + if err.name == "AbortError": + raise _TimeoutError( + message="Request timed out", request=request, response=response + ) + else: + raise _RequestError(message=err.message, request=request, response=response) + finally: + if timer_id is not None: + js.clearTimeout(timer_id) + + +def has_jspi() -> bool: + """ + Return true if jspi can be used. + + This requires both browser support and also WebAssembly + to be in the correct state - i.e. that the javascript + call into python was async not sync. + + :return: True if jspi can be used. + :rtype: bool + """ + try: + from pyodide.ffi import can_run_sync, run_sync # noqa: F401 + + return bool(can_run_sync()) + except ImportError: + return False + + +def _is_node_js() -> bool: + """ + Check if we are in Node.js. + + :return: True if we are in Node.js. + :rtype: bool + """ + return ( + hasattr(js, "process") + and hasattr(js.process, "release") + # According to the Node.js documentation, the release name is always "node". + and js.process.release.name == "node" + ) + + +def streaming_ready() -> bool | None: + if _fetcher: + return _fetcher.streaming_ready + else: + return None # no fetcher, return None to signify that + + +async def wait_for_streaming_ready() -> bool: + if _fetcher: + await _fetcher.js_worker_ready_promise + return True + else: + return False diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/request.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/response.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1088a1826d089e1b603c51e85560b8583a3e3d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,277 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + version_string="HTTP/?", + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None and amt >= 0: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content: + self._body = data + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Deserializes the body of the HTTP response as a Python object. + + The body of the HTTP response must be encoded using UTF-8, as per + `RFC 8529 Section 8.1 `_. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to + your custom decoder instead. + + If the body of the HTTP response is not decodable to UTF-8, a + `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a + valid JSON document, a `json.JSONDecodeError` will be raised. + + Read more :ref:`here `. + + :returns: The body of the HTTP response as a Python object. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/pyopenssl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 0000000000000000000000000000000000000000..8e05d3d785d53021a97a713cbdbb1f43708c9150 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,564 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 16.0.0) +* `cryptography`_ (minimum 1.3.4, from pyopenssl) +* `idna`_ (minimum 2.0) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL # type: ignore[import-not-found] +from cryptography import x509 + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from io import BytesIO +from socket import socket as socket_cls +from socket import timeout + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 # type: ignore[import-not-found] + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, +} + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data # type: ignore[no-any-return] + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) # type: ignore[no-any-return] + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise timeout() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self, how: int) -> None: + try: + self.connection.shutdown() + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"shutdown error: {e!r}") from e + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | None: + x509 = self.connection.get_peer_certificate() + + if not x509: + return x509 # type: ignore[no-any-return] + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return] + + return { + "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() # type: ignore[no-any-return] + + def selected_alpn_protocol(self) -> str | None: + alpn_proto = self.connection.get_alpn_proto_negotiated() + return alpn_proto.decode() if alpn_proto else None + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_flags(self) -> int: + return self._verify_flags + + @verify_flags.setter + def verify_flags(self, value: int) -> None: + self._verify_flags = value + self._ctx.get_cert_store().set_flags(self._verify_flags) + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(BytesIO(cadata)) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") # type: ignore[assignment] + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise timeout("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/socks.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..e3239b569d93c6139f9c6a86118a5884daf1dabd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,228 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks # type: ignore[import-untyped] +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + + +class _TYPE_SOCKS_OPTIONS(typing.TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None and parsed.auth is not None: + split = parsed.auth.split(":") + if len(split) == 2: + username, password = split + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..133e1d8f237f6fddd557ae1c0e0cf738f7cc2748 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__init__.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from importlib.metadata import version + +__all__ = [ + "inject_into_urllib3", + "extract_from_urllib3", +] + +import typing + +orig_HTTPSConnection: typing.Any = None + + +def inject_into_urllib3() -> None: + # First check if h2 version is valid + h2_version = version("h2") + if not h2_version.startswith("4."): + raise ImportError( + "urllib3 v2 supports h2 version 4.x.x, currently " + f"the 'h2' module is compiled with {h2_version!r}. " + "See: https://github.com/urllib3/urllib3/issues/3290" + ) + + # Import here to avoid circular dependencies. + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + from .connection import HTTP2Connection + + global orig_HTTPSConnection + orig_HTTPSConnection = urllib3_connection.HTTPSConnection + + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3_connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3_util.ALPN_PROTOCOLS = ["h2"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + from .. import connection as urllib3_connection + from .. import util as urllib3_util + from ..connectionpool import HTTPSConnectionPool + from ..util import ssl_ as urllib3_util_ssl + + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3_connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3_util.ALPN_PROTOCOLS = ["http/1.1"] + urllib3_util_ssl.ALPN_PROTOCOLS = ["http/1.1"] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e696a371eaf08d7635901c9559d2a9b96e2bcf20 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ed45f811a6dcc646912b944465252fa32ec85e1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96debca429a76bfc897809173a319993e2b6e783 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/__pycache__/probe.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/connection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..0a026da0a8357e324ded47b82b24042713b9bf06 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/connection.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +import logging +import re +import threading +import types +import typing + +import h2.config +import h2.connection +import h2.events + +from .._base_connection import _TYPE_BODY +from .._collections import HTTPHeaderDict +from ..connection import HTTPSConnection, _get_default_user_agent +from ..exceptions import ConnectionError +from ..response import BaseHTTPResponse + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + +log = logging.getLogger(__name__) + +RE_IS_LEGAL_HEADER_NAME = re.compile(rb"^[!#$%&'*+\-.^_`|~0-9a-z]+$") +RE_IS_ILLEGAL_HEADER_VALUE = re.compile(rb"[\0\x00\x0a\x0d\r\n]|^[ \r\n\t]|[ \r\n\t]$") + + +def _is_legal_header_name(name: bytes) -> bool: + """ + "An implementation that validates fields according to the definitions in Sections + 5.1 and 5.5 of [HTTP] only needs an additional check that field names do not + include uppercase characters." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + + `http.client._is_legal_header_name` does not validate the field name according to the + HTTP 1.1 spec, so we do that here, in addition to checking for uppercase characters. + + This does not allow for the `:` character in the header name, so should not + be used to validate pseudo-headers. + """ + return bool(RE_IS_LEGAL_HEADER_NAME.match(name)) + + +def _is_illegal_header_value(value: bytes) -> bool: + """ + "A field value MUST NOT contain the zero value (ASCII NUL, 0x00), line feed + (ASCII LF, 0x0a), or carriage return (ASCII CR, 0x0d) at any position. A field + value MUST NOT start or end with an ASCII whitespace character (ASCII SP or HTAB, + 0x20 or 0x09)." (https://httpwg.org/specs/rfc9113.html#n-field-validity) + """ + return bool(RE_IS_ILLEGAL_HEADER_VALUE.search(value)) + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + __slots__ = ( + "lock", + "_obj", + ) + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + if self._tunnel_host is not None: + raise NotImplementedError("Tunneling isn't supported with HTTP/2") + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + with self._h2_conn as conn: + conn.initiate_connection() + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + def putrequest( # type: ignore[override] + self, + method: str, + url: str, + **kwargs: typing.Any, + ) -> None: + """putrequest + This deviates from the HTTPConnection method signature since we never need to override + sending accept-encoding headers or the host header. + """ + if "skip_host" in kwargs: + raise NotImplementedError("`skip_host` isn't supported") + if "skip_accept_encoding" in kwargs: + raise NotImplementedError("`skip_accept_encoding` isn't supported") + + self._request_url = url or "/" + self._validate_path(url) # type: ignore[attr-defined] + + if ":" in self.host: + authority = f"[{self.host}]:{self.port or 443}" + else: + authority = f"{self.host}:{self.port or 443}" + + self._headers.append((b":scheme", b"https")) + self._headers.append((b":method", method.encode())) + self._headers.append((b":authority", authority.encode())) + self._headers.append((b":path", url.encode())) + + with self._h2_conn as conn: + self._h2_stream = conn.get_next_available_stream_id() + + def putheader(self, header: str | bytes, *values: str | bytes) -> None: # type: ignore[override] + # TODO SKIPPABLE_HEADERS from urllib3 are ignored. + header = header.encode() if isinstance(header, str) else header + header = header.lower() # A lot of upstream code uses capitalized headers. + if not _is_legal_header_name(header): + raise ValueError(f"Illegal header name {str(header)}") + + for value in values: + value = value.encode() if isinstance(value, str) else value + if _is_illegal_header_value(value): + raise ValueError(f"Illegal header value {str(value)}") + self._headers.append((header, value)) + + def endheaders(self, message_body: typing.Any = None) -> None: # type: ignore[override] + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + conn.send_headers( + stream_id=self._h2_stream, + headers=self._headers, + end_stream=(message_body is None), + ) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + self._headers = [] # Reset headers for the next request. + + def send(self, data: typing.Any) -> None: + """Send data to the server. + `data` can be: `str`, `bytes`, an iterable, or file-like objects + that support a .read() method. + """ + if self._h2_stream is None: + raise ConnectionError("Must call `putrequest` first.") + + with self._h2_conn as conn: + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + if hasattr(data, "read"): # file-like objects + while True: + chunk = data.read(self.blocksize) + if not chunk: + break + if isinstance(chunk, str): + chunk = chunk.encode() + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + return + + if isinstance(data, str): # str -> bytes + data = data.encode() + + try: + if isinstance(data, bytes): + conn.send_data(self._h2_stream, data, end_stream=True) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + else: + for chunk in data: + conn.send_data(self._h2_stream, chunk, end_stream=False) + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + conn.end_stream(self._h2_stream) + except TypeError: + raise TypeError( + "`data` should be str, bytes, iterable, or file. got %r" + % type(data) + ) + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + raise NotImplementedError( + "HTTP/2 does not support setting up a tunnel through a proxy" + ) + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := conn.data_to_send(): + self.sock.sendall(data_to_send) + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def request( # type: ignore[override] + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + *, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + **kwargs: typing.Any, + ) -> None: + """Send an HTTP/2 request""" + if "chunked" in kwargs: + # TODO this is often present from upstream. + # raise NotImplementedError("`chunked` isn't supported with HTTP/2") + pass + + if self.sock is not None: + self.sock.settimeout(self.timeout) + + self.putrequest(method, url) + + headers = headers or {} + for k, v in headers.items(): + if k.lower() == "transfer-encoding" and v == "chunked": + continue + else: + self.putheader(k, v) + + if b"user-agent" not in dict(self._headers): + self.putheader(b"user-agent", _get_default_user_agent()) + + if body: + self.endheaders(message_body=body) + self.send(body) + else: + self.endheaders() + + def close(self) -> None: + with self._h2_conn as conn: + try: + conn.close_connection() + if data := conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + version_string="HTTP/2", + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/probe.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/probe.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea900764f0885eafaac9454523417d86e33df2d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/http2/probe.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import threading + + +class _HTTP2ProbeCache: + __slots__ = ( + "_lock", + "_cache_locks", + "_cache_values", + ) + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cache_locks: dict[tuple[str, int], threading.RLock] = {} + self._cache_values: dict[tuple[str, int], bool | None] = {} + + def acquire_and_get(self, host: str, port: int) -> bool | None: + # By the end of this block we know that + # _cache_[values,locks] is available. + value = None + with self._lock: + key = (host, port) + try: + value = self._cache_values[key] + # If it's a known value we return right away. + if value is not None: + return value + except KeyError: + self._cache_locks[key] = threading.RLock() + self._cache_values[key] = None + + # If the value is unknown, we acquire the lock to signal + # to the requesting thread that the probe is in progress + # or that the current thread needs to return their findings. + key_lock = self._cache_locks[key] + key_lock.acquire() + try: + # If the by the time we get the lock the value has been + # updated we want to return the updated value. + value = self._cache_values[key] + + # In case an exception like KeyboardInterrupt is raised here. + except BaseException as e: # Defensive: + assert not isinstance(e, KeyError) # KeyError shouldn't be possible. + key_lock.release() + raise + + return value + + def set_and_release( + self, host: str, port: int, supports_http2: bool | None + ) -> None: + key = (host, port) + key_lock = self._cache_locks[key] + with key_lock: # Uses an RLock, so can be locked again from same thread. + if supports_http2 is None and self._cache_values[key] is not None: + raise ValueError( + "Cannot reset HTTP/2 support for origin after value has been set." + ) # Defensive: not expected in normal usage + + self._cache_values[key] = supports_http2 + key_lock.release() + + def _values(self) -> dict[tuple[str, int], bool | None]: + """This function is for testing purposes only. Gets the current state of the probe cache""" + with self._lock: + return {k: v for k, v in self._cache_values.items()} + + def _reset(self) -> None: + """This function is for testing purposes only. Reset the cache values""" + with self._lock: + self._cache_locks = {} + self._cache_values = {} + + +_HTTP2_PROBE_CACHE = _HTTP2ProbeCache() + +set_and_release = _HTTP2_PROBE_CACHE.set_and_release +acquire_and_get = _HTTP2_PROBE_CACHE.acquire_and_get +_values = _HTTP2_PROBE_CACHE._values +_reset = _HTTP2_PROBE_CACHE._reset + +__all__ = [ + "set_and_release", + "acquire_and_get", +] diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..534126033c083203649022fa9b753a433f005556 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__init__.py @@ -0,0 +1,42 @@ +# For backwards compatibility, provide imports that used to be here. +from __future__ import annotations + +from .connection import is_connection_dropped +from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers +from .response import is_fp_closed +from .retry import Retry +from .ssl_ import ( + ALPN_PROTOCOLS, + IS_PYOPENSSL, + SSLContext, + assert_fingerprint, + create_urllib3_context, + resolve_cert_reqs, + resolve_ssl_version, + ssl_wrap_socket, +) +from .timeout import Timeout +from .url import Url, parse_url +from .wait import wait_for_read, wait_for_write + +__all__ = ( + "IS_PYOPENSSL", + "SSLContext", + "ALPN_PROTOCOLS", + "Retry", + "Timeout", + "Url", + "assert_fingerprint", + "create_urllib3_context", + "is_connection_dropped", + "is_fp_closed", + "parse_url", + "make_headers", + "resolve_cert_reqs", + "resolve_ssl_version", + "ssl_wrap_socket", + "wait_for_read", + "wait_for_write", + "SKIP_HEADER", + "SKIPPABLE_HEADERS", +) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ff3cf51f32231b6764241831cbb0f9aa232b5e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..096f39e099af002006714b0439a4a83f4ec2c93d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/connection.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6fb73c7e00e0775354e3add989c05a01a8cea93 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/proxy.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a408c6cee9d9230ec6208c5bbff72eddb95b7e68 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/request.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6208fdd3a7b27bd375396d7d24bcbfe4bb7cb914 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/response.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78b3b7a90cb1b8b8c1c9e236c208d7f0905f0326 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/retry.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09961489a570140eddd4ceb1592d29c4a8d24845 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..978a5cd2b963e306163cec03e2481aa43eb95023 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c496644ef9d3d07359e17cce543e0928227e1a54 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/ssltransport.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e2f27dc08ffe4be4b523dbbdacb149a182773c4 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/timeout.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75210d1d1d59683d55fb9ca0a2b4e39e03944e16 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/url.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa7f47423ae071e3174a05ba80b94f208bbc0216 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/util.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd874dd203f061f2f6b0d8d6266f35eb91339e6b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/__pycache__/wait.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/connection.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f92519ee9124e91e5da7d60ccc3f274312ed3514 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/connection.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import socket +import typing + +from ..exceptions import LocationParseError +from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT + +_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]] + +if typing.TYPE_CHECKING: + from .._base_connection import BaseHTTPConnection + + +def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific + """ + Returns True if the connection is dropped and should be closed. + :param conn: :class:`urllib3.connection.HTTPConnection` object. + """ + return not conn.is_connected + + +# This function is copied from socket.py in the Python 2.7 standard +# library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. +def create_connection( + address: tuple[str, int], + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, +) -> socket.socket: + """Connect to *address* and return the socket object. + + Convenience function. Connect to *address* (a 2-tuple ``(host, + port)``) and return the socket object. Passing the optional + *timeout* parameter will set the timeout on the socket instance + before attempting to connect. If no *timeout* is supplied, the + global default timeout setting returned by :func:`socket.getdefaulttimeout` + is used. If *source_address* is set it must be a tuple of (host, port) + for the socket to bind as a source address before making the connection. + An host of '' or port 0 tells the OS to use the default. + """ + + host, port = address + if host.startswith("["): + host = host.strip("[]") + err = None + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + try: + host.encode("idna") + except UnicodeError: + raise LocationParseError(f"'{host}', label empty or too long") from None + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + sock = None + try: + sock = socket.socket(af, socktype, proto) + + # If provided, set socket level options before connecting. + _set_socket_options(sock, socket_options) + + if timeout is not _DEFAULT_TIMEOUT: + sock.settimeout(timeout) + if source_address: + sock.bind(source_address) + sock.connect(sa) + # Break explicitly a reference cycle + err = None + return sock + + except OSError as _: + err = _ + if sock is not None: + sock.close() + + if err is not None: + try: + raise err + finally: + # Break explicitly a reference cycle + err = None + else: + raise OSError("getaddrinfo returns an empty list") + + +def _set_socket_options( + sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None +) -> None: + if options is None: + return + + for opt in options: + sock.setsockopt(*opt) + + +def allowed_gai_family() -> socket.AddressFamily: + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host: str) -> bool: + """Returns True if the system can bind an IPv6 address.""" + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/urllib3/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + + +HAS_IPV6 = _has_ipv6("::1") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/proxy.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..908fc6621d0afbed16bde2c1957a5cf28d3a84d8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/proxy.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .url import Url + +if typing.TYPE_CHECKING: + from ..connection import ProxyConfig + + +def connection_requires_http_tunnel( + proxy_url: Url | None = None, + proxy_config: ProxyConfig | None = None, + destination_scheme: str | None = None, +) -> bool: + """ + Returns True if the connection requires an HTTP CONNECT through the proxy. + + :param URL proxy_url: + URL of the proxy. + :param ProxyConfig proxy_config: + Proxy configuration from poolmanager.py + :param str destination_scheme: + The scheme of the destination. (i.e https, http, etc) + """ + # If we're not using a proxy, no way to use a tunnel. + if proxy_url is None: + return False + + # HTTP destinations never require tunneling, we always forward. + if destination_scheme == "http": + return False + + # Support for forwarding with HTTPS proxies and HTTPS destinations. + if ( + proxy_url.scheme == "https" + and proxy_config + and proxy_config.use_forwarding_for_https + ): + return False + + # Otherwise always use a tunnel. + return True diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/request.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/request.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2372ba7e777826a4eb124ddfb54f0240b65d67 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/request.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import io +import sys +import typing +from base64 import b64encode +from enum import Enum + +from ..exceptions import UnrewindableBodyError +from .util import to_bytes + +if typing.TYPE_CHECKING: + from typing import Final + +# Pass as a value within ``headers`` to skip +# emitting some HTTP headers that are added automatically. +# The only headers that are supported are ``Accept-Encoding``, +# ``Host``, and ``User-Agent``. +SKIP_HEADER = "@@@SKIP_HEADER@@@" +SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"]) + +ACCEPT_ENCODING = "gzip,deflate" +try: + try: + import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 + except ImportError: + import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",br" + +try: + if sys.version_info >= (3, 14): + from compression import zstd as _unused_module_zstd # noqa: F401 + else: + from backports import zstd as _unused_module_zstd # noqa: F401 +except ImportError: + pass +else: + ACCEPT_ENCODING += ",zstd" + + +class _TYPE_FAILEDTELL(Enum): + token = 0 + + +_FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token + +_TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL] + +# When sending a request with these methods we aren't expecting +# a body so don't need to set an explicit 'Content-Length: 0' +# The reason we do this in the negative instead of tracking methods +# which 'should' have a body is because unknown methods should be +# treated as if they were 'POST' which *does* expect a body. +_METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"} + + +def make_headers( + keep_alive: bool | None = None, + accept_encoding: bool | list[str] | str | None = None, + user_agent: str | None = None, + basic_auth: str | None = None, + proxy_basic_auth: str | None = None, + disable_cache: bool | None = None, +) -> dict[str, str]: + """ + Shortcuts for generating request headers. + + :param keep_alive: + If ``True``, adds 'connection: keep-alive' header. + + :param accept_encoding: + Can be a boolean, list, or string. + ``True`` translates to 'gzip,deflate'. If the dependencies for + Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or + Zstandard (the ``backports.zstd`` package for Python before 3.14) + algorithms are installed, then their encodings are + included in the string ('br' and 'zstd', respectively). + List will get joined by comma. + String will be used as provided. + + :param user_agent: + String representing the user-agent you want, such as + "python-urllib3/0.6" + + :param basic_auth: + Colon-separated username:password string for 'authorization: basic ...' + auth header. + + :param proxy_basic_auth: + Colon-separated username:password string for 'proxy-authorization: basic ...' + auth header. + + :param disable_cache: + If ``True``, adds 'cache-control: no-cache' header. + + Example: + + .. code-block:: python + + import urllib3 + + print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0")) + # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} + print(urllib3.util.make_headers(accept_encoding=True)) + # {'accept-encoding': 'gzip,deflate'} + """ + headers: dict[str, str] = {} + if accept_encoding: + if isinstance(accept_encoding, str): + pass + elif isinstance(accept_encoding, list): + accept_encoding = ",".join(accept_encoding) + else: + accept_encoding = ACCEPT_ENCODING + headers["accept-encoding"] = accept_encoding + + if user_agent: + headers["user-agent"] = user_agent + + if keep_alive: + headers["connection"] = "keep-alive" + + if basic_auth: + headers["authorization"] = ( + f"Basic {b64encode(basic_auth.encode('latin-1')).decode()}" + ) + + if proxy_basic_auth: + headers["proxy-authorization"] = ( + f"Basic {b64encode(proxy_basic_auth.encode('latin-1')).decode()}" + ) + + if disable_cache: + headers["cache-control"] = "no-cache" + + return headers + + +def set_file_position( + body: typing.Any, pos: _TYPE_BODY_POSITION | None +) -> _TYPE_BODY_POSITION | None: + """ + If a position is provided, move file to that point. + Otherwise, we'll attempt to record a position for future use. + """ + if pos is not None: + rewind_body(body, pos) + elif getattr(body, "tell", None) is not None: + try: + pos = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body. + pos = _FAILEDTELL + + return pos + + +def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None: + """ + Attempt to rewind body to a certain position. + Primarily used for request redirects and retries. + + :param body: + File-like object that supports seek. + + :param int pos: + Position to seek to in file. + """ + body_seek = getattr(body, "seek", None) + if body_seek is not None and isinstance(body_pos, int): + try: + body_seek(body_pos) + except OSError as e: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect/retry." + ) from e + elif body_pos is _FAILEDTELL: + raise UnrewindableBodyError( + "Unable to record file position for rewinding " + "request body during a redirect/retry." + ) + else: + raise ValueError( + f"body_pos must be of type integer, instead it was {type(body_pos)}." + ) + + +class ChunksAndContentLength(typing.NamedTuple): + chunks: typing.Iterable[bytes] | None + content_length: int | None + + +def body_to_chunks( + body: typing.Any | None, method: str, blocksize: int +) -> ChunksAndContentLength: + """Takes the HTTP request method, body, and blocksize and + transforms them into an iterable of chunks to pass to + socket.sendall() and an optional 'Content-Length' header. + + A 'Content-Length' of 'None' indicates the length of the body + can't be determined so should use 'Transfer-Encoding: chunked' + for framing instead. + """ + + chunks: typing.Iterable[bytes] | None + content_length: int | None + + # No body, we need to make a recommendation on 'Content-Length' + # based on whether that request method is expected to have + # a body or not. + if body is None: + chunks = None + if method.upper() not in _METHODS_NOT_EXPECTING_BODY: + content_length = 0 + else: + content_length = None + + # Bytes or strings become bytes + elif isinstance(body, (str, bytes)): + chunks = (to_bytes(body),) + content_length = len(chunks[0]) + + # File-like object, TODO: use seek() and tell() for length? + elif hasattr(body, "read"): + + def chunk_readable() -> typing.Iterable[bytes]: + encode = isinstance(body, io.TextIOBase) + while True: + datablock = body.read(blocksize) + if not datablock: + break + if encode: + datablock = datablock.encode("utf-8") + yield datablock + + chunks = chunk_readable() + content_length = None + + # Otherwise we need to start checking via duck-typing. + else: + try: + # Check if the body implements the buffer API. + mv = memoryview(body) + except TypeError: + try: + # Check if the body is an iterable + chunks = iter(body) + content_length = None + except TypeError: + raise TypeError( + f"'body' must be a bytes-like object, file-like " + f"object, or iterable. Instead was {body!r}" + ) from None + else: + # Since it implements the buffer API can be passed directly to socket.sendall() + chunks = (body,) + content_length = mv.nbytes + + return ChunksAndContentLength(chunks=chunks, content_length=content_length) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/response.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/response.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4578696fa2e17a900c6890ec26d65e860b0b72 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/response.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import http.client as httplib +from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect + +from ..exceptions import HeaderParsingError + + +def is_fp_closed(obj: object) -> bool: + """ + Checks whether a given file-like object is closed. + + :param obj: + The file-like object to check. + """ + + try: + # Check `isclosed()` first, in case Python3 doesn't set `closed`. + # GH Issue #928 + return obj.isclosed() # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check via the official file-like-object way. + return obj.closed # type: ignore[no-any-return, attr-defined] + except AttributeError: + pass + + try: + # Check if the object is a container for another file-like object that + # gets released on exhaustion (e.g. HTTPResponse). + return obj.fp is None # type: ignore[attr-defined] + except AttributeError: + pass + + raise ValueError("Unable to determine whether fp is closed.") + + +def assert_header_parsing(headers: httplib.HTTPMessage) -> None: + """ + Asserts whether all headers have been successfully parsed. + Extracts encountered errors from the result of parsing headers. + + Only works on Python 3. + + :param http.client.HTTPMessage headers: Headers to verify. + + :raises urllib3.exceptions.HeaderParsingError: + If parsing errors are found. + """ + + # This will fail silently if we pass in the wrong kind of parameter. + # To make debugging easier add an explicit check. + if not isinstance(headers, httplib.HTTPMessage): + raise TypeError(f"expected httplib.Message, got {type(headers)}.") + + unparsed_data = None + + # get_payload is actually email.message.Message.get_payload; + # we're only interested in the result if it's not a multipart message + if not headers.is_multipart(): + payload = headers.get_payload() + + if isinstance(payload, (bytes, str)): + unparsed_data = payload + + # httplib is assuming a response body is available + # when parsing headers even when httplib only sends + # header data to parse_headers() This results in + # defects on multipart responses in particular. + # See: https://github.com/urllib3/urllib3/issues/800 + + # So we ignore the following defects: + # - StartBoundaryNotFoundDefect: + # The claimed start boundary was never found. + # - MultipartInvariantViolationDefect: + # A message claimed to be a multipart but no subparts were found. + defects = [ + defect + for defect in headers.defects + if not isinstance( + defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) + ) + ] + + if defects or unparsed_data: + raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) + + +def is_response_to_head(response: httplib.HTTPResponse) -> bool: + """ + Checks whether the request of a response has been a HEAD-request. + + :param http.client.HTTPResponse response: + Response to check if the originating request + used 'HEAD' as a method. + """ + # FIXME: Can we do this somehow without accessing private httplib _method? + method_str = response._method # type: str # type: ignore[attr-defined] + return method_str.upper() == "HEAD" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/retry.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/retry.py new file mode 100644 index 0000000000000000000000000000000000000000..b21b4b64ebbd4748eb6fa4301f947b0d4965da8b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/retry.py @@ -0,0 +1,549 @@ +from __future__ import annotations + +import email +import logging +import random +import re +import time +import typing +from itertools import takewhile +from types import TracebackType + +from ..exceptions import ( + ConnectTimeoutError, + InvalidHeader, + MaxRetryError, + ProtocolError, + ProxyError, + ReadTimeoutError, + ResponseError, +) +from .util import reraise + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from ..connectionpool import ConnectionPool + from ..response import BaseHTTPResponse + +log = logging.getLogger(__name__) + + +# Data structure for representing the metadata of requests that result in a retry. +class RequestHistory(typing.NamedTuple): + method: str | None + url: str | None + error: Exception | None + status: int | None + redirect_location: str | None + + +class Retry: + """Retry configuration. + + Each retry attempt will create a new Retry object with updated values, so + they can be safely reused. + + Retries can be defined as a default for a pool: + + .. code-block:: python + + retries = Retry(connect=5, read=2, redirect=5) + http = PoolManager(retries=retries) + response = http.request("GET", "https://example.com/") + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=Retry(10)) + + Retries can be disabled by passing ``False``: + + .. code-block:: python + + response = http.request("GET", "https://example.com/", retries=False) + + Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless + retries are disabled, in which case the causing exception will be raised. + + :param int total: + Total number of retries to allow. Takes precedence over other counts. + + Set to ``None`` to remove this constraint and fall back on other + counts. + + Set to ``0`` to fail on the first retry. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int connect: + How many connection-related errors to retry on. + + These are errors raised before the request is sent to the remote server, + which we assume has not triggered the server to process the request. + + Set to ``0`` to fail on the first retry of this type. + + :param int read: + How many times to retry on read errors. + + These errors are raised after the request was sent to the server, so the + request may have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + :param int redirect: + How many redirects to perform. Limit this to avoid infinite redirect + loops. + + A redirect is a HTTP response with a status code 301, 302, 303, 307 or + 308. + + Set to ``0`` to fail on the first retry of this type. + + Set to ``False`` to disable and imply ``raise_on_redirect=False``. + + :param int status: + How many times to retry on bad status codes. + + These are retries made on responses, where status code matches + ``status_forcelist``. + + Set to ``0`` to fail on the first retry of this type. + + :param int other: + How many times to retry on other errors. + + Other errors are errors that are not connect, read, redirect or status errors. + These errors might be raised after the request was sent to the server, so the + request might have side-effects. + + Set to ``0`` to fail on the first retry of this type. + + If ``total`` is not set, it's a good idea to set this to 0 to account + for unexpected edge cases and avoid infinite retry loops. + + :param Collection allowed_methods: + Set of uppercased HTTP method verbs that we should retry on. + + By default, we only retry on methods which are considered to be + idempotent (multiple requests with the same parameters end with the + same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`. + + Set to a ``None`` value to retry on any verb. + + :param Collection status_forcelist: + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``allowed_methods`` + and the response status code is in ``status_forcelist``. + + By default, this is disabled with ``None``. + + :param float backoff_factor: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: + + {backoff factor} * (2 ** ({number of previous retries})) + + seconds. If `backoff_jitter` is non-zero, this sleep is extended by:: + + random.uniform(0, {backoff jitter}) + + seconds. For example, if the backoff_factor is 0.1, then :func:`Retry.sleep` will + sleep for [0.0s, 0.2s, 0.4s, 0.8s, ...] between retries. No backoff will ever + be longer than `backoff_max`. + + By default, backoff is disabled (factor set to 0). + + :param bool raise_on_redirect: Whether, if the number of redirects is + exhausted, to raise a MaxRetryError, or to return a response with a + response code in the 3xx range. + + :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: + whether we should raise an exception, or return a response, + if status falls in ``status_forcelist`` range and retries have + been exhausted. + + :param tuple history: The history of the request encountered during + each call to :meth:`~Retry.increment`. The list is in the order + the requests occurred. Each list item is of class :class:`RequestHistory`. + + :param bool respect_retry_after_header: + Whether to respect Retry-After header on status codes defined as + :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. + + :param Collection remove_headers_on_redirect: + Sequence of headers to remove from the request when a response + indicating a redirect is returned before firing off the redirected + request. + + :param int retry_after_max: Number of seconds to allow as the maximum for + Retry-After headers. Defaults to :attr:`Retry.DEFAULT_RETRY_AFTER_MAX`. + Any Retry-After headers larger than this value will be limited to this + value. + """ + + #: Default methods to be used for ``allowed_methods`` + DEFAULT_ALLOWED_METHODS = frozenset( + ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] + ) + + #: Default status codes to be used for ``status_forcelist`` + RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) + + #: Default headers to be used for ``remove_headers_on_redirect`` + DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset( + ["Cookie", "Authorization", "Proxy-Authorization"] + ) + + #: Default maximum backoff time. + DEFAULT_BACKOFF_MAX = 120 + + # This is undocumented in the RFC. Setting to 6 hours matches other popular libraries. + #: Default maximum allowed value for Retry-After headers in seconds + DEFAULT_RETRY_AFTER_MAX: typing.Final[int] = 21600 + + # Backward compatibility; assigned outside of the class. + DEFAULT: typing.ClassVar[Retry] + + def __init__( + self, + total: bool | int | None = 10, + connect: int | None = None, + read: int | None = None, + redirect: bool | int | None = None, + status: int | None = None, + other: int | None = None, + allowed_methods: typing.Collection[str] | None = DEFAULT_ALLOWED_METHODS, + status_forcelist: typing.Collection[int] | None = None, + backoff_factor: float = 0, + backoff_max: float = DEFAULT_BACKOFF_MAX, + raise_on_redirect: bool = True, + raise_on_status: bool = True, + history: tuple[RequestHistory, ...] | None = None, + respect_retry_after_header: bool = True, + remove_headers_on_redirect: typing.Collection[ + str + ] = DEFAULT_REMOVE_HEADERS_ON_REDIRECT, + backoff_jitter: float = 0.0, + retry_after_max: int = DEFAULT_RETRY_AFTER_MAX, + ) -> None: + self.total = total + self.connect = connect + self.read = read + self.status = status + self.other = other + + if redirect is False or total is False: + redirect = 0 + raise_on_redirect = False + + self.redirect = redirect + self.status_forcelist = status_forcelist or set() + self.allowed_methods = allowed_methods + self.backoff_factor = backoff_factor + self.backoff_max = backoff_max + self.retry_after_max = retry_after_max + self.raise_on_redirect = raise_on_redirect + self.raise_on_status = raise_on_status + self.history = history or () + self.respect_retry_after_header = respect_retry_after_header + self.remove_headers_on_redirect = frozenset( + h.lower() for h in remove_headers_on_redirect + ) + self.backoff_jitter = backoff_jitter + + def new(self, **kw: typing.Any) -> Self: + params = dict( + total=self.total, + connect=self.connect, + read=self.read, + redirect=self.redirect, + status=self.status, + other=self.other, + allowed_methods=self.allowed_methods, + status_forcelist=self.status_forcelist, + backoff_factor=self.backoff_factor, + backoff_max=self.backoff_max, + retry_after_max=self.retry_after_max, + raise_on_redirect=self.raise_on_redirect, + raise_on_status=self.raise_on_status, + history=self.history, + remove_headers_on_redirect=self.remove_headers_on_redirect, + respect_retry_after_header=self.respect_retry_after_header, + backoff_jitter=self.backoff_jitter, + ) + + params.update(kw) + return type(self)(**params) # type: ignore[arg-type] + + @classmethod + def from_int( + cls, + retries: Retry | bool | int | None, + redirect: bool | int | None = True, + default: Retry | bool | int | None = None, + ) -> Retry: + """Backwards-compatibility for the old retries format.""" + if retries is None: + retries = default if default is not None else cls.DEFAULT + + if isinstance(retries, Retry): + return retries + + redirect = bool(redirect) and None + new_retries = cls(retries, redirect=redirect) + log.debug("Converted retries value: %r -> %r", retries, new_retries) + return new_retries + + def get_backoff_time(self) -> float: + """Formula for computing the current backoff + + :rtype: float + """ + # We want to consider only the last consecutive errors sequence (Ignore redirects). + consecutive_errors_len = len( + list( + takewhile(lambda x: x.redirect_location is None, reversed(self.history)) + ) + ) + if consecutive_errors_len <= 1: + return 0 + + backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) + if self.backoff_jitter != 0.0: + backoff_value += random.random() * self.backoff_jitter + return float(max(0, min(self.backoff_max, backoff_value))) + + def parse_retry_after(self, retry_after: str) -> float: + seconds: float + # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 + if re.match(r"^\s*[0-9]+\s*$", retry_after): + seconds = int(retry_after) + else: + retry_date_tuple = email.utils.parsedate_tz(retry_after) + if retry_date_tuple is None: + raise InvalidHeader(f"Invalid Retry-After header: {retry_after}") + + retry_date = email.utils.mktime_tz(retry_date_tuple) + seconds = retry_date - time.time() + + seconds = max(seconds, 0) + + # Check the seconds do not exceed the specified maximum + if seconds > self.retry_after_max: + seconds = self.retry_after_max + + return seconds + + def get_retry_after(self, response: BaseHTTPResponse) -> float | None: + """Get the value of Retry-After in seconds.""" + + retry_after = response.headers.get("Retry-After") + + if retry_after is None: + return None + + return self.parse_retry_after(retry_after) + + def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: + retry_after = self.get_retry_after(response) + if retry_after: + time.sleep(retry_after) + return True + + return False + + def _sleep_backoff(self) -> None: + backoff = self.get_backoff_time() + if backoff <= 0: + return + time.sleep(backoff) + + def sleep(self, response: BaseHTTPResponse | None = None) -> None: + """Sleep between retry attempts. + + This method will respect a server's ``Retry-After`` response header + and sleep the duration of the time requested. If that is not present, it + will use an exponential backoff. By default, the backoff factor is 0 and + this method will return immediately. + """ + + if self.respect_retry_after_header and response: + slept = self.sleep_for_retry(response) + if slept: + return + + self._sleep_backoff() + + def _is_connection_error(self, err: Exception) -> bool: + """Errors when we're fairly sure that the server did not receive the + request, so it should be safe to retry. + """ + if isinstance(err, ProxyError): + err = err.original_error + return isinstance(err, ConnectTimeoutError) + + def _is_read_error(self, err: Exception) -> bool: + """Errors that occur after the request has been started, so we should + assume that the server began processing it. + """ + return isinstance(err, (ReadTimeoutError, ProtocolError)) + + def _is_method_retryable(self, method: str) -> bool: + """Checks if a given HTTP method should be retried upon, depending if + it is included in the allowed_methods + """ + if self.allowed_methods and method.upper() not in self.allowed_methods: + return False + return True + + def is_retry( + self, method: str, status_code: int, has_retry_after: bool = False + ) -> bool: + """Is this method/status code retryable? (Based on allowlists and control + variables such as the number of total retries to allow, whether to + respect the Retry-After header, whether this header is present, and + whether the returned status code is on the list of status codes to + be retried upon on the presence of the aforementioned header) + """ + if not self._is_method_retryable(method): + return False + + if self.status_forcelist and status_code in self.status_forcelist: + return True + + return bool( + self.total + and self.respect_retry_after_header + and has_retry_after + and (status_code in self.RETRY_AFTER_STATUS_CODES) + ) + + def is_exhausted(self) -> bool: + """Are we out of retries?""" + retry_counts = [ + x + for x in ( + self.total, + self.connect, + self.read, + self.redirect, + self.status, + self.other, + ) + if x + ] + if not retry_counts: + return False + + return min(retry_counts) < 0 + + def increment( + self, + method: str | None = None, + url: str | None = None, + response: BaseHTTPResponse | None = None, + error: Exception | None = None, + _pool: ConnectionPool | None = None, + _stacktrace: TracebackType | None = None, + ) -> Self: + """Return a new Retry object with incremented retry counters. + + :param response: A response object, or None, if the server did not + return a response. + :type response: :class:`~urllib3.response.BaseHTTPResponse` + :param Exception error: An error encountered during the request, or + None if the response was received successfully. + + :return: A new ``Retry`` object. + """ + if self.total is False and error: + # Disabled, indicate to re-raise the error. + raise reraise(type(error), error, _stacktrace) + + total = self.total + if total is not None: + total -= 1 + + connect = self.connect + read = self.read + redirect = self.redirect + status_count = self.status + other = self.other + cause = "unknown" + status = None + redirect_location = None + + if error and self._is_connection_error(error): + # Connect retry? + if connect is False: + raise reraise(type(error), error, _stacktrace) + elif connect is not None: + connect -= 1 + + elif error and self._is_read_error(error): + # Read retry? + if read is False or method is None or not self._is_method_retryable(method): + raise reraise(type(error), error, _stacktrace) + elif read is not None: + read -= 1 + + elif error: + # Other retry? + if other is not None: + other -= 1 + + elif response and response.get_redirect_location(): + # Redirect retry? + if redirect is not None: + redirect -= 1 + cause = "too many redirects" + response_redirect_location = response.get_redirect_location() + if response_redirect_location: + redirect_location = response_redirect_location + status = response.status + + else: + # Incrementing because of a server error like a 500 in + # status_forcelist and the given method is in the allowed_methods + cause = ResponseError.GENERIC_ERROR + if response and response.status: + if status_count is not None: + status_count -= 1 + cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) + status = response.status + + history = self.history + ( + RequestHistory(method, url, error, status, redirect_location), + ) + + new_retry = self.new( + total=total, + connect=connect, + read=read, + redirect=redirect, + status=status_count, + other=other, + history=history, + ) + + if new_retry.is_exhausted(): + reason = error or ResponseError(cause) + raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] + + log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) + + return new_retry + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(total={self.total}, connect={self.connect}, " + f"read={self.read}, redirect={self.redirect}, status={self.status})" + ) + + +# For backwards compatibility (equivalent to pre-v1.9): +Retry.DEFAULT = Retry(3) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_.py new file mode 100644 index 0000000000000000000000000000000000000000..56fe9093adaa86b30085aef2435e49f84841df12 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_.py @@ -0,0 +1,527 @@ +from __future__ import annotations + +import hashlib +import hmac +import os +import socket +import sys +import typing +import warnings +from binascii import unhexlify + +from ..exceptions import ProxySchemeUnsupported, SSLError +from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE + +SSLContext = None +SSLTransport = None +HAS_NEVER_CHECK_COMMON_NAME = False +IS_PYOPENSSL = False +ALPN_PROTOCOLS = ["http/1.1"] + +_TYPE_VERSION_INFO = tuple[int, int, int, str, int] + +# Maps the length of a digest to a possible hash function producing this digest +HASHFUNC_MAP = { + length: getattr(hashlib, algorithm, None) + for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256")) +} + + +def _is_bpo_43522_fixed( + implementation_name: str, + version_info: _TYPE_VERSION_INFO, + pypy_version_info: _TYPE_VERSION_INFO | None, +) -> bool: + """Return True for CPython 3.9.3+ or 3.10+ and PyPy 7.3.8+ where + setting SSLContext.hostname_checks_common_name to False works. + + Outside of CPython and PyPy we don't know which implementations work + or not so we conservatively use our hostname matching as we know that works + on all implementations. + + https://github.com/urllib3/urllib3/issues/2192#issuecomment-821832963 + https://foss.heptapod.net/pypy/pypy/-/issues/3539 + """ + if implementation_name == "pypy": + # https://foss.heptapod.net/pypy/pypy/-/issues/3129 + return pypy_version_info >= (7, 3, 8) # type: ignore[operator] + elif implementation_name == "cpython": + major_minor = version_info[:2] + micro = version_info[2] + return (major_minor == (3, 9) and micro >= 3) or major_minor >= (3, 10) + else: # Defensive: + return False + + +def _is_has_never_check_common_name_reliable( + openssl_version: str, + openssl_version_number: int, + implementation_name: str, + version_info: _TYPE_VERSION_INFO, + pypy_version_info: _TYPE_VERSION_INFO | None, +) -> bool: + # As of May 2023, all released versions of LibreSSL fail to reject certificates with + # only common names, see https://github.com/urllib3/urllib3/pull/3024 + is_openssl = openssl_version.startswith("OpenSSL ") + # Before fixing OpenSSL issue #14579, the SSL_new() API was not copying hostflags + # like X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, which tripped up CPython. + # https://github.com/openssl/openssl/issues/14579 + # This was released in OpenSSL 1.1.1l+ (>=0x101010cf) + is_openssl_issue_14579_fixed = openssl_version_number >= 0x101010CF + + return is_openssl and ( + is_openssl_issue_14579_fixed + or _is_bpo_43522_fixed(implementation_name, version_info, pypy_version_info) + ) + + +if typing.TYPE_CHECKING: + from ssl import VerifyMode + from typing import TypedDict + + from .ssltransport import SSLTransport as SSLTransportType + + class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False): + subjectAltName: tuple[tuple[str, str], ...] + subject: tuple[tuple[tuple[str, str], ...], ...] + serialNumber: str + + +# Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X' +_SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {} + +try: # Do we have ssl at all? + import ssl + from ssl import ( # type: ignore[assignment] + CERT_REQUIRED, + HAS_NEVER_CHECK_COMMON_NAME, + OP_NO_COMPRESSION, + OP_NO_TICKET, + OPENSSL_VERSION, + OPENSSL_VERSION_NUMBER, + PROTOCOL_TLS, + PROTOCOL_TLS_CLIENT, + VERIFY_X509_STRICT, + OP_NO_SSLv2, + OP_NO_SSLv3, + SSLContext, + TLSVersion, + ) + + PROTOCOL_SSLv23 = PROTOCOL_TLS + + # Needed for Python 3.9 which does not define this + VERIFY_X509_PARTIAL_CHAIN = getattr(ssl, "VERIFY_X509_PARTIAL_CHAIN", 0x80000) + + # Setting SSLContext.hostname_checks_common_name = False didn't work before CPython + # 3.9.3, and 3.10 (but OK on PyPy) or OpenSSL 1.1.1l+ + if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable( + OPENSSL_VERSION, + OPENSSL_VERSION_NUMBER, + sys.implementation.name, + sys.version_info, + sys.pypy_version_info if sys.implementation.name == "pypy" else None, # type: ignore[attr-defined] + ): # Defensive: for Python < 3.9.3 + HAS_NEVER_CHECK_COMMON_NAME = False + + # Need to be careful here in case old TLS versions get + # removed in future 'ssl' module implementations. + for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"): + try: + _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr( + TLSVersion, attr + ) + except AttributeError: # Defensive: + continue + + from .ssltransport import SSLTransport # type: ignore[assignment] +except ImportError: + OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment, misc] + OP_NO_TICKET = 0x4000 # type: ignore[assignment, misc] + OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment, misc] + OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment, misc] + PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment, misc] + PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment, misc] + VERIFY_X509_PARTIAL_CHAIN = 0x80000 + VERIFY_X509_STRICT = 0x20 # type: ignore[assignment, misc] + + +_TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None] + + +def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None: + """ + Checks if given fingerprint matches the supplied certificate. + + :param cert: + Certificate as bytes object. + :param fingerprint: + Fingerprint as string of hexdigits, can be interspersed by colons. + """ + + if cert is None: + raise SSLError("No certificate for the peer.") + + fingerprint = fingerprint.replace(":", "").lower() + digest_length = len(fingerprint) + if digest_length not in HASHFUNC_MAP: + raise SSLError(f"Fingerprint of invalid length: {fingerprint}") + hashfunc = HASHFUNC_MAP.get(digest_length) + if hashfunc is None: + raise SSLError( + f"Hash function implementation unavailable for fingerprint length: {digest_length}" + ) + + # We need encode() here for py32; works on py2 and p33. + fingerprint_bytes = unhexlify(fingerprint.encode()) + + cert_digest = hashfunc(cert).digest() + + if not hmac.compare_digest(cert_digest, fingerprint_bytes): + raise SSLError( + f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"' + ) + + +def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode: + """ + Resolves the argument to a numeric constant, which can be passed to + the wrap_socket function/method from the ssl module. + Defaults to :data:`ssl.CERT_REQUIRED`. + If given a string it is assumed to be the name of the constant in the + :mod:`ssl` module or its abbreviation. + (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. + If it's neither `None` nor a string we assume it is already the numeric + constant which can directly be passed to wrap_socket. + """ + if candidate is None: + return CERT_REQUIRED + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "CERT_" + candidate) + return res # type: ignore[no-any-return] + + return candidate # type: ignore[return-value] + + +def resolve_ssl_version(candidate: None | int | str) -> int: + """ + like resolve_cert_reqs + """ + if candidate is None: + return PROTOCOL_TLS + + if isinstance(candidate, str): + res = getattr(ssl, candidate, None) + if res is None: + res = getattr(ssl, "PROTOCOL_" + candidate) + return typing.cast(int, res) + + return candidate + + +def create_urllib3_context( + ssl_version: int | None = None, + cert_reqs: int | None = None, + options: int | None = None, + ciphers: str | None = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + verify_flags: int | None = None, +) -> ssl.SSLContext: + """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3. + + :param ssl_version: + The desired protocol version to use. This will default to + PROTOCOL_SSLv23 which will negotiate the highest protocol that both + the server and your installation of OpenSSL support. + + This parameter is deprecated instead use 'ssl_minimum_version'. + :param ssl_minimum_version: + The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + :param ssl_maximum_version: + The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value. + Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the + default value. + :param cert_reqs: + Whether to require the certificate verification. This defaults to + ``ssl.CERT_REQUIRED``. + :param options: + Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, + ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. + :param ciphers: + Which cipher suites to allow the server to select. Defaults to either system configured + ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers. + :param verify_flags: + The flags for certificate verification operations. These default to + ``ssl.VERIFY_X509_PARTIAL_CHAIN`` and ``ssl.VERIFY_X509_STRICT`` for Python 3.13+. + :returns: + Constructed SSLContext object with specified options + :rtype: SSLContext + """ + if SSLContext is None: + raise TypeError("Can't create an SSLContext object without an ssl module") + + # This means 'ssl_version' was specified as an exact value. + if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT): + # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version' + # to avoid conflicts. + if ssl_minimum_version is not None or ssl_maximum_version is not None: + raise ValueError( + "Can't specify both 'ssl_version' and either " + "'ssl_minimum_version' or 'ssl_maximum_version'" + ) + + # 'ssl_version' is deprecated and will be removed in the future. + else: + # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead. + ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MINIMUM_SUPPORTED + ) + ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get( + ssl_version, TLSVersion.MAXIMUM_SUPPORTED + ) + + # This warning message is pushing users to use 'ssl_minimum_version' + # instead of both min/max. Best practice is to only set the minimum version and + # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED' + warnings.warn( + "'ssl_version' option is deprecated and will be " + "removed in urllib3 v2.6.0. Instead use 'ssl_minimum_version'", + category=DeprecationWarning, + stacklevel=2, + ) + + # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT + context = SSLContext(PROTOCOL_TLS_CLIENT) + + if ssl_minimum_version is not None: + context.minimum_version = ssl_minimum_version + else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here + context.minimum_version = TLSVersion.TLSv1_2 + + if ssl_maximum_version is not None: + context.maximum_version = ssl_maximum_version + + # Unless we're given ciphers defer to either system ciphers in + # the case of OpenSSL 1.1.1+ or use our own secure default ciphers. + if ciphers: + context.set_ciphers(ciphers) + + # Setting the default here, as we may have no ssl module on import + cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs + + if options is None: + options = 0 + # SSLv2 is easily broken and is considered harmful and dangerous + options |= OP_NO_SSLv2 + # SSLv3 has several problems and is now dangerous + options |= OP_NO_SSLv3 + # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ + # (issue #309) + options |= OP_NO_COMPRESSION + # TLSv1.2 only. Unless set explicitly, do not request tickets. + # This may save some bandwidth on wire, and although the ticket is encrypted, + # there is a risk associated with it being on wire, + # if the server is not rotating its ticketing keys properly. + options |= OP_NO_TICKET + + context.options |= options + + if verify_flags is None: + verify_flags = 0 + # In Python 3.13+ ssl.create_default_context() sets VERIFY_X509_PARTIAL_CHAIN + # and VERIFY_X509_STRICT so we do the same + if sys.version_info >= (3, 13): + verify_flags |= VERIFY_X509_PARTIAL_CHAIN + verify_flags |= VERIFY_X509_STRICT + + context.verify_flags |= verify_flags + + # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is + # necessary for conditional client cert authentication with TLS 1.3. + # The attribute is None for OpenSSL <= 1.1.0 or does not exist when using + # an SSLContext created by pyOpenSSL. + if getattr(context, "post_handshake_auth", None) is not None: + context.post_handshake_auth = True + + # The order of the below lines setting verify_mode and check_hostname + # matter due to safe-guards SSLContext has to prevent an SSLContext with + # check_hostname=True, verify_mode=NONE/OPTIONAL. + # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own + # 'ssl.match_hostname()' implementation. + if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL: + context.verify_mode = cert_reqs + context.check_hostname = True + else: + context.check_hostname = False + context.verify_mode = cert_reqs + + try: + context.hostname_checks_common_name = False + except AttributeError: # Defensive: for CPython < 3.9.3; for PyPy < 7.3.8 + pass + + if "SSLKEYLOGFILE" in os.environ: + sslkeylogfile = os.path.expandvars(os.environ.get("SSLKEYLOGFILE")) + else: + sslkeylogfile = None + if sslkeylogfile: + context.keylog_filename = sslkeylogfile + + return context + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: typing.Literal[False] = ..., +) -> ssl.SSLSocket: ... + + +@typing.overload +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = ..., + certfile: str | None = ..., + cert_reqs: int | None = ..., + ca_certs: str | None = ..., + server_hostname: str | None = ..., + ssl_version: int | None = ..., + ciphers: str | None = ..., + ssl_context: ssl.SSLContext | None = ..., + ca_cert_dir: str | None = ..., + key_password: str | None = ..., + ca_cert_data: None | str | bytes = ..., + tls_in_tls: bool = ..., +) -> ssl.SSLSocket | SSLTransportType: ... + + +def ssl_wrap_socket( + sock: socket.socket, + keyfile: str | None = None, + certfile: str | None = None, + cert_reqs: int | None = None, + ca_certs: str | None = None, + server_hostname: str | None = None, + ssl_version: int | None = None, + ciphers: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_cert_dir: str | None = None, + key_password: str | None = None, + ca_cert_data: None | str | bytes = None, + tls_in_tls: bool = False, +) -> ssl.SSLSocket | SSLTransportType: + """ + All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and + ca_cert_dir have the same meaning as they do when using + :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`, + :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`. + + :param server_hostname: + When SNI is supported, the expected hostname of the certificate + :param ssl_context: + A pre-made :class:`SSLContext` object. If none is provided, one will + be created using :func:`create_urllib3_context`. + :param ciphers: + A string of ciphers we wish the client to support. + :param ca_cert_dir: + A directory containing CA certificates in multiple separate files, as + supported by OpenSSL's -CApath flag or the capath argument to + SSLContext.load_verify_locations(). + :param key_password: + Optional password if the keyfile is encrypted. + :param ca_cert_data: + Optional string containing CA certificates in PEM format suitable for + passing as the cadata parameter to SSLContext.load_verify_locations() + :param tls_in_tls: + Use SSLTransport to wrap the existing socket. + """ + context = ssl_context + if context is None: + # Note: This branch of code and all the variables in it are only used in tests. + # We should consider deprecating and removing this code. + context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) + + if ca_certs or ca_cert_dir or ca_cert_data: + try: + context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) + except OSError as e: + raise SSLError(e) from e + + elif ssl_context is None and hasattr(context, "load_default_certs"): + # try to load OS default certs; works well on Windows. + context.load_default_certs() + + # Attempt to detect if we get the goofy behavior of the + # keyfile being encrypted and OpenSSL asking for the + # passphrase via the terminal and instead error out. + if keyfile and key_password is None and _is_key_file_encrypted(keyfile): + raise SSLError("Client private key is encrypted, password is required") + + if certfile: + if key_password is None: + context.load_cert_chain(certfile, keyfile) + else: + context.load_cert_chain(certfile, keyfile, key_password) + + context.set_alpn_protocols(ALPN_PROTOCOLS) + + ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname) + return ssl_sock + + +def is_ipaddress(hostname: str | bytes) -> bool: + """Detects whether the hostname given is an IPv4 or IPv6 address. + Also detects IPv6 addresses with Zone IDs. + + :param str hostname: Hostname to examine. + :return: True if the hostname is an IP address, False otherwise. + """ + if isinstance(hostname, bytes): + # IDN A-label bytes are ASCII compatible. + hostname = hostname.decode("ascii") + return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname)) + + +def _is_key_file_encrypted(key_file: str) -> bool: + """Detects if a key file is encrypted or not.""" + with open(key_file) as f: + for line in f: + # Look for Proc-Type: 4,ENCRYPTED + if "ENCRYPTED" in line: + return True + + return False + + +def _ssl_wrap_socket_impl( + sock: socket.socket, + ssl_context: ssl.SSLContext, + tls_in_tls: bool, + server_hostname: str | None = None, +) -> ssl.SSLSocket | SSLTransportType: + if tls_in_tls: + if not SSLTransport: + # Import error, ssl is not available. + raise ProxySchemeUnsupported( + "TLS in TLS requires support for the 'ssl' module" + ) + + SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) + return SSLTransport(sock, ssl_context, server_hostname) + + return ssl_context.wrap_socket(sock, server_hostname=server_hostname) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_match_hostname.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_match_hostname.py new file mode 100644 index 0000000000000000000000000000000000000000..25d91000419ea4a860f511ebe669fe171b79254c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssl_match_hostname.py @@ -0,0 +1,159 @@ +"""The match_hostname() function from Python 3.5, essential when using SSL.""" + +# Note: This file is under the PSF license as the code comes from the python +# stdlib. http://docs.python.org/3/license.html +# It is modified to remove commonName support. + +from __future__ import annotations + +import ipaddress +import re +import typing +from ipaddress import IPv4Address, IPv6Address + +if typing.TYPE_CHECKING: + from .ssl_ import _TYPE_PEER_CERT_RET_DICT + +__version__ = "3.5.0.1" + + +class CertificateError(ValueError): + pass + + +def _dnsname_match( + dn: typing.Any, hostname: str, max_wildcards: int = 1 +) -> typing.Match[str] | None | bool: + """Matching according to RFC 6125, section 6.4.3 + + http://tools.ietf.org/html/rfc6125#section-6.4.3 + """ + pats = [] + if not dn: + return False + + # Ported from python3-syntax: + # leftmost, *remainder = dn.split(r'.') + parts = dn.split(r".") + leftmost = parts[0] + remainder = parts[1:] + + wildcards = leftmost.count("*") + if wildcards > max_wildcards: + # Issue #17980: avoid denials of service by refusing more + # than one wildcard per fragment. A survey of established + # policy among SSL implementations showed it to be a + # reasonable choice. + raise CertificateError( + "too many wildcards in certificate DNS name: " + repr(dn) + ) + + # speed up common case w/o wildcards + if not wildcards: + return bool(dn.lower() == hostname.lower()) + + # RFC 6125, section 6.4.3, subitem 1. + # The client SHOULD NOT attempt to match a presented identifier in which + # the wildcard character comprises a label other than the left-most label. + if leftmost == "*": + # When '*' is a fragment by itself, it matches a non-empty dotless + # fragment. + pats.append("[^.]+") + elif leftmost.startswith("xn--") or hostname.startswith("xn--"): + # RFC 6125, section 6.4.3, subitem 3. + # The client SHOULD NOT attempt to match a presented identifier + # where the wildcard character is embedded within an A-label or + # U-label of an internationalized domain name. + pats.append(re.escape(leftmost)) + else: + # Otherwise, '*' matches any dotless string, e.g. www* + pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) + + # add the remaining fragments, ignore any wildcards + for frag in remainder: + pats.append(re.escape(frag)) + + pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) + return pat.match(hostname) + + +def _ipaddress_match(ipname: str, host_ip: IPv4Address | IPv6Address) -> bool: + """Exact matching of IP addresses. + + RFC 9110 section 4.3.5: "A reference identity of IP-ID contains the decoded + bytes of the IP address. An IP version 4 address is 4 octets, and an IP + version 6 address is 16 octets. [...] A reference identity of type IP-ID + matches if the address is identical to an iPAddress value of the + subjectAltName extension of the certificate." + """ + # OpenSSL may add a trailing newline to a subjectAltName's IP address + # Divergence from upstream: ipaddress can't handle byte str + ip = ipaddress.ip_address(ipname.rstrip()) + return bool(ip.packed == host_ip.packed) + + +def match_hostname( + cert: _TYPE_PEER_CERT_RET_DICT | None, + hostname: str, + hostname_checks_common_name: bool = False, +) -> None: + """Verify that *cert* (in decoded format as returned by + SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 + rules are followed, but IP addresses are not accepted for *hostname*. + + CertificateError is raised on failure. On success, the function + returns nothing. + """ + if not cert: + raise ValueError( + "empty or no certificate, match_hostname needs a " + "SSL socket or SSL context with either " + "CERT_OPTIONAL or CERT_REQUIRED" + ) + try: + # Divergence from upstream: ipaddress can't handle byte str + # + # The ipaddress module shipped with Python < 3.9 does not support + # scoped IPv6 addresses so we unconditionally strip the Zone IDs for + # now. Once we drop support for Python 3.9 we can remove this branch. + if "%" in hostname: + host_ip = ipaddress.ip_address(hostname[: hostname.rfind("%")]) + else: + host_ip = ipaddress.ip_address(hostname) + + except ValueError: + # Not an IP address (common case) + host_ip = None + dnsnames = [] + san: tuple[tuple[str, str], ...] = cert.get("subjectAltName", ()) + key: str + value: str + for key, value in san: + if key == "DNS": + if host_ip is None and _dnsname_match(value, hostname): + return + dnsnames.append(value) + elif key == "IP Address": + if host_ip is not None and _ipaddress_match(value, host_ip): + return + dnsnames.append(value) + + # We only check 'commonName' if it's enabled and we're not verifying + # an IP address. IP addresses aren't valid within 'commonName'. + if hostname_checks_common_name and host_ip is None and not dnsnames: + for sub in cert.get("subject", ()): + for key, value in sub: + if key == "commonName": + if _dnsname_match(value, hostname): + return + dnsnames.append(value) # Defensive: for Python < 3.9.3 + + if len(dnsnames) > 1: + raise CertificateError( + "hostname %r " + "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) + ) + elif len(dnsnames) == 1: + raise CertificateError(f"hostname {hostname!r} doesn't match {dnsnames[0]!r}") + else: + raise CertificateError("no appropriate subjectAltName fields were found") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssltransport.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssltransport.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59bc3bce2489c3a0aa5bcb83b737dcf33c033b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/ssltransport.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +import io +import socket +import ssl +import typing + +from ..exceptions import ProxySchemeUnsupported + +if typing.TYPE_CHECKING: + from typing_extensions import Self + + from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT + + +_WriteBuffer = typing.Union[bytearray, memoryview] +_ReturnValue = typing.TypeVar("_ReturnValue") + +SSL_BLOCKSIZE = 16384 + + +class SSLTransport: + """ + The SSLTransport wraps an existing socket and establishes an SSL connection. + + Contrary to Python's implementation of SSLSocket, it allows you to chain + multiple TLS connections together. It's particularly useful if you need to + implement TLS within TLS. + + The class supports most of the socket API operations. + """ + + @staticmethod + def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None: + """ + Raises a ProxySchemeUnsupported if the provided ssl_context can't be used + for TLS in TLS. + + The only requirement is that the ssl_context provides the 'wrap_bio' + methods. + """ + + if not hasattr(ssl_context, "wrap_bio"): + raise ProxySchemeUnsupported( + "TLS in TLS requires SSLContext.wrap_bio() which isn't " + "available on non-native SSLContext" + ) + + def __init__( + self, + socket: socket.socket, + ssl_context: ssl.SSLContext, + server_hostname: str | None = None, + suppress_ragged_eofs: bool = True, + ) -> None: + """ + Create an SSLTransport around socket using the provided ssl_context. + """ + self.incoming = ssl.MemoryBIO() + self.outgoing = ssl.MemoryBIO() + + self.suppress_ragged_eofs = suppress_ragged_eofs + self.socket = socket + + self.sslobj = ssl_context.wrap_bio( + self.incoming, self.outgoing, server_hostname=server_hostname + ) + + # Perform initial handshake. + self._ssl_io_loop(self.sslobj.do_handshake) + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_: typing.Any) -> None: + self.close() + + def fileno(self) -> int: + return self.socket.fileno() + + def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes: + return self._wrap_ssl_read(len, buffer) + + def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv") + return self._wrap_ssl_read(buflen) + + def recv_into( + self, + buffer: _WriteBuffer, + nbytes: int | None = None, + flags: int = 0, + ) -> None | int | bytes: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to recv_into") + if nbytes is None: + nbytes = len(buffer) + return self.read(nbytes, buffer) + + def sendall(self, data: bytes, flags: int = 0) -> None: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to sendall") + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + v = self.send(byte_view[count:]) + count += v + + def send(self, data: bytes, flags: int = 0) -> int: + if flags != 0: + raise ValueError("non-zero flags not allowed in calls to send") + return self._ssl_io_loop(self.sslobj.write, data) + + def makefile( + self, + mode: str, + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO: + """ + Python's httpclient uses makefile and buffered io when reading HTTP + messages and we need to support it. + + This is unfortunately a copy and paste of socket.py makefile with small + changes to point to the socket directly. + """ + if not set(mode) <= {"r", "w", "b"}: + raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)") + + writing = "w" in mode + reading = "r" in mode or not writing + assert reading or writing + binary = "b" in mode + rawmode = "" + if reading: + rawmode += "r" + if writing: + rawmode += "w" + raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type] + self.socket._io_refs += 1 # type: ignore[attr-defined] + if buffering is None: + buffering = -1 + if buffering < 0: + buffering = io.DEFAULT_BUFFER_SIZE + if buffering == 0: + if not binary: + raise ValueError("unbuffered streams must be binary") + return raw + buffer: typing.BinaryIO + if reading and writing: + buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment] + elif reading: + buffer = io.BufferedReader(raw, buffering) + else: + assert writing + buffer = io.BufferedWriter(raw, buffering) + if binary: + return buffer + text = io.TextIOWrapper(buffer, encoding, errors, newline) + text.mode = mode # type: ignore[misc] + return text + + def unwrap(self) -> None: + self._ssl_io_loop(self.sslobj.unwrap) + + def close(self) -> None: + self.socket.close() + + @typing.overload + def getpeercert( + self, binary_form: typing.Literal[False] = ... + ) -> _TYPE_PEER_CERT_RET_DICT | None: ... + + @typing.overload + def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ... + + def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET: + return self.sslobj.getpeercert(binary_form) # type: ignore[return-value] + + def version(self) -> str | None: + return self.sslobj.version() + + def cipher(self) -> tuple[str, str, int] | None: + return self.sslobj.cipher() + + def selected_alpn_protocol(self) -> str | None: + return self.sslobj.selected_alpn_protocol() + + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: + return self.sslobj.shared_ciphers() + + def compression(self) -> str | None: + return self.sslobj.compression() + + def settimeout(self, value: float | None) -> None: + self.socket.settimeout(value) + + def gettimeout(self) -> float | None: + return self.socket.gettimeout() + + def _decref_socketios(self) -> None: + self.socket._decref_socketios() # type: ignore[attr-defined] + + def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes: + try: + return self._ssl_io_loop(self.sslobj.read, len, buffer) + except ssl.SSLError as e: + if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs: + return 0 # eof, return 0. + else: + raise + + # func is sslobj.do_handshake or sslobj.unwrap + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ... + + # func is sslobj.write, arg1 is data + @typing.overload + def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ... + + # func is sslobj.read, arg1 is len, arg2 is buffer + @typing.overload + def _ssl_io_loop( + self, + func: typing.Callable[[int, bytearray | None], bytes], + arg1: int, + arg2: bytearray | None, + ) -> bytes: ... + + def _ssl_io_loop( + self, + func: typing.Callable[..., _ReturnValue], + arg1: None | bytes | int = None, + arg2: bytearray | None = None, + ) -> _ReturnValue: + """Performs an I/O loop between incoming/outgoing and the socket.""" + should_loop = True + ret = None + + while should_loop: + errno = None + try: + if arg1 is None and arg2 is None: + ret = func() + elif arg2 is None: + ret = func(arg1) + else: + ret = func(arg1, arg2) + except ssl.SSLError as e: + if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): + # WANT_READ, and WANT_WRITE are expected, others are not. + raise e + errno = e.errno + + buf = self.outgoing.read() + self.socket.sendall(buf) + + if errno is None: + should_loop = False + elif errno == ssl.SSL_ERROR_WANT_READ: + buf = self.socket.recv(SSL_BLOCKSIZE) + if buf: + self.incoming.write(buf) + else: + self.incoming.write_eof() + return typing.cast(_ReturnValue, ret) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/timeout.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb1be11d9cb06900dd82ecebd06aa6a7c5de916 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/timeout.py @@ -0,0 +1,275 @@ +from __future__ import annotations + +import time +import typing +from enum import Enum +from socket import getdefaulttimeout + +from ..exceptions import TimeoutStateError + +if typing.TYPE_CHECKING: + from typing import Final + + +class _TYPE_DEFAULT(Enum): + # This value should never be passed to socket.settimeout() so for safety we use a -1. + # socket.settimout() raises a ValueError for negative values. + token = -1 + + +_DEFAULT_TIMEOUT: Final[_TYPE_DEFAULT] = _TYPE_DEFAULT.token + +_TYPE_TIMEOUT = typing.Optional[typing.Union[float, _TYPE_DEFAULT]] + + +class Timeout: + """Timeout configuration. + + Timeouts can be defined as a default for a pool: + + .. code-block:: python + + import urllib3 + + timeout = urllib3.util.Timeout(connect=2.0, read=7.0) + + http = urllib3.PoolManager(timeout=timeout) + + resp = http.request("GET", "https://example.com/") + + print(resp.status) + + Or per-request (which overrides the default for the pool): + + .. code-block:: python + + response = http.request("GET", "https://example.com/", timeout=Timeout(10)) + + Timeouts can be disabled by setting all the parameters to ``None``: + + .. code-block:: python + + no_timeout = Timeout(connect=None, read=None) + response = http.request("GET", "https://example.com/", timeout=no_timeout) + + + :param total: + This combines the connect and read timeouts into one; the read timeout + will be set to the time leftover from the connect attempt. In the + event that both a connect timeout and a total are specified, or a read + timeout and a total are specified, the shorter timeout will be applied. + + Defaults to None. + + :type total: int, float, or None + + :param connect: + The maximum amount of time (in seconds) to wait for a connection + attempt to a server to succeed. Omitting the parameter will default the + connect timeout to the system default, probably `the global default + timeout in socket.py + `_. + None will set an infinite timeout for connection attempts. + + :type connect: int, float, or None + + :param read: + The maximum amount of time (in seconds) to wait between consecutive + read operations for a response from the server. Omitting the parameter + will default the read timeout to the system default, probably `the + global default timeout in socket.py + `_. + None will set an infinite timeout. + + :type read: int, float, or None + + .. note:: + + Many factors can affect the total amount of time for urllib3 to return + an HTTP response. + + For example, Python's DNS resolver does not obey the timeout specified + on the socket. Other factors that can affect total request time include + high CPU load, high swap, the program running at a low priority level, + or other behaviors. + + In addition, the read and total timeouts only measure the time between + read operations on the socket connecting the client and the server, + not the total amount of time for the request to return a complete + response. For most requests, the timeout is raised because the server + has not sent the first byte in the specified time. This is not always + the case; if a server streams one byte every fifteen seconds, a timeout + of 20 seconds will not trigger, even though the request will take + several minutes to complete. + """ + + #: A sentinel object representing the default timeout value + DEFAULT_TIMEOUT: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT + + def __init__( + self, + total: _TYPE_TIMEOUT = None, + connect: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + read: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + ) -> None: + self._connect = self._validate_timeout(connect, "connect") + self._read = self._validate_timeout(read, "read") + self.total = self._validate_timeout(total, "total") + self._start_connect: float | None = None + + def __repr__(self) -> str: + return f"{type(self).__name__}(connect={self._connect!r}, read={self._read!r}, total={self.total!r})" + + # __str__ provided for backwards compatibility + __str__ = __repr__ + + @staticmethod + def resolve_default_timeout(timeout: _TYPE_TIMEOUT) -> float | None: + return getdefaulttimeout() if timeout is _DEFAULT_TIMEOUT else timeout + + @classmethod + def _validate_timeout(cls, value: _TYPE_TIMEOUT, name: str) -> _TYPE_TIMEOUT: + """Check that a timeout attribute is valid. + + :param value: The timeout value to validate + :param name: The name of the timeout attribute to validate. This is + used to specify in error messages. + :return: The validated and casted version of the given value. + :raises ValueError: If it is a numeric value less than or equal to + zero, or the type is not an integer, float, or None. + """ + if value is None or value is _DEFAULT_TIMEOUT: + return value + + if isinstance(value, bool): + raise ValueError( + "Timeout cannot be a boolean value. It must " + "be an int, float or None." + ) + try: + float(value) + except (TypeError, ValueError): + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + try: + if value <= 0: + raise ValueError( + "Attempted to set %s timeout to %s, but the " + "timeout cannot be set to a value less " + "than or equal to 0." % (name, value) + ) + except TypeError: + raise ValueError( + "Timeout value %s was %s, but it must be an " + "int, float or None." % (name, value) + ) from None + + return value + + @classmethod + def from_float(cls, timeout: _TYPE_TIMEOUT) -> Timeout: + """Create a new Timeout from a legacy timeout value. + + The timeout value used by httplib.py sets the same timeout on the + connect(), and recv() socket requests. This creates a :class:`Timeout` + object that sets the individual timeouts to the ``timeout`` value + passed to this function. + + :param timeout: The legacy timeout value. + :type timeout: integer, float, :attr:`urllib3.util.Timeout.DEFAULT_TIMEOUT`, or None + :return: Timeout object + :rtype: :class:`Timeout` + """ + return Timeout(read=timeout, connect=timeout) + + def clone(self) -> Timeout: + """Create a copy of the timeout object + + Timeout properties are stored per-pool but each request needs a fresh + Timeout object to ensure each one has its own start/stop configured. + + :return: a copy of the timeout object + :rtype: :class:`Timeout` + """ + # We can't use copy.deepcopy because that will also create a new object + # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to + # detect the user default. + return Timeout(connect=self._connect, read=self._read, total=self.total) + + def start_connect(self) -> float: + """Start the timeout clock, used during a connect() attempt + + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to start a timer that has been started already. + """ + if self._start_connect is not None: + raise TimeoutStateError("Timeout timer has already been started.") + self._start_connect = time.monotonic() + return self._start_connect + + def get_connect_duration(self) -> float: + """Gets the time elapsed since the call to :meth:`start_connect`. + + :return: Elapsed time in seconds. + :rtype: float + :raises urllib3.exceptions.TimeoutStateError: if you attempt + to get duration for a timer that hasn't been started. + """ + if self._start_connect is None: + raise TimeoutStateError( + "Can't get connect duration for timer that has not started." + ) + return time.monotonic() - self._start_connect + + @property + def connect_timeout(self) -> _TYPE_TIMEOUT: + """Get the value to use when setting a connection timeout. + + This will be a positive float or integer, the value None + (never timeout), or the default system timeout. + + :return: Connect timeout. + :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None + """ + if self.total is None: + return self._connect + + if self._connect is None or self._connect is _DEFAULT_TIMEOUT: + return self.total + + return min(self._connect, self.total) # type: ignore[type-var] + + @property + def read_timeout(self) -> float | None: + """Get the value for the read timeout. + + This assumes some time has elapsed in the connection timeout and + computes the read timeout appropriately. + + If self.total is set, the read timeout is dependent on the amount of + time taken by the connect timeout. If the connection time has not been + established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be + raised. + + :return: Value to use for the read timeout. + :rtype: int, float or None + :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` + has not yet been called on this object. + """ + if ( + self.total is not None + and self.total is not _DEFAULT_TIMEOUT + and self._read is not None + and self._read is not _DEFAULT_TIMEOUT + ): + # In case the connect timeout has not yet been established. + if self._start_connect is None: + return self._read + return max(0, min(self.total - self.get_connect_duration(), self._read)) + elif self.total is not None and self.total is not _DEFAULT_TIMEOUT: + return max(0, self.total - self.get_connect_duration()) + else: + return self.resolve_default_timeout(self._read) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/url.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/url.py new file mode 100644 index 0000000000000000000000000000000000000000..db057f17be610174f30928748b5004dcbf6c501c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/url.py @@ -0,0 +1,469 @@ +from __future__ import annotations + +import re +import typing + +from ..exceptions import LocationParseError +from .util import to_str + +# We only want to normalize urls with an HTTP(S) scheme. +# urllib3 infers URLs without a scheme (None) to be http. +_NORMALIZABLE_SCHEMES = ("http", "https", None) + +# Almost all of these patterns were derived from the +# 'rfc3986' module: https://github.com/python-hyper/rfc3986 +_PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") +_SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") +_URI_RE = re.compile( + r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" + r"(?://([^\\/?#]*))?" + r"([^?#]*)" + r"(?:\?([^#]*))?" + r"(?:#(.*))?$", + re.UNICODE | re.DOTALL, +) + +_IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" +_HEX_PAT = "[0-9A-Fa-f]{1,4}" +_LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=_HEX_PAT, ipv4=_IPV4_PAT) +_subs = {"hex": _HEX_PAT, "ls32": _LS32_PAT} +_variations = [ + # 6( h16 ":" ) ls32 + "(?:%(hex)s:){6}%(ls32)s", + # "::" 5( h16 ":" ) ls32 + "::(?:%(hex)s:){5}%(ls32)s", + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", + # [ *4( h16 ":" ) h16 ] "::" ls32 + "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", + # [ *5( h16 ":" ) h16 ] "::" h16 + "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", + # [ *6( h16 ":" ) h16 ] "::" + "(?:(?:%(hex)s:){0,6}%(hex)s)?::", +] + +_UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~" +_IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" +_ZONE_ID_PAT = "(?:%25|%)(?:[" + _UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" +_IPV6_ADDRZ_PAT = r"\[" + _IPV6_PAT + r"(?:" + _ZONE_ID_PAT + r")?\]" +_REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" +_TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") + +_IPV4_RE = re.compile("^" + _IPV4_PAT + "$") +_IPV6_RE = re.compile("^" + _IPV6_PAT + "$") +_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT + "$") +_BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + _IPV6_ADDRZ_PAT[2:-2] + "$") +_ZONE_ID_RE = re.compile("(" + _ZONE_ID_PAT + r")\]$") + +_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % ( + _REG_NAME_PAT, + _IPV4_PAT, + _IPV6_ADDRZ_PAT, +) +_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL) + +_UNRESERVED_CHARS = set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" +) +_SUB_DELIM_CHARS = set("!$&'()*+,;=") +_USERINFO_CHARS = _UNRESERVED_CHARS | _SUB_DELIM_CHARS | {":"} +_PATH_CHARS = _USERINFO_CHARS | {"@", "/"} +_QUERY_CHARS = _FRAGMENT_CHARS = _PATH_CHARS | {"?"} + + +class Url( + typing.NamedTuple( + "Url", + [ + ("scheme", typing.Optional[str]), + ("auth", typing.Optional[str]), + ("host", typing.Optional[str]), + ("port", typing.Optional[int]), + ("path", typing.Optional[str]), + ("query", typing.Optional[str]), + ("fragment", typing.Optional[str]), + ], + ) +): + """ + Data structure for representing an HTTP URL. Used as a return value for + :func:`parse_url`. Both the scheme and host are normalized as they are + both case-insensitive according to RFC 3986. + """ + + def __new__( # type: ignore[no-untyped-def] + cls, + scheme: str | None = None, + auth: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme is not None: + scheme = scheme.lower() + return super().__new__(cls, scheme, auth, host, port, path, query, fragment) + + @property + def hostname(self) -> str | None: + """For backwards-compatibility with urlparse. We're nice like that.""" + return self.host + + @property + def request_uri(self) -> str: + """Absolute path including the query string.""" + uri = self.path or "/" + + if self.query is not None: + uri += "?" + self.query + + return uri + + @property + def authority(self) -> str | None: + """ + Authority component as defined in RFC 3986 3.2. + This includes userinfo (auth), host and port. + + i.e. + userinfo@host:port + """ + userinfo = self.auth + netloc = self.netloc + if netloc is None or userinfo is None: + return netloc + else: + return f"{userinfo}@{netloc}" + + @property + def netloc(self) -> str | None: + """ + Network location including host and port. + + If you need the equivalent of urllib.parse's ``netloc``, + use the ``authority`` property instead. + """ + if self.host is None: + return None + if self.port: + return f"{self.host}:{self.port}" + return self.host + + @property + def url(self) -> str: + """ + Convert self into a url + + This function should more or less round-trip with :func:`.parse_url`. The + returned url may not be exactly the same as the url inputted to + :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls + with a blank port will have : removed). + + Example: + + .. code-block:: python + + import urllib3 + + U = urllib3.util.parse_url("https://google.com/mail/") + + print(U.url) + # "https://google.com/mail/" + + print( urllib3.util.Url("https", "username:password", + "host.com", 80, "/path", "query", "fragment" + ).url + ) + # "https://username:password@host.com:80/path?query#fragment" + """ + scheme, auth, host, port, path, query, fragment = self + url = "" + + # We use "is not None" we want things to happen with empty strings (or 0 port) + if scheme is not None: + url += scheme + "://" + if auth is not None: + url += auth + "@" + if host is not None: + url += host + if port is not None: + url += ":" + str(port) + if path is not None: + url += path + if query is not None: + url += "?" + query + if fragment is not None: + url += "#" + fragment + + return url + + def __str__(self) -> str: + return self.url + + +@typing.overload +def _encode_invalid_chars( + component: str, allowed_chars: typing.Container[str] +) -> str: # Abstract + ... + + +@typing.overload +def _encode_invalid_chars( + component: None, allowed_chars: typing.Container[str] +) -> None: # Abstract + ... + + +def _encode_invalid_chars( + component: str | None, allowed_chars: typing.Container[str] +) -> str | None: + """Percent-encodes a URI component without reapplying + onto an already percent-encoded component. + """ + if component is None: + return component + + component = to_str(component) + + # Normalize existing percent-encoded bytes. + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + component, percent_encodings = _PERCENT_RE.subn( + lambda match: match.group(0).upper(), component + ) + + uri_bytes = component.encode("utf-8", "surrogatepass") + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + encoded_component = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring + byte = uri_bytes[i : i + 1] + byte_ord = ord(byte) + if (is_percent_encoded and byte == b"%") or ( + byte_ord < 128 and byte.decode() in allowed_chars + ): + encoded_component += byte + continue + encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) + + return encoded_component.decode() + + +def _remove_path_dot_segments(path: str) -> str: + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = path.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + if segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if path.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if path.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +@typing.overload +def _normalize_host(host: None, scheme: str | None) -> None: ... + + +@typing.overload +def _normalize_host(host: str, scheme: str | None) -> str: ... + + +def _normalize_host(host: str | None, scheme: str | None) -> str | None: + if host: + if scheme in _NORMALIZABLE_SCHEMES: + is_ipv6 = _IPV6_ADDRZ_RE.match(host) + if is_ipv6: + # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as + # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID + # separator as necessary to return a valid RFC 4007 scoped IP. + match = _ZONE_ID_RE.search(host) + if match: + start, end = match.span(1) + zone_id = host[start:end] + + if zone_id.startswith("%25") and zone_id != "%25": + zone_id = zone_id[3:] + else: + zone_id = zone_id[1:] + zone_id = _encode_invalid_chars(zone_id, _UNRESERVED_CHARS) + return f"{host[:start].lower()}%{zone_id}{host[end:]}" + else: + return host.lower() + elif not _IPV4_RE.match(host): + return to_str( + b".".join([_idna_encode(label) for label in host.split(".")]), + "ascii", + ) + return host + + +def _idna_encode(name: str) -> bytes: + if not name.isascii(): + try: + import idna + except ImportError: + raise LocationParseError( + "Unable to parse URL without the 'idna' module" + ) from None + + try: + return idna.encode(name.lower(), strict=True, std3_rules=True) + except idna.IDNAError: + raise LocationParseError( + f"Name '{name}' is not a valid IDNA label" + ) from None + + return name.lower().encode("ascii") + + +def _encode_target(target: str) -> str: + """Percent-encodes a request target so that there are no invalid characters + + Pre-condition for this function is that 'target' must start with '/'. + If that is the case then _TARGET_RE will always produce a match. + """ + match = _TARGET_RE.match(target) + if not match: # Defensive: + raise LocationParseError(f"{target!r} is not a valid request URI") + + path, query = match.groups() + encoded_target = _encode_invalid_chars(path, _PATH_CHARS) + if query is not None: + query = _encode_invalid_chars(query, _QUERY_CHARS) + encoded_target += "?" + query + return encoded_target + + +def parse_url(url: str) -> Url: + """ + Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is + performed to parse incomplete urls. Fields not provided will be None. + This parser is RFC 3986 and RFC 6874 compliant. + + The parser logic and helper functions are based heavily on + work done in the ``rfc3986`` module. + + :param str url: URL to parse into a :class:`.Url` namedtuple. + + Partly backwards-compatible with :mod:`urllib.parse`. + + Example: + + .. code-block:: python + + import urllib3 + + print( urllib3.util.parse_url('http://google.com/mail/')) + # Url(scheme='http', host='google.com', port=None, path='/mail/', ...) + + print( urllib3.util.parse_url('google.com:80')) + # Url(scheme=None, host='google.com', port=80, path=None, ...) + + print( urllib3.util.parse_url('/foo?bar')) + # Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) + """ + if not url: + # Empty + return Url() + + source_url = url + if not _SCHEME_RE.search(url): + url = "//" + url + + scheme: str | None + authority: str | None + auth: str | None + host: str | None + port: str | None + port_int: int | None + path: str | None + query: str | None + fragment: str | None + + try: + scheme, authority, path, query, fragment = _URI_RE.match(url).groups() # type: ignore[union-attr] + normalize_uri = scheme is None or scheme.lower() in _NORMALIZABLE_SCHEMES + + if scheme: + scheme = scheme.lower() + + if authority: + auth, _, host_port = authority.rpartition("@") + auth = auth or None + host, port = _HOST_PORT_RE.match(host_port).groups() # type: ignore[union-attr] + if auth and normalize_uri: + auth = _encode_invalid_chars(auth, _USERINFO_CHARS) + if port == "": + port = None + else: + auth, host, port = None, None, None + + if port is not None: + port_int = int(port) + if not (0 <= port_int <= 65535): + raise LocationParseError(url) + else: + port_int = None + + host = _normalize_host(host, scheme) + + if normalize_uri and path: + path = _remove_path_dot_segments(path) + path = _encode_invalid_chars(path, _PATH_CHARS) + if normalize_uri and query: + query = _encode_invalid_chars(query, _QUERY_CHARS) + if normalize_uri and fragment: + fragment = _encode_invalid_chars(fragment, _FRAGMENT_CHARS) + + except (ValueError, AttributeError) as e: + raise LocationParseError(source_url) from e + + # For the sake of backwards compatibility we put empty + # string values for path if there are any defined values + # beyond the path in the URL. + # TODO: Remove this when we break backwards compatibility. + if not path: + if query is not None or fragment is not None: + path = "" + else: + path = None + + return Url( + scheme=scheme, + auth=auth, + host=host, + port=port_int, + path=path, + query=query, + fragment=fragment, + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/util.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/util.py new file mode 100644 index 0000000000000000000000000000000000000000..35c77e4025842f548565334a3c04cba90f9283d6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/util.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import typing +from types import TracebackType + + +def to_bytes( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> bytes: + if isinstance(x, bytes): + return x + elif not isinstance(x, str): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.encode(encoding or "utf-8", errors=errors or "strict") + return x.encode() + + +def to_str( + x: str | bytes, encoding: str | None = None, errors: str | None = None +) -> str: + if isinstance(x, str): + return x + elif not isinstance(x, bytes): + raise TypeError(f"not expecting type {type(x).__name__}") + if encoding or errors: + return x.decode(encoding or "utf-8", errors=errors or "strict") + return x.decode() + + +def reraise( + tp: type[BaseException] | None, + value: BaseException, + tb: TracebackType | None = None, +) -> typing.NoReturn: + try: + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None # type: ignore[assignment] + tb = None diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/wait.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/wait.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca0c7ad5b232eeb1ad9c43d315bd1d74eaed9a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/urllib3/util/wait.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import select +import socket +from functools import partial + +__all__ = ["wait_for_read", "wait_for_write"] + + +# How should we wait on sockets? +# +# There are two types of APIs you can use for waiting on sockets: the fancy +# modern stateful APIs like epoll/kqueue, and the older stateless APIs like +# select/poll. The stateful APIs are more efficient when you have a lots of +# sockets to keep track of, because you can set them up once and then use them +# lots of times. But we only ever want to wait on a single socket at a time +# and don't want to keep track of state, so the stateless APIs are actually +# more efficient. So we want to use select() or poll(). +# +# Now, how do we choose between select() and poll()? On traditional Unixes, +# select() has a strange calling convention that makes it slow, or fail +# altogether, for high-numbered file descriptors. The point of poll() is to fix +# that, so on Unixes, we prefer poll(). +# +# On Windows, there is no poll() (or at least Python doesn't provide a wrapper +# for it), but that's OK, because on Windows, select() doesn't have this +# strange calling convention; plain select() works fine. +# +# So: on Windows we use select(), and everywhere else we use poll(). We also +# fall back to select() in case poll() is somehow broken or missing. + + +def select_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + rcheck = [] + wcheck = [] + if read: + rcheck.append(sock) + if write: + wcheck.append(sock) + # When doing a non-blocking connect, most systems signal success by + # marking the socket writable. Windows, though, signals success by marked + # it as "exceptional". We paper over the difference by checking the write + # sockets for both conditions. (The stdlib selectors module does the same + # thing.) + fn = partial(select.select, rcheck, wcheck, wcheck) + rready, wready, xready = fn(timeout) + return bool(rready or wready or xready) + + +def poll_wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + if not read and not write: + raise RuntimeError("must specify at least one of read=True, write=True") + mask = 0 + if read: + mask |= select.POLLIN + if write: + mask |= select.POLLOUT + poll_obj = select.poll() + poll_obj.register(sock, mask) + + # For some reason, poll() takes timeout in milliseconds + def do_poll(t: float | None) -> list[tuple[int, int]]: + if t is not None: + t *= 1000 + return poll_obj.poll(t) + + return bool(do_poll(timeout)) + + +def _have_working_poll() -> bool: + # Apparently some systems have a select.poll that fails as soon as you try + # to use it, either due to strange configuration or broken monkeypatching + # from libraries like eventlet/greenlet. + try: + poll_obj = select.poll() + poll_obj.poll(0) + except (AttributeError, OSError): + return False + else: + return True + + +def wait_for_socket( + sock: socket.socket, + read: bool = False, + write: bool = False, + timeout: float | None = None, +) -> bool: + # We delay choosing which implementation to use until the first time we're + # called. We could do it at import time, but then we might make the wrong + # decision if someone goes wild with monkeypatching select.poll after + # we're imported. + global wait_for_socket + if _have_working_poll(): + wait_for_socket = poll_wait_for_socket + elif hasattr(select, "select"): + wait_for_socket = select_wait_for_socket + return wait_for_socket(sock, read, write, timeout) + + +def wait_for_read(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for reading to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, read=True, timeout=timeout) + + +def wait_for_write(sock: socket.socket, timeout: float | None = None) -> bool: + """Waits for writing to be available on a given socket. + Returns True if the socket is readable, or False if the timeout expired. + """ + return wait_for_socket(sock, write=True, timeout=timeout) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d93be1bfdb6ff53c704674ca2757d82849e0c9ab Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasink.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasink.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4175786a500ec5ce251fb333d1d3cccb113ea254 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasink.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasource.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasource.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebfcdf8af831d0e8beea4dac143b8c4dfec0e401 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/bigquery_datasource.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/client_builder.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/client_builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79f2c53361492f4adeaf2aee50097ef23699b7f3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/client_builder.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/cluster_init.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/cluster_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d963454b8611ff0f21e71b8e1ebaf90b8f499e30 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/cluster_init.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/dashboard_sdk.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/dashboard_sdk.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3fd59f13318812ae5bd1e552326037e1f9f5454 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/dashboard_sdk.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/data.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de3c5435b8ea547f3b5f06b6bd7d21b4c8964c2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/data.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/render.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/render.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..814bcc45d31c48bd241de37e89886565a331abe8 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/__pycache__/render.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f74684bc750b2e5ef7ef6fa79827efc34f715bd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__init__.py @@ -0,0 +1,18 @@ +"""Ray on Vertex AI Prediction.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e79cc450fddf0faf8555802b9154ebaf264bb429 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..856fc73fe7bad9c0bb86c7a6e497c610ec722b07 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__init__.py @@ -0,0 +1,22 @@ +"""Ray on Vertex AI Prediction Tensorflow.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .register import register_sklearn + +__all__ = ("register_sklearn",) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d76e5aeb0a7b50c5f9230423d873920a6f7009e Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/register.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/register.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb7faea1af8c623e40947280b5ce4d16375fc2a1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/__pycache__/register.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/register.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/register.py new file mode 100644 index 0000000000000000000000000000000000000000..fb6c2333edb15a20aa12202802f1d4e0a683fbfb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/sklearn/register.py @@ -0,0 +1,173 @@ +"""Regsiter Scikit Learn for Ray on Vertex AI.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import pickle +import warnings +import ray +import ray.cloudpickle as cpickle +import tempfile +from typing import Optional, TYPE_CHECKING + +from google.cloud import aiplatform +from google.cloud.aiplatform import initializer +from google.cloud.aiplatform import utils +from google.cloud.aiplatform.utils import gcs_utils +from google.cloud.aiplatform.vertex_ray.predict.util import constants +from google.cloud.aiplatform.vertex_ray.predict.util import ( + predict_utils, +) +from google.cloud.aiplatform.vertex_ray.util._validation_utils import ( + _V2_4_WARNING_MESSAGE, + _V2_9_WARNING_MESSAGE, +) + + +try: + from ray.train import sklearn as ray_sklearn + + if TYPE_CHECKING: + import sklearn + +except ImportError as ie: + if ray.__version__ < "2.42.0": + raise ModuleNotFoundError("Sklearn isn't installed.") from ie + else: + sklearn = None + + +def register_sklearn( + checkpoint: "ray_sklearn.SklearnCheckpoint", + artifact_uri: Optional[str] = None, + display_name: Optional[str] = None, + **kwargs, +) -> aiplatform.Model: + """Uploads a Ray Sklearn Checkpoint as Sklearn Model to Model Registry. + + Example usage: + from vertex_ray.predict import sklearn + from ray.train.sklearn import SklearnCheckpoint + + trainer = SklearnTrainer(estimator=RandomForestClassifier, ...) + result = trainer.fit() + sklearn_checkpoint = SklearnCheckpoint.from_checkpoint(result.checkpoint) + + my_model = sklearn.register_sklearn( + checkpoint=sklearn_checkpoint, + artifact_uri="gs://{gcs-bucket-name}/path/to/store" + ) + + + Args: + checkpoint: SklearnCheckpoint instance. + artifact_uri (str): + Optional. The path to the directory where Model Artifacts will be saved. If + not set, will use staging bucket set in aiplatform.init(). + display_name (str): + Optional. The display name of the Model. The name can be up to 128 + characters long and can be consist of any UTF-8 characters. + **kwargs: + Any kwargs will be passed to aiplatform.Model registration. + + Returns: + model (aiplatform.Model): + Instantiated representation of the uploaded model resource. + + Raises: + ValueError: Invalid Argument. + RuntimeError: Only Ray version 2.9.3 is supported. + """ + ray_version = ray.__version__ + if ray_version != "2.9.3": + raise RuntimeError( + f"Ray version {ray_version} is not supported to upload Sklearn" + " model to Vertex Model Registry yet. Please use Ray 2.9.3." + ) + if ray_version == "2.9.3": + warnings.warn(_V2_9_WARNING_MESSAGE, DeprecationWarning, stacklevel=1) + + artifact_uri = artifact_uri or initializer.global_config.staging_bucket + predict_utils.validate_artifact_uri(artifact_uri) + display_model_name = ( + (f"ray-on-vertex-registered-sklearn-model-{utils.timestamped_unique_name()}") + if display_name is None + else display_name + ) + estimator = _get_estimator_from(checkpoint) + + model_dir = os.path.join(artifact_uri, display_model_name) + file_path = os.path.join(model_dir, constants._PICKLE_FILE_NAME) + + with tempfile.NamedTemporaryFile(suffix=constants._PICKLE_EXTENTION) as temp_file: + pickle.dump(estimator, temp_file) + gcs_utils.upload_to_gcs(temp_file.name, file_path) + return aiplatform.Model.upload_scikit_learn_model_file( + model_file_path=temp_file.name, display_name=display_model_name, **kwargs + ) + + +def _get_estimator_from( + checkpoint: "ray_sklearn.SklearnCheckpoint", +) -> "sklearn.base.BaseEstimator": + """Converts a SklearnCheckpoint to sklearn estimator. + + Args: + checkpoint: SklearnCheckpoint instance. + + Returns: + A Sklearn BaseEstimator + + Raises: + ValueError: Invalid Argument. + RuntimeError: Model not found. + RuntimeError: Ray version 2.4 is not supported. + RuntimeError: Only Ray version 2.9.3 is supported. + """ + + ray_version = ray.__version__ + if ray_version == "2.4.0": + raise RuntimeError(_V2_4_WARNING_MESSAGE) + if ray_version != "2.9.3": + raise RuntimeError( + f"Ray version {ray_version} is not supported to convert a Sklearn" + " checkpoint to sklearn estimator on Vertex yet. Please use Ray 2.9.3." + ) + + try: + return checkpoint.get_model() + except AttributeError: + model_file_name = ray.train.sklearn.SklearnCheckpoint.MODEL_FILENAME + + model_path = os.path.join(checkpoint.path, model_file_name) + + if os.path.exists(model_path): + with open(model_path, mode="rb") as f: + obj = pickle.load(f) + else: + try: + # Download from GCS to temp and then load_model + with tempfile.TemporaryDirectory() as temp_dir: + gcs_utils.download_from_gcs("gs://" + checkpoint.path, temp_dir) + with open(f"{temp_dir}/{model_file_name}", mode="rb") as f: + obj = cpickle.load(f) + except Exception as e: + raise RuntimeError( + f"{model_file_name} not found in this checkpoint due to: {e}." + ) + return obj diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a67539b75389dcd42deb7377a98dfe6b76192d62 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__init__.py @@ -0,0 +1,22 @@ +"""Ray on Vertex AI Prediction Tensorflow.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .register import register_tensorflow + +__all__ = ("register_tensorflow",) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccdf587e59ad40fb020940685aa521283deb248b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/register.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/register.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c445ed8190e9209ea934c0b6e869e2d4e8da995a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/__pycache__/register.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/register.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/register.py new file mode 100644 index 0000000000000000000000000000000000000000..d532bcdaa0d64249b855c7a4a8ee14768effc9f5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/tensorflow/register.py @@ -0,0 +1,161 @@ +"""Regsiter Tensorflow for Ray on Vertex AI.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import logging +import ray +from typing import Callable, Optional, Union, TYPE_CHECKING +import warnings +from google.cloud import aiplatform +from google.cloud.aiplatform import initializer +from google.cloud.aiplatform import utils +from google.cloud.aiplatform.vertex_ray.predict.util import constants +from google.cloud.aiplatform.vertex_ray.predict.util import ( + predict_utils, +) +from google.cloud.aiplatform.vertex_ray.util._validation_utils import ( + _V2_4_WARNING_MESSAGE, + _V2_9_WARNING_MESSAGE, +) + + +try: + from ray.train import tensorflow as ray_tensorflow + + if TYPE_CHECKING: + import tensorflow as tf + +except ModuleNotFoundError as mnfe: + raise ModuleNotFoundError("Tensorflow isn't installed.") from mnfe + + +def register_tensorflow( + checkpoint: ray_tensorflow.TensorflowCheckpoint, + artifact_uri: Optional[str] = None, + _model: Optional[Union["tf.keras.Model", Callable[[], "tf.keras.Model"]]] = None, + display_name: Optional[str] = None, + tensorflow_version: Optional[str] = None, + **kwargs, +) -> aiplatform.Model: + """Uploads a Ray Tensorflow Checkpoint as Tensorflow Model to Model Registry. + + Example usage: + from vertex_ray.predict import tensorflow + + def create_model(): + model = tf.keras.Sequential(...) + ... + return model + + result = trainer.fit() + my_model = tensorflow.register_tensorflow( + checkpoint=result.checkpoint, + _model=create_model, + artifact_uri="gs://{gcs-bucket-name}/path/to/store", + use_gpu=True + ) + + 1. `use_gpu` will be passed to aiplatform.Model.upload_tensorflow_saved_model() + 2. The `create_model` provides the model_definition which is required if + you create the TensorflowCheckpoint using `from_model` method. + More here, https://docs.ray.io/en/latest/train/api/doc/ray.train.tensorflow.TensorflowCheckpoint.get_model.html#ray.train.tensorflow.TensorflowCheckpoint.get_model + + Args: + checkpoint: TensorflowCheckpoint instance. + artifact_uri (str): + Optional. The path to the directory where Model Artifacts will be saved. If + not set, will use staging bucket set in aiplatform.init(). + _model: Tensorflow Model Definition. Refer + https://docs.ray.io/en/latest/train/api/doc/ray.train.tensorflow.TensorflowCheckpoint.get_model.html#ray.train.tensorflow.TensorflowCheckpoint.get_model + display_name (str): + Optional. The display name of the Model. The name can be up to 128 + characters long and can be consist of any UTF-8 characters. + tensorflow_version (str): + Optional. The version of the Tensorflow serving container. + Supported versions: + https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers + If the version is not specified, the latest version is used. + **kwargs: + Any kwargs will be passed to aiplatform.Model registration. + + Returns: + model (aiplatform.Model): + Instantiated representation of the uploaded model resource. + + Raises: + ValueError: Invalid Argument. + """ + if ray.__version__ == "2.9.3": + warnings.warn(_V2_9_WARNING_MESSAGE, DeprecationWarning, stacklevel=1) + if tensorflow_version is None: + tensorflow_version = constants._TENSORFLOW_VERSION + artifact_uri = artifact_uri or initializer.global_config.staging_bucket + predict_utils.validate_artifact_uri(artifact_uri) + prefix = "ray-on-vertex-registered-tensorflow-model" + display_model_name = ( + (f"{prefix}-{utils.timestamped_unique_name()}") + if display_name is None + else display_name + ) + tf_model = _get_tensorflow_model_from(checkpoint, model=_model) + model_dir = os.path.join(artifact_uri, prefix) + try: + import tensorflow as tf + + tf.saved_model.save(tf_model, model_dir) + except ImportError: + logging.warning("TensorFlow must be installed to save the trained model.") + return aiplatform.Model.upload_tensorflow_saved_model( + saved_model_dir=model_dir, + display_name=display_model_name, + tensorflow_version=tensorflow_version, + **kwargs, + ) + + +def _get_tensorflow_model_from( + checkpoint: ray_tensorflow.TensorflowCheckpoint, + model: Optional[Union["tf.keras.Model", Callable[[], "tf.keras.Model"]]] = None, +) -> "tf.keras.Model": + """Converts a TensorflowCheckpoint to Tensorflow Model. + + Args: + checkpoint: TensorflowCheckpoint instance. + model: Tensorflow Model Defination. + + Returns: + A Tensorflow Native Framework Model. + + Raises: + ValueError: Invalid Argument. + RuntimeError: Ray version 2.4.0 is not supported. + """ + ray_version = ray.__version__ + if ray_version == "2.4.0": + raise RuntimeError(_V2_4_WARNING_MESSAGE) + + try: + import tensorflow as tf + + try: + return tf.saved_model.load(checkpoint.path) + except OSError: + return tf.saved_model.load("gs://" + checkpoint.path) + + except ImportError: + logging.warning("TensorFlow must be installed to load the trained model.") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..175fcd90fa0c522d4cd198438fd1ae9ef017d206 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__init__.py @@ -0,0 +1,22 @@ +"""Ray on Vertex AI Prediction Tensorflow.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .register import get_pytorch_model_from + +__all__ = ("get_pytorch_model_from",) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28b9d7ea81baaff441fa719dc111db49fffe7c5b Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/register.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/register.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c6c1a9f0396a0db0ddfe2adec1167591823155 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/__pycache__/register.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/register.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/register.py new file mode 100644 index 0000000000000000000000000000000000000000..07b25ed72cf71692250f466e2abfd4b4d2a5a40e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/torch/register.py @@ -0,0 +1,113 @@ +"""Regsiter Torch for Ray on Vertex AI.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import warnings +import ray +from ray.air._internal.torch_utils import load_torch_model +import tempfile +from google.cloud.aiplatform.vertex_ray.util._validation_utils import ( + _V2_4_WARNING_MESSAGE, + _V2_9_WARNING_MESSAGE, +) +from google.cloud.aiplatform.utils import gcs_utils +from typing import Optional + + +try: + from ray.train import torch as ray_torch + import torch +except ModuleNotFoundError as mnfe: + raise ModuleNotFoundError("Torch isn't installed.") from mnfe + + +def get_pytorch_model_from( + checkpoint: ray_torch.TorchCheckpoint, + model: Optional[torch.nn.Module] = None, +) -> torch.nn.Module: + """Converts a TorchCheckpoint to Pytorch Model. + + Example: + from vertex_ray.predict import torch + result = TorchTrainer.fit(...) + + pytorch_model = torch.get_pytorch_model_from( + checkpoint=result.checkpoint + ) + + Args: + checkpoint: TorchCheckpoint instance. + model: If the checkpoint contains a model state dict, and not the model + itself, then the state dict will be loaded to this `model`. Otherwise, + the model will be discarded. + + Returns: + A Pytorch Native Framework Model. + + Raises: + ValueError: Invalid Argument. + ModuleNotFoundError: PyTorch isn't installed. + RuntimeError: Model not found. + RuntimeError: Ray version 2.4 is not supported. + RuntimeError: Only Ray version 2.9.3 is supported. + """ + ray_version = ray.__version__ + if ray_version == "2.4.0": + raise RuntimeError(_V2_4_WARNING_MESSAGE) + if ray_version != "2.9.3": + raise RuntimeError( + f"Ray on Vertex does not support Ray version {ray_version} to" + " convert PyTorch model artifacts yet. Please use Ray 2.9.3." + ) + if ray_version == "2.9.3": + warnings.warn(_V2_9_WARNING_MESSAGE, DeprecationWarning, stacklevel=1) + + try: + return checkpoint.get_model() + except AttributeError: + model_file_name = ray.train.torch.TorchCheckpoint.MODEL_FILENAME + + model_path = os.path.join(checkpoint.path, model_file_name) + + try: + import torch + + except ModuleNotFoundError as mnfe: + raise ModuleNotFoundError("PyTorch isn't installed.") from mnfe + + if os.path.exists(model_path): + model_or_state_dict = torch.load( + model_path, map_location="cpu", weights_only=True + ) + else: + try: + # Download from GCS to temp and then load_model + with tempfile.TemporaryDirectory() as temp_dir: + gcs_utils.download_from_gcs("gs://" + checkpoint.path, temp_dir) + model_or_state_dict = torch.load( + f"{temp_dir}/{model_file_name}", + map_location="cpu", + weights_only=True, + ) + except Exception as e: + raise RuntimeError( + f"{model_file_name} not found in this checkpoint due to: {e}." + ) + + model = load_torch_model(saved_model=model_or_state_dict, model_definition=model) + return model diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab6a82c3b473c5bd82e6d564b74d41915711e24d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/constants.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/predict_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/predict_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38642b84268dfbd35c0b750875acda1d336113ec Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/__pycache__/predict_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/constants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..840c824529b95ebdd6335571475c82b791ce854b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/constants.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Constants.""" + +# Required Names for model files are specified here +# https://cloud.google.com/vertex-ai/docs/training/exporting-model-artifacts#framework-specific_requirements +_PICKLE_FILE_NAME = "model.pkl" +_PICKLE_EXTENTION = ".pkl" + +_XGBOOST_VERSION = "1.6" +# TensorFlow 2.13 requires typing_extensions<4.6 and will cause errors in Ray. +# https://github.com/tensorflow/tensorflow/blob/v2.13.0/tensorflow/tools/pip_package/setup.py#L100 +# 2.13 is the latest supported version of Vertex prebuilt prediction container. +# Set 2.12 as default here since 2.13 cause errors. +_TENSORFLOW_VERSION = "2.12" diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/predict_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/predict_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e105dbd21294fef64497ceedb53e9cde2999e440 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/util/predict_utils.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +"""Predict Utils.""" + + +def validate_artifact_uri(artifact_uri: str) -> None: + if artifact_uri is None or not artifact_uri.startswith("gs://"): + raise ValueError("Argument 'artifact_uri' should start with 'gs://'.") diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d98b638879dcf4ae6b3db0f59311c2cebdf1dd7f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__init__.py @@ -0,0 +1,22 @@ +"""Ray on Vertex AI Prediction Tensorflow.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .register import register_xgboost + +__all__ = ("register_xgboost",) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aacceae30ad79a55731aabca981be6cd196e10af Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/register.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/register.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f99bea74f2bacd32dc94c4ad410d247b1d616750 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/__pycache__/register.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/register.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/register.py new file mode 100644 index 0000000000000000000000000000000000000000..7072b0f19299a4ebca3af3553db2a4c86982abdf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/predict/xgboost/register.py @@ -0,0 +1,189 @@ +"""Regsiter XGBoost for Ray on Vertex AI.""" + +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import pickle +import ray +import tempfile +from typing import Optional, TYPE_CHECKING +import warnings +from google.cloud import aiplatform +from google.cloud.aiplatform import initializer +from google.cloud.aiplatform import utils +from google.cloud.aiplatform.utils import gcs_utils +from google.cloud.aiplatform.vertex_ray.predict.util import constants +from google.cloud.aiplatform.vertex_ray.predict.util import ( + predict_utils, +) +from google.cloud.aiplatform.vertex_ray.util._validation_utils import ( + _V2_4_WARNING_MESSAGE, + _V2_9_WARNING_MESSAGE, +) + + +try: + from ray.train import xgboost as ray_xgboost + + if TYPE_CHECKING: + import xgboost + +except ModuleNotFoundError as mnfe: + if ray.__version__ == "2.9.3": + raise ModuleNotFoundError("XGBoost isn't installed.") from mnfe + else: + xgboost = None + + +def register_xgboost( + checkpoint: "ray_xgboost.XGBoostCheckpoint", + artifact_uri: Optional[str] = None, + display_name: Optional[str] = None, + xgboost_version: Optional[str] = None, + **kwargs, +) -> aiplatform.Model: + """Uploads a Ray XGBoost Checkpoint as XGBoost Model to Model Registry. + + Example usage: + from vertex_ray.predict import xgboost + from ray.train.xgboost import XGBoostCheckpoint + + trainer = XGBoostTrainer(...) + result = trainer.fit() + xgboost_checkpoint = XGBoostCheckpoint.from_checkpoint(result.checkpoint) + + my_model = xgboost.register_xgboost( + checkpoint=xgboost_checkpoint, + artifact_uri="gs://{gcs-bucket-name}/path/to/store", + display_name="my-ray-on-vertex-xgboost-model", + ) + + + Args: + checkpoint: XGBoostCheckpoint instance. + artifact_uri (str): + The path to the directory where Model Artifacts will be saved. If + not set, will use staging bucket set in aiplatform.init(). + display_name (str): + Optional. The display name of the Model. The name can be up to 128 + characters long and can be consist of any UTF-8 characters. + xgboost_version (str): Optional. The version of the XGBoost serving container. + Supported versions: + https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers + If the version is not specified, the version 1.6 is used. + **kwargs: + Any kwargs will be passed to aiplatform.Model registration. + + Returns: + model (aiplatform.Model): + Instantiated representation of the uploaded model resource. + + Raises: + ValueError: Invalid Argument. + RuntimeError: Only Ray version 2.9.3 is supported. + """ + ray_version = ray.__version__ + if ray_version != "2.9.3": + raise RuntimeError( + f"Ray version {ray_version} is not supported to upload XGBoost" + " model to Vertex Model Registry yet. Please use Ray 2.9.3." + ) + if ray_version == "2.9.3": + warnings.warn(_V2_9_WARNING_MESSAGE, DeprecationWarning, stacklevel=1) + artifact_uri = artifact_uri or initializer.global_config.staging_bucket + predict_utils.validate_artifact_uri(artifact_uri) + display_model_name = ( + (f"ray-on-vertex-registered-xgboost-model-{utils.timestamped_unique_name()}") + if display_name is None + else display_name + ) + model = _get_xgboost_model_from(checkpoint) + + model_dir = os.path.join(artifact_uri, display_model_name) + file_path = os.path.join(model_dir, constants._PICKLE_FILE_NAME) + if xgboost_version is None: + xgboost_version = constants._XGBOOST_VERSION + + with tempfile.NamedTemporaryFile(suffix=constants._PICKLE_EXTENTION) as temp_file: + pickle.dump(model, temp_file) + gcs_utils.upload_to_gcs(temp_file.name, file_path) + return aiplatform.Model.upload_xgboost_model_file( + model_file_path=temp_file.name, + display_name=display_model_name, + xgboost_version=xgboost_version, + **kwargs, + ) + + +def _get_xgboost_model_from( + checkpoint: "ray_xgboost.XGBoostCheckpoint", +) -> "xgboost.Booster": + """Converts a XGBoostCheckpoint to XGBoost model. + + Args: + checkpoint: XGBoostCheckpoint instance. + + Returns: + A XGBoost core Booster + + Raises: + ValueError: Invalid Argument. + ModuleNotFoundError: XGBoost isn't installed. + RuntimeError: Model not found. + RuntimeError: Ray version 2.4 is not supported. + RuntimeError: Only Ray version 2.9.3 is supported. + """ + ray_version = ray.__version__ + if ray_version == "2.4.0": + raise RuntimeError(_V2_4_WARNING_MESSAGE) + if ray_version != "2.9.3": + raise RuntimeError( + f"Ray version {ray_version} is not supported to convert a XGBoost" + " checkpoint to XGBoost model on Vertex yet. Please use Ray 2.9.3." + ) + + try: + # This works for Ray v2.5 + return checkpoint.get_model() + except AttributeError: + # This works for Ray v2.9 + model_file_name = ray.train.xgboost.XGBoostCheckpoint.MODEL_FILENAME + + model_path = os.path.join(checkpoint.path, model_file_name) + + try: + import xgboost + + except ModuleNotFoundError as mnfe: + raise ModuleNotFoundError("XGBoost isn't installed.") from mnfe + + booster = xgboost.Booster() + if os.path.exists(model_path): + booster.load_model(model_path) + return booster + + try: + # Download from GCS to temp and then load_model + with tempfile.TemporaryDirectory() as temp_dir: + gcs_utils.download_from_gcs("gs://" + checkpoint.path, temp_dir) + booster.load_model(f"{temp_dir}/{model_file_name}") + return booster + except Exception as e: + raise RuntimeError( + f"{model_file_name} not found in this checkpoint due to: {e}." + ) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_shellurirow.html.j2 b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_shellurirow.html.j2 new file mode 100644 index 0000000000000000000000000000000000000000..748ffe9a09222e71eaf8f65633aba10b30fb5d9c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_shellurirow.html.j2 @@ -0,0 +1,4 @@ + + Interactive Terminal Uri: + {{ shell_uri }} + \ No newline at end of file diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_table.html.j2 b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_table.html.j2 new file mode 100644 index 0000000000000000000000000000000000000000..f6749382082c3c09b6ac459d1a02101725d23d35 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/templates/context_table.html.j2 @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + {{ shell_uri_row }} + + + + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_gapic_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_gapic_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e766dab366e471eab0b768cfb13397a988489e8a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_gapic_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_validation_utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_validation_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a0b2c54ac3df501daa5e8966de2c9f276cfc58 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/_validation_utils.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/resources.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/resources.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2946eb36d73239680bec13c5dc3900d6598d77d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/__pycache__/resources.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_gapic_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_gapic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e84162c45a7ec6d8f7790bcd1c3b2e15166da215 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_gapic_utils.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import datetime +import logging +import time +from typing import Optional + +from google.api_core import exceptions +from google.cloud.aiplatform import initializer +from google.cloud.aiplatform.utils import ( + PersistentResourceClientWithOverride, +) +from google.cloud.aiplatform.vertex_ray.util import _validation_utils +from google.cloud.aiplatform.vertex_ray.util.resources import ( + AutoscalingSpec, + Cluster, + PscIConfig, + Resources, +) +from google.cloud.aiplatform_v1beta1.types.persistent_resource import ( + PersistentResource, +) +from google.cloud.aiplatform_v1beta1.types.persistent_resource_service import ( + GetPersistentResourceRequest, +) + + +_PRIVATE_PREVIEW_IMAGE = "-docker.pkg.dev/vertex-ai/training/tf-" +_OFFICIAL_IMAGE = "-docker.pkg.dev/vertex-ai/training/ray-" + + +def create_persistent_resource_client(): + # location is inhereted from the global configuration at aiplatform.init(). + return initializer.global_config.create_client( + client_class=PersistentResourceClientWithOverride, + appended_gapic_version="vertex_ray", + ).select_version("v1beta1") + + +def polling_delay(num_attempts: int, time_scale: float) -> datetime.timedelta: + """Computes a delay to the next attempt to poll the Vertex service. + + This does bounded exponential backoff, starting with $time_scale. + If $time_scale == 0, it starts with a small time interval, less than + 1 second. + + Args: + num_attempts: The number of times have we polled and found that the + desired result was not yet available. + time_scale: The shortest polling interval, in seconds, or zero. Zero is + treated as a small interval, less than 1 second. + + Returns: + A recommended delay interval, in seconds. + """ + # The polling schedule is slow initially , and then gets faster until 6 + # attempts (after that the sleeping time remains the same). + small_interval = 30.0 # Seconds + interval = max(time_scale, small_interval) * 0.765 ** min(num_attempts, 6) + return datetime.timedelta(seconds=interval) + + +def get_persistent_resource( + persistent_resource_name: str, tolerance: Optional[int] = 0 +): + """Get persistent resource. + + Args: + persistent_resource_name: + "projects//locations//persistentResources/". + tolerance: number of attemps to get persistent resource. + + Returns: + aiplatform_v1.PersistentResource if state is RUNNING. + + Raises: + ValueError: Invalid cluster resource name. + RuntimeError: Service returns error. + RuntimeError: Cluster resource state is STOPPING. + RuntimeError: Cluster resource state is ERROR. + """ + + client = create_persistent_resource_client() + request = GetPersistentResourceRequest(name=persistent_resource_name) + + # TODO(b/277117901): Add test cases for polling and error handling + num_attempts = 0 + while True: + try: + response = client.get_persistent_resource(request) + except exceptions.NotFound: + response = None + if num_attempts >= tolerance: + raise ValueError( + "[Ray on Vertex AI]: Invalid cluster_resource_name %s (404 not" + " found)." % persistent_resource_name + ) + if response: + if response.error.message: + logging.error( + "[Ray on Vertex AI]: %s - %s", + persistent_resource_name, + response.error.message, + ) + raise RuntimeError( + "[Ray on Vertex AI]: Cluster %s returned an error." + % persistent_resource_name + ) + + print("[Ray on Vertex AI]: Cluster State =", response.state) + if response.state == PersistentResource.State.RUNNING: + return response + elif response.state == PersistentResource.State.STOPPING: + raise RuntimeError( + "[Ray on Vertex AI]: Cluster %s is stopping." + % persistent_resource_name + ) + elif response.state == PersistentResource.State.ERROR: + raise RuntimeError( + "[Ray on Vertex AI]: Cluster %s encountered an error." + % persistent_resource_name + ) + # Polling decay + sleep_time = polling_delay(num_attempts=num_attempts, time_scale=150.0) + num_attempts += 1 + print( + "Waiting for cluster provisioning; attempt {}; sleeping for {} seconds".format( + num_attempts, sleep_time + ) + ) + time.sleep(sleep_time.total_seconds()) + + +def persistent_resource_to_cluster( + persistent_resource: PersistentResource, +) -> Optional[Cluster]: + """Format a PersistentResource to a dictionary. + + Args: + persistent_resource: PersistentResource. + Returns: + Cluster. + """ + dashboard_address = persistent_resource.resource_runtime.access_uris.get( + "RAY_DASHBOARD_URI" + ) + cluster = Cluster( + cluster_resource_name=persistent_resource.name, + network=persistent_resource.network, + reserved_ip_ranges=persistent_resource.reserved_ip_ranges, + state=persistent_resource.state.name, + labels=persistent_resource.labels, + dashboard_address=dashboard_address, + ) + if not persistent_resource.resource_runtime_spec.ray_spec: + # skip PersistentResource without RaySpec + logging.info( + "[Ray on Vertex AI]: Cluster %s does not have Ray installed." + % persistent_resource.name, + ) + return + if persistent_resource.psc_interface_config: + cluster.psc_interface_config = PscIConfig( + network_attachment=persistent_resource.psc_interface_config.network_attachment + ) + resource_pools = persistent_resource.resource_pools + + head_resource_pool = resource_pools[0] + head_id = head_resource_pool.id + head_image_uri = ( + persistent_resource.resource_runtime_spec.ray_spec.resource_pool_images[head_id] + ) + if persistent_resource.resource_runtime_spec.service_account_spec.service_account: + cluster.service_account = ( + persistent_resource.resource_runtime_spec.service_account_spec.service_account + ) + if not head_image_uri: + head_image_uri = persistent_resource.resource_runtime_spec.ray_spec.image_uri + + try: + python_version, ray_version = _validation_utils.get_versions_from_image_uri( + head_image_uri + ) + except IndexError: + if _PRIVATE_PREVIEW_IMAGE in head_image_uri: + # If using outdated images + logging.info( + "[Ray on Vertex AI]: The image of cluster %s is outdated." + " It is recommended to delete and recreate the cluster to obtain" + " the latest image." % persistent_resource.name + ) + return None + else: + # Custom image might also cause IndexError + python_version = None + ray_version = None + cluster.python_version = python_version + cluster.ray_version = ray_version + cluster.ray_metric_enabled = not ( + persistent_resource.resource_runtime_spec.ray_spec.ray_metric_spec.disabled + ) + cluster.ray_logs_enabled = not ( + persistent_resource.resource_runtime_spec.ray_spec.ray_logs_spec.disabled + ) + + accelerator_type = head_resource_pool.machine_spec.accelerator_type + if accelerator_type.value != 0: + accelerator_type = accelerator_type.name + else: + accelerator_type = None + if _OFFICIAL_IMAGE in head_image_uri: + # Official training image is not custom + head_image_uri = None + head_node_type = Resources( + machine_type=head_resource_pool.machine_spec.machine_type, + accelerator_type=accelerator_type, + accelerator_count=head_resource_pool.machine_spec.accelerator_count, + boot_disk_type=head_resource_pool.disk_spec.boot_disk_type, + boot_disk_size_gb=head_resource_pool.disk_spec.boot_disk_size_gb, + node_count=1, + custom_image=head_image_uri, + ) + worker_node_types = [] + if head_resource_pool.replica_count > 1: + # head_node_type.node_count must be 1. If the head_resource_pool (the first + # resource pool) has replica_count > 1, the rest replica are worker nodes. + worker_node_count = head_resource_pool.replica_count - 1 + worker_node_types.append( + Resources( + machine_type=head_resource_pool.machine_spec.machine_type, + accelerator_type=accelerator_type, + accelerator_count=head_resource_pool.machine_spec.accelerator_count, + boot_disk_type=head_resource_pool.disk_spec.boot_disk_type, + boot_disk_size_gb=head_resource_pool.disk_spec.boot_disk_size_gb, + node_count=worker_node_count, + custom_image=head_image_uri, + ) + ) + if head_resource_pool.autoscaling_spec: + worker_node_types[0].autoscaling_spec = AutoscalingSpec( + min_replica_count=head_resource_pool.autoscaling_spec.min_replica_count, + max_replica_count=head_resource_pool.autoscaling_spec.max_replica_count, + ) + for i in range(len(resource_pools) - 1): + # Convert the second and more resource pools to vertex_ray.Resources, + # and append then to worker_node_types. + accelerator_type = resource_pools[i + 1].machine_spec.accelerator_type + if accelerator_type.value != 0: + accelerator_type = accelerator_type.name + else: + accelerator_type = None + worker_image_uri = ( + persistent_resource.resource_runtime_spec.ray_spec.resource_pool_images[ + resource_pools[i + 1].id + ] + ) + if _OFFICIAL_IMAGE in worker_image_uri: + # Official training image is not custom + worker_image_uri = None + + resource = Resources( + machine_type=resource_pools[i + 1].machine_spec.machine_type, + accelerator_type=accelerator_type, + accelerator_count=resource_pools[i + 1].machine_spec.accelerator_count, + boot_disk_type=resource_pools[i + 1].disk_spec.boot_disk_type, + boot_disk_size_gb=resource_pools[i + 1].disk_spec.boot_disk_size_gb, + node_count=resource_pools[i + 1].replica_count, + custom_image=worker_image_uri, + ) + if resource_pools[i + 1].autoscaling_spec: + resource.autoscaling_spec = AutoscalingSpec( + min_replica_count=resource_pools[ + i + 1 + ].autoscaling_spec.min_replica_count, + max_replica_count=resource_pools[ + i + 1 + ].autoscaling_spec.max_replica_count, + ) + + worker_node_types.append(resource) + + cluster.head_node_type = head_node_type + cluster.worker_node_types = worker_node_types + + return cluster diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_validation_utils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_validation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2a833aa764866190a5343cd9f4ba13bc50bb59 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/_validation_utils.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import google.auth +import google.auth.transport.requests +import logging +import ray +import re +from immutabledict import immutabledict + +from google.cloud.aiplatform import initializer +from google.cloud.aiplatform.utils import resource_manager_utils + +SUPPORTED_RAY_VERSIONS = immutabledict( + {"2.9": "2.9.3", "2.33": "2.33.0", "2.42": "2.42.0", "2.47": "2.47.1"} +) +SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS = immutabledict( + { + "3.10": ("2.9", "2.33", "2.42"), + "3.11": ("2.42", "2.47"), + } +) +_V2_4_WARNING_MESSAGE = ( + "After google-cloud-aiplatform>1.53.0, using Ray version = 2.4 will result in " + "an error. Please use Ray version = 2.33.0, 2.42.0 or 2.47.1 (default) instead." +) +_V2_9_WARNING_MESSAGE = ( + "In March 2025, using Ray version = 2.9 will result in an error. " + "Please use Ray version = 2.33.0, 2.42.0 or 2.47.1 (default) instead." +) + + +# Artifact Repository available regions. +_AVAILABLE_REGIONS = ["us", "europe", "asia"] +# If region is not available, assume using the default region. +_DEFAULT_REGION = "us" + +_PERSISTENT_RESOURCE_NAME_PATTERN = "projects/{}/locations/{}/persistentResources/{}" +_VALID_RESOURCE_NAME_REGEX = "[a-z][a-zA-Z0-9._-]{0,127}" +_DASHBOARD_URI_SUFFIX = "aiplatform-training.googleusercontent.com" + + +def valid_resource_name(resource_name): + """Check if address is a valid resource name.""" + resource_name_split = resource_name.split("/") + if not ( + len(resource_name_split) == 6 + and resource_name_split[0] == "projects" + and resource_name_split[2] == "locations" + and resource_name_split[4] == "persistentResources" + ): + raise ValueError( + "[Ray on Vertex AI]: Address must be in the following " + "format: vertex_ray://projects//locations//persistentResources/ " + "or vertex_ray://." + ) + + +def maybe_reconstruct_resource_name(address) -> str: + """Reconstruct full persistent resource name if only id was given.""" + if re.match("^{}$".format(_VALID_RESOURCE_NAME_REGEX), address): + # Assume only cluster name (persistent resource id) was given. + logging.info( + "[Ray on Vertex AI]: Cluster name was given as address, reconstructing full resource name" + ) + return _PERSISTENT_RESOURCE_NAME_PATTERN.format( + resource_manager_utils.get_project_number( + initializer.global_config.project + ), + initializer.global_config.location, + address, + ) + + return address + + +def get_local_ray_version(): + ray_version = ray.__version__.split(".") + if len(ray_version) == 3: + ray_version = ray_version[:2] + return ".".join(ray_version) + + +def get_image_uri(ray_version, python_version, enable_cuda): + """Image uri for a given ray version and python version.""" + if ray_version not in SUPPORTED_RAY_VERSIONS: + raise ValueError( + "[Ray on Vertex AI]: The supported Ray versions are %s (%s) and %s (%s)." + % ( + list(SUPPORTED_RAY_VERSIONS.keys())[0], + list(SUPPORTED_RAY_VERSIONS.values())[0], + list(SUPPORTED_RAY_VERSIONS.keys())[1], + list(SUPPORTED_RAY_VERSIONS.values())[1], + ) + ) + if python_version is None: + for pv, ray_versions in SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS.items(): + if ray_version in ray_versions: + python_version = pv + break + if python_version not in SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS: + raise ValueError( + "[Ray on Vertex AI]: The supported Python versions are 3.10 or 3.11." + ) + + if ray_version not in SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS[python_version]: + raise ValueError( + "[Ray on Vertex AI]: The supported Ray version(s) for Python version %s: %s." + % ( + python_version, + SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS[python_version], + ) + ) + + location = initializer.global_config.location + region = location.split("-")[0] + if region not in _AVAILABLE_REGIONS: + region = _DEFAULT_REGION + ray_version = ray_version.replace(".", "-") + python_version = python_version.replace(".", "") + if enable_cuda: + return f"{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.{ray_version}.py{python_version}:latest" + else: + return f"{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.{ray_version}.py{python_version}:latest" + + +def get_versions_from_image_uri(image_uri): + """Get ray version and python version from image uri.""" + logging.info(f"[Ray on Vertex AI]: Getting versions from image uri: {image_uri}") + image_label = image_uri.split("/")[-1].split(":")[0] + py_version = image_label[-3] + "." + image_label[-2:] + ray_version = image_label.split(".")[1].replace("-", ".") + if ( + py_version in SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS + and ray_version in SUPPORTED_RAY_VERSIONS_FROM_PYTHON_VERSIONS[py_version] + ): + return py_version, ray_version + else: + # May not parse custom image and get the versions correctly + return None, None + + +def valid_dashboard_address(address): + """Check if address is a valid dashboard uri.""" + return address.endswith(_DASHBOARD_URI_SUFFIX) + + +def get_bearer_token(): + """Get bearer token through Application Default Credentials.""" + creds, _ = google.auth.default( + scopes=["https://www.googleapis.com/auth/cloud-platform"] + ) + + # creds.valid is False, and creds.token is None + # Need to refresh credentials to populate those + auth_req = google.auth.transport.requests.Request() + creds.refresh(auth_req) + return creds.token diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/resources.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..a9143a4dfd2beb62e0e8a580de397e4aa0d899ff --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/vertex_ray/util/resources.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- + +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +from typing import Dict, List, Optional +from google.cloud.aiplatform_v1beta1.types import PersistentResource + + +@dataclasses.dataclass +class AutoscalingSpec: + """Autoscaling spec for a ray cluster node. + + Attributes: + min_replica_count: The minimum number of replicas in the cluster. + max_replica_count: The maximum number of replicas in the cluster. + """ + + min_replica_count: int = 1 + max_replica_count: int = 2 + + +@dataclasses.dataclass +class Resources: + """Resources for a ray cluster node. + + Attributes: + machine_type: See the list of machine types: + https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types + node_count: This argument represents how many nodes to start for the + ray cluster. + accelerator_type: e.g. "NVIDIA_TESLA_P4". + Vertex AI supports the following types of GPU: + https://cloud.google.com/vertex-ai/docs/training/configure-compute#specifying_gpus + accelerator_count: The number of accelerators to attach to the machine. + boot_disk_type: Type of the boot disk (default is "pd-ssd"). + Valid values: "pd-ssd" (Persistent Disk Solid State Drive) or + "pd-standard" (Persistent Disk Hard Disk Drive). + boot_disk_size_gb: Size in GB of the boot disk (default is 100GB). Must + be either unspecified or within the range of [100, 64000]. + custom_image: Custom image for this resource (e.g. + us-docker.pkg.dev/my-project/ray-gpu.2-9.py310-tf:latest). + autoscaling_spec: Autoscaling spec for this resource. + """ + + machine_type: Optional[str] = "n1-standard-16" + node_count: Optional[int] = 1 + accelerator_type: Optional[str] = None + accelerator_count: Optional[int] = 0 + boot_disk_type: Optional[str] = "pd-ssd" + boot_disk_size_gb: Optional[int] = 100 + custom_image: Optional[str] = None + autoscaling_spec: Optional[AutoscalingSpec] = None + + +@dataclasses.dataclass +class NodeImages: + """Custom images for a ray cluster. + + We currently support Ray v2.9, v2.33, v2.42 and python v3.10. + We also support python v3.11 for Ray v2.42 and v2.47. + The custom images must be extended from the following base images: + "{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.2-9.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.2-9.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.2-33.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.2-33.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.2-42.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.2-42.py310:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.2-42.py311:latest", + "{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.2-42.py311:latest". + "{region}-docker.pkg.dev/vertex-ai/training/ray-cpu.2-47.py311:latest", or + "{region}-docker.pkg.dev/vertex-ai/training/ray-gpu.2-47.py311:latest". In + order to use custom images, need to specify both head and worker images. + + Attributes: + head: image for head node (eg. us-docker.pkg.dev/my-project/ray-cpu.2-47.py311:latest). + worker: image for all worker nodes (eg. us-docker.pkg.dev/my-project/ray-gpu.2-47.py311:latest). + """ + + head: str = None + worker: str = None + + +@dataclasses.dataclass +class PscIConfig: + """PSC-I config. + + Attributes: + network_attachment: Optional. The name or full name of the Compute Engine + `network attachment ` + to attach to the resource. It has a format: + ``projects/{project}/regions/{region}/networkAttachments/{networkAttachment}``. + Where {project} is a project number, as in ``12345``, and + {networkAttachment} is a network attachment name. To specify + this field, you must have already [created a network + attachment] + (https://cloud.google.com/vpc/docs/create-manage-network-attachments#create-network-attachments). + This field is only used for resources using PSC-I. Make sure you do not + specify the network here for VPC peering. + """ + + network_attachment: str = None + + +@dataclasses.dataclass +class NfsMount: + """NFS mount. + + Attributes: + server: Required. IP address of the NFS server. + path: Required. Source path exported from NFS server. Has to start + with '/', and combined with the ip address, it indicates the + source mount path in the form of ``server:path``. + mount_point: Required. Destination mount path. The NFS will be mounted + for the user under /mnt/nfs/. + """ + + server: str = None + path: str = None + mount_point: str = None + + +@dataclasses.dataclass +class Cluster: + """Ray cluster (output only). + + Attributes: + cluster_resource_name: It has a format: + "projects//locations//persistentResources/". + network: Virtual private cloud (VPC) network. It has a format: + "projects//global/networks/". + For Ray Client, VPC peering is required to connect to the cluster + managed in the Vertex API service. For Ray Job API, VPC network is + not required because cluster connection can be accessed through + dashboard address. + reserved_ip_ranges: A list of names for the reserved IP ranges under + the VPC network that can be used for this cluster. If set, we will + deploy the cluster within the provided IP ranges. Otherwise, the + cluster is deployed to any IP ranges under the provided VPC network. + Example: ["vertex-ai-ip-range"]. + service_account: Service account to be used for running Ray programs on + the cluster. + state: Describes the cluster state (defined in PersistentResource.State). + python_version: Python version for the ray cluster (e.g. "3.11"). + ray_version: Ray version for the ray cluster (e.g. "2.47"). + head_node_type: The head node resource. Resources.node_count must be 1. + If not set, by default it is a CPU node with machine_type of n1-standard-8. + worker_node_types: The list of Resources of the worker nodes. Should not + duplicate the elements in the list. + dashboard_address: For Ray Job API (JobSubmissionClient), with this + cluster connection doesn't require VPC peering. + labels: + The labels with user-defined metadata to organize Ray cluster. + + Label keys and values can be no longer than 64 characters (Unicode + codepoints), can only contain lowercase letters, numeric characters, + underscores and dashes. International characters are allowed. + + See https://goo.gl/xmQnxf for more information and examples of labels. + """ + + cluster_resource_name: str = None + network: str = None + reserved_ip_ranges: List[str] = None + service_account: str = None + state: PersistentResource.State = None + python_version: str = None + ray_version: str = None + head_node_type: Resources = None + worker_node_types: List[Resources] = None + dashboard_address: str = None + ray_metric_enabled: bool = True + ray_logs_enabled: bool = True + psc_interface_config: PscIConfig = None + labels: Dict[str, str] = None + + +def _check_machine_spec_identical( + node_type_1: Resources, + node_type_2: Resources, +) -> int: + """Check if node_type_1 and node_type_2 have the same machine_spec. + If they are identical, return additional_replica_count.""" + additional_replica_count = 0 + + # Check if machine_spec are the same + if ( + node_type_1.machine_type == node_type_2.machine_type + and node_type_1.accelerator_type == node_type_2.accelerator_type + and node_type_1.accelerator_count == node_type_2.accelerator_count + ): + if node_type_1.boot_disk_type != node_type_2.boot_disk_type: + raise ValueError( + "Worker disk type must match the head node's disk type if" + " sharing the same machine_type, accelerator_type, and" + " accelerator_count" + ) + if node_type_1.boot_disk_size_gb != node_type_2.boot_disk_size_gb: + raise ValueError( + "Worker disk size must match the head node's disk size if" + " sharing the same machine_type, accelerator_type, and" + " accelerator_count" + ) + additional_replica_count = node_type_2.node_count + return additional_replica_count + + return additional_replica_count diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df7a5e405f6ddc1c34af4a60eba06be9a53a3783 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_parse.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_parse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aee497ea102b7aea29bd4350399b5e866143301 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_parse.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_path.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_path.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f03b40ea728881120fb2ca8a358567b99b58e328 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_path.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_query.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_query.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce5e548c7f7400f102a340567585f17a752a096a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_query.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c0b486bc6878be268d4aba8e6919d943b94db5c Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoters.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21bcb4c063185ebd221e5f7d85a2f42c550cd400 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7604a621d24a4fb439b693f3ba708340e85c984 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_url.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cbf0a7658b8590a76d76080e9a36f68fd57de3d Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/yarl/__pycache__/_url.cpython-311.pyc differ