Skip to content

Commit

Permalink
Create pybind11 wrapings
Browse files Browse the repository at this point in the history
Also add support for packaging with scikit-build
  • Loading branch information
phcerdan committed Aug 28, 2019
1 parent d52c066 commit 8add968
Show file tree
Hide file tree
Showing 24 changed files with 540 additions and 21 deletions.
2 changes: 1 addition & 1 deletion .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: false #MODIFIED
BraceWrapping:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
_skbuild/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ message(STATUS "PERM version: ${PERM_VERSION}")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
include(GNUInstallDirs) # Define CMAKE_INSTALL_xxx: LIBDIR, INCLUDEDIR

option(PERM_BUILD_TESTING "Enable Tests" ON)
option(PERM_BUILD_ENABLE_VALGRIND "Enable Valgrind as a memchecker for tests (require debug symbols)" OFF)
Expand Down
2 changes: 1 addition & 1 deletion cmake/PERMConfig.cmake.in
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
include(CMakeFindDependencyMacro)

get_filename_component(PERM_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
if(NOT TARGET Perm)
if(NOT TARGET PERMCore)
include ("${PERM_CMAKE_DIR}/PERMTargets.cmake")
endif()
12 changes: 6 additions & 6 deletions cmake/PERMModuleMacros.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
# ${MODULE_${MODULE_NAME}_DEPENDS}
# ${GTEST_LIBRARIES})
macro(perm_add_gtests)
foreach(test_file ${MODULE_${MODULE_NAME}_TESTS})
foreach(test_file ${test_files})
string(REGEX REPLACE "\\.[^.]*$" "" test_name "${test_file}")
add_executable(${test_name} ${test_file})
target_link_libraries(${test_name} PRIVATE
${MODULE_${MODULE_NAME}_TEST_DEPENDS}
PERMCore
${GTEST_LIBRARIES}
)
target_include_directories(${test_name} SYSTEM PRIVATE
${MODULE_${MODULE_NAME}_TEST_SYSTEM_INCLUDE_DIRS})
# target_include_directories(${test_name} SYSTEM PRIVATE)
gtest_discover_tests(
${test_name}
TEST_PREFIX ${MODULE_NAME}||${test_name}||
PROPERTIES LABELS ${MODULE_NAME}
TEST_PREFIX PERM||${test_name}||
PROPERTIES LABELS PERM
)
endforeach()
endmacro(perm_add_gtests)
3 changes: 3 additions & 0 deletions developer_requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cmake
ninja
scikit-build
30 changes: 28 additions & 2 deletions include/perm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,35 @@
#ifndef PERM_HPP
#define PERM_HPP

#include "perm_common_types.hpp"
#include <cstddef> // For size_t
#include <functional>
#include <ostream>

namespace perm {
struct parameters_in_t {
size_t steps = 1000;
size_t monomers = 100;
/// Used only if num_monomers = 0
float_t end_to_end_distance = 0.0;
void print(std::ostream &os) const;
};

struct parameters_out_t {
parameters_out_t() = default;
parameters_out_t(const parameters_in_t &input) : in(input){};
single_chain_t<int> chain;
parameters_in_t in;
float_t energy = 0.0;
void print(std::ostream &os) const;
};

void hola();
single_chain_t<int> random_walk_lattice_2D(const size_t &monomers);
parameters_out_t run_simple_sampling(const parameters_in_t &parameters);
float_t
energy(const single_chain_t<int> &chain,
const std::function<float_t(const vec3D_t<int> &, const vec3D_t<int> &)>
&energy_pair_func);

} //end ns
} // namespace perm
#endif
61 changes: 61 additions & 0 deletions include/perm_common_types.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/* Copyright (C) 2019 Pablo Hernandez-Cerdan
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef PERM_COMMON_TYPES_HPP
#define PERM_COMMON_TYPES_HPP
#include <iostream>
#include <vector>

namespace perm {
/// float type (hard-coded better than templated for now)
using float_t = double;

template <typename T>
struct vec3D_t {
T x;
T y;
T z;
void print(std::ostream &os) const {
os << x << " " << y << " " << z << std::endl;
}
friend bool operator==(const vec3D_t<T> &lhs, const vec3D_t<T> &rhs) {
return lhs.x == lhs.x && lhs.y == lhs.y && lhs.z == lhs.z;
}
T &operator[](const size_t index) {
return (index == 0 ? x : (index == 1 ? y : z));
}
const T &operator[](const size_t index) const {
return (index == 0 ? x : (index == 1 ? y : z));
}
constexpr size_t size() { return 3; };
};

template <typename T>
vec3D_t<T> plus(const vec3D_t<T> &lhs, const vec3D_t<T> &rhs) {
vec3D_t<T> out;
out.x = lhs.x + rhs.x;
out.y = lhs.y + rhs.y;
out.z = lhs.z + rhs.z;
return out;
}

template <typename T>
struct single_chain_t {
/// Number of monomers in the single-chain polymer
size_t monomers = 0;
/** Ordered collection of points,
* start: points[0],
* end: points[num_monomers - 1]
*/
std::vector<vec3D_t<T>> points;
void print(std::ostream &os) const {
os << "chain.monomers= " << monomers << std::endl;
for (const auto &p : points) {
p.print(os);
}
}
};
} // namespace perm
#endif
78 changes: 78 additions & 0 deletions include/perm_rng.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/* Copyright (C) 2019 Pablo Hernandez-Cerdan
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef PERM_RNG_HPP
#define PERM_RNG_HPP

#include "perm_common_types.hpp"
#include <random>
namespace RNG {

inline std::mt19937 &engine() {
/// seed generation
static thread_local std::random_device rdev{};
/// engine instantiation: e
static thread_local std::mt19937 e{rdev()};
// static thread_local std::mt19937 e{4342};
return e;
}

/// Randomize reseed the input engine with a random generate seed.
inline void randomize_engine(std::mt19937 &eng) {
std::random_device rd{};
eng.seed(rd());
}

/// Uniform random distribution from double [0.0,1)
inline double rand01() {
static thread_local std::uniform_real_distribution<double> uid(0.0, 1.0);
return uid(engine());
}

/**
* Return 1 with probability p
* @param p must be lesser or equal than 1
* @return 1 with probability p, 0 if not.
*/
inline bool random_bool(const double p) { return (rand01() < p) ? 1 : 0; }

/**
* Uniform random distribution from int [min,max]
* @param min
* @param max
* @return int from [min,max]
*/
inline int rand_range_int(const int &min, const int &max) {
// note that inside function static variables doesn't interfer if they have
// the same name
std::uniform_int_distribution<int> uid(min, max);
return uid(engine());
}

inline perm::vec3D_t<int> rand_lattice_2D() {
// note that inside function static variables doesn't interfer if they have
// the same name
std::uniform_int_distribution<int> uid(0, 3);
const auto lattice_int = uid(engine());
switch (lattice_int) {
case 0 /* -x */:
return perm::vec3D_t<int>{-1, 0, 0};
break;
case 1 /* +x */:
return perm::vec3D_t<int>{1, 0, 0};
break;
case 2 /* -y */:
return perm::vec3D_t<int>{0, -1, 0};
break;
case 3 /* +y */:
return perm::vec3D_t<int>{0, 1, 0};
break;
}
// Not really needed, unreachable, but warnings if removed in gcc
return perm::vec3D_t<int>{999, 999, 999};
}
} // namespace RNG

#endif
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"]
57 changes: 57 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from __future__ import print_function
from os import sys, path

try:
from skbuild import setup
except ImportError:
print('scikit-build is required to build from source.', file=sys.stderr)
print('Please run:', file=sys.stderr)
print('', file=sys.stderr)
print(' python -m pip install scikit-build')
sys.exit(1)

sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

with open('README.md', 'r') as fp:
readme = fp.read()
with open('developer_requirements.txt', 'r') as fp:
developer_requirements = list(filter(bool, (line.strip() for line in fp)))

setup(
name='perm',
version='0.1',
author='Pablo Hernandez-Cerdan',
author_email='[email protected]',
packages=['perm'],
download_url=r'https://github.com/phcerdan/perm/releases',
description=r'PERM: Prune and Enrichment Rosenbluth Method',
long_description=readme,
classifiers=[
"OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Programming Language :: Python",
"Programming Language :: C++",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Software Development :: Libraries",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Operating System :: Unix",
"Operating System :: MacOS"
],
license='MPL2',
keywords='PERM montecarlo SAW polymer simulation',
url=r'https://github.com/phcerdan/perm',
install_requires=[],
cmake_args=[
'-DBUILD_SHARED_LIBS:BOOL=TRUE',
'-DPERM_BUILD_TESTING:BOOL=FALSE',
'-DPERM_WRAP_PYTHON:BOOL=TRUE',
# '-DCMAKE_BUILD_TYPE:STRING=Release',
]
)

4 changes: 2 additions & 2 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
set(PERMCore_sources
perm.cpp
perm_common_types.cpp
)

add_library(PERMCore ${PERMCore_sources} )
target_include_directories(PERMCore PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
target_link_libraries(PERMCore
)
set_property(TARGET PERMCore PROPERTY POSITION_INDEPENDENT_CODE ON)
# install targets
install(TARGETS PERMCore
EXPORT PERMTargets
Expand Down
55 changes: 46 additions & 9 deletions src/perm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,58 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */


#include "perm.hpp"
#include "perm_rng.hpp"
#include <iostream>

namespace perm {
using precision_t = float;

struct parameters {
size_t steps = 1000;
size_t num_monomers = 100;
/// Used only if num_monomers = 0
precision_t end_to_end_distance = 0.0;
void parameters_in_t::print(std::ostream &os) const {
os << "steps= " << steps << std::endl;
os << "monomers= " << monomers << std::endl;
os << "end_to_end_distance= " << end_to_end_distance << std::endl;
}

void parameters_out_t::print(std::ostream &os) const {
in.print(os);
os << "energy= " << energy << std::endl;
chain.print(os);
}

parameters_out_t run_simple_sampling(const parameters_in_t &parameters_in) {
parameters_out_t parameters_out(parameters_in);
auto &chain = parameters_out.chain;
chain.points.emplace_back(vec3D_t<int>{0, 0, 0});
chain.monomers++;
return parameters_out;
}

single_chain_t<int> random_walk_lattice_2D(const size_t &monomers) {
single_chain_t<int> chain;
chain.points.emplace_back(vec3D_t<int>{0, 0, 0});
chain.monomers++;
while (chain.monomers < monomers) {
chain.points.emplace_back(
perm::plus(chain.points.back(), RNG::rand_lattice_2D()));
chain.monomers++;
}
return chain;
}

float_t
energy(const single_chain_t<int> &chain,
const std::function<float_t(const vec3D_t<int> &, const vec3D_t<int> &)>
&energy_pair_func) {

if (chain.monomers == 0 || chain.points.empty()) {
return 0.0;
}

void hola() {
std::cout << "HOLA" << std::endl;
auto &points = chain.points;
double sum = 0.0;
for (size_t i = 0; i != points.size() - 1; i++) {
sum += energy_pair_func(points[i], points[i + 1]);
}
return sum;
}
} // namespace perm
8 changes: 8 additions & 0 deletions src/perm_common_types.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/* Copyright (C) 2019 Pablo Hernandez-Cerdan
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "perm_common_types.hpp"

namespace perm {} // end namespace perm
4 changes: 4 additions & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
set(test_files
test_perm.cpp
)
perm_add_gtests()
Loading

0 comments on commit 8add968

Please sign in to comment.