2524976cb583bf942e49fdc43b1e51d74ade2a99
[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)
138 {
139     const int coord_index_for_output = pull.coord.size() + 1;
140     if (pcrd->eType == PullingAlgorithm::Constraint)
141     {
142         GMX_THROW(gmx::InvalidInputError(gmx::formatString(
143                 "pull-coord%d can not have type 'constraint' and geometry 'transformation'",
144                 coord_index_for_output)));
145     }
146
147     /*Validate the mathematical expression to epullgTRANSFORMATION*/
148     if (pcrd->expression.empty())
149     {
150         GMX_THROW(gmx::InvalidInputError(
151                 gmx::formatString("pull-coord%d-expression not set for pull coordinate of geometry "
152                                   "'transformation'",
153                                   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         GMX_THROW(gmx::InvalidInputError(gmx::formatString(
164                 "pull-coord%d-dx cannot be set to zero for pull coordinate of geometry "
165                 "'transformation'",
166                 coord_index_for_output)));
167     }
168     /* make sure that the kappa of all previous pull coords is 0*/
169     int previousCoordOutputIndex = 0;
170     for (const auto& previousPcrd : pull.coord)
171     {
172         previousCoordOutputIndex++;
173         // See if the previous variable is used by the transformatino coord
174         // Note that a simple std::string::find won't work since we don't want x1 to match x11 etc.
175         std::string previousPcrdName = gmx::formatString("x%d(\\D|$)", previousCoordOutputIndex);
176         std::regex  rx(previousPcrdName);
177
178         std::ptrdiff_t number_of_matches = std::distance(
179                 std::sregex_iterator(pcrd->expression.begin(), pcrd->expression.end(), rx),
180                 std::sregex_iterator());
181
182         if (number_of_matches == 0)
183         {
184             // This previous coordinate is not used in this transformation, do not check it
185             continue;
186         }
187
188         if (previousPcrd.eType == PullingAlgorithm::Constraint)
189         {
190             GMX_THROW(gmx::InvalidInputError(
191                     gmx::formatString("pull-coord%d can not use pull-coord%d in the "
192                                       "transformation since this is a constraint",
193                                       coord_index_for_output,
194                                       previousCoordOutputIndex)));
195         }
196     }
197 }
198
199 static void init_pull_coord(t_pull_coord*        pcrd,
200                             char*                dim_buf,
201                             const char*          origin_buf,
202                             const char*          vec_buf,
203                             const pull_params_t& pull,
204                             warninp_t            wi)
205 {
206     const int coord_index_for_output = pull.coord.size() + 1;
207
208     int  m;
209     dvec origin, vec;
210     char buf[STRLEN];
211
212     if (pcrd->eType == PullingAlgorithm::Constraint
213         && (pcrd->eGeom == PullGroupGeometry::Cylinder || pcrd->eGeom == PullGroupGeometry::DirectionRelative
214             || pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis
215             || pcrd->eGeom == PullGroupGeometry::Dihedral))
216     {
217         gmx_fatal(FARGS,
218                   "Pulling of type %s can not be combined with geometry %s. Consider using pull "
219                   "type %s.",
220                   enumValueToString(pcrd->eType),
221                   enumValueToString(pcrd->eGeom),
222                   enumValueToString(PullingAlgorithm::Umbrella));
223     }
224
225     if (pcrd->eType == PullingAlgorithm::External)
226     {
227         if (pcrd->externalPotentialProvider[0] == '\0')
228         {
229             sprintf(buf,
230                     "The use of pull type '%s' for pull coordinate %d requires that the name of "
231                     "the module providing the potential external is set with the option %s%d%s",
232                     enumValueToString(pcrd->eType),
233                     coord_index_for_output,
234                     "pull-coord",
235                     coord_index_for_output,
236                     "-potential-provider");
237             warning_error(wi, buf);
238         }
239
240         if (pcrd->rate != 0)
241         {
242             sprintf(buf,
243                     "The use of pull type '%s' for pull coordinate %d requires that the pull rate "
244                     "is zero",
245                     enumValueToString(pcrd->eType),
246                     coord_index_for_output);
247             warning_error(wi, buf);
248         }
249
250         if (pcrd->eGeom == PullGroupGeometry::Cylinder)
251         {
252             /* Warn the user of a PBC restriction, caused by the fact that
253              * there is no reference value with an external pull potential.
254              */
255             sprintf(buf,
256                     "With pull type '%s' and geometry '%s', the distance component along the "
257                     "cylinder axis between atoms in the cylinder group and the COM of the pull "
258                     "group should be smaller than half the box length",
259                     enumValueToString(pcrd->eType),
260                     enumValueToString(pcrd->eGeom));
261             warning_note(wi, buf);
262         }
263     }
264
265     process_pull_dim(dim_buf, pcrd->dim, pcrd);
266
267     string2dvec(origin_buf, origin);
268     if (pcrd->group[0] != 0 && dnorm(origin) > 0)
269     {
270         gmx_fatal(FARGS, "The pull origin can only be set with an absolute reference");
271     }
272
273     /* Check the given initial reference value and warn for dangerous values */
274     if (pcrd->eGeom == PullGroupGeometry::Distance)
275     {
276         if (pcrd->bStart && pcrd->init < 0)
277         {
278             sprintf(buf,
279                     "The initial reference distance set by pull-coord-init is set to a negative "
280                     "value (%g) with geometry %s while distances need to be non-negative. "
281                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
282                     "this value, but only for certain starting distances. "
283                     "If this is a mistake you may want to use geometry %s instead.",
284                     pcrd->init,
285                     enumValueToString(pcrd->eGeom),
286                     enumValueToString(PullGroupGeometry::Direction));
287             warning(wi, buf);
288         }
289     }
290     else if (pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis)
291     {
292         if (pcrd->bStart && (pcrd->init < 0 || pcrd->init > 180))
293         {
294             /* This value of pcrd->init may be ok depending on pcrd->bStart which modifies pcrd->init later on */
295             sprintf(buf,
296                     "The initial reference angle set by pull-coord-init (%g) is outside of the "
297                     "allowed range [0, 180] degrees for geometry (%s). "
298                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
299                     "this value, but only for certain starting angles.",
300                     pcrd->init,
301                     enumValueToString(pcrd->eGeom));
302             warning(wi, buf);
303         }
304     }
305     else if (pcrd->eGeom == PullGroupGeometry::Dihedral)
306     {
307         if (pcrd->bStart && (pcrd->init < -180 || pcrd->init > 180))
308         {
309             sprintf(buf,
310                     "The initial reference angle set by pull-coord-init (%g) is outside of the "
311                     "allowed range [-180, 180] degrees for geometry (%s). "
312                     "This may work, since you have set pull-coord-start to 'yes' which modifies "
313                     "this value, but only for certain starting angles.",
314                     pcrd->init,
315                     enumValueToString(pcrd->eGeom));
316             warning(wi, buf);
317         }
318     }
319
320     /* Check and set the pull vector */
321     clear_dvec(vec);
322     string2dvec(vec_buf, vec);
323
324     if (pcrd->eGeom == PullGroupGeometry::Direction || pcrd->eGeom == PullGroupGeometry::Cylinder
325         || pcrd->eGeom == PullGroupGeometry::DirectionPBC || pcrd->eGeom == PullGroupGeometry::AngleAxis)
326     {
327         if (dnorm2(vec) == 0)
328         {
329             gmx_fatal(FARGS,
330                       "With pull geometry %s the pull vector can not be 0,0,0",
331                       enumValueToString(pcrd->eGeom));
332         }
333         for (int d = 0; d < DIM; d++)
334         {
335             if (vec[d] != 0 && pcrd->dim[d] == 0)
336             {
337                 gmx_fatal(FARGS,
338                           "pull-coord-vec has non-zero %c-component while pull_dim for the "
339                           "%c-dimension is set to N",
340                           'x' + d,
341                           'x' + d);
342             }
343         }
344
345         /* Normalize the direction vector */
346         dsvmul(1 / dnorm(vec), vec, vec);
347     }
348     else /* This case is for are all the geometries where the pull vector is not used */
349     {
350         if (dnorm2(vec) > 0)
351         {
352             sprintf(buf,
353                     "A pull vector is given (%g  %g  %g) but will not be used with geometry %s. If "
354                     "you really want to use this "
355                     "vector, consider using geometry %s instead.",
356                     vec[0],
357                     vec[1],
358                     vec[2],
359                     enumValueToString(pcrd->eGeom),
360                     pcrd->eGeom == PullGroupGeometry::Angle
361                             ? enumValueToString(PullGroupGeometry::AngleAxis)
362                             : enumValueToString(PullGroupGeometry::Direction));
363             warning(wi, buf);
364         }
365     }
366     if (pcrd->eGeom == PullGroupGeometry::Transformation)
367     {
368         initTransformationPullCoord(pcrd, pull);
369     }
370
371     for (m = 0; m < DIM; m++)
372     {
373         pcrd->origin[m] = origin[m];
374         pcrd->vec[m]    = vec[m];
375     }
376 }
377
378 std::vector<std::string> read_pullparams(std::vector<t_inpfile>* inp, pull_params_t* pull, warninp_t wi)
379 {
380     int  nscan, idum;
381     char buf[STRLEN];
382     char provider[STRLEN], groups[STRLEN], dim_buf[STRLEN], expression[STRLEN];
383     char wbuf[STRLEN], origin_buf[STRLEN], vec_buf[STRLEN];
384
385     /* read pull parameters */
386     printStringNoNewline(inp, "Cylinder radius for dynamic reaction force groups (nm)");
387     pull->cylinder_r     = get_ereal(inp, "pull-cylinder-r", 1.5, wi);
388     pull->constr_tol     = get_ereal(inp, "pull-constr-tol", 1E-6, wi);
389     pull->bPrintCOM      = (getEnum<Boolean>(inp, "pull-print-com", wi) != Boolean::No);
390     pull->bPrintRefValue = (getEnum<Boolean>(inp, "pull-print-ref-value", wi) != Boolean::No);
391     pull->bPrintComp     = (getEnum<Boolean>(inp, "pull-print-components", wi) != Boolean::No);
392     pull->nstxout        = get_eint(inp, "pull-nstxout", 50, wi);
393     pull->nstfout        = get_eint(inp, "pull-nstfout", 50, wi);
394     pull->bSetPbcRefToPrevStepCOM =
395             (getEnum<Boolean>(inp, "pull-pbc-ref-prev-step-com", wi) != Boolean::No);
396     pull->bXOutAverage = (getEnum<Boolean>(inp, "pull-xout-average", wi) != Boolean::No);
397     pull->bFOutAverage = (getEnum<Boolean>(inp, "pull-fout-average", wi) != Boolean::No);
398     printStringNoNewline(inp, "Number of pull groups");
399     pull->ngroup = get_eint(inp, "pull-ngroups", 1, wi);
400     printStringNoNewline(inp, "Number of pull coordinates");
401     pull->ncoord = get_eint(inp, "pull-ncoords", 1, wi);
402
403     if (pull->ngroup < 1)
404     {
405         gmx_fatal(FARGS, "pull-ngroups should be >= 1");
406     }
407     /* We always add an absolute reference group (index 0), even if not used */
408     pull->ngroup += 1;
409
410     if (pull->ncoord < 1)
411     {
412         gmx_fatal(FARGS, "pull-ncoords should be >= 1");
413     }
414
415     /* pull group options */
416     printStringNoNewline(inp, "Group and coordinate parameters");
417
418     /* Read the pull groups */
419     std::vector<std::string> pullGroups(pull->ngroup);
420     char                     readBuffer[STRLEN];
421     /* Group 0 is the absolute reference, we don't read anything for 0 */
422     pull->group.emplace_back(t_pull_group());
423     for (int groupNum = 1; groupNum < pull->ngroup; groupNum++)
424     {
425         t_pull_group pullGroup;
426         sprintf(buf, "pull-group%d-name", groupNum);
427         setStringEntry(inp, buf, readBuffer, "");
428         pullGroups[groupNum] = readBuffer;
429         sprintf(buf, "pull-group%d-weights", groupNum);
430         setStringEntry(inp, buf, wbuf, "");
431         sprintf(buf, "pull-group%d-pbcatom", groupNum);
432         pullGroup.pbcatom       = get_eint(inp, buf, 0, wi);
433         pullGroup.pbcatom_input = pullGroup.pbcatom;
434
435         /* Initialize the pull group */
436         pullGroup.weight = setupPullGroupWeights(wbuf);
437         pull->group.emplace_back(pullGroup);
438     }
439
440     /* Read the pull coordinates */
441     for (int coordNum = 1; coordNum < pull->ncoord + 1; coordNum++)
442     {
443         t_pull_coord pullCoord; // = &pull->coord[coordNum - 1];
444         sprintf(buf, "pull-coord%d-type", coordNum);
445         pullCoord.eType = getEnum<PullingAlgorithm>(inp, buf, wi);
446         sprintf(buf, "pull-coord%d-potential-provider", coordNum);
447         setStringEntry(inp, buf, provider, "");
448         pullCoord.externalPotentialProvider = provider;
449         sprintf(buf, "pull-coord%d-expression", coordNum);
450         setStringEntry(inp, buf, expression, "");
451         pullCoord.expression = expression;
452         sprintf(buf, "pull-coord%d-dx", coordNum);
453         pullCoord.dx = get_ereal(inp, buf, 1e-9, wi);
454         sprintf(buf, "pull-coord%d-geometry", coordNum);
455         pullCoord.eGeom = getEnum<PullGroupGeometry>(inp, buf, wi);
456         sprintf(buf, "pull-coord%d-groups", coordNum);
457         setStringEntry(inp, buf, groups, "");
458
459         switch (pullCoord.eGeom)
460         {
461             case PullGroupGeometry::Dihedral: pullCoord.ngroup = 6; break;
462             case PullGroupGeometry::DirectionRelative:
463             case PullGroupGeometry::Angle: pullCoord.ngroup = 4; break;
464             case PullGroupGeometry::Transformation: pullCoord.ngroup = 0; break;
465             default: pullCoord.ngroup = 2; break;
466         }
467
468         nscan = sscanf(groups,
469                        "%d %d %d %d %d %d %d",
470                        &pullCoord.group[0],
471                        &pullCoord.group[1],
472                        &pullCoord.group[2],
473                        &pullCoord.group[3],
474                        &pullCoord.group[4],
475                        &pullCoord.group[5],
476                        &idum);
477         if (nscan < 0)
478         {
479             // If the groups are not defined we can get a negative value here.
480             // It makes more sense to change it to 0
481             nscan = 0;
482         }
483         if (nscan != pullCoord.ngroup)
484         {
485             auto message = gmx::formatString(
486                     "%s should contain %d pull group indices with geometry %s."
487                     " Found %d groups.",
488                     buf,
489                     pullCoord.ngroup,
490                     enumValueToString(pullCoord.eGeom),
491                     nscan);
492             set_warning_line(wi, nullptr, -1);
493             warning_error(wi, message);
494         }
495         for (int g = 0; g < pullCoord.ngroup; g++)
496         {
497             if (pullCoord.group[g] < 0 || pullCoord.group[g] >= pull->ngroup)
498             {
499                 /* Quit with a fatal error to avoid invalid memory access */
500                 gmx_fatal(FARGS,
501                           "%s contains an invalid pull group %d, you should have %d <= group <= %d",
502                           buf,
503                           pullCoord.group[g],
504                           0,
505                           pull->ngroup - 1);
506             }
507         }
508
509         sprintf(buf, "pull-coord%d-dim", coordNum);
510         setStringEntry(inp, buf, dim_buf, "Y Y Y");
511         sprintf(buf, "pull-coord%d-origin", coordNum);
512         setStringEntry(inp, buf, origin_buf, "0.0 0.0 0.0");
513         sprintf(buf, "pull-coord%d-vec", coordNum);
514         setStringEntry(inp, buf, vec_buf, "0.0 0.0 0.0");
515         sprintf(buf, "pull-coord%d-start", coordNum);
516         pullCoord.bStart = (getEnum<Boolean>(inp, buf, wi) != Boolean::No);
517         sprintf(buf, "pull-coord%d-init", coordNum);
518         pullCoord.init = get_ereal(inp, buf, 0.0, wi);
519         sprintf(buf, "pull-coord%d-rate", coordNum);
520         pullCoord.rate = get_ereal(inp, buf, 0.0, wi);
521         sprintf(buf, "pull-coord%d-k", coordNum);
522         pullCoord.k = get_ereal(inp, buf, 0.0, wi);
523         sprintf(buf, "pull-coord%d-kB", coordNum);
524         pullCoord.kB = get_ereal(inp, buf, pullCoord.k, wi);
525
526         /* Initialize the pull coordinate */
527         init_pull_coord(&pullCoord, dim_buf, origin_buf, vec_buf, *pull, wi);
528
529         pullCoord.coordIndex = coordNum - 1;
530         pull->coord.emplace_back(pullCoord);
531     }
532
533     return pullGroups;
534 }
535
536 void process_pull_groups(gmx::ArrayRef<t_pull_group>      pullGroups,
537                          gmx::ArrayRef<const std::string> pullGroupNames,
538                          const t_blocka*                  grps,
539                          char**                           gnames)
540 {
541     /* Absolute reference group (might not be used) is special */
542     pullGroups.front().pbcatom       = -1;
543     pullGroups.front().pbcatom_input = -1;
544
545     // Skip pull group 0 here, as that is the absolute reference
546     for (int g = 1; g < int(pullGroups.size()); g++)
547     {
548         auto& pullGroup = pullGroups[g];
549
550         if (pullGroupNames[g].empty())
551         {
552             gmx_fatal(FARGS, "Pull option pull_group%d required by grompp has not been set.", g);
553         }
554
555         int ig                = search_string(pullGroupNames[g].c_str(), grps->nr, gnames);
556         int numPullGroupAtoms = grps->index[ig + 1] - grps->index[ig];
557
558         fprintf(stderr, "Pull group %d '%s' has %d atoms\n", g, pullGroupNames[g].c_str(), numPullGroupAtoms);
559
560         if (numPullGroupAtoms == 0)
561         {
562             gmx_fatal(FARGS, "Pull group %d '%s' is empty", g, pullGroupNames[g].c_str());
563         }
564
565         for (int i = 0; i < numPullGroupAtoms; i++)
566         {
567             pullGroup.ind.push_back(grps->a[grps->index[ig] + i]);
568         }
569
570         if (!pullGroup.weight.empty() && pullGroup.weight.size() != pullGroup.ind.size())
571         {
572             gmx_fatal(FARGS,
573                       "Number of weights (%ld) for pull group %d '%s' does not match the number of "
574                       "atoms (%ld)",
575                       gmx::ssize(pullGroup.weight),
576                       g,
577                       pullGroupNames[g].c_str(),
578                       gmx::ssize(pullGroup.ind));
579         }
580
581         pullGroup.pbcatom_input = pullGroup.pbcatom;
582         if (pullGroup.ind.size() == 1)
583         {
584             /* No pbc is required for this group */
585             pullGroup.pbcatom = -1;
586         }
587         else
588         {
589             if (pullGroup.pbcatom > 0)
590             {
591                 pullGroup.pbcatom -= 1;
592             }
593             else if (pullGroup.pbcatom == 0)
594             {
595                 pullGroup.pbcatom = pullGroup.ind[(pullGroup.ind.size() - 1) / 2];
596             }
597             else
598             {
599                 /* Use cosine weighting */
600                 pullGroup.pbcatom = -1;
601             }
602         }
603     }
604 }
605
606 void checkPullCoords(gmx::ArrayRef<const t_pull_group> pullGroups, gmx::ArrayRef<const t_pull_coord> pullCoords)
607 {
608     for (int c = 0; c < pullCoords.ssize(); ++c)
609     {
610         const t_pull_coord& pcrd = pullCoords[c];
611
612         GMX_RELEASE_ASSERT(pcrd.coordIndex == c, "coordIndex should match the index in the vector");
613
614         if (pcrd.eGeom == PullGroupGeometry::Transformation)
615         {
616             GMX_RELEASE_ASSERT(pcrd.ngroup == 0,
617                                "Transformation coordinates don't use groups and "
618                                "should have 'ngroup' set to zero");
619             continue;
620         }
621         if (pcrd.group[0] < 0 || pcrd.group[0] >= int(pullGroups.size()) || pcrd.group[1] < 0
622             || pcrd.group[1] >= int(pullGroups.size()))
623         {
624             gmx_fatal(FARGS,
625                       "Pull group index in pull-coord%d-groups out of range, should be between %d "
626                       "and %d",
627                       pcrd.coordIndex + 1,
628                       0,
629                       int(pullGroups.size()) + 1);
630         }
631
632         if (pcrd.group[0] == pcrd.group[1])
633         {
634             gmx_fatal(FARGS, "Identical pull group indices in pull-coord%d-groups", pcrd.coordIndex + 1);
635         }
636
637         if (pcrd.eGeom == PullGroupGeometry::Cylinder)
638         {
639             if (!pullGroups[pcrd.group[0]].weight.empty())
640             {
641                 gmx_fatal(
642                         FARGS,
643                         "Weights are not supported for the reference group with cylinder pulling");
644             }
645         }
646         c++;
647     }
648 }
649
650 pull_t* set_pull_init(t_inputrec*                    ir,
651                       const gmx_mtop_t&              mtop,
652                       gmx::ArrayRef<const gmx::RVec> x,
653                       matrix                         box,
654                       real                           lambda,
655                       warninp_t                      wi)
656 {
657     pull_t* pull_work;
658     t_pbc   pbc;
659
660     pull_params_t*           pull = ir->pull.get();
661     gmx::LocalAtomSetManager atomSets;
662     pull_work     = init_pull(nullptr, pull, ir, mtop, nullptr, &atomSets, lambda);
663     auto  mdAtoms = gmx::makeMDAtoms(nullptr, mtop, *ir, false);
664     auto* md      = mdAtoms->mdatoms();
665     atoms2md(mtop, *ir, -1, {}, mtop.natoms, mdAtoms.get());
666     if (ir->efep != FreeEnergyPerturbationType::No)
667     {
668         update_mdatoms(md, lambda);
669     }
670
671     set_pbc(&pbc, ir->pbcType, box);
672
673     double t_start = ir->init_t + ir->init_step * ir->delta_t;
674
675     if (pull->bSetPbcRefToPrevStepCOM)
676     {
677         initPullComFromPrevStep(nullptr, pull_work, gmx::arrayRefFromArray(md->massT, md->nr), pbc, x);
678     }
679     pull_calc_coms(nullptr, pull_work, gmx::arrayRefFromArray(md->massT, md->nr), pbc, t_start, x, {});
680
681     for (int g = 0; g < pull->ngroup; g++)
682     {
683         bool groupObeysPbc =
684                 pullCheckPbcWithinGroup(*pull_work, x, pbc, g, c_pullGroupSmallGroupThreshold);
685         if (!groupObeysPbc)
686         {
687             char buf[STRLEN];
688             if (pull->group[g].pbcatom_input == 0)
689             {
690                 sprintf(buf,
691                         "When the maximum distance from a pull group reference atom to other atoms "
692                         "in the "
693                         "group is larger than %g times half the box size a centrally placed "
694                         "atom should be chosen as pbcatom. Pull group %d is larger than that and "
695                         "does not have "
696                         "a specific atom selected as reference atom.",
697                         c_pullGroupSmallGroupThreshold,
698                         g);
699                 warning_error(wi, buf);
700             }
701             else if (!pull->bSetPbcRefToPrevStepCOM)
702             {
703                 sprintf(buf,
704                         "The maximum distance from the chosen PBC atom (%d) of pull group %d to "
705                         "other "
706                         "atoms in the group is larger than %g times half the box size. "
707                         "Set the pull-pbc-ref-prev-step-com option to yes.",
708                         pull->group[g].pbcatom + 1,
709                         g,
710                         c_pullGroupSmallGroupThreshold);
711                 warning_error(wi, buf);
712             }
713         }
714         if (groupObeysPbc)
715         {
716             groupObeysPbc = pullCheckPbcWithinGroup(*pull_work, x, pbc, g, c_pullGroupPbcMargin);
717             if (!groupObeysPbc)
718             {
719                 char buf[STRLEN];
720                 sprintf(buf,
721                         "Pull group %d has atoms at a distance larger than %g times half the box "
722                         "size from the PBC atom (%d). "
723                         "If atoms are or will more beyond half the box size from the PBC atom, the "
724                         "COM will be ill defined.",
725                         g,
726                         c_pullGroupPbcMargin,
727                         pull->group[g].pbcatom + 1);
728                 set_warning_line(wi, nullptr, -1);
729                 warning(wi, buf);
730             }
731         }
732     }
733
734     fprintf(stderr, "Pull group  natoms  pbc atom  distance at start  reference at t=0\n");
735     for (int c = 0; c < pull->ncoord; c++)
736     {
737         real init = 0;
738
739         t_pull_coord* pcrd = &pull->coord[c];
740
741         t_pull_group* pgrp0 = &pull->group[pcrd->group[0]];
742         t_pull_group* pgrp1 = &pull->group[pcrd->group[1]];
743         fprintf(stderr, "%8d  %8zu  %8d\n", pcrd->group[0], pgrp0->ind.size(), pgrp0->pbcatom + 1);
744         fprintf(stderr, "%8d  %8zu  %8d ", pcrd->group[1], pgrp1->ind.size(), pgrp1->pbcatom + 1);
745
746         if (pcrd->bStart)
747         {
748             init       = pcrd->init;
749             pcrd->init = 0;
750         }
751
752         double value = get_pull_coord_value(pull_work, c, pbc);
753
754         value *= pull_conversion_factor_internal2userinput(*pcrd);
755         fprintf(stderr, " %10.3f %s", value, pull_coordinate_units(*pcrd));
756
757         if (pcrd->bStart)
758         {
759             pcrd->init = value + init;
760         }
761
762         if (pcrd->eGeom == PullGroupGeometry::Distance)
763         {
764             if (pcrd->init < 0)
765             {
766                 gmx_fatal(FARGS,
767                           "The initial pull distance (%g) needs to be non-negative with geometry "
768                           "%s. If you want a signed distance, use geometry %s instead.",
769                           pcrd->init,
770                           enumValueToString(pcrd->eGeom),
771                           enumValueToString(PullGroupGeometry::Direction));
772             }
773
774             /* TODO: With a positive init but a negative rate things could still
775              * go wrong, but it might be fine if you don't pull too far.
776              * We should give a warning or note when there is only one pull dim
777              * active, since that is usually the problematic case when you should
778              * be using direction. We will do this later, since an already planned
779              * generalization of the pull code makes pull dim available here.
780              */
781         }
782         else if (pcrd->eGeom == PullGroupGeometry::Angle || pcrd->eGeom == PullGroupGeometry::AngleAxis)
783         {
784             if (pcrd->init < 0 || pcrd->init > 180)
785             {
786                 gmx_fatal(FARGS,
787                           "The initial pull reference angle (%g) is outside of the allowed range "
788                           "[0, 180] degrees.",
789                           pcrd->init);
790             }
791         }
792         else if (pcrd->eGeom == PullGroupGeometry::Dihedral)
793         {
794             if (pcrd->init < -180 || pcrd->init > 180)
795             {
796                 gmx_fatal(FARGS,
797                           "The initial pull reference angle (%g) is outside of the allowed range "
798                           "[-180, 180] degrees.",
799                           pcrd->init);
800             }
801         }
802
803
804         fprintf(stderr, "     %10.3f %s\n", pcrd->init, pull_coordinate_units(*pcrd));
805     }
806
807     return pull_work;
808 }