diff --git a/.gitignore b/.gitignore index e6837a8..c78aded 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ polychrom/_polymer_math.cpp dist polychrom/*.so .vscode +polychrom/_native_engine.cpp +polychrom/_native_engine_x86_64_v3.cpp diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..b115f16 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,4 @@ +include polychrom/_native/engine.hpp +include polychrom/*.pyx +include polychrom/__polymer_math.cpp +include polychrom/__polymer_math.h diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp new file mode 100644 index 0000000..ed9ae27 --- /dev/null +++ b/polychrom/_native/engine.hpp @@ -0,0 +1,1707 @@ +// Native CPU engine for polychrom. +// +// A small, specialised molecular dynamics engine for coarse-grained polymer +// models, used by ``Simulation(platform="native")``. It reproduces the subset +// of OpenMM that polychrom uses (harmonic and tabulated bonds, tabulated +// angles, tabulated short-range pair potentials with exclusions, spherical +// confinement, tethers, and OpenMM's Langevin-type integrators) with data +// structures tuned for polymer systems on multi-core CPUs: +// +// * one OpenMP parallel region per ``step(n)`` call; the phases of a time step +// are work-sharing loops separated by barriers, not separate fork/joins; +// * Verlet neighbour lists with a skin. Entries are packed into 32 bits +// (particle index and periodic image code), so the inner loop needs no +// rounding. Particles that have moved more than half the skin since the +// last build (the "fast set", e.g. beads pulled by a freshly placed loop +// extrusion bond) get their interactions from a direct search every step; +// lists are rebuilt only when the fast set grows beyond max(64, N/32); +// * list builds from cell-ordered coordinates: the candidates of a cell are +// copied into one buffer and filtered four at a time (AVX2), dropping +// chain-neighbour exclusions in the same pass; +// * full (i, j and j, i) neighbour lists, so pair forces are accumulated by the +// owning thread without atomics or per-thread force buffers; +// * bonded terms evaluated into a contribution buffer (one vector per bond, +// two per angle) and gathered per particle through a CSR index, in chunks +// of particles, so that the buffer stays in the cache; +// * few passes over the per-particle arrays per step, and no per-particle or +// per-term loads of parameters that are the same for all; +// * a counter-based Ziggurat Gaussian generator keyed by (seed, step, +// coordinate). +// +// Forces and trajectories therefore do not depend on the number of threads +// (only the summation order of the reported potential energy does). The +// generic and the x86-64-v3 (AVX2) build give the same results. +// +// Units follow OpenMM: nm, ps, amu, kJ/mol, K. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif +#ifdef __AVX2__ +#include +#endif + +namespace pcn { + +// Same value as OpenMM's BOLTZ (kJ/mol/K). +constexpr double BOLTZ = 0.0083144626181532395; + +// Whether this CPU (and OS) supports the instructions of the x86-64-v3 build of +// the engine (AVX2, FMA, BMI2). Both builds use -ffp-contract=off, so they +// produce the same results. +static inline bool cpu_has_x86_64_v3() { +#if (defined(__x86_64__) || defined(_M_X64)) && (defined(__GNUC__) || defined(__clang__)) + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && __builtin_cpu_supports("bmi2"); +#else + return false; +#endif +} + +static inline int thread_id() { +#ifdef _OPENMP + return omp_get_thread_num(); +#else + return 0; +#endif +} +static inline int team_size() { +#ifdef _OPENMP + return omp_get_num_threads(); +#else + return 1; +#endif +} + +// Round to nearest without a libm call (valid for |t| < 2^51). +static inline double round_fast(double t) { + const double M = 6755399441055744.0; // 2^52 + 2^51 + return (t + M) - M; +} + +// --------------------------------------------------------------------------- +// Cubic Hermite table of a function of one variable (value and derivative at +// uniformly spaced knots), stored as per-interval polynomial coefficients in +// t = (x - x_k) / h. Outside [x0, x1] the function is extrapolated linearly. +// --------------------------------------------------------------------------- +struct Table { + double x0 = 0, x1 = 0, h = 1, inv_h = 1; + int n = 0; // number of intervals + std::vector c; + double e_lo = 0, d_lo = 0, e_hi = 0, d_hi = 0; + + void build(double x0_, double x1_, int nknots, const double* E, const double* D) { + if (nknots < 2 || !(x1_ > x0_)) throw std::invalid_argument("Table: need >= 2 knots and x1 > x0"); + for (int k = 0; k < nknots; ++k) + if (!std::isfinite(E[k]) || !std::isfinite(D[k])) throw std::invalid_argument("Table: non-finite value"); + x0 = x0_; + x1 = x1_; + n = nknots - 1; + h = (x1 - x0) / n; + inv_h = 1.0 / h; + c.assign(4 * (size_t)n, 0.0); + for (int k = 0; k < n; ++k) { + const double e0 = E[k], e1 = E[k + 1], m0 = D[k] * h, m1 = D[k + 1] * h; + c[4 * k + 0] = e0; + c[4 * k + 1] = m0; + c[4 * k + 2] = -3 * e0 - 2 * m0 + 3 * e1 - m1; + c[4 * k + 3] = 2 * e0 + m0 - 2 * e1 + m1; + } + e_lo = E[0]; + d_lo = D[0]; + e_hi = E[nknots - 1]; + d_hi = D[nknots - 1]; + } + + // For pair tables on [0, x1]: no range checks, x must be in [0, x1]. + inline void eval_in_range(double x, double& e, double& de) const { + const double u = (x - x0) * inv_h; + int k = (int)u; + k = k < n ? k : n - 1; + const double t = u - k; + const double* p = &c[4 * (size_t)k]; + e = p[0] + t * (p[1] + t * (p[2] + t * p[3])); + de = (p[1] + t * (2.0 * p[2] + t * 3.0 * p[3])) * inv_h; + } + + inline void eval(double x, double& e, double& de) const { + const double u = (x - x0) * inv_h; + if (u < 0.0) { + de = d_lo; + e = e_lo + d_lo * (x - x0); + return; + } + const int k = (int)u; + if (k >= n) { + de = d_hi; + e = e_hi + d_hi * (x - x1); + return; + } + const double t = u - k; + const double* p = &c[4 * (size_t)k]; + e = p[0] + t * (p[1] + t * (p[2] + t * p[3])); + de = (p[1] + t * (2.0 * p[2] + t * 3.0 * p[3])) * inv_h; + } +}; + +// --------------------------------------------------------------------------- +// Random numbers: splitmix64 finaliser as a counter-based hash, and the +// Marsaglia-Tsang (2000) Ziggurat for normal deviates (128 layers). Layer +// index and value come from disjoint bits of one 64-bit draw. +// --------------------------------------------------------------------------- +static inline uint64_t mix64(uint64_t z) { + z += 0x9E3779B97F4A7C15ull; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +static inline double u01(uint64_t r) { // (0, 1] + return ((r >> 11) + 1) * (1.0 / 9007199254740992.0); +} + +struct ZigguratTables { + uint32_t kn[128]; + double wn[128], fn[128]; + ZigguratTables() { + const double m1 = 2147483648.0; + double dn = 3.442619855899, tn = dn; + const double vn = 9.91256303526217e-3; + const double q = vn / std::exp(-.5 * dn * dn); + kn[0] = (uint32_t)((dn / q) * m1); + kn[1] = 0; + wn[0] = q / m1; + wn[127] = dn / m1; + fn[0] = 1.; + fn[127] = std::exp(-.5 * dn * dn); + for (int i = 126; i >= 1; i--) { + dn = std::sqrt(-2. * std::log(vn / dn + std::exp(-.5 * dn * dn))); + kn[i + 1] = (uint32_t)((dn / tn) * m1); + tn = dn; + fn[i] = std::exp(-.5 * dn * dn); + wn[i] = dn / m1; + } + } +}; + +static inline const ZigguratTables& zig() { + static const ZigguratTables t; + return t; +} + +// Rest of znormal after the draw r (from state st) was not accepted by the +// fast test (about 1 % of the draws); kept out of line, so that the callers' +// loops stay small. +#if defined(__GNUC__) || defined(__clang__) +__attribute__((noinline, cold)) +#endif +static double znormal_slow(uint64_t st, uint64_t r) { + const ZigguratTables& Z = zig(); + for (;;) { + const int iz = (int)(r & 127); + const int32_t hz = (int32_t)(uint32_t)(r >> 32); + const uint32_t ahz = hz < 0 ? (uint32_t)(-(int64_t)hz) : (uint32_t)hz; + if (ahz < Z.kn[iz]) return hz * Z.wn[iz]; + if (iz == 0) { // tail beyond R + const double R = 3.442619855899; + double xx, yy; + do { + st += 0x9E3779B97F4A7C15ull; + xx = -std::log(u01(mix64(st))) / R; + st += 0x9E3779B97F4A7C15ull; + yy = -std::log(u01(mix64(st))); + } while (yy + yy < xx * xx); + return hz > 0 ? R + xx : -R - xx; + } + const double xx = hz * Z.wn[iz]; + st += 0x9E3779B97F4A7C15ull; + if (Z.fn[iz] + u01(mix64(st)) * (Z.fn[iz - 1] - Z.fn[iz]) < std::exp(-.5 * xx * xx)) return xx; + st += 0x9E3779B97F4A7C15ull; + r = mix64(st); + } +} + +// Standard normal deviate from the stream that starts at state `st`. +static inline double znormal(uint64_t st) { + const ZigguratTables& Z = zig(); + st += 0x9E3779B97F4A7C15ull; + const uint64_t r = mix64(st); + const int iz = (int)(r & 127); + const int32_t hz = (int32_t)(uint32_t)(r >> 32); + const uint32_t ahz = hz < 0 ? (uint32_t)(-(int64_t)hz) : (uint32_t)hz; + if (ahz < Z.kn[iz]) return hz * Z.wn[iz]; + return znormal_slow(st, r); +} + +// --------------------------------------------------------------------------- +// Force terms +// --------------------------------------------------------------------------- +struct BondSet { // harmonic (k, r0) or tabulated E(r) + bool tabulated = false; + bool pbc = false; + std::vector i, j; + std::vector r0, k; // harmonic + bool uniform = false; // harmonic with the same r0 and k for all bonds (not loaded per bond) + std::vector tab; // tabulated: index into tables + std::vector tables; + size_t contrib_offset = 0; + // processing order: terms order[chunk_off[k], chunk_off[k + 1]) have their lowest + // particle in chunk k (order is the identity if in_order) + std::vector order, chunk_off; + bool in_order = true; +}; + +struct AngleTable { + Table t; // E(theta), theta in [0, pi] + Table tc; // E(cos theta), cos theta in [c_lo, c_hi]; used there (avoids atan2) + double c_lo = 2, c_hi = -2; +}; + +struct AngleSet { + bool pbc = false; + std::vector i, j, k, tab; + int tab_all = -1; // table of all angles if they share one (tab not loaded per angle), else -1 + std::vector tables; + size_t contrib_offset = 0; + std::vector order, chunk_off; // as in BondSet + bool in_order = true; +}; + +constexpr int NB_SHIFT_BITS = 27; +constexpr uint32_t NB_INDEX_MASK = (1u << NB_SHIFT_BITS) - 1; +constexpr int MAX_PARTICLES = 1 << NB_SHIFT_BITS; + +struct PairForce { + double cutoff = 1.0, skin = 0.3; + int ntypes = 1; + std::vector type; // per particle + std::vector
tables; // ntypes * ntypes + std::vector excl_start, excl; // CSR of sorted exclusions, symmetric + // Verlet list (full), entries = index | image_code << 27 + std::vector nb_start; + std::vector nb; + bool need_rebuild = true; + long n_builds = 0; +}; + +struct SphericalConfinement { // polychrom.forces.spherical_confinement + std::vector particles; + double kb, aa, t, tt, sign, cx, cy, cz; +}; + +struct Tether { // polychrom.forces.tether_particles: kx (x-x0)^2 + ky (y-y0)^2 + kz (z-z0)^2 + std::vector particles; + std::vector x0; // 3 per particle + double k[3] = {0, 0, 0}; + bool pbc = false; +}; + +// LANGEVIN is LANGEVIN_MIDDLE: in OpenMM 8, LangevinIntegrator subclasses LangevinMiddleIntegrator. +enum IntegratorType { LANGEVIN = 0, LANGEVIN_MIDDLE = 1, VARIABLE_LANGEVIN = 2, BROWNIAN = 3 }; + +// --------------------------------------------------------------------------- +// Engine +// --------------------------------------------------------------------------- +class Engine { + public: + explicit Engine(int N_) : N(N_) { + if (N <= 0) throw std::invalid_argument("Engine: N must be positive"); + if (N >= MAX_PARTICLES) throw std::invalid_argument("Engine: too many particles"); + x.assign(3 * (size_t)N, 0.0); + v.assign(3 * (size_t)N, 0.0); + f.assign(3 * (size_t)N, 0.0); + x_ref.assign(3 * (size_t)N, 0.0); + xw.assign(3 * (size_t)N, 0.0); + img.assign(3 * (size_t)N, 0); + mass.assign(N, 100.0); + inv_mass.assign(N, 0.01); + uniform_sqrt_inv_mass = std::sqrt(inv_mass[0]); + (void)zig(); + } + + // ---- configuration --------------------------------------------------- + void set_threads(int n) { +#ifdef _OPENMP + if (n > 0) omp_set_num_threads(n); +#endif + (void)n; + } + int get_threads() const { +#ifdef _OPENMP + return omp_get_max_threads(); +#else + return 1; +#endif + } + + void set_masses(const double* m) { + bool uniform = true; + for (int p = 0; p < N; ++p) { + mass[p] = m[p]; + inv_mass[p] = m[p] > 0 ? 1.0 / m[p] : 0.0; + uniform = uniform && inv_mass[p] == inv_mass[0]; + } + mass_uniform = uniform; + uniform_sqrt_inv_mass = uniform && inv_mass[0] > 0 ? std::sqrt(inv_mass[0]) : 0.0; + invalidate(); + } + + void set_box(bool use_pbc, double lx, double ly, double lz) { + if (use_pbc && !(lx > 0 && ly > 0 && lz > 0)) throw std::invalid_argument("box sizes must be positive"); + pbc = use_pbc; + box[0] = lx; + box[1] = ly; + box[2] = lz; + invalidate(); + } + + void set_positions(const double* p) { + for (size_t c = 0; c < 3 * (size_t)N; ++c) + if (!std::isfinite(p[c])) throw std::invalid_argument("non-finite position"); + std::copy(p, p + 3 * (size_t)N, x.begin()); + invalidate(); + } + void get_positions(double* p) const { std::copy(x.begin(), x.end(), p); } + void set_velocities(const double* p) { std::copy(p, p + 3 * (size_t)N, v.begin()); } + void get_velocities(double* p) const { std::copy(v.begin(), v.end(), p); } + void get_forces(double* p) { + compute(); + std::copy(f.begin(), f.end(), p); + } + + void set_velocities_to_temperature(double T_, uint64_t seed_) { + const double kT = BOLTZ * T_; + const uint64_t base = mix64(seed_ ^ 0xD1B54A32D192ED03ull); + for (int p = 0; p < N; ++p) { + const double s = std::sqrt(kT * inv_mass[p]); + for (int d = 0; d < 3; ++d) v[3 * p + d] = s * znormal(mix64(base ^ (uint64_t)(3 * p + d))); + } + } + + // Bonds ----------------------------------------------------------------- + int add_bond_set(bool tabulated, bool use_pbc) { + BondSet b; + b.tabulated = tabulated; + b.pbc = use_pbc; + bonds.push_back(std::move(b)); + topology_dirty = true; + invalidate(); + return (int)bonds.size() - 1; + } + void set_harmonic_bonds(int s, int n, const int* i, const int* j, const double* r0, const double* k) { + BondSet& b = bonds.at(s); + if (b.tabulated) throw std::invalid_argument("bond set is tabulated"); + if (n != (int)b.i.size() || !std::equal(i, i + n, b.i.begin()) || !std::equal(j, j + n, b.j.begin())) { + check_indices(n, i); + check_indices(n, j); + b.i.assign(i, i + n); + b.j.assign(j, j + n); + topology_dirty = true; + } + b.r0.assign(r0, r0 + n); + b.k.assign(k, k + n); + b.uniform = n > 0 && std::all_of(r0, r0 + n, [&](double v) { return v == r0[0]; }) && + std::all_of(k, k + n, [&](double v) { return v == k[0]; }); + invalidate(); + } + int add_bond_table(int s, double x0, double x1, int nknots, const double* E, const double* D) { + BondSet& b = bonds.at(s); + b.tables.emplace_back(); + b.tables.back().build(x0, x1, nknots, E, D); + invalidate(); + return (int)b.tables.size() - 1; + } + void set_tabulated_bonds(int s, int n, const int* i, const int* j, const int* tab) { + BondSet& b = bonds.at(s); + if (!b.tabulated) throw std::invalid_argument("bond set is harmonic"); + check_indices(n, i); + check_indices(n, j); + for (int q = 0; q < n; ++q) + if (tab[q] < 0 || tab[q] >= (int)b.tables.size()) throw std::out_of_range("bond table index"); + b.i.assign(i, i + n); + b.j.assign(j, j + n); + b.tab.assign(tab, tab + n); + topology_dirty = true; + invalidate(); + } + void clear_bond_tables(int s) { + bonds.at(s).tables.clear(); + invalidate(); + } + + // Angles ---------------------------------------------------------------- + int add_angle_set(bool use_pbc) { + AngleSet a; + a.pbc = use_pbc; + angles.push_back(std::move(a)); + topology_dirty = true; + invalidate(); + return (int)angles.size() - 1; + } + // Et, Dt: E and dE/dtheta on uniform knots in [0, pi]. Ec, Dc: E and dE/dcos + // on uniform knots in [c_lo, c_hi] (empty if nc == 0), used for cos(theta) in + // that range. + int add_angle_table(int s, int nt, const double* Et, const double* Dt, double c_lo, double c_hi, int nc, + const double* Ec, const double* Dc) { + AngleSet& a = angles.at(s); + AngleTable at; + at.t.build(0.0, M_PI, nt, Et, Dt); + if (nc > 0) { + if (!(c_lo >= -1.0 && c_hi <= 1.0 && c_hi > c_lo)) throw std::invalid_argument("bad cos range"); + at.tc.build(c_lo, c_hi, nc, Ec, Dc); + at.c_lo = c_lo; + at.c_hi = c_hi; + } + a.tables.push_back(std::move(at)); + invalidate(); + return (int)a.tables.size() - 1; + } + void set_angles(int s, int n, const int* i, const int* j, const int* k, const int* tab) { + AngleSet& a = angles.at(s); + check_indices(n, i); + check_indices(n, j); + check_indices(n, k); + for (int q = 0; q < n; ++q) + if (tab[q] < 0 || tab[q] >= (int)a.tables.size()) throw std::out_of_range("angle table index"); + a.i.assign(i, i + n); + a.j.assign(j, j + n); + a.k.assign(k, k + n); + a.tab.assign(tab, tab + n); + a.tab_all = n > 0 && std::all_of(tab, tab + n, [&](int t) { return t == tab[0]; }) ? tab[0] : -1; + topology_dirty = true; + invalidate(); + } + void clear_angle_tables(int s) { + angles.at(s).tables.clear(); + invalidate(); + } + + // Pair potentials --------------------------------------------------------- + int add_pair_force(double cutoff, double skin, int ntypes, const int* type) { + if (!(cutoff > 0)) throw std::invalid_argument("cutoff must be positive"); + if (ntypes < 1) throw std::invalid_argument("ntypes must be >= 1"); + PairForce pf; + pf.cutoff = cutoff; + pf.skin = std::max(0.0, skin); + pf.ntypes = ntypes; + pf.type.assign(type, type + N); + for (int t : pf.type) + if (t < 0 || t >= ntypes) throw std::out_of_range("particle type"); + pf.tables.resize((size_t)ntypes * ntypes); + pf.excl_start.assign(N + 1, 0); + pairs.push_back(std::move(pf)); + invalidate(); + return (int)pairs.size() - 1; + } + void set_pair_table(int s, int ta, int tb, double x0, double x1, int nknots, const double* E, const double* D) { + PairForce& pf = pairs.at(s); + if (ta < 0 || tb < 0 || ta >= pf.ntypes || tb >= pf.ntypes) throw std::out_of_range("pair type"); + pf.tables[(size_t)ta * pf.ntypes + tb].build(x0, x1, nknots, E, D); + invalidate(); + } + void set_pair_skin(int s, double skin) { + pairs.at(s).skin = std::max(0.0, skin); + invalidate(); + } + void set_pair_exclusions(int s, int n, const int* i, const int* j) { + PairForce& pf = pairs.at(s); + check_indices(n, i); + check_indices(n, j); + std::vector cnt(N + 1, 0); + for (int q = 0; q < n; ++q) { + if (i[q] == j[q]) continue; + cnt[i[q] + 1]++; + cnt[j[q] + 1]++; + } + for (int p = 0; p < N; ++p) cnt[p + 1] += cnt[p]; + pf.excl_start = cnt; + pf.excl.assign(cnt[N], 0); + std::vector fill(cnt.begin(), cnt.end() - 1); + for (int q = 0; q < n; ++q) { + if (i[q] == j[q]) continue; + pf.excl[fill[i[q]]++] = j[q]; + pf.excl[fill[j[q]]++] = i[q]; + } + for (int p = 0; p < N; ++p) { + auto b = pf.excl.begin() + pf.excl_start[p], e = pf.excl.begin() + pf.excl_start[p + 1]; + std::sort(b, e); + } + invalidate(); + } + long get_pair_builds(int s) const { return pairs.at(s).n_builds; } + long get_pair_list_size(int s) const { return (long)pairs.at(s).nb.size(); } + int get_fast_count() const { return nfast; } + void get_fast_particles(int* out) const { std::copy(fast_list.begin(), fast_list.end(), out); } + + // External forces --------------------------------------------------------- + int add_spherical_confinement(int n, const int* particles, double kb, double aa, double t, double tt, + double sign, double cx, double cy, double cz) { + check_indices(n, particles); + SphericalConfinement sc{std::vector(particles, particles + n), kb, aa, t, tt, sign, cx, cy, cz}; + spheres.push_back(std::move(sc)); + invalidate(); + return (int)spheres.size() - 1; + } + void set_spherical_confinement(int s, double kb, double aa, double t, double tt, double sign, double cx, + double cy, double cz) { + SphericalConfinement& sc = spheres.at(s); + sc.kb = kb; + sc.aa = aa; + sc.t = t; + sc.tt = tt; + sc.sign = sign; + sc.cx = cx; + sc.cy = cy; + sc.cz = cz; + invalidate(); + } + int add_tether(int n, const int* particles, const double* x0, double kx, double ky, double kz, bool use_pbc) { + check_indices(n, particles); + Tether t; + t.particles.assign(particles, particles + n); + t.x0.assign(x0, x0 + 3 * (size_t)n); + t.k[0] = kx; + t.k[1] = ky; + t.k[2] = kz; + t.pbc = use_pbc; + tethers.push_back(std::move(t)); + invalidate(); + return (int)tethers.size() - 1; + } + void set_tether_k(int s, double kx, double ky, double kz) { + Tether& t = tethers.at(s); + t.k[0] = kx; + t.k[1] = ky; + t.k[2] = kz; + invalidate(); + } + + // Integrator ---------------------------------------------------------------- + void set_integrator(int type, double temperature, double friction, double dt, double error_tol) { + if (type < LANGEVIN || type > BROWNIAN) throw std::invalid_argument("unknown integrator type"); + if (type == BROWNIAN && !(friction > 0)) throw std::invalid_argument("Brownian dynamics needs friction > 0"); + integrator = (IntegratorType)type; + T = temperature; + gamma = friction; + error_tol_ = error_tol; + if (integrator == VARIABLE_LANGEVIN) { + if (!(error_tol > 0)) throw std::invalid_argument("error tolerance must be positive"); + dt_ = 0.0; + } else { + if (!(dt > 0)) throw std::invalid_argument("step size must be positive"); + dt_ = dt; + } + } + void set_temperature(double t) { T = t; } + void set_friction(double g) { gamma = g; } + void set_step_size(double dt) { dt_ = dt; } + double get_step_size() const { return dt_; } + void set_error_tolerance(double e) { error_tol_ = e; } + void set_max_step_size(double m) { max_dt = m > 0 ? m : std::numeric_limits::infinity(); } + void set_seed(uint64_t s) { seed = s; } + double get_time() const { return time_; } + void set_time(double t) { time_ = t; } + long long get_step_count() const { return nsteps; } + + double potential_energy() { + compute(); + return epot; + } + + // Kinetic energy as reported by OpenMM's Reference platform + // (computeShiftedKineticEnergy): VariableLangevin shifts the velocities by + // half a step, LangevinMiddle (= Langevin) and Brownian do not. + double kinetic_energy() { + double shift = 0.0; + if (integrator == VARIABLE_LANGEVIN) shift = 0.5 * dt_; + if (shift != 0.0) compute(); + double ek = 0.0; +#pragma omp parallel for schedule(static) reduction(+ : ek) + for (int p = 0; p < N; ++p) { + double s = 0; + for (int d = 0; d < 3; ++d) { + const double vv = v[3 * p + d] + shift * f[3 * p + d] * inv_mass[p]; + s += vv * vv; + } + ek += 0.5 * mass[p] * s; + } + return ek; + } + + void compute() { + if (forces_valid) return; + prepare(); + stepping = false; +#pragma omp parallel + forces_inner(); + check_error(); + } + + void step(int n) { + if (n <= 0) return; + prepare(); + stepping = true; + dt_selected = false; +#pragma omp parallel + { + for (int s = 0; s < n; ++s) { + forces_inner(); + integrate_inner(); + if (error_flag.load(std::memory_order_relaxed)) break; // same value on all threads after barrier + } + } + stepping = false; + check_error(); + } + + private: + int N; + bool pbc = false; + double box[3] = {0, 0, 0}; + std::vector x, v, f, mass, inv_mass; + bool mass_uniform = true; // all masses equal: inv_mass[0] is used, not loaded per particle + double uniform_sqrt_inv_mass = 0.0; // sqrt(1 / mass) if all masses are equal, else 0 + std::vector x_ref; // positions at the last neighbour-list build + std::vector img; // periodic image at the last build: offset img * box (PBC only) + std::vector xw; // x - img * box (PBC only), updated by the integrator + + std::vector bonds; + std::vector angles; + std::vector pairs; + std::vector spheres; + std::vector tethers; + + bool topology_dirty = true; + std::vector contrib; + std::vector gather_start; + std::vector gather_idx; + std::vector chunk_reach; // lowest chunk holding the lowest particle of a term that reaches chunk k + // gather_idx kinds: add vector v, subtract it, or subtract v and the next vector + static constexpr uint32_t GATHER_PLUS = 0, GATHER_MINUS = 1, GATHER_MINUS_PAIR = 2; + + bool forces_valid = false; + double epot = 0.0; + bool rebuild_all = true; + // Fast set: particles that moved more than half the skin since the last build. + std::vector fast; // per particle + std::vector fast_list; + std::vector> fast_binned; // (current cell, particle), sorted + int nfast = 0; + double fast_lim2 = 0.0; // (skin / 2)^2 + int fast_max = 64; + struct Contribution { + int q; + double fx, fy, fz; + }; + struct FastSpan { // contributions of fast_list[a]: thr_scratch[tid].contrib[start, start + count) + int tid; + size_t start, count; + }; + std::vector fast_span; + + IntegratorType integrator = LANGEVIN_MIDDLE; + double T = 300.0, gamma = 1.0, dt_ = 0.001, error_tol_ = 0.01; + double max_dt = std::numeric_limits::infinity(); + double vl_err = 0.0; // variable Langevin: sum of (f/m)^2 over all coordinates + bool stepping = false; // inside step(): select the step size together with the forces + bool dt_selected = false; // step size of the current step already selected + double time_ = 0.0; + long long nsteps = 0; + uint64_t seed = 1; + + // per-thread scratch (padded against false sharing) + static constexpr int PAD = 8; + std::vector thr; + // per-block partial sums over particles (independent of the number of threads) + static constexpr int SUM_BLOCK = 64; + std::vector block_sum; + struct ThreadScratch { + std::vector bx, by, bz; // candidate buffer of the current cell (capacity, not length) + std::vector be; + std::vector ent; // list entries found by this thread (capacity, not length) + std::vector> seg; // (particle, offset in ent) + std::vector fast; // fast particles found by this thread + std::vector contrib; // forces on other particles from the fast set + }; + std::vector thr_scratch; + + // neighbour-list scratch + std::vector cell_of, cell_start, cell_list, nb_count, fill, occupied; + std::vector sorted_xyz; // wrapped coordinates in cell_list order: x[N], y[N], z[N] + double shifts[27][3]; + double grid_lo[3], grid_edge[3]; + int grid_nc[3] = {1, 1, 1}; + + std::atomic error_flag{0}; + std::string error_msg; + + void check_indices(int n, const int* idx) const { + for (int q = 0; q < n; ++q) + if (idx[q] < 0 || idx[q] >= N) throw std::out_of_range("particle index out of range"); + } + + void invalidate() { + forces_valid = false; + for (auto& pf : pairs) pf.need_rebuild = true; + } + + void set_error(const char* msg) { + int expected = 0; + if (error_flag.compare_exchange_strong(expected, 1)) error_msg = msg; + } + void check_error() { + if (error_flag.load()) { + error_flag = 0; + forces_valid = false; + throw std::runtime_error(error_msg); + } + } + + inline void min_image(double& dx, double& dy, double& dz) const { + dx -= box[0] * round_fast(dx / box[0]); + dy -= box[1] * round_fast(dy / box[1]); + dz -= box[2] * round_fast(dz / box[2]); + } + + // Serial preparation before entering a parallel region. + void prepare() { + if (topology_dirty) rebuild_topology(); + int nt = get_threads(); + thr.assign((size_t)PAD * (nt + 1), 0.0); + thr_scratch.resize(nt); + block_sum.assign((N + SUM_BLOCK - 1) / SUM_BLOCK, 0.0); + if (pbc) + for (auto& pf : pairs) { + const double lmin = std::min(box[0], std::min(box[1], box[2])); + if (!(pf.cutoff < 0.5 * lmin)) + throw std::invalid_argument("cutoff must be smaller than half the periodic box"); + if (pf.cutoff + pf.skin >= 0.5 * lmin) pf.skin = std::max(0.0, 0.499 * lmin - pf.cutoff); + } + if ((int)fast.size() != N) { + fast.assign(N, 0); + fast_list.clear(); + nfast = 0; + for (auto& pf : pairs) pf.need_rebuild = true; + } + double smin = std::numeric_limits::infinity(); + for (auto& pf : pairs) smin = std::min(smin, pf.skin); + fast_lim2 = pairs.empty() ? std::numeric_limits::infinity() : 0.25 * smin * smin; + fast_max = std::max(64, N / 32); + for (int a = 0; a < 27; ++a) { + const int sx = a / 9 - 1, sy = (a / 3) % 3 - 1, sz = a % 3 - 1; + shifts[a][0] = sx * box[0]; + shifts[a][1] = sy * box[1]; + shifts[a][2] = sz * box[2]; + } + } + + // Sum the per-thread value slot into a single number (call from a single thread after a barrier). + double thr_sum() const { + double s = 0; + for (size_t t = 0; t + PAD <= thr.size(); t += PAD) s += thr[t]; + return s; + } + + // ---- bonded bookkeeping ---------------------------------------------------- + // The contribution buffer holds one force vector per bond (on i; j gets its + // negative) and two per angle (on i and k; j gets -f_i - f_k). The gather + // index entries are (vector index << 2 | GATHER_*), in the order of the + // terms, so each particle sums its contributions in a fixed order. + void rebuild_topology() { + size_t slots = 0, nterm = 0; + for (auto& b : bonds) { + b.contrib_offset = slots; + slots += b.i.size(); + nterm += 2 * b.i.size(); + } + for (auto& a : angles) { + a.contrib_offset = slots; + slots += 2 * a.i.size(); + nterm += 3 * a.i.size(); + } + if (slots >= (size_t(1) << 30)) throw std::invalid_argument("too many bonds and angles"); + contrib.assign(3 * slots, 0.0); + std::vector owner(nterm); + std::vector code(nterm); + size_t t = 0; + auto add = [&](int p, size_t slot, uint32_t kind) { + owner[t] = p; + code[t++] = (uint32_t)(slot << 2) | kind; + }; + for (auto& b : bonds) + for (size_t q = 0; q < b.i.size(); ++q) { + add(b.i[q], b.contrib_offset + q, GATHER_PLUS); + add(b.j[q], b.contrib_offset + q, GATHER_MINUS); + } + for (auto& a : angles) + for (size_t q = 0; q < a.i.size(); ++q) { + add(a.i[q], a.contrib_offset + 2 * q, GATHER_PLUS); + add(a.j[q], a.contrib_offset + 2 * q, GATHER_MINUS_PAIR); + add(a.k[q], a.contrib_offset + 2 * q + 1, GATHER_PLUS); + } + // processing order of the terms: by the chunk of their lowest particle + const int nblk = (N + SUM_BLOCK - 1) / SUM_BLOCK; + chunk_reach.resize(nblk); + for (int k = 0; k < nblk; ++k) chunk_reach[k] = k; + auto order_terms = [&](int n, auto lo_hi, std::vector& order, std::vector& off, bool& in_order) { + off.assign(nblk + 1, 0); + std::vector lo(n); + in_order = true; + for (int q = 0; q < n; ++q) { + int a, b; + lo_hi(q, a, b); + lo[q] = a / SUM_BLOCK; + for (int k = b / SUM_BLOCK; k > lo[q]; --k) chunk_reach[k] = std::min(chunk_reach[k], lo[q]); + off[lo[q] + 1]++; + if (q > 0 && lo[q] < lo[q - 1]) in_order = false; + } + for (int k = 0; k < nblk; ++k) off[k + 1] += off[k]; + order.clear(); + if (!in_order) { + order.resize(n); + std::vector fl(off.begin(), off.end() - 1); + for (int q = 0; q < n; ++q) order[fl[lo[q]]++] = q; + } + }; + for (auto& b : bonds) + order_terms((int)b.i.size(), [&](int q, int& lo, int& hi) { + lo = std::min(b.i[q], b.j[q]); + hi = std::max(b.i[q], b.j[q]); + }, b.order, b.chunk_off, b.in_order); + for (auto& a : angles) + order_terms((int)a.i.size(), [&](int q, int& lo, int& hi) { + lo = std::min(a.i[q], std::min(a.j[q], a.k[q])); + hi = std::max(a.i[q], std::max(a.j[q], a.k[q])); + }, a.order, a.chunk_off, a.in_order); + gather_start.assign(N + 1, 0); + for (size_t c = 0; c < nterm; ++c) gather_start[owner[c] + 1]++; + for (int p = 0; p < N; ++p) gather_start[p + 1] += gather_start[p]; + gather_idx.assign(nterm, 0); + std::vector fl(gather_start.begin(), gather_start.end() - 1); + for (size_t c = 0; c < nterm; ++c) gather_idx[fl[owner[c]]++] = code[c]; + topology_dirty = false; + } + + // ---- neighbour lists (called by all threads of a team) ------------------------- + void build_list_inner(PairForce& pf) { + const int tid = thread_id(); + const double rl = pf.cutoff + pf.skin, rl2 = rl * rl; + // 1. image offsets and wrapped coordinates + if (pbc) { +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) + for (int d = 0; d < 3; ++d) { + double fl = std::floor(x[3 * p + d] / box[d]); + double w = x[3 * p + d] - fl * box[d]; + if (w >= box[d]) { // rounding at the upper edge + w -= box[d]; + fl += 1.0; + } + if (w < 0) w = 0; + if (!(std::fabs(fl) < 2e9)) { // also NaN + set_error("particle too far from the periodic box (simulation exploded?)"); + fl = 0; + } + img[3 * p + d] = (int32_t)fl; + xw[3 * p + d] = w; + } + } else { +#pragma omp for schedule(static) + for (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c]; + } + // 2. grid geometry and counting sort into cells +#pragma omp single + { + double len[3]; + if (pbc) { + for (int d = 0; d < 3; ++d) { + grid_lo[d] = 0.0; + len[d] = box[d]; + } + } else { + for (int d = 0; d < 3; ++d) { + double mn = std::numeric_limits::infinity(), mx = -mn; + for (int p = 0; p < N; ++p) { + mn = std::min(mn, x[3 * p + d]); + mx = std::max(mx, x[3 * p + d]); + } + if (!std::isfinite(mn) || !std::isfinite(mx)) { + set_error("non-finite particle coordinates (simulation exploded?)"); + mn = 0; + mx = 1; + } + grid_lo[d] = mn; + len[d] = std::max(mx - mn, rl) * (1 + 1e-12); + } + } + double e = rl; + const double vol = len[0] * len[1] * len[2]; + e = std::max(e, std::cbrt(vol / (8.0 * N + 27))); // at most ~8N cells + long ncell = 1; + for (int d = 0; d < 3; ++d) { + grid_nc[d] = std::max(1, (int)std::floor(len[d] / e)); + grid_edge[d] = len[d] / grid_nc[d]; + ncell *= grid_nc[d]; + } + cell_of.resize(N); + cell_list.resize(N + 4); // + padding for the run copies below + nb_count.resize(N); + cell_start.assign(ncell + 1, 0); + } + // cell of each particle (parallel), then counting sort (serial) +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) { + int ci[3]; + for (int d = 0; d < 3; ++d) { + double cd = (xw[3 * p + d] - grid_lo[d]) / grid_edge[d]; + cd = cd > 0 ? cd : 0; // also maps NaN to 0 + ci[d] = cd < grid_nc[d] - 1 ? (int)cd : grid_nc[d] - 1; + } + cell_of[p] = (ci[0] * grid_nc[1] + ci[1]) * grid_nc[2] + ci[2]; + } +#pragma omp single + { + const long ncell = (long)cell_start.size() - 1; + for (int p = 0; p < N; ++p) cell_start[cell_of[p] + 1]++; + occupied.clear(); + for (long c = 0; c < ncell; ++c) { + if (cell_start[c + 1]) occupied.push_back((int)c); + cell_start[c + 1] += cell_start[c]; + } + fill.assign(cell_start.begin(), cell_start.end() - 1); + for (int p = 0; p < N; ++p) cell_list[fill[cell_of[p]]++] = p; + sorted_xyz.resize(3 * ((size_t)N + 4)); // + padding for the run copies below + } + // wrapped coordinates in cell order (structure of arrays) + double* const SX = sorted_xyz.data(); + double* const SY = SX + (N + 4); + double* const SZ = SY + (N + 4); +#pragma omp for schedule(static) + for (int s = 0; s < N; ++s) { + const int q = cell_list[s]; + SX[s] = xw[3 * q]; + SY[s] = xw[3 * q + 1]; + SZ[s] = xw[3 * q + 2]; + } + // 3. candidate scan per occupied cell. The 3x3 columns of the stencil + // are contiguous runs of cells along z, hence contiguous ranges of the + // cell-ordered coordinates. They are copied (shifted to the right + // periodic image) into one flat buffer that all particles of the cell + // then filter without branches. + ThreadScratch& ts = thr_scratch[tid]; + size_t nent = 0; + ts.seg.clear(); + const int nc0 = grid_nc[0], nc1 = grid_nc[1], nc2 = grid_nc[2]; + const int nocc = (int)occupied.size(); +#pragma omp for schedule(dynamic, 32) nowait + for (int oc = 0; oc < nocc; ++oc) { + const int c = occupied[oc]; + const int cx = c / (nc1 * nc2), cy = (c / nc2) % nc1, cz = c % nc2; + int run_lo[27], run_hi[27], run_code[27], nrun = 0, ncand = 0; + auto add_run = [&](int first_cell, int last_cell, int code) { // inclusive cell range + const int lo = cell_start[first_cell], hi = cell_start[last_cell + 1]; + if (lo == hi) return; + run_lo[nrun] = lo; + run_hi[nrun] = hi; + run_code[nrun++] = code; + ncand += hi - lo; + }; + for (int ox = -1; ox <= 1; ++ox) { + int a = cx + ox, sx = 0; + if (a < 0 || a >= nc0) { + if (!pbc) continue; + if (a < 0) { a += nc0; sx = -1; } else { a -= nc0; sx = 1; } + } + for (int oy = -1; oy <= 1; ++oy) { + int b = cy + oy, sy = 0; + if (b < 0 || b >= nc1) { + if (!pbc) continue; + if (b < 0) { b += nc1; sy = -1; } else { b -= nc1; sy = 1; } + } + const int col = (a * nc1 + b) * nc2; + const int code0 = (sx + 1) * 9 + (sy + 1) * 3; // + (sz + 1) + if (cz >= 1 && cz + 1 < nc2) { + add_run(col + cz - 1, col + cz + 1, code0 + 1); + } else { + for (int oz = -1; oz <= 1; ++oz) { + int d = cz + oz, sz = 0; + if (d < 0 || d >= nc2) { + if (!pbc) continue; + if (d < 0) { d += nc2; sz = -1; } else { d -= nc2; sz = 1; } + } + add_run(col + d, col + d, code0 + sz + 1); + } + } + } + } + // One buffer per cell, so that each particle runs a single filter + // loop (separate short loops per run cost a branch miss each). + if ((int)ts.bx.size() < ncand + 4) { // + padding to a multiple of 4 / run copies + ts.bx.resize(2 * ncand + 4); + ts.by.resize(2 * ncand + 4); + ts.bz.resize(2 * ncand + 4); + ts.be.resize(2 * ncand + 4); + } + double* const BX = ts.bx.data(); + double* const BY = ts.by.data(); + double* const BZ = ts.bz.data(); + uint32_t* const BE = ts.be.data(); + const int* const CL = cell_list.data(); + int nbuf = 0; + for (int r = 0; r < nrun; ++r) { + const double* sh = shifts[run_code[r]]; + const double shx = sh[0], shy = sh[1], shz = sh[2]; + const uint32_t code = (uint32_t)run_code[r] << NB_SHIFT_BITS; + const int lo = run_lo[r], len = run_hi[r] - lo; +#ifdef __AVX2__ + // Runs are short (a few particles): copy whole groups of 4, which + // may read up to 3 entries past the run (the arrays are padded) + // and write past it (overwritten by the next run or the padding). + const __m256d SHX = _mm256_set1_pd(shx), SHY = _mm256_set1_pd(shy), SHZ = _mm256_set1_pd(shz); + const __m128i CODE = _mm_set1_epi32((int)code); + for (int k = 0; k < len; k += 4) { + _mm256_storeu_pd(BX + nbuf + k, _mm256_add_pd(_mm256_loadu_pd(SX + lo + k), SHX)); + _mm256_storeu_pd(BY + nbuf + k, _mm256_add_pd(_mm256_loadu_pd(SY + lo + k), SHY)); + _mm256_storeu_pd(BZ + nbuf + k, _mm256_add_pd(_mm256_loadu_pd(SZ + lo + k), SHZ)); + _mm_storeu_si128((__m128i*)(BE + nbuf + k), + _mm_or_si128(_mm_loadu_si128((const __m128i*)(CL + lo + k)), CODE)); + } +#else + for (int k = 0; k < len; ++k) { + BX[nbuf + k] = SX[lo + k] + shx; + BY[nbuf + k] = SY[lo + k] + shy; + BZ[nbuf + k] = SZ[lo + k] + shz; + BE[nbuf + k] = (uint32_t)CL[lo + k] | code; + } +#endif + nbuf += len; + } + for (int k = nbuf; k < ((nbuf + 3) & ~3); ++k) { // far away: never within rl + BX[k] = BY[k] = BZ[k] = 1e300; + BE[k] = 0; + } + for (int si = cell_start[c]; si < cell_start[c + 1]; ++si) { + const int p = CL[si]; + const double px = SX[si], py = SY[si], pz = SZ[si]; + if (ts.ent.size() < nent + nbuf + 4) ts.ent.resize(2 * (nent + nbuf + 4)); + uint32_t* const out = ts.ent.data() + nent; + // drop p itself and its exclusions: in the filter if there are at + // most two (chain neighbours), else afterwards (branch-free if few) + const int* ex_b = pf.excl.data() + pf.excl_start[p]; + const int nex = pf.excl_start[p + 1] - pf.excl_start[p]; + const uint32_t self = (uint32_t)p | (13u << NB_SHIFT_BITS); + const uint32_t none = ~0u; // never equal to a particle index + if (nex <= 2) { + const int m = filter_candidates(px, py, pz, BX, BY, BZ, BE, nbuf, rl2, self, + nex > 0 ? (uint32_t)ex_b[0] : none, + nex > 1 ? (uint32_t)ex_b[1] : none, out); + nb_count[p] = m; + ts.seg.push_back({p, nent}); + nent += m; + continue; + } + const int n = filter_candidates(px, py, pz, BX, BY, BZ, BE, nbuf, rl2, none, none, none, out); + int m = 0; + if (nex <= 8) { + for (int k = 0; k < n; ++k) { + const uint32_t ent = out[k]; + const int q = (int)(ent & NB_INDEX_MASK); + bool keep = ent != self; + for (int z = 0; z < nex; ++z) keep &= ex_b[z] != q; + out[m] = ent; + m += keep; + } + } else { + for (int k = 0; k < n; ++k) { + const uint32_t ent = out[k]; + if (ent == self || std::binary_search(ex_b, ex_b + nex, (int)(ent & NB_INDEX_MASK))) continue; + out[m++] = ent; + } + } + nb_count[p] = m; + ts.seg.push_back({p, nent}); + nent += m; + } + } +#pragma omp barrier + // 4. CSR offsets, then each thread scatters its segments +#pragma omp single + { + pf.nb_start.resize(N + 1); + pf.nb_start[0] = 0; + for (int p = 0; p < N; ++p) pf.nb_start[p + 1] = pf.nb_start[p] + nb_count[p]; + pf.nb.resize(pf.nb_start[N]); + } + for (const auto& sg : ts.seg) + std::copy(ts.ent.begin() + sg.second, ts.ent.begin() + sg.second + nb_count[sg.first], + pf.nb.begin() + pf.nb_start[sg.first]); +#pragma omp barrier + // 5. reference positions +#pragma omp for schedule(static) + for (size_t c = 0; c < 3 * (size_t)N; ++c) x_ref[c] = x[c]; +#pragma omp single + { + pf.need_rebuild = false; + pf.n_builds++; + } + } + + // Entries BE[k] of the candidates within sqrt(rl2) of (px, py, pz), in order, + // to out[0, n); returns n. Entries equal to `self` and entries whose particle + // is ex0 or ex1 are left out. BX, BY, BZ, BE are padded to a multiple of 4 + // with far-away candidates, and out has room for 3 entries beyond n. + static inline int filter_candidates(double px, double py, double pz, const double* BX, const double* BY, + const double* BZ, const uint32_t* BE, int nbuf, double rl2, uint32_t self, + uint32_t ex0, uint32_t ex1, uint32_t* out) { + int n = 0; +#ifdef __AVX2__ + // 4 candidates at a time; the accepted entries are moved to the front + // with a byte shuffle chosen by the comparison mask. Same arithmetic + // (no FMA, same order) as the scalar loop, so the same lists. + alignas(16) static const uint8_t compress[16][16] = { +#define PCN_L(a) 4 * a, 4 * a + 1, 4 * a + 2, 4 * a + 3 + {PCN_L(0), PCN_L(0), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(0), PCN_L(0), PCN_L(0)}, + {PCN_L(1), PCN_L(0), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(1), PCN_L(0), PCN_L(0)}, + {PCN_L(2), PCN_L(0), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(2), PCN_L(0), PCN_L(0)}, + {PCN_L(1), PCN_L(2), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(1), PCN_L(2), PCN_L(0)}, + {PCN_L(3), PCN_L(0), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(3), PCN_L(0), PCN_L(0)}, + {PCN_L(1), PCN_L(3), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(1), PCN_L(3), PCN_L(0)}, + {PCN_L(2), PCN_L(3), PCN_L(0), PCN_L(0)}, {PCN_L(0), PCN_L(2), PCN_L(3), PCN_L(0)}, + {PCN_L(1), PCN_L(2), PCN_L(3), PCN_L(0)}, {PCN_L(0), PCN_L(1), PCN_L(2), PCN_L(3)}, +#undef PCN_L + }; + const __m256d PX = _mm256_set1_pd(px), PY = _mm256_set1_pd(py), PZ = _mm256_set1_pd(pz); + const __m256d RL2 = _mm256_set1_pd(rl2); + const __m128i SELF = _mm_set1_epi32((int)self), EX0 = _mm_set1_epi32((int)ex0), EX1 = _mm_set1_epi32((int)ex1); + const __m128i IMASK = _mm_set1_epi32((int)NB_INDEX_MASK); + for (int k = 0; k < nbuf; k += 4) { + const __m256d dx = _mm256_sub_pd(PX, _mm256_loadu_pd(BX + k)); + const __m256d dy = _mm256_sub_pd(PY, _mm256_loadu_pd(BY + k)); + const __m256d dz = _mm256_sub_pd(PZ, _mm256_loadu_pd(BZ + k)); + const __m256d d2 = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(dx, dx), _mm256_mul_pd(dy, dy)), + _mm256_mul_pd(dz, dz)); + const __m128i e = _mm_loadu_si128((const __m128i*)(BE + k)); + const __m128i qi = _mm_and_si128(e, IMASK); + const __m128i drop = _mm_or_si128(_mm_cmpeq_epi32(e, SELF), + _mm_or_si128(_mm_cmpeq_epi32(qi, EX0), _mm_cmpeq_epi32(qi, EX1))); + const int m = _mm256_movemask_pd(_mm256_cmp_pd(d2, RL2, _CMP_LT_OQ)) & ~_mm_movemask_ps(_mm_castsi128_ps(drop)); + _mm_storeu_si128((__m128i*)(out + n), + _mm_shuffle_epi8(e, _mm_load_si128((const __m128i*)compress[m]))); + n += __builtin_popcount(m); + } +#else + for (int k = 0; k < nbuf; ++k) { + const double dx = px - BX[k], dy = py - BY[k], dz = pz - BZ[k]; + const uint32_t e = BE[k], q = e & NB_INDEX_MASK; + out[n] = e; + n += (dx * dx + dy * dy + dz * dz < rl2) & (e != self) & (q != ex0) & (q != ex1); + } +#endif + return n; + } + + // Pair interactions of the fast set (called by all threads of a team, after + // the list-based pair loop). Fast-slow pairs are found through the cell + // grid of the last build: a slow particle moved less than skin/2, so it is + // within the 27-cell stencil around the fast particle's current cell. + // Fast-fast pairs are found by binning the fast set into the same grid at + // its current positions. Each pair is computed once; forces on the partner + // are buffered and applied by one thread, in the order of the fast list, so + // that the result does not depend on which thread handled which particle. + void fast_set_forces(double& e) { + const int tid = thread_id(); + const PairForce& pf = pairs[0]; + const double rc2 = pf.cutoff * pf.cutoff; + const int nc0 = grid_nc[0], nc1 = grid_nc[1], nc2 = grid_nc[2]; + std::vector& out = thr_scratch[tid].contrib; + out.clear(); + auto current_cell = [&](int p, int* ci) { + for (int d = 0; d < 3; ++d) { + double xx = x[3 * p + d]; + if (pbc) xx -= std::floor(xx / box[d]) * box[d]; + double cd = (xx - grid_lo[d]) / grid_edge[d]; + cd = cd > 0 ? cd : 0; + ci[d] = cd < grid_nc[d] - 1 ? (int)cd : grid_nc[d] - 1; + } + }; +#pragma omp single + { + fast_span.resize(nfast); + fast_binned.resize(nfast); + for (int a = 0; a < nfast; ++a) { + int ci[3]; + current_cell(fast_list[a], ci); + fast_binned[a] = {(ci[0] * nc1 + ci[1]) * nc2 + ci[2], fast_list[a]}; + } + std::sort(fast_binned.begin(), fast_binned.end()); + } + auto pair = [&](int p, int q, double& fx, double& fy, double& fz) { + double dx = x[3 * p] - x[3 * q], dy = x[3 * p + 1] - x[3 * q + 1], dz = x[3 * p + 2] - x[3 * q + 2]; + if (pbc) min_image(dx, dy, dz); + const double r2 = dx * dx + dy * dy + dz * dz; + if (r2 >= rc2) return; + const int* ex_b = pf.excl.data() + pf.excl_start[p]; + const int* ex_e = pf.excl.data() + pf.excl_start[p + 1]; + if (ex_b != ex_e && std::binary_search(ex_b, ex_e, q)) return; + const double r = std::sqrt(r2); + double en, de; + pf.tables[(size_t)pf.type[p] * pf.ntypes + pf.type[q]].eval_in_range(r, en, de); + e += en; + const double sc = r > 0 ? -de / r : 0.0; + fx += sc * dx; + fy += sc * dy; + fz += sc * dz; + out.push_back({q, -sc * dx, -sc * dy, -sc * dz}); + }; +#pragma omp for schedule(dynamic, 4) + for (int a = 0; a < nfast; ++a) { + const int p = fast_list[a]; + const size_t out0 = out.size(); + double fx = 0, fy = 0, fz = 0; + int ci[3]; + current_cell(p, ci); + for (int ox = -1; ox <= 1; ++ox) { + int ca = ci[0] + ox; + if (ca < 0 || ca >= nc0) { + if (!pbc) continue; + ca = (ca + nc0) % nc0; + } + for (int oy = -1; oy <= 1; ++oy) { + int cb = ci[1] + oy; + if (cb < 0 || cb >= nc1) { + if (!pbc) continue; + cb = (cb + nc1) % nc1; + } + for (int oz = -1; oz <= 1; ++oz) { + int cc = ci[2] + oz; + if (cc < 0 || cc >= nc2) { + if (!pbc) continue; + cc = (cc + nc2) % nc2; + } + const int cell = (ca * nc1 + cb) * nc2 + cc; + for (int s = cell_start[cell]; s < cell_start[cell + 1]; ++s) { + const int q = cell_list[s]; + if (fast[q]) continue; // includes q == p + pair(p, q, fx, fy, fz); + } + // fast partners binned at their current positions; q > p counts each pair once + auto lo = std::lower_bound(fast_binned.begin(), fast_binned.end(), std::make_pair(cell, 0)); + for (; lo != fast_binned.end() && lo->first == cell; ++lo) + if (lo->second > p) pair(p, lo->second, fx, fy, fz); + } + } + } + f[3 * p] += fx; + f[3 * p + 1] += fy; + f[3 * p + 2] += fz; + fast_span[a] = {tid, out0, out.size() - out0}; + } +#pragma omp single + for (int a = 0; a < nfast; ++a) { + const FastSpan& sp = fast_span[a]; + const Contribution* c = thr_scratch[sp.tid].contrib.data() + sp.start; + for (size_t k = 0; k < sp.count; ++k) { + f[3 * c[k].q] += c[k].fx; + f[3 * c[k].q + 1] += c[k].fy; + f[3 * c[k].q + 2] += c[k].fz; + } + } + } + + // ---- bonded terms (any thread) --------------------------------------------------- + // Forces on i of bonds order[t] (or t if in order), t in [t0, t1), into the + // contribution buffer; energies added to e. + inline void bond_terms(const BondSet& b, int t0, int t1, double& e) { + const bool bp = b.pbc && pbc; + double en_sum = 0.0; + for (int t = t0; t < t1; ++t) { + const int q = b.in_order ? t : b.order[t]; + const int i = b.i[q], j = b.j[q]; + double dx = x[3 * i] - x[3 * j], dy = x[3 * i + 1] - x[3 * j + 1], dz = x[3 * i + 2] - x[3 * j + 2]; + if (bp) min_image(dx, dy, dz); + const double r = std::sqrt(dx * dx + dy * dy + dz * dz); + double en, de; + if (b.tabulated) { + b.tables[b.tab[q]].eval(r, en, de); + } else { + const double ext = r - (b.uniform ? b.r0[0] : b.r0[q]); + de = (b.uniform ? b.k[0] : b.k[q]) * ext; + en = 0.5 * de * ext; + } + en_sum += en; + const double s = r > 0 ? -de / r : 0.0; + double* c = contrib.data() + 3 * (b.contrib_offset + (size_t)q); + c[0] = s * dx; + c[1] = s * dy; + c[2] = s * dz; + } + e += en_sum; + } + + // Forces on i and k of angles order[t] (or t if in order), t in [t0, t1), into + // the contribution buffer; energies added to e. + inline void angle_terms(const AngleSet& a, int t0, int t1, double& e) { + const bool ap = a.pbc && pbc; + double en_sum = 0.0; + for (int t = t0; t < t1; ++t) { + const int q = a.in_order ? t : a.order[t]; + const int i = a.i[q], j = a.j[q], k = a.k[q]; + double ax = x[3 * i] - x[3 * j], ay = x[3 * i + 1] - x[3 * j + 1], az = x[3 * i + 2] - x[3 * j + 2]; + double bx = x[3 * k] - x[3 * j], by = x[3 * k + 1] - x[3 * j + 1], bz = x[3 * k + 2] - x[3 * j + 2]; + if (ap) { + min_image(ax, ay, az); + min_image(bx, by, bz); + } + double* c = contrib.data() + 3 * (a.contrib_offset + 2 * (size_t)q); // f_i, f_k + const AngleTable& at = a.tables[a.tab_all >= 0 ? a.tab_all : a.tab[q]]; + const double aa2 = ax * ax + ay * ay + az * az, bb2 = bx * bx + by * by + bz * bz; + const double dot = ax * bx + ay * by + az * bz; + double en, de; + if (aa2 == 0 || bb2 == 0) { + at.t.eval(0.0, en, de); + en_sum += en; + for (int z = 0; z < 6; ++z) c[z] = 0.0; + continue; + } + const double inv_ab = 1.0 / std::sqrt(aa2 * bb2); + double cs = dot * inv_ab; + cs = cs > 1.0 ? 1.0 : (cs < -1.0 ? -1.0 : cs); + if (cs >= at.c_lo && cs <= at.c_hi) { + at.tc.eval(cs, en, de); // de = dE/dcos + en_sum += en; + // f_i = -dE/dc * (b/(|a||b|) - c a/|a|^2), f_k likewise + const double ca = cs / aa2, cb = cs / bb2; + const double fix = -de * (bx * inv_ab - ca * ax), fiy = -de * (by * inv_ab - ca * ay), + fiz = -de * (bz * inv_ab - ca * az); + const double fkx = -de * (ax * inv_ab - cb * bx), fky = -de * (ay * inv_ab - cb * by), + fkz = -de * (az * inv_ab - cb * bz); + c[0] = fix; + c[1] = fiy; + c[2] = fiz; + c[3] = fkx; + c[4] = fky; + c[5] = fkz; + } else { + const double nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx; + const double nn = std::sqrt(nx * nx + ny * ny + nz * nz); + const double theta = std::atan2(nn, dot); + at.t.eval(theta, en, de); // de = dE/dtheta + en_sum += en; + if (nn < 1e-12 * std::sqrt(aa2 * bb2)) { + for (int z = 0; z < 6; ++z) c[z] = 0.0; + continue; + } + // f_i = dE/dtheta (n x a) / (|n| |a|^2), f_k = dE/dtheta (b x n) / (|n| |b|^2) + const double si = de / (nn * aa2), sk = de / (nn * bb2); + const double fix = si * (ny * az - nz * ay), fiy = si * (nz * ax - nx * az), + fiz = si * (nx * ay - ny * ax); + const double fkx = sk * (by * nz - bz * ny), fky = sk * (bz * nx - bx * nz), + fkz = sk * (bx * ny - by * nx); + c[0] = fix; + c[1] = fiy; + c[2] = fiz; + c[3] = fkx; + c[4] = fky; + c[5] = fkz; + } + } + e += en_sum; + } + + // Gather the bonded contributions of the particles of chunk blk into f + // (after the other forces), and the variable Langevin error sum of the chunk. + inline void gather_block(int blk, bool vl) { + double err = 0.0; + for (int p = blk * SUM_BLOCK, pe = std::min(N, p + SUM_BLOCK); p < pe; ++p) { + double fx = 0, fy = 0, fz = 0; + for (int s = gather_start[p]; s < gather_start[p + 1]; ++s) { + const uint32_t g = gather_idx[s]; + const double* c = &contrib[3 * (size_t)(g >> 2)]; + if ((g & 3) == GATHER_PLUS) { + fx += c[0]; + fy += c[1]; + fz += c[2]; + } else if ((g & 3) == GATHER_MINUS) { + fx += -c[0]; + fy += -c[1]; + fz += -c[2]; + } else { // the same expression as -f_i - f_k in the angle loop + fx += -c[0] - c[3]; + fy += -c[1] - c[4]; + fz += -c[2] - c[5]; + } + } + fx += f[3 * p]; + fy += f[3 * p + 1]; + fz += f[3 * p + 2]; + f[3 * p] = fx; + f[3 * p + 1] = fy; + f[3 * p + 2] = fz; + if (vl) { + const double im = mass_uniform ? inv_mass[0] : inv_mass[p]; + const double ax = im * fx, ay = im * fy, az = im * fz; + err += ax * ax; + err += ay * ay; + err += az * az; + } + } + block_sum[blk] = err; + } + + // ---- forces (called by all threads of a team) ------------------------------------ + void forces_inner() { + if (forces_valid) return; // shared flag, consistent after the last barrier + const int tid = thread_id(); + // Neighbour lists. All lists share x_ref and the image offsets, so if + // one needs a rebuild, all are rebuilt. The decision is taken by one + // thread and published by the barrier at the end of the single block. +#pragma omp single + { + rebuild_all = false; + for (auto& pf : pairs) + if (pf.need_rebuild) rebuild_all = true; + // the direct search for the fast set uses the grid of the (single) + // pair force and needs >= 3 cells per periodic dimension + const bool escape_ok = pairs.size() == 1 && (!pbc || (grid_nc[0] >= 3 && grid_nc[1] >= 3 && grid_nc[2] >= 3)); + if (nfast > (escape_ok ? fast_max : 0)) rebuild_all = true; + } + if (rebuild_all) { + for (auto& pf : pairs) build_list_inner(pf); +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) fast[p] = 0; +#pragma omp single + { + nfast = 0; + fast_list.clear(); + } + } + // xw = x - img * box (wrapped coordinates, PBC only) is kept up to date + // by the integrator; after a rebuild, img has changed. + if (rebuild_all && pbc) { +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) + for (int d = 0; d < 3; ++d) xw[3 * p + d] = x[3 * p + d] - img[3 * p + d] * box[d]; + } + const double* const XW = pbc ? xw.data() : x.data(); + + double e = 0.0; + const uint8_t* is_fast = nfast > 0 ? fast.data() : nullptr; + // pair forces + external forces, owner computes; the fast set is handled below +#pragma omp for schedule(dynamic, 64) + for (int p = 0; p < N; ++p) { + double fx = 0, fy = 0, fz = 0, ep = 0; + const double px = XW[3 * p], py = XW[3 * p + 1], pz = XW[3 * p + 2]; + if (!is_fast || !is_fast[p]) + for (const PairForce& pf : pairs) { + const double rc2 = pf.cutoff * pf.cutoff; + const Table* row = &pf.tables[(size_t)pf.type[p] * pf.ntypes]; + const bool one_type = pf.ntypes == 1; + const uint32_t* nb = pf.nb.data(); + for (int s = pf.nb_start[p], se = pf.nb_start[p + 1]; s < se; ++s) { + const uint32_t ent = nb[s]; + const int q = (int)(ent & NB_INDEX_MASK); + if (is_fast && is_fast[q]) continue; + const double* sh = shifts[ent >> NB_SHIFT_BITS]; + const double dx = px - XW[3 * q] - sh[0], dy = py - XW[3 * q + 1] - sh[1], + dz = pz - XW[3 * q + 2] - sh[2]; + const double r2 = dx * dx + dy * dy + dz * dz; + if (r2 >= rc2) continue; + const double r = std::sqrt(r2); + double en, de; + (one_type ? row[0] : row[pf.type[q]]).eval_in_range(r, en, de); + ep += en; + const double sc = r > 0 ? -de / r : 0.0; + fx += sc * dx; + fy += sc * dy; + fz += sc * dz; + } + } + e += 0.5 * ep; + f[3 * p] = fx; + f[3 * p + 1] = fy; + f[3 * p + 2] = fz; + } + if (nfast > 0) fast_set_forces(e); + for (const SphericalConfinement& sc : spheres) { + const int n = (int)sc.particles.size(); +#pragma omp for schedule(static) + for (int q = 0; q < n; ++q) { + const int p = sc.particles[q]; + const double dx = x[3 * p] - sc.cx, dy = x[3 * p + 1] - sc.cy, dz = x[3 * p + 2] - sc.cz; + const double r = std::sqrt(dx * dx + dy * dy + dz * dz + sc.tt * sc.tt); + const double u = r - sc.aa; + if (sc.sign * u < 0) continue; // Lepton: step(x) = x >= 0 + const double root = std::sqrt(u * u + sc.t * sc.t); + e += sc.kb * (root - sc.t); + const double s = -sc.kb * u / (root * r); + f[3 * p] += s * dx; + f[3 * p + 1] += s * dy; + f[3 * p + 2] += s * dz; + } + } + for (const Tether& t : tethers) { + const int n = (int)t.particles.size(); + const bool tp = t.pbc && pbc; +#pragma omp for schedule(static) + for (int q = 0; q < n; ++q) { + const int p = t.particles[q]; + double dx = x[3 * p] - t.x0[3 * q], dy = x[3 * p + 1] - t.x0[3 * q + 1], + dz = x[3 * p + 2] - t.x0[3 * q + 2]; + if (tp) min_image(dx, dy, dz); + e += t.k[0] * dx * dx + t.k[1] * dy * dy + t.k[2] * dz * dz; + f[3 * p] -= 2 * t.k[0] * dx; + f[3 * p + 1] -= 2 * t.k[1] * dy; + f[3 * p + 2] -= 2 * t.k[2] * dz; + } + } + // Bonded terms and the gather of their contributions, in chunks of + // SUM_BLOCK particles, so that the contributions are still in the cache + // when they are gathered. The terms are processed by the chunk of their + // lowest particle; once the terms of chunks 0..k are done, chunk k can be + // gathered. Each thread takes a contiguous range of chunks; a chunk that + // terms from an earlier thread's range reach into is gathered after a + // barrier. The gather is the last update of f, so the variable Langevin + // error sum (sum of |f/m|^2, see integrate_inner) is accumulated there, + // per chunk, so that it does not depend on the number of threads. + const bool vl = integrator == VARIABLE_LANGEVIN; + const int nblk = (N + SUM_BLOCK - 1) / SUM_BLOCK; + const int nt = team_size(); + const int k0 = (int)((long)tid * nblk / nt), k1 = (int)((long)(tid + 1) * nblk / nt); + for (int k = k0; k < k1; ++k) { + for (const BondSet& bs : bonds) bond_terms(bs, bs.chunk_off[k], bs.chunk_off[k + 1], e); + for (const AngleSet& as : angles) angle_terms(as, as.chunk_off[k], as.chunk_off[k + 1], e); + if (chunk_reach[k] >= k0) gather_block(k, vl); + } + thr[(size_t)PAD * tid] = e; +#pragma omp barrier + for (int k = k0; k < k1; ++k) + if (chunk_reach[k] < k0) gather_block(k, vl); +#pragma omp barrier +#pragma omp single + { + epot = thr_sum(); + if (!std::isfinite(epot)) set_error("non-finite potential energy (simulation exploded?)"); + if (vl) { + double err = 0.0; + for (int b = 0; b < nblk; ++b) err += block_sum[b]; + vl_err = err; + if (stepping) { + select_step_size(); + dt_selected = true; + } + } + forces_valid = true; + } // implicit barrier + } + + // ReferenceVariableStochasticDynamics::updatePart1: step size from the error + // sum over all coordinates of (f/m)^2 (vl_err, computed with the forces). + void select_step_size() { + double er = std::sqrt(vl_err / (3.0 * N)); + double nd = er > 0 ? std::sqrt(error_tol_ / er) : max_dt; + if (dt_ > 0.0) nd = std::min(nd, 2.0 * dt_); + if (nd > dt_ && nd < 1.2 * dt_) nd = dt_; + if (nd > max_dt) nd = max_dt; + if (!std::isfinite(nd) || nd <= 0) { + set_error("variable Langevin: invalid step size (simulation exploded?)"); + nd = dt_ > 0 ? dt_ : 1e-6; + } + dt_ = nd; + } + + // ---- integration (called by all threads of a team) ------------------------------------ + void integrate_inner() { + const int tid = thread_id(); + if (integrator == VARIABLE_LANGEVIN && !dt_selected) { + // forces were already valid when the step started (e.g. after getState). + // dt_selected is only written in single blocks of forces_inner and + // below, so all threads take this branch alike. +#pragma omp single + select_step_size(); + } + const double dt = dt_; + const double kT = BOLTZ * T; + const double vscale = std::exp(-dt * gamma); + const double noisescale = std::sqrt(kT * (1 - vscale * vscale)); + const uint64_t base = mix64(seed ^ mix64((uint64_t)nsteps)); + std::vector& my_fast = thr_scratch[tid].fast; + my_fast.clear(); + bool bad = false; + + // local restrict pointers: the stores below cannot change the inputs + double* __restrict X = x.data(); + double* __restrict V = v.data(); + double* __restrict XW = xw.data(); + const double* __restrict F = f.data(); + const int32_t* __restrict IMG = img.data(); + const double box_d[3] = {box[0], box[1], box[2]}; + const double* __restrict XREF = x_ref.data(); + const double* __restrict IM = inv_mass.data(); + const bool brownian = integrator == BROWNIAN, wrap = pbc; + const double sim_all = uniform_sqrt_inv_mass; // 0 unless all masses are equal +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) { + const double im = mass_uniform ? IM[0] : IM[p]; + if (im == 0) continue; + const double sim = sim_all != 0 ? sim_all : std::sqrt(im); + const size_t c0 = 3 * (size_t)p; + const double gs[3] = {znormal(base + ((uint64_t)c0 << 24)), znormal(base + ((uint64_t)(c0 + 1) << 24)), + znormal(base + ((uint64_t)(c0 + 2) << 24))}; + double d2 = 0.0; + for (int d = 0; d < 3; ++d) { + const size_t c = c0 + d; + const double g = gs[d]; + double xx; + if (brownian) { + // ReferenceBrownianDynamics + const double dx = dt / gamma * im * F[c] + std::sqrt(2.0 * kT * dt / gamma) * sim * g; + xx = X[c] + dx; + V[c] = dx / dt; + } else { + // ReferenceLangevinMiddleDynamics (OpenMM 8: also LangevinIntegrator and, + // with the step size chosen above, VariableLangevinIntegrator) + double vv = V[c] + dt * im * F[c]; + xx = X[c] + 0.5 * dt * vv; + vv = vscale * vv + noisescale * sim * g; + xx += 0.5 * dt * vv; + V[c] = vv; + } + X[c] = xx; + if (wrap) XW[c] = xx - IMG[c] * box_d[d]; + const double dd = xx - XREF[c]; + d2 += dd * dd; + } + if (!(d2 <= std::numeric_limits::max())) bad = true; // NaN or inf + const bool fp = d2 > fast_lim2; + fast[p] = fp; + if (fp) my_fast.push_back(p); + } + thr[(size_t)PAD * tid] = bad ? 1.0 : 0.0; +#pragma omp barrier +#pragma omp single + { + if (thr_sum() != 0.0) set_error("non-finite coordinates (simulation exploded?)"); + fast_list.clear(); + for (const ThreadScratch& ts : thr_scratch) fast_list.insert(fast_list.end(), ts.fast.begin(), ts.fast.end()); + nfast = (int)fast_list.size(); + time_ += dt; + nsteps++; + forces_valid = false; + dt_selected = false; + } // implicit barrier + } +}; + +} // namespace pcn diff --git a/polychrom/_native_engine.pyx b/polychrom/_native_engine.pyx new file mode 100644 index 0000000..a5d18ed --- /dev/null +++ b/polychrom/_native_engine.pyx @@ -0,0 +1,299 @@ +# distutils: language = c++ +# cython: language_level=3, boundscheck=False, wraparound=False +"""Thin Cython wrapper around the native C++ engine (polychrom/_native/engine.hpp). + +Use :mod:`polychrom.native` instead of this module directly. +""" + +import numpy as np + +cimport numpy as cnp +from libc.stdint cimport uint64_t +from libcpp cimport bool as cbool + +cnp.import_array() + + +cdef extern from "_native/engine.hpp" namespace "pcn" nogil: + cbool cpu_has_x86_64_v3() + + cdef cppclass Engine: + Engine(int N) except + + void set_threads(int n) + int get_threads() + void set_masses(const double* m) + void set_box(cbool pbc, double lx, double ly, double lz) + void set_positions(const double* p) + void get_positions(double* p) + void set_velocities(const double* p) + void get_velocities(double* p) + void get_forces(double* p) except + + void set_velocities_to_temperature(double T, uint64_t seed) + int add_bond_set(cbool tabulated, cbool pbc) + void set_harmonic_bonds(int s, int n, const int* i, const int* j, const double* r0, const double* k) except + + int add_bond_table(int s, double x0, double x1, int nknots, const double* E, const double* D) except + + void set_tabulated_bonds(int s, int n, const int* i, const int* j, const int* tab) except + + void clear_bond_tables(int s) except + + int add_angle_set(cbool pbc) + int add_angle_table(int s, int nt, const double* Et, const double* Dt, double c_lo, double c_hi, int nc, + const double* Ec, const double* Dc) except + + void set_angles(int s, int n, const int* i, const int* j, const int* k, const int* tab) except + + void clear_angle_tables(int s) except + + int add_pair_force(double cutoff, double skin, int ntypes, const int* type) except + + void set_pair_table(int s, int ta, int tb, double x0, double x1, int nknots, const double* E, const double* D) except + + void set_pair_exclusions(int s, int n, const int* i, const int* j) except + + long get_pair_builds(int s) except + + long get_pair_list_size(int s) except + + int get_fast_count() + void get_fast_particles(int* out) + void set_pair_skin(int s, double skin) except + + int add_spherical_confinement(int n, const int* particles, double kb, double aa, double t, double tt, + double sign, double cx, double cy, double cz) except + + void set_spherical_confinement(int s, double kb, double aa, double t, double tt, double sign, + double cx, double cy, double cz) except + + int add_tether(int n, const int* particles, const double* x0, double kx, double ky, double kz, + cbool pbc) except + + void set_tether_k(int s, double kx, double ky, double kz) except + + void set_integrator(int type, double temperature, double friction, double dt, double error_tol) except + + void set_temperature(double t) + void set_friction(double g) + void set_step_size(double dt) + double get_step_size() + void set_max_step_size(double m) + void set_error_tolerance(double e) + void set_seed(uint64_t s) + double get_time() + void set_time(double t) + long long get_step_count() + double potential_energy() except + + double kinetic_energy() except + + void step(int n) except + + void compute() except + + + +INTEGRATORS = {"langevin": 0, "langevinmiddle": 1, "variablelangevin": 2, "brownian": 3} + + +cdef inline cnp.ndarray _d(a, n=None): + arr = np.ascontiguousarray(a, dtype=np.float64) + if n is not None and arr.size != n: + raise ValueError(f"expected {n} values, got {arr.size}") + return arr + + +cdef inline cnp.ndarray _i(a, n=None): + arr = np.ascontiguousarray(a, dtype=np.intc) + if n is not None and arr.size != n: + raise ValueError(f"expected {n} values, got {arr.size}") + return arr + + +def cpu_supports_x86_64_v3(): + """True if the CPU can run the x86-64-v3 (AVX2, FMA) build of the engine.""" + return cpu_has_x86_64_v3() + + +cdef class NativeEngine: + cdef Engine* e + cdef readonly int N + + def __cinit__(self, int N): + self.e = new Engine(N) + self.N = N + + def __dealloc__(self): + del self.e + + # configuration ------------------------------------------------------- + def set_threads(self, int n): + self.e.set_threads(n) + + def get_threads(self): + return self.e.get_threads() + + def set_masses(self, m): + cdef cnp.ndarray a = _d(m, self.N) + self.e.set_masses( a.data) + + def set_box(self, pbc, lx=0.0, ly=0.0, lz=0.0): + self.e.set_box(bool(pbc), lx, ly, lz) + + def set_positions(self, p): + cdef cnp.ndarray a = _d(p, 3 * self.N) + self.e.set_positions( a.data) + + def get_positions(self): + cdef cnp.ndarray a = np.empty((self.N, 3)) + self.e.get_positions( a.data) + return a + + def set_velocities(self, p): + cdef cnp.ndarray a = _d(p, 3 * self.N) + self.e.set_velocities( a.data) + + def get_velocities(self): + cdef cnp.ndarray a = np.empty((self.N, 3)) + self.e.get_velocities( a.data) + return a + + def get_forces(self): + cdef cnp.ndarray a = np.empty((self.N, 3)) + with nogil: + self.e.get_forces( a.data) + return a + + def set_velocities_to_temperature(self, double T, uint64_t seed): + self.e.set_velocities_to_temperature(T, seed) + + # bonds --------------------------------------------------------------- + def add_bond_set(self, tabulated, pbc=False): + return self.e.add_bond_set(bool(tabulated), bool(pbc)) + + def set_harmonic_bonds(self, int s, i, j, r0, k): + cdef cnp.ndarray ai = _i(i) + cdef int n = ai.size + cdef cnp.ndarray aj = _i(j, n), ar = _d(r0, n), ak = _d(k, n) + self.e.set_harmonic_bonds(s, n, ai.data, aj.data, ar.data, ak.data) + + def add_bond_table(self, int s, double x0, double x1, E, D): + cdef cnp.ndarray ae = _d(E) + cdef cnp.ndarray ad = _d(D, ae.size) + return self.e.add_bond_table(s, x0, x1, ae.size, ae.data, ad.data) + + def set_tabulated_bonds(self, int s, i, j, tab): + cdef cnp.ndarray ai = _i(i) + cdef int n = ai.size + cdef cnp.ndarray aj = _i(j, n), at = _i(tab, n) + self.e.set_tabulated_bonds(s, n, ai.data, aj.data, at.data) + + def clear_bond_tables(self, int s): + self.e.clear_bond_tables(s) + + # angles ---------------------------------------------------------------- + def add_angle_set(self, pbc=False): + return self.e.add_angle_set(bool(pbc)) + + def add_angle_table(self, int s, Et, Dt, double c_lo=0.0, double c_hi=0.0, Ec=(), Dc=()): + """E, dE/dtheta on [0, pi]; optionally E, dE/dcos on [c_lo, c_hi].""" + cdef cnp.ndarray aet = _d(Et) + cdef cnp.ndarray adt = _d(Dt, aet.size) + cdef cnp.ndarray aec = _d(Ec) + cdef cnp.ndarray adc = _d(Dc, aec.size) + return self.e.add_angle_table(s, aet.size, aet.data, adt.data, c_lo, c_hi, aec.size, + aec.data, adc.data) + + def set_angles(self, int s, i, j, k, tab): + cdef cnp.ndarray ai = _i(i) + cdef int n = ai.size + cdef cnp.ndarray aj = _i(j, n), ak = _i(k, n), at = _i(tab, n) + self.e.set_angles(s, n, ai.data, aj.data, ak.data, at.data) + + def clear_angle_tables(self, int s): + self.e.clear_angle_tables(s) + + # pair potentials --------------------------------------------------------- + def add_pair_force(self, double cutoff, double skin, int ntypes, types): + cdef cnp.ndarray at = _i(types, self.N) + return self.e.add_pair_force(cutoff, skin, ntypes, at.data) + + def set_pair_table(self, int s, int ta, int tb, double x0, double x1, E, D): + cdef cnp.ndarray ae = _d(E) + cdef cnp.ndarray ad = _d(D, ae.size) + self.e.set_pair_table(s, ta, tb, x0, x1, ae.size, ae.data, ad.data) + + def set_pair_exclusions(self, int s, i, j): + cdef cnp.ndarray ai = _i(i) + cdef int n = ai.size + cdef cnp.ndarray aj = _i(j, n) + self.e.set_pair_exclusions(s, n, ai.data, aj.data) + + def get_pair_builds(self, int s): + return self.e.get_pair_builds(s) + + def get_pair_list_size(self, int s): + return self.e.get_pair_list_size(s) + + def get_fast_count(self): + """Particles that moved more than half the skin since the last list build.""" + return self.e.get_fast_count() + + def get_fast_particles(self): + cdef cnp.ndarray a = np.empty(self.e.get_fast_count(), dtype=np.intc) + if a.size: + self.e.get_fast_particles( a.data) + return a + + def set_pair_skin(self, int s, double skin): + self.e.set_pair_skin(s, skin) + + # external ---------------------------------------------------------------- + def add_spherical_confinement(self, particles, double kb, double aa, double t, double tt, double sign, + double cx, double cy, double cz): + cdef cnp.ndarray ap = _i(particles) + return self.e.add_spherical_confinement(ap.size, ap.data, kb, aa, t, tt, sign, cx, cy, cz) + + def set_spherical_confinement(self, int s, double kb, double aa, double t, double tt, double sign, + double cx, double cy, double cz): + self.e.set_spherical_confinement(s, kb, aa, t, tt, sign, cx, cy, cz) + + def add_tether(self, particles, x0, double kx, double ky, double kz, pbc=False): + cdef cnp.ndarray ap = _i(particles) + cdef cnp.ndarray ax = _d(x0, 3 * ap.size) + return self.e.add_tether(ap.size, ap.data, ax.data, kx, ky, kz, bool(pbc)) + + def set_tether_k(self, int s, double kx, double ky, double kz): + self.e.set_tether_k(s, kx, ky, kz) + + # integrator ---------------------------------------------------------------- + def set_integrator(self, kind, double temperature, double friction, double dt=0.0, double error_tol=0.0): + self.e.set_integrator(INTEGRATORS[kind.lower()], temperature, friction, dt, error_tol) + + def set_temperature(self, double t): + self.e.set_temperature(t) + + def set_friction(self, double g): + self.e.set_friction(g) + + def set_step_size(self, double dt): + self.e.set_step_size(dt) + + def get_step_size(self): + return self.e.get_step_size() + + def set_error_tolerance(self, double e): + self.e.set_error_tolerance(e) + + def set_max_step_size(self, double m): + self.e.set_max_step_size(m) + + def set_seed(self, uint64_t s): + self.e.set_seed(s) + + def get_time(self): + return self.e.get_time() + + def set_time(self, double t): + self.e.set_time(t) + + def get_step_count(self): + return self.e.get_step_count() + + def potential_energy(self): + cdef double r + with nogil: + r = self.e.potential_energy() + return r + + def kinetic_energy(self): + cdef double r + with nogil: + r = self.e.kinetic_energy() + return r + + def step(self, int n): + with nogil: + self.e.step(n) + + def compute(self): + with nogil: + self.e.compute() diff --git a/polychrom/_native_engine_x86_64_v3.pyx b/polychrom/_native_engine_x86_64_v3.pyx new file mode 100644 index 0000000..29ce49d --- /dev/null +++ b/polychrom/_native_engine_x86_64_v3.pyx @@ -0,0 +1,9 @@ +# distutils: language = c++ +# cython: language_level=3, boundscheck=False, wraparound=False +"""The native engine compiled for x86-64-v3 (AVX2, FMA, BMI2). + +polychrom.native imports it instead of polychrom._native_engine when the CPU +supports these instructions. +""" + +include "_native_engine.pyx" diff --git a/polychrom/native.py b/polychrom/native.py new file mode 100644 index 0000000..6056b6d --- /dev/null +++ b/polychrom/native.py @@ -0,0 +1,1015 @@ +""" +Native CPU backend: ``Simulation(platform="native")`` +===================================================== + +A specialised multi-threaded CPU engine (``polychrom/_native/engine.hpp``) that +runs polychrom simulations without an OpenMM context. It is much faster than +OpenMM's CPU platform for polymer models, because it avoids per-step overheads +that are irrelevant for coarse-grained polymers (see the engine header for the +techniques used). + +The backend is a drop-in replacement: forces are still created by the functions +in :mod:`polychrom.forces` as OpenMM force objects, and ``Simulation.context`` +and ``Simulation.integrator`` provide the subset of the OpenMM ``Context`` and +``Integrator`` API that polychrom code uses, including +``force.updateParametersInContext(sim.context)`` for loop extrusion. + +How forces are translated +------------------------- + +* ``HarmonicBondForce`` is evaluated natively. +* ``CustomBondForce``, ``CustomAngleForce`` and ``CustomNonbondedForce`` are + tabulated: a two- or three-particle copy of the force (same expression, + global parameters, tabulated functions, switching function) is evaluated with + OpenMM's Reference platform on a fine grid, once per distinct set of + per-bond/angle/particle parameters, and interpolated with cubic Hermite + splines that use the exact energies and derivatives. Any energy expression + therefore works, as long as it depends only on the distance (angle) and the + number of distinct parameter sets is moderate. +* ``CustomExternalForce`` is supported for + :func:`polychrom.forces.spherical_confinement` and + :func:`polychrom.forces.tether_particles`. + +Anything else raises :class:`NotImplementedError` when the context is created. + +Integrators: ``langevin``, ``langevinMiddle``, ``variableLangevin`` and +``brownian`` follow the algorithms of the corresponding OpenMM Reference +implementations. Random numbers differ from OpenMM's, so trajectories agree +statistically, not bit by bit. + +Threads: ``POLYCHROM_NATIVE_THREADS``, else ``OMP_NUM_THREADS``, else +``OPENMM_CPU_THREADS``, else one thread per 500 particles up to the number of +CPUs available to the process. On shared machines, set it explicitly to the +number of cores you have to yourself. + +Instruction set: on x86-64 CPUs with AVX2 and FMA, a build of the engine for +x86-64-v3 is used (same results, faster). ``POLYCHROM_NATIVE_ISA=baseline`` +selects the generic build; :data:`ENGINE_ISA` tells which one is in use. +""" + +import copy +import os +import re +import warnings +import xml.etree.ElementTree as ET + +import numpy as np +import openmm +import simtk.unit as u + +from polychrom import _native_engine as _native_engine_baseline + + +def _select_engine_module(): + """The x86-64-v3 build of the engine if it is installed and the CPU supports + it, unless POLYCHROM_NATIVE_ISA=baseline; else the generic build.""" + if ( + os.environ.get("POLYCHROM_NATIVE_ISA", "").lower() != "baseline" + and _native_engine_baseline.cpu_supports_x86_64_v3() + ): + try: + from polychrom import _native_engine_x86_64_v3 + + return _native_engine_x86_64_v3, "x86-64-v3" + except ImportError: + pass + return _native_engine_baseline, "baseline" + + +_native_engine, ENGINE_ISA = _select_engine_module() + +nm = u.nanometer +ps = u.picosecond +kJ_mol = u.kilojoule_per_mole + +# Tables (energy and derivative per knot) start with this many knots and are +# refined by doubling until the cubic Hermite interpolant of the derivative is +# within TABLE_TOL (relative to its maximum) of OpenMM at the interval midpoints. +PAIR_KNOTS = (513, 8193) +ANGLE_KNOTS = (1025, 8193) +BOND_KNOTS = (2049, 16385) +TABLE_TOL = 1e-6 +TABLE_WARN = 1e-4 # warn if a table cannot reach this accuracy +TABLE_E_CAP = 250.0 # kJ/mol (~100 kT) above the minimum: steeper regions are never sampled and not checked +MAX_TABLES = 64 # per force; more distinct parameter sets are rejected + + +def _val(x, unit=None): + if u.is_quantity(x): + return x.value_in_unit(unit) if unit is not None else x._value + return x + + +def _array(x, unit): + """Quantity / list of Vec3 / array -> float64 numpy array in `unit`.""" + if u.is_quantity(x): + x = x.value_in_unit(unit) + return np.asarray([list(v) for v in x] if isinstance(x, (list, tuple)) else x, dtype=np.float64) + + +PARTICLES_PER_THREAD = 500 + + +def _thread_count(N): + """Threads for N particles: POLYCHROM_NATIVE_THREADS, OMP_NUM_THREADS or + OPENMM_CPU_THREADS if set, else one per PARTICLES_PER_THREAD particles, up to + the number of CPUs this process may use. Small systems do not gain from more + threads, and on a busy shared machine every time step waits for the slowest + thread at each barrier.""" + for var in ("POLYCHROM_NATIVE_THREADS", "OMP_NUM_THREADS", "OPENMM_CPU_THREADS"): + v = os.environ.get(var) + if v: + return int(v) + try: + ncpu = len(os.sched_getaffinity(0)) + except AttributeError: # not on Linux + ncpu = os.cpu_count() or 1 + return max(1, min(ncpu, N // PARTICLES_PER_THREAD)) + + +class NativePlatform: + """Stand-in for an OpenMM Platform object.""" + + def getName(self): + return "native" + + def getSpeed(self): + return 10.0 + + +# --------------------------------------------------------------------------- +# Integrator +# --------------------------------------------------------------------------- + + +class NativeIntegrator: + """Stand-in for an OpenMM integrator; steps the native engine of its context.""" + + KINDS = ("langevin", "langevinmiddle", "variablelangevin", "brownian") + + def __init__(self, kind, temperature, collision_rate, timestep=None, error_tol=None): + kind = kind.lower() + if kind not in self.KINDS: + raise NotImplementedError( + f"integrator {kind!r} is not supported by the native platform; use one of {self.KINDS}" + ) + self.kind = kind + self._temperature = float(_val(temperature, u.kelvin)) + self._friction = float(_val(collision_rate, 1 / ps)) + self._dt = float(_val(timestep, ps)) if timestep is not None else 0.0 + self._error_tol = float(error_tol) if error_tol is not None else 0.0 + self._seed = 0 + self._max_dt = 0.0 + self._engine = None + if kind == "variablelangevin" and not self._error_tol > 0: + raise ValueError("variableLangevin needs error_tol > 0") + if kind != "variablelangevin" and not self._dt > 0: + raise ValueError(f"{kind} needs a positive timestep") + + def _bind(self, engine): + self._engine = engine + engine.set_integrator(self.kind, self._temperature, self._friction, self._dt, self._error_tol) + seed = self._seed if self._seed != 0 else int.from_bytes(os.urandom(8), "little") or 1 + engine.set_seed(seed) + if self._max_dt > 0: + engine.set_max_step_size(self._max_dt) + + def _require_engine(self): + if self._engine is None: + raise RuntimeError("integrator is not bound to a context yet") + return self._engine + + def step(self, steps): + self._require_engine().step(int(steps)) + + def getStepSize(self): + dt = self._engine.get_step_size() if self._engine is not None else self._dt + return dt * ps + + def setStepSize(self, dt): + self._dt = float(_val(dt, ps)) + if self._engine is not None: + self._engine.set_step_size(self._dt) + + def getTemperature(self): + return self._temperature * u.kelvin + + def setTemperature(self, t): + self._temperature = float(_val(t, u.kelvin)) + if self._engine is not None: + self._engine.set_temperature(self._temperature) + + def getFriction(self): + return self._friction / ps + + def setFriction(self, g): + self._friction = float(_val(g, 1 / ps)) + if self._engine is not None: + self._engine.set_friction(self._friction) + + def getErrorTolerance(self): + return self._error_tol + + def setErrorTolerance(self, tol): + self._error_tol = float(tol) + if self._engine is not None: + self._engine.set_error_tolerance(self._error_tol) + + def setMaximumStepSize(self, dt): + self._max_dt = float(_val(dt, ps)) + if self._engine is not None: + self._engine.set_max_step_size(self._max_dt) + + def getRandomNumberSeed(self): + return self._seed + + def setRandomNumberSeed(self, seed): + self._seed = int(seed) + if self._engine is not None and self._seed != 0: + self._engine.set_seed(self._seed) + + +# --------------------------------------------------------------------------- +# State +# --------------------------------------------------------------------------- + + +class NativeState: + """Stand-in for an OpenMM State.""" + + def __init__(self, time, step, positions=None, velocities=None, forces=None, ekin=None, epot=None, box=None): + self._time, self._step = time, step + self._pos, self._vel, self._forces = positions, velocities, forces + self._ekin, self._epot, self._box = ekin, epot, box + + @staticmethod + def _need(x, what): + if x is None: + raise RuntimeError(f"{what} were not requested in getState()") + return x + + def getTime(self): + return self._time * ps + + def getStepCount(self): + return self._step + + def getPositions(self, asNumpy=False): + x = self._need(self._pos, "positions") + return x * nm if asNumpy else [openmm.Vec3(*v) for v in x] * nm + + def getVelocities(self, asNumpy=False): + x = self._need(self._vel, "velocities") + return x * (nm / ps) if asNumpy else [openmm.Vec3(*v) for v in x] * (nm / ps) + + def getForces(self, asNumpy=False): + x = self._need(self._forces, "forces") + return x * (kJ_mol / nm) if asNumpy else [openmm.Vec3(*v) for v in x] * (kJ_mol / nm) + + def getKineticEnergy(self): + return self._need(self._ekin, "energies") * kJ_mol + + def getPotentialEnergy(self): + return self._need(self._epot, "energies") * kJ_mol + + def getPeriodicBoxVectors(self, asNumpy=False): + b = self._box + vecs = [openmm.Vec3(b[0], 0, 0), openmm.Vec3(0, b[1], 0), openmm.Vec3(0, 0, b[2])] + return (np.diag(b) * nm) if asNumpy else vecs * nm + + +# --------------------------------------------------------------------------- +# Tabulation of custom forces +# --------------------------------------------------------------------------- + + +class _Batch: + """Evaluate a small configuration (pair, bond or angle) of a force for many + values of its coordinate at once: SLOTS well-separated copies live in one + Reference-platform context, so one getState() call yields SLOTS exact + derivatives. Energies of a single configuration come from filling all slots + with it. + """ + + SLOTS = 1024 + + def __init__(self, root, kind, params, spacing): + self.kind = kind + self.spacing = spacing + M = self.SLOTS + # Copy everything but the (possibly huge) per-particle/bond/angle lists. + big, tag = { + "pair": (("Particles", "Exclusions", "InteractionGroups"), "Particle"), + "bond": (("Bonds",), "Bond"), + "angle": (("Angles",), "Angle"), + }[kind] + small = ET.Element(root.tag, dict(root.attrib)) + for child in root: + if child.tag in big: + ET.SubElement(small, child.tag) + else: + small.append(copy.deepcopy(child)) + root = small + if kind == "pair": + root.set("method", "1") # CutoffNonPeriodic + root.set("useLongRangeCorrection", "0") + container, per = root.find("Particles"), 2 + else: + root.set("usesPeriodic", "0") + container, per = root.find("Bonds" if kind == "bond" else "Angles"), 2 if kind == "bond" else 3 + proto = tag + for k in range(M): + if kind == "pair": + for prm in params: + e = ET.SubElement(container, proto) + for q, v in enumerate(prm): + e.set(f"param{q + 1}", repr(v)) + else: + e = ET.SubElement(container, proto) + for q in range(per): + e.set(f"p{q + 1}", str(per * k + q)) + for q, v in enumerate(params): + e.set(f"param{q + 1}", repr(v)) + self.per = per + system = openmm.System() + for _ in range(per * M): + system.addParticle(1.0) + system.addForce(openmm.XmlSerializer.deserialize(ET.tostring(root, encoding="unicode"))) + self.ctx = openmm.Context( + system, openmm.VerletIntegrator(0.001), openmm.Platform.getPlatformByName("Reference") + ) + self.offsets = np.zeros((M, 3)) + self.offsets[:, 1] = np.arange(M) * spacing + + def _positions(self, xs): + M = self.SLOTS + pos = np.zeros((M, self.per, 3)) + pos += self.offsets[:, None, :] + if self.kind == "angle": # i on the x axis, j at the origin, k on the unit circle + pos[:, 0, 0] += 1.0 + pos[:, 2, 0] += np.cos(xs) + pos[:, 2, 1] += np.sin(xs) + else: # second particle on the x axis + pos[:, 1, 0] += xs + return pos.reshape(-1, 3) + + def derivative(self, xs): + """dE/dx at each x (x = distance, or angle in radians).""" + xs = np.asarray(xs, dtype=float) + out = np.empty(len(xs)) + M = self.SLOTS + for start in range(0, len(xs), M): + chunk = xs[start : start + M] + full = np.full(M, chunk[0]) + full[: len(chunk)] = chunk + self.ctx.setPositions(self._positions(full) * nm) + F = self.ctx.getState(getForces=True).getForces(asNumpy=True).value_in_unit(kJ_mol / nm) + F = F.reshape(M, self.per, 3) + if self.kind == "angle": # dE/dtheta = -f_k . e_theta + D = -(F[:, 2, 0] * -np.sin(full) + F[:, 2, 1] * np.cos(full)) + else: # dE/dr = -f_2 . e_x + D = -F[:, 1, 0] + out[start : start + len(chunk)] = D[: len(chunk)] + return out + + def energy(self, x): + self.ctx.setPositions(self._positions(np.full(self.SLOTS, float(x))) * nm) + return self.ctx.getState(getEnergy=True).getPotentialEnergy().value_in_unit(kJ_mol) / self.SLOTS + + +def _hermite_derivative(x, E, D, xq): + """Derivative of the cubic Hermite interpolant (uniform knots x, values E, slopes D) at xq.""" + h = x[1] - x[0] + k = np.clip(((xq - x[0]) / h).astype(int), 0, len(x) - 2) + t = (xq - x[k]) / h + e0, e1, m0, m1 = E[k], E[k + 1], D[k] * h, D[k + 1] * h + c1, c2, c3 = m0, -3 * e0 - 2 * m0 + 3 * e1 - m1, 2 * e0 + m0 - 2 * e1 + m1 + return (c1 + t * (2 * c2 + t * 3 * c3)) / h + + +def _integrate(x, D, Dm, energy_at, anchor, what): + """E on knots x by Simpson integration of D (knots) and Dm (midpoints). + + Integrates over the run of finite intervals that contains the knot nearest to + `anchor`, where E is evaluated directly. Returns (E, lo, hi): E is NaN + outside the finite window [lo, hi] of knot indices. + """ + n = len(x) + h = x[1] - x[0] + ok_knot = np.isfinite(D) + ok_int = ok_knot[1:] & ok_knot[:-1] & np.isfinite(Dm) + ia = int(np.clip(round((anchor - x[0]) / h), 0, n - 1)) + if not ok_knot[ia]: + finite = np.flatnonzero(ok_knot) + if len(finite) == 0: + raise ValueError(f"{what}: the force is not finite anywhere on the table range") + ia = finite[np.argmin(np.abs(finite - ia))] + lo = ia + while lo > 0 and ok_int[lo - 1]: + lo -= 1 + hi = ia + while hi < n - 1 and ok_int[hi]: + hi += 1 + E = np.full(n, np.nan) + with np.errstate(all="ignore"): + integ = h / 6 * (D[:-1] + 4 * Dm + D[1:]) # E[k+1] - E[k] + E[ia] = energy_at(x[ia]) + if not np.isfinite(E[ia]): + raise ValueError(f"{what}: energy is not finite at x = {x[ia]}") + E[ia + 1 : hi + 1] = E[ia] + np.cumsum(integ[ia:hi]) + E[lo:ia] = E[ia] - np.cumsum(integ[lo:ia][::-1])[::-1] + return E, lo, hi + + +def _quarter_error(deriv, x, E, D, lo, hi): + """Relative error of the interpolated derivative at the quarter points of + the finite intervals whose energy is within TABLE_E_CAP of the minimum; + returns (max error, interval index of the max, xq, Dq).""" + h = x[1] - x[0] + n = len(x) + xq = np.concatenate([x[:-1] + 0.25 * h, x[:-1] + 0.75 * h]) + with np.errstate(all="ignore"): + Dq = deriv(xq) + sel = np.concatenate([np.arange(n - 1)] * 2) + with np.errstate(invalid="ignore"): + low = np.minimum(E[:-1], E[1:]) <= np.nanmin(E) + TABLE_E_CAP # per interval + good = (sel >= lo) & (sel < hi) & np.isfinite(Dq) & low[sel] + if not good.any(): + return 0.0, 0, xq, Dq + err = np.abs(_hermite_derivative(x, E, D, xq[good]) - Dq[good]) / (np.abs(Dq[good]) + 1.0) + k = int(np.argmax(err)) + return float(err[k]), int(sel[good][k]), xq, Dq + + +def _locate_kink(deriv, a, b): + """Position of a jump in dD/dx (a kink of the force) inside [a, b], by zooming.""" + for _ in range(4): + xs = np.linspace(a, b, 65) + with np.errstate(all="ignore"): + d2 = np.abs(np.diff(deriv(xs), 2)) + k = int(np.nanargmax(d2)) + 1 # second difference is centred on xs[k] + a, b = xs[max(k - 1, 0)], xs[min(k + 1, 64)] + return 0.5 * (a + b) + + +def _table(deriv, energy_at, x0, x1, knots, anchor, what, extend=True): + """Tabulate E and dE/dx on uniform knots in [x0, x1'] (x1' >= x1). + + dE/dx comes from deriv(xs) (exact, batched). E is obtained by integrating + dE/dx with Simpson's rule from the knot nearest to `anchor`, where E is + evaluated directly. The resolution is doubled (from knots[0] up to knots[1] + knots) until the derivative of the cubic Hermite interpolant agrees with + deriv() at the quarter points of every interval to + TABLE_TOL * (|dE/dx| + 1 kJ/mol/nm). If that fails because the force has a + kink (e.g. where smooth_square_well switches from repulsion to attraction), + the knot spacing is adjusted so that a knot falls exactly on the kink; the + table may then extend slightly beyond x1 (only if `extend`). Where dE/dx is not finite (e.g. + beyond the range of FENE bonds), the table is extrapolated linearly from the + finite range, with a warning. + """ + n, nmax = knots + x = np.linspace(x0, x1, n) + with np.errstate(all="ignore"): + D = deriv(x) + Dm = deriv(0.5 * (x[1:] + x[:-1])) + best = None + prev_err = None + aligned = not extend + while True: + E, lo, hi = _integrate(x, D, Dm, energy_at, anchor, what) + err, kbad, xq, Dq = _quarter_error(deriv, x, E, D, lo, hi) + if best is None or err < best[-1]: + best = (x, D, E, lo, hi, err) + if err <= TABLE_TOL or 2 * len(x) - 1 > nmax: + break + # cubic Hermite gains ~8x per doubling where the force is smooth + slow = prev_err is not None and err > 0.3 * prev_err + if slow and not aligned and lo < kbad < hi - 1: + # A kink strictly inside the finite range (not a singularity at its + # edge): put a knot on it and (as closely as possible) on x1, which is + # a kink too for pair potentials that vanish at the cutoff. Later + # doublings keep both on knots. + aligned = True + h = x[1] - x[0] + xk = _locate_kink(deriv, x[kbad], x[kbad + 1]) + if xk - x0 > 4 * h: + m0 = int(round((xk - x0) / h)) + ratio = (x1 - x0) / (xk - x0) + ms = np.arange(max(1, m0 // 2), 2 * m0 + 1) + frac = np.abs(ms * ratio - np.round(ms * ratio)) + good = ms[frac <= 1e-4] + m = int(good[0]) if len(good) else int(ms[np.argmin(frac)]) + h2 = (xk - x0) / m + n2 = int(np.ceil((x1 - x0) / h2 - 1e-6)) + 1 + if n2 <= nmax: + x = x0 + h2 * np.arange(n2) + with np.errstate(all="ignore"): + D = deriv(x) + Dm = deriv(0.5 * (x[1:] + x[:-1])) + prev_err = None + continue + if slow and err > 0.9 * prev_err: + # No improvement: the error is noise in OpenMM's own derivative (e.g. + # of the angle near theta = pi). Keep the best table. + break + prev_err = err + # refine: midpoints become knots, quarter points become midpoints + n = len(x) + xn = np.empty(2 * n - 1) + Dn = np.empty(2 * n - 1) + xn[0::2], xn[1::2] = x, 0.5 * (x[1:] + x[:-1]) + Dn[0::2], Dn[1::2] = D, Dm + order = np.argsort(xq) + x, D, Dm = xn, Dn, Dq[order] + x, D, E, lo, hi, err = best + if err > TABLE_WARN: + warnings.warn(f"{what}: tabulated force has a relative error of up to {err:.1e}") + if lo > 0 or hi < len(x) - 1: + D = D.copy() + E[:lo] = E[lo] + D[lo] * (x[:lo] - x[lo]) + D[:lo] = D[lo] + E[hi + 1 :] = E[hi] + D[hi] * (x[hi + 1 :] - x[hi]) + D[hi + 1 :] = D[hi] + warnings.warn( + f"{what}: the force is not finite for x < {x[lo]:.4g} or x > {x[hi]:.4g}; " + "the native platform extrapolates linearly there" + ) + return x, E, D + + +def _force_xml(force): + return ET.fromstring(openmm.XmlSerializer.serialize(force)) + + +def _param_tuple(elem, n): + return tuple(float(elem.get(f"param{k + 1}")) for k in range(n)) + + +def _set_global_defaults(root, values): + gp = root.find("GlobalParameters") + if gp is not None: + for p in gp: + if p.get("name") in values: + p.set("default", repr(float(values[p.get("name")]))) + + +def _pair_table(root, params_a, params_b, cutoff, what): + """E(r), dE/dr on [0, cutoff] of a CustomNonbondedForce between two particles.""" + b = _Batch(root, "pair", (params_a, params_b), spacing=3 * cutoff) + lo, hi = 1e-6 * cutoff, cutoff * (1 - 1e-12) # no direction at r = 0; stay inside the cutoff + + def deriv(r): + return np.where(r < cutoff, b.derivative(np.clip(r, lo, hi)), 0.0) + + def energy(r): + return b.energy(min(max(r, lo), hi)) if r < cutoff else 0.0 + + return _table(deriv, energy, 0.0, cutoff, PAIR_KNOTS, cutoff, what) + + +ANGLE_COS_SPLIT = 0.25 # rad: cos(theta) tables stop this far from a non-flat end + + +def _angle_table(root, params, what): + """Tables of a CustomAngleForce for one parameter set. + + Returns (E_theta, D_theta, cos_table) where the first two tabulate E and + dE/dtheta on [0, pi], and cos_table is None or (c_lo, c_hi, E, dE/dcos). + The engine uses the cos table (no atan2 per angle and step) for + cos(theta) in [c_lo, c_hi] and the theta table elsewhere. dE/dcos = + -dE/dtheta / sin(theta) is finite at theta = pi (or 0) only if the potential + is flat there; otherwise the cos table stops ANGLE_COS_SPLIT short of it. + """ + b = _Batch(root, "angle", params, spacing=10.0) + eps = 1e-5 # OpenMM's angle derivative is inaccurate within ~1e-6 rad of 0 and pi + + def deriv_theta(th): + return b.derivative(np.clip(th, eps, np.pi - eps)) + + _, Et, Dt = _table(deriv_theta, b.energy, 0.0, np.pi, ANGLE_KNOTS, 0.5 * np.pi, what, extend=False) + if not (np.all(np.isfinite(Et)) and np.all(np.isfinite(Dt))): + raise ValueError(f"{what}: energy is not finite for all angles") + d_end = deriv_theta(np.array([1e-4, np.pi - 1e-4])) + flat = np.abs(d_end) <= 1e-3 * max(np.abs(Dt).max(), 1e-300) # at theta = 0, pi + c_hi = 1.0 if flat[0] else np.cos(ANGLE_COS_SPLIT) + c_lo = -1.0 if flat[1] else -np.cos(ANGLE_COS_SPLIT) + + def deriv_cos_inner(c): # dE/dcos = -dE/dtheta / sin(theta), for |c| < 1 + td = np.arccos(c) + return b.derivative(td) / -np.sin(td) + + def deriv_cos(c): + """At c = +-1 the limit is taken by quadratic extrapolation from c -+ 1e-3 k + (k = 1, 2, 3), which ignores sub-1e-3 features such as the one caused by + the truncated pi in forces.grosberg_angle.""" + c = np.asarray(c, dtype=float) + out = np.empty_like(c) + inner = np.abs(c) < 1 - 1e-12 + if inner.any(): + out[inner] = deriv_cos_inner(c[inner]) + for end in (-1.0, 1.0): + at_end = ~inner & (np.sign(c) == end) + if at_end.any(): + d = deriv_cos_inner(end - end * 1e-3 * np.arange(1, 4)) + out[at_end] = 3 * d[0] - 3 * d[1] + d[2] + return out + + def energy_cos(c): + return b.energy(np.arccos(np.clip(c, -1, 1))) + + _, Ec, Dc = _table(deriv_cos, energy_cos, c_lo, c_hi, ANGLE_KNOTS, 0.5 * (c_lo + c_hi), what, extend=False) + return Et, Dt, (c_lo, c_hi, Ec, Dc) + + +def _bond_table(root, params, rmax, what): + b = _Batch(root, "bond", params, spacing=2 * rmax + 10) + + def deriv(r): + return b.derivative(np.maximum(r, 1e-7)) + + # anchor: the force-free point (usually the rest length) if inside the range + r = np.linspace(0, rmax, 257) + with np.errstate(all="ignore"): + d = np.abs(deriv(r)) + anchor = r[np.nanargmin(np.where(np.isfinite(d), d, np.nan))] if np.isfinite(d).any() else 0.5 * rmax + return _table(deriv, lambda x: b.energy(max(x, 1e-7)), 0.0, rmax, BOND_KNOTS, anchor, what) + + +# --------------------------------------------------------------------------- +# External forces recognised by expression +# --------------------------------------------------------------------------- + +_SPHERICAL = ( + "step(invert_sign*(r-aa)) * kb * (sqrt((r-aa)*(r-aa) + t*t) - t); " + "r = sqrt((x-x0)^2 + (y-y0)^2 + (z-z0)^2 + tt^2)" +) +_TETHER = "kx * (x - x0)^2 + ky * (y - y0)^2 + kz * (z - z0)^2" +_TETHER_PBC = ( + "kx * periodicdistance(x, 0, 0, x0, 0, 0)^2 + ky * periodicdistance(0, y, 0, 0, y0, 0)^2 " + "+ kz * periodicdistance(0, 0, z, 0, 0, z0)^2" +) + + +def _strip_prefix(energy, name): + return re.sub(r"(? update function + self._engine = _native_engine.NativeEngine(self._N) + self._engine.set_threads(_thread_count(self._N)) + masses = np.array([_val(system.getParticleMass(i), u.dalton) for i in range(self._N)]) + self._engine.set_masses(masses) + if self._pbc: + a, b, c = system.getDefaultPeriodicBoxVectors() + self._box = np.array([_val(a, nm)[0], _val(b, nm)[1], _val(c, nm)[2]]) + self._engine.set_box(True, *self._box) + else: + self._box = np.zeros(3) + self._engine.set_box(False) + for f in self._forces: + self._add_force(f) + integrator._bind(self._engine) + + # -- force translation --------------------------------------------------- + def _globals(self, f): + names = [] + if hasattr(f, "getNumGlobalParameters"): + for i in range(f.getNumGlobalParameters()): + name = f.getGlobalParameterName(i) + names.append(name) + if name not in self._params: + self._params[name] = float(f.getGlobalParameterDefaultValue(i)) + return names + + def _add_force(self, f): + name = getattr(f, "name", type(f).__name__) + if f.getForceGroup() != 0: + warnings.warn(f"force {name}: force groups are ignored by the native platform") + if isinstance(f, openmm.HarmonicBondForce): + handler = self._add_harmonic_bonds(f) + elif isinstance(f, openmm.CustomBondForce): + handler = self._add_custom_bonds(f, name) + elif isinstance(f, openmm.CustomAngleForce): + handler = self._add_custom_angles(f, name) + elif isinstance(f, openmm.CustomNonbondedForce): + handler = self._add_custom_nonbonded(f, name) + elif isinstance(f, openmm.CustomExternalForce): + handler = self._add_external(f, name) + else: + raise NotImplementedError(f"force {name} ({type(f).__name__}) is not supported by the native platform") + self._handlers[id(f)] = handler + self._redirect_update(f, handler) + + def _redirect_update(self, f, handler): + cls_update = type(f).updateParametersInContext + native_ctx = self + + def updateParametersInContext(context): + if context is native_ctx: + handler() + else: + cls_update(f, context) + + f.updateParametersInContext = updateParametersInContext + + def _add_harmonic_bonds(self, f): + s = self._engine.add_bond_set(False, f.usesPeriodicBoundaryConditions()) + + def update(): + root = _force_xml(f) + bonds = root.find("Bonds") + n = len(bonds) + i = np.fromiter((int(b.get("p1")) for b in bonds), np.intc, n) + j = np.fromiter((int(b.get("p2")) for b in bonds), np.intc, n) + d = np.fromiter((float(b.get("d")) for b in bonds), np.float64, n) + k = np.fromiter((float(b.get("k")) for b in bonds), np.float64, n) + self._engine.set_harmonic_bonds(s, i, j, d, k) + + update() + return update + + def _add_custom_bonds(self, f, name): + if f.getNumBonds() == 0: + return lambda: None + s = self._engine.add_bond_set(True, f.usesPeriodicBoundaryConditions()) + globals_ = self._globals(f) + npar = f.getNumPerBondParameters() + rmax = 8.0 * self._length_scale + + def update(): + root = _force_xml(f) + _set_global_defaults(root, {g: self._params[g] for g in globals_}) + bonds = root.find("Bonds") + keys = [_param_tuple(b, npar) for b in bonds] + uniq = sorted(set(keys)) + if len(uniq) > MAX_TABLES: + raise NotImplementedError(f"force {name}: more than {MAX_TABLES} distinct bond parameter sets") + self._engine.clear_bond_tables(s) + for key in uniq: + x, E, D = _bond_table(root, key, rmax, f"bond force {name}") + self._engine.add_bond_table(s, x[0], x[-1], E, D) + index = {key: t for t, key in enumerate(uniq)} + i = [int(b.get("p1")) for b in bonds] + j = [int(b.get("p2")) for b in bonds] + self._engine.set_tabulated_bonds(s, i, j, [index[k] for k in keys]) + + update() + return update + + def _add_custom_angles(self, f, name): + if f.getNumAngles() == 0: + return lambda: None + s = self._engine.add_angle_set(f.usesPeriodicBoundaryConditions()) + globals_ = self._globals(f) + npar = f.getNumPerAngleParameters() + + def update(): + root = _force_xml(f) + _set_global_defaults(root, {g: self._params[g] for g in globals_}) + angles = root.find("Angles") + keys = [_param_tuple(a, npar) for a in angles] + uniq = sorted(set(keys)) + if len(uniq) > MAX_TABLES: + raise NotImplementedError(f"force {name}: more than {MAX_TABLES} distinct angle parameter sets") + self._engine.clear_angle_tables(s) + for key in uniq: + Et, Dt, (c_lo, c_hi, Ec, Dc) = _angle_table(root, key, f"angle force {name}") + self._engine.add_angle_table(s, Et, Dt, c_lo, c_hi, Ec, Dc) + index = {key: t for t, key in enumerate(uniq)} + self._engine.set_angles( + s, + [int(a.get("p1")) for a in angles], + [int(a.get("p2")) for a in angles], + [int(a.get("p3")) for a in angles], + [index[k] for k in keys], + ) + + update() + return update + + def _add_custom_nonbonded(self, f, name): + if f.getNumInteractionGroups() > 0: + raise NotImplementedError(f"force {name}: interaction groups are not supported by the native platform") + if f.getNonbondedMethod() == f.NoCutoff: + raise NotImplementedError(f"force {name}: the native platform needs a cutoff") + if f.getNumComputedValues() if hasattr(f, "getNumComputedValues") else 0: + raise NotImplementedError(f"force {name}: computed values are not supported") + cutoff = float(_val(f.getCutoffDistance(), nm)) + if self._pbc and cutoff >= 0.5 * self._box.min(): + raise ValueError(f"force {name}: cutoff {cutoff} must be below half the periodic box") + globals_ = self._globals(f) + npar = f.getNumPerParticleParameters() + state = {} + + def build(first): + root = _force_xml(f) + _set_global_defaults(root, {g: self._params[g] for g in globals_}) + particles = root.find("Particles") + keys = [_param_tuple(p, npar) for p in particles] + uniq = sorted(set(keys)) + if len(uniq) > MAX_TABLES: + raise NotImplementedError(f"force {name}: more than {MAX_TABLES} distinct per-particle parameter sets") + index = {key: t for t, key in enumerate(uniq)} + types = np.array([index[k] for k in keys], dtype=np.intc) + if first: + state["s"] = self._engine.add_pair_force(cutoff, default_skin(cutoff), len(uniq), types) + elif len(uniq) != state["ntypes"] or not np.array_equal(types, state["types"]): + raise NotImplementedError( + f"force {name}: changing per-particle parameters after context creation is not supported " + "by the native platform; call Simulation.reinitialize()" + ) + s = state["s"] + state["ntypes"], state["types"] = len(uniq), types + for a in range(len(uniq)): + for b in range(a, len(uniq)): + x, E, D = _pair_table(root, uniq[a], uniq[b], cutoff, f"nonbonded force {name}") + self._engine.set_pair_table(s, a, b, x[0], x[-1], E, D) + if a != b: + self._engine.set_pair_table(s, b, a, x[0], x[-1], E, D) + excl = root.find("Exclusions") + ei = [int(e.get("p1")) for e in excl] if excl is not None else [] + ej = [int(e.get("p2")) for e in excl] if excl is not None else [] + self._engine.set_pair_exclusions(s, ei, ej) + + build(True) + return lambda: build(False) + + def _add_external(self, f, name): + energy = _strip_prefix(f.getEnergyFunction(), name) + self._globals(f) # registers the force's global parameters, read through g() below + n = f.getNumParticles() + particles = np.empty(n, dtype=np.intc) + params = np.empty((n, f.getNumPerParticleParameters())) + for k in range(n): + p, par = f.getParticleParameters(k) + particles[k] = p + params[k] = par + + def g(key): + return self._params[f"{name}_{key}" if f"{name}_{key}" in self._params else key] + + if energy == _SPHERICAL: + s = self._engine.add_spherical_confinement(particles, 0, 0, 0, 0, 1, 0, 0, 0) + + def update(): + self._engine.set_spherical_confinement( + s, g("kb"), g("aa"), g("t"), g("tt"), g("invert_sign"), g("x0"), g("y0"), g("z0") + ) + + elif energy in (_TETHER, _TETHER_PBC): + pbc = energy == _TETHER_PBC + s = self._engine.add_tether(particles, params[:, :3], 0, 0, 0, pbc) + + def update(): + self._engine.set_tether_k(s, g("kx"), g("ky"), g("kz")) + + else: + raise NotImplementedError( + f"force {name}: CustomExternalForce with energy {f.getEnergyFunction()!r} is not supported " + "by the native platform (supported: spherical_confinement, tether_particles)" + ) + update() + return update + + # -- OpenMM Context API ------------------------------------------------------ + def getSystem(self): + return self._system + + def getIntegrator(self): + return self._integrator + + def getPlatform(self): + return NativePlatform() + + def setPositions(self, positions): + x = _array(positions, nm) + if x.shape != (self._N, 3): + raise ValueError(f"expected positions of shape ({self._N}, 3), got {x.shape}") + self._engine.set_positions(x) + + def setVelocities(self, velocities): + v = _array(velocities, nm / ps) + if v.shape != (self._N, 3): + raise ValueError(f"expected velocities of shape ({self._N}, 3), got {v.shape}") + self._engine.set_velocities(v) + + def setVelocitiesToTemperature(self, temperature, randomSeed=None): + seed = randomSeed if randomSeed is not None else int.from_bytes(os.urandom(8), "little") + self._engine.set_velocities_to_temperature(float(_val(temperature, u.kelvin)), seed) + + def getTime(self): + return self._engine.get_time() * ps + + def setTime(self, t): + self._engine.set_time(float(_val(t, ps))) + + def getStepCount(self): + return self._engine.get_step_count() + + def getParameter(self, name): + return self._params[name] + + def getParameters(self): + return dict(self._params) + + def setParameter(self, name, value): + if name not in self._params: + raise KeyError(f"unknown global parameter {name!r}") + self._params[name] = float(_val(value)) + for f in self._forces: + if hasattr(f, "getNumGlobalParameters") and any( + f.getGlobalParameterName(i) == name for i in range(f.getNumGlobalParameters()) + ): + self._handlers[id(f)]() + + def getState( + self, + getPositions=False, + getVelocities=False, + getForces=False, + getEnergy=False, + getParameters=False, + enforcePeriodicBox=False, + groups=-1, + **kwargs, + ): + e = self._engine + pos = vel = forces = ekin = epot = None + if getPositions: + pos = e.get_positions() + if enforcePeriodicBox and self._pbc: + pos = pos - np.floor(pos / self._box) * self._box + if getVelocities: + vel = e.get_velocities() + if getForces: + forces = e.get_forces() + if getEnergy: + epot = e.potential_energy() + ekin = e.kinetic_energy() + return NativeState(e.get_time(), e.get_step_count(), pos, vel, forces, ekin, epot, self._box) + + def reinitialize(self, preserveState=False): + st = self.getState(getPositions=True, getVelocities=True) if preserveState else None + t = self._engine.get_time() + self.__init__(self._system, self._integrator, self._forces, self._pbc, self._length_scale) + if st is not None: + self._engine.set_positions(st._pos) + self._engine.set_velocities(st._vel) + self._engine.set_time(t) + + # -- extras ------------------------------------------------------------------ + def minimize(self, tolerance=10.0, maxIterations=0): + """Local energy minimisation with OpenMM's L-BFGS on its CPU platform.""" + integ = openmm.VerletIntegrator(0.001) + ctx = openmm.Context(self._system, integ, openmm.Platform.getPlatformByName("CPU")) + ctx.setPositions(self._engine.get_positions() * nm) + for name, value in self._params.items(): + ctx.setParameter(name, value) + openmm.LocalEnergyMinimizer.minimize(ctx, tolerance, maxIterations) + self._engine.set_positions(ctx.getState(getPositions=True).getPositions(asNumpy=True).value_in_unit(nm)) + del ctx + + @property + def engine(self): + return self._engine + + +def default_skin(cutoff): + """Verlet-list skin. Polymer beads move ~1-2% of a bond per step, so lists + are rebuilt every few steps; a large skin keeps rebuilds rare.""" + return 0.75 * cutoff diff --git a/polychrom/simulation.py b/polychrom/simulation.py index 593874e..28a8775 100644 --- a/polychrom/simulation.py +++ b/polychrom/simulation.py @@ -212,6 +212,9 @@ def __init__(self, **kwargs): CUDA (preferred fast GPU platform) OpenCL (maybe slower GPU platofrm, does not need CUDA installed) CPU (medium speed parallelized CPU platform) + native (polychrom's own multi-threaded CPU engine, much faster than + OpenMM's CPU platform; see :mod:`polychrom.native` for supported forces + and integrators) reference (slow CPU platform for debug) verbose : bool, optional @@ -294,6 +297,10 @@ def __init__(self, **kwargs): platform_object = openmm.Platform.getPlatformByName("CUDA") elif platform.lower() == "cpu": platform_object = openmm.Platform.getPlatformByName("CPU") + elif platform.lower() == "native": + from polychrom import native + + platform_object = native.NativePlatform() else: raise RuntimeError("Undefined platform: {0}".format(platform)) self.platform = platform_object @@ -303,7 +310,20 @@ def __init__(self, **kwargs): self.collisionRate = kwargs["collision_rate"] * (1 / picosecond) self.integrator_type = kwargs["integrator"] - if isinstance(self.integrator_type, str): + self.native = platform.lower() == "native" + if self.native: + if not isinstance(self.integrator_type, str): + raise NotImplementedError("the native platform does not support user-defined integrators") + from polychrom import native + + self.integrator = native.NativeIntegrator( + self.integrator_type, + self.temperature, + kwargs["collision_rate"], + timestep=kwargs["timestep"] * 1e-3 if "timestep" in kwargs else None, + error_tol=kwargs.get("error_tol"), + ) + elif isinstance(self.integrator_type, str): self.integrator_type = str(self.integrator_type) if self.integrator_type.lower() == "langevin": self.integrator = openmm.LangevinIntegrator( @@ -553,11 +573,25 @@ def _apply_forces(self): {i: j.__getstate__() for i, j in self.force_dict.items()}, ) - self.context = openmm.Context(self.system, self.integrator, self.platform, self.properties) + self._create_context() self.init_positions() self.init_velocities() self.forces_applied = True + def _create_context(self): + if self.native: + from polychrom import native + + self.context = native.NativeContext( + self.system, + self.integrator, + list(self.force_dict.values()), + pbc=self.PBC, + length_scale=self.length_scale, + ) + else: + self.context = openmm.Context(self.system, self.integrator, self.platform, self.properties) + def initialize(self, **kwargs): """Initialize, particles, velocities for the first time. Only need to use this function if your system has no forces (free Brownian particles). @@ -568,7 +602,7 @@ def initialize(self, **kwargs): self.masses = np.zeros(self.N, dtype=float) + self.kwargs["mass"] for mass in self.masses: self.system.addParticle(mass) - self.context = openmm.Context(self.system, self.integrator, self.platform, self.properties) + self._create_context() self.init_positions() self.init_velocities(**kwargs) @@ -672,7 +706,10 @@ def local_energy_minimization(self, tolerance: float = 0.3, maxIterations=0, ran locTime = self.state.getTime() logging.info("before minimization eK={0}, eP={1}, time={2}".format(eK, eP, locTime)) - openmm.LocalEnergyMinimizer.minimize(self.context, tolerance, maxIterations) # type: ignore + if self.native: + self.context.minimize(tolerance, maxIterations) + else: + openmm.LocalEnergyMinimizer.minimize(self.context, tolerance, maxIterations) # type: ignore self.state = self.context.getState(getPositions=True, getEnergy=True) eK = self.state.getKineticEnergy() / self.N / self.kT diff --git a/setup.py b/setup.py index b38b911..5f93963 100644 --- a/setup.py +++ b/setup.py @@ -1,16 +1,54 @@ +import os +import platform +import sys + import numpy from Cython.Build import cythonize from setuptools import Extension, setup +# The native CPU engine benefits from OpenMP; it still builds without it (single-threaded). +# Extra flags (e.g. "-march=znver3") can be passed via POLYCHROM_NATIVE_CFLAGS. +# No FMA contraction, so that the baseline and the x86-64-v3 build give the same results. +native_compile_args = ["-O3", "-std=c++17", "-fno-math-errno", "-ffp-contract=off"] +native_link_args = [] +if sys.platform != "darwin" and os.environ.get("POLYCHROM_NO_OPENMP") is None: + native_compile_args.append("-fopenmp") + native_link_args.append("-fopenmp") +native_compile_args += os.environ.get("POLYCHROM_NATIVE_CFLAGS", "").split() + # Define Cython extensions ext_modules = [ Extension( "polychrom._polymer_math", ["polychrom/_polymer_math.pyx", "polychrom/__polymer_math.cpp"], include_dirs=[numpy.get_include()], - ) + ), + Extension( + "polychrom._native_engine", + ["polychrom/_native_engine.pyx"], + include_dirs=[numpy.get_include(), "polychrom"], + depends=["polychrom/_native/engine.hpp"], + language="c++", + extra_compile_args=native_compile_args, + extra_link_args=native_link_args, + ), ] +# A second build of the engine for x86-64-v3 CPUs (AVX2, FMA, BMI2: Intel Haswell and AMD +# Zen or newer), selected at run time by polychrom.native. +if platform.machine().lower() in ("x86_64", "amd64") and sys.platform != "win32": + ext_modules.append( + Extension( + "polychrom._native_engine_x86_64_v3", + ["polychrom/_native_engine_x86_64_v3.pyx"], + include_dirs=[numpy.get_include(), "polychrom"], + depends=["polychrom/_native/engine.hpp", "polychrom/_native_engine.pyx"], + language="c++", + extra_compile_args=native_compile_args[:3] + ["-mavx2", "-mfma", "-mbmi2"] + native_compile_args[3:], + extra_link_args=native_link_args, + ) + ) + setup( ext_modules=cythonize(ext_modules, language_level="3"), ) diff --git a/tests/test_native.py b/tests/test_native.py new file mode 100644 index 0000000..30ddd7b --- /dev/null +++ b/tests/test_native.py @@ -0,0 +1,288 @@ +"""Tests of the native CPU platform against OpenMM's Reference platform.""" + +import numpy as np +import pytest + +import polychrom.starting_conformations +from polychrom import forcekits, forces +from polychrom.simulation import Simulation + +native = pytest.importorskip("polychrom.native") + + +def _make(platform, N, data, build, PBCbox=False, integrator="langevin", collision_rate=0.1): + sim = Simulation( + platform=platform, + integrator=integrator, + timestep=70, + error_tol=0.01, + collision_rate=collision_rate, + N=N, + reporters=[], + PBCbox=PBCbox, + verbose=False, + ) + sim.set_data(data, random_offset=0) + build(sim) + sim._apply_forces() + return sim + + +def _forces_energy(sim): + st = sim.context.getState(getForces=True, getEnergy=True) + return np.asarray(st.getForces(asNumpy=True)._value), st.getPotentialEnergy()._value + + +def _compare(build, N=300, PBCbox=False, seed=0, rtol=2e-6, data=None): + rng = np.random.default_rng(seed) + if data is None: + data = polychrom.starting_conformations.grow_cubic(N, 12) + rng.normal(0, 0.15, (N, 3)) + ref = _make("reference", N, data, build, PBCbox) + nat = _make("native", N, data, build, PBCbox) + f_ref, e_ref = _forces_energy(ref) + f_nat, e_nat = _forces_energy(nat) + scale = np.abs(f_ref).max() + np.testing.assert_allclose(f_nat, f_ref, atol=rtol * scale, rtol=0) + assert e_nat == pytest.approx(e_ref, rel=rtol, abs=1e-8) + return ref, nat + + +def _chain(**kw): + def build(sim): + sim.add_force(forcekits.polymer_chains(sim, **kw)) + + return build + + +def test_polymer_chain_open(): + _compare( + _chain( + bond_force_kwargs={"bondLength": 1.0, "bondWiggleDistance": 0.1}, + angle_force_kwargs={"k": 1.5}, + nonbonded_force_kwargs={"trunc": 1.5, "radiusMult": 1.05}, + ) + ) + + +def test_polymer_chain_pbc(): + _compare( + _chain( + bond_force_kwargs={"bondLength": 1.0, "bondWiggleDistance": 0.1}, + angle_force_kwargs={"k": 1.5}, + nonbonded_force_kwargs={"trunc": 3.0}, + ), + PBCbox=[9.0, 9.0, 9.0], + ) + + +def test_smooth_square_well_rings_and_angle_offset(): + def build(sim): + sim.add_force( + forcekits.polymer_chains( + sim, + chains=[(0, 150, True), (150, 300, False)], + angle_force_kwargs={"k": 2.0, "theta_0": 2.5}, # not flat at pi: theta-table path + nonbonded_force_func=forces.smooth_square_well, + nonbonded_force_kwargs={"attractionEnergy": 0.3, "attractionRadius": 1.7}, + ) + ) + + _compare(build) + + +def test_heteropolymer_types_confinement_tether(): + N = 300 + types = np.arange(N) % 3 + + def build(sim): + sim.add_force( + forcekits.polymer_chains( + sim, + nonbonded_force_func=forces.heteropolymer_SSW, + nonbonded_force_kwargs=dict( + interactionMatrix=np.array([[0.1, 0.4, 0.0], [0.4, 0.2, 0.3], [0.0, 0.3, 0.5]]), + monomerTypes=types, + extraHardParticlesIdxs=[5, 17], + ), + ) + ) + sim.add_force(forces.spherical_confinement(sim, r=5.5, k=3)) + sim.add_force(forces.tether_particles(sim, [0, 10, -1], k=[1, 2, 3])) + + _compare(build, N=N) + + +def test_constant_force_bonds(): + def build(sim): + sim.add_force( + forcekits.polymer_chains( + sim, + bond_force_func=forces.constant_force_bonds, + bond_force_kwargs={"bondWiggleDistance": 0.1}, + ) + ) + + _compare(build, rtol=1e-5) + + +def test_grosberg_rings(): + N = 200 + data = polychrom.starting_conformations.grow_cubic(N, 12) # lattice: FENE bonds within range + + def build(sim): + sim.add_force(forcekits.grosberg_polymer_chains(sim, chains=[(0, None, True)])) + + with pytest.warns(UserWarning, match="extrapolates linearly"): + _compare(build, N=N, data=data, rtol=1e-5) + + +def test_update_bonds_and_parameters(): + """Loop-extrusion style bond updates and global parameter changes.""" + N = 300 + lef = {} + + def build(sim): + sim.add_force(forcekits.polymer_chains(sim)) + f = forces.harmonic_bonds(sim, [(10, 50), (100, 180)], bondWiggleDistance=0.2, name="lef", override_checks=True) + lef[id(sim)] = f + sim.add_force(f) + + ref, nat = _compare(build, N=N) + for sim in (ref, nat): + f = lef[id(sim)] + f.setBondParameters(0, 10, 50, 0.5, 0.0) # like bondUpdater: same particles, new parameters + f.setBondParameters(1, 100, 180, 0.5, 500.0) + f.updateParametersInContext(sim.context) + sim.context.setParameter("polynomial_repulsive_REPe", 4.0) + f_ref, e_ref = _forces_energy(ref) + f_nat, e_nat = _forces_energy(nat) + np.testing.assert_allclose(f_nat, f_ref, atol=2e-6 * np.abs(f_ref).max(), rtol=0) + assert e_nat == pytest.approx(e_ref, rel=2e-6) + + +def test_unsupported_force_raises(): + def build(sim): + sim.add_force(forcekits.polymer_chains(sim)) + sim.add_force(forces.pull_force(sim, [0], [[1.0, 0, 0]])) + + with pytest.raises(NotImplementedError, match="Pull"): + _make("native", 50, polychrom.starting_conformations.grow_cubic(50, 8), build) + + +@pytest.mark.parametrize("integrator", ["langevin", "variableLangevin", "langevinMiddle", "brownian"]) +def test_integrators_run_and_thermalise(integrator): + N = 400 + data = polychrom.starting_conformations.grow_cubic(N, 14) + # parameters of the loop extrusion example; Brownian dynamics needs strong friction for a 70 fs step + build = _chain( + bond_force_kwargs={"bondLength": 1.0, "bondWiggleDistance": 0.1}, + angle_force_kwargs={"k": 1.5}, + nonbonded_force_kwargs={"trunc": 1.5, "radiusMult": 1.05}, + ) + sim = _make("native", N, data, build, integrator=integrator, collision_rate=30 if integrator == "brownian" else 0.1) + sim.integrator.setRandomNumberSeed(7) + for _ in range(4): + res = sim.do_block(200, save=False) + assert np.isfinite(res["pos"]).all() + if integrator != "brownian": + assert 1.0 < res["kineticEnergy"] < 2.0 # 1.5 kT per particle + + +@pytest.mark.parametrize("integrator", ["langevin", "variableLangevin"]) +def test_trajectory_independent_of_threads(integrator): + """Bit-identical trajectories for any number of threads, also with a fast + set (particles pulled by stiff long bonds) and a variable step size.""" + N = 500 + data = polychrom.starting_conformations.grow_cubic(N, 14) + pulls = [(i, i + 60) for i in range(0, N - 60, 23)] + + def build(sim): + sim.add_force(forcekits.polymer_chains(sim)) + sim.add_force( + forces.harmonic_bonds(sim, pulls, bondWiggleDistance=0.3, bondLength=0.5, name="pull", override_checks=True) + ) + + out = [] + for threads in (1, 3, 4): + sim = _make("native", N, data, build, PBCbox=[20.0, 20.0, 20.0], integrator=integrator) + eng = sim.context.engine + eng.set_threads(threads) + sim.integrator.setRandomNumberSeed(11) + sim.context.setVelocitiesToTemperature(300, 5) + fast = 0 + for _ in range(60): + sim.integrator.step(5) + fast = max(fast, eng.get_fast_count()) + sim.context.getState(getEnergy=True) # next step starts with valid forces + assert fast > 8, "test does not exercise the fast set" + out.append(sim.context.getState(getPositions=True).getPositions(asNumpy=True)._value) + for o in out[1:]: + np.testing.assert_array_equal(out[0], o) + + +def test_bonded_terms_across_chunks(): + """Bonded terms are processed in chunks of particles; a ring's closing bond + and long bonds reach over several chunks and thread ranges.""" + N = 2600 + rng = np.random.default_rng(5) + data = polychrom.starting_conformations.grow_cubic(N, 20) + rng.normal(0, 0.15, (N, 3)) + longs = [(i, i + 1500) for i in range(0, N - 1500, 97)] + + def build(sim): + sim.add_force(forcekits.polymer_chains(sim, chains=[(0, None, True)])) + sim.add_force(forces.harmonic_bonds(sim, longs, bondLength=2.0, name="long", override_checks=True)) + + ref = _make("reference", N, data, build) + f_ref, e_ref = _forces_energy(ref) + for threads in (1, 4): + nat = _make("native", N, data, build) + nat.context.engine.set_threads(threads) + f_nat, e_nat = _forces_energy(nat) + np.testing.assert_allclose(f_nat, f_ref, atol=2e-6 * np.abs(f_ref).max(), rtol=0) + assert e_nat == pytest.approx(e_ref, rel=2e-6) + + +@pytest.mark.parametrize("PBCbox", [False, [14.0, 14.0, 14.0]]) +def test_fast_set_forces(PBCbox): + """Particles pulled by stiff long bonds (as by freshly placed loop extrusion + bonds) move more than half the skin; their pair forces come from the direct + search, not the lists. Compare with Reference at the same positions.""" + N = 400 + data = polychrom.starting_conformations.grow_cubic(N, 12) + pulls = [(i, i + 60) for i in range(0, N - 60, 37)] + + def build(sim): + sim.add_force(forcekits.polymer_chains(sim, nonbonded_force_kwargs={"trunc": 3.0})) + sim.add_force( + forces.harmonic_bonds(sim, pulls, bondWiggleDistance=0.3, bondLength=0.5, name="pull", override_checks=True) + ) + + nat = _make("native", N, data, build, PBCbox) + eng = nat.context.engine + box = np.array(PBCbox) if PBCbox else None + + def fast_fast_contacts(x, fast): + d = x[fast][:, None, :] - x[fast][None, :, :] + if box is not None: + d -= box * np.round(d / box) + r = np.linalg.norm(d, axis=-1) + not_bonded = np.abs(fast[:, None] - fast[None, :]) > 1 # chain neighbours are excluded + return np.sum(np.triu((r < 1.0) & not_bonded, 1)) + + found = False + for _ in range(400): + nat.integrator.step(1) + fast = eng.get_fast_particles() + if len(fast) > 1: + x = nat.context.getState(getPositions=True).getPositions(asNumpy=True)._value + if fast_fast_contacts(x, fast) > 0: + found = True + break + assert found, "no fast-fast contact: test does not exercise the fast set" + builds = eng.get_pair_builds(0) + ref = _make("reference", N, x, build, PBCbox) + f_ref, e_ref = _forces_energy(ref) + f_nat, e_nat = _forces_energy(nat) + assert eng.get_pair_builds(0) == builds # the forces above came from lists + fast set + np.testing.assert_allclose(f_nat, f_ref, atol=2e-6 * np.abs(f_ref).max(), rtol=0) + assert e_nat == pytest.approx(e_ref, rel=2e-6)