2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
5 * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
38 * Implements functions in swapcoords.h.
40 * \author Carsten Kutzner <ckutzne@gwdg.de>
41 * \ingroup module_swap
45 #include "swapcoords.h"
55 #include "gromacs/domdec/domdec_struct.h"
56 #include "gromacs/domdec/localatomset.h"
57 #include "gromacs/domdec/localatomsetmanager.h"
58 #include "gromacs/fileio/confio.h"
59 #include "gromacs/fileio/gmxfio.h"
60 #include "gromacs/fileio/xvgr.h"
61 #include "gromacs/gmxlib/network.h"
62 #include "gromacs/math/vec.h"
63 #include "gromacs/mdlib/groupcoord.h"
64 #include "gromacs/mdrunutility/handlerestart.h"
65 #include "gromacs/mdtypes/commrec.h"
66 #include "gromacs/mdtypes/imdmodule.h"
67 #include "gromacs/mdtypes/inputrec.h"
68 #include "gromacs/mdtypes/md_enums.h"
69 #include "gromacs/mdtypes/mdrunoptions.h"
70 #include "gromacs/mdtypes/observableshistory.h"
71 #include "gromacs/mdtypes/state.h"
72 #include "gromacs/mdtypes/swaphistory.h"
73 #include "gromacs/pbcutil/pbc.h"
74 #include "gromacs/timing/wallcycle.h"
75 #include "gromacs/topology/mtop_lookup.h"
76 #include "gromacs/topology/topology.h"
77 #include "gromacs/utility/cstringutil.h"
78 #include "gromacs/utility/fatalerror.h"
79 #include "gromacs/utility/pleasecite.h"
80 #include "gromacs/utility/smalloc.h"
81 #include "gromacs/utility/snprintf.h"
83 static const char* SwS = { "SWAP:" }; /**< For output that comes from the swap module */
84 static const char* SwSEmpty = { " " }; /**< Placeholder for multi-line output */
85 static const char* CompStr[eCompNR] = { "A", "B" }; /**< Compartment name */
86 static const char* SwapStr[eSwapTypesNR + 1] = { "", "X-", "Y-", "Z-",
87 nullptr }; /**< Name for the swap types. */
88 static const char* DimStr[DIM + 1] = { "X", "Y", "Z", nullptr }; /**< Name for the swap dimension. */
90 /** Keep track of through which channel the ions have passed */
98 static const char* ChannelString[eChHistNr] = { "none", "channel0", "channel1" }; /**< Name for the channels */
100 /*! \brief Domain identifier.
102 * Keeps track of from which compartment the ions came before passing the
112 static const char* DomainString[eDomainNr] = { "not_assigned", "Domain_A",
113 "Domain_B" }; /**< Name for the domains */
118 extern template LocalAtomSet LocalAtomSetManager::add<void, void>(ArrayRef<const int> globalAtomIndex);
121 * \brief Implement Computational Electrophysiology swapping.
123 class SwapCoordinates final : public IMDModule
126 IMdpOptionProvider* mdpOptionProvider() override { return nullptr; }
127 IMDOutputProvider* outputProvider() override { return nullptr; }
128 void initForceProviders(ForceProviders* /* forceProviders */) override {}
131 std::unique_ptr<IMDModule> createSwapCoordinatesModule()
133 return std::make_unique<SwapCoordinates>();
140 * Structure containing compartment-specific data.
142 typedef struct swap_compartment
144 int nMol; /**< Number of ion or water molecules detected
145 in this compartment. */
146 int nMolBefore; /**< Number of molecules before swapping. */
147 int nMolReq; /**< Requested number of molecules in compartment. */
148 real nMolAv; /**< Time-averaged number of molecules matching
149 the compartment conditions. */
150 int* nMolPast; /**< Past molecule counts for time-averaging. */
151 int* ind; /**< Indices to collective array of atoms. */
152 real* dist; /**< Distance of atom to bulk layer, which is
153 normally the center layer of the compartment */
154 int nalloc; /**< Allocation size for ind array. */
155 int inflow_net; /**< Net inflow of ions into this compartment. */
160 * This structure contains data needed for the groups involved in swapping:
161 * split group 0, split group 1, solvent group, ion groups.
163 typedef struct swap_group
165 /*!\brief Construct a swap group given the managed swap atoms.
167 * \param[in] atomset Managed indices of atoms that are part of the swap group.
169 swap_group(const gmx::LocalAtomSet& atomset);
170 char* molname = nullptr; /**< Name of the group or ion type */
171 int apm = 0; /**< Number of atoms in each molecule */
172 gmx::LocalAtomSet atomset; /**< The atom indices in the swap group */
173 rvec* xc = nullptr; /**< Collective array of group atom positions (size nat) */
174 ivec* xc_shifts = nullptr; /**< Current (collective) shifts (size nat) */
175 ivec* xc_eshifts = nullptr; /**< Extra shifts since last DD step (size nat) */
176 rvec* xc_old = nullptr; /**< Old (collective) positions (size nat) */
177 real q = 0.; /**< Total charge of one molecule of this group */
178 real* m = nullptr; /**< Masses (can be omitted, size apm) */
179 unsigned char* comp_from = nullptr; /**< (Collective) Stores from which compartment this
180 molecule has come. This way we keep track of
181 through which channel an ion permeates
182 (size nMol = nat/apm) */
183 unsigned char* comp_now = nullptr; /**< In which compartment this ion is now (size nMol) */
184 unsigned char* channel_label = nullptr; /**< Which channel was passed at last by this ion?
186 rvec center; /**< Center of the group; COM if masses are used */
187 t_compartment comp[eCompNR]; /**< Distribution of particles of this group across
188 the two compartments */
189 real vacancy[eCompNR]; /**< How many molecules need to be swapped in? */
190 int fluxfromAtoB[eChanNR]; /**< Net flux of ions per channel */
191 int nCyl[eChanNR]; /**< Number of ions residing in a channel */
192 int nCylBoth = 0; /**< Ions assigned to cyl0 and cyl1. Not good. */
195 t_swapgrp::swap_group(const gmx::LocalAtomSet& atomset) : atomset{ atomset }
200 for (int compartment = eCompA; compartment < eCompNR; ++compartment)
202 comp[compartment] = {};
203 vacancy[compartment] = 0;
205 for (int channel = eChan0; channel < eChanNR; ++channel)
207 fluxfromAtoB[channel] = 0;
213 * Main (private) data structure for the position swapping protocol.
217 int swapdim; /**< One of XX, YY, ZZ */
218 t_pbc* pbc; /**< Needed to make molecules whole. */
219 FILE* fpout; /**< Output file. */
220 int ngrp; /**< Number of t_swapgrp groups */
221 std::vector<t_swapgrp> group; /**< Separate groups for channels, solvent, ions */
222 int fluxleak; /**< Flux not going through any of the channels. */
223 real deltaQ; /**< The charge imbalance between the compartments. */
227 /*! \brief Check whether point is in channel.
229 * A channel is a cylinder defined by a disc
230 * with radius r around its center c. The thickness of the cylinder is
237 * <---------c--------->
243 * \param[in] point The position (xyz) under consideration.
244 * \param[in] center The center of the cylinder.
245 * \param[in] d_up The upper extension of the cylinder.
246 * \param[in] d_down The lower extension.
247 * \param[in] r_cyl2 Cylinder radius squared.
248 * \param[in] pbc Structure with info about periodic boundary conditions.
249 * \param[in] normal The membrane normal direction is typically 3, i.e. z, but can be x or y also.
251 * \returns Whether the point is inside the defined cylindric channel.
253 static gmx_bool is_in_channel(rvec point, rvec center, real d_up, real d_down, real r_cyl2, t_pbc* pbc, int normal)
256 int plane1, plane2; /* Directions tangential to membrane */
259 plane1 = (normal + 1) % 3; /* typically 0, i.e. XX */
260 plane2 = (normal + 2) % 3; /* typically 1, i.e. YY */
262 /* Get the distance vector dr between the point and the center of the cylinder */
263 pbc_dx(pbc, point, center, dr); /* This puts center in the origin */
265 /* Check vertical direction */
266 if ((dr[normal] > d_up) || (dr[normal] < -d_down))
271 /* Check radial direction */
272 if ((dr[plane1] * dr[plane1] + dr[plane2] * dr[plane2]) > r_cyl2)
277 /* All check passed, this point is in the cylinder */
282 /*! \brief Prints output to CompEL output file.
284 * Prints to swap output file how many ions are in each compartment,
285 * where the centers of the split groups are, and how many ions of each type
286 * passed the channels.
288 static void print_ionlist(t_swap* s, double time, const char comment[])
291 fprintf(s->fpout, "%12.5e", time);
293 // Output number of molecules and difference to reference counts for each
294 // compartment and ion type
295 for (int iComp = 0; iComp < eCompNR; iComp++)
297 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
299 t_compartment* comp = &s->group[ig].comp[iComp];
301 fprintf(s->fpout, "%10d%10.1f%10d", comp->nMol, comp->nMolAv - comp->nMolReq, comp->inflow_net);
305 // Output center of split groups
306 fprintf(s->fpout, "%10g%10g", s->group[eGrpSplit0].center[s->swapdim],
307 s->group[eGrpSplit1].center[s->swapdim]);
309 // Output ion flux for each channel and ion type
310 for (int iChan = 0; iChan < eChanNR; iChan++)
312 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
314 t_swapgrp* g = &s->group[ig];
315 fprintf(s->fpout, "%10d", g->fluxfromAtoB[iChan]);
319 /* Output the number of molecules that leaked from A to B */
320 fprintf(s->fpout, "%10d", s->fluxleak);
322 fprintf(s->fpout, "%s\n", comment);
326 /*! \brief Get the center of a group of nat atoms.
328 * Since with PBC an atom group might not be whole, use the first atom as the
329 * reference atom and determine the center with respect to this reference.
331 static void get_molecule_center(rvec x[], int nat, const real* weights, rvec center, t_pbc* pbc)
334 rvec weightedPBCimage;
336 rvec reference, correctPBCimage, dx;
339 /* Use the first atom as the reference and put other atoms near that one */
340 /* This does not work for large molecules that span > half of the box! */
341 copy_rvec(x[0], reference);
343 /* Calculate either the weighted center or simply the center of geometry */
346 for (i = 0; i < nat; i++)
348 /* PBC distance between position and reference */
349 pbc_dx(pbc, x[i], reference, dx);
351 /* Add PBC distance to reference */
352 rvec_add(reference, dx, correctPBCimage);
354 /* Take weight into account */
355 if (nullptr == weights)
364 svmul(wi, correctPBCimage, weightedPBCimage);
367 rvec_inc(center, weightedPBCimage);
371 svmul(1.0 / wsum, center, center);
375 /*! \brief Return TRUE if position x of ion (or water) is found in the compartment,
376 * i.e. between w1 and w2.
378 * One can define and additional offset "b" if one wants to exchange ions/water
379 * to or from a plane not directly in the middle of w1 and w2. The offset can be
380 * in ]-1.0, ..., +1.0 [.
381 * A bulkOffset of 0.0 means 'no offset', so the swap-layer is directly in the
382 * middle between w1 and w2. Offsets -1.0 < b < 0.0 will yield swaps nearer to w1,
383 * whereas offsets 0.0 < 0 < +1.0 will yield swaps nearer to w2.
387 * ||--------------+-------------|-------------+------------------------||
388 * w1 ? ? ? ? ? ? ? ? ? ? ? w2
389 * ||--------------+-------------|----b--------+------------------------||
394 * \param[in] w1 Position of 'wall' atom 1.
395 * \param[in] w2 Position of 'wall' atom 2.
396 * \param[in] x Position of the ion or the water molecule under consideration.
397 * \param[in] l Length of the box, from || to || in the sketch.
398 * \param[in] bulkOffset Where is the bulk layer "b" to be found between w1 and w2?
399 * \param[out] distance_from_b Distance of x to the bulk layer "b".
401 * \returns TRUE if x is between w1 and w2.
403 * Also computes the distance of x to the compartment center (the layer that is
404 * normally situated in the middle of w1 and w2 that would be considered as having
405 * the bulk concentration of ions).
407 static gmx_bool compartment_contains_atom(real w1, real w2, real x, real l, real bulkOffset, real* distance_from_b)
413 /* First set the origin in the middle of w1 and w2 */
420 /* Now choose the PBC image of x that is closest to the origin: */
431 *distance_from_b = static_cast<real>(fabs(x - bulkOffset * 0.5 * width));
433 /* Return TRUE if we now are in area "????" */
434 return (x >= w1) && (x < w2);
438 /*! \brief Updates the time-averaged number of ions in a compartment. */
439 static void update_time_window(t_compartment* comp, int values, int replace)
445 /* Put in the new value */
448 comp->nMolPast[replace] = comp->nMol;
451 /* Compute the new time-average */
453 for (i = 0; i < values; i++)
455 average += comp->nMolPast[i];
458 comp->nMolAv = average;
462 /*! \brief Add the atom with collective index ci to the atom list in compartment 'comp'.
464 * \param[in] ci Index of this ion in the collective xc array.
465 * \param[inout] comp Compartment to add this atom to.
466 * \param[in] distance Shortest distance of this atom to the bulk layer,
467 * from which ion/water pairs are selected for swapping.
469 static void add_to_list(int ci, t_compartment* comp, real distance)
473 if (nr >= comp->nalloc)
475 comp->nalloc = over_alloc_dd(nr + 1);
476 srenew(comp->ind, comp->nalloc);
477 srenew(comp->dist, comp->nalloc);
480 comp->dist[nr] = distance;
485 /*! \brief Determine the compartment boundaries from the channel centers. */
486 static void get_compartment_boundaries(int c, t_swap* s, const matrix box, real* left, real* right)
489 real leftpos, rightpos, leftpos_orig;
494 gmx_fatal(FARGS, "No compartment %c.", c + 'A');
497 pos0 = s->group[eGrpSplit0].center[s->swapdim];
498 pos1 = s->group[eGrpSplit1].center[s->swapdim];
511 /* This gets us the other compartment: */
514 leftpos_orig = leftpos;
516 rightpos = leftpos_orig + box[s->swapdim][s->swapdim];
524 /*! \brief Determine the per-channel ion flux.
526 * To determine the flux through the individual channels, we
527 * remember the compartment and channel history of each ion. An ion can be
528 * either in channel0 or channel1, or in the remaining volume of compartment
532 * +-----------------+
535 * ||||||||||0|||||||| bilayer with channel 0
540 * |||||1||||||||||||| bilayer with channel 1
543 * +-----------------+
547 static void detect_flux_per_channel(t_swapgrp* g,
551 unsigned char* comp_now,
552 unsigned char* comp_from,
553 unsigned char* channel_label,
563 gmx_bool in_cyl0, in_cyl1;
569 /* Check whether ion is inside any of the channels */
570 in_cyl0 = is_in_channel(atomPosition, s->group[eGrpSplit0].center, sc->cyl0u, sc->cyl0l,
571 cyl0_r2, s->pbc, sd);
572 in_cyl1 = is_in_channel(atomPosition, s->group[eGrpSplit1].center, sc->cyl1u, sc->cyl1l,
573 cyl1_r2, s->pbc, sd);
575 if (in_cyl0 && in_cyl1)
577 /* Ion appears to be in both channels. Something is severely wrong! */
579 *comp_now = eDomainNotset;
580 *comp_from = eDomainNotset;
581 *channel_label = eChHistPassedNone;
585 /* Ion is in channel 0 now */
586 *channel_label = eChHistPassedCh0;
587 *comp_now = eDomainNotset;
592 /* Ion is in channel 1 now */
593 *channel_label = eChHistPassedCh1;
594 *comp_now = eDomainNotset;
599 /* Ion is not in any of the channels, so it must be in domain A or B */
602 *comp_now = eDomainA;
606 *comp_now = eDomainB;
610 /* Only take action, if ion is now in domain A or B, and was before
611 * in the other domain!
613 if (eDomainNotset == *comp_from)
615 /* Maybe we can set the domain now */
616 *comp_from = *comp_now; /* Could still be eDomainNotset, though */
618 else if ((*comp_now != eDomainNotset) /* if in channel */
619 && (*comp_from != *comp_now))
621 /* Obviously the ion changed its domain.
622 * Count this for the channel through which it has passed. */
623 switch (*channel_label)
625 case eChHistPassedNone:
628 fprintf(stderr, " %s Warning! Step %s, ion %d moved from %s to %s\n", SwS,
629 gmx_step_str(step, buf), iAtom, DomainString[*comp_from],
630 DomainString[*comp_now]);
633 fprintf(stderr, ", possibly due to a swap in the original simulation.\n");
638 "but did not pass cyl0 or cyl1 as defined in the .mdp file.\n"
639 "Do you have an ion somewhere within the membrane?\n");
640 /* Write this info to the CompEL output file: */
642 " # Warning: step %s, ion %d moved from %s to %s (probably through the "
644 gmx_step_str(step, buf), iAtom, DomainString[*comp_from],
645 DomainString[*comp_now]);
648 case eChHistPassedCh0:
649 case eChHistPassedCh1:
650 if (*channel_label == eChHistPassedCh0)
659 if (eDomainA == *comp_from)
661 g->fluxfromAtoB[chan_nr]++;
665 g->fluxfromAtoB[chan_nr]--;
667 fprintf(fpout, "# Atom nr. %d finished passing %s.\n", iAtom,
668 ChannelString[*channel_label]);
671 gmx_fatal(FARGS, "%s Unknown channel history entry for ion type '%s'\n", SwS, g->molname);
674 /* This ion has moved to the _other_ compartment ... */
675 *comp_from = *comp_now;
676 /* ... and it did not pass any channel yet */
677 *channel_label = eChHistPassedNone;
682 /*! \brief Determines which ions or solvent molecules are in compartment A and B */
683 static void sortMoleculesIntoCompartments(t_swapgrp* g,
693 int nMolNotInComp[eCompNR]; /* consistency check */
694 real cyl0_r2 = sc->cyl0r * sc->cyl0r;
695 real cyl1_r2 = sc->cyl1r * sc->cyl1r;
697 /* Get us a counter that cycles in the range of [0 ... sc->nAverage[ */
698 int replace = (step / sc->nstswap) % sc->nAverage;
700 for (int comp = eCompA; comp <= eCompB; comp++)
704 /* Get lists of atoms that match criteria for this compartment */
705 get_compartment_boundaries(comp, s, box, &left, &right);
707 /* First clear the ion molecule lists */
708 g->comp[comp].nMol = 0;
709 nMolNotInComp[comp] = 0; /* consistency check */
711 /* Loop over the molecules and atoms of this group */
712 for (int iMol = 0, iAtom = 0; iAtom < static_cast<int>(g->atomset.numAtomsGlobal());
713 iAtom += g->apm, iMol++)
718 /* Is this first atom of the molecule in the compartment that we look at? */
719 if (compartment_contains_atom(left, right, g->xc[iAtom][sd], box[sd][sd],
720 sc->bulkOffset[comp], &dist))
722 /* Add the first atom of this molecule to the list of molecules in this compartment */
723 add_to_list(iAtom, &g->comp[comp], dist);
725 /* Master also checks for ion groups through which channel each ion has passed */
726 if (MASTER(cr) && (g->comp_now != nullptr) && !bIsSolvent)
728 int globalAtomNr = g->atomset.globalIndex()[iAtom] + 1; /* PDB index starts at 1 ... */
729 detect_flux_per_channel(g, globalAtomNr, comp, g->xc[iAtom], &g->comp_now[iMol],
730 &g->comp_from[iMol], &g->channel_label[iMol], sc, s,
731 cyl0_r2, cyl1_r2, step, bRerun, fpout);
736 nMolNotInComp[comp]++;
739 /* Correct the time-averaged number of ions in the compartment */
742 update_time_window(&g->comp[comp], sc->nAverage, replace);
746 /* Flux detection warnings */
747 if (MASTER(cr) && !bIsSolvent)
753 "%s Warning: %d atoms were detected as being in both channels! Probably your "
755 "%s cylinder is way too large, or one compartment has collapsed (step "
757 SwS, g->nCylBoth, SwS, step);
759 fprintf(s->fpout, "Warning: %d atoms were assigned to both channels!\n", g->nCylBoth);
765 if (bIsSolvent && nullptr != fpout)
767 fprintf(fpout, "# Solv. molecules in comp.%s: %d comp.%s: %d\n", CompStr[eCompA],
768 g->comp[eCompA].nMol, CompStr[eCompB], g->comp[eCompB].nMol);
771 /* Consistency checks */
772 const auto numMolecules = static_cast<int>(g->atomset.numAtomsGlobal() / g->apm);
773 if (nMolNotInComp[eCompA] + nMolNotInComp[eCompB] != numMolecules)
776 "%s Warning: Inconsistency while assigning '%s' molecules to compartments. !inA: "
777 "%d, !inB: %d, total molecules %d\n",
778 SwS, g->molname, nMolNotInComp[eCompA], nMolNotInComp[eCompB], numMolecules);
781 int sum = g->comp[eCompA].nMol + g->comp[eCompB].nMol;
782 if (sum != numMolecules)
785 "%s Warning: %d molecules are in group '%s', but altogether %d have been assigned "
786 "to the compartments.\n",
787 SwS, numMolecules, g->molname, sum);
792 /*! \brief Find out how many group atoms are in the compartments initially */
793 static void get_initial_ioncounts(const t_inputrec* ir,
795 const rvec x[], /* the initial positions */
805 /* Loop over the user-defined (ion) groups */
806 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
810 /* Copy the initial positions of the atoms in the group
811 * to the collective array so that we can compartmentalize */
812 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
814 int ind = g->atomset.globalIndex()[i];
815 copy_rvec(x[ind], g->xc[i]);
818 /* Set up the compartments and get lists of atoms in each compartment */
819 sortMoleculesIntoCompartments(g, cr, sc, s, box, 0, s->fpout, bRerun, FALSE);
821 /* Set initial molecule counts if requested (as signaled by "-1" value) */
822 for (int ic = 0; ic < eCompNR; ic++)
824 int requested = sc->grp[ig].nmolReq[ic];
827 g->comp[ic].nMolReq = g->comp[ic].nMol;
831 g->comp[ic].nMolReq = requested;
835 /* Check whether the number of requested molecules adds up to the total number */
836 int req = g->comp[eCompA].nMolReq + g->comp[eCompB].nMolReq;
837 int tot = g->comp[eCompA].nMol + g->comp[eCompB].nMol;
842 "Mismatch of the number of %s ions summed over both compartments.\n"
843 "You requested a total of %d ions (%d in A and %d in B),\n"
844 "but there are a total of %d ions of this type in the system.\n",
845 g->molname, req, g->comp[eCompA].nMolReq, g->comp[eCompB].nMolReq, tot);
848 /* Initialize time-averaging:
849 * Write initial concentrations to all time bins to start with */
850 for (int ic = 0; ic < eCompNR; ic++)
852 g->comp[ic].nMolAv = g->comp[ic].nMol;
853 for (int i = 0; i < sc->nAverage; i++)
855 g->comp[ic].nMolPast[i] = g->comp[ic].nMol;
862 /*! \brief Copy history of ion counts from checkpoint file.
864 * When called, the checkpoint file has already been read in. Here we copy
865 * over the values from .cpt file to the swap data structure.
867 static void get_initial_ioncounts_from_cpt(const t_inputrec* ir,
869 swaphistory_t* swapstate,
881 /* Copy the past values from the checkpoint values that have been read in already */
884 fprintf(stderr, "%s Copying values from checkpoint\n", SwS);
887 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
890 gs = &swapstate->ionType[ig - eSwapFixedGrpNR];
892 for (int ic = 0; ic < eCompNR; ic++)
894 g->comp[ic].nMolReq = gs->nMolReq[ic];
895 g->comp[ic].inflow_net = gs->inflow_net[ic];
899 fprintf(stderr, "%s ... Influx netto: %d Requested: %d Past values: ", SwS,
900 g->comp[ic].inflow_net, g->comp[ic].nMolReq);
903 for (int j = 0; j < sc->nAverage; j++)
905 g->comp[ic].nMolPast[j] = gs->nMolPast[ic][j];
908 fprintf(stderr, "%d ", g->comp[ic].nMolPast[j]);
913 fprintf(stderr, "\n");
921 /*! \brief The master lets all others know about the initial ion counts. */
922 static void bc_initial_concentrations(t_commrec* cr, t_swapcoords* swap, t_swap* s)
928 for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
932 for (ic = 0; ic < eCompNR; ic++)
934 gmx_bcast(sizeof(g->comp[ic].nMolReq), &(g->comp[ic].nMolReq), cr);
935 gmx_bcast(sizeof(g->comp[ic].nMol), &(g->comp[ic].nMol), cr);
936 gmx_bcast(swap->nAverage * sizeof(g->comp[ic].nMolPast[0]), g->comp[ic].nMolPast, cr);
942 /*! \brief Ensure that each atom belongs to at most one of the swap groups. */
943 static void check_swap_groups(t_swap* s, int nat, gmx_bool bVerbose)
945 int* nGroup = nullptr; /* This array counts for each atom in the MD system to
946 how many swap groups it belongs (should be 0 or 1!) */
948 int nMultiple = 0; /* Number of atoms belonging to multiple groups */
953 fprintf(stderr, "%s Making sure each atom belongs to at most one of the swap groups.\n", SwS);
956 /* Add one to the group count of atoms belonging to a swap group: */
958 for (int i = 0; i < s->ngrp; i++)
960 t_swapgrp* g = &s->group[i];
961 for (size_t j = 0; j < g->atomset.numAtomsGlobal(); j++)
963 /* Get the global index of this atom of this group: */
964 ind = g->atomset.globalIndex()[j];
968 /* Make sure each atom belongs to at most one of the groups: */
969 for (int i = 0; i < nat; i++)
981 "%s Cannot perform swapping since %d atom%s allocated to more than one swap "
983 "%s Each atom must be allocated to at most one of the split groups, the swap "
984 "groups, or the solvent.\n"
985 "%s Check the .mdp file settings regarding the swap index groups or the index "
986 "groups themselves.\n",
987 SwS, nMultiple, (1 == nMultiple) ? " is" : "s are", SwSEmpty, SwSEmpty);
992 /*! \brief Get the number of atoms per molecule for this group.
994 * Also ensure that all the molecules in this group have this number of atoms.
996 static int get_group_apm_check(int igroup, t_swap* s, gmx_bool bVerbose, gmx_mtop_t* mtop)
998 t_swapgrp* g = &s->group[igroup];
999 const int* ind = s->group[igroup].atomset.globalIndex().data();
1000 int nat = s->group[igroup].atomset.numAtomsGlobal();
1002 /* Determine the number of solvent atoms per solvent molecule from the
1003 * first solvent atom: */
1005 mtopGetMolblockIndex(mtop, ind[0], &molb, nullptr, nullptr);
1006 int apm = mtop->moleculeBlockIndices[molb].numAtomsPerMolecule;
1010 fprintf(stderr, "%s Checking whether all %s molecules consist of %d atom%s\n", SwS,
1011 g->molname, apm, apm > 1 ? "s" : "");
1014 /* Check whether this is also true for all other solvent atoms */
1015 for (int i = 1; i < nat; i++)
1017 mtopGetMolblockIndex(mtop, ind[i], &molb, nullptr, nullptr);
1018 if (apm != mtop->moleculeBlockIndices[molb].numAtomsPerMolecule)
1020 gmx_fatal(FARGS, "Not all molecules of swap group %d consist of %d atoms.", igroup, apm);
1024 // TODO: check whether charges and masses of each molecule are identical!
1029 /*! \brief Print the legend to the swap output file.
1031 * Also print the initial values of ion counts and position of split groups.
1033 static void print_ionlist_legend(const t_inputrec* ir, t_swap* s, const gmx_output_env_t* oenv)
1035 const char** legend;
1039 int nIonTypes = ir->swap->ngrp - eSwapFixedGrpNR;
1040 snew(legend, eCompNR * nIonTypes * 3 + 2 + eChanNR * nIonTypes + 1);
1042 // Number of molecules and difference to reference counts for each
1043 // compartment and ion type
1044 for (int ic = count = 0; ic < eCompNR; ic++)
1046 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1048 t_swapGroup* g = &ir->swap->grp[ig];
1049 real q = s->group[ig].q;
1051 snprintf(buf, STRLEN, "%s %s ions (charge %s%g)", CompStr[ic], g->molname, q > 0 ? "+" : "", q);
1052 legend[count++] = gmx_strdup(buf);
1054 snprintf(buf, STRLEN, "%s av. mismatch to %d %s ions", CompStr[ic],
1055 s->group[ig].comp[ic].nMolReq, g->molname);
1056 legend[count++] = gmx_strdup(buf);
1058 snprintf(buf, STRLEN, "%s net %s ion influx", CompStr[ic], g->molname);
1059 legend[count++] = gmx_strdup(buf);
1063 // Center of split groups
1064 snprintf(buf, STRLEN, "%scenter of %s of split group 0", SwapStr[ir->eSwapCoords],
1065 (nullptr != s->group[eGrpSplit0].m) ? "mass" : "geometry");
1066 legend[count++] = gmx_strdup(buf);
1067 snprintf(buf, STRLEN, "%scenter of %s of split group 1", SwapStr[ir->eSwapCoords],
1068 (nullptr != s->group[eGrpSplit1].m) ? "mass" : "geometry");
1069 legend[count++] = gmx_strdup(buf);
1071 // Ion flux for each channel and ion type
1072 for (int ic = 0; ic < eChanNR; ic++)
1074 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1076 t_swapGroup* g = &ir->swap->grp[ig];
1077 snprintf(buf, STRLEN, "A->ch%d->B %s permeations", ic, g->molname);
1078 legend[count++] = gmx_strdup(buf);
1082 // Number of molecules that leaked from A to B
1083 snprintf(buf, STRLEN, "leakage");
1084 legend[count++] = gmx_strdup(buf);
1086 xvgr_legend(s->fpout, count, legend, oenv);
1089 "# Instantaneous ion counts and time-averaged differences to requested numbers\n");
1091 // We add a simple text legend helping to identify the columns with xvgr legend strings
1092 fprintf(s->fpout, "# time (ps)");
1093 for (int i = 0; i < count; i++)
1095 snprintf(buf, STRLEN, "s%d", i);
1096 fprintf(s->fpout, "%10s", buf);
1098 fprintf(s->fpout, "\n");
1103 /*! \brief Initialize channel ion flux detection routine.
1105 * Initialize arrays that keep track of where the ions come from and where
1108 static void detect_flux_per_channel_init(t_swap* s, swaphistory_t* swapstate, const bool isRestart)
1111 swapstateIons_t* gs;
1113 /* All these flux detection routines run on the master only */
1114 if (swapstate == nullptr)
1119 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1122 gs = &swapstate->ionType[ig - eSwapFixedGrpNR];
1124 /******************************************************/
1125 /* Channel and domain history for the individual ions */
1126 /******************************************************/
1127 if (isRestart) /* set the pointers right */
1129 g->comp_from = gs->comp_from;
1130 g->channel_label = gs->channel_label;
1132 else /* allocate memory for molecule counts */
1134 snew(g->comp_from, g->atomset.numAtomsGlobal() / g->apm);
1135 gs->comp_from = g->comp_from;
1136 snew(g->channel_label, g->atomset.numAtomsGlobal() / g->apm);
1137 gs->channel_label = g->channel_label;
1139 snew(g->comp_now, g->atomset.numAtomsGlobal() / g->apm);
1141 /* Initialize the channel and domain history counters */
1142 for (size_t i = 0; i < g->atomset.numAtomsGlobal() / g->apm; i++)
1144 g->comp_now[i] = eDomainNotset;
1147 g->comp_from[i] = eDomainNotset;
1148 g->channel_label[i] = eChHistPassedNone;
1152 /************************************/
1153 /* Channel fluxes for both channels */
1154 /************************************/
1155 g->nCyl[eChan0] = 0;
1156 g->nCyl[eChan1] = 0;
1162 fprintf(stderr, "%s Copying channel fluxes from checkpoint file data\n", SwS);
1166 // Loop over ion types (and both channels)
1167 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1170 gs = &swapstate->ionType[ig - eSwapFixedGrpNR];
1172 for (int ic = 0; ic < eChanNR; ic++)
1174 fprintf(stderr, "%s Channel %d flux history for ion type %s (charge %g): ", SwS, ic,
1178 g->fluxfromAtoB[ic] = gs->fluxfromAtoB[ic];
1182 g->fluxfromAtoB[ic] = 0;
1185 fprintf(stderr, "%d molecule%s", g->fluxfromAtoB[ic], g->fluxfromAtoB[ic] == 1 ? "" : "s");
1186 fprintf(stderr, "\n");
1190 /* Set pointers for checkpoint writing */
1191 swapstate->fluxleak_p = &s->fluxleak;
1192 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1195 gs = &swapstate->ionType[ig - eSwapFixedGrpNR];
1197 for (int ic = 0; ic < eChanNR; ic++)
1199 gs->fluxfromAtoB_p[ic] = &g->fluxfromAtoB[ic];
1205 /*! \brief Outputs the initial structure to PDB file for debugging reasons.
1207 * Output the starting structure so that in case of multimeric channels
1208 * the user can check whether we have the correct PBC image for all atoms.
1209 * If this is not correct, the ion counts per channel will be very likely
1212 static void outputStartStructureIfWanted(gmx_mtop_t* mtop, rvec* x, PbcType pbcType, const matrix box)
1214 char* env = getenv("GMX_COMPELDUMP");
1219 "\n%s Found env.var. GMX_COMPELDUMP, will output CompEL starting structure made "
1221 "%s In case of multimeric channels, please check whether they have the correct PBC "
1222 "representation.\n",
1225 write_sto_conf_mtop("CompELAssumedWholeConfiguration.pdb", *mtop->name, mtop, x, nullptr,
1231 /*! \brief Initialize the swapstate structure, used for checkpoint writing.
1233 * The swapstate struct stores the information we need to make the channels
1234 * whole again after restarts from a checkpoint file. Here we do the following:
1235 * a) If we did not start from .cpt, we prepare the struct for proper .cpt writing,
1236 * b) if we did start from .cpt, we copy over the last whole structures from .cpt,
1237 * c) in any case, for subsequent checkpoint writing, we set the pointers in
1238 * swapstate to the x_old arrays, which contain the correct PBC representation of
1239 * multimeric channels at the last time step.
1241 static void init_swapstate(swaphistory_t* swapstate,
1245 const rvec* x, /* the initial positions */
1247 const t_inputrec* ir)
1249 rvec* x_pbc = nullptr; /* positions of the whole MD system with molecules made whole */
1253 /* We always need the last whole positions such that
1254 * in the next time step we can make the channels whole again in PBC */
1255 if (swapstate->bFromCpt)
1257 /* Copy the last whole positions of each channel from .cpt */
1258 g = &(s->group[eGrpSplit0]);
1259 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
1261 copy_rvec(swapstate->xc_old_whole[eChan0][i], g->xc_old[i]);
1263 g = &(s->group[eGrpSplit1]);
1264 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
1266 copy_rvec(swapstate->xc_old_whole[eChan1][i], g->xc_old[i]);
1271 swapstate->eSwapCoords = ir->eSwapCoords;
1273 /* Set the number of ion types and allocate memory for checkpointing */
1274 swapstate->nIonTypes = s->ngrp - eSwapFixedGrpNR;
1275 snew(swapstate->ionType, swapstate->nIonTypes);
1277 /* Store the total number of ions of each type in the swapstateIons
1278 * structure that is accessible during checkpoint writing */
1279 for (int ii = 0; ii < swapstate->nIonTypes; ii++)
1281 swapstateIons_t* gs = &swapstate->ionType[ii];
1282 gs->nMol = sc->grp[ii + eSwapFixedGrpNR].nat;
1285 /* Extract the initial split group positions. */
1287 /* Remove pbc, make molecule whole. */
1288 snew(x_pbc, mtop->natoms);
1289 copy_rvecn(x, x_pbc, 0, mtop->natoms);
1291 /* This can only make individual molecules whole, not multimers */
1292 do_pbc_mtop(ir->pbcType, box, mtop, x_pbc);
1294 /* Output the starting structure? */
1295 outputStartStructureIfWanted(mtop, x_pbc, ir->pbcType, box);
1297 /* If this is the first run (i.e. no checkpoint present) we assume
1298 * that the starting positions give us the correct PBC representation */
1299 for (int ig = eGrpSplit0; ig <= eGrpSplit1; ig++)
1301 g = &(s->group[ig]);
1302 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
1304 copy_rvec(x_pbc[g->atomset.globalIndex()[i]], g->xc_old[i]);
1309 /* Prepare swapstate arrays for later checkpoint writing */
1310 swapstate->nat[eChan0] = s->group[eGrpSplit0].atomset.numAtomsGlobal();
1311 swapstate->nat[eChan1] = s->group[eGrpSplit1].atomset.numAtomsGlobal();
1314 /* For subsequent checkpoint writing, set the swapstate pointers to the xc_old
1315 * arrays that get updated at every swapping step */
1316 swapstate->xc_old_whole_p[eChan0] = &s->group[eGrpSplit0].xc_old;
1317 swapstate->xc_old_whole_p[eChan1] = &s->group[eGrpSplit1].xc_old;
1320 /*! \brief Determine the total charge imbalance resulting from the swap groups */
1321 static real getRequestedChargeImbalance(t_swap* s)
1326 real particle_charge;
1327 real particle_number[eCompNR];
1329 // s->deltaQ = ( (-1) * s->comp[eCompA][eIonNEG].nat_req + s->comp[eCompA][eIonPOS].nat_req )
1330 // - ( (-1) * s->comp[eCompB][eIonNEG].nat_req + s->comp[eCompB][eIonPOS].nat_req );
1332 for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1336 particle_charge = g->q;
1337 particle_number[eCompA] = g->comp[eCompA].nMolReq;
1338 particle_number[eCompB] = g->comp[eCompB].nMolReq;
1340 DeltaQ += particle_charge * (particle_number[eCompA] - particle_number[eCompB]);
1347 /*! \brief Sorts anions and cations into two separate groups
1349 * This routine should be called for the 'anions' and 'cations' group,
1350 * of which the indices were lumped together in the older version of the code.
1352 static void copyIndicesToGroup(const int* indIons, int nIons, t_swapGroup* g, t_commrec* cr)
1356 /* If explicit ion counts were requested in the .mdp file
1357 * (by setting positive values for the number of ions),
1358 * we can make an additional consistency check here */
1359 if ((g->nmolReq[eCompA] < 0) && (g->nmolReq[eCompB] < 0))
1361 if (g->nat != (g->nmolReq[eCompA] + g->nmolReq[eCompB]))
1363 gmx_fatal_collective(FARGS, cr->mpi_comm_mysim, MASTER(cr),
1364 "%s Inconsistency while importing swap-related data from an old "
1365 "input file version.\n"
1366 "%s The requested ion counts in compartments A (%d) and B (%d)\n"
1367 "%s do not add up to the number of ions (%d) of this type for the "
1369 SwS, SwSEmpty, g->nmolReq[eCompA], g->nmolReq[eCompB], SwSEmpty,
1370 g->nat, g->molname);
1374 srenew(g->ind, g->nat);
1375 for (int i = 0; i < g->nat; i++)
1377 g->ind[i] = indIons[i];
1382 /*! \brief Converts old .tpr file CompEL contents to new data layout.
1384 * If we have read an old .tpr file (tpxv <= tpxv_CompElPolyatomicIonsAndMultipleIonTypes),
1385 * anions and cations are stored together in group #3. In the new
1386 * format we store each ion type in a separate group.
1387 * The 'classic' groups are:
1388 * #0 split group 0 - OK
1389 * #1 split group 1 - OK
1391 * #3 anions - contains also cations, needs to be converted
1392 * #4 cations - empty before conversion
1395 static void convertOldToNewGroupFormat(t_swapcoords* sc, gmx_mtop_t* mtop, gmx_bool bVerbose, t_commrec* cr)
1397 t_swapGroup* g = &sc->grp[3];
1399 /* Loop through the atom indices of group #3 (anions) and put all indices
1400 * that belong to cations into the cation group.
1404 int* indAnions = nullptr;
1405 int* indCations = nullptr;
1406 snew(indAnions, g->nat);
1407 snew(indCations, g->nat);
1410 for (int i = 0; i < g->nat; i++)
1412 const t_atom& atom = mtopGetAtomParameters(mtop, g->ind[i], &molb);
1415 // This is an anion, add it to the list of anions
1416 indAnions[nAnions++] = g->ind[i];
1420 // This is a cation, add it to the list of cations
1421 indCations[nCations++] = g->ind[i];
1427 fprintf(stdout, "%s Sorted %d ions into separate groups of %d anions and %d cations.\n",
1428 SwS, g->nat, nAnions, nCations);
1432 /* Now we have the correct lists of anions and cations.
1433 * Copy it to the right groups.
1435 copyIndicesToGroup(indAnions, nAnions, g, cr);
1437 copyIndicesToGroup(indCations, nCations, g, cr);
1443 /*! \brief Returns TRUE if we started from an old .tpr
1445 * Then we need to re-sort anions and cations into separate groups */
1446 static gmx_bool bConvertFromOldTpr(t_swapcoords* sc)
1448 // If the last group has no atoms it means we need to convert!
1449 return (sc->ngrp >= 5) && (0 == sc->grp[4].nat);
1453 t_swap* init_swapcoords(FILE* fplog,
1454 const t_inputrec* ir,
1457 const t_state* globalState,
1458 ObservablesHistory* oh,
1460 gmx::LocalAtomSetManager* atomSets,
1461 const gmx_output_env_t* oenv,
1462 const gmx::MdrunOptions& mdrunOptions,
1463 const gmx::StartingBehavior startingBehavior)
1466 swapstateIons_t* gs;
1467 swaphistory_t* swapstate = nullptr;
1469 if ((PAR(cr)) && !DOMAINDECOMP(cr))
1471 gmx_fatal(FARGS, "Position swapping is only implemented for domain decomposition!");
1475 auto s = new t_swap();
1477 if (mdrunOptions.rerun)
1482 "%s This module does not support reruns in parallel\nPlease request a serial "
1483 "run with -nt 1 / -np 1\n",
1487 fprintf(stderr, "%s Rerun - using every available frame\n", SwS);
1489 sc->nAverage = 1; /* averaging makes no sense for reruns */
1492 if (MASTER(cr) && startingBehavior == gmx::StartingBehavior::NewSimulation)
1494 fprintf(fplog, "\nInitializing ion/water position exchanges\n");
1495 please_cite(fplog, "Kutzner2011b");
1498 switch (ir->eSwapCoords)
1500 case eswapX: s->swapdim = XX; break;
1501 case eswapY: s->swapdim = YY; break;
1502 case eswapZ: s->swapdim = ZZ; break;
1503 default: s->swapdim = -1; break;
1506 const gmx_bool bVerbose = mdrunOptions.verbose;
1508 // For compatibility with old .tpr files
1509 if (bConvertFromOldTpr(sc))
1511 convertOldToNewGroupFormat(sc, mtop, bVerbose && MASTER(cr), cr);
1514 /* Copy some data and pointers to the group structures for convenience */
1515 /* Number of atoms in the group */
1517 for (int i = 0; i < s->ngrp; i++)
1519 s->group.emplace_back(atomSets->add(
1520 gmx::ArrayRef<const int>(sc->grp[i].ind, sc->grp[i].ind + sc->grp[i].nat)));
1521 s->group[i].molname = sc->grp[i].molname;
1524 /* Check for overlapping atoms */
1525 check_swap_groups(s, mtop->natoms, bVerbose && MASTER(cr));
1527 /* Allocate space for the collective arrays for all groups */
1528 /* For the collective position array */
1529 for (int i = 0; i < s->ngrp; i++)
1532 snew(g->xc, g->atomset.numAtomsGlobal());
1534 /* For the split groups (the channels) we need some extra memory to
1535 * be able to make the molecules whole even if they span more than
1536 * half of the box size. */
1537 if ((i == eGrpSplit0) || (i == eGrpSplit1))
1539 snew(g->xc_shifts, g->atomset.numAtomsGlobal());
1540 snew(g->xc_eshifts, g->atomset.numAtomsGlobal());
1541 snew(g->xc_old, g->atomset.numAtomsGlobal());
1547 if (oh->swapHistory == nullptr)
1549 oh->swapHistory = std::make_unique<swaphistory_t>(swaphistory_t{});
1551 swapstate = oh->swapHistory.get();
1553 init_swapstate(swapstate, sc, s, mtop, globalState->x.rvec_array(), globalState->box, ir);
1556 /* After init_swapstate we have a set of (old) whole positions for our
1557 * channels. Now transfer that to all nodes */
1560 for (int ig = eGrpSplit0; ig <= eGrpSplit1; ig++)
1562 g = &(s->group[ig]);
1563 gmx_bcast((g->atomset.numAtomsGlobal()) * sizeof((g->xc_old)[0]), g->xc_old, (cr));
1567 /* Make sure that all molecules in the solvent and ion groups contain the
1568 * same number of atoms each */
1569 for (int ig = eGrpSolvent; ig < s->ngrp; ig++)
1573 g = &(s->group[ig]);
1574 g->apm = get_group_apm_check(ig, s, MASTER(cr) && bVerbose, mtop);
1576 /* Since all molecules of a group are equal, we only need enough space
1577 * to determine properties of a single molecule at at time */
1578 snew(g->m, g->apm); /* For the center of mass */
1579 charge = 0; /* To determine the charge imbalance */
1581 for (int j = 0; j < g->apm; j++)
1583 const t_atom& atom = mtopGetAtomParameters(mtop, g->atomset.globalIndex()[j], &molb);
1587 /* Total charge of one molecule of this group: */
1592 /* Need mass-weighted center of split group? */
1593 for (int j = eGrpSplit0; j <= eGrpSplit1; j++)
1596 if (sc->massw_split[j])
1598 /* Save the split group masses if mass-weighting is requested */
1599 snew(g->m, g->atomset.numAtomsGlobal());
1601 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
1603 g->m[i] = mtopGetAtomMass(mtop, g->atomset.globalIndex()[i], &molb);
1608 /* Make a t_pbc struct on all nodes so that the molecules
1609 * chosen for an exchange can be made whole. */
1612 bool restartWithAppending = (startingBehavior == gmx::StartingBehavior::RestartWithAppending);
1617 fprintf(stderr, "%s Opening output file %s%s\n", SwS, fn,
1618 restartWithAppending ? " for appending" : "");
1621 s->fpout = gmx_fio_fopen(fn, restartWithAppending ? "a" : "w");
1623 if (!restartWithAppending)
1625 xvgr_header(s->fpout, "Molecule counts", "Time (ps)", "counts", exvggtXNY, oenv);
1627 for (int ig = 0; ig < s->ngrp; ig++)
1629 g = &(s->group[ig]);
1630 fprintf(s->fpout, "# %s group '%s' contains %d atom%s",
1631 ig < eSwapFixedGrpNR ? eSwapFixedGrp_names[ig] : "Ion", g->molname,
1632 static_cast<int>(g->atomset.numAtomsGlobal()),
1633 (g->atomset.numAtomsGlobal() > 1) ? "s" : "");
1634 if (!(eGrpSplit0 == ig || eGrpSplit1 == ig))
1636 fprintf(s->fpout, " with %d atom%s in each molecule of charge %g", g->apm,
1637 (g->apm > 1) ? "s" : "", g->q);
1639 fprintf(s->fpout, ".\n");
1642 fprintf(s->fpout, "#\n# Initial positions of split groups:\n");
1645 for (int j = eGrpSplit0; j <= eGrpSplit1; j++)
1648 for (size_t i = 0; i < g->atomset.numAtomsGlobal(); i++)
1650 copy_rvec(globalState->x[sc->grp[j].ind[i]], g->xc[i]);
1652 /* xc has the correct PBC representation for the two channels, so we do
1653 * not need to correct for that */
1654 get_center(g->xc, g->m, g->atomset.numAtomsGlobal(), g->center);
1655 if (!restartWithAppending)
1657 fprintf(s->fpout, "# %s group %s-center %5f nm\n", eSwapFixedGrp_names[j],
1658 DimStr[s->swapdim], g->center[s->swapdim]);
1662 if (!restartWithAppending)
1664 if ((0 != sc->bulkOffset[eCompA]) || (0 != sc->bulkOffset[eCompB]))
1666 fprintf(s->fpout, "#\n");
1668 "# You provided an offset for the position of the bulk layer(s).\n");
1670 "# That means the layers to/from which ions and water molecules are "
1673 "# are not midway (= at 0.0) between the compartment-defining layers (at "
1675 fprintf(s->fpout, "# bulk-offsetA = %g\n", sc->bulkOffset[eCompA]);
1676 fprintf(s->fpout, "# bulk-offsetB = %g\n", sc->bulkOffset[eCompB]);
1679 fprintf(s->fpout, "#\n");
1680 fprintf(s->fpout, "# Split0 cylinder radius %f nm, up %f nm, down %f nm\n", sc->cyl0r,
1681 sc->cyl0u, sc->cyl0l);
1682 fprintf(s->fpout, "# Split1 cylinder radius %f nm, up %f nm, down %f nm\n", sc->cyl1r,
1683 sc->cyl1u, sc->cyl1l);
1685 fprintf(s->fpout, "#\n");
1686 if (!mdrunOptions.rerun)
1689 "# Coupling constant (number of swap attempt steps to average over): %d "
1690 "(translates to %f ps).\n",
1691 sc->nAverage, sc->nAverage * sc->nstswap * ir->delta_t);
1692 fprintf(s->fpout, "# Threshold is %f\n", sc->threshold);
1693 fprintf(s->fpout, "#\n");
1695 "# Remarks about which atoms passed which channel use global atoms numbers "
1696 "starting at one.\n");
1705 /* Allocate memory to remember the past particle counts for time averaging */
1706 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1708 g = &(s->group[ig]);
1709 for (int ic = 0; ic < eCompNR; ic++)
1711 snew(g->comp[ic].nMolPast, sc->nAverage);
1715 /* Get the initial particle concentrations and let the other nodes know */
1718 if (startingBehavior != gmx::StartingBehavior::NewSimulation)
1720 get_initial_ioncounts_from_cpt(ir, s, swapstate, cr, bVerbose);
1724 fprintf(stderr, "%s Determining initial numbers of ions per compartment.\n", SwS);
1725 get_initial_ioncounts(ir, s, globalState->x.rvec_array(), globalState->box, cr,
1726 mdrunOptions.rerun);
1729 /* Prepare (further) checkpoint writes ... */
1730 if (startingBehavior != gmx::StartingBehavior::NewSimulation)
1732 /* Consistency check */
1733 if (swapstate->nAverage != sc->nAverage)
1735 gmx_fatal(FARGS, "%s Ion count averaging steps mismatch! checkpoint: %d, tpr: %d",
1736 SwS, swapstate->nAverage, sc->nAverage);
1741 swapstate->nAverage = sc->nAverage;
1743 fprintf(stderr, "%s Setting pointers for checkpoint writing\n", SwS);
1744 for (int ic = 0; ic < eCompNR; ic++)
1746 for (int ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1749 gs = &swapstate->ionType[ig - eSwapFixedGrpNR];
1751 gs->nMolReq_p[ic] = &(g->comp[ic].nMolReq);
1752 gs->nMolPast_p[ic] = &(g->comp[ic].nMolPast[0]);
1753 gs->inflow_net_p[ic] = &(g->comp[ic].inflow_net);
1757 /* Determine the total charge imbalance */
1758 s->deltaQ = getRequestedChargeImbalance(s);
1762 fprintf(stderr, "%s Requested charge imbalance is Q(A) - Q(B) = %g e.\n", SwS, s->deltaQ);
1764 if (!restartWithAppending)
1766 fprintf(s->fpout, "# Requested charge imbalance is Q(A)-Q(B) = %g e.\n", s->deltaQ);
1772 bc_initial_concentrations(cr, ir->swap, s);
1775 /* Update the time-averaged number of molecules for all groups and compartments */
1776 for (int ig = eSwapFixedGrpNR; ig < sc->ngrp; ig++)
1779 for (int ic = 0; ic < eCompNR; ic++)
1781 update_time_window(&g->comp[ic], sc->nAverage, -1);
1785 /* Initialize arrays that keep track of through which channel the ions go */
1786 detect_flux_per_channel_init(s, swapstate, startingBehavior != gmx::StartingBehavior::NewSimulation);
1788 /* We need to print the legend if we open this file for the first time. */
1789 if (MASTER(cr) && !restartWithAppending)
1791 print_ionlist_legend(ir, s, oenv);
1797 void finish_swapcoords(t_swap* s)
1805 // Close the swap output file
1806 gmx_fio_fclose(s->fpout);
1810 /*! \brief Do we need to swap a molecule in any of the ion groups with a water molecule at this step?
1812 * From the requested and average molecule counts we determine whether a swap is needed
1813 * at this time step.
1815 static gmx_bool need_swap(t_swapcoords* sc, t_swap* s)
1820 for (ig = eSwapFixedGrpNR; ig < sc->ngrp; ig++)
1824 for (ic = 0; ic < eCompNR; ic++)
1826 if (g->comp[ic].nMolReq - g->comp[ic].nMolAv >= sc->threshold)
1836 /*! \brief Return the index of an atom or molecule suitable for swapping.
1838 * Returns the index of an atom that is far off the compartment boundaries,
1839 * that is near to the bulk layer to/from which the swaps take place.
1840 * Other atoms of the molecule (if any) will directly follow the returned index.
1842 * \param[in] comp Structure containing compartment-specific data.
1843 * \param[in] molname Name of the molecule.
1845 * \returns Index of the first atom of the molecule chosen for a position exchange.
1847 static int get_index_of_distant_atom(t_compartment* comp, const char molname[])
1850 real d = GMX_REAL_MAX;
1853 /* comp->nat contains the original number of atoms in this compartment
1854 * prior to doing any swaps. Some of these atoms may already have been
1855 * swapped out, but then they are marked with a distance of GMX_REAL_MAX
1857 for (int iMol = 0; iMol < comp->nMolBefore; iMol++)
1859 if (comp->dist[iMol] < d)
1862 d = comp->dist[ibest];
1869 "Could not get index of %s atom. Compartment contains %d %s molecules before "
1871 molname, comp->nMolBefore, molname);
1874 /* Set the distance of this index to infinity such that it won't get selected again in
1877 comp->dist[ibest] = GMX_REAL_MAX;
1879 return comp->ind[ibest];
1883 /*! \brief Swaps centers of mass and makes molecule whole if broken */
1884 static void translate_positions(rvec* x, int apm, rvec old_com, rvec new_com, t_pbc* pbc)
1887 rvec reference, dx, correctPBCimage;
1890 /* Use the first atom as the reference for PBC */
1891 copy_rvec(x[0], reference);
1893 for (i = 0; i < apm; i++)
1895 /* PBC distance between position and reference */
1896 pbc_dx(pbc, x[i], reference, dx);
1898 /* Add PBC distance to reference */
1899 rvec_add(reference, dx, correctPBCimage);
1901 /* Subtract old_com from correct image and add new_com */
1902 rvec_dec(correctPBCimage, old_com);
1903 rvec_inc(correctPBCimage, new_com);
1905 copy_rvec(correctPBCimage, x[i]);
1910 /*! \brief Write back the modified local positions from the collective array to the official positions. */
1911 static void apply_modified_positions(swap_group* g, rvec x[])
1913 auto collectiveIndex = g->atomset.collectiveIndex().begin();
1914 for (const auto localIndex : g->atomset.localIndex())
1916 /* Copy the possibly modified position */
1917 copy_rvec(g->xc[*collectiveIndex], x[localIndex]);
1923 gmx_bool do_swapcoords(t_commrec* cr,
1928 gmx_wallcycle* wcycle,
1935 int j, ic, ig, nswaps;
1936 int thisC, otherC; /* Index into this compartment and the other one */
1937 gmx_bool bSwap = FALSE;
1938 t_swapgrp * g, *gsol;
1940 rvec com_solvent, com_particle; /* solvent and swap molecule's center of mass */
1943 wallcycle_start(wcycle, ewcSWAP);
1947 set_pbc(s->pbc, ir->pbcType, box);
1949 /* Assemble the positions of the split groups, i.e. the channels.
1950 * Here we also pass a shifts array to communicate_group_positions(), so that it can make
1951 * the molecules whole even in cases where they span more than half of the box in
1953 for (ig = eGrpSplit0; ig <= eGrpSplit1; ig++)
1955 g = &(s->group[ig]);
1956 communicate_group_positions(cr, g->xc, g->xc_shifts, g->xc_eshifts, TRUE, x,
1957 g->atomset.numAtomsGlobal(), g->atomset.numAtomsLocal(),
1958 g->atomset.localIndex().data(),
1959 g->atomset.collectiveIndex().data(), g->xc_old, box);
1961 get_center(g->xc, g->m, g->atomset.numAtomsGlobal(), g->center); /* center of split groups == channels */
1964 /* Assemble the positions of the ions (ig = 3, 4, ...). These molecules should
1965 * be small and we can always make them whole with a simple distance check.
1966 * Therefore we pass NULL as third argument. */
1967 for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
1969 g = &(s->group[ig]);
1970 communicate_group_positions(cr, g->xc, nullptr, nullptr, FALSE, x, g->atomset.numAtomsGlobal(),
1971 g->atomset.numAtomsLocal(), g->atomset.localIndex().data(),
1972 g->atomset.collectiveIndex().data(), nullptr, nullptr);
1974 /* Determine how many ions of this type each compartment contains */
1975 sortMoleculesIntoCompartments(g, cr, sc, s, box, step, s->fpout, bRerun, FALSE);
1978 /* Output how many ions are in the compartments */
1981 print_ionlist(s, t, "");
1984 /* If we are doing a rerun, we are finished here, since we cannot perform
1991 /* Do we have to perform a swap? */
1992 bSwap = need_swap(sc, s);
1995 /* Since we here know that we have to perform ion/water position exchanges,
1996 * we now assemble the solvent positions */
1997 g = &(s->group[eGrpSolvent]);
1998 communicate_group_positions(cr, g->xc, nullptr, nullptr, FALSE, x, g->atomset.numAtomsGlobal(),
1999 g->atomset.numAtomsLocal(), g->atomset.localIndex().data(),
2000 g->atomset.collectiveIndex().data(), nullptr, nullptr);
2002 /* Determine how many molecules of solvent each compartment contains */
2003 sortMoleculesIntoCompartments(g, cr, sc, s, box, step, s->fpout, bRerun, TRUE);
2005 /* Save number of solvent molecules per compartment prior to any swaps */
2006 g->comp[eCompA].nMolBefore = g->comp[eCompA].nMol;
2007 g->comp[eCompB].nMolBefore = g->comp[eCompB].nMol;
2009 for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
2011 g = &(s->group[ig]);
2013 for (ic = 0; ic < eCompNR; ic++)
2015 /* Determine in which compartment ions are missing and where they are too many */
2016 g->vacancy[ic] = g->comp[ic].nMolReq - g->comp[ic].nMolAv;
2018 /* Save number of ions per compartment prior to swaps */
2019 g->comp[ic].nMolBefore = g->comp[ic].nMol;
2023 /* Now actually perform the particle exchanges, one swap group after another */
2024 gsol = &s->group[eGrpSolvent];
2025 for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++)
2029 for (thisC = 0; thisC < eCompNR; thisC++)
2031 /* Index to the other compartment */
2032 otherC = (thisC + 1) % eCompNR;
2034 while (g->vacancy[thisC] >= sc->threshold)
2036 /* Swap in an ion */
2038 /* Get the xc-index of the first atom of a solvent molecule of this compartment */
2039 isol = get_index_of_distant_atom(&gsol->comp[thisC], gsol->molname);
2041 /* Get the xc-index of a particle from the other compartment */
2042 iion = get_index_of_distant_atom(&g->comp[otherC], g->molname);
2044 get_molecule_center(&gsol->xc[isol], gsol->apm, gsol->m, com_solvent, s->pbc);
2045 get_molecule_center(&g->xc[iion], g->apm, g->m, com_particle, s->pbc);
2047 /* Subtract solvent molecule's center of mass and add swap particle's center of mass */
2048 translate_positions(&gsol->xc[isol], gsol->apm, com_solvent, com_particle, s->pbc);
2049 /* Similarly for the swap particle, subtract com_particle and add com_solvent */
2050 translate_positions(&g->xc[iion], g->apm, com_particle, com_solvent, s->pbc);
2052 /* Keep track of the changes */
2053 g->vacancy[thisC]--;
2054 g->vacancy[otherC]++;
2055 g->comp[thisC].nMol++;
2056 g->comp[otherC].nMol--;
2057 g->comp[thisC].inflow_net++;
2058 g->comp[otherC].inflow_net--;
2059 /* Correct the past time window to still get the right averages from now on */
2060 g->comp[thisC].nMolAv++;
2061 g->comp[otherC].nMolAv--;
2062 for (j = 0; j < sc->nAverage; j++)
2064 g->comp[thisC].nMolPast[j]++;
2065 g->comp[otherC].nMolPast[j]--;
2067 /* Clear ion history */
2070 int iMol = iion / g->apm;
2071 g->channel_label[iMol] = eChHistPassedNone;
2072 g->comp_from[iMol] = eDomainNotset;
2074 /* That was the swap */
2079 if (nswaps && bVerbose)
2081 fprintf(stderr, "%s Performed %d swap%s in step %" PRId64 " for iontype %s.\n", SwS,
2082 nswaps, nswaps > 1 ? "s" : "", step, g->molname);
2086 if (s->fpout != nullptr)
2088 print_ionlist(s, t, " # after swap");
2091 /* For the solvent and user-defined swap groups, each rank writes back its
2092 * (possibly modified) local positions to the official position array. */
2093 for (ig = eGrpSolvent; ig < s->ngrp; ig++)
2096 apply_modified_positions(g, x);
2099 } /* end of if(bSwap) */
2101 wallcycle_stop(wcycle, ewcSWAP);