Skip to content

Commit

Permalink
use skbuild
Browse files Browse the repository at this point in the history
  • Loading branch information
maxscheurer committed Feb 25, 2021
1 parent 6fa6d62 commit 9d7e862
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 136 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install pytest numpy h5py numba scipy pandas
pip install pytest numpy h5py scipy pandas scikit-build pybind11
pip install git+https://gitlab.com/reinholdt/polarizationsolver.git@master
- name: Configure CMake (Linux)
Expand All @@ -58,5 +58,5 @@ jobs:
run: |
rm -rf build
python setup.py install
pytest
pytest --pyargs cppe
4 changes: 2 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ jobs:
python -m pip install --user setuptools wheel
- name: Build a source tarball
run: |
pip install pytest numpy h5py numba scipy pandas
pip install pytest numpy h5py scipy pandas scikit-build pybind11
pip install git+https://gitlab.com/reinholdt/polarizationsolver.git@master
python setup.py install
pytest
pytest --pyargs cppe
python setup.py sdist
- name: Publish distribution 📦 to Test PyPI
if: startsWith(github.ref, 'refs/tags')
Expand Down
10 changes: 6 additions & 4 deletions cppe/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ include(CMakePackageConfigHelpers)
include(ExternalProject)

if(ENABLE_OPENMP)
find_package(OpenMP REQUIRED)
find_package(OpenMP)
if (OPENMP_FOUND)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
else()
message(WARNING "Suitable OpenMP could not be found. Building without OpenMP instead.")
endif()
endif()

Expand Down Expand Up @@ -105,7 +107,7 @@ if(${ENABLE_PYTHON_INTERFACE})
# install the Python tests
install(DIRECTORY "../tests"
DESTINATION ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}${PYMOD_INSTALL_LIBDIR}/cppe
FILES_MATCHING PATTERN "*.py" PATTERN "*.pot" PATTERN "*.hdf5")
FILES_MATCHING PATTERN "*.py" PATTERN "*.pot" PATTERN "*.hdf5" PATTERN "*.csv")
endif()

target_compile_definitions(cppe INTERFACE USING_${PN})
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build-system]
requires = ["setuptools", "wheel", "scikit-build", "cmake", "ninja"]
155 changes: 28 additions & 127 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@
"""Setup for cppe"""
import os
import sys
import glob
import setuptools

from setuptools import Extension, find_packages, setup
from setuptools.command.build_ext import build_ext as BuildCommand
try:
from skbuild import setup
except ImportError:
print("Please update pip, you need pip 10 or greater,\n"
" or you need to install the PEP 518 requirements"
" in pyproject.toml yourself",
file=sys.stderr,
)
raise

try:
from sphinx.setup_command import BuildDoc as BuildSphinxDoc
Expand All @@ -22,6 +28,13 @@ def initialize_options(self):
def finalize_options(self):
pass

try:
import pybind11
except ImportError:
print("Please install pybind11 before installing cppe.",
file=sys.stderr,
)
raise

__version__ = "0.3.1"

Expand All @@ -31,117 +44,12 @@ def strip_readme():
return "".join([line for line in fp if not line.startswith("<img")])


#
# Pybind11 BuildExt
#
class GetPyBindInclude:
"""Helper class to determine the pybind11 include path
The purpose of this class is to postpone importing pybind11
until it is actually installed, so that the ``get_include()``
method can be invoked. """

def __init__(self, user=False):
self.user = user

def __str__(self):
import pybind11

return pybind11.get_include(self.user)


# As of Python 3.6, CCompiler has a `has_flag` method.
# cf http:https://bugs.python.org/issue26689
def has_flag(compiler, flagname, opts=[]):
"""Return a boolean indicating whether a flag name is supported on
the specified compiler.
"""
import tempfile
opts += ['-Wno-unused-command-line-argument']

with tempfile.NamedTemporaryFile("w", suffix=".cpp") as f:
f.write("int main (int argc, char **argv) { return 0; }")
try:
extra_postargs = ["-Werror", flagname] + opts
compiler.compile([f.name], extra_postargs=extra_postargs)
except setuptools.distutils.errors.CompileError:
return False
return True


def cpp_flag(compiler, opts=[]):
"""Return the -std=c++[11/14] compiler flag.
The c++14 is preferred over c++11 (when it is available).
"""
if has_flag(compiler, "-std=c++14", opts):
return "-std=c++14"
elif has_flag(compiler, "-std=c++11", opts):
return "-std=c++11"
else:
raise RuntimeError("Unsupported compiler -- at least C++11 support "
"is needed!")


