| 1 | // ---------------------------------------------------------------------------- |
| 2 | // "THE BEER-WARE LICENSE" (Revision 42): |
| 3 | // <[email protected]> wrote this file. As long as you retain |
| 4 | // this notice you can do whatever you want with this stuff. If we meet some day, |
| 5 | // and you think this stuff is worth it, you can buy me a beer in return. |
| 6 | // Daniel Kratzert |
| 7 | // ---------------------------------------------------------------------------- |
| 8 | // |
| 9 | // C++ acceleration for the Shortest-Distance-Matrix algorithm. |
| 10 | // This module is optional; sdm.py falls back to pure Python when it cannot be |
| 11 | // imported (HAS_CPP = False). |
| 12 | // |
| 13 | // Build: |
| 14 | // macOS : uv pip install pybind11 && uv pip install -e . --no-build-isolation |
| 15 | // (optionally: brew install libomp for multi-threaded acceleration) |
| 16 | // Linux : uv pip install pybind11 && uv pip install -e . --no-build-isolation |
| 17 | // Windows: uv pip install pybind11 && uv pip install -e . --no-build-isolation |
| 18 | // |
| 19 | // Interface (mirrors the Python call in sdm.py): |
| 20 | // |
| 21 | // calc_sdm_cpp( |
| 22 | // coords : list[list[float]], # N × 3, fractional coordinates |
| 23 | // symm_m : list[list[list[float]]], # S × 3×3 symmetry rotation matrices |
| 24 | // symm_t : list[list[float]], # S × 3 symmetry translation vectors |
| 25 | // aga, bbe, cal, asq, bsq, csq : float, # metric-tensor cross-terms / squares |
| 26 | // radii : list[float], # N covalent radii (Å), from Python |
| 27 | // is_h : list[bool], # N hydrogen flags |
| 28 | // parts : list[float], # N disorder-part numbers |
| 29 | // ) -> list[tuple[int, int, int, float, float, bool]] |
| 30 | // i j best_n mind dddd covalent |
| 31 | |
| 32 | #include <pybind11/pybind11.h> |
| 33 | #include <pybind11/stl.h> |
| 34 | |
| 35 | #include <array> |
| 36 | #include <cmath> |
| 37 | #include <tuple> |
| 38 | #include <vector> |
| 39 | |
| 40 | #ifdef _OPENMP |
| 41 | #include <omp.h> |
| 42 | #endif |
| 43 | |
| 44 | namespace py = pybind11; |
| 45 | |
| 46 | // Result type: (atom_i, atom_j, symmetry_index, min_distance, covalent_cutoff, is_covalent) |
| 47 | using ResultTuple = std::tuple<int, int, int, double, double, bool>; |
| 48 | |
| 49 | // --------------------------------------------------------------------------- |
| 50 | // calc_sdm_cpp |
| 51 | // |
| 52 | // Direct C++17 translation of the pure-Python fallback in sdm.py::SDM.calc_sdm(). |
| 53 | // The outer i-loop is parallelised with OpenMP; each thread accumulates results |
| 54 | // in a thread-local vector that is merged serially after the parallel region. |
| 55 | // When OpenMP is not available at compile time the loop runs single-threaded. |
| 56 | // --------------------------------------------------------------------------- |
| 57 | std::vector<ResultTuple> calc_sdm_cpp( |
| 58 | const std::vector<std::vector<double>>& coords, // N × 3 |
| 59 | const std::vector<std::vector<std::vector<double>>>& symm_m, // S × 3×3 |
| 60 | const std::vector<std::vector<double>>& symm_t, // S × 3 |
| 61 | double aga, double bbe, double cal, |
| 62 | double asq, double bsq, double csq, |
| 63 | const std::vector<double>& radii, |
| 64 | const std::vector<bool>& is_h, |
| 65 | const std::vector<double>& parts |
| 66 | ) { |
| 67 | const int N = static_cast<int>(coords.size()); |
| 68 | const int S = static_cast<int>(symm_m.size()); |
| 69 | |
| 70 | // Pre-compute at2 + 0.5 (at2_plushalf in Python) |
| 71 | std::vector<std::array<double, 3>> at2_ph(N); |
| 72 | for (int j = 0; j < N; ++j) { |
| 73 | at2_ph[j] = {coords[j][0] + 0.5, coords[j][1] + 0.5, coords[j][2] + 0.5}; |
| 74 | } |
| 75 | |
| 76 | // Flatten symmetry data for cache-friendly access |
| 77 | // symm_m_flat[s][row][col] and symm_t_flat[s][0..2] |
| 78 | std::vector<std::array<std::array<double, 3>, 3>> sm(S); |
| 79 | std::vector<std::array<double, 3>> st(S); |
| 80 | for (int s = 0; s < S; ++s) { |
| 81 | for (int r = 0; r < 3; ++r) |
| 82 | for (int c = 0; c < 3; ++c) |
| 83 | sm[s][r][c] = symm_m[s][r][c]; |
| 84 | for (int c = 0; c < 3; ++c) |
| 85 | st[s][c] = symm_t[s][c]; |
| 86 | } |
| 87 | |
| 88 | #ifdef _OPENMP |
| 89 | const int nthreads = omp_get_max_threads(); |
| 90 | std::vector<std::vector<ResultTuple>> thread_results(nthreads); |
| 91 | |
| 92 | #pragma omp parallel for schedule(dynamic) |
| 93 | for (int i = 0; i < N; ++i) { |
| 94 | std::vector<ResultTuple>& local = thread_results[omp_get_thread_num()]; |
| 95 | #else |
| 96 | std::vector<ResultTuple> serial_results; |
| 97 | serial_results.reserve(static_cast<size_t>(N) * N / 4); |
| 98 | |
| 99 | for (int i = 0; i < N; ++i) { |
| 100 | std::vector<ResultTuple>& local = serial_results; |
| 101 | #endif |
| 102 | const double x1 = coords[i][0]; |
| 103 | const double y1 = coords[i][1]; |
| 104 | const double z1 = coords[i][2]; |
| 105 | |
| 106 | // Apply all symmetry operations to atom i → prime_array |
| 107 | std::vector<std::array<double, 3>> prime(S); |
| 108 | for (int s = 0; s < S; ++s) { |
| 109 | prime[s][0] = x1 * sm[s][0][0] + y1 * sm[s][1][0] + z1 * sm[s][2][0] + st[s][0]; |
| 110 | prime[s][1] = x1 * sm[s][0][1] + y1 * sm[s][1][1] + z1 * sm[s][2][1] + st[s][1]; |
| 111 | prime[s][2] = x1 * sm[s][0][2] + y1 * sm[s][1][2] + z1 * sm[s][2][2] + st[s][2]; |
| 112 | } |
| 113 | |
| 114 | for (int j = 0; j < N; ++j) { |
| 115 | double mind = 1.0e6; |
| 116 | int best_n = -1; |
| 117 | |
| 118 | const double atp_x = at2_ph[j][0]; |
| 119 | const double atp_y = at2_ph[j][1]; |
| 120 | const double atp_z = at2_ph[j][2]; |
| 121 | |
| 122 | for (int n = 0; n < S; ++n) { |
| 123 | const double dx = prime[n][0] - atp_x; |
| 124 | const double dy = prime[n][1] - atp_y; |
| 125 | const double dz = prime[n][2] - atp_z; |
| 126 | |
| 127 | // Reduce to [-0.5, 0.5) range (equivalent to Python's dx - floor(dx) - 0.5) |
| 128 | const double dpx = dx - std::floor(dx) - 0.5; |
| 129 | const double dpy = dy - std::floor(dy) - 0.5; |
| 130 | const double dpz = dz - std::floor(dz) - 0.5; |
| 131 | |
| 132 | const double A = 2.0 * (dpx * dpy * aga + dpx * dpz * bbe + dpy * dpz * cal); |
| 133 | const double dk2 = dpx * dpx * asq + dpy * dpy * bsq + dpz * dpz * csq + A; |
| 134 | |
| 135 | if (dk2 > 16.0) continue; // distance > 4 Å — skip |
| 136 | |
| 137 | double dk = std::sqrt(dk2); |
| 138 | if (n > 0) dk += 0.0001; // symmetry-generated copies get a tiny penalty |
| 139 | |
| 140 | if (dk > 0.01 && mind >= dk) { |
| 141 | mind = dk; |
| 142 | best_n = n; |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | if (best_n < 0) continue; // no valid distance found → skip pair |
| 147 | |
| 148 | // Compute covalent cutoff (dddd) — mirrors Python logic exactly: |
| 149 | // if (neither is H AND part product is 0) OR same part → use radii sum * 1.2 |
| 150 | // else → 0.0 (non-bonded) |
| 151 | const bool ih_i = is_h[i]; |
| 152 | const bool ih_j = is_h[j]; |
| 153 | const double part_i = parts[i]; |
| 154 | const double part_j = parts[j]; |
| 155 | |
| 156 | double dddd; |
| 157 | if ((!ih_i && !ih_j && part_i * part_j == 0.0) || part_i == part_j) { |
| 158 | dddd = (radii[i] + radii[j]) * 1.2; |
| 159 | } else { |
| 160 | dddd = 0.0; |
| 161 | } |
| 162 | |
| 163 | const bool covalent = mind < dddd; |
| 164 | local.emplace_back(i, j, best_n, mind, dddd, covalent); |
| 165 | } |
| 166 | } // end parallel for |
| 167 | |
| 168 | #ifdef _OPENMP |
| 169 | // Merge thread-local vectors into a single result |
| 170 | std::vector<ResultTuple> results; |
| 171 | for (auto& tr : thread_results) |
| 172 | results.insert(results.end(), tr.begin(), tr.end()); |
| 173 | return results; |
| 174 | #else |
| 175 | return serial_results; |
| 176 | #endif |
| 177 | } |
| 178 | |
| 179 | // --------------------------------------------------------------------------- |
| 180 | // Module registration |
| 181 | // --------------------------------------------------------------------------- |
| 182 | PYBIND11_MODULE(sdm_cpp, m) { |
| 183 | m.doc() = R"doc( |
| 184 | Fast C++ implementation of the Shortest-Distance-Matrix (SDM) algorithm |
| 185 | used by fastmolwidget to grow crystal structures. |
| 186 | |
| 187 | Compiled with OpenMP support when libomp is available (macOS: optionally brew install libomp). |
| 188 | Falls back gracefully to single-threaded execution when OpenMP is absent. |
| 189 | )doc"; |
| 190 | |
| 191 | m.def( |
| 192 | "calc_sdm_cpp", |
| 193 | &calc_sdm_cpp, |
| 194 | py::arg("coords"), |
| 195 | py::arg("symm_m"), |
| 196 | py::arg("symm_t"), |
| 197 | py::arg("aga"), py::arg("bbe"), py::arg("cal"), |
| 198 | py::arg("asq"), py::arg("bsq"), py::arg("csq"), |
| 199 | py::arg("radii"), |
| 200 | py::arg("is_h"), |
| 201 | py::arg("parts"), |
| 202 | R"doc( |
| 203 | Calculate the Shortest Distance Matrix for all atom pairs. |
| 204 | |
| 205 | Parameters |
| 206 | ---------- |
| 207 | coords : list of [x, y, z] (fractional coordinates), length N |
| 208 | symm_m : list of 3×3 symmetry rotation matrices, length S |
| 209 | symm_t : list of 3-element translation vectors, length S |
| 210 | aga : cell[0]*cell[1]*cos(gamma) |
| 211 | bbe : cell[0]*cell[2]*cos(beta) |
| 212 | cal : cell[1]*cell[2]*cos(alpha) |
| 213 | asq : cell[0]**2 |
| 214 | bsq : cell[1]**2 |
| 215 | csq : cell[2]**2 |
| 216 | radii : covalent radii for each atom (Å), length N |
| 217 | is_h : True if the atom is H or D, length N |
| 218 | parts : SHELX disorder-part number for each atom, length N |
| 219 | |
| 220 | Returns |
| 221 | ------- |
| 222 | list of (i, j, best_n, mind, dddd, covalent) |
| 223 | i, j : atom indices |
| 224 | best_n : symmetry-operation index that gave the shortest distance |
| 225 | mind : shortest distance found (Å) |
| 226 | dddd : covalent-bond cutoff (0.0 if the pair cannot be bonded) |
| 227 | covalent : True when mind < dddd |
| 228 | )doc" |
| 229 | ); |
| 230 | |
| 231 | #ifdef _OPENMP |
| 232 | m.attr("has_openmp") = true; |
| 233 | #else |
| 234 | m.attr("has_openmp") = false; |
| 235 | #endif |
| 236 | } |
| 237 |