Loading...
Searching...
No Matches
aux::ProblemSetUp Class Reference

Set up the GP-dimer problem. More...

#include <gpr/auxiliary/ProblemSetUp.h>

Public Member Functions

 ProblemSetUp ()
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 cutOffEnergy (const gpr::FieldMatrixd &E_reference, gpr::FieldMatrixd &E_R)
 Subtract reference energy value from E_R.
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 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 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.
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 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.

Detailed Description

Set up the GP-dimer problem.

Definition at line 33 of file ProblemSetUp.h.

Constructor & Destructor Documentation

◆ ProblemSetUp()

aux::ProblemSetUp::ProblemSetUp ( )

Definition at line 40 of file ProblemSetUp.cpp.

40{ }

◆ ~ProblemSetUp()

aux::ProblemSetUp::~ProblemSetUp ( )
virtual

Definition at line 42 of file ProblemSetUp.cpp.

42{ }

Member Function Documentation

◆ activateFrozenAtoms()

bool aux::ProblemSetUp::activateFrozenAtoms ( const gpr::Coord & R,
const double activation_distance,
gpr::AtomsConfiguration & atoms_config )

Update the active frozen-atom set for one or more configurations.

If nn_frozen is positive, the active set contains the nearest nn_frozen atoms selected from the active and inactive frozen atoms, measured against every configuration in R. Otherwise, inactive atoms within activation_distance are activated; a nonpositive distance activates all inactive atoms. When evict_frozen is enabled, active atoms outside a positive activation radius return to the inactive set. Radius and nearest-neighbour distances use the configured periodic cell. Pair-type indices are added when the active set introduces a new pair.

Frozen atoms that coincide with moving atoms are removed from the frozen sets. The active set is rebuilt only when its membership changes, preserving feature order otherwise.

Parameters
RConfigurations with one row per geometry. Each row may contain moving-atom coordinates only or the full frame; frozen coordinates in a full-frame row do not participate in selection.
activation_distanceRadius for activating and, when enabled, evicting frozen atoms.
atoms_configStructure and active/inactive atom sets used by the GP model.
Returns
True if the active frozen-atom membership changes; false otherwise.

We let it go on if all atoms are moving. If frozen atoms exist, some of them must be either active or inactive: all of them already active (every frozen atom within the activation distance from the start) is a complete state with nothing left to activate, not an error.

Definition at line 138 of file ProblemSetUp.cpp.

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}
#define EMPTY
Definition Macros.h:39
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.
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::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
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
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
void resize(const Index_t num_atoms)
Definition Structures.h:814

◆ calculateGeneralPotential()

void aux::ProblemSetUp::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.

Each row of 'R' represents one configuration including the coordinates of the moving atoms: [x_1,y_1,z_1,x_2,y_2,z_2,...].

Parameters
atoms_configFull configuration of the system (i.e. both constrained and unconstrained atoms)
cell_dimensionsCell dimension
mid_pointCoordinates, energy and gradients of the middle point of the dimer (1 x D)
general_potentialReference to a type-erased potential wrapper
num_of_callsNumber of calls for the general potential
batch_chunkOracle batch chunk (pot::OracleBatchLayout::chunk): 0 evaluates every image a rank owns in one call, K cuts the images into contiguous chunks of K

Images are shared out over the MPI ranks by a layout-independent owner map, each rank evaluates its images in one call through the potential's batch surface where it has one, a failure on any rank reaches every rank before the values are exchanged, and every rank holds the same energies and gradients afterwards.

Definition at line 579 of file ProblemSetUp.cpp.

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
611 pot::OracleBatchLayout layout = pot::OracleBatchLayout::world(batch_chunk);
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}
@ MOVING_ATOM
Definition Enums.h:35
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.
static DistributedState & instance()
void initialize(int block_size=0, int nprow=0)
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.
@ 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)
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
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).

◆ cutOffEnergy()

void aux::ProblemSetUp::cutOffEnergy ( const gpr::FieldMatrixd & E_reference,
gpr::FieldMatrixd & E_R )

Subtract reference energy value from E_R.

Parameters
E_referenceA field with the reference enerfy
E_RIn/out energy field

Definition at line 44 of file ProblemSetUp.cpp.

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}

◆ initializeEnergyAndGradient()

void aux::ProblemSetUp::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.

Definition at line 744 of file ProblemSetUp.cpp.

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}
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.
FieldMatrixd E

◆ removeDuplicatedAtoms()

void aux::ProblemSetUp::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.

Definition at line 520 of file ProblemSetUp.cpp.

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}

◆ setPairtypeForMovingAtoms()

void aux::ProblemSetUp::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.

The provided n_pt should be equal to the number of active pairtypes before the update.

Parameters
atomtype_movAtomtype indices for moving atoms (1 x N_mov)
pairtypePairtype indices for pairs of atomtypes before the update (n_at x n_at)
n_ptNumber of active pairtypes before and after the update

Definition at line 502 of file ProblemSetUp.cpp.

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}

◆ updateConf()

void aux::ProblemSetUp::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.

Parameters
unfreezed_atomsThe coordinates of the unfreezed atoms
atoms_configThe initial configuration of atoms.
coord_atom_newThe new coordinates of all atoms.

Definition at line 475 of file ProblemSetUp.cpp.

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}

The documentation for this class was generated from the following files: