Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

numpy: add new recipe #20283

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions recipes/numpy/all/conandata.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
sources:
"1.26.4":
url: "https://github.com/numpy/numpy/releases/download/v1.26.4/numpy-1.26.4.tar.gz"
sha256: "2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010"
155 changes: 155 additions & 0 deletions recipes/numpy/all/conanfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import os
import textwrap

from conan import ConanFile, conan_version
from conan.errors import ConanInvalidConfiguration
from conan.tools.env import Environment, VirtualBuildEnv
from conan.tools.files import copy, get, save
from conan.tools.gnu import PkgConfigDeps
from conan.tools.layout import basic_layout
from conan.tools.meson import Meson, MesonToolchain
from conan.tools.scm import Version

required_conan_version = ">=1.60.0 <2 || >=2.0.6"


class NumpyConan(ConanFile):
name = "numpy"
description = "NumPy is the fundamental package for scientific computing with Python."
license = "BSD 3-Clause"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://numpy.org/devdocs/reference/c-api/index.html"
topics = ("ndarray", "array", "linear algebra", "npymath")

package_type = "application"
settings = "os", "arch", "compiler", "build_type"
options = {
"fPIC": [True, False],
}
default_options = {
"fPIC": True,
}
short_paths = True

def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC

def configure(self):
self.settings.rm_safe("compiler.libcxx")
self.settings.rm_safe("compiler.cppstd")

def validate(self):
if conan_version.major == 1:
raise ConanInvalidConfiguration("Conan v1 is not supported")
# https://github.com/numpy/numpy/blob/v1.26.4/meson.build#L28
if self.settings.compiler == "gcc" and self.settings.compiler.version < Version("8.4"):
raise ConanInvalidConfiguration(f"{self.ref} requires GCC 8.4+")

def layout(self):
basic_layout(self, src_folder="src")

def requirements(self):
self.requires("openblas/0.3.27")
self.requires("cpython/3.12.7", transitive_headers=True, transitive_libs=True)

def build_requirements(self):
self.tool_requires("cpython/<host_version>")
self.tool_requires("ninja/[>=1.10.2 <2]")
if not self.conf.get("tools.gnu:pkg_config", default=False, check_type=str):
self.tool_requires("pkgconf/[>=2.2 <3]")

def source(self):
get(self, **self.conan_data["sources"][self.version], strip_root=True)

@property
def _meson_root(self):
return self.source_path.joinpath("vendored-meson", "meson")

@property
def _build_site_packages(self):
return os.path.join(self.build_folder, "site-packages")

def generate(self):
venv = VirtualBuildEnv(self)
venv.generate()

env = Environment()
# NumPy can only be built with its vendored Meson
env.prepend_path("PATH", str(self._meson_root))
env.prepend_path("PYTHONPATH", self._build_site_packages)
env.prepend_path("PATH", os.path.join(self._build_site_packages, "bin"))
env.vars(self).save_script("conanbuild_paths")

tc = MesonToolchain(self)
tc.project_options["allow-noblas"] = False
tc.project_options["blas-order"] = ["openblas"]
tc.project_options["lapack-order"] = ["openblas"]
tc.generate()

tc = PkgConfigDeps(self)
tc.generate()

@staticmethod
def _chmod_plus_x(name):
os.chmod(name, os.stat(name).st_mode | 0o111)

def _patch_sources(self):
# Add missing wrapper scripts to the vendored meson
save(self, self._meson_root.joinpath("meson"),
textwrap.dedent("""\
#!/usr/bin/env bash
meson_dir=$(dirname "$0")
export PYTHONDONTWRITEBYTECODE=1
exec "$meson_dir/meson.py" "$@"
"""))
self._chmod_plus_x(self._meson_root.joinpath("meson"))
save(self, self._meson_root.joinpath("meson.cmd"),
textwrap.dedent("""\
@echo off
set PYTHONDONTWRITEBYTECODE=1
CALL python %~dp0/meson.py %*
"""))

# Install cython
self.run(f"python -m pip install cython --no-cache-dir --target {self._build_site_packages}")

def build(self):
self._patch_sources()
meson = Meson(self)
meson.configure()
meson.build()

def package(self):
copy(self, "LICENSE*.txt", self.source_folder, os.path.join(self.package_folder, "licenses"))
meson = Meson(self)
meson.install()

