From b33f6d7f3c3739fe0af45029e1fcfc947a7892cd Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 00:40:43 +0100 Subject: [PATCH 01/23] Add a native multi-threaded CPU engine for polymer simulations OpenMM's CPU platform spends most of its time on per-step overheads that do not matter for coarse-grained polymer models. Profile of the loop extrusion benchmark (N = 10,000, density 0.1, harmonic bonds, polychrom angle force, polynomial_repulsive, LangevinMiddle 70 fs), OpenMM 8.6.1 CPU platform, one thread on an EPYC 7551: integrator only, no forces 0.96 ms/step + HarmonicBondForce 1.40 ms/step + CustomAngleForce 4.02 ms/step + CustomNonbondedForce 7.81 ms/step all three 10.51 ms/step (95 steps/s) and 6 threads only reach 7.9 ms/step; on the Zen 3 nodes 256 threads are slower than 32. Add polychrom/_native/engine.hpp, a small C++17/OpenMP engine with a Cython wrapper (polychrom._native_engine), reproducing the subset of OpenMM used by polychrom: - harmonic bonds, tabulated bonds, tabulated angles (in cos(theta) where smooth, avoiding atan2), tabulated pair potentials with per-type tables and exclusions, spherical confinement and tethers; - OpenMM 8's LangevinMiddle (= Langevin), VariableLangevin (same step size rule as ReferenceVariableStochasticDynamics) and Brownian integrators; - Verlet lists with a skin, packed 32-bit entries (index and periodic image), built per occupied cell with a branch-free candidate filter; - one OpenMP parallel region per step(n) call, owner-computes pair forces and a CSR gather of bonded contributions, a counter-based Ziggurat RNG, and the variable Langevin error summed over fixed blocks of 64 particles, so forces and trajectories do not depend on the number of threads. Same benchmark, native engine, one thread on the same EPYC 7551: 1.80 ms/step (555 steps/s), 5.8x faster. Zen 3 measurements are in the following commits. Assisted-by: claude-opus-5.5 (Claude Code) --- .gitignore | 1 + MANIFEST.in | 4 + polychrom/_native/engine.hpp | 1244 ++++++++++++++++++++++++++++++++++ polychrom/_native_engine.pyx | 280 ++++++++ setup.py | 23 +- 5 files changed, 1551 insertions(+), 1 deletion(-) create mode 100644 MANIFEST.in create mode 100644 polychrom/_native/engine.hpp create mode 100644 polychrom/_native_engine.pyx diff --git a/.gitignore b/.gitignore index e6837a8..72f39a8 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ polychrom/_polymer_math.cpp dist polychrom/*.so .vscode +polychrom/_native_engine.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..820c2c9 --- /dev/null +++ b/polychrom/_native/engine.hpp @@ -0,0 +1,1244 @@ +// 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, rebuilt when a particle has moved more +// than half the skin. Entries are packed into 32 bits (particle index and +// periodic image code), so the inner loop needs no rounding; +// * 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 in parallel into a contribution buffer and gathered +// per particle through a CSR index; +// * 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). +// +// Units follow OpenMM: nm, ps, amu, kJ/mol, K. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +namespace pcn { + +// Same value as OpenMM's BOLTZ (kJ/mol/K). +constexpr double BOLTZ = 0.0083144626181532395; + +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; +} + +// Standard normal deviate from the stream that starts at state `st`. +static inline double znormal(uint64_t st) { + const ZigguratTables& Z = zig(); + for (;;) { + 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]; + 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; + } +} + +// --------------------------------------------------------------------------- +// 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 + std::vector tab; // tabulated: index into tables + std::vector tables; + size_t contrib_offset = 0; +}; + +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; + std::vector tables; + size_t contrib_offset = 0; +}; + +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.0); + mass.assign(N, 100.0); + inv_mass.assign(N, 0.01); + (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) { + for (int p = 0; p < N; ++p) { + mass[p] = m[p]; + inv_mass[p] = m[p] > 0 ? 1.0 / m[p] : 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); + 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); + 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(); } + + // 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(); +#pragma omp parallel + forces_inner(); + check_error(); + } + + void step(int n) { + if (n <= 0) return; + prepare(); +#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 + } + } + check_error(); + } + + private: + int N; + bool pbc = false; + double box[3] = {0, 0, 0}; + std::vector x, v, f, mass, inv_mass; + std::vector x_ref; // positions at the last neighbour-list build + std::vector img; // periodic image offset at the last build (multiple of box) + std::vector xw; // x - img, refreshed every force evaluation + + 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, gather_idx; + + bool forces_valid = false; + double epot = 0.0; + double max_disp2 = std::numeric_limits::infinity(); + bool rebuild_all = true; + + 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 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; + std::vector be, tmp, ent; + std::vector> seg; // (particle, offset in ent) + }; + std::vector thr_scratch; + + // neighbour-list scratch + std::vector cell_of, cell_start, cell_list, nb_count, fill, occupied; + double shifts[27][3]; + double grid_lo[3], grid_edge[3]; + int grid_nc[3]; + + 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; + max_disp2 = std::numeric_limits::infinity(); + 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); + } + 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 ---------------------------------------------------- + void rebuild_topology() { + size_t off = 0; + for (auto& b : bonds) { + b.contrib_offset = off; + off += 2 * b.i.size(); + } + for (auto& a : angles) { + a.contrib_offset = off; + off += 3 * a.i.size(); + } + contrib.assign(3 * off, 0.0); + std::vector owner(off); + for (auto& b : bonds) + for (size_t q = 0; q < b.i.size(); ++q) { + owner[b.contrib_offset + 2 * q] = b.i[q]; + owner[b.contrib_offset + 2 * q + 1] = b.j[q]; + } + for (auto& a : angles) + for (size_t q = 0; q < a.i.size(); ++q) { + owner[a.contrib_offset + 3 * q] = a.i[q]; + owner[a.contrib_offset + 3 * q + 1] = a.j[q]; + owner[a.contrib_offset + 3 * q + 2] = a.k[q]; + } + gather_start.assign(N + 1, 0); + for (size_t c = 0; c < off; ++c) gather_start[owner[c] + 1]++; + for (int p = 0; p < N; ++p) gather_start[p + 1] += gather_start[p]; + gather_idx.assign(off, 0); + std::vector fl(gather_start.begin(), gather_start.end() - 1); + for (size_t c = 0; c < off; ++c) gather_idx[fl[owner[c]]++] = (int)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; + img[3 * p + d] = fl * box[d]; + xw[3 * p + d] = w; + } + } else { +#pragma omp for schedule(static) + for (size_t c = 0; c < 3 * (size_t)N; ++c) { + img[c] = 0.0; + 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); + nb_count.resize(N); + cell_start.assign(ncell + 1, 0); + 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]; + 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; + } + // 3. candidate scan per occupied cell. The 3x3 columns of the stencil + // are contiguous runs of cells along z; their particles are copied once + // (shifted to the right periodic image) into a small buffer that all + // particles of the cell then filter without branches. + ThreadScratch& ts = thr_scratch[tid]; + ts.ent.clear(); + 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; + ts.bx.clear(); + ts.by.clear(); + ts.bz.clear(); + ts.be.clear(); + auto add_run = [&](int first_cell, int last_cell, int code) { // inclusive cell range + const double shx = shifts[code][0], shy = shifts[code][1], shz = shifts[code][2]; + for (int s = cell_start[first_cell], se = cell_start[last_cell + 1]; s < se; ++s) { + const int q = cell_list[s]; + ts.bx.push_back(xw[3 * q] + shx); + ts.by.push_back(xw[3 * q + 1] + shy); + ts.bz.push_back(xw[3 * q + 2] + shz); + ts.be.push_back((uint32_t)q | ((uint32_t)code << NB_SHIFT_BITS)); + } + }; + 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); + } + } + } + } + const int nbuf = (int)ts.bx.size(); + if ((int)ts.tmp.size() < nbuf) ts.tmp.resize(nbuf); + const double* BX = ts.bx.data(); + const double* BY = ts.by.data(); + const double* BZ = ts.bz.data(); + const uint32_t* BE = ts.be.data(); + uint32_t* tmp = ts.tmp.data(); + for (int si = cell_start[c]; si < cell_start[c + 1]; ++si) { + const int p = cell_list[si]; + const double px = xw[3 * p], py = xw[3 * p + 1], pz = xw[3 * p + 2]; + int n = 0; + for (int k = 0; k < nbuf; ++k) { + const double dx = px - BX[k], dy = py - BY[k], dz = pz - BZ[k]; + tmp[n] = BE[k]; + n += (dx * dx + dy * dy + dz * dz < rl2); + } + const int* ex_b = pf.excl.data() + pf.excl_start[p]; + const int* ex_e = pf.excl.data() + pf.excl_start[p + 1]; + const size_t start = ts.ent.size(); + for (int k = 0; k < n; ++k) { + const uint32_t ent = tmp[k]; + const int q = (int)(ent & NB_INDEX_MASK); + if (q == p && (ent >> NB_SHIFT_BITS) == 13) continue; + if (ex_b != ex_e && std::binary_search(ex_b, ex_e, q)) continue; + ts.ent.push_back(ent); + } + nb_count[p] = (int)(ts.ent.size() - start); + ts.seg.push_back({p, start}); + } + } +#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++; + } + } + + // ---- 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 || max_disp2 > 0.25 * pf.skin * pf.skin) rebuild_all = true; + } + if (rebuild_all) { + for (auto& pf : pairs) build_list_inner(pf); +#pragma omp single + max_disp2 = 0.0; + } + if (pbc) { +#pragma omp for schedule(static) + for (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c] - img[c]; + } else { +#pragma omp for schedule(static) + for (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c]; + } + + double e = 0.0; + // pair forces + external forces, owner computes +#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]; + 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); + 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; + } + 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 into the contribution buffer + for (const BondSet& b : bonds) { + const int n = (int)b.i.size(); + const bool bp = b.pbc && pbc; + double* C = contrib.data() + 3 * b.contrib_offset; +#pragma omp for schedule(static) nowait + for (int q = 0; q < n; ++q) { + 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.r0[q]; + de = b.k[q] * ext; + en = 0.5 * de * ext; + } + e += en; + const double s = r > 0 ? -de / r : 0.0; + double* c = C + 6 * (size_t)q; + c[0] = s * dx; + c[1] = s * dy; + c[2] = s * dz; + c[3] = -c[0]; + c[4] = -c[1]; + c[5] = -c[2]; + } + } + for (const AngleSet& a : angles) { + const int n = (int)a.i.size(); + const bool ap = a.pbc && pbc; + double* C = contrib.data() + 3 * a.contrib_offset; +#pragma omp for schedule(static) nowait + for (int q = 0; q < n; ++q) { + 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 = C + 9 * (size_t)q; + const AngleTable& at = a.tables[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); + e += en; + for (int z = 0; z < 9; ++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 + e += 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] = -fix - fkx; + c[4] = -fiy - fky; + c[5] = -fiz - fkz; + c[6] = fkx; + c[7] = fky; + c[8] = 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 + e += en; + if (nn < 1e-12 * std::sqrt(aa2 * bb2)) { + for (int z = 0; z < 9; ++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] = -fix - fkx; + c[4] = -fiy - fky; + c[5] = -fiz - fkz; + c[6] = fkx; + c[7] = fky; + c[8] = fkz; + } + } + } + thr[(size_t)PAD * tid] = e; +#pragma omp barrier + // gather +#pragma omp for schedule(static) nowait + for (int p = 0; p < N; ++p) { + double fx = 0, fy = 0, fz = 0; + for (int s = gather_start[p]; s < gather_start[p + 1]; ++s) { + const double* c = &contrib[3 * (size_t)gather_idx[s]]; + fx += c[0]; + fy += c[1]; + fz += c[2]; + } + f[3 * p] += fx; + f[3 * p + 1] += fy; + f[3 * p + 2] += fz; + } +#pragma omp single + { + epot = thr_sum(); + if (!std::isfinite(epot)) set_error("non-finite potential energy (simulation exploded?)"); + forces_valid = true; + } // implicit barrier + } + + // ---- integration (called by all threads of a team) ------------------------------------ + void integrate_inner() { + const int tid = thread_id(); + if (integrator == VARIABLE_LANGEVIN) { + // ReferenceVariableStochasticDynamics::updatePart1: step size selection. + // Summed in fixed blocks of particles, so that the step size does not + // depend on the number of threads. + const int nblk = (N + SUM_BLOCK - 1) / SUM_BLOCK; +#pragma omp for schedule(static) + for (int b = 0; b < nblk; ++b) { + double err = 0.0; + for (int p = b * SUM_BLOCK, pe = std::min(N, p + SUM_BLOCK); p < pe; ++p) + for (int d = 0; d < 3; ++d) { + const double a = inv_mass[p] * f[3 * p + d]; + err += a * a; + } + block_sum[b] = err; + } +#pragma omp single + { + double err = 0.0; + for (int b = 0; b < nblk; ++b) err += block_sum[b]; + double er = std::sqrt(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; + } + } + 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)); + double md2 = 0.0; + +#pragma omp for schedule(static) + for (int p = 0; p < N; ++p) { + const double im = inv_mass[p]; + if (im == 0) continue; + const double sim = std::sqrt(im); + double d2 = 0.0; + for (int d = 0; d < 3; ++d) { + const size_t c = 3 * (size_t)p + d; + const double g = znormal(base + ((uint64_t)c << 24)); + if (integrator == BROWNIAN) { + // ReferenceBrownianDynamics + const double dx = dt / gamma * im * f[c] + std::sqrt(2.0 * kT * dt / gamma) * sim * g; + 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]; + double xx = x[c] + 0.5 * dt * vv; + vv = vscale * vv + noisescale * sim * g; + xx += 0.5 * dt * vv; + v[c] = vv; + x[c] = xx; + } + const double dd = x[c] - x_ref[c]; + d2 += dd * dd; + } + if (!(d2 <= std::numeric_limits::max())) d2 = std::numeric_limits::infinity(); // NaN + md2 = std::max(md2, d2); + } + thr[(size_t)PAD * tid] = md2; +#pragma omp barrier +#pragma omp single + { + double m = 0; + for (size_t t = 0; t + PAD <= thr.size(); t += PAD) m = std::max(m, thr[t]); + max_disp2 = m; + if (!std::isfinite(m)) set_error("non-finite coordinates (simulation exploded?)"); + time_ += dt; + nsteps++; + forces_valid = false; + } // implicit barrier + } +}; + +} // namespace pcn diff --git a/polychrom/_native_engine.pyx b/polychrom/_native_engine.pyx new file mode 100644 index 0000000..6a76666 --- /dev/null +++ b/polychrom/_native_engine.pyx @@ -0,0 +1,280 @@ +# 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: + 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 + + 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 + + +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 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/setup.py b/setup.py index b38b911..09e27c9 100644 --- a/setup.py +++ b/setup.py @@ -1,14 +1,35 @@ +import os +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. +native_compile_args = ["-O3", "-std=c++17", "-fno-math-errno"] +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, + ), ] setup( From 3d889aec6f76ba1eee160e140ddd8a50a03fbe28 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 00:40:54 +0100 Subject: [PATCH 02/23] Add Simulation(platform="native") backed by the native CPU engine polychrom.native translates the OpenMM force objects created by polychrom.forces into native engine terms and provides stand-ins for the parts of openmm.Context, Integrator and State that polychrom code uses, so existing scripts run unchanged: - HarmonicBondForce is evaluated natively; CustomBondForce, CustomAngleForce and CustomNonbondedForce of any isotropic expression are tabulated once per distinct parameter set. A copy of the force (via XmlSerializer, so global parameters, tabulated functions and switching are kept) is evaluated for 1024 configurations per call on the Reference platform. Energies are integrated from the exact derivatives (Simpson), and tables are refined until the interpolated force matches OpenMM at the quarter points to 1e-6. Kinks (smooth_square_well at REPsigma and at the cutoff) are put on knots. - spherical_confinement and tether_particles are recognised by expression. - force.updateParametersInContext(sim.context) is redirected to the engine, so polychrom.lib.extrusion.bondUpdater works; context.setParameter re-tabulates the affected force. - Energy minimisation uses OpenMM's L-BFGS on a temporary CPU context. - Unsupported forces and integrators raise NotImplementedError. Tabulating the heteropolymer_SSW test case (6 particle types) took 39 s with one OpenMM call per point; batching brings it to about 1 s. In OpenMM 8, LangevinIntegrator subclasses LangevinMiddleIntegrator and VariableLangevinIntegrator uses the same middle scheme (ReferenceVariableStochasticDynamics.cpp, OpenMM 8.2.0), which the engine follows. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/native.py | 962 ++++++++++++++++++++++++++++++++++++++++ polychrom/simulation.py | 45 +- 2 files changed, 1003 insertions(+), 4 deletions(-) create mode 100644 polychrom/native.py diff --git a/polychrom/native.py b/polychrom/native.py new file mode 100644 index 0000000..ffb7123 --- /dev/null +++ b/polychrom/native.py @@ -0,0 +1,962 @@ +""" +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 all cores. +""" + +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 + +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) + + +def _thread_count(): + for var in ("POLYCHROM_NATIVE_THREADS", "OMP_NUM_THREADS", "OPENMM_CPU_THREADS"): + v = os.environ.get(var) + if v: + return int(v) + return 0 # OpenMP default + + +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 + root = copy.deepcopy(root) + M = self.SLOTS + if kind == "pair": + root.set("method", "1") # CutoffNonPeriodic + root.set("useLongRangeCorrection", "0") + container, per = root.find("Particles"), 2 + for tag in ("Exclusions", "InteractionGroups"): + el = root.find(tag) + if el is not None: + for child in list(el): + el.remove(child) + else: + root.set("usesPeriodic", "0") + container, per = root.find("Bonds" if kind == "bond" else "Angles"), 2 if kind == "bond" else 3 + proto = container[0].tag + for child in list(container): + container.remove(child) + 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])) + 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 err <= TABLE_TOL or 2 * n - 1 > nmax: + break + # refine: midpoints become knots, quarter points become midpoints + 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, n = xn, Dn, Dq[order], 2 * n - 1 + # A kink strictly inside the finite range (not a singularity at its edge): + # put knots on it and (as closely as possible) on x1, which is a kink too + # for pair potentials that vanish at the cutoff. + h = x[1] - x[0] + xk = _locate_kink(deriv, x[kbad], x[kbad + 1]) if err > TABLE_TOL and extend and lo < kbad < hi - 1 else None + if xk is not None and 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 + else: + n2 = 0 + if 0 < n2 <= 2 * nmax: + x2 = x0 + h2 * np.arange(n2) + with np.errstate(all="ignore"): + D2 = deriv(x2) + Dm2 = deriv(0.5 * (x2[1:] + x2[:-1])) + E2, lo2, hi2 = _integrate(x2, D2, Dm2, energy_at, anchor, what) + err2 = _quarter_error(deriv, x2, E2, D2, lo2, hi2)[0] + if err2 < err: + x, D, E, lo, hi, err = x2, D2, E2, lo2, hi2, err2 + 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) + nthreads = _thread_count() + if nthreads > 0: + self._engine.set_threads(nthreads) + 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) + globals_ = self._globals(f) + 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 From 09fe19199b1778ab3995c240b34a075cab0f6137 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 00:40:55 +0100 Subject: [PATCH 03/23] Test the native platform against OpenMM's Reference platform Compare forces and energies for open, ring and periodic chains with harmonic, constant-force and FENE bonds, angle forces (theta_0 = pi and not), polynomial_repulsive, smooth_square_well, heteropolymer_SSW with three types and extra-hard particles, spherical confinement, anisotropic tethers, bond parameter updates and global parameter changes. Also check that all four integrators thermalise, that unsupported forces raise, and that trajectories do not depend on the number of threads. The variableLangevin integrator test uses the loop extrusion parameters: with the default polymer_chains bonds (wiggle 0.05) and no minimisation, OpenMM's CPU platform fails as well: variableLangevin CPU EKExceedsError('Ek=18.92304825791721 exceeds 10') variableLangevin native EKExceedsError('Ek=20.55497869700652 exceeds 10') Assisted-by: claude-opus-5.5 (Claude Code) --- tests/test_native.py | 202 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 tests/test_native.py diff --git a/tests/test_native.py b/tests/test_native.py new file mode 100644 index 0000000..04e8bcd --- /dev/null +++ b/tests/test_native.py @@ -0,0 +1,202 @@ +"""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 + + +def test_trajectory_independent_of_threads(): + N = 500 + data = polychrom.starting_conformations.grow_cubic(N, 14) + out = [] + for threads in (1, 3): + sim = _make("native", N, data, _chain(), PBCbox=[20.0, 20.0, 20.0]) + sim.context.engine.set_threads(threads) + sim.integrator.setRandomNumberSeed(11) + sim.context.setVelocitiesToTemperature(300, 5) + sim.integrator.step(300) + out.append(sim.context.getState(getPositions=True).getPositions(asNumpy=True)._value) + np.testing.assert_array_equal(out[0], out[1]) From 0ae685044849ce09cd3b450f902c18ef93ebe7e5 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:10:05 +0100 Subject: [PATCH 04/23] Stop table refinement at OpenMM's noise floor and refine after kink alignment Near theta = pi, OpenMM's derivative of an angle potential is accurate to only ~1e-5, so the refinement of the polychrom angle_force table never met the 1e-6 target and always went to the 8193-knot maximum (256 KiB): [('angle force angle', 8193), ('angle force angle', 2049), ...] Refine while doubling the resolution reduces the error; cubic Hermite interpolation gains ~8x per doubling where the force is smooth. When it gains less than 3x, first try to put a knot on a kink (and on the cutoff), then keep doubling, which keeps both on knots; stop when a doubling no longer helps, keeping the best table. The angle table now has 1025 knots; smooth_square_well converges at the kink instead of stalling: knots 2049: err 1.21e-01 at x=0.99941 knots 1038: err 7.21e-05 at x=1.00000 (kink aligned) knots 4149: err 1.47e-06 at x=1.00000 On Zen 3 (wallaby, EPYC 7763, one thread, loop extrusion benchmark, N = 10,000) the smaller angle table makes no measurable difference (375-386 steps/s before and after); it mainly removes wasted tabulation. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/native.py | 67 +++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 27 deletions(-) diff --git a/polychrom/native.py b/polychrom/native.py index ffb7123..e02112e 100644 --- a/polychrom/native.py +++ b/polychrom/native.py @@ -430,43 +430,56 @@ def _table(deriv, energy_at, x0, x1, knots, anchor, what, extend=True): 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 err <= TABLE_TOL or 2 * n - 1 > nmax: + 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, n = xn, Dn, Dq[order], 2 * n - 1 - # A kink strictly inside the finite range (not a singularity at its edge): - # put knots on it and (as closely as possible) on x1, which is a kink too - # for pair potentials that vanish at the cutoff. - h = x[1] - x[0] - xk = _locate_kink(deriv, x[kbad], x[kbad + 1]) if err > TABLE_TOL and extend and lo < kbad < hi - 1 else None - if xk is not None and 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 - else: - n2 = 0 - if 0 < n2 <= 2 * nmax: - x2 = x0 + h2 * np.arange(n2) - with np.errstate(all="ignore"): - D2 = deriv(x2) - Dm2 = deriv(0.5 * (x2[1:] + x2[:-1])) - E2, lo2, hi2 = _integrate(x2, D2, Dm2, energy_at, anchor, what) - err2 = _quarter_error(deriv, x2, E2, D2, lo2, hi2)[0] - if err2 < err: - x, D, E, lo, hi, err = x2, D2, E2, lo2, hi2, err2 + 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: From ee1ac0454173950261ad210248976658a060ad92 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:10:16 +0100 Subject: [PATCH 05/23] Build the tabulation template without copying the per-particle lists _Batch deep-copied the serialized force, including all particles, exclusions, bonds or angles, and then removed those children one by one (quadratic). Setting up the loop extrusion benchmark with N = 200,000: 599997 15.622 0.000 15.622 0.000 {method 'remove' of 'xml.etree.ElementTree.Element' objects} 4/2 1.310 0.328 6.217 3.109 {method '__deepcopy__' of 'xml.etree.ElementTree.Element' objects} _apply_forces cumulative 34.3 s Copy only the small children (expression, parameters, functions) and start with empty lists. _apply_forces now takes 12.6 s, of which 4.5 s are OpenMM's own XmlSerializer.serialize. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/native.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/polychrom/native.py b/polychrom/native.py index e02112e..e3b8126 100644 --- a/polychrom/native.py +++ b/polychrom/native.py @@ -259,23 +259,28 @@ class _Batch: def __init__(self, root, kind, params, spacing): self.kind = kind self.spacing = spacing - root = copy.deepcopy(root) 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 - for tag in ("Exclusions", "InteractionGroups"): - el = root.find(tag) - if el is not None: - for child in list(el): - el.remove(child) else: root.set("usesPeriodic", "0") container, per = root.find("Bonds" if kind == "bond" else "Angles"), 2 if kind == "bond" else 3 - proto = container[0].tag - for child in list(container): - container.remove(child) + proto = tag for k in range(M): if kind == "pair": for prm in params: From af85c24acbf4a26eb4dea4f60c1378ae95a674fe Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:10:21 +0100 Subject: [PATCH 06/23] Handle fast particles without rebuilding the neighbour lists In the loop extrusion benchmark, the LEF bonds that are switched on pull their (distant) monomers together by up to ~0.4 nm per step, so the "rebuild when any particle moved more than half the skin" rule rebuilt the lists every 1.5 steps: native N=10000: 366 steps/s, dt 148 fs, steps/rebuild 1.5, list 3.5/particle Keep lists valid for the particles that moved less than half the skin, and give the others (the fast set) their pair interactions from a direct search every step: fast-slow pairs through the cell grid of the last build (a slow particle is still within the 27-cell stencil), fast-fast pairs directly. Each such pair is computed once, the force on the partner is buffered and applied by one thread in the order of the fast list, so results stay independent of the thread count. Lists are rebuilt when the fast set exceeds max(64, N/32) particles, or with several pair forces or fewer than 3 cells per periodic dimension whenever it is not empty. Zen 3 (wallaby, EPYC 7763), one thread, same benchmark, three runs each: before: 377, 389, 388 steps/s, steps/rebuild 1.5-1.6 after: 549, 550, 558 steps/s, steps/rebuild 3.3-3.4 Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 172 +++++++++++++++++++++++++++++++---- 1 file changed, 155 insertions(+), 17 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 820c2c9..2ee4008 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -9,9 +9,12 @@ // // * 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, rebuilt when a particle has moved more -// than half the skin. Entries are packed into 32 bits (particle index and -// periodic image code), so the inner loop needs no rounding; +// * 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); // * 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 in parallel into a contribution buffer and gathered @@ -623,8 +626,22 @@ class Engine { bool forces_valid = false; double epot = 0.0; - double max_disp2 = std::numeric_limits::infinity(); 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; + 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; @@ -643,6 +660,8 @@ class Engine { std::vector bx, by, bz; std::vector be, tmp, ent; 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; @@ -650,7 +669,7 @@ class Engine { std::vector cell_of, cell_start, cell_list, nb_count, fill, occupied; double shifts[27][3]; double grid_lo[3], grid_edge[3]; - int grid_nc[3]; + int grid_nc[3] = {1, 1, 1}; std::atomic error_flag{0}; std::string error_msg; @@ -662,7 +681,6 @@ class Engine { void invalidate() { forces_valid = false; - max_disp2 = std::numeric_limits::infinity(); for (auto& pf : pairs) pf.need_rebuild = true; } @@ -698,6 +716,16 @@ class Engine { 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]; @@ -936,6 +964,99 @@ class Engine { } } + // 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 checked directly. 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 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 single + fast_span.resize(nfast); +#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]; + 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; + } + 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); + } + } + } + } + for (int b = a + 1; b < nfast; ++b) pair(p, fast_list[b], 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; + } + } + } + // ---- forces (called by all threads of a team) ------------------------------------ void forces_inner() { if (forces_valid) return; // shared flag, consistent after the last barrier @@ -947,12 +1068,21 @@ class Engine { { rebuild_all = false; for (auto& pf : pairs) - if (pf.need_rebuild || max_disp2 > 0.25 * pf.skin * pf.skin) rebuild_all = true; + 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 - max_disp2 = 0.0; + { + nfast = 0; + fast_list.clear(); + } } if (pbc) { #pragma omp for schedule(static) @@ -963,11 +1093,13 @@ class Engine { } double e = 0.0; - // pair forces + external forces, owner computes + 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]; @@ -976,6 +1108,7 @@ class Engine { 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]; @@ -996,6 +1129,7 @@ class Engine { 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) @@ -1194,7 +1328,9 @@ class Engine { 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)); - double md2 = 0.0; + std::vector& my_fast = thr_scratch[tid].fast; + my_fast.clear(); + bool bad = false; #pragma omp for schedule(static) for (int p = 0; p < N; ++p) { @@ -1223,17 +1359,19 @@ class Engine { const double dd = x[c] - x_ref[c]; d2 += dd * dd; } - if (!(d2 <= std::numeric_limits::max())) d2 = std::numeric_limits::infinity(); // NaN - md2 = std::max(md2, d2); + 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] = md2; + thr[(size_t)PAD * tid] = bad ? 1.0 : 0.0; #pragma omp barrier #pragma omp single { - double m = 0; - for (size_t t = 0; t + PAD <= thr.size(); t += PAD) m = std::max(m, thr[t]); - max_disp2 = m; - if (!std::isfinite(m)) set_error("non-finite coordinates (simulation exploded?)"); + 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; From 13fc2bb8283de925073e8837b37641957f653af7 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:17:32 +0100 Subject: [PATCH 07/23] Default to one native thread per 500 particles With the OpenMP default (all CPUs in the affinity mask), a small system on a busy shared host spent almost all its time waiting at barriers. N = 200, 70 blocks of 200 steps, 6 CPUs, load average 16.8: POLYCHROM_NATIVE_THREADS=1: 1.73 s POLYCHROM_NATIVE_THREADS=2: 1.56 s unset (6 threads): 150.96 s Use min(available CPUs, N / 500) threads unless POLYCHROM_NATIVE_THREADS, OMP_NUM_THREADS or OPENMM_CPU_THREADS is set. The unset case now takes 1.83 s, and tests/test_native.py runs in 9 s instead of 25 s on that host. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/native.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/polychrom/native.py b/polychrom/native.py index e3b8126..c08837a 100644 --- a/polychrom/native.py +++ b/polychrom/native.py @@ -38,7 +38,9 @@ statistically, not bit by bit. Threads: ``POLYCHROM_NATIVE_THREADS``, else ``OMP_NUM_THREADS``, else -``OPENMM_CPU_THREADS``, else all cores. +``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. """ import copy @@ -82,12 +84,24 @@ def _array(x, unit): return np.asarray([list(v) for v in x] if isinstance(x, (list, tuple)) else x, dtype=np.float64) -def _thread_count(): +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) - return 0 # OpenMP default + 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: @@ -652,9 +666,7 @@ def __init__(self, system, integrator, forces, pbc, length_scale=1.0): self._params = {} # current values of global parameters, by name self._handlers = {} # id(force) -> update function self._engine = _native_engine.NativeEngine(self._N) - nthreads = _thread_count() - if nthreads > 0: - self._engine.set_threads(nthreads) + 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: From c076e7a74d683321c5e76be47d955a2b0cda1f38 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:22:12 +0100 Subject: [PATCH 08/23] Cap the fast set and assign list-build cells in parallel Profile of the loop extrusion benchmark, N = 200,000, 64 threads on Zen 3 (wallaby), 254-259 steps/s: 36.59% forces_inner 30.38% gomp_team_barrier_wait_end 14.37% build_list_inner 5.62% fast_set_forces With max(64, N/32) the fast set could hold 6250 particles at N = 200,000, and its fast-fast pairs are checked directly (~2e7 pairs per step). Limit it to 1024 particles. Also move the per-particle cell assignment of the list build out of the serial section, which the other threads wait for. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 2ee4008..d16a56f 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -14,7 +14,8 @@ // 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); +// lists are rebuilt only when the fast set grows beyond +// min(1024, max(64, N/32)) particles; // * 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 in parallel into a contribution buffer and gathered @@ -725,7 +726,8 @@ class Engine { 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); + // fast-fast pairs are checked directly (O(nfast^2)), so keep the set small + fast_max = std::min(1024, 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]; @@ -838,16 +840,22 @@ class Engine { cell_list.resize(N); nb_count.resize(N); cell_start.assign(ncell + 1, 0); - 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]; - cell_start[cell_of[p] + 1]++; + } + // 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); From 51193d9e6f1acfd6df1cdbdd987f269e48ca2419 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 01:33:50 +0100 Subject: [PATCH 09/23] Find fast-fast pairs through the cell grid and test the fast set Capping the fast set at 1024 particles (to bound the direct fast-fast check) made rebuilds more frequent at large N and was slower overall. Loop extrusion benchmark, N = 200,000, 64 threads, Zen 3 (wallaby): max(64, N/32) cap, O(nfast^2): 254, 259 steps/s, steps/rebuild 3.4 cap 1024: 246, 231 steps/s, steps/rebuild 2.3-2.4 Bin the fast set by its current cell instead (sorted (cell, particle) pairs, looked up for the same 27-cell stencil), which costs O(nfast log nfast), and restore the max(64, N/32) limit. Add a test in which stiff long bonds pull particles fast enough to enter the fast set, stepping until two non-bonded fast particles are within the cutoff, and comparing forces with the Reference platform without a list rebuild in between. With the fast-fast lookup disabled the test fails: E Mismatched elements: 6 / 1200 (0.5%) Also extend test_trajectory_independent_of_threads to variable Langevin, add stiff long bonds that pull particles into the fast set, and compare 1, 3 and 4 threads. Before the summation-order fixes in "Add a native multi-threaded CPU engine ..." and "Handle fast particles without rebuilding the neighbour lists", it failed, also between runs of one build: E Mismatched elements: 574 / 1500 (38.3%) E Mismatched elements: 1500 / 1500 (100%) 2 failed, 14 deselected in 3.03s Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 52 ++++++++++++++++--------- polychrom/_native_engine.pyx | 12 ++++++ tests/test_native.py | 74 +++++++++++++++++++++++++++++++++--- 3 files changed, 114 insertions(+), 24 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index d16a56f..ea2aa18 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -14,8 +14,7 @@ // 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 -// min(1024, max(64, N/32)) particles; +// lists are rebuilt only when the fast set grows beyond max(64, N/32); // * 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 in parallel into a contribution buffer and gathered @@ -488,6 +487,8 @@ class Engine { } 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, @@ -631,6 +632,7 @@ class Engine { // 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; @@ -726,8 +728,7 @@ class Engine { 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-fast pairs are checked directly (O(nfast^2)), so keep the set small - fast_max = std::min(1024, std::max(64, N / 32)); + 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]; @@ -976,10 +977,10 @@ class Engine { // 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 checked directly. 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. + // 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]; @@ -987,6 +988,26 @@ class Engine { 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); @@ -1005,21 +1026,13 @@ class Engine { fz += sc * dz; out.push_back({q, -sc * dx, -sc * dy, -sc * dz}); }; -#pragma omp single - fast_span.resize(nfast); #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]; - 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; - } + current_cell(p, ci); for (int ox = -1; ox <= 1; ++ox) { int ca = ci[0] + ox; if (ca < 0 || ca >= nc0) { @@ -1044,10 +1057,13 @@ class Engine { 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); } } } - for (int b = a + 1; b < nfast; ++b) pair(p, fast_list[b], fx, fy, fz); f[3 * p] += fx; f[3 * p + 1] += fy; f[3 * p + 2] += fz; diff --git a/polychrom/_native_engine.pyx b/polychrom/_native_engine.pyx index 6a76666..471afb9 100644 --- a/polychrom/_native_engine.pyx +++ b/polychrom/_native_engine.pyx @@ -42,6 +42,8 @@ cdef extern from "_native/engine.hpp" namespace "pcn" nogil: 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 + @@ -204,6 +206,16 @@ cdef class NativeEngine: 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) diff --git a/tests/test_native.py b/tests/test_native.py index 04e8bcd..b5c8b6a 100644 --- a/tests/test_native.py +++ b/tests/test_native.py @@ -188,15 +188,77 @@ def test_integrators_run_and_thermalise(integrator): assert 1.0 < res["kineticEnergy"] < 2.0 # 1.5 kT per particle -def test_trajectory_independent_of_threads(): +@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): - sim = _make("native", N, data, _chain(), PBCbox=[20.0, 20.0, 20.0]) - sim.context.engine.set_threads(threads) + 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) - sim.integrator.step(300) + fast = 0 + for _ in range(60): + sim.integrator.step(5) + fast = max(fast, eng.get_fast_count()) + assert fast > 8, "test does not exercise the fast set" out.append(sim.context.getState(getPositions=True).getPositions(asNumpy=True)._value) - np.testing.assert_array_equal(out[0], out[1]) + for o in out[1:]: + np.testing.assert_array_equal(out[0], o) + + +@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 + rng = np.random.default_rng(3) + 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) From 16601475c67181550267b686dee58b03ba30c2bb Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 10:54:02 +0100 Subject: [PATCH 10/23] Filter list-build candidates from cell-ordered coordinates The candidate buffer of each cell was filled with four push_back calls per particle, gathered from the per-particle coordinate array, and each accepted candidate was checked with a binary search over the particle's exclusions. Copy the wrapped coordinates into cell order once per build, so that the nine stencil columns of a cell are contiguous ranges that are copied into the buffer with plain loops, and compare against up to eight exclusions without branches. The candidate order is unchanged, so trajectories are bit-identical (position hashes of a 4,000-particle loop extrusion run with variable and fixed-step Langevin, one thread). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1), per particle and step in the timed region: steps/s cycles instructions branch misses before: 360-361 782 1756 7 after: 364-369 763 1597 5 Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 120 ++++++++++++++++++++++++----------- 1 file changed, 82 insertions(+), 38 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index ea2aa18..31bb9ea 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -660,8 +660,9 @@ class Engine { static constexpr int SUM_BLOCK = 64; std::vector block_sum; struct ThreadScratch { - std::vector bx, by, bz; - std::vector be, tmp, ent; + 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 @@ -670,6 +671,7 @@ class Engine { // 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}; @@ -864,13 +866,26 @@ class Engine { } 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); + } + // wrapped coordinates in cell order (structure of arrays) + double* const SX = sorted_xyz.data(); + double* const SY = SX + N; + double* const SZ = SY + N; +#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; their particles are copied once - // (shifted to the right periodic image) into a small buffer that all - // particles of the cell then filter without branches. + // 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]; - ts.ent.clear(); + 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(); @@ -878,19 +893,14 @@ class Engine { 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; - ts.bx.clear(); - ts.by.clear(); - ts.bz.clear(); - ts.be.clear(); + 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 double shx = shifts[code][0], shy = shifts[code][1], shz = shifts[code][2]; - for (int s = cell_start[first_cell], se = cell_start[last_cell + 1]; s < se; ++s) { - const int q = cell_list[s]; - ts.bx.push_back(xw[3 * q] + shx); - ts.by.push_back(xw[3 * q + 1] + shy); - ts.bz.push_back(xw[3 * q + 2] + shz); - ts.be.push_back((uint32_t)q | ((uint32_t)code << NB_SHIFT_BITS)); - } + 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; @@ -920,34 +930,68 @@ class Engine { } } } - const int nbuf = (int)ts.bx.size(); - if ((int)ts.tmp.size() < nbuf) ts.tmp.resize(nbuf); - const double* BX = ts.bx.data(); - const double* BY = ts.by.data(); - const double* BZ = ts.bz.data(); - const uint32_t* BE = ts.be.data(); - uint32_t* tmp = ts.tmp.data(); + // 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) { + ts.bx.resize(2 * ncand); + ts.by.resize(2 * ncand); + ts.bz.resize(2 * ncand); + ts.be.resize(2 * ncand); + } + 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; + 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; + } + nbuf += len; + } for (int si = cell_start[c]; si < cell_start[c + 1]; ++si) { - const int p = cell_list[si]; - const double px = xw[3 * p], py = xw[3 * p + 1], pz = xw[3 * p + 2]; + const int p = CL[si]; + const double px = SX[si], py = SY[si], pz = SZ[si]; + if (ts.ent.size() < nent + nbuf) ts.ent.resize(2 * (nent + nbuf)); + uint32_t* const out = ts.ent.data() + nent; int n = 0; for (int k = 0; k < nbuf; ++k) { const double dx = px - BX[k], dy = py - BY[k], dz = pz - BZ[k]; - tmp[n] = BE[k]; + out[n] = BE[k]; n += (dx * dx + dy * dy + dz * dz < rl2); } + // drop p itself and its exclusions (compared branch-free if few) const int* ex_b = pf.excl.data() + pf.excl_start[p]; - const int* ex_e = pf.excl.data() + pf.excl_start[p + 1]; - const size_t start = ts.ent.size(); - for (int k = 0; k < n; ++k) { - const uint32_t ent = tmp[k]; - const int q = (int)(ent & NB_INDEX_MASK); - if (q == p && (ent >> NB_SHIFT_BITS) == 13) continue; - if (ex_b != ex_e && std::binary_search(ex_b, ex_e, q)) continue; - ts.ent.push_back(ent); + const int nex = pf.excl_start[p + 1] - pf.excl_start[p]; + const uint32_t self = (uint32_t)p | (13u << NB_SHIFT_BITS); + 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] = (int)(ts.ent.size() - start); - ts.seg.push_back({p, start}); + nb_count[p] = m; + ts.seg.push_back({p, nent}); + nent += m; } } #pragma omp barrier From 3e3e72b80ef2cfce3a0526a72dc3687aa3841293 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 10:58:19 +0100 Subject: [PATCH 11/23] Build the native engine for x86-64-v3 as well and select it at run time The engine was compiled for baseline x86-64 (SSE2), so the compiler could use neither AVX2 nor FMA. Build a second extension module, polychrom._native_engine_x86_64_v3 (-mavx2 -mfma -mbmi2), from the same Cython source, and import it in polychrom.native when the CPU supports these instructions (__builtin_cpu_supports, which also checks that the OS saves the AVX state). POLYCHROM_NATIVE_ISA=baseline selects the generic build; polychrom.native.ENGINE_ISA tells which one is in use. Compile both with -ffp-contract=off, so that the compiler does not fuse multiplications and additions into FMA instructions in one build only: both builds give bit-identical trajectories (position hashes of a 4,000- particle loop extrusion run with variable and fixed-step Langevin). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1), per particle and step: cycles instructions baseline: 675-685 1586 -march=native: 660 1453 The node is shared and the cycle counts vary by about 10 % between runs. On a dedicated EPYC 7763 (Zen 3), the two builds were equally fast at this commit (574 and 575 cycles per particle and step); with the AVX2 code of the following commits, the x86-64-v3 build is 16 % faster (at "Keep the rare Ziggurat rejection path out of the integrator loop", one thread, three runs each; cycles per particle and step in parentheses): N = 10,000 N = 200,000 baseline build: 628 steps/s (554) 26 steps/s (683) x86-64-v3 build: 730 steps/s (477) 30 steps/s (578) Assisted-by: claude-opus-5.5 (Claude Code) --- .gitignore | 1 + polychrom/_native/engine.hpp | 12 ++++++++++++ polychrom/_native_engine.pyx | 7 +++++++ polychrom/_native_engine_x86_64_v3.pyx | 9 +++++++++ polychrom/native.py | 25 ++++++++++++++++++++++++- setup.py | 19 ++++++++++++++++++- 6 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 polychrom/_native_engine_x86_64_v3.pyx diff --git a/.gitignore b/.gitignore index 72f39a8..c78aded 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ dist polychrom/*.so .vscode polychrom/_native_engine.cpp +polychrom/_native_engine_x86_64_v3.cpp diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 31bb9ea..db72a31 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -48,6 +48,18 @@ 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(); diff --git a/polychrom/_native_engine.pyx b/polychrom/_native_engine.pyx index 471afb9..a5d18ed 100644 --- a/polychrom/_native_engine.pyx +++ b/polychrom/_native_engine.pyx @@ -15,6 +15,8 @@ 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) @@ -86,6 +88,11 @@ cdef inline cnp.ndarray _i(a, n=None): 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 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 index c08837a..7690122 100644 --- a/polychrom/native.py +++ b/polychrom/native.py @@ -41,6 +41,10 @@ ``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 @@ -53,7 +57,26 @@ import openmm import simtk.unit as u -from polychrom import _native_engine +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 diff --git a/setup.py b/setup.py index 09e27c9..5f93963 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ import os +import platform import sys import numpy @@ -7,7 +8,8 @@ # 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. -native_compile_args = ["-O3", "-std=c++17", "-fno-math-errno"] +# 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") @@ -32,6 +34,21 @@ ), ] +# 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"), ) From 11bb07dad09c27a5a7cf77ecbbe6ded600b276eb Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:16:51 +0100 Subject: [PATCH 12/23] Fold two per-step passes over the particles into existing ones Each step refreshed the wrapped coordinates (xw = x - img) in a pass of its own, and variable Langevin summed (f/m)^2 in another pass over the forces, followed by a barrier. For large systems, whose data does not fit into the caches, every pass streams the arrays from memory. Update xw in the integrator, right after the new x (and once after a list rebuild, when img changes); without PBC, the pair loop reads x. Accumulate the error sum in the loop that gathers the bonded forces, which is the last update of f, and select the step size in the single block that follows it. If the forces were already valid when a step starts (after getState), the integrator selects it as before. Trajectories are bit-identical to the previous commit (position hashes of a 4,000-particle loop extrusion run, 1 and 3 threads). The thread test now queries the energy between steps, so that variable Langevin also starts steps with valid forces: a first version of this change, which set the "step size selected" flag inside the single block that the threads test it for, deadlocked there. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 123 +++++++++++++++++++++-------------- tests/test_native.py | 1 + 2 files changed, 76 insertions(+), 48 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index db72a31..cf828a2 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -600,6 +600,7 @@ class Engine { void compute() { if (forces_valid) return; prepare(); + stepping = false; #pragma omp parallel forces_inner(); check_error(); @@ -608,6 +609,8 @@ class Engine { void step(int n) { if (n <= 0) return; prepare(); + stepping = true; + dt_selected = false; #pragma omp parallel { for (int s = 0; s < n; ++s) { @@ -616,6 +619,7 @@ class Engine { if (error_flag.load(std::memory_order_relaxed)) break; // same value on all threads after barrier } } + stepping = false; check_error(); } @@ -661,6 +665,9 @@ class Engine { 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; @@ -1164,13 +1171,13 @@ class Engine { fast_list.clear(); } } - if (pbc) { + // xw = x - img (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 (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c] - img[c]; - } else { -#pragma omp for schedule(static) - for (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c]; } + const double* const XW = pbc ? xw.data() : x.data(); double e = 0.0; const uint8_t* is_fast = nfast > 0 ? fast.data() : nullptr; @@ -1178,7 +1185,7 @@ class Engine { #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]; + 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; @@ -1190,8 +1197,8 @@ class Engine { 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 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); @@ -1347,61 +1354,79 @@ class Engine { } thr[(size_t)PAD * tid] = e; #pragma omp barrier - // gather -#pragma omp for schedule(static) nowait - for (int p = 0; p < N; ++p) { - double fx = 0, fy = 0, fz = 0; - for (int s = gather_start[p]; s < gather_start[p + 1]; ++s) { - const double* c = &contrib[3 * (size_t)gather_idx[s]]; - fx += c[0]; - fy += c[1]; - fz += c[2]; + // Gather the bonded contributions; this is the last update of f, so the + // variable Langevin error sum (sum of |f/m|^2, see integrate_inner) is + // accumulated here, in fixed blocks of particles, 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; +#pragma omp for schedule(static) + for (int b = 0; b < nblk; ++b) { + double err = 0.0; + for (int p = b * 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 double* c = &contrib[3 * (size_t)gather_idx[s]]; + fx += c[0]; + fy += c[1]; + fz += c[2]; + } + 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 = inv_mass[p], ax = im * fx, ay = im * fy, az = im * fz; + err += ax * ax; + err += ay * ay; + err += az * az; + } } - f[3 * p] += fx; - f[3 * p + 1] += fy; - f[3 * p + 2] += fz; + block_sum[b] = err; } #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) { - // ReferenceVariableStochasticDynamics::updatePart1: step size selection. - // Summed in fixed blocks of particles, so that the step size does not - // depend on the number of threads. - const int nblk = (N + SUM_BLOCK - 1) / SUM_BLOCK; -#pragma omp for schedule(static) - for (int b = 0; b < nblk; ++b) { - double err = 0.0; - for (int p = b * SUM_BLOCK, pe = std::min(N, p + SUM_BLOCK); p < pe; ++p) - for (int d = 0; d < 3; ++d) { - const double a = inv_mass[p] * f[3 * p + d]; - err += a * a; - } - block_sum[b] = err; - } + 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 - { - double err = 0.0; - for (int b = 0; b < nblk; ++b) err += block_sum[b]; - double er = std::sqrt(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; - } + select_step_size(); } const double dt = dt_; const double kT = BOLTZ * T; @@ -1436,6 +1461,7 @@ class Engine { v[c] = vv; x[c] = xx; } + if (pbc) xw[c] = x[c] - img[c]; const double dd = x[c] - x_ref[c]; d2 += dd * dd; } @@ -1455,6 +1481,7 @@ class Engine { time_ += dt; nsteps++; forces_valid = false; + dt_selected = false; } // implicit barrier } }; diff --git a/tests/test_native.py b/tests/test_native.py index b5c8b6a..71b0b09 100644 --- a/tests/test_native.py +++ b/tests/test_native.py @@ -213,6 +213,7 @@ def build(sim): 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:]: From bd52d3476f630a34e3875aff08ca3032ac56dbae Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:18:45 +0100 Subject: [PATCH 13/23] Store one force vector per bond and two per angle The bonded terms wrote the force on every particle they involve into the contribution buffer, 2 vectors per bond and 3 per angle, although the force on j is -f_i for a bond and -f_i - f_k for an angle. For a chain that is 120 bytes per particle and step written and read back by the gather, the largest single item of the per-step memory traffic. Store only f_i for bonds and f_i, f_k for angles, and let the gather index say whether to add the vector, subtract it, or subtract it and the next one (the same expression as before, so trajectories are bit-identical: position hashes of a 4,000-particle loop extrusion run, 1 and 3 threads). This saves 72 of the 120 bytes for a chain. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 96 +++++++++++++++++++++--------------- 1 file changed, 57 insertions(+), 39 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index cf828a2..4688112 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -640,7 +640,10 @@ class Engine { bool topology_dirty = true; std::vector contrib; - std::vector gather_start, gather_idx; + std::vector gather_start; + std::vector gather_idx; + // 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; @@ -766,35 +769,48 @@ class Engine { } // ---- 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 off = 0; + size_t slots = 0, nterm = 0; for (auto& b : bonds) { - b.contrib_offset = off; - off += 2 * b.i.size(); + b.contrib_offset = slots; + slots += b.i.size(); + nterm += 2 * b.i.size(); } for (auto& a : angles) { - a.contrib_offset = off; - off += 3 * a.i.size(); + a.contrib_offset = slots; + slots += 2 * a.i.size(); + nterm += 3 * a.i.size(); } - contrib.assign(3 * off, 0.0); - std::vector owner(off); + 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) { - owner[b.contrib_offset + 2 * q] = b.i[q]; - owner[b.contrib_offset + 2 * q + 1] = b.j[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) { - owner[a.contrib_offset + 3 * q] = a.i[q]; - owner[a.contrib_offset + 3 * q + 1] = a.j[q]; - owner[a.contrib_offset + 3 * q + 2] = a.k[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); } gather_start.assign(N + 1, 0); - for (size_t c = 0; c < off; ++c) gather_start[owner[c] + 1]++; + 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(off, 0); + gather_idx.assign(nterm, 0); std::vector fl(gather_start.begin(), gather_start.end() - 1); - for (size_t c = 0; c < off; ++c) gather_idx[fl[owner[c]]++] = (int)c; + for (size_t c = 0; c < nterm; ++c) gather_idx[fl[owner[c]]++] = code[c]; topology_dirty = false; } @@ -1270,13 +1286,10 @@ class Engine { } e += en; const double s = r > 0 ? -de / r : 0.0; - double* c = C + 6 * (size_t)q; + double* c = C + 3 * (size_t)q; c[0] = s * dx; c[1] = s * dy; c[2] = s * dz; - c[3] = -c[0]; - c[4] = -c[1]; - c[5] = -c[2]; } } for (const AngleSet& a : angles) { @@ -1292,7 +1305,7 @@ class Engine { min_image(ax, ay, az); min_image(bx, by, bz); } - double* c = C + 9 * (size_t)q; + double* c = C + 6 * (size_t)q; // f_i, f_k const AngleTable& at = a.tables[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; @@ -1300,7 +1313,7 @@ class Engine { if (aa2 == 0 || bb2 == 0) { at.t.eval(0.0, en, de); e += en; - for (int z = 0; z < 9; ++z) c[z] = 0.0; + for (int z = 0; z < 6; ++z) c[z] = 0.0; continue; } const double inv_ab = 1.0 / std::sqrt(aa2 * bb2); @@ -1318,12 +1331,9 @@ class Engine { c[0] = fix; c[1] = fiy; c[2] = fiz; - c[3] = -fix - fkx; - c[4] = -fiy - fky; - c[5] = -fiz - fkz; - c[6] = fkx; - c[7] = fky; - c[8] = fkz; + 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); @@ -1331,7 +1341,7 @@ class Engine { at.t.eval(theta, en, de); // de = dE/dtheta e += en; if (nn < 1e-12 * std::sqrt(aa2 * bb2)) { - for (int z = 0; z < 9; ++z) c[z] = 0.0; + 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) @@ -1343,12 +1353,9 @@ class Engine { c[0] = fix; c[1] = fiy; c[2] = fiz; - c[3] = -fix - fkx; - c[4] = -fiy - fky; - c[5] = -fiz - fkz; - c[6] = fkx; - c[7] = fky; - c[8] = fkz; + c[3] = fkx; + c[4] = fky; + c[5] = fkz; } } } @@ -1366,10 +1373,21 @@ class Engine { for (int p = b * 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 double* c = &contrib[3 * (size_t)gather_idx[s]]; - fx += c[0]; - fy += c[1]; - fz += c[2]; + 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]; From 14e6d8768bba95c2655a3675eb988b8c1d013d9c Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:22:36 +0100 Subject: [PATCH 14/23] Filter list-build candidates four at a time with AVX2 In the x86-64-v3 build, compare four candidates per iteration and move the accepted entries to the front with a byte shuffle chosen by the comparison mask (16-entry table), instead of one candidate per iteration. The candidate buffer is padded to a multiple of four with far-away entries. The arithmetic is the same as in the scalar loop (no FMA, same order), so the lists and trajectories are bit-identical, also between the two builds (position hashes of a 4,000-particle loop extrusion run, 1 and 3 threads, both builds). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared node, cycles vary by ~10 %), per particle and step: cycles instructions baseline build: 664 1612 x86-64-v3 build: 626 1352 Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 72 ++++++++++++++++++++++++++++++------ 1 file changed, 60 insertions(+), 12 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 4688112..882c7ed 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -42,6 +42,9 @@ #ifdef _OPENMP #include #endif +#ifdef __AVX2__ +#include +#endif namespace pcn { @@ -967,11 +970,11 @@ class Engine { } // 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) { - ts.bx.resize(2 * ncand); - ts.by.resize(2 * ncand); - ts.bz.resize(2 * ncand); - ts.be.resize(2 * ncand); + if ((int)ts.bx.size() < ncand + 3) { // + padding to a multiple of 4 + ts.bx.resize(2 * ncand + 3); + ts.by.resize(2 * ncand + 3); + ts.bz.resize(2 * ncand + 3); + ts.be.resize(2 * ncand + 3); } double* const BX = ts.bx.data(); double* const BY = ts.by.data(); @@ -992,17 +995,16 @@ class Engine { } 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) ts.ent.resize(2 * (nent + nbuf)); + if (ts.ent.size() < nent + nbuf + 4) ts.ent.resize(2 * (nent + nbuf + 4)); uint32_t* const out = ts.ent.data() + nent; - int n = 0; - for (int k = 0; k < nbuf; ++k) { - const double dx = px - BX[k], dy = py - BY[k], dz = pz - BZ[k]; - out[n] = BE[k]; - n += (dx * dx + dy * dy + dz * dz < rl2); - } + const int n = filter_candidates(px, py, pz, BX, BY, BZ, BE, nbuf, rl2, out); // drop p itself and its exclusions (compared 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]; @@ -1052,6 +1054,52 @@ class Engine { } } + // Entries BE[k] of the candidates within sqrt(rl2) of (px, py, pz), in order, + // to out[0, n); returns n. 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* 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); + 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 int m = _mm256_movemask_pd(_mm256_cmp_pd(d2, RL2, _CMP_LT_OQ)); + const __m128i e = _mm_loadu_si128((const __m128i*)(BE + k)); + _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]; + out[n] = BE[k]; + n += (dx * dx + dy * dy + dz * dz < rl2); + } +#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 From 5952f12fc0fccbb7e9c92df094a88a24bd87d891 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:26:21 +0100 Subject: [PATCH 15/23] Copy the stencil runs of the list build in groups of four with AVX2 The nine stencil columns of a cell hold a few particles each (about 3.5 in the loop extrusion benchmark), and the compiler's vectorised copy loop spends most of its time in its prologue and epilogue. In the x86-64-v3 build, copy each run in whole groups of four, reading up to three entries past the run from padded arrays and writing past it into the candidate buffer, where the next run or the far-away padding overwrites them. Trajectories are bit-identical (both builds, 1 and 3 threads). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared node), per particle and step: 1352 -> 1301 instructions, 626 -> 600 cycles. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 882c7ed..84e1e48 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -878,7 +878,7 @@ class Engine { ncell *= grid_nc[d]; } cell_of.resize(N); - cell_list.resize(N); + cell_list.resize(N + 4); // + padding for the run copies below nb_count.resize(N); cell_start.assign(ncell + 1, 0); } @@ -904,12 +904,12 @@ class Engine { } 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); + 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; - double* const SZ = SY + N; + 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]; @@ -970,11 +970,11 @@ class Engine { } // 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 + 3) { // + padding to a multiple of 4 - ts.bx.resize(2 * ncand + 3); - ts.by.resize(2 * ncand + 3); - ts.bz.resize(2 * ncand + 3); - ts.be.resize(2 * ncand + 3); + 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(); @@ -987,12 +987,27 @@ class Engine { 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 From 0398895d9f03cb874168c643213dbb566feacb94 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:31:14 +0100 Subject: [PATCH 16/23] Keep the integrator's new coordinates in registers The integrator stored x[c] and read it back twice (for the wrapped coordinate and the displacement since the last list build); as all arrays are double, the compiler had to assume that each store may change the other inputs. Use the new coordinate from the register and restrict-qualified local pointers. Also skip the square root of the inverse mass per particle when all masses are equal (polychrom's default). Trajectories are bit-identical (both builds, 1 and 3 threads). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared node), per particle and step: 1301 -> 1294 instructions, 600 -> 584 cycles (within the noise of this node). Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 40 +++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 84e1e48..189eadd 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -295,6 +295,7 @@ class Engine { img.assign(3 * (size_t)N, 0.0); mass.assign(N, 100.0); inv_mass.assign(N, 0.01); + uniform_sqrt_inv_mass = std::sqrt(inv_mass[0]); (void)zig(); } @@ -314,10 +315,13 @@ class Engine { } 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]; } + uniform_sqrt_inv_mass = uniform && inv_mass[0] > 0 ? std::sqrt(inv_mass[0]) : 0.0; invalidate(); } @@ -631,6 +635,7 @@ class Engine { bool pbc = false; double box[3] = {0, 0, 0}; std::vector x, v, f, mass, inv_mass; + 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 offset at the last build (multiple of box) std::vector xw; // x - img, refreshed every force evaluation @@ -1518,32 +1523,43 @@ class Engine { 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 double* __restrict IMG = img.data(); + 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 = inv_mass[p]; + const double im = IM[p]; if (im == 0) continue; - const double sim = std::sqrt(im); + const double sim = sim_all != 0 ? sim_all : std::sqrt(im); double d2 = 0.0; for (int d = 0; d < 3; ++d) { const size_t c = 3 * (size_t)p + d; const double g = znormal(base + ((uint64_t)c << 24)); - if (integrator == BROWNIAN) { + double xx; + if (brownian) { // ReferenceBrownianDynamics - const double dx = dt / gamma * im * f[c] + std::sqrt(2.0 * kT * dt / gamma) * sim * g; - x[c] += dx; - v[c] = dx / dt; + 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]; - double xx = x[c] + 0.5 * dt * vv; + 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; + V[c] = vv; } - if (pbc) xw[c] = x[c] - img[c]; - const double dd = x[c] - x_ref[c]; + X[c] = xx; + if (wrap) XW[c] = xx - IMG[c]; + const double dd = xx - XREF[c]; d2 += dd * dd; } if (!(d2 <= std::numeric_limits::max())) bad = true; // NaN or inf From 77e38b372829db20231c0cd81863a12b0e2b2fdc Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:33:20 +0100 Subject: [PATCH 17/23] Do not load per-term parameters that are the same for all terms polychrom gives all particles the same mass, all chain bonds the same length and stiffness, and all angles the same potential, yet the gather, the integrator and the bonded loops loaded the inverse mass, r0 and k, and the angle table index per particle or term: 8 + 16 + 4 bytes per particle and step from memory for large systems. Detect the uniform case when the parameters are set and use the first value. Trajectories are bit-identical (1 and 3 threads). Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 189eadd..5a52b59 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -229,6 +229,7 @@ struct BondSet { // harmonic (k, r0) or tabulated E(r) 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; @@ -243,6 +244,7 @@ struct AngleTable { 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; }; @@ -321,6 +323,7 @@ class Engine { 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(); } @@ -379,6 +382,8 @@ class Engine { } 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) { @@ -444,6 +449,7 @@ class Engine { 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(); } @@ -635,6 +641,7 @@ class Engine { 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 offset at the last build (multiple of box) @@ -1348,8 +1355,8 @@ class Engine { if (b.tabulated) { b.tables[b.tab[q]].eval(r, en, de); } else { - const double ext = r - b.r0[q]; - de = b.k[q] * ext; + 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; } e += en; @@ -1374,7 +1381,7 @@ class Engine { min_image(bx, by, bz); } double* c = C + 6 * (size_t)q; // f_i, f_k - const AngleTable& at = a.tables[a.tab[q]]; + 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; @@ -1464,7 +1471,8 @@ class Engine { f[3 * p + 1] = fy; f[3 * p + 2] = fz; if (vl) { - const double im = inv_mass[p], ax = im * fx, ay = im * fy, az = im * fz; + 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; @@ -1535,7 +1543,7 @@ class Engine { 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 = IM[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); double d2 = 0.0; From 07945b36e65f0a6c845709a95b5a99929bc17526 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:34:35 +0100 Subject: [PATCH 18/23] Store periodic images as integer counts The image offset of each coordinate at the last list build (a multiple of the box) was stored as a double and read by the integrator every step to update the wrapped coordinates. Store the count as a 32-bit integer instead: 12 instead of 24 bytes per particle and step. The product count * box is the same double as before, so trajectories are bit-identical (1 and 3 threads). A count beyond 2e9 boxes (or NaN) is reported as an exploded simulation. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 5a52b59..69aa74d 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -294,7 +294,7 @@ class Engine { 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.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]); @@ -644,8 +644,8 @@ class Engine { 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 offset at the last build (multiple of box) - std::vector xw; // x - img, refreshed every force evaluation + 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; @@ -845,15 +845,16 @@ class Engine { fl += 1.0; } if (w < 0) w = 0; - img[3 * p + d] = fl * box[d]; + 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) { - img[c] = 0.0; - xw[c] = x[c]; - } + 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 @@ -1262,11 +1263,12 @@ class Engine { fast_list.clear(); } } - // xw = x - img (wrapped coordinates, PBC only) is kept up to date by - // the integrator; after a rebuild, img has changed. + // 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 (size_t c = 0; c < 3 * (size_t)N; ++c) xw[c] = x[c] - img[c]; + 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(); @@ -1536,7 +1538,8 @@ class Engine { double* __restrict V = v.data(); double* __restrict XW = xw.data(); const double* __restrict F = f.data(); - const double* __restrict IMG = img.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; @@ -1566,7 +1569,7 @@ class Engine { V[c] = vv; } X[c] = xx; - if (wrap) XW[c] = xx - IMG[c]; + if (wrap) XW[c] = xx - IMG[c] * box_d[d]; const double dd = xx - XREF[c]; d2 += dd * dd; } From 0fd0367608a8ec2f92346b1ba8089b60d8c85ed8 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:41:48 +0100 Subject: [PATCH 19/23] Gather bonded forces chunk by chunk while they are in the cache The bonded terms wrote their forces into the contribution buffer in one pass over all terms, and a second pass after a barrier gathered them per particle. For large systems the buffer (72 bytes per particle for a chain) goes to memory and back every step, and the coordinates are streamed twice, once for the bonds and once for the angles. Process the terms in chunks of 64 particles instead (the blocks of the error sum), by the chunk of their lowest particle, and gather a chunk right after its terms: the terms of chunks 0..k are all that reach chunk k. Each thread takes a contiguous range of chunks; a chunk that terms from an earlier range reach into (a ring's closing bond, long bonds, or a chain crossing the range boundary) is gathered after a barrier. Terms that are not sorted by their lowest particle (loop extrusion bonds) are processed through an index. Contribution slots, the gather order and the error-sum blocks are unchanged, so trajectories are bit-identical (both builds, 1, 3 and 4 threads). Add a test with a ring and bonds spanning 1500 particles at N = 2600, compared with the Reference platform with 1 and 4 threads. With every chunk gathered right away (ignoring terms from other ranges), it fails: E Mismatched elements: 11 / 7800 (0.141%) 1 failed, 16 deselected in 3.07s The chunks are small so that all threads get some: with chunks of 1024 particles, a single run at N = 10,000 had only 10 of them, and became slower than before this optimisation work at 32 and 64 threads. Loop extrusion benchmark, EPYC 7763 (Zen 3), one run on contiguous cores, at the end of this series, steps/s (two runs each): threads 1 8 32 64 before the series 546 3328 4843 4572 chunks of 1024 particles 759 3880 4526 3946 chunks of 256 particles 742 4276 5316 4740 chunks of 64 particles 747 4322 5714 4916 At N = 200,000 (8, 32 and 64 threads) the chunk size makes no measurable difference. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 338 +++++++++++++++++++++-------------- tests/test_native.py | 22 +++ 2 files changed, 223 insertions(+), 137 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 69aa74d..b043691 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -233,6 +233,10 @@ struct BondSet { // harmonic (k, r0) or tabulated E(r) 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 { @@ -247,6 +251,8 @@ struct AngleSet { 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; @@ -657,6 +663,7 @@ class Engine { 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; @@ -820,6 +827,40 @@ class Engine { 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]; @@ -1236,6 +1277,146 @@ class Engine { } } + // ---- 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 @@ -1342,146 +1523,29 @@ class Engine { f[3 * p + 2] -= 2 * t.k[2] * dz; } } - // bonded terms into the contribution buffer - for (const BondSet& b : bonds) { - const int n = (int)b.i.size(); - const bool bp = b.pbc && pbc; - double* C = contrib.data() + 3 * b.contrib_offset; -#pragma omp for schedule(static) nowait - for (int q = 0; q < n; ++q) { - 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; - } - e += en; - const double s = r > 0 ? -de / r : 0.0; - double* c = C + 3 * (size_t)q; - c[0] = s * dx; - c[1] = s * dy; - c[2] = s * dz; - } - } - for (const AngleSet& a : angles) { - const int n = (int)a.i.size(); - const bool ap = a.pbc && pbc; - double* C = contrib.data() + 3 * a.contrib_offset; -#pragma omp for schedule(static) nowait - for (int q = 0; q < n; ++q) { - 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 = C + 6 * (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); - e += 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 - e += 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 - e += 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; - } - } - } - thr[(size_t)PAD * tid] = e; -#pragma omp barrier - // Gather the bonded contributions; this is the last update of f, so the - // variable Langevin error sum (sum of |f/m|^2, see integrate_inner) is - // accumulated here, in fixed blocks of particles, so that it does not - // depend on the number of threads. + // 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; -#pragma omp for schedule(static) - for (int b = 0; b < nblk; ++b) { - double err = 0.0; - for (int p = b * 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[b] = err; + 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(); diff --git a/tests/test_native.py b/tests/test_native.py index 71b0b09..444bc48 100644 --- a/tests/test_native.py +++ b/tests/test_native.py @@ -220,6 +220,28 @@ def build(sim): 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 From 064ddf3741522be039389383cd89dcd359e294a6 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:47:45 +0100 Subject: [PATCH 20/23] Keep the rare Ziggurat rejection path out of the integrator loop The normal deviate generator was inlined three times per particle with its rejection loop, tail sampling and exp/log calls, which are needed for about 1 % of the draws. The integrator loop ran out of registers and kept the displacement sum and its array pointers on the stack. Inline only the first draw and the fast acceptance test, continue in a separate cold function from the same state otherwise, and draw the three deviates of a particle before updating its coordinates. The random numbers and trajectories are bit-identical (both builds, 1 and 3 threads). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared node), per particle and step: 1369 -> 1286 instructions, 618-634 -> 579-581 cycles. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index b043691..8227a3f 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -194,12 +194,15 @@ static inline const ZigguratTables& zig() { return t; } -// Standard normal deviate from the stream that starts at state `st`. -static inline double znormal(uint64_t st) { +// 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 (;;) { - 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; @@ -218,9 +221,23 @@ static inline double znormal(uint64_t st) { 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 // --------------------------------------------------------------------------- @@ -1613,10 +1630,13 @@ class Engine { 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 = 3 * (size_t)p + d; - const double g = znormal(base + ((uint64_t)c << 24)); + const size_t c = c0 + d; + const double g = gs[d]; double xx; if (brownian) { // ReferenceBrownianDynamics From ef4ca4a4e9d9b9d8da5f1b744f868f71b96448ad Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 11:53:54 +0100 Subject: [PATCH 21/23] Drop chain-neighbour exclusions in the list-build filter After the distance filter, every accepted candidate was compared with the particle itself and its exclusions in a second loop. In a polymer, almost every particle excludes just its two chain neighbours, which are always within the list radius. For particles with at most two exclusions, compare the candidates' indices with them (and the entry with the particle itself) in the filter, four at a time with AVX2, and leave them out of the same compaction. Lists and trajectories are bit-identical (both builds, 1 and 3 threads). Loop extrusion benchmark, N = 10,000, one thread, EPYC 7551 (Zen 1, shared node), per particle and step: 1286 -> 1249 instructions, 579-581 -> 556-563 cycles, 5 -> 4 branch misses. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index 8227a3f..ff55280 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -1090,11 +1090,22 @@ class Engine { 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; - const int n = filter_candidates(px, py, pz, BX, BY, BZ, BE, nbuf, rl2, out); - // drop p itself and its exclusions (compared branch-free if few) + // 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) { @@ -1141,10 +1152,12 @@ class Engine { } // Entries BE[k] of the candidates within sqrt(rl2) of (px, py, pz), in order, - // to out[0, n); returns n. BX, BY, BZ, BE are padded to a multiple of 4 with - // far-away candidates, and out has room for 3 entries beyond n. + // 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* out) { + 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 @@ -1164,14 +1177,19 @@ class Engine { }; 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 int m = _mm256_movemask_pd(_mm256_cmp_pd(d2, RL2, _CMP_LT_OQ)); 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); @@ -1179,8 +1197,9 @@ class Engine { #else for (int k = 0; k < nbuf; ++k) { const double dx = px - BX[k], dy = py - BY[k], dz = pz - BZ[k]; - out[n] = BE[k]; - n += (dx * dx + dy * dy + dz * dz < rl2); + 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; From f3bf897dc71dd940d5c22627c4a225c460eb8d96 Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 12:05:04 +0100 Subject: [PATCH 22/23] Describe the per-core techniques in the engine's header comment Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/_native/engine.hpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/polychrom/_native/engine.hpp b/polychrom/_native/engine.hpp index ff55280..ed9ae27 100644 --- a/polychrom/_native/engine.hpp +++ b/polychrom/_native/engine.hpp @@ -15,15 +15,22 @@ // 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 in parallel into a contribution buffer and gathered -// per particle through a CSR index; +// * 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). +// (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. From d00825382ef23a715d8894bf104ed2dd9b00ab5c Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Wed, 25 Nov 2026 19:25:55 +0100 Subject: [PATCH 23/23] Fix black and flake8 findings in the native platform The pull request template asks for black, isort and flake8. Before this commit: would reformat tests/test_native.py would reformat polychrom/native.py polychrom/native.py:679:121: E501 line too long (124 > 120 characters) polychrom/native.py:871:9: F841 local variable 'globals_' is assigned to but never used tests/test_native.py:249:5: F841 local variable 'rng' is assigned to but never used tests/test_native.py:255:121: E501 line too long (131 > 120 characters) Wrap the long lines as black does, drop the unused random generator, and keep the call of _globals in _add_external (it registers the global parameters that g() reads) without assigning its result. black, isort and flake8 (max line length 120, as in pyproject.toml) now pass for polychrom/native.py, polychrom/simulation.py, tests/test_native.py and setup.py. Assisted-by: claude-opus-5.5 (Claude Code) --- polychrom/native.py | 10 +++++----- tests/test_native.py | 5 +++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/polychrom/native.py b/polychrom/native.py index 7690122..6056b6d 100644 --- a/polychrom/native.py +++ b/polychrom/native.py @@ -679,7 +679,9 @@ def __init__(self, system, integrator, forces, pbc, length_scale=1.0): if not isinstance(integrator, NativeIntegrator): raise TypeError("the native platform needs a NativeIntegrator") if system.getNumForces() != len(forces): - raise NotImplementedError("forces added directly to Simulation.system are not supported by the native platform") + raise NotImplementedError( + "forces added directly to Simulation.system are not supported by the native platform" + ) self._system = system self._integrator = integrator self._forces = list(forces) @@ -841,9 +843,7 @@ def build(first): 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" - ) + 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: @@ -871,7 +871,7 @@ def build(first): def _add_external(self, f, name): energy = _strip_prefix(f.getEnergyFunction(), name) - globals_ = self._globals(f) + 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())) diff --git a/tests/test_native.py b/tests/test_native.py index 444bc48..30ddd7b 100644 --- a/tests/test_native.py +++ b/tests/test_native.py @@ -248,13 +248,14 @@ def test_fast_set_forces(PBCbox): 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 - rng = np.random.default_rng(3) 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)) + 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