Add preprocessing and integration test for transformation coordinate
[alexxy/gromacs.git] / src / gromacs / gmxpreprocess / readpull.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 #include "gmxpre.h"
39
40 #include <cassert>
41 #include <cstdlib>
42 #include <cstring>
43 #include <regex>
44
45 #include "gromacs/domdec/localatomsetmanager.h"
46 #include "gromacs/fileio/readinp.h"
47 #include "gromacs/fileio/warninp.h"
48 #include "gromacs/gmxpreprocess/readir.h"
49 #include "gromacs/math/vec.h"
50 #include "gromacs/mdlib/mdatoms.h"
51 #include "gromacs/mdtypes/inputrec.h"
52 #include "gromacs/mdtypes/md_enums.h"
53 #include "gromacs/mdtypes/mdatom.h"
54 #include "gromacs/mdtypes/pull_params.h"
55 #include "gromacs/pbcutil/pbc.h"
56 #include "gromacs/pulling/pull.h"
57 #include "gromacs/topology/topology.h"
58 #include "gromacs/utility/arrayref.h"
59 #include "gromacs/utility/basedefinitions.h"
60 #include "gromacs/utility/cstringutil.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/fatalerror.h"
63 #include "gromacs/utility/futil.h"
64 #include "gromacs/utility/smalloc.h"
65 #include "gromacs/utility/stringutil.h"
66
67
68 static void string2dvec(const char buf[], dvec nums)
69 {
70     double dum;
71
72     if (sscanf(buf, "%lf%lf%lf%lf", &nums[0], &nums[1], &nums[2], &dum) != 3)
73     {
74         gmx_fatal(FARGS, "Expected three numbers at input line %s", buf);
75     }
76 }
77
78 static std::vector<real> setupPullGroupWeights(const char* wbuf)
79 {
80     double d;
81     int    n;
82
83     std::vector<real> weight;
84     while (sscanf(wbuf, "%lf %n", &d, &n) == 1)
85     {
86         weight.push_back(d);
87         wbuf += n;
88     }
89     return weight;
90 }
91
92 static void process_pull_dim(char* dim_buf, ivec dim, const t_pull_coord* pcrd)
93 {
94     char* ptr  = dim_buf;
95     int   ndim = 0;
96     for (int d = 0; d < DIM; d++)
97     {
98         int  nchar = 0;
99         char pulldim1[STRLEN];
100         if (sscanf(ptr, "%s%n", pulldim1, &nchar) != 1)
101         {
102             gmx_fatal(FARGS, "Less than 3 pull dimensions given in pull_dim: '%s'", dim_buf);
103         }
104
105         if (gmx::equalCaseInsensitive(pulldim1, "N", 1))
106         {
107             dim[d] = 0;
108         }
109         else if (gmx::equalCaseInsensitive(pulldim1, "Y", 1))
110         {
111             dim[d] = 1;
112             ndim++;
113         }
114         else
115         {
116             gmx_fatal(FARGS, "Please use Y(ES) or N(O) for pull_dim only (not %s)", pulldim1);
117         }
118         ptr += nchar;
119     }
120     if (ndim == 0)
121     {
122         gmx_fatal(FARGS, "All entries in pull dim are N");
123     }
124     if ((pcrd->eGeom == PullGroupGeometry::Dihedral) && (ndim < 3))
125     {
126         gmx_fatal(FARGS, "Pull geometry dihedral is only useful with pull-dim = Y Y Y");
127     }
128     if ((pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis)
129         && (ndim < 2))
130     {
131         gmx_fatal(FARGS,
132                   "Pull geometry %s is only useful with pull-dim = Y for at least 2 dimensions",
133                   enumValueToString(pcrd->eGeom));
134     }
135 }
136
137 static void initTransformationPullCoord(t_pull_coord* pcrd, const pull_params_t& pull, warninp_t wi)
138 {
139     const int coord_index_for_output = pull.coord.size() + 1;
140     if (pcrd->eType == PullingAlgorithm::Constraint)
141     {
142         warning_error(
143                 wi,
144                 gmx::formatString(
145                         "pull-coord%d cannot have type 'constraint' and geometry 'transformation'",
146                         coord_index_for_output));
147     }
148
149     /*Validate the mathematical expression to epullgTRANSFORMATION*/
150     if (pcrd->expression.empty())
151     {
152         warning_error(
153                 wi, gmx::formatString("pull-coord%d-expression not set for pull coordinate of geometry 'transformation'", coord_index_for_output));
154     }
155     else if (pcrd->expression[0] == '"' || pcrd->expression[0] == '\'')
156     {
157         GMX_THROW(gmx::InvalidInputError(gmx::formatString(
158                 "pull-coord%d-expression should not start with double quote or a quote",
159                 coord_index_for_output)));
160     }
161     if (pcrd->dx == 0)
162     {
163         warning_error(
164                 wi,
165                 gmx::formatString(
166                         "pull-coord%d-dx cannot be set to zero for pull coordinate of geometry "
167                         "'transformation'",
168                         coord_index_for_output));
169     }
170     /* make sure that the kappa of all previous pull coords is 0*/
171     int previousCoordOutputIndex = 0;
172     for (const auto& previousPcrd : pull.coord)
173     {
174         previousCoordOutputIndex++;
175         // See if the previous variable is used by the transformation coord
176         // Note that a simple std::string::find won't work since we don't want x1 to match x11 etc.
177         std::string previousPcrdName = gmx::formatString("x%d(\\D|$)", previousCoordOutputIndex);
178         std::regex  rx(previousPcrdName);
179
180         std::ptrdiff_t number_of_matches = std::distance(
181                 std::sregex_iterator(pcrd->expression.begin(), pcrd->expression.end(), rx),
182                 std::sregex_iterator());
183
184         if (number_of_matches == 0)
185         {
186             // This previous coordinate is not used in this transformation, do not check it
187             continue;
188         }
189
190         if (previousPcrd.eType == PullingAlgorithm::Constraint)
191         {
192             warning_error(wi,
193                           gmx::formatString("pull-coord%d can not use pull-coord%d in the "
194                                             "transformation since this is a "
195                                             "constraint",
196                                             coord_index_for_output,
197                                             previousCoordOutputIndex));
198         }
199         else if (previousPcrd.k != 0 && pcrd->k != 0)
200         {
201             warning_note(
202                     wi,
203                     gmx::formatString("pull-coord%d has a non-zero force constant and is also "
204                                       "referenced in pull-coord%d-expression. "
205                                       "Make sure that this is intended. "
206                                       "In most use cases, the pull coordinates referenced by a "
207                                       "transformation coordinate should have their force constant "
208                                       "set to zero.",
209                                       coord_index_for_output,
210                                       previousCoordOutputIndex));
211         }
212     }
213 }
214
215 static void init_pull_coord(t_pull_coord*        pcrd,
216                             char*                dim_buf,
217                             const char*          origin_buf,
218                             const char*          vec_buf,
219                             const pull_params_t& pull,
220                             warninp_t            wi)
221 {
222     const int coord_index_for_output = pull.coord.size() + 1;
223
224     int  m;
225     dvec origin, vec;
226     char buf[STRLEN];
227
228     if (pcrd->eType == PullingAlgorithm::Constraint
229         && (pcrd->eGeom == PullGroupGeometry::Cylinder || pcrd->eGeom == PullGroupGeometry::DirectionRelative
230             || pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis
231             || pcrd->eGeom == PullGroupGeometry::Dihedral))
232     {
233         gmx_fatal(FARGS,
234                   "Pulling of type %s can not be combined with geometry %s. Consider using pull "
235                   "type %s.",
236                   enumValueToString(pcrd->eType),
237                   enumValueToString(pcrd->eGeom),
238                   enumValueToString(PullingAlgorithm::Umbrella));
239     }
240
241     if (pcrd->eType == PullingAlgorithm::External)
242     {
243         if (pcrd->externalPotentialProvider[0] == '\0')
244         {
245             sprintf(buf,
246                     "The use of pull type '%s' for pull coordinate %d requires that the name of "
247                     "the module providing the potential external is set with the option %s%d%s",
248                     enumValueToString(pcrd->eType),
249                     coord_index_for_output,
250                     "pull-coord",
251                     coord_index_for_output,
252                     "-potential-provider");
253             warning_error(wi, buf);
254         }
255
256         if (pcrd->rate != 0)
257         {
258             sprintf(buf,
259                     "The use of pull type '%s' for pull coordinate %d requires that the pull rate "
260                     "is zero",
261                     enumValueToString(pcrd->eType),
262                     coord_index_for_output);
263             warning_error(wi, buf);
264         }
265
266         if (pcrd->eGeom == PullGroupGeometry::Cylinder)
267         {
268             /* Warn the user of a PBC restriction, caused by the fact that
269              * there is no reference value with an external pull potential.
270              */
271             sprintf(buf,
272                     "With pull type '%s' and geometry '%s', the distance component along the "
273                     "cylinder axis between atoms in the cylinder group and the COM of the pull "
274                     "group should be smaller than half the box length",
275                     enumValueToString(pcrd->eType),
276                     enumValueToString(pcrd->eGeom));
277             warning_note(wi, buf);
278         }
279     }
280
281     process_pull_dim(dim_buf, pcrd->dim, pcrd);
282
283     string2dvec(origin_buf, origin);
284     if (pcrd->group[0] != 0 && dnorm(origin) > 0)
285     {
286         gmx_fatal(FARGS, "The pull origin can only be set with an absolute reference");
287     }
288
289     /* Check the given initial reference value and warn for dangerous values */
290     if (pcrd->eGeom == PullGroupGeometry::Distance)
291     {
292         if (pcrd->bStart && pcrd->init < 0)
293         {
294             sprintf(buf,
295                     "The initial reference distance set by pull-coord-init is set to a negative "
296                     "value (%g) with geometry %s while distances need to be non-negative. "
297                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
298                     "this value, but only for certain starting distances. "
299                     "If this is a mistake you may want to use geometry %s instead.",
300                     pcrd->init,
301                     enumValueToString(pcrd->eGeom),
302                     enumValueToString(PullGroupGeometry::Direction));
303             warning(wi, buf);
304         }
305     }
306     else if (pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis)
307     {
308         if (pcrd->bStart && (pcrd->init < 0 || pcrd->init > 180))
309         {
310             /* This value of pcrd->init may be ok depending on pcrd->bStart which modifies pcrd->init later on */
311             sprintf(buf,
312                     "The initial reference angle set by pull-coord-init (%g) is outside of the "
313                     "allowed range [0, 180] degrees for geometry (%s). "
314                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
315                     "this value, but only for certain starting angles.",
316                     pcrd->init,
317                     enumValueToString(pcrd->eGeom));
318             warning(wi, buf);
319         }
320     }
321     else if (pcrd->eGeom == PullGroupGeometry::Dihedral)
322     {
323         if (pcrd->bStart && (pcrd->init < -180 || pcrd->init > 180))
324         {
325             sprintf(buf,
326                     "The initial reference angle set by pull-coord-init (%g) is outside of the "
327                     "allowed range [-180, 180] degrees for geometry (%s). "
328                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
329                     "this value, but only for certain starting angles.",
330                     pcrd->init,
331                     enumValueToString(pcrd->eGeom));
332             warning(wi, buf);
333         }
334     }
335
336     /* Check and set the pull vector */
337     clear_dvec(vec);
338     string2dvec(vec_buf, vec);
339
340     if (pcrd->eGeom == PullGroupGeometry::Direction || pcrd->eGeom == PullGroupGeometry::Cylinder
341         || pcrd->eGeom == PullGroupGeometry::DirectionPBC || pcrd->eGeom == PullGroupGeometry::AngleAxis)
342     {
343         if (dnorm2(vec) == 0)
344         {
345             gmx_fatal(FARGS,
346                       "With pull geometry %s the pull vector can not be 0,0,0",
347                       enumValueToString(pcrd->eGeom));
348         }
349         for (int d = 0; d < DIM; d++)
350         {
351             if (vec[d] != 0 && pcrd->dim[d] == 0)
352             {
353                 gmx_fatal(FARGS,
354                           "pull-coord-vec has non-zero %c-component while pull_dim for the "
355                           "%c-dimension is set to N",
356                           'x' + d,
357                           'x' + d);
358             }
359         }
360
361         /* Normalize the direction vector */
362         dsvmul(1 / dnorm(vec), vec, vec);
363     }
364     else /* This case is for are all the geometries where the pull vector is not used */
365     {
366         if (dnorm2(vec) > 0)
367         {
368             sprintf(buf,
369                     "A pull vector is given (%g  %g  %g) but will not be used with geometry %s. If "
370                     "you really want to use this "
371                     "vector, consider using geometry %s instead.",
372                     vec[0],
373                     vec[1],
374                     vec[2],
375                     enumValueToString(pcrd->eGeom),
376                     pcrd->eGeom == PullGroupGeometry::Angle
377                             ? enumValueToString(PullGroupGeometry::AngleAxis)
378                             : enumValueToString(PullGroupGeometry::Direction));
379             warning(wi, buf);
380         }
381     }
382     if (pcrd->eGeom == PullGroupGeometry::Transformation)
383     {
384         initTransformationPullCoord(pcrd, pull, wi);
385     }
386
387     for (m = 0; m < DIM; m++)
388     {
389         pcrd->origin[m] = origin[m];
390         pcrd->vec[m]    = vec[m];
391     }
392 }
393
394 std::vector<std::string> read_pullparams(std::vector<t_inpfile>* inp, pull_params_t* pull, warninp_t wi)
395 {
396     int  nscan, idum;
397     char buf[STRLEN];
398     char provider[STRLEN], groups[STRLEN], dim_buf[STRLEN], expression[STRLEN];
399     char wbuf[STRLEN], origin_buf[STRLEN], vec_buf[STRLEN];
400
401     /* read pull parameters */
402     printStringNoNewline(inp, "Cylinder radius for dynamic reaction force groups (nm)");
403     pull->cylinder_r     = get_ereal(inp, "pull-cylinder-r", 1.5, wi);
404     pull->constr_tol     = get_ereal(inp, "pull-constr-tol", 1E-6, wi);
405     pull->bPrintCOM      = (getEnum<Boolean>(inp, "pull-print-com", wi) != Boolean::No);
406     pull->bPrintRefValue = (getEnum<Boolean>(inp, "pull-print-ref-value", wi) != Boolean::No);
407     pull->bPrintComp     = (getEnum<Boolean>(inp, "pull-print-components", wi) != Boolean::No);
408     pull->nstxout        = get_eint(inp, "pull-nstxout", 50, wi);
409     pull->nstfout        = get_eint(inp, "pull-nstfout", 50, wi);
410     pull->bSetPbcRefToPrevStepCOM =
411             (getEnum<Boolean>(inp, "pull-pbc-ref-prev-step-com", wi) != Boolean::No);
412     pull->bXOutAverage = (getEnum<Boolean>(inp, "pull-xout-average", wi) != Boolean::No);
413     pull->bFOutAverage = (getEnum<Boolean>(inp, "pull-fout-average", wi) != Boolean::No);
414     printStringNoNewline(inp, "Number of pull groups");
415     pull->ngroup = get_eint(inp, "pull-ngroups", 1, wi);
416     printStringNoNewline(inp, "Number of pull coordinates");
417     pull->ncoord = get_eint(inp, "pull-ncoords", 1, wi);
418
419     if (pull->ngroup < 1)
420     {
421         gmx_fatal(FARGS, "pull-ngroups should be >= 1");
422     }
423     /* We always add an absolute reference group (index 0), even if not used */
424     pull->ngroup += 1;
425
426     if (pull->ncoord < 1)
427     {
428         gmx_fatal(FARGS, "pull-ncoords should be >= 1");
429     }
430
431     /* pull group options */
432     printStringNoNewline(inp, "Group and coordinate parameters");
433
434     /* Read the pull groups */
435     std::vector<std::string> pullGroups(pull->ngroup);
436     char                     readBuffer[STRLEN];
437     /* Group 0 is the absolute reference, we don't read anything for 0 */
438     pull->group.emplace_back(t_pull_group());
439     for (int groupNum = 1; groupNum < pull->ngroup; groupNum++)
440     {
441         t_pull_group pullGroup;
442         sprintf(buf, "pull-group%d-name", groupNum);
443         setStringEntry(inp, buf, readBuffer, "");
444         pullGroups[groupNum] = readBuffer;
445         sprintf(buf, "pull-group%d-weights", groupNum);
446         setStringEntry(inp, buf, wbuf, "");
447         sprintf(buf, "pull-group%d-pbcatom", groupNum);
448         pullGroup.pbcatom       = get_eint(inp, buf, 0, wi);
449         pullGroup.pbcatom_input = pullGroup.pbcatom;
450
451         /* Initialize the pull group */
452         pullGroup.weight = setupPullGroupWeights(wbuf);
453         pull->group.emplace_back(pullGroup);
454     }
455
456     /* Read the pull coordinates */
457     for (int coordNum = 1; coordNum < pull->ncoord + 1; coordNum++)
458     {
459         t_pull_coord pullCoord; // = &pull->coord[coordNum - 1];
460         sprintf(buf, "pull-coord%d-type", coordNum);
461         pullCoord.eType = getEnum<PullingAlgorithm>(inp, buf, wi);
462         sprintf(buf, "pull-coord%d-potential-provider", coordNum);
463         setStringEntry(inp, buf, provider, "");
464         pullCoord.externalPotentialProvider = provider;
465         sprintf(buf, "pull-coord%d-expression", coordNum);
466         setStringEntry(inp, buf, expression, "");
467         pullCoord.expression = expression;
468         sprintf(buf, "pull-coord%d-dx", coordNum);
469         pullCoord.dx = get_ereal(inp, buf, 1e-9, wi);
470         sprintf(buf, "pull-coord%d-geometry", coordNum);
471         pullCoord.eGeom = getEnum<PullGroupGeometry>(inp, buf, wi);
472         sprintf(buf, "pull-coord%d-groups", coordNum);
473         setStringEntry(inp, buf, groups, "");
474
475         switch (pullCoord.eGeom)
476         {
477             case PullGroupGeometry::Dihedral: pullCoord.ngroup = 6; break;
478             case PullGroupGeometry::DirectionRelative:
479             case PullGroupGeometry::Angle: pullCoord.ngroup = 4; break;
480             case PullGroupGeometry::Transformation: pullCoord.ngroup = 0; break;
481             default: pullCoord.ngroup = 2; break;
482         }
483
484         nscan = sscanf(groups,
485                        "%d %d %d %d %d %d %d",
486                        &pullCoord.group[0],
487                        &pullCoord.group[1],
488                        &pullCoord.group[2],
489                        &pullCoord.group[3],
490                        &pullCoord.group[4],
491                        &pullCoord.group[5],
492                        &idum);
493         if (nscan < 0)
494         {
495             // If the groups are not defined we can get a negative value here.
496             // It makes more sense to change it to 0
497             nscan = 0;
498         }
499         if (nscan != pullCoord.ngroup)
500         {
501             auto message = gmx::formatString(
502                     "%s should contain %d pull group indices with geometry %s."
503                     " Found %d groups.",
504                     buf,
505                     pullCoord.ngroup,
506                     enumValueToString(pullCoord.eGeom),
507                     nscan);
508             set_warning_line(wi, nullptr, -1);
509             warning_error(wi, message);
510         }
511         for (int g = 0; g < pullCoord.ngroup; g++)
512         {
513             if (pullCoord.group[g] < 0 || pullCoord.group[g] >= pull->ngroup)
514             {
515                 /* Quit with a fatal error to avoid invalid memory access */
516                 gmx_fatal(FARGS,
517                           "%s contains an invalid pull group %d, you should have %d <= group <= %d",
518                           buf,
519                           pullCoord.group[g],
520                           0,
521                           pull->ngroup - 1);
522             }
523         }
524
525         sprintf(buf, "pull-coord%d-dim", coordNum);
526         setStringEntry(inp, buf, dim_buf, "Y Y Y");
527         sprintf(buf, "pull-coord%d-origin", coordNum);
528         setStringEntry(inp, buf, origin_buf, "0.0 0.0 0.0");
529         sprintf(buf, "pull-coord%d-vec", coordNum);
530         setStringEntry(inp, buf, vec_buf, "0.0 0.0 0.0");
531         sprintf(buf, "pull-coord%d-start", coordNum);
532         pullCoord.bStart = (getEnum<Boolean>(inp, buf, wi) != Boolean::No);
533         sprintf(buf, "pull-coord%d-init", coordNum);
534         pullCoord.init = get_ereal(inp, buf, 0.0, wi);
535         sprintf(buf, "pull-coord%d-rate", coordNum);
536         pullCoord.rate = get_ereal(inp, buf, 0.0, wi);
537         sprintf(buf, "pull-coord%d-k", coordNum);
538         pullCoord.k = get_ereal(inp, buf, 0.0, wi);
539         sprintf(buf, "pull-coord%d-kB", coordNum);
540         pullCoord.kB = get_ereal(inp, buf, pullCoord.k, wi);
541
542         /* Initialize the pull coordinate */
543         init_pull_coord(&pullCoord, dim_buf, origin_buf, vec_buf, *pull, wi);
544
545         pullCoord.coordIndex = coordNum - 1;
546         pull->coord.emplace_back(pullCoord);
547     }
548
549     return pullGroups;
550 }
551
552 void process_pull_groups(gmx::ArrayRef<t_pull_group>      pullGroups,
553                          gmx::ArrayRef<const std::string> pullGroupNames,
554                          const t_blocka*                  grps,
555                          char**                           gnames)
556 {
557     /* Absolute reference group (might not be used) is special */
558     pullGroups.front().pbcatom       = -1;
559     pullGroups.front().pbcatom_input = -1;
560
561     // Skip pull group 0 here, as that is the absolute reference
562     for (int g = 1; g < int(pullGroups.size()); g++)
563     {
564         auto& pullGroup = pullGroups[g];
565
566         if (pullGroupNames[g].empty())
567         {
568             gmx_fatal(FARGS, "Pull option pull_group%d required by grompp has not been set.", g);
569         }
570
571         int ig                = search_string(pullGroupNames[g].c_str(), grps->nr, gnames);
572         int numPullGroupAtoms = grps->index[ig + 1] - grps->index[ig];
573
574         fprintf(stderr, "Pull group %d '%s' has %d atoms\n", g, pullGroupNames[g].c_str(), numPullGroupAtoms);
575
576         if (numPullGroupAtoms == 0)
577         {
578             gmx_fatal(FARGS, "Pull group %d '%s' is empty", g, pullGroupNames[g].c_str());
579         }
580
581         for (int i = 0; i < numPullGroupAtoms; i++)
582         {
583             pullGroup.ind.push_back(grps->a[grps->index[ig] + i]);
584         }
585
586         if (!pullGroup.weight.empty() && pullGroup.weight.size() != pullGroup.ind.size())
587         {
588             gmx_fatal(FARGS,
589                       "Number of weights (%ld) for pull group %d '%s' does not match the number of "
590                       "atoms (%ld)",
591                       gmx::ssize(pullGroup.weight),
592                       g,
593                       pullGroupNames[g].c_str(),
594                       gmx::ssize(pullGroup.ind));
595         }
596
597         pullGroup.pbcatom_input = pullGroup.pbcatom;
598         if (pullGroup.ind.size() == 1)
599         {
600             /* No pbc is required for this group */
601             pullGroup.pbcatom = -1;
602         }
603         else
604         {
605             if (pullGroup.pbcatom > 0)
606             {
607                 pullGroup.pbcatom -= 1;
608             }
609             else if (pullGroup.pbcatom == 0)
610             {
611                 pullGroup.pbcatom = pullGroup.ind[(pullGroup.ind.size() - 1) / 2];
612             }
613             else
614             {
615                 /* Use cosine weighting */
616                 pullGroup.pbcatom = -1;
617             }
618         }
619     }
620 }
621
622 void checkPullCoords(gmx::ArrayRef<const t_pull_group> pullGroups, gmx::ArrayRef<const t_pull_coord> pullCoords)
623 {
624     for (int c = 0; c < pullCoords.ssize(); ++c)
625     {
626         const t_pull_coord& pcrd = pullCoords[c];
627
628         GMX_RELEASE_ASSERT(pcrd.coordIndex == c, "coordIndex should match the index in the vector");
629
630         if (pcrd.eGeom == PullGroupGeometry::Transformation)
631         {
632             GMX_RELEASE_ASSERT(pcrd.ngroup == 0,
633                                "Transformation coordinates don't use groups and "
634                                "should have 'ngroup' set to zero");
635             continue;
636         }
637         if (pcrd.group[0] < 0 || pcrd.group[0] >= int(pullGroups.size()) || pcrd.group[1] < 0
638             || pcrd.group[1] >= int(pullGroups.size()))
639         {
640             gmx_fatal(FARGS,
641                       "Pull group index in pull-coord%d-groups out of range, should be between %d "
642                       "and %d",
643                       pcrd.coordIndex + 1,
644                       0,
645                       int(pullGroups.size()) + 1);
646         }
647
648         if (pcrd.group[0] == pcrd.group[1])
649         {
650             gmx_fatal(FARGS, "Identical pull group indices in pull-coord%d-groups", pcrd.coordIndex + 1);
651         }
652
653         if (pcrd.eGeom == PullGroupGeometry::Cylinder)
654         {
655             if (!pullGroups[pcrd.group[0]].weight.empty())
656             {
657                 gmx_fatal(
658                         FARGS,
659                         "Weights are not supported for the reference group with cylinder pulling");
660             }
661         }
662         c++;
663     }
664 }
665
666 pull_t* set_pull_init(t_inputrec*                    ir,
667                       const gmx_mtop_t&              mtop,
668                       gmx::ArrayRef<const gmx::RVec> x,
669                       matrix                         box,
670                       real                           lambda,
671                       warninp_t                      wi)
672 {
673     pull_t* pull_work;
674     t_pbc   pbc;
675
676     pull_params_t*           pull = ir->pull.get();
677     gmx::LocalAtomSetManager atomSets;
678     pull_work     = init_pull(nullptr, pull, ir, mtop, nullptr, &atomSets, lambda);
679     auto  mdAtoms = gmx::makeMDAtoms(nullptr, mtop, *ir, false);
680     auto* md      = mdAtoms->mdatoms();
681     atoms2md(mtop, *ir, -1, {}, mtop.natoms, mdAtoms.get());
682     if (ir->efep != FreeEnergyPerturbationType::No)
683     {
684         update_mdatoms(md, lambda);
685     }
686
687     set_pbc(&pbc, ir->pbcType, box);
688
689     double t_start = ir->init_t + ir->init_step * ir->delta_t;
690
691     if (pull->bSetPbcRefToPrevStepCOM)
692     {
693         initPullComFromPrevStep(nullptr, pull_work, gmx::arrayRefFromArray(md->massT, md->nr), pbc, x);
694     }
695     pull_calc_coms(nullptr, pull_work, gmx::arrayRefFromArray(md->massT, md->nr), pbc, t_start, x, {});
696
697     for (int g = 0; g < pull->ngroup; g++)
698     {
699         bool groupObeysPbc =
700                 pullCheckPbcWithinGroup(*pull_work, x, pbc, g, c_pullGroupSmallGroupThreshold);
701         if (!groupObeysPbc)
702         {
703             char buf[STRLEN];
704             if (pull->group[g].pbcatom_input == 0)
705             {
706                 sprintf(buf,
707                         "When the maximum distance from a pull group reference atom to other atoms "
708                         "in the "
709                         "group is larger than %g times half the box size a centrally placed "
710                         "atom should be chosen as pbcatom. Pull group %d is larger than that and "
711                         "does not have "
712                         "a specific atom selected as reference atom.",
713                         c_pullGroupSmallGroupThreshold,
714                         g);
715                 warning_error(wi, buf);
716             }
717             else if (!pull->bSetPbcRefToPrevStepCOM)
718             {
719                 sprintf(buf,
720                         "The maximum distance from the chosen PBC atom (%d) of pull group %d to "
721                         "other "
722                         "atoms in the group is larger than %g times half the box size. "
723                         "Set the pull-pbc-ref-prev-step-com option to yes.",
724                         pull->group[g].pbcatom + 1,
725                         g,
726                         c_pullGroupSmallGroupThreshold);
727                 warning_error(wi, buf);
728             }
729         }
730         if (groupObeysPbc)
731         {
732             groupObeysPbc = pullCheckPbcWithinGroup(*pull_work, x, pbc, g, c_pullGroupPbcMargin);
733             if (!groupObeysPbc)
734             {
735                 char buf[STRLEN];
736                 sprintf(buf,
737                         "Pull group %d has atoms at a distance larger than %g times half the box "
738                         "size from the PBC atom (%d). "
739                         "If atoms are or will more beyond half the box size from the PBC atom, the "
740                         "COM will be ill defined.",
741                         g,
742                         c_pullGroupPbcMargin,
743                         pull->group[g].pbcatom + 1);
744                 set_warning_line(wi, nullptr, -1);
745                 warning(wi, buf);
746             }
747         }
748     }
749
750     fprintf(stderr, "Pull group  natoms  pbc atom  distance at start  reference at t=0\n");
751     for (int c = 0; c < pull->ncoord; c++)
752     {
753         real init = 0;
754
755         t_pull_coord* pcrd = &pull->coord[c];
756
757         t_pull_group* pgrp0 = &pull->group[pcrd->group[0]];
758         t_pull_group* pgrp1 = &pull->group[pcrd->group[1]];
759         fprintf(stderr, "%8d  %8zu  %8d\n", pcrd->group[0], pgrp0->ind.size(), pgrp0->pbcatom + 1);
760         fprintf(stderr, "%8d  %8zu  %8d ", pcrd->group[1], pgrp1->ind.size(), pgrp1->pbcatom + 1);
761
762         if (pcrd->bStart)
763         {
764             init       = pcrd->init;
765             pcrd->init = 0;
766         }
767
768         double value = get_pull_coord_value(pull_work, c, pbc);
769
770         value *= pull_conversion_factor_internal2userinput(*pcrd);
771         fprintf(stderr, " %10.3f %s", value, pull_coordinate_units(*pcrd));
772
773         if (pcrd->bStart)
774         {
775             pcrd->init = value + init;
776         }
777
778         if (pcrd->eGeom == PullGroupGeometry::Distance)
779         {
780             if (pcrd->init < 0)
781             {
782                 gmx_fatal(FARGS,
783                           "The initial pull distance (%g) needs to be non-negative with geometry "
784                           "%s. If you want a signed distance, use geometry %s instead.",
785                           pcrd->init,
786                           enumValueToString(pcrd->eGeom),
787                           enumValueToString(PullGroupGeometry::Direction));
788             }
789
790             /* TODO: With a positive init but a negative rate things could still
791              * go wrong, but it might be fine if you don't pull too far.
792              * We should give a warning or note when there is only one pull dim
793              * active, since that is usually the problematic case when you should
794              * be using direction. We will do this later, since an already planned
795              * generalization of the pull code makes pull dim available here.
796              */
797         }
798         else if (pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis)
799         {
800             if (pcrd->init < 0 || pcrd->init > 180)
801             {
802                 gmx_fatal(FARGS,
803                           "The initial pull reference angle (%g) is outside of the allowed range "
804                           "[0, 180] degrees.",
805                           pcrd->init);
806             }
807         }
808         else if (pcrd->eGeom == PullGroupGeometry::Dihedral)
809         {
810             if (pcrd->init < -180 || pcrd->init > 180)
811             {
812                 gmx_fatal(FARGS,
813                           "The initial pull reference angle (%g) is outside of the allowed range "
814                           "[-180, 180] degrees.",
815                           pcrd->init);
816             }
817         }
818
819
820         fprintf(stderr, "     %10.3f %s\n", pcrd->init, pull_coordinate_units(*pcrd));
821     }
822
823     return pull_work;
824 }