@property
def _rel_site_packages(self):
if self.settings.os == "Windows":
return os.path.join("Lib", "site-packages")
else:
python_minor = Version(self.dependencies["cpython"].ref.version).minor
return os.path.join("lib", f"python3.{python_minor}", "site-packages")

@property
def _rel_pkg_root(self):
return os.path.join(self._rel_site_packages, "numpy")

def package_info(self):
self.cpp_info.components["npymath"].set_property("pkg_config_name", "npymath")
self.cpp_info.components["npymath"].libs = ["npymath"]
self.cpp_info.components["npymath"].libdirs = [
os.path.join(self._rel_pkg_root, "core", "lib"),
os.path.join(self._rel_pkg_root, "random", "lib"),
]
self.cpp_info.components["npymath"].includedirs = [os.path.join(self._rel_pkg_root, "core", "include")]
if self.settings.os in ["Linux", "FreeBSD"]:
self.cpp_info.components["npymath"].system_libs = ["m"]

self.cpp_info.components["numpy"].libdirs = [os.path.join(self._rel_pkg_root, "core")]
self.cpp_info.components["numpy"].requires = ["openblas::openblas", "cpython::cpython", "npymath"]
self.cpp_info.components["numpy"].includedirs = []

self.runenv_info.prepend_path("PYTHONPATH", os.path.join(self.package_folder, self._rel_site_packages))
38 changes: 38 additions & 0 deletions recipes/numpy/all/test_package/conanfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from conan import ConanFile
from conan.tools.build import can_run
from conan.tools.cmake import cmake_layout
from conan.tools.meson import Meson


class TestPackageConan(ConanFile):
settings = "os", "arch", "compiler", "build_type"
generators = "PkgConfigDeps", "MesonToolchain", "VirtualRunEnv", "VirtualBuildEnv"
test_type = "explicit"

def layout(self):
cmake_layout(self)

def requirements(self):
self.requires(self.tested_reference_str)

def build_requirements(self):
self.tool_requires("meson/[>=1.2.3 <2]")
self.tool_requires("cpython/3.12.7")
if not self.conf.get("tools.gnu:pkg_config", default=False, check_type=str):
self.tool_requires("pkgconf/[>=2.2 <3]")

# Note: when building with CMake, the following is required:
# def generate(self):
# VirtualRunEnv(self).generate()
# # Required for find_package(Python) to work with cpython/*:shared=True
# VirtualRunEnv(self).generate(scope="build")

def build(self):
meson = Meson(self)
meson.configure()
meson.build()

def test(self):
if can_run(self):
self.run('python -c "import test_package; print(test_package.create_numpy_array())"',
env=["conanbuild", "conanrun"], cwd=self.build_folder)
8 changes: 8 additions & 0 deletions recipes/numpy/all/test_package/meson.build
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
project('test_package', 'c')
package_dep = dependency('numpy')
py = import('python').find_installation(pure: false)
py.extension_module(
'test_package',
sources : ['test_package.c'],
dependencies : [package_dep],
)
42 changes: 42 additions & 0 deletions recipes/numpy/all/test_package/test_package.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION

// Workaround for GCC<10 bug, see https://github.com/numpy/numpy/issues/16970
#if defined __GNUC__ && !defined __clang__ && __GNUC__ < 10
struct _typeobject {};
#endif

#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/halffloat.h>
#include <numpy/ufuncobject.h>

static PyObject* create_numpy_array(PyObject *self, PyObject *args) {
npy_intp dims[2] = {5, 5};
PyObject *pyArray = PyArray_SimpleNew(2, dims, NPY_HALF);

for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
*((npy_half *)PyArray_GETPTR2((PyArrayObject *)pyArray, i, j)) = npy_float_to_half((float)i * j);
}
}

return pyArray;
}

static PyMethodDef ExampleMethods[] = {
{"create_numpy_array", create_numpy_array, METH_VARARGS, "Create a 2D NumPy array."},
{NULL, NULL, 0, NULL}
};

static PyModuleDef moduledef = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "test_package",
.m_methods = ExampleMethods,
};

PyMODINIT_FUNC PyInit_test_package(void)
{
import_array();
import_umath();
return PyModule_Create(&moduledef);
}
3 changes: 3 additions & 0 deletions recipes/numpy/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
versions:
"1.26.4":
folder: all
Loading