Introduce ObservablesHistory container
[gromacs.git] / src / gromacs / mdlib / constr.cpp
blob377b4f733e8aa6360a4bdf225a23df3c0806b4ad
1 /*
2 * This file is part of the GROMACS molecular simulation package.
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, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
37 #include "gmxpre.h"
39 #include "constr.h"
41 #include <assert.h>
42 #include <stdlib.h>
44 #include <cmath>
46 #include <algorithm>
48 #include "gromacs/domdec/domdec.h"
49 #include "gromacs/domdec/domdec_struct.h"
50 #include "gromacs/essentialdynamics/edsam.h"
51 #include "gromacs/fileio/confio.h"
52 #include "gromacs/fileio/gmxfio.h"
53 #include "gromacs/fileio/pdbio.h"
54 #include "gromacs/gmxlib/nrnb.h"
55 #include "gromacs/math/utilities.h"
56 #include "gromacs/math/vec.h"
57 #include "gromacs/mdlib/gmx_omp_nthreads.h"
58 #include "gromacs/mdlib/mdrun.h"
59 #include "gromacs/mdlib/splitter.h"
60 #include "gromacs/mdtypes/commrec.h"
61 #include "gromacs/mdtypes/inputrec.h"
62 #include "gromacs/mdtypes/md_enums.h"
63 #include "gromacs/mdtypes/state.h"
64 #include "gromacs/pbcutil/pbc.h"
65 #include "gromacs/pulling/pull.h"
66 #include "gromacs/topology/block.h"
67 #include "gromacs/topology/invblock.h"
68 #include "gromacs/topology/mtop_lookup.h"
69 #include "gromacs/topology/mtop_util.h"
70 #include "gromacs/utility/exceptions.h"
71 #include "gromacs/utility/fatalerror.h"
72 #include "gromacs/utility/pleasecite.h"
73 #include "gromacs/utility/smalloc.h"
74 #include "gromacs/utility/txtdump.h"
76 typedef struct gmx_constr {
77 int ncon_tot; /* The total number of constraints */
78 int nflexcon; /* The number of flexible constraints */
79 int n_at2con_mt; /* The size of at2con = #moltypes */
80 t_blocka *at2con_mt; /* A list of atoms to constraints */
81 int n_at2settle_mt; /* The size of at2settle = #moltypes */
82 int **at2settle_mt; /* A list of atoms to settles */
83 gmx_bool bInterCGsettles;
84 gmx_lincsdata_t lincsd; /* LINCS data */
85 gmx_shakedata_t shaked; /* SHAKE data */
86 gmx_settledata_t settled; /* SETTLE data */
87 int nblocks; /* The number of SHAKE blocks */
88 int *sblock; /* The SHAKE blocks */
89 int sblock_nalloc; /* The allocation size of sblock */
90 real *lagr; /* -2 times the Lagrange multipliers for SHAKE */
91 int lagr_nalloc; /* The allocation size of lagr */
92 int maxwarn; /* The maximum number of warnings */
93 int warncount_lincs;
94 int warncount_settle;
95 gmx_edsam_t ed; /* The essential dynamics data */
97 /* Thread local working data */
98 tensor *vir_r_m_dr_th; /* Thread virial contribution */
99 bool *bSettleErrorHasOccurred; /* Did a settle error occur? */
101 /* Only used for printing warnings */
102 const gmx_mtop_t *warn_mtop; /* Pointer to the global topology */
103 } t_gmx_constr;
105 typedef struct {
106 int iatom[3];
107 int blocknr;
108 } t_sortblock;
110 static int pcomp(const void *p1, const void *p2)
112 int db;
113 int min1, min2, max1, max2;
114 t_sortblock *a1 = (t_sortblock *)p1;
115 t_sortblock *a2 = (t_sortblock *)p2;
117 db = a1->blocknr-a2->blocknr;
119 if (db != 0)
121 return db;
124 min1 = std::min(a1->iatom[1], a1->iatom[2]);
125 max1 = std::max(a1->iatom[1], a1->iatom[2]);
126 min2 = std::min(a2->iatom[1], a2->iatom[2]);
127 max2 = std::max(a2->iatom[1], a2->iatom[2]);
129 if (min1 == min2)
131 return max1-max2;
133 else
135 return min1-min2;
139 int n_flexible_constraints(struct gmx_constr *constr)
141 int nflexcon;
143 if (constr)
145 nflexcon = constr->nflexcon;
147 else
149 nflexcon = 0;
152 return nflexcon;
155 static void clear_constraint_quantity_nonlocal(gmx_domdec_t *dd, rvec *q)
157 int nonlocal_at_start, nonlocal_at_end, at;
159 dd_get_constraint_range(dd, &nonlocal_at_start, &nonlocal_at_end);
161 for (at = nonlocal_at_start; at < nonlocal_at_end; at++)
163 clear_rvec(q[at]);
167 void too_many_constraint_warnings(int eConstrAlg, int warncount)
169 gmx_fatal(FARGS,
170 "Too many %s warnings (%d)\n"
171 "If you know what you are doing you can %s"
172 "set the environment variable GMX_MAXCONSTRWARN to -1,\n"
173 "but normally it is better to fix the problem",
174 (eConstrAlg == econtLINCS) ? "LINCS" : "SETTLE", warncount,
175 (eConstrAlg == econtLINCS) ?
176 "adjust the lincs warning threshold in your mdp file\nor " : "\n");
179 static void write_constr_pdb(const char *fn, const char *title,
180 const gmx_mtop_t *mtop,
181 int start, int homenr, t_commrec *cr,
182 rvec x[], matrix box)
184 char fname[STRLEN];
185 FILE *out;
186 int dd_ac0 = 0, dd_ac1 = 0, i, ii, resnr;
187 gmx_domdec_t *dd;
188 const char *anm, *resnm;
190 dd = nullptr;
191 if (DOMAINDECOMP(cr))
193 dd = cr->dd;
194 dd_get_constraint_range(dd, &dd_ac0, &dd_ac1);
195 start = 0;
196 homenr = dd_ac1;
199 if (PAR(cr))
201 sprintf(fname, "%s_n%d.pdb", fn, cr->sim_nodeid);
203 else
205 sprintf(fname, "%s.pdb", fn);
208 out = gmx_fio_fopen(fname, "w");
210 fprintf(out, "TITLE %s\n", title);
211 gmx_write_pdb_box(out, -1, box);
212 int molb = 0;
213 for (i = start; i < start+homenr; i++)
215 if (dd != nullptr)
217 if (i >= dd->nat_home && i < dd_ac0)
219 continue;
221 ii = dd->gatindex[i];
223 else
225 ii = i;
227 mtopGetAtomAndResidueName(mtop, ii, &molb, &anm, &resnr, &resnm, nullptr);
228 gmx_fprintf_pdb_atomline(out, epdbATOM, ii+1, anm, ' ', resnm, ' ', resnr, ' ',
229 10*x[i][XX], 10*x[i][YY], 10*x[i][ZZ], 1.0, 0.0, "");
231 fprintf(out, "TER\n");
233 gmx_fio_fclose(out);
236 static void dump_confs(FILE *fplog, gmx_int64_t step, const gmx_mtop_t *mtop,
237 int start, int homenr, t_commrec *cr,
238 rvec x[], rvec xprime[], matrix box)
240 char buf[STRLEN], buf2[22];
242 char *env = getenv("GMX_SUPPRESS_DUMP");
243 if (env)
245 return;
248 sprintf(buf, "step%sb", gmx_step_str(step, buf2));
249 write_constr_pdb(buf, "initial coordinates",
250 mtop, start, homenr, cr, x, box);
251 sprintf(buf, "step%sc", gmx_step_str(step, buf2));
252 write_constr_pdb(buf, "coordinates after constraining",
253 mtop, start, homenr, cr, xprime, box);
254 if (fplog)
256 fprintf(fplog, "Wrote pdb files with previous and current coordinates\n");
258 fprintf(stderr, "Wrote pdb files with previous and current coordinates\n");
261 static void pr_sortblock(FILE *fp, const char *title, int nsb, t_sortblock sb[])
263 int i;
265 fprintf(fp, "%s\n", title);
266 for (i = 0; (i < nsb); i++)
268 fprintf(fp, "i: %5d, iatom: (%5d %5d %5d), blocknr: %5d\n",
269 i, sb[i].iatom[0], sb[i].iatom[1], sb[i].iatom[2],
270 sb[i].blocknr);
274 gmx_bool constrain(FILE *fplog, gmx_bool bLog, gmx_bool bEner,
275 struct gmx_constr *constr,
276 t_idef *idef, t_inputrec *ir,
277 t_commrec *cr,
278 gmx_int64_t step, int delta_step,
279 real step_scaling,
280 t_mdatoms *md,
281 rvec *x, rvec *xprime, rvec *min_proj,
282 gmx_bool bMolPBC, matrix box,
283 real lambda, real *dvdlambda,
284 rvec *v, tensor *vir,
285 t_nrnb *nrnb, int econq)
287 gmx_bool bOK, bDump;
288 int start, homenr;
289 tensor vir_r_m_dr;
290 real scaled_delta_t;
291 real invdt, vir_fac = 0, t;
292 t_ilist *settle;
293 int nsettle;
294 t_pbc pbc, *pbc_null;
295 char buf[22];
296 int nth, th;
298 if (econq == econqForceDispl && !EI_ENERGY_MINIMIZATION(ir->eI))
300 gmx_incons("constrain called for forces displacements while not doing energy minimization, can not do this while the LINCS and SETTLE constraint connection matrices are mass weighted");
303 bOK = TRUE;
304 bDump = FALSE;
306 start = 0;
307 homenr = md->homenr;
309 scaled_delta_t = step_scaling * ir->delta_t;
311 /* Prepare time step for use in constraint implementations, and
312 avoid generating inf when ir->delta_t = 0. */
313 if (ir->delta_t == 0)
315 invdt = 0.0;
317 else
319 invdt = 1.0/scaled_delta_t;
322 if (ir->efep != efepNO && EI_DYNAMICS(ir->eI))
324 /* Set the constraint lengths for the step at which this configuration
325 * is meant to be. The invmasses should not be changed.
327 lambda += delta_step*ir->fepvals->delta_lambda;
330 if (vir != nullptr)
332 clear_mat(vir_r_m_dr);
335 where();
337 settle = &idef->il[F_SETTLE];
338 nsettle = settle->nr/(1+NRAL(F_SETTLE));
340 if (nsettle > 0)
342 nth = gmx_omp_nthreads_get(emntSETTLE);
344 else
346 nth = 1;
349 /* We do not need full pbc when constraints do not cross charge groups,
350 * i.e. when dd->constraint_comm==NULL.
351 * Note that PBC for constraints is different from PBC for bondeds.
352 * For constraints there is both forward and backward communication.
354 if (ir->ePBC != epbcNONE &&
355 (cr->dd || bMolPBC) && !(cr->dd && cr->dd->constraint_comm == nullptr))
357 /* With pbc=screw the screw has been changed to a shift
358 * by the constraint coordinate communication routine,
359 * so that here we can use normal pbc.
361 pbc_null = set_pbc_dd(&pbc, ir->ePBC,
362 DOMAINDECOMP(cr) ? cr->dd->nc : nullptr,
363 FALSE, box);
365 else
367 pbc_null = nullptr;
370 /* Communicate the coordinates required for the non-local constraints
371 * for LINCS and/or SETTLE.
373 if (cr->dd)
375 dd_move_x_constraints(cr->dd, box, x, xprime, econq == econqCoord);
377 if (v != nullptr)
379 /* We need to initialize the non-local components of v.
380 * We never actually use these values, but we do increment them,
381 * so we should avoid uninitialized variables and overflows.
383 clear_constraint_quantity_nonlocal(cr->dd, v);
387 if (constr->lincsd != nullptr)
389 bOK = constrain_lincs(fplog, bLog, bEner, ir, step, constr->lincsd, md, cr,
390 x, xprime, min_proj,
391 box, pbc_null, lambda, dvdlambda,
392 invdt, v, vir != nullptr, vir_r_m_dr,
393 econq, nrnb,
394 constr->maxwarn, &constr->warncount_lincs);
395 if (!bOK && constr->maxwarn < INT_MAX)
397 if (fplog != nullptr)
399 fprintf(fplog, "Constraint error in algorithm %s at step %s\n",
400 econstr_names[econtLINCS], gmx_step_str(step, buf));
402 bDump = TRUE;
406 if (constr->nblocks > 0)
408 switch (econq)
410 case (econqCoord):
411 bOK = bshakef(fplog, constr->shaked,
412 md->invmass, constr->nblocks, constr->sblock,
413 idef, ir, x, xprime, nrnb,
414 constr->lagr, lambda, dvdlambda,
415 invdt, v, vir != nullptr, vir_r_m_dr,
416 constr->maxwarn < INT_MAX, econq);
417 break;
418 case (econqVeloc):
419 bOK = bshakef(fplog, constr->shaked,
420 md->invmass, constr->nblocks, constr->sblock,
421 idef, ir, x, min_proj, nrnb,
422 constr->lagr, lambda, dvdlambda,
423 invdt, nullptr, vir != nullptr, vir_r_m_dr,
424 constr->maxwarn < INT_MAX, econq);
425 break;
426 default:
427 gmx_fatal(FARGS, "Internal error, SHAKE called for constraining something else than coordinates");
428 break;
431 if (!bOK && constr->maxwarn < INT_MAX)
433 if (fplog != nullptr)
435 fprintf(fplog, "Constraint error in algorithm %s at step %s\n",
436 econstr_names[econtSHAKE], gmx_step_str(step, buf));
438 bDump = TRUE;
442 if (nsettle > 0)
444 bool bSettleErrorHasOccurred = false;
446 switch (econq)
448 case econqCoord:
449 #pragma omp parallel for num_threads(nth) schedule(static)
450 for (th = 0; th < nth; th++)
454 if (th > 0)
456 clear_mat(constr->vir_r_m_dr_th[th]);
459 csettle(constr->settled,
460 nth, th,
461 pbc_null,
462 x[0], xprime[0],
463 invdt, v ? v[0] : nullptr,
464 vir != nullptr,
465 th == 0 ? vir_r_m_dr : constr->vir_r_m_dr_th[th],
466 th == 0 ? &bSettleErrorHasOccurred : &constr->bSettleErrorHasOccurred[th]);
468 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
470 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
471 if (v != nullptr)
473 inc_nrnb(nrnb, eNR_CONSTR_V, nsettle*3);
475 if (vir != nullptr)
477 inc_nrnb(nrnb, eNR_CONSTR_VIR, nsettle*3);
479 break;
480 case econqVeloc:
481 case econqDeriv:
482 case econqForce:
483 case econqForceDispl:
484 #pragma omp parallel for num_threads(nth) schedule(static)
485 for (th = 0; th < nth; th++)
489 int calcvir_atom_end;
491 if (vir == nullptr)
493 calcvir_atom_end = 0;
495 else
497 calcvir_atom_end = md->homenr;
500 if (th > 0)
502 clear_mat(constr->vir_r_m_dr_th[th]);
505 int start_th = (nsettle* th )/nth;
506 int end_th = (nsettle*(th+1))/nth;
508 if (start_th >= 0 && end_th - start_th > 0)
510 settle_proj(constr->settled, econq,
511 end_th-start_th,
512 settle->iatoms+start_th*(1+NRAL(F_SETTLE)),
513 pbc_null,
515 xprime, min_proj, calcvir_atom_end,
516 th == 0 ? vir_r_m_dr : constr->vir_r_m_dr_th[th]);
519 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
521 /* This is an overestimate */
522 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
523 break;
524 case econqDeriv_FlexCon:
525 /* Nothing to do, since the are no flexible constraints in settles */
526 break;
527 default:
528 gmx_incons("Unknown constraint quantity for settle");
531 if (vir != nullptr)
533 /* Reduce the virial contributions over the threads */
534 for (int th = 1; th < nth; th++)
536 m_add(vir_r_m_dr, constr->vir_r_m_dr_th[th], vir_r_m_dr);
540 if (econq == econqCoord)
542 for (int th = 1; th < nth; th++)
544 bSettleErrorHasOccurred = bSettleErrorHasOccurred || constr->bSettleErrorHasOccurred[th];
547 if (bSettleErrorHasOccurred)
549 char buf[STRLEN];
550 sprintf(buf,
551 "\nstep " "%" GMX_PRId64 ": One or more water molecules can not be settled.\n"
552 "Check for bad contacts and/or reduce the timestep if appropriate.\n",
553 step);
554 if (fplog)
556 fprintf(fplog, "%s", buf);
558 fprintf(stderr, "%s", buf);
559 constr->warncount_settle++;
560 if (constr->warncount_settle > constr->maxwarn)
562 too_many_constraint_warnings(-1, constr->warncount_settle);
564 bDump = TRUE;
566 bOK = FALSE;
571 if (vir != nullptr)
573 /* The normal uses of constrain() pass step_scaling = 1.0.
574 * The call to constrain() for SD1 that passes step_scaling =
575 * 0.5 also passes vir = NULL, so cannot reach this
576 * assertion. This assertion should remain until someone knows
577 * that this path works for their intended purpose, and then
578 * they can use scaled_delta_t instead of ir->delta_t
579 * below. */
580 assert(gmx_within_tol(step_scaling, 1.0, GMX_REAL_EPS));
581 switch (econq)
583 case econqCoord:
584 vir_fac = 0.5/(ir->delta_t*ir->delta_t);
585 break;
586 case econqVeloc:
587 vir_fac = 0.5/ir->delta_t;
588 break;
589 case econqForce:
590 case econqForceDispl:
591 vir_fac = 0.5;
592 break;
593 default:
594 gmx_incons("Unsupported constraint quantity for virial");
597 if (EI_VV(ir->eI))
599 vir_fac *= 2; /* only constraining over half the distance here */
601 for (int i = 0; i < DIM; i++)
603 for (int j = 0; j < DIM; j++)
605 (*vir)[i][j] = vir_fac*vir_r_m_dr[i][j];
610 if (bDump)
612 dump_confs(fplog, step, constr->warn_mtop, start, homenr, cr, x, xprime, box);
615 if (econq == econqCoord)
617 if (ir->bPull && pull_have_constraint(ir->pull_work))
619 if (EI_DYNAMICS(ir->eI))
621 t = ir->init_t + (step + delta_step)*ir->delta_t;
623 else
625 t = ir->init_t;
627 set_pbc(&pbc, ir->ePBC, box);
628 pull_constraint(ir->pull_work, md, &pbc, cr, ir->delta_t, t, x, xprime, v, *vir);
630 if (constr->ed && delta_step > 0)
632 /* apply the essential dynamcs constraints here */
633 do_edsam(ir, step, cr, xprime, v, box, constr->ed);
637 return bOK;
640 real *constr_rmsd_data(struct gmx_constr *constr)
642 if (constr->lincsd)
644 return lincs_rmsd_data(constr->lincsd);
646 else
648 return nullptr;
652 real constr_rmsd(struct gmx_constr *constr)
654 if (constr->lincsd)
656 return lincs_rmsd(constr->lincsd);
658 else
660 return 0;
664 static void make_shake_sblock_serial(struct gmx_constr *constr,
665 t_idef *idef, const t_mdatoms *md)
667 int i, j, m, ncons;
668 int bstart, bnr;
669 t_blocka sblocks;
670 t_sortblock *sb;
671 t_iatom *iatom;
672 int *inv_sblock;
674 /* Since we are processing the local topology,
675 * the F_CONSTRNC ilist has been concatenated to the F_CONSTR ilist.
677 ncons = idef->il[F_CONSTR].nr/3;
679 init_blocka(&sblocks);
680 gen_sblocks(nullptr, 0, md->homenr, idef, &sblocks, FALSE);
683 bstart=(idef->nodeid > 0) ? blocks->multinr[idef->nodeid-1] : 0;
684 nblocks=blocks->multinr[idef->nodeid] - bstart;
686 bstart = 0;
687 constr->nblocks = sblocks.nr;
688 if (debug)
690 fprintf(debug, "ncons: %d, bstart: %d, nblocks: %d\n",
691 ncons, bstart, constr->nblocks);
694 /* Calculate block number for each atom */
695 inv_sblock = make_invblocka(&sblocks, md->nr);
697 done_blocka(&sblocks);
699 /* Store the block number in temp array and
700 * sort the constraints in order of the sblock number
701 * and the atom numbers, really sorting a segment of the array!
703 #ifdef DEBUGIDEF
704 pr_idef(fplog, 0, "Before Sort", idef);
705 #endif
706 iatom = idef->il[F_CONSTR].iatoms;
707 snew(sb, ncons);
708 for (i = 0; (i < ncons); i++, iatom += 3)
710 for (m = 0; (m < 3); m++)
712 sb[i].iatom[m] = iatom[m];
714 sb[i].blocknr = inv_sblock[iatom[1]];
717 /* Now sort the blocks */
718 if (debug)
720 pr_sortblock(debug, "Before sorting", ncons, sb);
721 fprintf(debug, "Going to sort constraints\n");
724 qsort(sb, ncons, (size_t)sizeof(*sb), pcomp);
726 if (debug)
728 pr_sortblock(debug, "After sorting", ncons, sb);
731 iatom = idef->il[F_CONSTR].iatoms;
732 for (i = 0; (i < ncons); i++, iatom += 3)
734 for (m = 0; (m < 3); m++)
736 iatom[m] = sb[i].iatom[m];
739 #ifdef DEBUGIDEF
740 pr_idef(fplog, 0, "After Sort", idef);
741 #endif
743 j = 0;
744 snew(constr->sblock, constr->nblocks+1);
745 bnr = -2;
746 for (i = 0; (i < ncons); i++)
748 if (sb[i].blocknr != bnr)
750 bnr = sb[i].blocknr;
751 constr->sblock[j++] = 3*i;
754 /* Last block... */
755 constr->sblock[j++] = 3*ncons;
757 if (j != (constr->nblocks+1))
759 fprintf(stderr, "bstart: %d\n", bstart);
760 fprintf(stderr, "j: %d, nblocks: %d, ncons: %d\n",
761 j, constr->nblocks, ncons);
762 for (i = 0; (i < ncons); i++)
764 fprintf(stderr, "i: %5d sb[i].blocknr: %5d\n", i, sb[i].blocknr);
766 for (j = 0; (j <= constr->nblocks); j++)
768 fprintf(stderr, "sblock[%3d]=%5d\n", j, (int)constr->sblock[j]);
770 gmx_fatal(FARGS, "DEATH HORROR: "
771 "sblocks does not match idef->il[F_CONSTR]");
773 sfree(sb);
774 sfree(inv_sblock);
777 static void make_shake_sblock_dd(struct gmx_constr *constr,
778 const t_ilist *ilcon, const t_block *cgs,
779 const gmx_domdec_t *dd)
781 int ncons, c, cg;
782 t_iatom *iatom;
784 if (dd->ncg_home+1 > constr->sblock_nalloc)
786 constr->sblock_nalloc = over_alloc_dd(dd->ncg_home+1);
787 srenew(constr->sblock, constr->sblock_nalloc);
790 ncons = ilcon->nr/3;
791 iatom = ilcon->iatoms;
792 constr->nblocks = 0;
793 cg = 0;
794 for (c = 0; c < ncons; c++)
796 if (c == 0 || iatom[1] >= cgs->index[cg+1])
798 constr->sblock[constr->nblocks++] = 3*c;
799 while (iatom[1] >= cgs->index[cg+1])
801 cg++;
804 iatom += 3;
806 constr->sblock[constr->nblocks] = 3*ncons;
809 t_blocka make_at2con(int start, int natoms,
810 const t_ilist *ilist, const t_iparams *iparams,
811 gmx_bool bDynamics, int *nflexiblecons)
813 int *count, ncon, con, con_tot, nflexcon, ftype, i, a;
814 t_iatom *ia;
815 t_blocka at2con;
816 gmx_bool bFlexCon;
818 snew(count, natoms);
819 nflexcon = 0;
820 for (ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
822 ncon = ilist[ftype].nr/3;
823 ia = ilist[ftype].iatoms;
824 for (con = 0; con < ncon; con++)
826 bFlexCon = (iparams[ia[0]].constr.dA == 0 &&
827 iparams[ia[0]].constr.dB == 0);
828 if (bFlexCon)
830 nflexcon++;
832 if (bDynamics || !bFlexCon)
834 for (i = 1; i < 3; i++)
836 a = ia[i] - start;
837 count[a]++;
840 ia += 3;
843 *nflexiblecons = nflexcon;
845 at2con.nr = natoms;
846 at2con.nalloc_index = at2con.nr+1;
847 snew(at2con.index, at2con.nalloc_index);
848 at2con.index[0] = 0;
849 for (a = 0; a < natoms; a++)
851 at2con.index[a+1] = at2con.index[a] + count[a];
852 count[a] = 0;
854 at2con.nra = at2con.index[natoms];
855 at2con.nalloc_a = at2con.nra;
856 snew(at2con.a, at2con.nalloc_a);
858 /* The F_CONSTRNC constraints have constraint numbers
859 * that continue after the last F_CONSTR constraint.
861 con_tot = 0;
862 for (ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
864 ncon = ilist[ftype].nr/3;
865 ia = ilist[ftype].iatoms;
866 for (con = 0; con < ncon; con++)
868 bFlexCon = (iparams[ia[0]].constr.dA == 0 &&
869 iparams[ia[0]].constr.dB == 0);
870 if (bDynamics || !bFlexCon)
872 for (i = 1; i < 3; i++)
874 a = ia[i] - start;
875 at2con.a[at2con.index[a]+count[a]++] = con_tot;
878 con_tot++;
879 ia += 3;
883 sfree(count);
885 return at2con;
888 static int *make_at2settle(int natoms, const t_ilist *ilist)
890 int *at2s;
891 int a, stride, s;
893 snew(at2s, natoms);
894 /* Set all to no settle */
895 for (a = 0; a < natoms; a++)
897 at2s[a] = -1;
900 stride = 1 + NRAL(F_SETTLE);
902 for (s = 0; s < ilist->nr; s += stride)
904 at2s[ilist->iatoms[s+1]] = s/stride;
905 at2s[ilist->iatoms[s+2]] = s/stride;
906 at2s[ilist->iatoms[s+3]] = s/stride;
909 return at2s;
912 void set_constraints(struct gmx_constr *constr,
913 gmx_localtop_t *top, const t_inputrec *ir,
914 const t_mdatoms *md, t_commrec *cr)
916 t_idef *idef = &top->idef;
918 if (constr->ncon_tot > 0)
920 /* We are using the local topology,
921 * so there are only F_CONSTR constraints.
923 int ncons = idef->il[F_CONSTR].nr/3;
925 /* With DD we might also need to call LINCS with ncons=0 for
926 * communicating coordinates to other nodes that do have constraints.
928 if (ir->eConstrAlg == econtLINCS)
930 set_lincs(idef, md, EI_DYNAMICS(ir->eI), cr, constr->lincsd);
932 if (ir->eConstrAlg == econtSHAKE)
934 if (cr->dd)
936 make_shake_sblock_dd(constr, &idef->il[F_CONSTR], &top->cgs, cr->dd);
938 else
940 make_shake_sblock_serial(constr, idef, md);
942 if (ncons > constr->lagr_nalloc)
944 constr->lagr_nalloc = over_alloc_dd(ncons);
945 srenew(constr->lagr, constr->lagr_nalloc);
950 if (constr->settled)
952 settle_set_constraints(constr->settled,
953 &idef->il[F_SETTLE], md);
956 /* Make a selection of the local atoms for essential dynamics */
957 if (constr->ed && cr->dd)
959 dd_make_local_ed_indices(cr->dd, constr->ed);
963 static void constr_recur(const t_blocka *at2con,
964 const t_ilist *ilist, const t_iparams *iparams,
965 gmx_bool bTopB,
966 int at, int depth, int nc, int *path,
967 real r0, real r1, real *r2max,
968 int *count)
970 int ncon1;
971 t_iatom *ia1, *ia2;
972 int c, con, a1;
973 gmx_bool bUse;
974 t_iatom *ia;
975 real len, rn0, rn1;
977 (*count)++;
979 ncon1 = ilist[F_CONSTR].nr/3;
980 ia1 = ilist[F_CONSTR].iatoms;
981 ia2 = ilist[F_CONSTRNC].iatoms;
983 /* Loop over all constraints connected to this atom */
984 for (c = at2con->index[at]; c < at2con->index[at+1]; c++)
986 con = at2con->a[c];
987 /* Do not walk over already used constraints */
988 bUse = TRUE;
989 for (a1 = 0; a1 < depth; a1++)
991 if (con == path[a1])
993 bUse = FALSE;
996 if (bUse)
998 ia = constr_iatomptr(ncon1, ia1, ia2, con);
999 /* Flexible constraints currently have length 0, which is incorrect */
1000 if (!bTopB)
1002 len = iparams[ia[0]].constr.dA;
1004 else
1006 len = iparams[ia[0]].constr.dB;
1008 /* In the worst case the bond directions alternate */
1009 if (nc % 2 == 0)
1011 rn0 = r0 + len;
1012 rn1 = r1;
1014 else
1016 rn0 = r0;
1017 rn1 = r1 + len;
1019 /* Assume angles of 120 degrees between all bonds */
1020 if (rn0*rn0 + rn1*rn1 + rn0*rn1 > *r2max)
1022 *r2max = rn0*rn0 + rn1*rn1 + r0*rn1;
1023 if (debug)
1025 fprintf(debug, "Found longer constraint distance: r0 %5.3f r1 %5.3f rmax %5.3f\n", rn0, rn1, sqrt(*r2max));
1026 for (a1 = 0; a1 < depth; a1++)
1028 fprintf(debug, " %d %5.3f",
1029 path[a1],
1030 iparams[constr_iatomptr(ncon1, ia1, ia2, con)[0]].constr.dA);
1032 fprintf(debug, " %d %5.3f\n", con, len);
1035 /* Limit the number of recursions to 1000*nc,
1036 * so a call does not take more than a second,
1037 * even for highly connected systems.
1039 if (depth + 1 < nc && *count < 1000*nc)
1041 if (ia[1] == at)
1043 a1 = ia[2];
1045 else
1047 a1 = ia[1];
1049 /* Recursion */
1050 path[depth] = con;
1051 constr_recur(at2con, ilist, iparams,
1052 bTopB, a1, depth+1, nc, path, rn0, rn1, r2max, count);
1053 path[depth] = -1;
1059 static real constr_r_max_moltype(const gmx_moltype_t *molt,
1060 const t_iparams *iparams,
1061 const t_inputrec *ir)
1063 int natoms, nflexcon, *path, at, count;
1065 t_blocka at2con;
1066 real r0, r1, r2maxA, r2maxB, rmax, lam0, lam1;
1068 if (molt->ilist[F_CONSTR].nr == 0 &&
1069 molt->ilist[F_CONSTRNC].nr == 0)
1071 return 0;
1074 natoms = molt->atoms.nr;
1076 at2con = make_at2con(0, natoms, molt->ilist, iparams,
1077 EI_DYNAMICS(ir->eI), &nflexcon);
1078 snew(path, 1+ir->nProjOrder);
1079 for (at = 0; at < 1+ir->nProjOrder; at++)
1081 path[at] = -1;
1084 r2maxA = 0;
1085 for (at = 0; at < natoms; at++)
1087 r0 = 0;
1088 r1 = 0;
1090 count = 0;
1091 constr_recur(&at2con, molt->ilist, iparams,
1092 FALSE, at, 0, 1+ir->nProjOrder, path, r0, r1, &r2maxA, &count);
1094 if (ir->efep == efepNO)
1096 rmax = sqrt(r2maxA);
1098 else
1100 r2maxB = 0;
1101 for (at = 0; at < natoms; at++)
1103 r0 = 0;
1104 r1 = 0;
1105 count = 0;
1106 constr_recur(&at2con, molt->ilist, iparams,
1107 TRUE, at, 0, 1+ir->nProjOrder, path, r0, r1, &r2maxB, &count);
1109 lam0 = ir->fepvals->init_lambda;
1110 if (EI_DYNAMICS(ir->eI))
1112 lam0 += ir->init_step*ir->fepvals->delta_lambda;
1114 rmax = (1 - lam0)*sqrt(r2maxA) + lam0*sqrt(r2maxB);
1115 if (EI_DYNAMICS(ir->eI))
1117 lam1 = ir->fepvals->init_lambda + (ir->init_step + ir->nsteps)*ir->fepvals->delta_lambda;
1118 rmax = std::max(rmax, (1 - lam1)*std::sqrt(r2maxA) + lam1*std::sqrt(r2maxB));
1122 done_blocka(&at2con);
1123 sfree(path);
1125 return rmax;
1128 real constr_r_max(FILE *fplog, const gmx_mtop_t *mtop, const t_inputrec *ir)
1130 int mt;
1131 real rmax;
1133 rmax = 0;
1134 for (mt = 0; mt < mtop->nmoltype; mt++)
1136 rmax = std::max(rmax,
1137 constr_r_max_moltype(&mtop->moltype[mt],
1138 mtop->ffparams.iparams, ir));
1141 if (fplog)
1143 fprintf(fplog, "Maximum distance for %d constraints, at 120 deg. angles, all-trans: %.3f nm\n", 1+ir->nProjOrder, rmax);
1146 return rmax;
1149 gmx_constr_t init_constraints(FILE *fplog,
1150 const gmx_mtop_t *mtop, const t_inputrec *ir,
1151 gmx_edsam_t ed, edsamhistory_t *edsamHistory, t_state *state,
1152 t_commrec *cr)
1154 int nconstraints =
1155 gmx_mtop_ftype_count(mtop, F_CONSTR) +
1156 gmx_mtop_ftype_count(mtop, F_CONSTRNC);
1157 int nsettles =
1158 gmx_mtop_ftype_count(mtop, F_SETTLE);
1160 GMX_RELEASE_ASSERT(!ir->bPull || ir->pull_work != nullptr, "init_constraints called with COM pulling before/without initializing the pull code");
1162 if (nconstraints + nsettles == 0 &&
1163 !(ir->bPull && pull_have_constraint(ir->pull_work)) &&
1164 ed == nullptr)
1166 return nullptr;
1169 struct gmx_constr *constr;
1171 snew(constr, 1);
1173 constr->ncon_tot = nconstraints;
1174 constr->nflexcon = 0;
1175 if (nconstraints > 0)
1177 constr->n_at2con_mt = mtop->nmoltype;
1178 snew(constr->at2con_mt, constr->n_at2con_mt);
1179 for (int mt = 0; mt < mtop->nmoltype; mt++)
1181 int nflexcon;
1182 constr->at2con_mt[mt] = make_at2con(0, mtop->moltype[mt].atoms.nr,
1183 mtop->moltype[mt].ilist,
1184 mtop->ffparams.iparams,
1185 EI_DYNAMICS(ir->eI), &nflexcon);
1186 for (int i = 0; i < mtop->nmolblock; i++)
1188 if (mtop->molblock[i].type == mt)
1190 constr->nflexcon += mtop->molblock[i].nmol*nflexcon;
1195 if (constr->nflexcon > 0)
1197 if (fplog)
1199 fprintf(fplog, "There are %d flexible constraints\n",
1200 constr->nflexcon);
1201 if (ir->fc_stepsize == 0)
1203 fprintf(fplog, "\n"
1204 "WARNING: step size for flexible constraining = 0\n"
1205 " All flexible constraints will be rigid.\n"
1206 " Will try to keep all flexible constraints at their original length,\n"
1207 " but the lengths may exhibit some drift.\n\n");
1208 constr->nflexcon = 0;
1211 if (constr->nflexcon > 0)
1213 please_cite(fplog, "Hess2002");
1217 if (ir->eConstrAlg == econtLINCS)
1219 constr->lincsd = init_lincs(fplog, mtop,
1220 constr->nflexcon, constr->at2con_mt,
1221 DOMAINDECOMP(cr) && cr->dd->bInterCGcons,
1222 ir->nLincsIter, ir->nProjOrder);
1225 if (ir->eConstrAlg == econtSHAKE)
1227 if (DOMAINDECOMP(cr) && cr->dd->bInterCGcons)
1229 gmx_fatal(FARGS, "SHAKE is not supported with domain decomposition and constraint that cross charge group boundaries, use LINCS");
1231 if (constr->nflexcon)
1233 gmx_fatal(FARGS, "For this system also velocities and/or forces need to be constrained, this can not be done with SHAKE, you should select LINCS");
1235 please_cite(fplog, "Ryckaert77a");
1236 if (ir->bShakeSOR)
1238 please_cite(fplog, "Barth95a");
1241 constr->shaked = shake_init();
1245 if (nsettles > 0)
1247 please_cite(fplog, "Miyamoto92a");
1249 constr->bInterCGsettles = inter_charge_group_settles(mtop);
1251 constr->settled = settle_init(mtop);
1253 /* Make an atom to settle index for use in domain decomposition */
1254 constr->n_at2settle_mt = mtop->nmoltype;
1255 snew(constr->at2settle_mt, constr->n_at2settle_mt);
1256 for (int mt = 0; mt < mtop->nmoltype; mt++)
1258 constr->at2settle_mt[mt] =
1259 make_at2settle(mtop->moltype[mt].atoms.nr,
1260 &mtop->moltype[mt].ilist[F_SETTLE]);
1263 /* Allocate thread-local work arrays */
1264 int nthreads = gmx_omp_nthreads_get(emntSETTLE);
1265 if (nthreads > 1 && constr->vir_r_m_dr_th == nullptr)
1267 snew(constr->vir_r_m_dr_th, nthreads);
1268 snew(constr->bSettleErrorHasOccurred, nthreads);
1272 if (nconstraints + nsettles > 0 && ir->epc == epcMTTK)
1274 gmx_fatal(FARGS, "Constraints are not implemented with MTTK pressure control.");
1277 constr->maxwarn = 999;
1278 char *env = getenv("GMX_MAXCONSTRWARN");
1279 if (env)
1281 constr->maxwarn = 0;
1282 sscanf(env, "%8d", &constr->maxwarn);
1283 if (constr->maxwarn < 0)
1285 constr->maxwarn = INT_MAX;
1287 if (fplog)
1289 fprintf(fplog,
1290 "Setting the maximum number of constraint warnings to %d\n",
1291 constr->maxwarn);
1293 if (MASTER(cr))
1295 fprintf(stderr,
1296 "Setting the maximum number of constraint warnings to %d\n",
1297 constr->maxwarn);
1300 constr->warncount_lincs = 0;
1301 constr->warncount_settle = 0;
1303 /* Initialize the essential dynamics sampling.
1304 * Put the pointer to the ED struct in constr */
1305 constr->ed = ed;
1306 if (ed != nullptr || edsamHistory != nullptr)
1308 init_edsam(mtop, ir, cr, ed, as_rvec_array(state->x.data()), state->box, edsamHistory);
1311 constr->warn_mtop = mtop;
1313 return constr;
1316 const t_blocka *atom2constraints_moltype(gmx_constr_t constr)
1318 return constr->at2con_mt;
1321 const int **atom2settle_moltype(gmx_constr_t constr)
1323 return (const int **)constr->at2settle_mt;
1327 gmx_bool inter_charge_group_constraints(const gmx_mtop_t *mtop)
1329 const gmx_moltype_t *molt;
1330 const t_block *cgs;
1331 const t_ilist *il;
1332 int mb;
1333 int *at2cg, cg, a, ftype, i;
1334 gmx_bool bInterCG;
1336 bInterCG = FALSE;
1337 for (mb = 0; mb < mtop->nmolblock && !bInterCG; mb++)
1339 molt = &mtop->moltype[mtop->molblock[mb].type];
1341 if (molt->ilist[F_CONSTR].nr > 0 ||
1342 molt->ilist[F_CONSTRNC].nr > 0 ||
1343 molt->ilist[F_SETTLE].nr > 0)
1345 cgs = &molt->cgs;
1346 snew(at2cg, molt->atoms.nr);
1347 for (cg = 0; cg < cgs->nr; cg++)
1349 for (a = cgs->index[cg]; a < cgs->index[cg+1]; a++)
1351 at2cg[a] = cg;
1355 for (ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
1357 il = &molt->ilist[ftype];
1358 for (i = 0; i < il->nr && !bInterCG; i += 1+NRAL(ftype))
1360 if (at2cg[il->iatoms[i+1]] != at2cg[il->iatoms[i+2]])
1362 bInterCG = TRUE;
1367 sfree(at2cg);
1371 return bInterCG;
1374 gmx_bool inter_charge_group_settles(const gmx_mtop_t *mtop)
1376 const gmx_moltype_t *molt;
1377 const t_block *cgs;
1378 const t_ilist *il;
1379 int mb;
1380 int *at2cg, cg, a, ftype, i;
1381 gmx_bool bInterCG;
1383 bInterCG = FALSE;
1384 for (mb = 0; mb < mtop->nmolblock && !bInterCG; mb++)
1386 molt = &mtop->moltype[mtop->molblock[mb].type];
1388 if (molt->ilist[F_SETTLE].nr > 0)
1390 cgs = &molt->cgs;
1391 snew(at2cg, molt->atoms.nr);
1392 for (cg = 0; cg < cgs->nr; cg++)
1394 for (a = cgs->index[cg]; a < cgs->index[cg+1]; a++)
1396 at2cg[a] = cg;
1400 for (ftype = F_SETTLE; ftype <= F_SETTLE; ftype++)
1402 il = &molt->ilist[ftype];
1403 for (i = 0; i < il->nr && !bInterCG; i += 1+NRAL(F_SETTLE))
1405 if (at2cg[il->iatoms[i+1]] != at2cg[il->iatoms[i+2]] ||
1406 at2cg[il->iatoms[i+1]] != at2cg[il->iatoms[i+3]])
1408 bInterCG = TRUE;
1413 sfree(at2cg);
1417 return bInterCG;
1420 /* helper functions for andersen temperature control, because the
1421 * gmx_constr construct is only defined in constr.c. Return the list
1422 * of blocks (get_sblock) and the number of blocks (get_nblocks). */
1424 extern int *get_sblock(struct gmx_constr *constr)
1426 return constr->sblock;
1429 extern int get_nblocks(struct gmx_constr *constr)
1431 return constr->nblocks;