Loading...
Searching...
No Matches
ProblemSetUp.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5/*
6 * ProblemSetUpimer.cpp
7 *
8 * Created on: 24 Sep 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#include "ProblemSetUp.h"
14
15#include <algorithm>
16#include <cfloat>
17#include <cmath>
18#include <cstdlib>
19#include <iostream>
20#include <limits>
21#include <numeric>
22#include <set>
23#include <stdexcept>
24#include <string>
25#include <vector>
26
29#include "MinImage.h"
30
31#ifdef GPR_HAVE_MPI
32#include <mpi.h>
33#ifdef GPR_LINALG_SCALAPACK
35#endif
36#endif
37
38namespace aux {
39
41
43
46{
47 if (E_R.size() == 0) return;
48 // E_reference is the per-observation zero level; when E_R holds
49 // multiple observation rows (e.g. an init_observations buffer
50 // carried over from a sibling phase) but E_reference is a single
51 // row, broadcast the scalar zero level across every row instead
52 // of letting Eigen assert on the row mismatch. Same-shape inputs
53 // take the elementwise path verbatim.
54 if (E_reference.rows() == E_R.rows() && E_reference.cols() == E_R.cols()) {
55 E_R = E_R - E_reference;
56 return;
57 }
58 if (E_reference.size() == 1) {
59 const double e0 = E_reference(0, 0);
60 E_R.array() -= e0;
61 return;
62 }
63 // Single-column reference broadcast across rows.
64 if (E_reference.cols() == E_R.cols() && E_reference.rows() == 1) {
65 E_R.rowwise() -= E_reference.row(0);
66 return;
67 }
68 // Single-row reference broadcast across columns.
69 if (E_reference.rows() == E_R.rows() && E_reference.cols() == 1) {
70 E_R.colwise() -= E_reference.col(0);
71 return;
72 }
73 // Same-shape fallback (will still assert if dimensions do not
74 // match; this preserves the original failure mode for unrelated
75 // mis-sizings that are not the legitimate scalar-broadcast case).
76 E_R = E_R - E_reference;
77}
78
79namespace {
80
81// Rows of R that list every atom of the frame, frozen ones included, cut
82// down to their moving columns. A frozen atom in such a row sits at
83// distance zero from itself and would activate whatever the radius. Rows
84// that already hold only the moving atoms come back unchanged.
85gpr::Coord movingColumns(const gpr::Coord& R,
86 const gpr::AtomsConfiguration& atoms_config)
87{
88 const Eigen::Index n_atoms = atoms_config.is_frozen.size();
89 const Eigen::Index n_moving = atoms_config.atoms_mov.positions.cols() / 3;
90 if (n_moving == n_atoms || R.cols() != 3 * n_atoms) return R;
91 gpr::Coord packed(R.rows(), 3 * n_moving);
92 for (Eigen::Index i = 0; i < R.rows(); ++i) {
93 Eigen::Index m = 0;
94 for (Eigen::Index a = 0; a < n_atoms; ++a) {
95 if (*(atoms_config.is_frozen.data() + a) != MOVING_ATOM) continue;
96 for (Eigen::Index c = 0; c < 3; ++c)
97 packed(i, 3 * m + c) = R(i, 3 * a + c);
98 ++m;
99 }
100 }
101 return packed;
102}
103
104// Pair distances between moving atoms are unchanged by any rigid motion of
105// the moving set, so only the frozen anchors can fix it. One anchor leaves
106// three rotations about itself and two leave the rotation about the line
107// through them: the GP then predicts no force along that rotation and a
108// search on it cannot remove the true force there. Anchors that span a plane
109// leave no rigid motion. Returns the smallest count from requested, taken
110// in the sorted order, whose anchors span a plane. A pool on one line keeps
111// the rotation about it at every count, so the request then stands.
112template <class Position>
113gpr::Index_t anchorsFixingRigidMotion(gpr::Index_t requested,
114 const std::vector<gpr::Index_t>& order,
115 const Position& position,
116 const gpr::geometry::PairBox& box)
117{
118 const auto pool = static_cast<gpr::Index_t>(order.size());
119 gpr::Index_t count = std::min(requested, pool);
120 const auto spansPlane = [&](gpr::Index_t n) {
121 if (n < 3) return false;
122 const Eigen::Vector3d base = position(order[0]);
123 const Eigen::Vector3d u = box.displacement(base, position(order[1]));
124 for (gpr::Index_t j = 2; j < n; ++j) {
125 const Eigen::Vector3d v =
126 box.displacement(base, position(order[j]));
127 if (u.cross(v).norm() > 1e-6 * u.norm() * v.norm()) return true;
128 }
129 return false;
130 };
131 for (gpr::Index_t n = count; n <= pool; ++n)
132 if (spansPlane(n)) return n;
133 return count;
134}
135
136} // namespace
137
139 const double activation_distance,
140 gpr::AtomsConfiguration& atoms_config)
141{
142 const gpr::Coord R = movingColumns(R_given, atoms_config);
143 const gpr::geometry::PairBox box(atoms_config.cell);
144 gpr::AtomsPositionAndType* inactive_atoms =
145 &atoms_config.atoms_froz_inactive;
146 gpr::AtomsPositionAndType* active_atoms = &atoms_config.atoms_froz_active;
147 gpr::AtomsPositionAndType* moving_atoms = &atoms_config.atoms_mov;
148 std::vector<int> activated_atoms(inactive_atoms->positions.cols() / 3,
149 EMPTY);
150 std::vector<gpr::Index_t> activated_atomtypes; // auxiliary vector
151 bool active_set_changed = false;
152
157 if (moving_atoms->positions.size() != atoms_config.positions.size()) {
158 gpr::assertMsg(
159 inactive_atoms->type.size() != 0 || active_atoms->type.size() != 0,
160 "Error! Frozen atoms exist but neither the active nor the "
161 "inactive frozen set holds any!\n");
162 }
163
164 // First, check that there are no clones of moving atoms among inactive
165 // frozen atoms. If such a clone exists - remove it from the set of inactive
166 // frozen atoms. We are checking atoms by calculating the distance between
167 // them.
168 const gpr::Index_t n_active_before_cleanup =
169 static_cast<gpr::Index_t>(active_atoms->type.size());
170 removeDuplicatedAtoms(*moving_atoms, *active_atoms, *inactive_atoms);
171 active_set_changed = active_atoms->type.size() != n_active_before_cleanup;
172
173 // Keep a fixed number of frozen atoms nearest to any moving atom in R.
174 // Membership changes require re-featuring the stored observations, even
175 // though the number of pair features stays constant.
176 const gpr::Index_t nn_frozen = atoms_config.nn_frozen;
177 if (nn_frozen > 0) {
178 const gpr::Index_t n_act_old = static_cast<gpr::Index_t>(
179 gpr::coord::numPoints(active_atoms->positions));
180 const gpr::Index_t n_inact = static_cast<gpr::Index_t>(
181 gpr::coord::numPoints(inactive_atoms->positions));
182 const gpr::Index_t pool = n_act_old + n_inact;
183 if (pool == 0) return active_set_changed;
184
185 // Snapshot the pooled frozen atoms (active first, then inactive)
186 // before any resize zeroes the buffers.
187 const gpr::Coord oa_pos = active_atoms->positions;
188 const gpr::FieldMatrixIdx oa_type = active_atoms->type;
189 const gpr::Coord oi_pos = inactive_atoms->positions;
190 const gpr::FieldMatrixIdx oi_type = inactive_atoms->type;
191 auto pool_pos = [&](gpr::Index_t k) {
192 return k < n_act_old ? gpr::coord::at(oa_pos, k)
193 : gpr::coord::at(oi_pos, k - n_act_old);
194 };
195 auto pool_type = [&](gpr::Index_t k) {
196 return k < n_act_old ? *(oa_type.data() + k)
197 : *(oi_type.data() + (k - n_act_old));
198 };
199
200 std::vector<double> mindist(pool);
201 for (gpr::Index_t k = 0; k < pool; ++k) {
202 const Eigen::Vector3d p = pool_pos(k);
203 double dmin = std::numeric_limits<double>::infinity();
204 for (Eigen::Index i = 0; i < R.rows(); ++i)
205 for (Eigen::Index m = 0, end = R.cols() / 3; m < end; ++m)
206 dmin =
207 std::min(dmin, box.dist2(p, gpr::coord::at(R, i, m)));
208 mindist[k] = dmin;
209 }
210 std::vector<gpr::Index_t> order(pool);
211 std::iota(order.begin(), order.end(), 0);
212 std::stable_sort(order.begin(), order.end(),
213 [&](gpr::Index_t a, gpr::Index_t b) {
214 return mindist[a] < mindist[b];
215 });
216 const gpr::Index_t n_new_act =
217 anchorsFixingRigidMotion(nn_frozen, order, pool_pos, box);
218
219 // The active set is unchanged iff exactly the previously-active atoms
220 // (pool indices [0, n_act_old)) are reselected; any chosen index >=
221 // n_act_old means a previously-inactive atom entered.
222 bool changed = active_set_changed || (n_new_act != n_act_old);
223 for (gpr::Index_t r = 0; r < n_new_act && !changed; ++r)
224 if (order[r] >= n_act_old) changed = true;
225
226 // Preserve the active feature ordering when membership is unchanged.
227 // Descriptor rows use frozen-atom order, so reordering without a model
228 // refresh would make cached observations inconsistent with predictions.
229 if (!changed) return false;
230 if (n_new_act > nn_frozen)
231 std::cout << "\n Using " << n_new_act << " nearest frozen atoms "
232 << "instead of " << nn_frozen << ": fewer anchors leave "
233 << "a rigid rotation of the moving atoms that pair "
234 << "distances do not see.\n";
235
236 active_atoms->resize(n_new_act);
237 inactive_atoms->resize(pool - n_new_act);
238 for (gpr::Index_t r = 0; r < pool; ++r) {
239 const gpr::Index_t src = order[r];
240 if (r < n_new_act) {
241 gpr::coord::set(active_atoms->positions, 0, r, pool_pos(src));
242 *(active_atoms->type.data() + r) = pool_type(src);
243 } else {
244 const gpr::Index_t d = r - n_new_act;
245 gpr::coord::set(inactive_atoms->positions, 0, d, pool_pos(src));
246 *(inactive_atoms->type.data() + d) = pool_type(src);
247 }
248 }
249
250 if (changed) {
251 // Register moving x active-frozen pairtypes for any new types.
252 std::set<gpr::Index_t> umov(
253 moving_atoms->type.data(),
254 moving_atoms->type.data() + moving_atoms->type.size());
255 std::set<gpr::Index_t> uact(
256 active_atoms->type.data(),
257 active_atoms->type.data() + active_atoms->type.size());
258 for (const auto& ai: umov) {
259 for (const auto& aj: uact) {
260 if (atoms_config.pairtype(ai, aj) == EMPTY) {
261 ++atoms_config.n_pt;
262 atoms_config.pairtype(ai, aj) =
263 atoms_config.n_pt + EMPTY;
264 atoms_config.pairtype(aj, ai) =
265 atoms_config.n_pt + EMPTY;
266 }
267 }
268 }
269 }
270 return changed;
271 }
272
273 // Do it only if inactive atoms exist
274 if (inactive_atoms->positions.size() != 0) {
275 if (activation_distance > 0.) {
276 // Activate inactive frozen atoms (for every omage) within the
277 // radius of 'activation_distance' from some moving atom
278 gpr::Index_t num_inactive_atoms =
279 gpr::coord::numPoints(inactive_atoms->positions);
280 std::vector<int> activated_atoms(num_inactive_atoms, EMPTY);
281 for (Eigen::Index i = 0; i < R.rows(); ++i) {
282 for (gpr::Index_t n = 0; n < num_inactive_atoms; ++n) {
283 Eigen::Vector3d atom_fro_inactive =
284 gpr::coord::at(inactive_atoms->positions, n);
285 for (Eigen::Index m = 0, end = R.cols() / 3; m < end; ++m) {
286 if (box.dist2(atom_fro_inactive,
287 gpr::coord::at(R, i, m)) <
288 activation_distance * activation_distance)
289 activated_atoms[n] = n;
290 }
291 }
292 }
293
294 // Check how many atoms were activated
295 long num_activated_atoms = activated_atoms.size() -
296 std::count(activated_atoms.begin(),
297 activated_atoms.end(), EMPTY);
298 // std::cout <<num_activated_atoms << " were activated\n" ;
299
300 if (num_activated_atoms != 0) {
301 // Existing active atoms must be carried across the grow:
302 // AtomsPositionAndType::resize() setZero()s its buffers (it
303 // does not preserve), so without saving + restoring them the
304 // previously-active frozen atoms are wiped to position 0 /
305 // type 0. That makes pairtype(type 0, moving type) == EMPTY
306 // and indexes the per-pairtype distance vector at -1 (segfault)
307 // -- only triggered when the active set grows incrementally
308 // (small actdist_fro + a migrating moving atom), which the
309 // all-at-once activation in the molecular benches never hits.
310 const gpr::Index_t existing_active =
311 static_cast<gpr::Index_t>(active_atoms->type.size());
312 gpr::Coord existing_positions = active_atoms->positions;
313 gpr::FieldMatrixIdx existing_type = active_atoms->type;
314
315 gpr::Index_t tot_activated_atoms =
316 existing_active + (gpr::Index_t)num_activated_atoms;
317 std::cout << "\n Now we have " << tot_activated_atoms
318 << " total active atoms\n";
319 active_atoms->resize(tot_activated_atoms);
320 activated_atomtypes.resize(num_activated_atoms);
321
322 // Restore the previously-active frozen atoms (resize zeroed
323 // them); the newly-activated atoms are appended after.
324 for (gpr::Index_t k = 0; k < existing_active; ++k) {
325 gpr::coord::set(active_atoms->positions, 0, k,
326 gpr::coord::at(existing_positions, k));
327 *(active_atoms->type.data() + k) =
328 *(existing_type.data() + k);
329 }
330
331 gpr::Index_t counter = existing_active;
332 gpr::Index_t new_idx = 0;
333 // Append newly-activated inactive atoms after the existing ones
334 for (gpr::Index_t n = 0; n < activated_atoms.size(); ++n) {
335 if (activated_atoms[n] != EMPTY) {
337 active_atoms->positions, 0, counter,
338 gpr::coord::at(inactive_atoms->positions, n));
339 *(active_atoms->type.data() + counter) =
340 *(inactive_atoms->type.data() + n);
341 activated_atomtypes[new_idx] =
342 *(active_atoms->type.data() + counter);
343 ++counter;
344 ++new_idx;
345 }
346 }
347
348 // Now remove reassigned inactive atoms
349 for (int n = (int)activated_atoms.size() - 1; n >= 0; --n) {
350 if (activated_atoms[n] != EMPTY) {
352 activated_atoms[n]);
353 gpr::field::deleteColumn(inactive_atoms->type,
354 activated_atoms[n]);
355 }
356 }
357
358 active_set_changed = true;
359 }
360 } else {
361 // Activate all inactive frozen atoms
362 active_set_changed = true;
363 atoms_config.atoms_froz_active = atoms_config.atoms_froz_inactive;
364 inactive_atoms->clear();
365 }
366
367 // Activate new pairtypes if necessary
368 if (active_set_changed) {
369 // Get unique indices from `atoms_config.atomtype_mov`.
370 std::set<gpr::Index_t> unique_atomtype_mov(
371 moving_atoms->type.data(),
372 moving_atoms->type.data() + moving_atoms->type.size());
373 std::set<gpr::Index_t> unique_atomtype_activated(
374 activated_atomtypes.begin(), activated_atomtypes.end());
375
376 // NOTE: Same logic as setPairtypeForMovingAtoms() but for
377 // activated-frozen × moving pairs rather than moving × moving.
378 for (auto& at_i: unique_atomtype_mov) {
379 for (auto& at_j: unique_atomtype_activated) {
380 if (atoms_config.pairtype(at_i, at_j) == EMPTY) {
381 ++atoms_config.n_pt;
382 atoms_config.pairtype(at_i, at_j) =
383 atoms_config.n_pt + EMPTY;
384 atoms_config.pairtype(at_j, at_i) =
385 atoms_config.n_pt + EMPTY;
386 }
387 }
388 }
389 }
390 }
391
392 // Eviction (Stage 2 fix): the active frozen set is non-monotonic. Active
393 // frozen atoms that have left the activation radius are returned to the
394 // inactive set, so the set tracks a moving window around the migrating
395 // moving atom(s) instead of growing without bound (the bloat failure mode
396 // the CuH2-step demonstrator surfaced). The eviction predicate is the same
397 // within-actdist test used for activation, applied every step; no
398 // hysteresis margin (uniform rule). When every active atom is still within
399 // range -- the all-at-once activation the molecular benches produce --
400 // nothing is evicted and the partition is unchanged (bit-identical).
401 //
402 // Opt-in (config: evict_frozen): the default keeps the monotonic
403 // activation contract (so the molecular benches and the activateFrozenAtoms
404 // unit test stay bit-identical); eviction is a non-monotonic active-set
405 // variant the caller enables explicitly, mirroring the opt-in
406 // nearest-neighbour construction rather than replacing actdist_fro.
407 if (atoms_config.evict_frozen && activation_distance > 0. &&
408 active_atoms->positions.size() != 0) {
409 const gpr::Index_t n_active = static_cast<gpr::Index_t>(
410 gpr::coord::numPoints(active_atoms->positions));
411 std::vector<gpr::Index_t> keep, evict;
412 keep.reserve(n_active);
413 for (gpr::Index_t a = 0; a < n_active; ++a) {
414 const Eigen::Vector3d pa =
415 gpr::coord::at(active_atoms->positions, a);
416 bool within = false;
417 for (Eigen::Index i = 0; i < R.rows() && !within; ++i) {
418 for (Eigen::Index m = 0, end = R.cols() / 3; m < end; ++m) {
419 if (box.dist2(pa, gpr::coord::at(R, i, m)) <
420 activation_distance * activation_distance) {
421 within = true;
422 break;
423 }
424 }
425 }
426 if (within)
427 keep.push_back(a);
428 else
429 evict.push_back(a);
430 }
431 if (!evict.empty()) {
432 const gpr::Coord old_active_pos = active_atoms->positions;
433 const gpr::FieldMatrixIdx old_active_type = active_atoms->type;
434 const gpr::Index_t n_inactive_old = static_cast<gpr::Index_t>(
435 gpr::coord::numPoints(inactive_atoms->positions));
436 const gpr::Coord old_inactive_pos = inactive_atoms->positions;
437 const gpr::FieldMatrixIdx old_inactive_type = inactive_atoms->type;
438
439 // Rebuild the active set from the survivors (order preserved).
440 active_atoms->resize(static_cast<gpr::Index_t>(keep.size()));
441 for (std::size_t k = 0; k < keep.size(); ++k) {
442 gpr::coord::set(active_atoms->positions, 0,
443 static_cast<gpr::Index_t>(k),
444 gpr::coord::at(old_active_pos, keep[k]));
445 *(active_atoms->type.data() + k) =
446 *(old_active_type.data() + keep[k]);
447 }
448
449 // Restore the existing inactive atoms (resize zeros), then append
450 // the evicted atoms after them.
451 inactive_atoms->resize(n_inactive_old +
452 static_cast<gpr::Index_t>(evict.size()));
453 for (gpr::Index_t k = 0; k < n_inactive_old; ++k) {
454 gpr::coord::set(inactive_atoms->positions, 0, k,
455 gpr::coord::at(old_inactive_pos, k));
456 *(inactive_atoms->type.data() + k) =
457 *(old_inactive_type.data() + k);
458 }
459 for (std::size_t e = 0; e < evict.size(); ++e) {
460 const gpr::Index_t dst =
461 n_inactive_old + static_cast<gpr::Index_t>(e);
462 gpr::coord::set(inactive_atoms->positions, 0, dst,
463 gpr::coord::at(old_active_pos, evict[e]));
464 *(inactive_atoms->type.data() + dst) =
465 *(old_active_type.data() + evict[e]);
466 }
467 std::cout << "\n Evicted " << evict.size() << " frozen atoms; "
468 << keep.size() << " remain active\n";
469 active_set_changed = true;
470 }
471 }
472 return active_set_changed;
473}
474
475void ProblemSetUp::updateConf(const gpr::Coord& unfreezed_atoms,
476 const gpr::AtomsConfiguration& atoms_config,
477 gpr::Coord& coord_atom_new)
478{
479 const Eigen::Index num_atoms = atoms_config.is_frozen.size();
480 const Eigen::Index num_images = unfreezed_atoms.rows();
481
482 coord_atom_new.resize(num_images, atoms_config.positions.cols());
483 for (Eigen::Index row = 0; row < num_images; ++row) {
484 const Eigen::Index source_row =
485 atoms_config.positions.rows() == num_images ? row : 0;
486 coord_atom_new.row(row) = atoms_config.positions.row(source_row);
487
488 gpr::Index_t counter = 0;
489 for (Eigen::Index n = 0; n < num_atoms; ++n) {
490 if (*(atoms_config.is_frozen.data() + n) == MOVING_ATOM) {
492 coord_atom_new, static_cast<gpr::Index_t>(row),
493 static_cast<gpr::Index_t>(n),
494 gpr::coord::at(unfreezed_atoms,
495 static_cast<gpr::Index_t>(row), counter));
496 ++counter;
497 }
498 }
499 }
500}
501
503 const gpr::FieldMatrixIdx& atomtype_mov, gpr::Index_t& n_pt,
504 gpr::FieldMatrixi& pairtype)
505{
506 Eigen::Index N_mov = atomtype_mov.size();
507 for (Eigen::Index i = 0; i < N_mov - 1; ++i) {
508 gpr::Index_t at_i = atomtype_mov(0, i);
509 for (Eigen::Index j = i + 1; j < N_mov; ++j) {
510 gpr::Index_t at_j = atomtype_mov(0, j);
511 if (pairtype(at_i, at_j) == EMPTY) {
512 ++n_pt;
513 pairtype(at_i, at_j) = n_pt + EMPTY;
514 pairtype(at_j, at_i) = n_pt + EMPTY;
515 }
516 }
517 }
518}
519
521 const gpr::AtomsPositionAndType& moving_atoms,
522 gpr::AtomsPositionAndType& active_atoms,
523 gpr::AtomsPositionAndType& inactive_atoms)
524{
525 std::vector<gpr::Index_t> clones_act;
526 std::vector<gpr::Index_t> clones_inact;
527 Eigen::Index num_active_atoms = active_atoms.type.size();
528 Eigen::Index num_inactive_atoms = inactive_atoms.type.size();
529 Eigen::Index num_moving_atoms = moving_atoms.type.size();
530
531 if (num_moving_atoms == 0) return;
532
533 for (Eigen::Index m = 0; m < num_moving_atoms; ++m) {
534 Eigen::Vector3d mov_at_pos = gpr::coord::at(moving_atoms.positions, m);
535 for (Eigen::Index n = 0; n < num_active_atoms; ++n) {
536 Eigen::Vector3d act_at_pos =
537 gpr::coord::at(active_atoms.positions, n);
538 if ((mov_at_pos - act_at_pos).norm() <= DBL_EPSILON) {
539 clones_act.push_back(n);
540 }
541 }
542 for (Eigen::Index n = 0; n < num_inactive_atoms; ++n) {
543 Eigen::Vector3d inact_at_pos =
544 gpr::coord::at(inactive_atoms.positions, n);
545 if ((mov_at_pos - inact_at_pos).norm() <= DBL_EPSILON) {
546 clones_inact.push_back(n);
547 }
548 }
549 }
550
551 // Sort and Unique to ensure safe backward deletion
552 std::sort(clones_act.begin(), clones_act.end());
553 auto last_act = std::unique(clones_act.begin(), clones_act.end());
554 clones_act.erase(last_act, clones_act.end());
555
556 std::sort(clones_inact.begin(), clones_inact.end());
557 auto last_inact = std::unique(clones_inact.begin(), clones_inact.end());
558 clones_inact.erase(last_inact, clones_inact.end());
559
560 eraseClones(clones_act, active_atoms);
561 eraseClones(clones_inact, inactive_atoms);
562}
563
564void ProblemSetUp::eraseClones(const std::vector<gpr::Index_t>& clones,
566{
567 if (!clones.empty()) {
568 gpr::io::LogManager log_man;
569 log_man << "Warning! Some (in)active frozen atoms were discovered as "
570 "duplicates of the moving atoms and will be removed from "
571 "the data sets..\n";
572 for (int n = (int)clones.size() - 1; n >= 0; --n) {
573 gpr::coord::deleteColumnAt(atoms.positions, clones[n]);
574 gpr::field::deleteColumn(atoms.type, clones[n]);
575 }
576 }
577}
578
580 const gpr::AtomsConfiguration& atoms_config,
581 const gpr::vector3_reg (&cell_dimensions)[3],
582 gpr::Observation& middle_point, pot::PotentialWrapper& general_potential,
583 gpr::Index_t& num_of_calls, Eigen::Index batch_chunk)
584{
585 const Eigen::Index num_im = middle_point.R.rows();
586 const Eigen::Index dim = middle_point.R.cols();
587 const Eigen::Index num_atoms = atoms_config.is_frozen.size();
588 gpr::Coord coord_atom_new;
589 double box[9];
590
591 box[0] = cell_dimensions[0](0);
592 box[1] = cell_dimensions[0](1);
593 box[2] = cell_dimensions[0](2);
594
595 box[3] = cell_dimensions[1](0);
596 box[4] = cell_dimensions[1](1);
597 box[5] = cell_dimensions[1](2);
598
599 box[6] = cell_dimensions[2](0);
600 box[7] = cell_dimensions[2](1);
601 box[8] = cell_dimensions[2](2);
602
603 middle_point.E.resize(num_im, 1);
604 middle_point.E.setZero();
605 middle_point.G.resize(num_im, dim);
606 middle_point.G.setZero();
607
608 updateConf(middle_point.R, atoms_config, coord_atom_new);
609 const Eigen::Index full_dim = coord_atom_new.cols();
610
612#ifdef GPR_HAVE_MPI
613 if (layout.nprocs > 1) {
614 // Trigger DistributedState::initialize() so the dup'd gpr_comm_ is
615 // valid before any collective in this function uses it.
618 }
619#endif
620 // Independent images rotate through the communicator so that small
621 // central stencils use every rank; the rotation is a function of the
622 // call count, which every rank holds.
623 layout.owner_offset =
624 layout.nprocs > 1
625 ? static_cast<int>(num_of_calls %
626 static_cast<gpr::Index_t>(layout.nprocs))
627 : 0;
628
629 // Owned images are evaluated in one call per group through the
630 // potential's batch surface; a potential without one is walked image
631 // by image. Every attempted image counts as one oracle call, so the
632 // count a failure leaves behind is the number of geometries the
633 // potential was asked for.
634 std::vector<double> energies(static_cast<std::size_t>(num_im), 0.0);
635 Eigen::MatrixXd gradients = Eigen::MatrixXd::Zero(num_im, full_dim);
636 gpr::Index_t local_new_calls = 0;
637 std::string failure;
638 const auto nonfinite = [](double energy, const Eigen::RowVectorXd& grad) {
639 return !std::isfinite(energy) || !grad.allFinite();
640 };
641 for (const auto& group: pot::ownedOracleGroups(num_im, layout)) {
642 if (!failure.empty()) break;
643 try {
644 if (general_potential.hasForceBatch() && group.size() > 1) {
645 const std::size_t B = group.size();
646 const auto stride = static_cast<std::size_t>(full_dim);
647 std::vector<double> R(B * stride);
648 std::vector<double> F(B * stride,
649 std::numeric_limits<double>::quiet_NaN());
650 std::vector<double> U(B,
651 std::numeric_limits<double>::quiet_NaN());
652 for (std::size_t b = 0; b < B; ++b) {
653 const Eigen::Index n = group[b];
654 std::copy(coord_atom_new.row(n).data(),
655 coord_atom_new.row(n).data() + full_dim,
656 R.data() + b * stride);
657 }
658 local_new_calls += static_cast<gpr::Index_t>(B);
659 general_potential.forceBatch(num_atoms, B, R.data(),
660 atoms_config.atomicNrs.data(),
661 F.data(), U.data(), nullptr, box);
662 for (std::size_t b = 0; b < B; ++b) {
663 const Eigen::Index n = group[b];
664 energies[static_cast<std::size_t>(n)] = U[b];
665 gradients.row(n) = Eigen::Map<const Eigen::RowVectorXd>(
666 F.data() + b * stride, full_dim);
667 if (nonfinite(U[b], gradients.row(n)))
668 throw std::runtime_error(
669 "Potential evaluation returned nonfinite energy "
670 "or forces");
671 }
672 } else {
673 for (const Eigen::Index n: group) {
674 ++local_new_calls;
675 double E_local = std::numeric_limits<double>::quiet_NaN();
676 Eigen::RowVectorXd G_local = Eigen::RowVectorXd::Constant(
677 full_dim, std::numeric_limits<double>::quiet_NaN());
678 general_potential.force(
679 num_atoms, coord_atom_new.row(n).data(),
680 atoms_config.atomicNrs.data(), G_local.data(), &E_local,
681 nullptr /*variance*/, box);
682 energies[static_cast<std::size_t>(n)] = E_local;
683 gradients.row(n) = G_local;
684 if (nonfinite(E_local, G_local))
685 throw std::runtime_error(
686 "Potential evaluation returned nonfinite energy "
687 "or forces");
688 }
689 }
690 } catch (const std::exception& error) {
691 failure = error.what();
692 if (failure.empty()) failure = "Potential evaluation failed";
693 } catch (...) {
694 failure = "Potential evaluation raised a non-standard exception";
695 }
696 }
697
698 // Publish failures before any value collective. All participants leave
699 // through the same exception and count every attempted oracle call.
700 const auto outcome = pot::agreeOracleBatchStatus(
701 failure.empty() ? pot::OracleBatchStatus::Ok
703 failure, layout);
704#ifdef GPR_HAVE_MPI
705 if (layout.nprocs > 1) {
706 gpr::Index_t global_calls = 0;
707 MPI_Allreduce(&local_new_calls, &global_calls, 1, MPI_UINT32_T, MPI_SUM,
708 layout.comm);
709 num_of_calls += global_calls;
710 } else {
711 num_of_calls += local_new_calls;
712 }
713#else
714 num_of_calls += local_new_calls;
715#endif
716 if (outcome.status != pot::OracleBatchStatus::Ok) {
717 middle_point.E.setConstant(std::numeric_limits<double>::quiet_NaN());
718 middle_point.G.setConstant(std::numeric_limits<double>::quiet_NaN());
719 throw std::runtime_error(outcome.message);
720 }
721
722 // Every rank holds the owners' values after the union; entries a rank
723 // did not evaluate are positive zero; the bitwise union preserves the
724 // owner's values without changing signed zeros.
725 pot::allreduceOwnedOracleValues(energies, gradients, layout);
726
727 // Forces of the moving atoms become the gradient rows of the
728 // observation.
729 for (Eigen::Index n = 0; n < num_im; ++n) {
730 middle_point.E(n, 0) = energies[static_cast<std::size_t>(n)];
731 gpr::Index_t counter = 0;
732 for (Eigen::Index m = 0; m < num_atoms; ++m) {
733 if (*(atoms_config.is_frozen.data() + m) == MOVING_ATOM) {
734 middle_point.G(n, 3 * counter) = gradients(n, 3 * m);
735 middle_point.G(n, 3 * counter + 1) = gradients(n, 3 * m + 1);
736 middle_point.G(n, 3 * counter + 2) = gradients(n, 3 * m + 2);
737 counter++;
738 }
739 }
740 middle_point.G.row(n) *= -1.;
741 }
742}
743
745 const gpr::FieldMatrixd& E_reference,
746 const gpr::AtomsConfiguration& atoms_config,
747 const gpr::vector3_reg (&system_size)[3], gpr::Observation& middle_point,
748 pot::PotentialWrapper& general_potential, gpr::Index_t& num_of_calls)
749{
750 middle_point.E.resize(E_reference.rows(), E_reference.cols());
751 calculateGeneralPotential(atoms_config, system_size, middle_point,
752 general_potential, num_of_calls);
753}
754
755} /* namespace aux */
@ MOVING_ATOM
Definition Enums.h:35
#define EMPTY
Definition Macros.h:39
One step's oracle points shared out over the ranks of a communicator, with a layout-independent owner...
void removeDuplicatedAtoms(const gpr::AtomsPositionAndType &moving_atoms, gpr::AtomsPositionAndType &active_atoms, gpr::AtomsPositionAndType &inactive_atoms)
Remove clones of the moving atoms from the set of inactive frozen atoms.
void updateConf(const gpr::Coord &unfreezed_atoms, const gpr::AtomsConfiguration &atoms_config, gpr::Coord &coord_atom_new)
Update an atomic configuration with new coordinates for the unfreezed atoms.
virtual ~ProblemSetUp()
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.
void calculateGeneralPotential(const gpr::AtomsConfiguration &atoms_config, const gpr::vector3_reg(&cell_dimensions)[3], gpr::Observation &mid_point, pot::PotentialWrapper &general_potential, gpr::Index_t &num_of_calls, Eigen::Index batch_chunk=0)
Invoke potential calculation.
void initializeEnergyAndGradient(const gpr::FieldMatrixd &E_reference, const gpr::AtomsConfiguration &atoms_config, const gpr::vector3_reg(&system_size)[3], gpr::Observation &middle_point, pot::PotentialWrapper &general_potential, gpr::Index_t &num_of_calls)
Initialize energy and gradient.
void cutOffEnergy(const gpr::FieldMatrixd &E_reference, gpr::FieldMatrixd &E_R)
Subtract reference energy value from E_R.
void setPairtypeForMovingAtoms(const gpr::FieldMatrixIdx &atomtype_mov, gpr::Index_t &n_pt, gpr::FieldMatrixi &pairtype)
Set pairtype indices for moving+moving atom pairs and gives the updated number of active pairtypes.
void displacement(const double p[3], const double q[3], double dr[3]) const
Displacement from p to q. Cartesian q - p when the cell is zero.
Definition MinImage.h:210
double dist2(const Eigen::Vector3d &p, const Eigen::Vector3d &q) const
Definition MinImage.h:235
Responsible for logging.
Definition LogManager.h:28
static DistributedState & instance()
void initialize(int block_size=0, int nprow=0)
Type-erased wrapper around any potential that provides a force() interface.
void forceBatch(long N, std::size_t B, const double *R, const int *atomicNrs, double *F, double *U, const double *box)
Batched means; requires hasForceBatch().
bool hasForceBatch() const noexcept
void force(long N, const double *R, const int *atomicNrs, double *F, double *U, double *energy_noise_rms, const double *box)
Invoke the wrapped potential.
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
void deleteColumnAt(FieldMatrixd &mat, Index_t j)
Index_t numPoints(const FieldMatrixd &mat)
void deleteColumn(Eigen::PlainObjectBase< Derived > &mat, Eigen::Index j)
Eigen::Vector3d vector3_reg
Definition Macros.h:36
Eigen::Matrix< int, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixi
Definition Macros.h:27
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
@ Failed
A geometry was refused or a value was not finite; message set.
Definition OracleBatch.h:81
OracleBatchOutcome agreeOracleBatchStatus(OracleBatchStatus local_status, const std::string &local_message, const OracleBatchLayout &layout)
std::vector< std::vector< Eigen::Index > > ownedOracleGroups(Eigen::Index count, const OracleBatchLayout &layout)
The groups this rank evaluates, each one batch call, in point order.
void allreduceOwnedOracleValues(std::vector< double > &energies, Eigen::MatrixXd &gradients, const OracleBatchLayout &layout, double *communication_seconds)
Stores configurations of all atoms in the system.
Definition Structures.h:832
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
Coord positions
Positions of all atoms in the system.
Definition Structures.h:833
Structure of atoms positions and types.
Definition Structures.h:810
void resize(const Index_t num_atoms)
Definition Structures.h:814
Observation data: energy, gradient and positions.
FieldMatrixd E
How a step's oracle points are shared out.
Definition OracleBatch.h:46
OracleBatchComm comm
Definition OracleBatch.h:62
static OracleBatchLayout world(Eigen::Index chunk=0, int owner_offset=0)
The layout of the running communicator (rank 0 of 1 without MPI).