class BuildExt(BuildCommand):
"""A custom build extension for adding compiler-specific options."""
def build_extensions(self):
opts = []
potential_opts = ['-fopenmp']
potential_linker_args = ['-lgomp']
if sys.platform == "darwin":
potential_opts += ["-stdlib=libc++", "-mmacosx-version-min=10.9"]
if self.compiler.compiler_type == "unix":
opts.append(cpp_flag(self.compiler, opts))
potential_opts += ["-fvisibility=hidden", "-Wall", "-Wextra"]
opts.extend([newopt for newopt in potential_opts
if has_flag(self.compiler, newopt, opts)])

link_args = [newopt for newopt in potential_linker_args
if has_flag(self.compiler, newopt, opts)]

for ext in self.extensions:
ext.extra_compile_args = opts
ext.extra_link_args = link_args
BuildCommand.build_extensions(self)


#
# Main setup code
#
# Setup RPATH on Linux and MacOS
if sys.platform == "darwin":
extra_link_args = ["-Wl,-rpath,@loader_path",]
runtime_library_dirs = []
elif sys.platform == "linux":
extra_link_args = []
runtime_library_dirs = ["$ORIGIN",]
else:
raise OSError("Unsupported platform: {}".format(sys.platform))

# Setup source directories
sources = glob.glob("cppe/*.cc")
sources += glob.glob("cppe/core/*.cc")
sources += glob.glob("cppe/core/tensors/*.cc")
sources += glob.glob("cppe/core/fmm/*.cc")
sources += glob.glob("cppe/utils/*.cc")
sources += glob.glob("cppe/python_iface/*.cc")
def is_conda_build():
return (
os.environ.get("CONDA_BUILD", None) == "1"
or os.environ.get("CONDA_EXE", None)
)

# Setup build of the libadcc extension
ext_modules = [
Extension(
"cppe.pycppe", sources=sources,
include_dirs=[
# Path to pybind11 headers
GetPyBindInclude(),
GetPyBindInclude(user=True),
"external/eigen3",
],
extra_link_args=extra_link_args,
runtime_library_dirs=runtime_library_dirs,
language="c++",
),
]

setup(
name="cppe",
Expand All @@ -151,11 +59,11 @@ def build_extensions(self):
keywords=[
"polarizable", "embedding", "excited", "states", "QM/MM",
"electronic", "structure", "computational", "chemistry", "quantum",
"spectroscopy",
"spectroscopy", "fast", "multipole", "method",
],
author="Maximilian Scheurer, Peter Reinholdt,"
" Michael F. Herbst, Lori A. Burns",
autor_email="[email protected]",
author_email="[email protected]",
license="LGPL v3",
url="https://github.com/maxscheurer/cppe",
project_urls={
Expand All @@ -178,23 +86,16 @@ def build_extensions(self):
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: Linux",
],
package_dir={'cppe': 'cppe/python_iface'},
packages=['cppe'],
packages=["cppe"],
package_data={"": ["LICENSE*"]},
ext_modules=ext_modules,
zip_safe=False,
platforms=["Linux", "Mac OS-X"],
python_requires=">=3.6",
setup_requires=["pybind11 >= 2.2"],
install_requires=["pybind11 >= 2.2"],
tests_require=[
"pytest", "numpy", "h5py", "numba", "scipy", "pandas"
cmake_args=[
f'-Dpybind11_DIR={pybind11.get_cmake_dir()}',
'-DENABLE_PYTHON_INTERFACE=ON',
'-DCMAKE_INSTALL_LIBDIR:PATH=.'
],
# extras_require={
# "build_docs": ["sphinx>=2", "breathe", "sphinxcontrib-bibtex",
# "sphinx-automodapi"],
# },
cmdclass={"build_ext": BuildExt,
# "build_docs": BuildDocs,
},
)
2 changes: 1 addition & 1 deletion tests/test_fmm.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_field_computation(self):
fs = np.loadtxt(self.fs_file)
else:
fmuls = cppe.MultipoleFields(potentials, options)
fs = fmuls.compute_tree()
fs = fmuls.compute()
np.savetxt(self.fs_file, fs)

ref = pd.read_csv(os.path.join(self.dirname, "ref_fmm_errors.csv"))
Expand Down

0 comments on commit 9d7e862

Please sign in to comment.